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
8197d2ae15812097563d15f1999aa0fb8d38b79e
c2b0bd5aa4b3f4fb8a887fab57c5fc08be03aa01
/interpreter.lean
e4c36d4322b138dbe2a09c88f3e37651149f227f
[]
no_license
cipher1024/lambda-calc
f72aa6dedea96fc7831d1898f3150a18baefdf0b
327eaa12588018c01b2205f3e4e0048de1d97afd
refs/heads/master
1,625,672,854,392
1,507,233,523,000
1,507,233,523,000
99,383,225
4
0
null
null
null
null
UTF-8
Lean
false
false
20,475
lean
universe variables u v w open nat lemma left_rec (m n : β„•) : m < 1 + (m + n) := begin rw [add_comm,← nat.succ_eq_add_one], apply nat.succ_le_succ, apply nat.le_add_right end -- lemma left_rec' {m n : β„•} (i : β„•) (h : 1 + m + n < succ i) -- : m < i := -- sorry -- lemma right_rec' {m n : β„•} (i : β„•) (h : 1 + m + n < succ i) -- : n < i := -- sorry namespace interpreter inductive type : Type | int : type | list : type β†’ type | fn : type β†’ type β†’ type infixr ` ↦ `:50 := type.fn inductive list_cons : Type | nil : list_cons | cons : list_cons inductive expr : Type u β†’ Type (u+1) | var : βˆ€ {var : Type u}, var β†’ expr var | lit : βˆ€ {var : Type u}, β„• β†’ expr var | constr : βˆ€ {var : Type u}, type β†’ list_cons β†’ expr var | case : βˆ€ {v : Type u}, expr v β†’ expr v β†’ expr (fin 2 βŠ• v) β†’ expr v | abs : βˆ€ {v : Type u}, type β†’ expr (fin 1 βŠ• v) β†’ expr v | app : βˆ€ {v : Type u}, expr v β†’ expr v β†’ expr v | bind' : βˆ€ {v : Type u} (n : β„•), (fin (succ n) β†’ type) β†’ (fin (succ n) β†’ expr (fin (succ n) βŠ• v)) β†’ expr (fin (succ n) βŠ• v) β†’ expr v open expr def option.map {Ξ³ Ξ± Ξ²} (f : Ξ± β†’ Ξ²) : Ξ³ βŠ• Ξ± β†’ Ξ³ βŠ• Ξ² | (sum.inr x) := sum.inr $ f x | (sum.inl x) := sum.inl x lemma option.id_map {Ξ± Ξ²} (x : Ξ± βŠ• Ξ²) : option.map id x = x := by { induction x ; refl } lemma option.map_comp {e} {Ξ± Ξ² Ξ³} (g : Ξ± β†’ Ξ²) (h : Ξ² β†’ Ξ³) (x : e βŠ• Ξ±) : option.map (h ∘ g) x = option.map h (option.map g x) := by { induction x ; refl } instance {Ξ±} : functor (sum Ξ±) := { map := @option.map Ξ± , id_map := @option.id_map _ , map_comp := @option.map_comp Ξ± } -- def expr.map_t := βˆ€ {Ξ± Ξ²}, (Ξ± β†’ Ξ²) β†’ expr Ξ± β†’ expr Ξ² -- def expr.map' (map : expr.map_t) : expr.map_t -- | _ _ f (expr.var v) := expr.var $ f v -- | _ _ f (expr.lit n) := expr.lit n -- | Ξ± Ξ² f (@expr.abs .(_) n t e) := -- let h := left_rec (sizeof e) (sizeof e) in -- @expr.abs _ n t $ map (has_map.map f) e -- | Ξ± Ξ² _ (expr.constr c t) := expr.constr c t -- | Ξ± Ξ² f (expr.case p eβ‚€ e₁) := -- expr.case -- (map f p) -- (map f eβ‚€) -- (map (has_map.map f) e₁) -- | Ξ± Ξ² f (@expr.abs .(_) n t e) := expr.abs t $ .map (has_map.map f) e -- | Ξ± Ξ² f (expr.app eβ‚€ e₁) := expr.app (expr.map f eβ‚€) (expr.map f e₁) -- | Ξ± Ξ² f (@expr.bind' .(_) n Ξ“ bs e) := -- expr.bind' Ξ“ -- (expr.map (has_map.map f) ∘ bs) -- (expr.map (has_map.map f) e) -- #print expr.sizeof -- #print prefix interpreter.expr. open has_map -- lemma functor.id_map' {Ξ±} (f : Type u β†’ Type v) [functor f] -- : (map id : f Ξ± β†’ f Ξ±) = id := -- funext functor.id_map lemma functor.id_map' {Ξ±} (f : Type u β†’ Type v) [functor f] : (map id : f Ξ± β†’ f Ξ±) = id := funext functor.id_map lemma functor.map_comp' {Ξ± Ξ² Ξ³} (f : Type u β†’ Type v) [functor f] (g : Ξ± β†’ Ξ²) (h : Ξ² β†’ Ξ³) : (map (h ∘ g) : f Ξ± β†’ f Ξ³) = map h ∘ map g := funext (functor.map_comp g h) def expr.map : βˆ€ {Ξ± Ξ²}, (Ξ± β†’ Ξ²) β†’ expr Ξ± β†’ expr Ξ² | _ _ f (expr.var v) := expr.var (f v) | _ _ f (expr.lit v) := expr.lit v | _ _ f (expr.constr t c) := expr.constr t c | _ _ f (expr.case e eβ‚€ e₁) := expr.case (expr.map f e) (expr.map f eβ‚€) (expr.map (map f) e₁) | _ _ f (expr.app eβ‚€ e₁) := expr.app (expr.map f eβ‚€) (expr.map f e₁) | _ _ f (expr.abs t e) := expr.abs t (expr.map (map f) e) | Ξ± Ξ² f (expr.bind' n ts bs e) := expr.bind' n ts (Ξ» i, expr.map (map f) (bs i)) (expr.map (map f) e) -- -- begin -- -- intros Ξ± Ξ² f e, -- -- revert Ξ² f, -- -- induction e ; intros Ξ² f, -- -- { apply expr.var (f a) }, -- -- { apply expr.lit a }, -- -- { apply expr.constr a a_1 }, -- -- { apply expr.case (ih_1 f) (ih_2 f) (ih_3 $ map f) }, -- -- { apply expr.abs a (ih_1 $ map f) }, -- -- { apply expr.app (ih_1 f) (ih_2 f) }, -- -- { apply expr.bind' a (Ξ» v, ih_1 v $ map f) (ih_2 $ map f), }, -- -- end instance : has_map expr := { map := @expr.map } open has_map namespace expr def right {Ξ± : Type u} {Ξ² : Type (max w v)} {Ξ³ : Type w} (f : Ξ± β†’ expr Ξ²) : Ξ³ βŠ• Ξ± β†’ expr (Ξ³ βŠ• Ξ²) | (sum.inl x) := expr.var (sum.inl x) | (sum.inr e) := sum.inr <$> f e def bind : βˆ€ {Ξ± Ξ² : Type u}, expr Ξ± β†’ (Ξ± β†’ expr Ξ²) β†’ expr Ξ² | _ _ (expr.var v) f := f v | _ _ (expr.lit n) f := expr.lit n | _ _ (expr.constr t c) f := expr.constr t c | _ _ (expr.case p eβ‚€ e₁) f := case (bind p f) (bind eβ‚€ f) (bind e₁ $ expr.right f) | _ _ (expr.abs t e) f := expr.abs t (bind e $ expr.right f) | _ _ (expr.app eβ‚€ e₁) f := expr.app (bind eβ‚€ f) (bind e₁ f) | _ _ (expr.bind' n ts bs e) f := expr.bind' n ts (Ξ» i, bind (bs i) $ expr.right f) (bind e $ expr.right f) instance : has_bind expr := { bind := @expr.bind } lemma right_var_eq_var_comp_map {Ξ± Ξ² Ξ³} (f : Ξ± β†’ Ξ²) : right (var ∘ f) = var ∘ (has_map.map f : Ξ³ βŠ• Ξ± β†’ Ξ³ βŠ• Ξ²) := begin apply funext, intro, cases x with x x ; refl, end lemma map_eq_bind {Ξ± Ξ²} (e : expr Ξ±) (f : Ξ± β†’ Ξ²) : f <$> e = e >>= expr.var ∘ f := begin revert Ξ² f, induction e ; intros Ξ² f ; try { refl }, case expr.case Ξ± e eβ‚€ e₁ { unfold has_map.map map has_bind.bind bind at *, simp [ih_1,ih_2,ih_3,right_var_eq_var_comp_map], refl }, case expr.abs Ξ± t e { unfold has_map.map map has_bind.bind bind at *, simp [ih_1,right_var_eq_var_comp_map], refl }, case expr.app Ξ± eβ‚€ e₁ { unfold has_map.map map has_bind.bind bind at *, simp [ih_1,ih_2] }, case expr.bind' Ξ± n ts bs e { unfold has_map.map map has_bind.bind bind at *, simp [ih_1,ih_2,right_var_eq_var_comp_map], refl }, end lemma expr.pure_bind {Ξ± Ξ²} (x : Ξ±) (f : Ξ± β†’ expr Ξ²) : (expr.var x >>= f) = f x := by refl lemma expr.map_bind_assoc {Ξ± Ξ² Ξ³} (x : expr Ξ±) (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ expr Ξ³) : f <$> x >>= g = x >>= (g ∘ f) := sorry lemma expr.bind_map_assoc {Ξ± Ξ² Ξ³} (x : expr Ξ±) (f : Ξ² β†’ Ξ³) (g : Ξ± β†’ expr Ξ²) : x >>= (Ξ» i, f <$> g i) = f <$> (x >>= g) := sorry lemma expr.bind_map_inr_eq_map_inr_bind {Ξ± Ξ² : Type (max u v)} {Ξ³ : Type u} (x : expr Ξ±) (g : Ξ± β†’ expr Ξ²) : sum.inr <$> x >>= right g = (sum.inr <$> (x >>= g) : expr (Ξ³ βŠ• Ξ²)) := by simp [expr.map_bind_assoc,right,function.comp,expr.bind_map_assoc] lemma option_id_map (Ξ± n) : option.map id = @id (fin n βŠ• Ξ±) := functor.id_map' _ lemma expr.id_map {Ξ±}(e : expr Ξ±) : id <$> e = e := begin induction e ; simp [has_map.map,expr.map,option_id_map] at *, all_goals { simp [ih_1] }, all_goals { simp [ih_2] }, all_goals { simp [ih_3] }, end lemma expr.bind_assoc {Ξ± Ξ² : Type (u)} {Ξ³ : Type (u)} (x : expr Ξ±) (f : Ξ± β†’ expr Ξ²) (g : Ξ² β†’ expr Ξ³) : x >>= f >>= g = x >>= (Ξ» i, f i >>= g) := begin unfold has_bind.bind at *, revert f g Ξ² Ξ³, induction x ; intros Ξ² Ξ³ f g ; try { refl }, case expr.case v e eβ‚€ e₁ { simp [bind,ih_1,ih_2,ih_3], apply congr_arg, apply congr_arg, apply funext, intro x, cases x with x x, refl, apply @expr.bind_map_inr_eq_map_inr_bind _ _ (fin 2) (f x) g }, case expr.abs v t e { simp [bind,ih_1], apply congr_arg, apply congr_arg, apply funext, intro x, cases x with x x, refl, apply @expr.bind_map_inr_eq_map_inr_bind _ _ (fin 1) (f x) g }, case expr.app v eβ‚€ e₁ { simp [bind,ih_1,ih_2], }, case expr.bind' v n ts bs e { simp [bind,ih_1,ih_2], tactic.congr, { apply funext, intro i, apply congr_arg, apply funext, intro j, cases j with j j, refl, apply @expr.bind_map_inr_eq_map_inr_bind _ _ (fin (succ n)) (f j) g }, { apply funext, intro i, cases i with i i, refl, unfold right, apply @expr.bind_map_inr_eq_map_inr_bind _ _ (fin (succ n)) (f i) g, } }, end lemma bind_pure_comp_eq_map {Ξ± Ξ² : Type u} (f : Ξ± β†’ Ξ²) (x : expr Ξ±) : x >>= expr.var ∘ f = f <$> x := begin revert Ξ² , induction x ; intros Ξ² f ; try { refl } ; unfold has_bind.bind bind at *, { simp [ih_1,ih_2,right_var_eq_var_comp_map,has_map.map,expr.map], apply congr_arg, rw [ih_3], refl }, { simp [right_var_eq_var_comp_map,ih_1], refl }, { simp [ih_1,ih_2], refl }, { simp [right_var_eq_var_comp_map,ih_1,ih_2], refl } end instance : monad expr := { pure := Ξ» Ξ±, expr.var , bind := @expr.bind , map := @expr.map , id_map := @expr.id_map , bind_pure_comp_eq_map := @bind_pure_comp_eq_map , pure_bind := @expr.pure_bind , bind_assoc := @expr.bind_assoc } def split_max {n} : fin (succ n) β†’ option (fin n) | ⟨i,_⟩ := if h : i < n then some ⟨i,h⟩ else none def mk_local {n Ξ³} (t : Ξ³) (Ξ“ : fin n β†’ Ξ³) (i : fin (succ n)) : Ξ³ := match split_max i with | none := t | (some i) := Ξ“ i end def add_local {v Ξ³} (t : Ξ³) (Ξ“ : v β†’ Ξ³) : fin 1 βŠ• v β†’ Ξ³ | (sum.inr v) := Ξ“ v | (sum.inl _) := t def add_locals {Ξ± Ξ² Ξ³} (t : Ξ± β†’ Ξ³) (Ξ“ : Ξ² β†’ Ξ³) : Ξ± βŠ• Ξ² β†’ Ξ³ | (sum.inr x) := Ξ“ x | (sum.inl x) := t x def l_pair {Ξ³} (tβ‚€ t₁ : Ξ³) : fin 2 β†’ Ξ³ | x := if x = 0 then tβ‚€ else t₁ infixr ` <+ `:10 := add_local infixr ` << `:10 := add_locals infixr ` <| `:10 := mk_local inductive has_type : βˆ€ {v}, (v β†’ type) β†’ expr v β†’ type β†’ Prop | var : βˆ€ {v} (Ξ“ : v β†’ type) (var : v), has_type Ξ“ (expr.var var) (Ξ“ var) | lit : βˆ€ {v} (Ξ“ : v β†’ type) (n : β„•), has_type Ξ“ (expr.lit n) type.int | nil : βˆ€ {v} (Ξ“ : v β†’ type) (t : type), has_type Ξ“ (expr.constr t list_cons.nil) (type.list t) | cons : βˆ€ {v} (Ξ“ : v β†’ type) (t : type), has_type Ξ“ (expr.constr t list_cons.cons) (type.fn t $ type.fn (type.list t) (type.list t)) | app : βˆ€ {v} (Ξ“ : v β†’ type) (eβ‚€ e₁ : expr v) (tβ‚€ t₁ : type), has_type Ξ“ eβ‚€ (type.fn tβ‚€ t₁) β†’ has_type Ξ“ e₁ tβ‚€ β†’ has_type Ξ“ (expr.app eβ‚€ e₁) t₁ | case : βˆ€ {v} (Ξ“ : v β†’ type) (p eβ‚€ : expr v) (e₁ : expr (fin 2 βŠ• v)) (tp t : type), has_type Ξ“ p (type.list tp) β†’ has_type Ξ“ eβ‚€ t β†’ has_type (l_pair tp (type.list tp) << Ξ“) e₁ t β†’ has_type Ξ“ (expr.case p eβ‚€ e₁) t | abs : βˆ€ {v} (Ξ“ : v β†’ type) (t : type) (e : expr (fin 1 βŠ• v)) (t' : type), has_type (t <+ Ξ“) e t' β†’ has_type Ξ“ (expr.abs t e) (t ↦ t') | bind : βˆ€ {v} (Ξ“ : v β†’ type) {n : β„•} (Ξ“' : fin (succ n) β†’ type) (ls : fin (succ n) β†’ expr (fin (succ n) βŠ• v)) (e : expr (fin (succ n) βŠ• v)) (t : type), (βˆ€ l, has_type (Ξ“' << Ξ“) (ls l) (Ξ“' l)) β†’ has_type (Ξ“' << Ξ“) e t β†’ has_type Ξ“ (expr.bind' _ Ξ“' ls e) t notation g` ⊒ `:50 e` :: `:0 t := has_type g e t theorem unique_type {v} (Ξ“ : v β†’ type) (e : expr v) (tβ‚€ t₁ : type) (hβ‚€ : Ξ“ ⊒ e :: tβ‚€) (h₁ : Ξ“ ⊒ e :: t₁) : tβ‚€ = t₁ := begin revert tβ‚€, revert t₁, induction e ; intros tβ‚€ hβ‚€ t₁ h₁ ; try { cases hβ‚€ ; cases h₁ ; refl }, case expr.case _ v { cases hβ‚€, cases h₁, apply ih_2 _ _ a_3 _ a_6, }, case expr.abs v' t term { cases hβ‚€, cases h₁, apply congr_arg, apply ih_1 _ _ a _ a_1 }, case expr.app v' eβ‚€ e₁ { cases hβ‚€, cases h₁, have h := ih_1 _ _ a _ a_2, injection h with hβ‚€ h₁, }, case expr.bind' v' n Ξ“' defs body { cases hβ‚€, cases h₁, apply ih_2 (Ξ“' << Ξ“) ; assumption } end def insert_last {n v} (e : expr $ fin n βŠ• v) : fin (succ n) βŠ• v β†’ expr (fin n βŠ• v) | (sum.inl i) := match split_max i with | none := e | (some i) := expr.var (sum.inl i) end | (sum.inr v) := expr.var $ sum.inr v def from_right {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) : Ξ± βŠ• Ξ² β†’ Ξ² | (sum.inr x) := x | (sum.inl x) := f x def subst_last {n v} (eβ‚€ : expr v) (e₁ : expr (fin (succ n) βŠ• v)) : expr (fin n βŠ• v) := e₁ >>= insert_last (sum.inr <$> eβ‚€) def subst_one {v} (eβ‚€ : expr v) (e₁ : expr (fin 1 βŠ• v)) : expr v := from_right fin.elim0 <$> subst_last eβ‚€ e₁ -- e₁ >>= has_map.map (from_right fin.elim0) ∘ insert_last (sum.inr <$> eβ‚€) def subst_two {v} (x xs : expr v) (e₁ : expr (fin 2 βŠ• v)) : expr v := subst_one x $ subst_last xs e₁ def nil {v} (t : type) : expr v := expr.constr t list_cons.nil def cons {v} (t : type) (eβ‚€ e₁ : expr v) : expr v := expr.app (expr.app (expr.constr t list_cons.cons) eβ‚€) e₁ inductive small_step : βˆ€ {v}, (v β†’ expr v) β†’ expr v β†’ expr v β†’ Prop | var : βˆ€ {v} (t : v β†’ expr v) (var : v), small_step t (expr.var var) (t var) | app : βˆ€ {v} (Ξ“ : v β†’ expr v) {n : β„•} (t : type) (eβ‚€ : expr $ fin 1 βŠ• v) (e₁ : expr v), small_step Ξ“ (expr.app (expr.abs t eβ‚€) e₁) (subst_one e₁ eβ‚€) | case : βˆ€ {v} (Ξ“ : v β†’ expr v) (p p' eβ‚€ : expr v) (e₁ : expr (fin 2 βŠ• v)), small_step Ξ“ p p' β†’ small_step Ξ“ (expr.case p eβ‚€ e₁) (expr.case p' eβ‚€ e₁) | case_nil : βˆ€ {v} (Ξ“ : v β†’ expr v) (t : type) (p p' eβ‚€ : expr v) (e₁ : expr (fin 2 βŠ• v)), small_step Ξ“ (expr.case (expr.nil t) eβ‚€ e₁) eβ‚€ | case_cons : βˆ€ {v} (Ξ“ : v β†’ expr v) (t : type) (x xs eβ‚€ : expr v) (e₁ : expr (fin 2 βŠ• v)), small_step Ξ“ (expr.case (expr.cons t x xs) eβ‚€ e₁) (subst_two x xs e₁) | bind : βˆ€ {v} (Ξ“ : v β†’ expr v) {n : β„•} (Ξ“' : fin (succ n) β†’ type) (ls : fin (succ n) β†’ expr (fin (succ n) βŠ• v)) (e e' : expr (fin (succ n) βŠ• v)), small_step (ls << (has_map.map sum.inr ∘ Ξ“)) e e' β†’ small_step Ξ“ (expr.bind' _ Ξ“' ls e) (expr.bind' _ Ξ“' ls e') | bind' : βˆ€ {v} (Ξ“ : v β†’ expr v) {n : β„•} (Ξ“' : fin (succ n) β†’ type) (ls : fin (succ n) β†’ expr (fin (succ n) βŠ• v)) (e : expr v), small_step Ξ“ (expr.bind' _ Ξ“' ls $ sum.inr <$> e) e notation g` ⊧ `e` ~> `t := small_step g e t inductive value' (v : Type (u+1)) : Type v β†’ Type ((max v u)+1) | nat {} : βˆ€ {v' : Type v}, β„• β†’ value' v' | cons : βˆ€ {v'}, type β†’ v β†’ v β†’ value' v' | nil {} : βˆ€ {v'}, type β†’ value' v' | abs {} : Ξ  {v'}, type β†’ expr (fin 1 βŠ• v') β†’ value' v' inductive value : Type (u+1) | mk : value' value empty β†’ value def whnf (v : Type u) : Type (u+1) := value' (expr v) v def i0 {v n} : expr (fin (succ n) βŠ• v) := expr.var (sum.inl 0) def i1 {v n} : expr (fin (succ $ succ n) βŠ• v) := expr.var (sum.inl 1) -- def mk_app {v : Type u} : expr v β†’ list (expr v) β†’ expr v -- | e list.nil := e -- | eβ‚€ (list.cons e₁ es) := mk_app (expr.app eβ‚€ e₁) es -- def is_whnf {v : Type u} : expr v β†’ list (expr v) β†’ option (whnf v) -- | (lit v) es := _ -- some (mk_app (value'.nat v) es) -- | (var v) es := none -- | (cons t list_cons.nil) es := _ -- some value'.nil -- | (cons t list_cons.cons) es := _ -- -- some $ value'.abs (l_pair t $ type.list t) (expr.cons i0 i1) -- | (app eβ‚€ e₁) es := _ -- | (@abs .(v) _ t e) es := _ -- some $ value'.abs t e -- | (@bind' .(v) _ _ _ _) es := _ -- none -- | (case _ _ _) es := _ -- none def whnf.to_expr {v} : whnf v β†’ expr v | (value'.nat n) := expr.lit n | (value'.cons t eβ‚€ e₁) := cons t eβ‚€ e₁ | (value'.nil t) := expr.nil t | (@value'.abs .(_) .(_) t e) := expr.abs t e def whnf_eval {v} (st : v β†’ expr v) (e : expr v) (e' : whnf v) : Prop := tc (small_step st) e e'.to_expr notation g` ⊧ `e` ~>⁺ `t := whnf_eval g e t /- theorems -/ -- unique type -- deterministic evaluation theorem map_preserves_types {var var'} (Ξ“ : var β†’ type) (Ξ“' : var' β†’ type) {e : expr var} {t : type} {sub : var β†’ var'} (He : Ξ“ ⊒ e :: t) (Hsub : βˆ€ v, Ξ“' (sub v) = Ξ“ v) : Ξ“' ⊒ (sub <$> e) :: t := sorry theorem bind_preserves_types {var var'} (Ξ“ : var β†’ type) (Ξ“' : var' β†’ type) {e : expr var} {t : type} {sub : var β†’ expr var'} (He : Ξ“ ⊒ e :: t) (Hsub : βˆ€ v, Ξ“' ⊒ sub v :: Ξ“ v) : Ξ“' ⊒ (e >>= sub) :: t := begin revert var' Ξ“' t, induction e ; intros var' Ξ“' t sub He Hsub ; unfold has_bind.bind bind at *, case expr.var { cases He, apply Hsub }, case expr.lit { cases He, apply has_type.lit, }, case expr.constr { cases He, apply has_type.nil, apply has_type.cons }, case expr.case { cases He with hβ‚€ h₁ hβ‚‚, apply has_type.case, { apply ih_1 _ _ a_3 Hsub, }, { apply ih_2 _ _ a_4 Hsub, }, { apply ih_3 _ _ a_5, intro v, cases v with v v ; unfold right, { apply has_type.var }, { apply map_preserves_types Ξ“', apply Hsub, intro, refl } } }, case expr.abs { cases He, apply has_type.abs, apply ih_1 _ _ a_2, intro v, cases v with v v ; unfold right, { apply has_type.var }, { apply map_preserves_types, apply Hsub, intro, refl } }, case expr.app { cases He, apply has_type.app, apply ih_1 _ _ a_2 Hsub, apply ih_2 _ _ a_3 Hsub, }, case expr.bind' { cases He, apply has_type.bind, { intro v', apply ih_1 v' _ _ (a_3 _), intro v'', cases v'' with v'' v'' ; unfold right, { apply has_type.var }, { apply map_preserves_types, apply Hsub, intro, refl } }, { apply ih_2 _ _ a_4, intro v'', cases v'' with v'' v'' ; unfold right, { apply has_type.var }, { apply map_preserves_types, apply Hsub, intro, refl } } }, end theorem subst_last_preserves_types {n var} {Ξ“ : var β†’ type} {Ξ“' : fin n β†’ type} {e : expr (fin (succ n) βŠ• var)} {t : type} {e' : expr var} (t' : type) (He : ((t' <| Ξ“') << Ξ“) ⊒ e :: t) (He' : Ξ“ ⊒ e' :: t') : (Ξ“' << Ξ“) ⊒ subst_last e' e :: t := begin unfold subst_last, apply bind_preserves_types _ _ He, intro v, cases v with v v ; unfold insert_last, { destruct (split_max v), { intros h, simp [h,insert_last._match_1], apply map_preserves_types Ξ“, simp [add_locals,mk_local,h], apply He', intro, refl }, { intros i h, simp [h,insert_last._match_1,add_locals,mk_local,h], apply has_type.var } }, { apply has_type.var } end theorem subst_one_preserves_types {var} {Ξ“ : var β†’ type} {e : expr (fin 1 βŠ• var)} {t : type} {e' : expr var} (t' : type) (He : (t' <+ Ξ“) ⊒ e :: t) (He' : Ξ“ ⊒ e' :: t') : Ξ“ ⊒ subst_one e' e :: t := sorry -- begin -- unfold subst_one, -- apply map_preserves_types (_ << t' <+ Ξ“) _, -- apply subst_last_preserves_types _ _ He, -- apply He', -- intro, cases v with v v, -- apply v.elim0, -- refl -- end theorem subst_two_preserves_types {var} {Ξ“ : var β†’ type} {e : expr (fin 2 βŠ• var)} {t : type} {eβ‚€ : expr var} (tβ‚€ : type) {e₁ : expr var} (t₁ : type) (He : (l_pair tβ‚€ t₁ << Ξ“) ⊒ e :: t) (Heβ‚€ : Ξ“ ⊒ eβ‚€ :: tβ‚€) (He₁ : Ξ“ ⊒ e₁ :: t₁) : Ξ“ ⊒ subst_two eβ‚€ e₁ e :: t := sorry -- begin -- unfold subst_two, -- apply subst_one_preserves_types, -- apply subst_last_preserves_types, -- end -- evaluation preserves types theorem evaluation_preserves_types {var} (V : var β†’ expr var) (Ξ“ : var β†’ type) (Hstore : βˆ€ i, Ξ“ ⊒ V i :: Ξ“ i) (e e' : expr var) (t : type) (Hval : V ⊧ e ~> e') (Htype : Ξ“ ⊒ e :: t) : Ξ“ ⊒ e' :: t := begin revert t, induction Hval ; introv Ht, case small_step.var vv store { cases Ht, apply Hstore }, case expr.small_step.app _ M { rename Ξ“_1 Ξ“, cases Ht, cases a, apply subst_one_preserves_types t ; assumption }, case expr.small_step.case { cases Ht, apply has_type.case _ _ _ _ tp, { apply ih_1 _ Hstore _ a_1, }, all_goals { assumption } }, case expr.small_step.case_nil { cases Ht with d ; assumption }, case expr.small_step.case_cons { cases Ht, cases a, cases a_3, cases a_5, apply subst_two_preserves_types t (type.list t), { assumption }, { cases a_3, have H := unique_type _ _ _ _ a_5 a_7, cases H, assumption }, { cases a, cases a_7, cases a_9, assumption, }, }, case expr.small_step.bind { cases Ht, apply has_type.bind _ _ _ _ _ a_1, apply ih_1 _ _ _ a_2, admit }, case expr.small_step.bind' { cases Ht, admit } end end expr end interpreter
1c4bfce4ee9fe229a4350af80c19ca13d099383e
9c2e8d73b5c5932ceb1333265f17febc6a2f0a39
/src/S4/semantics.lean
f85aa09728c8db7b805f74baaa3b8663d3997b79
[ "MIT" ]
permissive
minchaowu/ModalTab
2150392108dfdcaffc620ff280a8b55fe13c187f
9bb0bf17faf0554d907ef7bdd639648742889178
refs/heads/master
1,626,266,863,244
1,592,056,874,000
1,592,056,874,000
153,314,364
12
1
null
null
null
null
UTF-8
Lean
false
false
12,747
lean
import .ops open subtype nnf tmodel list section variables (Ο† ψ : nnf) (Γ₁ Ξ“β‚‚ Ξ” Ξ›: list nnf) {st : Type} variables (k : S4 st) (s : st) open list theorem sat_subset (h₁ : Γ₁ βŠ† Ξ“β‚‚) (hβ‚‚ : sat k s Ξ“β‚‚) : sat k s Γ₁ := Ξ» x hx, hβ‚‚ _ (h₁ hx) theorem sat_sublist (h₁ : Γ₁ <+ Ξ“β‚‚) (hβ‚‚ :sat k s Ξ“β‚‚) : sat k s Γ₁ := sat_subset _ _ _ _ (sublist.subset h₁) hβ‚‚ theorem sat_append (h₁ : sat k s Γ₁) (hβ‚‚ : sat k s Ξ“β‚‚) : sat k s (Γ₁ ++ Ξ“β‚‚) := begin intros Ο† h, rw mem_append at h, cases h, apply h₁ _ h, apply hβ‚‚ _ h end theorem unsat_contra {Ξ” n} : var n ∈ Ξ” β†’ neg n ∈ Ξ” β†’ unsatisfiable Ξ”:= begin intros h₁ hβ‚‚, intros v hsat, intros s hsat, have := hsat _ h₁, have := hsat _ hβ‚‚, simpa end theorem unsat_contra_seqt {Ξ” : sseqt} {n} : var n ∈ Ξ”.m β†’ neg n ∈ Ξ”.m β†’ unsatisfiable (Ξ”.m ++ Ξ”.b):= begin intros h₁ hβ‚‚, intros st m, intros s hsat, have := unsat_contra h₁ hβ‚‚, have := this _ m s, apply this, apply sat_subset _ _ _ _ _ hsat, simp end theorem sat_of_and : force k s (and Ο† ψ) ↔ (force k s Ο†) ∧ (force k s ψ) := by split; {intro, simpa} theorem sat_of_sat_erase (h₁ : sat k s $ Ξ”.erase Ο†) (hβ‚‚ : force k s Ο†) : sat k s Ξ” := begin intro ψ, intro h, by_cases (ψ = Ο†), {rw h, assumption}, {have : ψ ∈ Ξ”.erase Ο†, rw mem_erase_of_ne, assumption, exact h, apply h₁, assumption} end theorem unsat_and_of_unsat_split (h₁ : and Ο† ψ ∈ Ξ”) (hβ‚‚ : unsatisfiable $ Ο† :: ψ :: Ξ”.erase (and Ο† ψ)) : unsatisfiable Ξ” := begin intro st, intros, intro h, apply hβ‚‚, swap 3, exact k, swap, exact s, intro e, intro he, cases he, {rw he, have := h _ h₁, rw sat_of_and at this, exact this.1}, {cases he, {rw he, have := h _ h₁, rw sat_of_and at this, exact this.2}, {have := h _ h₁, apply h, apply mem_of_mem_erase he} } end theorem unsat_and_of_unsat_split_seqt {Ξ“} (h₁ : and Ο† ψ ∈ Ξ”) (hβ‚‚ : unsatisfiable $ (Ο† :: ψ :: Ξ”.erase (and Ο† ψ)++Ξ“)) : unsatisfiable (Ξ”++Ξ“) := begin intro st, intros, intro h, apply hβ‚‚, swap 3, exact k, swap, exact s, intro e, intro he, cases he, {rw he, have := h _ (mem_append_left _ h₁), rw sat_of_and at this, exact this.1}, {cases he, {rw he, have := h _ (mem_append_left _ h₁), rw sat_of_and at this, exact this.2}, {have := h _ (mem_append_left _ h₁), apply h, apply mem_of_mem_erase, rw erase_append_left, exact he, exact h₁} } end theorem sat_and_of_sat_split (h₁ : and Ο† ψ ∈ Ξ”) (hβ‚‚ : sat k s $ Ο† :: ψ :: Ξ”.erase (and Ο† ψ)) : sat k s Ξ” := begin intro e, intro he, by_cases (e = and Ο† ψ), { rw h, dsimp, split, repeat {apply hβ‚‚, simp} }, { have : e ∈ Ξ”.erase (and Ο† ψ), { rw mem_erase_of_ne, repeat { assumption } }, apply hβ‚‚, simp [this] } end theorem sat_and_of_sat_split_seqt {Ξ“} (h₁ : and Ο† ψ ∈ Ξ”) (hβ‚‚ : sat k s $ (Ο† :: ψ :: Ξ”.erase (and Ο† ψ)++Ξ“)) : sat k s (Ξ”++Ξ“) := begin intro e, intro he, by_cases (e = and Ο† ψ), { rw h, dsimp, split, repeat {apply hβ‚‚, simp} }, { have : e ∈ Ξ”.erase (and Ο† ψ) ++ Ξ“, { rw ←erase_append_left, rw mem_erase_of_ne, repeat {assumption} }, apply hβ‚‚, simp [this] } end theorem sat_split_of_sat_and_seqt {Ξ“} (h₁ : and Ο† ψ ∈ Ξ”) (hβ‚‚ : sat k s (Ξ”++Ξ“)) : sat k s $ (Ο† :: ψ :: Ξ”.erase (and Ο† ψ)++Ξ“) := begin intros e he, rw mem_append at he, cases he, have : force k s (and Ο† ψ), {apply hβ‚‚, simp [h₁]}, rw sat_of_and at this, {cases he, {rw he, exact this.left}, {cases he, rw he, exact this.right, apply hβ‚‚, rw mem_append, left, apply mem_of_mem_erase he} }, {apply hβ‚‚, rw mem_append, right, exact he} end theorem unsat_or_of_unsat_split_seqt {Ξ“} (h : or Ο† ψ ∈ Ξ”) (h₁ : unsatisfiable $ (Ο† :: Ξ”.erase (nnf.or Ο† ψ)++Ξ“)) (hβ‚‚ : unsatisfiable $ (ψ :: Ξ”.erase (nnf.or Ο† ψ)++Ξ“)) : unsatisfiable $ (Ξ”++Ξ“) := begin intro, intros, intro hsat, have := hsat _ (mem_append_left _ h), dsimp at this, cases this, {apply h₁, swap 3, exact k, swap, exact s, intro e, intro he, cases he, rw he, exact this, apply hsat, apply mem_of_mem_erase, rw erase_append_left, exact he, exact h}, {apply hβ‚‚, swap 3, exact k, swap, exact s, intro e, intro he, cases he, rw he, exact this, apply hsat, apply mem_of_mem_erase, rw erase_append_left, exact he, exact h} end theorem sat_or_of_sat_split_left (h : or Ο† ψ ∈ Ξ”) (hl : sat k s $ Ο† :: Ξ”.erase (nnf.or Ο† ψ)) : sat k s Ξ” := begin intros e he, by_cases (e = or Ο† ψ), { rw h, dsimp, left, apply hl, simp}, {have : e ∈ Ξ”.erase (or Ο† ψ), { rw mem_erase_of_ne, repeat { assumption } }, apply hl, simp [this]} end theorem sat_or_of_sat_split_right (h : or Ο† ψ ∈ Ξ”) (hl : sat k s $ ψ :: Ξ”.erase (nnf.or Ο† ψ)) : sat k s Ξ” := begin intros e he, by_cases (e = or Ο† ψ), { rw h, dsimp, right, apply hl, simp}, { have : e ∈ Ξ”.erase (or Ο† ψ), { rw mem_erase_of_ne, repeat { assumption } }, apply hl, simp [this] } end /- S4-specific lemmas -/ theorem force_of_force_box (h : force k s $ box Ο†) : force k s Ο† := by apply h; apply k.refl theorem force_box_box_of_force_box : force k s (box Ο†) β†’ force k s (box (box Ο†)) := by intros h s₁ rs₁ sβ‚‚ rsβ‚‚; apply h; apply k.trans rs₁ rsβ‚‚ theorem unsat_of_unsat_box_new (h₁ : box Ο† ∈ Ξ”) (hβ‚‚ : unsatisfiable $ (Ο† :: Ξ”.erase (box Ο†)) ++ box Ο† :: Ξ›) : unsatisfiable (Ξ” ++ Ξ›) := begin intros st k s h, apply hβ‚‚, swap 3, exact k, swap, exact s, intros e he, rw [mem_append] at he, cases he, {cases he, {rw he, apply force_of_force_box, apply h (box Ο†), simp [h₁]}, {apply h, rw mem_append, left, apply mem_of_mem_erase he }}, {cases he, {rw ←he at h₁, apply h, rw mem_append, left, exact h₁}, {apply h, rw mem_append, right, assumption}} end theorem sat_copy_of_sat_box_new (h₁ : box Ο† ∈ Ξ”) (hβ‚‚ : sat k s $ (Ο† :: Ξ”.erase (box Ο†)) ++ box Ο† :: Ξ›) : sat k s (Ξ” ++ Ξ›) := begin intros ψ hΟ†, rw mem_append at hΟ†, cases hΟ†, {by_cases heq : ψ = box Ο†, {rw heq, apply hβ‚‚ (box Ο†), simp}, {have := mem_erase_of_ne heq, rw ←this at hΟ†, apply hβ‚‚, simp, right, left, exact hΟ†}}, {apply hβ‚‚, simp, repeat {right}, exact hΟ†} end theorem unsat_of_unsat_box_dup (h₁ : box Ο† ∈ Ξ”) (h₃ : unsatisfiable $ (Ο† :: Ξ”.erase (box Ο†)) ++ Ξ›) : unsatisfiable (Ξ” ++ Ξ›) := begin intros st k s h, apply h₃, swap 3, exact k, swap, exact s, intros e he, cases he, {rw he, apply force_of_force_box, apply h (box Ο†), simp [h₁]}, {have := mem_append.1 he, cases this, {apply h, apply mem_append_left, apply mem_of_mem_erase this}, {apply h, apply mem_append_right, exact this}} end end def unmodal_seqt (Ξ“ : sseqt) : list sseqt := @list.pmap _ _ (Ξ» Ο†, Ο† βˆ‰ Ξ“.h ∧ dia Ο† ∈ Ξ“.m) (Ξ» d h, ({s := some {d := d, b := Ξ“.b}, a := {d := d, b := Ξ“.b} :: Ξ“.a, h := d :: Ξ“.h, m := d :: Ξ“.b, ndh := begin rw list.nodup_cons, split, exact h.1, exact Ξ“.ndh end, sph := begin apply list.cons_subperm_of_mem, apply Ξ“.ndh, exact h.1, apply mem_closure_dia, apply Ξ“.sbm, exact h.2, exact Ξ“.sph end, sbm := begin rw list.cons_subset, split, apply mem_closure_dia, apply Ξ“.sbm, exact h.2, apply list.subperm.subset, exact Ξ“.spb end, ha := begin intros Ο† h, cases h with l r, rw l, simp, right, apply Ξ“.ha, exact r end, ps₁ := begin simp [dsig] end, psβ‚‚ := begin simp [bsig] end, .. Ξ“} : sseqt)) (filter_undia Ξ“.h Ξ“.m) (begin intros Ο† hmem,split, {apply mem_filter_dia_right, exact hmem}, {apply mem_filter_dia_right_aux, exact hmem} end) def unmodal_seqt_size (Ξ“ : sseqt) : βˆ€ (i : sseqt), i ∈ unmodal_seqt Ξ“ β†’ (prod.measure_lex' sseqt_size i Ξ“) := list.pmapp _ _ begin intros Ο† h hmem, right, left, apply length_sub_lt_of_nodup_subperm, {apply Ξ“.sph}, {apply mem_closure_dia, apply Ξ“.sbm, exact h.2}, {exact h.1}, {exact Ξ“.ndh} end _ def sat_unmodal_of_sat {Ξ“ : sseqt} : βˆ€ (i : sseqt), i ∈ unmodal_seqt Ξ“ β†’ (βˆ€ {st : Type} (k : S4 st) s, sat k s (Ξ“.m ++ Ξ“.b) β†’ βˆƒ s', sat k s' (i.m ++ i.b)) := list.pmapp _ _ begin intros Ο† hninh hmem st k s h, have hd : force k s (dia Ο†), { apply h, rw mem_append, left, exact hninh.2 }, have hb : βˆ€ Ο† ∈ Ξ“.b, force k s (box Ο†), { intros Ξ³ hΞ³, have := box_only_ex Ξ“.hb hΞ³, cases this with w hw, rw hw, apply force_box_box_of_force_box, have := h _ (mem_append_right _ hΞ³), rw hw at this, exact this}, rcases hd with ⟨w, hrw, hfw⟩, split, swap, exact w, intros ψ hψ, simp at hψ, cases hψ, {rw hψ, exact hfw}, {apply hb, exact hψ, exact hrw} end _ def unsat_of_unsat_unmodal {Ξ“ : sseqt} (i : sseqt) : i ∈ unmodal_seqt Ξ“ ∧ unsatisfiable (i.m ++ i.b) β†’ unsatisfiable (Ξ“.m ++ Ξ“.b) := begin intro hex, intros st k s h, have := sat_unmodal_of_sat i hex.1 k s h, cases this with w hw, have := hex.2, exact this _ _ _ hw end def unmodal_mem_box (Ξ“ : sseqt) : βˆ€ (i : sseqt), i ∈ unmodal_seqt Ξ“ β†’ (βˆ€ Ο†, box Ο† ∈ Ξ“.b β†’ box Ο† ∈ i.m) := list.pmapp _ _ begin intros Ο† h hmem ψ hψ, right, exact hψ end _ def mem_unmodal_seqt (Ξ“ : sseqt) (Ο†) (h : Ο† βˆ‰ Ξ“.h ∧ dia Ο† ∈ Ξ“.m) : βˆƒ (i : sseqt), i ∈ unmodal_seqt Ξ“ ∧ Ο† ∈ i.m := begin split, swap, {exact ({s := some {d := Ο†, b := Ξ“.b}, a := {d := Ο†, b := Ξ“.b} :: Ξ“.a, h := Ο† :: Ξ“.h, m := Ο† :: Ξ“.b, ndh := begin rw list.nodup_cons, split, exact h.1, exact Ξ“.ndh end, sph := begin apply list.cons_subperm_of_mem, apply Ξ“.ndh, exact h.1, apply mem_closure_dia, apply Ξ“.sbm, exact h.2, exact Ξ“.sph end, sbm := begin rw list.cons_subset, split, apply mem_closure_dia, apply Ξ“.sbm, exact h.2, apply list.subperm.subset, exact Ξ“.spb end, ha := begin intros Ο† h, cases h with l r, rw l, simp, right, apply Ξ“.ha, exact r end, ps₁ := begin intro, simp [dsig] end, psβ‚‚ := begin intro, simp [bsig] end, .. Ξ“} : sseqt)}, { dsimp [unmodal_seqt], split, {let mf := (Ξ» (d : nnf) (h : d βˆ‰ Ξ“.h ∧ dia d ∈ Ξ“.m), ({s := some {d := d, b := Ξ“.b}, a := {d := d, b := Ξ“.b} :: Ξ“.a, h := d :: Ξ“.h, m := d :: Ξ“.b, ndh := begin rw list.nodup_cons, split, exact h.1, exact Ξ“.ndh end, sph := begin apply list.cons_subperm_of_mem, apply Ξ“.ndh, exact h.1, apply mem_closure_dia, apply Ξ“.sbm, exact h.2, exact Ξ“.sph end, sbm := begin rw list.cons_subset, split, apply mem_closure_dia, apply Ξ“.sbm, exact h.2, apply list.subperm.subset, exact Ξ“.spb end, ha := begin intros Ο† h, cases h with l r, rw l, simp, right, apply Ξ“.ha, exact r end, ps₁ := begin simp [dsig] end, psβ‚‚ := begin simp [bsig] end, .. Ξ“} :sseqt)), have hmem := mem_filter_undia_left _ _ _ h.2 h.1, have hf : βˆ€ (y : nnf), y ∈ filter_undia (Ξ“.h) (Ξ“.m) β†’ y βˆ‰ Ξ“.h ∧ dia y ∈ Ξ“.m, {intros h hy, split, {apply mem_filter_dia_right, exact hy}, {apply mem_filter_dia_right_aux, exact hy}}, exact mem_pmap_of_mem mf hmem hf}, { simp } } end theorem unmodal_sig (Ξ“ : sseqt) : βˆ€ (i : sseqt), i ∈ unmodal_seqt Ξ“ β†’ (βˆ€ a, a ∈ i.a β†’ some a = i.s ∨ a ∈ Ξ“.a) := list.pmapp _ _ begin intros Ο† h hmem a ha, simp at ha, cases ha, {left, simp, exact ha}, {right, exact ha} end _ theorem unsat_of_closed_and {Ξ“ Ξ”} (i : and_instance Ξ“ Ξ”) (h : unsatisfiable Ξ”) : unsatisfiable Ξ“ := by cases i; { apply unsat_and_of_unsat_split, repeat {assumption} } theorem unsat_of_closed_and_seqt {Ξ“ Ξ”} (i : and_instance_seqt Ξ“ Ξ”) (h : unsatisfiable (Ξ”.m++Ξ”.b)) : unsatisfiable (Ξ“.m++Ξ“.b) := by cases i; {apply unsat_and_of_unsat_split_seqt, repeat {assumption} } theorem unsat_of_closed_or_seqt {Γ₁ Ξ“β‚‚ Ξ” : sseqt} (i : or_instance_seqt Ξ” Γ₁ Ξ“β‚‚) (h₁ : unsatisfiable (Γ₁.m++Γ₁.b)) (hβ‚‚ : unsatisfiable (Ξ“β‚‚.m++Ξ“β‚‚.b)) : unsatisfiable (Ξ”.m++Ξ”.b) := by cases i; {apply unsat_or_of_unsat_split_seqt, repeat { assumption }} theorem unsat_of_closed_box_new {Ξ“ Ξ”} (i : box_new_instance_seqt Ξ“ Ξ”) (h : unsatisfiable $ (Ξ”.m++Ξ”.b)) : unsatisfiable (Ξ“.m++Ξ“.b) := by cases i; { apply unsat_of_unsat_box_new, repeat { assumption } } theorem unsat_of_closed_box_dup {Ξ“ Ξ”} (i : box_dup_instance_seqt Ξ“ Ξ”) (h : unsatisfiable $ (Ξ”.m++Ξ”.b)) : unsatisfiable (Ξ“.m++Ξ“.b) := by cases i; { apply unsat_of_unsat_box_dup, repeat { assumption } }
55c06d71b616638c81a44ad78f87b2d251e90e09
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/homology/local_cohomology.lean
2812460b2b143e5c0c9b2516c00ac1c296768bfb
[ "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
10,668
lean
/- Copyright (c) 2023 Emily Witt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Emily Witt, Scott Morrison, Jake Levinson, Sam van Gool -/ import ring_theory.ideal.basic import algebra.category.Module.colimits import algebra.category.Module.projective import category_theory.abelian.ext import category_theory.limits.final import ring_theory.noetherian /-! # Local cohomology. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the `i`-th local cohomology module of an `R`-module `M` with support in an ideal `I` of `R`, where `R` is a commutative ring, as the direct limit of Ext modules: Given a collection of ideals cofinal with the powers of `I`, consider the directed system of quotients of `R` by these ideals, and take the direct limit of the system induced on the `i`-th Ext into `M`. One can, of course, take the collection to simply be the integral powers of `I`. ## References * [M. Hochster, *Local cohomology*][hochsterunpublished] <https://dept.math.lsa.umich.edu/~hochster/615W22/lcc.pdf> * [R. Hartshorne, *Local cohomology: A seminar given by A. Grothendieck*][hartshorne61] * [M. Brodmann and R. Sharp, *Local cohomology: An algebraic introduction with geometric applications*][brodmannsharp13] * [S. Iyengar, G. Leuschke, A. Leykin, Anton, C. Miller, E. Miller, A. Singh, U. Walther, *Twenty-four hours of local cohomology*][iyengaretal13] ## Tags local cohomology, local cohomology modules ## Future work * Prove that this definition is equivalent to: * the right-derived functor definition * the characterization as the limit of Koszul homology * the characterization as the cohomology of a Cech-like complex * Establish long exact sequence(s) in local cohomology -/ open opposite open category_theory open category_theory.limits noncomputable theory universes u v v' namespace local_cohomology /- We define local cohomology, implemented as a direct limit of `Ext(R/J, -)`. -/ section variables {R : Type u} [comm_ring R] {D : Type v} [small_category D] /-- The directed system of `R`-modules of the form `R/J`, where `J` is an ideal of `R`, determined by the functor `I` -/ def ring_mod_ideals (I : D β₯€ ideal R) : D β₯€ Module.{u} R := { obj := Ξ» t, Module.of R $ R β§Έ (I.obj t), map := Ξ» s t w, submodule.mapq _ _ (linear_map.id) (I.map w).down.down } /- TODO: Once this file is ported, move this file to the right location. -/ instance Module_enough_projectives' : enough_projectives (Module.{u} R) := Module.Module_enough_projectives.{u} /-- The diagram we will take the colimit of to define local cohomology, corresponding to the directed system determined by the functor `I` -/ def diagram (I : D β₯€ ideal R) (i : β„•) : Dα΅’α΅– β₯€ Module.{u} R β₯€ Module.{u} R := (ring_mod_ideals I).op β‹™ Ext R (Module.{u} R) i end section -- We momentarily need to work with a type inequality, as later we will take colimits -- along diagrams either in Type, or in the same universe as the ring, and we need to cover both. variables {R : Type max u v} [comm_ring R] {D : Type v} [small_category D] /-- `local_cohomology.of_diagram I i` is the the functor sending a module `M` over a commutative ring `R` to the direct limit of `Ext^i(R/J, M)`, where `J` ranges over a collection of ideals of `R`, represented as a functor `I`. -/ /- In this definition we do not assume any special property of the diagram `I`, but the relevant case will be where `I` is (cofinal with) the diagram of powers of a single given ideal. Below, we give two equivalent definitions of the usual local cohomology with support in an ideal `J`, `local_cohomology` and `local_cohomology.of_self_le_radical`. -/ def of_diagram (I : D β₯€ ideal R) (i : β„•) : Module.{max u v} R β₯€ Module.{max u v} R := colimit (diagram.{(max u v) v} I i) end section variables {R : Type max u v v'} [comm_ring R] {D : Type v} [small_category D] variables {E : Type v'} [small_category E] (I' : E β₯€ D) (I : D β₯€ ideal R) /-- Local cohomology along a composition of diagrams. -/ def diagram_comp (i : β„•) : diagram (I' β‹™ I) i β‰… I'.op β‹™ (diagram I i) := iso.refl _ /-- Local cohomology agrees along precomposition with a cofinal diagram. -/ def iso_of_final [functor.initial I'] (i : β„•) : of_diagram.{(max u v) v'} (I' β‹™ I) i β‰… of_diagram.{(max u v') v} I i := (has_colimit.iso_of_nat_iso (diagram_comp _ _ _)) β‰ͺ≫ (functor.final.colimit_iso _ _) end section diagrams variables {R : Type u} [comm_ring R] /-- The functor sending a natural number `i` to the `i`-th power of the ideal `J` -/ def ideal_powers_diagram (J : ideal R) : β„•α΅’α΅– β₯€ ideal R := { obj := Ξ» t, J^(unop t), map := Ξ» s t w, ⟨⟨ideal.pow_le_pow w.unop.down.down⟩⟩, } /-- The full subcategory of all ideals with radical containing `J` -/ @[derive category] def self_le_radical (J : ideal R) : Type u := full_subcategory (Ξ» J' : ideal R, J ≀ J'.radical) instance self_le_radical.inhabited (J : ideal R) : inhabited (self_le_radical J) := { default := ⟨J, ideal.le_radical⟩ } /-- The diagram of all ideals with radical containing `J`, represented as a functor. This is the "largest" diagram that computes local cohomology with support in `J`. -/ def self_le_radical_diagram (J : ideal R) : (self_le_radical J) β₯€ ideal R := full_subcategory_inclusion _ end diagrams end local_cohomology /-! We give two models for the local cohomology with support in an ideal `J`: first in terms of the powers of `J` (`local_cohomology`), then in terms of *all* ideals with radical containing `J` (`local_cohomology.of_self_le_radical`). -/ section models_for_local_cohomology open local_cohomology variables {R : Type u} [comm_ring R] /-- `local_cohomology J i` is `i`-th the local cohomology module of a module `M` over a commutative ring `R` with support in the ideal `J` of `R`, defined as the direct limit of `Ext^i(R/J^t, M)` over all powers `t : β„•`. -/ def local_cohomology (J : ideal R) (i : β„•) : Module.{u} R β₯€ Module.{u} R := of_diagram (ideal_powers_diagram J) i /-- Local cohomology as the direct limit of `Ext^i(R/J', M)` over *all* ideals `J'` with radical containing `J`. -/ def local_cohomology.of_self_le_radical (J : ideal R) (i : β„•) : Module.{u} R β₯€ Module.{u} R := of_diagram.{u} (self_le_radical_diagram.{u} J) i end models_for_local_cohomology namespace local_cohomology /-! Showing equivalence of different definitions of local cohomology. * `local_cohomology.iso_self_le_radical` gives the isomorphism `local_cohomology J i β‰… local_cohomology.of_self_le_radical J i` * `local_cohomology.iso_of_same_radical` gives the isomorphism `local_cohomology J i β‰… local_cohomology K i` when `J.radical = K.radical`. -/ section local_cohomology_equiv variables {R : Type u} [comm_ring R] /-- Lifting `ideal_powers_diagram J` from a diagram valued in `ideals R` to a diagram valued in `self_le_radical J`. -/ def ideal_powers_to_self_le_radical (J : ideal R) : β„•α΅’α΅– β₯€ self_le_radical J := full_subcategory.lift _ (ideal_powers_diagram J) (Ξ» k, begin change _ ≀ (J^(unop k)).radical, cases (unop k), { simp only [ideal.radical_top, pow_zero, ideal.one_eq_top, le_top] }, { simp only [J.radical_pow _ n.succ_pos, ideal.le_radical] }, end) variables {I J K : ideal R} /-- PORTING NOTE: This lemma should probably be moved to `ring_theory/finiteness.lean` to be near `ideal.exists_radical_pow_le_of_fg`, which it generalizes. -/ lemma ideal.exists_pow_le_of_le_radical_of_fg (hIJ : I ≀ J.radical) (hJ : J.radical.fg) : βˆƒ (k : β„•), I^k ≀ J := begin obtain ⟨k, hk⟩ := J.exists_radical_pow_le_of_fg hJ, use k, calc I^k ≀ J.radical^k : ideal.pow_mono hIJ _ ... ≀ J : hk, end /-- The diagram of powers of `J` is initial in the diagram of all ideals with radical containing `J`. This uses noetherianness. -/ instance ideal_powers_initial [hR : is_noetherian R R] : functor.initial (ideal_powers_to_self_le_radical J) := { out := Ξ» J', begin apply @zigzag_is_connected _ _ _, { intros j1 j2, apply relation.refl_trans_gen.single, -- The inclusions `J^n1 ≀ J'` and `J^n2 ≀ J'` always form a triangle, based on -- which exponent is larger. cases le_total (unop j1.left) (unop j2.left) with h, right, exact ⟨costructured_arrow.hom_mk (hom_of_le h).op (of_as_true trivial)⟩, left, exact ⟨costructured_arrow.hom_mk (hom_of_le h).op (of_as_true trivial)⟩ }, { obtain ⟨k, hk⟩ := ideal.exists_pow_le_of_le_radical_of_fg J'.2 (is_noetherian_def.mp hR _), exact ⟨costructured_arrow.mk (⟨⟨hk⟩⟩ : (ideal_powers_to_self_le_radical J).obj (op k) ⟢ J')⟩}, end } /-- Local cohomology (defined in terms of powers of `J`) agrees with local cohomology computed over all ideals with radical containing `J`. -/ def iso_self_le_radical (J : ideal R) [is_noetherian R R] (i : β„•) : local_cohomology.of_self_le_radical J i β‰… local_cohomology J i := (local_cohomology.iso_of_final.{u u 0} (ideal_powers_to_self_le_radical J) (self_le_radical_diagram J) i).symm β‰ͺ≫ has_colimit.iso_of_nat_iso (iso.refl _) /-- Casting from the full subcategory of ideals with radical containing `J` to the full subcategory of ideals with radical containing `K`. -/ def self_le_radical.cast (hJK : J.radical = K.radical) : self_le_radical J β₯€ self_le_radical K := full_subcategory.map (Ξ» L hL, begin rw ← ideal.radical_le_radical_iff at ⊒ hL, exact hJK.symm.trans_le hL, end) -- TODO generalize this to the equivalence of full categories for any `iff`. instance self_le_radical.cast_is_equivalence (hJK : J.radical = K.radical) : is_equivalence (self_le_radical.cast hJK) := { inverse := self_le_radical.cast hJK.symm, unit_iso := by tidy, counit_iso := by tidy } /-- The natural isomorphism between local cohomology defined using the `of_self_le_radical` diagram, assuming `J.radical = K.radical`. -/ def self_le_radical.iso_of_same_radical (hJK : J.radical = K.radical) (i : β„•) : of_self_le_radical J i β‰… of_self_le_radical K i := (iso_of_final.{u u u} (self_le_radical.cast hJK.symm) _ _).symm /-- Local cohomology agrees on ideals with the same radical. -/ def iso_of_same_radical [is_noetherian R R] (hJK : J.radical = K.radical) (i : β„•) : local_cohomology J i β‰… local_cohomology K i := (iso_self_le_radical J i).symm β‰ͺ≫ self_le_radical.iso_of_same_radical hJK i β‰ͺ≫ iso_self_le_radical K i end local_cohomology_equiv end local_cohomology
de276d65e4c23b4b3c045db9da294395e970ce84
4727251e0cd73359b15b664c3170e5d754078599
/src/probability/ident_distrib.lean
2424ce81a4e8b01c5fc026b17f367fe586ba5f38
[ "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,335
lean
/- Copyright (c) 2022 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import probability.variance /-! # Identically distributed random variables Two random variables defined on two (possibly different) probability spaces but taking value in the same space are *identically distributed* if their distributions (i.e., the image probability measures on the target space) coincide. We define this concept and establish its basic properties in this file. ## Main definitions and results * `ident_distrib f g ΞΌ Ξ½` registers that the image of `ΞΌ` under `f` coincides with the image of `Ξ½` under `g` (and that `f` and `g` are almost everywhere measurable, as otherwise the image measures don't make sense). The measures can be kept implicit as in `ident_distrib f g` if the spaces are registered as measure spaces. * `ident_distrib.comp`: being identically distributed is stable under composition with measurable maps. There are two main kind of lemmas, under the assumption that `f` and `g` are identically distributed: lemmas saying that two quantities computed for `f` and `g` are the same, and lemmas saying that if `f` has some property then `g` also has it. The first kind is registered as `ident_distrib.foo_eq`, the second one as `ident_distrib.foo_snd` (in the latter case, to deduce a property of `f` from one of `g`, use `h.symm.foo_snd` where `h : ident_distrib f g ΞΌ Ξ½`). For instance: * `ident_distrib.measure_mem_eq`: if `f` and `g` are identically distributed, then the probabilities that they belong to a given measurable set are the same. * `ident_distrib.integral_eq`: if `f` and `g` are identically distributed, then their integrals are the same. * `ident_distrib.variance_eq`: if `f` and `g` are identically distributed, then their variances are the same. * `ident_distrib.ae_strongly_measurable_snd`: if `f` and `g` are identically distributed and `f` is almost everywhere strongly measurable, then so is `g`. * `ident_distrib.mem_β„’p_snd`: if `f` and `g` are identically distributed and `f` belongs to `β„’p`, then so does `g`. We also register several dot notation shortcuts for convenience. For instance, if `h : ident_distrib f g ΞΌ Ξ½`, then `h.sq` states that `f^2` and `g^2` are identically distributed, and `h.norm` states that `βˆ₯fβˆ₯` and `βˆ₯gβˆ₯` are identically distributed, and so on. -/ open measure_theory filter finset noncomputable theory open_locale topological_space big_operators measure_theory ennreal nnreal variables {Ξ± Ξ² Ξ³ Ξ΄ : Type*} [measurable_space Ξ±] [measurable_space Ξ²] [measurable_space Ξ³] [measurable_space Ξ΄] namespace probability_theory /-- Two functions defined on two (possibly different) measure spaces are identically distributed if their image measures coincide. This only makes sense when the functions are ae measurable (as otherwise the image measures are not defined), so we require this as well in the definition. -/ structure ident_distrib (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ³) (ΞΌ : measure Ξ± . volume_tac) (Ξ½ : measure Ξ² . volume_tac) : Prop := (ae_measurable_fst : ae_measurable f ΞΌ) (ae_measurable_snd : ae_measurable g Ξ½) (map_eq : measure.map f ΞΌ = measure.map g Ξ½) namespace ident_distrib open topological_space variables {ΞΌ : measure Ξ±} {Ξ½ : measure Ξ²} {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ³} protected lemma refl (hf : ae_measurable f ΞΌ) : ident_distrib f f ΞΌ ΞΌ := { ae_measurable_fst := hf, ae_measurable_snd := hf, map_eq := rfl } protected lemma symm (h : ident_distrib f g ΞΌ Ξ½) : ident_distrib g f Ξ½ ΞΌ := { ae_measurable_fst := h.ae_measurable_snd, ae_measurable_snd := h.ae_measurable_fst, map_eq := h.map_eq.symm } protected lemma trans {ρ : measure Ξ΄} {h : Ξ΄ β†’ Ξ³} (h₁ : ident_distrib f g ΞΌ Ξ½) (hβ‚‚ : ident_distrib g h Ξ½ ρ) : ident_distrib f h ΞΌ ρ := { ae_measurable_fst := h₁.ae_measurable_fst, ae_measurable_snd := hβ‚‚.ae_measurable_snd, map_eq := h₁.map_eq.trans hβ‚‚.map_eq } protected lemma comp_of_ae_measurable {u : Ξ³ β†’ Ξ΄} (h : ident_distrib f g ΞΌ Ξ½) (hu : ae_measurable u (measure.map f ΞΌ)) : ident_distrib (u ∘ f) (u ∘ g) ΞΌ Ξ½ := { ae_measurable_fst := hu.comp_ae_measurable h.ae_measurable_fst, ae_measurable_snd := by { rw h.map_eq at hu, exact hu.comp_ae_measurable h.ae_measurable_snd }, map_eq := begin rw [← ae_measurable.map_map_of_ae_measurable hu h.ae_measurable_fst, ← ae_measurable.map_map_of_ae_measurable _ h.ae_measurable_snd, h.map_eq], rwa ← h.map_eq, end } protected lemma comp {u : Ξ³ β†’ Ξ΄} (h : ident_distrib f g ΞΌ Ξ½) (hu : measurable u) : ident_distrib (u ∘ f) (u ∘ g) ΞΌ Ξ½ := h.comp_of_ae_measurable hu.ae_measurable lemma measure_mem_eq (h : ident_distrib f g ΞΌ Ξ½) {s : set Ξ³} (hs : measurable_set s) : ΞΌ (f ⁻¹' s) = Ξ½ (g ⁻¹' s) := by rw [← measure.map_apply_of_ae_measurable h.ae_measurable_fst hs, ← measure.map_apply_of_ae_measurable h.ae_measurable_snd hs, h.map_eq] alias measure_mem_eq ← probability_theory.ident_distrib.measure_preimage_eq lemma ae_snd (h : ident_distrib f g ΞΌ Ξ½) {p : Ξ³ β†’ Prop} (pmeas : measurable_set {x | p x}) (hp : βˆ€α΅ x βˆ‚ΞΌ, p (f x)) : βˆ€α΅ x βˆ‚Ξ½, p (g x) := begin apply (ae_map_iff h.ae_measurable_snd pmeas).1, rw ← h.map_eq, exact (ae_map_iff h.ae_measurable_fst pmeas).2 hp, end lemma ae_mem_snd (h : ident_distrib f g ΞΌ Ξ½) {t : set Ξ³} (tmeas : measurable_set t) (ht : βˆ€α΅ x βˆ‚ΞΌ, f x ∈ t) : βˆ€α΅ x βˆ‚Ξ½, g x ∈ t := h.ae_snd tmeas ht /-- In a second countable topology, the first function in an identically distributed pair is a.e. strongly measurable. So is the second function, but use `h.symm.ae_strongly_measurable_fst` as `h.ae_strongly_measurable_snd` has a different meaning.-/ lemma ae_strongly_measurable_fst [topological_space Ξ³] [metrizable_space Ξ³] [opens_measurable_space Ξ³] [second_countable_topology Ξ³] (h : ident_distrib f g ΞΌ Ξ½) : ae_strongly_measurable f ΞΌ := h.ae_measurable_fst.ae_strongly_measurable /-- If `f` and `g` are identically distributed and `f` is a.e. strongly measurable, so is `g`. -/ lemma ae_strongly_measurable_snd [topological_space Ξ³] [metrizable_space Ξ³] [borel_space Ξ³] (h : ident_distrib f g ΞΌ Ξ½) (hf : ae_strongly_measurable f ΞΌ) : ae_strongly_measurable g Ξ½ := begin refine ae_strongly_measurable_iff_ae_measurable_separable.2 ⟨h.ae_measurable_snd, _⟩, rcases (ae_strongly_measurable_iff_ae_measurable_separable.1 hf).2 with ⟨t, t_sep, ht⟩, refine ⟨closure t, t_sep.closure, _⟩, apply h.ae_mem_snd is_closed_closure.measurable_set, filter_upwards [ht] with x hx using subset_closure hx, end lemma ae_strongly_measurable_iff [topological_space Ξ³] [metrizable_space Ξ³] [borel_space Ξ³] (h : ident_distrib f g ΞΌ Ξ½) : ae_strongly_measurable f ΞΌ ↔ ae_strongly_measurable g Ξ½ := ⟨λ hf, h.ae_strongly_measurable_snd hf, Ξ» hg, h.symm.ae_strongly_measurable_snd hg⟩ lemma ess_sup_eq [conditionally_complete_linear_order Ξ³] [topological_space Ξ³] [opens_measurable_space Ξ³] [order_closed_topology Ξ³] (h : ident_distrib f g ΞΌ Ξ½) : ess_sup f ΞΌ = ess_sup g Ξ½ := begin have I : βˆ€ a, ΞΌ {x : Ξ± | a < f x} = Ξ½ {x : Ξ² | a < g x} := Ξ» a, h.measure_mem_eq measurable_set_Ioi, simp_rw [ess_sup_eq_Inf, I], end lemma lintegral_eq {f : Ξ± β†’ ℝβ‰₯0∞} {g : Ξ² β†’ ℝβ‰₯0∞} (h : ident_distrib f g ΞΌ Ξ½) : ∫⁻ x, f x βˆ‚ΞΌ = ∫⁻ x, g x βˆ‚Ξ½ := begin change ∫⁻ x, id (f x) βˆ‚ΞΌ = ∫⁻ x, id (g x) βˆ‚Ξ½, rw [← lintegral_map' ae_measurable_id h.ae_measurable_fst, ← lintegral_map' ae_measurable_id h.ae_measurable_snd, h.map_eq], end lemma integral_eq [normed_group Ξ³] [normed_space ℝ Ξ³] [complete_space Ξ³] [borel_space Ξ³] (h : ident_distrib f g ΞΌ Ξ½) : ∫ x, f x βˆ‚ΞΌ = ∫ x, g x βˆ‚Ξ½ := begin by_cases hf : ae_strongly_measurable f ΞΌ, { have A : ae_strongly_measurable id (measure.map f ΞΌ), { rw ae_strongly_measurable_iff_ae_measurable_separable, rcases (ae_strongly_measurable_iff_ae_measurable_separable.1 hf).2 with ⟨t, t_sep, ht⟩, refine ⟨ae_measurable_id, ⟨closure t, t_sep.closure, _⟩⟩, rw ae_map_iff h.ae_measurable_fst, { filter_upwards [ht] with x hx using subset_closure hx }, { exact is_closed_closure.measurable_set } }, change ∫ x, id (f x) βˆ‚ΞΌ = ∫ x, id (g x) βˆ‚Ξ½, rw [← integral_map h.ae_measurable_fst A], rw h.map_eq at A, rw [← integral_map h.ae_measurable_snd A, h.map_eq] }, { rw integral_non_ae_strongly_measurable hf, rw h.ae_strongly_measurable_iff at hf, rw integral_non_ae_strongly_measurable hf } end lemma snorm_eq [normed_group Ξ³] [opens_measurable_space Ξ³] (h : ident_distrib f g ΞΌ Ξ½) (p : ℝβ‰₯0∞) : snorm f p ΞΌ = snorm g p Ξ½ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp only [h_top, snorm, snorm_ess_sup, ennreal.top_ne_zero, eq_self_iff_true, if_true, if_false], apply ess_sup_eq, exact h.comp (measurable_coe_nnreal_ennreal.comp measurable_nnnorm) }, simp only [snorm_eq_snorm' h0 h_top, snorm', one_div], congr' 1, apply lintegral_eq, exact h.comp (measurable.pow_const (measurable_coe_nnreal_ennreal.comp measurable_nnnorm) p.to_real), end lemma mem_β„’p_snd [normed_group Ξ³] [borel_space Ξ³] {p : ℝβ‰₯0∞} (h : ident_distrib f g ΞΌ Ξ½) (hf : mem_β„’p f p ΞΌ) : mem_β„’p g p Ξ½ := begin refine ⟨h.ae_strongly_measurable_snd hf.ae_strongly_measurable, _⟩, rw ← h.snorm_eq, exact hf.2 end lemma mem_β„’p_iff [normed_group Ξ³] [borel_space Ξ³] {p : ℝβ‰₯0∞} (h : ident_distrib f g ΞΌ Ξ½) : mem_β„’p f p ΞΌ ↔ mem_β„’p g p Ξ½ := ⟨λ hf, h.mem_β„’p_snd hf, Ξ» hg, h.symm.mem_β„’p_snd hg⟩ lemma integrable_snd [normed_group Ξ³] [borel_space Ξ³] (h : ident_distrib f g ΞΌ Ξ½) (hf : integrable f ΞΌ) : integrable g Ξ½ := begin rw ← mem_β„’p_one_iff_integrable at hf ⊒, exact h.mem_β„’p_snd hf end lemma integrable_iff [normed_group Ξ³] [borel_space Ξ³] (h : ident_distrib f g ΞΌ Ξ½) : integrable f ΞΌ ↔ integrable g Ξ½ := ⟨λ hf, h.integrable_snd hf, Ξ» hg, h.symm.integrable_snd hg⟩ protected lemma norm [normed_group Ξ³] [borel_space Ξ³] (h : ident_distrib f g ΞΌ Ξ½) : ident_distrib (Ξ» x, βˆ₯f xβˆ₯) (Ξ» x, βˆ₯g xβˆ₯) ΞΌ Ξ½ := h.comp measurable_norm protected lemma nnnorm [normed_group Ξ³] [borel_space Ξ³] (h : ident_distrib f g ΞΌ Ξ½) : ident_distrib (Ξ» x, βˆ₯f xβˆ₯β‚Š) (Ξ» x, βˆ₯g xβˆ₯β‚Š) ΞΌ Ξ½ := h.comp measurable_nnnorm protected lemma pow [has_pow Ξ³ β„•] [has_measurable_pow Ξ³ β„•] (h : ident_distrib f g ΞΌ Ξ½) {n : β„•} : ident_distrib (Ξ» x, (f x) ^ n) (Ξ» x, (g x) ^ n) ΞΌ Ξ½ := h.comp (measurable_id.pow_const n) protected lemma sq [has_pow Ξ³ β„•] [has_measurable_pow Ξ³ β„•] (h : ident_distrib f g ΞΌ Ξ½) : ident_distrib (Ξ» x, (f x) ^ 2) (Ξ» x, (g x) ^ 2) ΞΌ Ξ½ := h.comp (measurable_id.pow_const 2) protected lemma coe_nnreal_ennreal {f : Ξ± β†’ ℝβ‰₯0} {g : Ξ² β†’ ℝβ‰₯0} (h : ident_distrib f g ΞΌ Ξ½) : ident_distrib (Ξ» x, (f x : ℝβ‰₯0∞)) (Ξ» x, (g x : ℝβ‰₯0∞)) ΞΌ Ξ½ := h.comp measurable_coe_nnreal_ennreal @[to_additive] lemma mul_const [has_mul Ξ³] [has_measurable_mul Ξ³] (h : ident_distrib f g ΞΌ Ξ½) (c : Ξ³) : ident_distrib (Ξ» x, f x * c) (Ξ» x, g x * c) ΞΌ Ξ½ := h.comp (measurable_mul_const c) @[to_additive] lemma const_mul [has_mul Ξ³] [has_measurable_mul Ξ³] (h : ident_distrib f g ΞΌ Ξ½) (c : Ξ³) : ident_distrib (Ξ» x, c * f x) (Ξ» x, c * g x) ΞΌ Ξ½ := h.comp (measurable_const_mul c) @[to_additive] lemma div_const [has_div Ξ³] [has_measurable_div Ξ³] (h : ident_distrib f g ΞΌ Ξ½) (c : Ξ³) : ident_distrib (Ξ» x, f x / c) (Ξ» x, g x / c) ΞΌ Ξ½ := h.comp (has_measurable_div.measurable_div_const c) @[to_additive] lemma const_div [has_div Ξ³] [has_measurable_div Ξ³] (h : ident_distrib f g ΞΌ Ξ½) (c : Ξ³) : ident_distrib (Ξ» x, c / f x) (Ξ» x, c / g x) ΞΌ Ξ½ := h.comp (has_measurable_div.measurable_const_div c) lemma variance_eq {f : Ξ± β†’ ℝ} {g : Ξ² β†’ ℝ} (h : ident_distrib f g ΞΌ Ξ½) : variance f ΞΌ = variance g Ξ½ := begin convert (h.sub_const (∫ x, f x βˆ‚ΞΌ)).sq.integral_eq, rw h.integral_eq, refl end end ident_distrib end probability_theory
5dac3a3501c26ac434a7c2304ee32749688489ef
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/complex/isometry.lean
a6cf5209ba1b822bd3e8d01717fb694fcd2de3a3
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
6,704
lean
/- Copyright (c) 2021 FranΓ§ois Sunatori. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: FranΓ§ois Sunatori -/ import analysis.complex.circle import linear_algebra.determinant import linear_algebra.general_linear_group /-! # Isometries of the Complex Plane The lemma `linear_isometry_complex` states the classification of isometries in the complex plane. Specifically, isometries with rotations but without translation. The proof involves: 1. creating a linear isometry `g` with two fixed points, `g(0) = 0`, `g(1) = 1` 2. applying `linear_isometry_complex_aux` to `g` The proof of `linear_isometry_complex_aux` is separated in the following parts: 1. show that the real parts match up: `linear_isometry.re_apply_eq_re` 2. show that I maps to either I or -I 3. every z is a linear combination of a + b * I ## References * [Isometries of the Complex Plane](http://helmut.knaust.info/mediawiki/images/b/b5/Iso.pdf) -/ noncomputable theory open complex open_locale complex_conjugate local notation `|` x `|` := complex.abs x /-- An element of the unit circle defines a `linear_isometry_equiv` from `β„‚` to itself, by rotation. -/ def rotation : circle β†’* (β„‚ ≃ₗᡒ[ℝ] β„‚) := { to_fun := Ξ» a, { norm_map' := Ξ» x, show |a * x| = |x|, by rw [complex.abs_mul, abs_coe_circle, one_mul], ..distrib_mul_action.to_linear_equiv ℝ β„‚ a }, map_one' := linear_isometry_equiv.ext $ one_smul _, map_mul' := Ξ» _ _, linear_isometry_equiv.ext $ mul_smul _ _ } @[simp] lemma rotation_apply (a : circle) (z : β„‚) : rotation a z = a * z := rfl @[simp] lemma rotation_symm (a : circle) : (rotation a).symm = rotation a⁻¹ := linear_isometry_equiv.ext $ Ξ» x, rfl @[simp] lemma rotation_trans (a b : circle) : (rotation a).trans (rotation b) = rotation (b * a) := by { ext1, simp } lemma rotation_ne_conj_lie (a : circle) : rotation a β‰  conj_lie := begin intro h, have h1 : rotation a 1 = conj 1 := linear_isometry_equiv.congr_fun h 1, have hI : rotation a I = conj I := linear_isometry_equiv.congr_fun h I, rw [rotation_apply, ring_hom.map_one, mul_one] at h1, rw [rotation_apply, conj_I, ← neg_one_mul, mul_left_inj' I_ne_zero, h1, eq_neg_self_iff] at hI, exact one_ne_zero hI, end /-- Takes an element of `β„‚ ≃ₗᡒ[ℝ] β„‚` and checks if it is a rotation, returns an element of the unit circle. -/ @[simps] def rotation_of (e : β„‚ ≃ₗᡒ[ℝ] β„‚) : circle := ⟨(e 1) / complex.abs (e 1), by simp⟩ @[simp] lemma rotation_of_rotation (a : circle) : rotation_of (rotation a) = a := subtype.ext $ by simp lemma rotation_injective : function.injective rotation := function.left_inverse.injective rotation_of_rotation lemma linear_isometry.re_apply_eq_re_of_add_conj_eq (f : β„‚ β†’β‚—α΅’[ℝ] β„‚) (h₃ : βˆ€ z, z + conj z = f z + conj (f z)) (z : β„‚) : (f z).re = z.re := by simpa [ext_iff, add_re, add_im, conj_re, conj_im, ←two_mul, (show (2 : ℝ) β‰  0, by simp [two_ne_zero'])] using (h₃ z).symm lemma linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re {f : β„‚ β†’β‚—α΅’[ℝ] β„‚} (hβ‚‚ : βˆ€ z, (f z).re = z.re) (z : β„‚) : (f z).im = z.im ∨ (f z).im = -z.im := begin have h₁ := f.norm_map z, simp only [complex.abs, norm_eq_abs] at h₁, rwa [real.sqrt_inj (norm_sq_nonneg _) (norm_sq_nonneg _), norm_sq_apply (f z), norm_sq_apply z, hβ‚‚, add_left_cancel_iff, mul_self_eq_mul_self_iff] at h₁, end lemma linear_isometry.im_apply_eq_im {f : β„‚ β†’β‚—α΅’[ℝ] β„‚} (h : f 1 = 1) (z : β„‚) : z + conj z = f z + conj (f z) := begin have : βˆ₯f z - 1βˆ₯ = βˆ₯z - 1βˆ₯ := by rw [← f.norm_map (z - 1), f.map_sub, h], apply_fun Ξ» x, x ^ 2 at this, simp only [norm_eq_abs, ←norm_sq_eq_abs] at this, rw [←of_real_inj, ←mul_conj, ←mul_conj] at this, rw [ring_hom.map_sub, ring_hom.map_sub] at this, simp only [sub_mul, mul_sub, one_mul, mul_one] at this, rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs, linear_isometry.norm_map] at this, rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs] at this, simp only [sub_sub, sub_right_inj, mul_one, of_real_pow, ring_hom.map_one, norm_eq_abs] at this, simp only [add_sub, sub_left_inj] at this, rw [add_comm, ←this, add_comm], end lemma linear_isometry.re_apply_eq_re {f : β„‚ β†’β‚—α΅’[ℝ] β„‚} (h : f 1 = 1) (z : β„‚) : (f z).re = z.re := begin apply linear_isometry.re_apply_eq_re_of_add_conj_eq, intro z, apply linear_isometry.im_apply_eq_im h, end lemma linear_isometry_complex_aux {f : β„‚ ≃ₗᡒ[ℝ] β„‚} (h : f 1 = 1) : f = linear_isometry_equiv.refl ℝ β„‚ ∨ f = conj_lie := begin have h0 : f I = I ∨ f I = -I, { have : |f I| = 1 := by simpa using f.norm_map complex.I, simp only [ext_iff, ←and_or_distrib_left, neg_re, I_re, neg_im, neg_zero], split, { rw ←I_re, exact @linear_isometry.re_apply_eq_re f.to_linear_isometry h I, }, { apply @linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re f.to_linear_isometry, intro z, rw @linear_isometry.re_apply_eq_re f.to_linear_isometry h } }, refine h0.imp (Ξ» h' : f I = I, _) (Ξ» h' : f I = -I, _); { apply linear_isometry_equiv.to_linear_equiv_injective, apply complex.basis_one_I.ext', intros i, fin_cases i; simp [h, h'] } end lemma linear_isometry_complex (f : β„‚ ≃ₗᡒ[ℝ] β„‚) : βˆƒ a : circle, f = rotation a ∨ f = conj_lie.trans (rotation a) := begin let a : circle := ⟨f 1, by simpa using f.norm_map 1⟩, use a, have : (f.trans (rotation a).symm) 1 = 1, { simpa using rotation_apply a⁻¹ (f 1) }, refine (linear_isometry_complex_aux this).imp (Ξ» h₁, _) (Ξ» hβ‚‚, _), { simpa using eq_mul_of_inv_mul_eq h₁ }, { exact eq_mul_of_inv_mul_eq hβ‚‚ } end /-- The matrix representation of `rotation a` is equal to the conformal matrix `![![re a, -im a], ![im a, re a]]`. -/ lemma to_matrix_rotation (a : circle) : linear_map.to_matrix basis_one_I basis_one_I (rotation a).to_linear_equiv = matrix.plane_conformal_matrix (re a) (im a) (by simp [pow_two, ←norm_sq_apply]) := begin ext i j, simp [linear_map.to_matrix_apply], fin_cases i; fin_cases j; simp end /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (a : circle) : ((rotation a).to_linear_equiv : β„‚ β†’β‚—[ℝ] β„‚).det = 1 := begin rw [←linear_map.det_to_matrix basis_one_I, to_matrix_rotation, matrix.det_fin_two], simp [←norm_sq_apply] end /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (a : circle) : (rotation a).to_linear_equiv.det = 1 := by rw [←units.eq_iff, linear_equiv.coe_det, det_rotation, units.coe_one]
9c686af72b56d7b41559f5da1fda3e76ac6404a8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/limits.lean
5a3d894b2752b35c664f1029a4f2f1a2b1a8d21f
[]
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
89,876
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) mk' :: where (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) mk' :: where (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)
17a49c99f9e4f8b6a670e267c006683140f91e1c
471bedbd023d35c9d078c2f936dd577ace7f5813
/library/init/data/string/basic.lean
264f2a258aebf9955884f6d2a88fab3e64195db2
[ "Apache-2.0" ]
permissive
lambdaxymox/lean
e06f0fa503666df827edd9867d7f49ca017aae64
fc13c8c72a15dab71a2c2b31410c2cadc3526bd7
refs/heads/master
1,666,785,407,985
1,666,153,673,000
1,666,153,673,000
310,165,986
0
0
Apache-2.0
1,604,542,096,000
1,604,542,095,000
null
UTF-8
Lean
false
false
8,666
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.basic import init.data.char.basic /- In the VM, strings are implemented using a dynamic array and UTF-8 encoding. TODO: we currently cannot mark string_imp as private because we need to bind string_imp.mk and string_imp.cases_on in the VM. -/ structure string_imp := (data : list char) def string := string_imp def list.as_string (s : list char) : string := ⟨s⟩ namespace string instance : has_lt string := ⟨λ s₁ sβ‚‚, s₁.data < sβ‚‚.data⟩ /- Remark: this function has a VM builtin efficient implementation. -/ instance has_decidable_lt (s₁ sβ‚‚ : string) : decidable (s₁ < sβ‚‚) := list.has_decidable_lt s₁.data sβ‚‚.data instance has_decidable_eq : decidable_eq string := Ξ» ⟨x⟩ ⟨y⟩, match list.has_dec_eq x y with | is_true p := is_true (congr_arg string_imp.mk p) | is_false p := is_false (Ξ» q, p (string_imp.mk.inj q)) end def empty : string := ⟨[]⟩ def length : string β†’ nat | ⟨s⟩ := s.length /- The internal implementation uses dynamic arrays and will perform destructive updates if the string is not shared. -/ def push : string β†’ char β†’ string | ⟨s⟩ c := ⟨s ++ [c]⟩ /- The internal implementation uses dynamic arrays and will perform destructive updates if the string is not shared. -/ def append : string β†’ string β†’ string | ⟨a⟩ ⟨b⟩ := ⟨a ++ b⟩ /- O(n) in the VM, where n is the length of the string -/ def to_list : string β†’ list char | ⟨s⟩ := s def fold {Ξ±} (a : Ξ±) (f : Ξ± β†’ char β†’ Ξ±) (s : string) : Ξ± := s.to_list.foldl f a /- In the VM, the string iterator is implemented as a pointer to the string being iterated + index. TODO: we currently cannot mark interator_imp as private because we need to bind string_imp.mk and string_imp.cases_on in the VM. -/ structure iterator_imp := (fst : list char) (snd : list char) def iterator := iterator_imp def mk_iterator : string β†’ iterator | ⟨s⟩ := ⟨[], s⟩ namespace iterator def curr : iterator β†’ char | ⟨p, c::n⟩ := c | _ := default /- In the VM, `set_curr` is constant time if the string being iterated is not shared and linear time if it is. -/ def set_curr : iterator β†’ char β†’ iterator | ⟨p, c::n⟩ c' := ⟨p, c'::n⟩ | it c' := it def next : iterator β†’ iterator | ⟨p, c::n⟩ := ⟨c::p, n⟩ | ⟨p, []⟩ := ⟨p, []⟩ def prev : iterator β†’ iterator | ⟨c::p, n⟩ := ⟨p, c::n⟩ | ⟨[], n⟩ := ⟨[], n⟩ def has_next : iterator β†’ bool | ⟨p, []⟩ := ff | _ := tt def has_prev : iterator β†’ bool | ⟨[], n⟩ := ff | _ := tt def insert : iterator β†’ string β†’ iterator | ⟨p, n⟩ ⟨s⟩ := ⟨p, s++n⟩ def remove : iterator β†’ nat β†’ iterator | ⟨p, n⟩ m := ⟨p, n.drop m⟩ /- In the VM, `to_string` is a constant time operation. -/ def to_string : iterator β†’ string | ⟨p, n⟩ := ⟨p.reverse ++ n⟩ def to_end : iterator β†’ iterator | ⟨p, n⟩ := ⟨n.reverse ++ p, []⟩ def next_to_string : iterator β†’ string | ⟨p, n⟩ := ⟨n⟩ def prev_to_string : iterator β†’ string | ⟨p, n⟩ := ⟨p.reverse⟩ protected def extract_core : list char β†’ list char β†’ option (list char) | [] cs := none | (c::cs₁) csβ‚‚ := if cs₁ = csβ‚‚ then some [c] else match extract_core cs₁ csβ‚‚ with | none := none | some r := some (c::r) end def extract : iterator β†’ iterator β†’ option string | ⟨p₁, nβ‚βŸ© ⟨pβ‚‚, nβ‚‚βŸ© := if p₁.reverse ++ n₁ β‰  pβ‚‚.reverse ++ nβ‚‚ then none else if n₁ = nβ‚‚ then some "" else match iterator.extract_core n₁ nβ‚‚ with | none := none | some r := some ⟨r⟩ end end iterator end string /- The following definitions do not have builtin support in the VM -/ instance : inhabited string := ⟨string.empty⟩ instance : has_sizeof string := ⟨string.length⟩ instance : has_append string := ⟨string.append⟩ namespace string def str : string β†’ char β†’ string := push def is_empty (s : string) : bool := to_bool (s.length = 0) def front (s : string) : char := s.mk_iterator.curr def back (s : string) : char := s.mk_iterator.to_end.prev.curr def join (l : list string) : string := l.foldl (Ξ» r s, r ++ s) "" def singleton (c : char) : string := empty.push c def intercalate (s : string) (ss : list string) : string := (list.intercalate s.to_list (ss.map to_list)).as_string namespace iterator def nextn : iterator β†’ nat β†’ iterator | it 0 := it | it (i+1) := nextn it.next i def prevn : iterator β†’ nat β†’ iterator | it 0 := it | it (i+1) := prevn it.prev i end iterator def pop_back (s : string) : string := s.mk_iterator.to_end.prev.prev_to_string def popn_back (s : string) (n : nat) : string := (s.mk_iterator.to_end.prevn n).prev_to_string def backn (s : string) (n : nat) : string := (s.mk_iterator.to_end.prevn n).next_to_string end string protected def char.to_string (c : char) : string := string.singleton c private def to_nat_core : string.iterator β†’ nat β†’ nat β†’ nat | it 0 r := r | it (i+1) r := let c := it.curr in let r := r*10 + c.to_nat - '0'.to_nat in to_nat_core it.next i r def string.to_nat (s : string) : nat := to_nat_core s.mk_iterator s.length 0 namespace string private lemma nil_ne_append_singleton : βˆ€ (c : char) (l : list char), [] β‰  l ++ [c] | c [] := Ξ» h, list.no_confusion h | c (d::l) := Ξ» h, list.no_confusion h lemma empty_ne_str : βˆ€ (c : char) (s : string), empty β‰  str s c | c ⟨l⟩ := Ξ» h : string_imp.mk [] = string_imp.mk (l ++ [c]), string_imp.no_confusion h $ Ξ» h, nil_ne_append_singleton _ _ h lemma str_ne_empty (c : char) (s : string) : str s c β‰  empty := (empty_ne_str c s).symm private lemma str_ne_str_left_aux : βˆ€ {c₁ cβ‚‚ : char} (l₁ lβ‚‚ : list char), c₁ β‰  cβ‚‚ β†’ l₁ ++ [c₁] β‰  lβ‚‚ ++ [cβ‚‚] | c₁ cβ‚‚ [] [] h₁ hβ‚‚ := list.no_confusion hβ‚‚ (Ξ» h _, absurd h h₁) | c₁ cβ‚‚ (d₁::l₁) [] h₁ hβ‚‚ := have d₁ :: (l₁ ++ [c₁]) = [cβ‚‚], from hβ‚‚, have l₁ ++ [c₁] = [], from list.no_confusion this (Ξ» _ h, h), absurd this.symm (nil_ne_append_singleton _ _) | c₁ cβ‚‚ [] (dβ‚‚::lβ‚‚) h₁ hβ‚‚ := have [c₁] = dβ‚‚ :: (lβ‚‚ ++ [cβ‚‚]), from hβ‚‚, have [] = lβ‚‚ ++ [cβ‚‚], from list.no_confusion this (Ξ» _ h, h), absurd this (nil_ne_append_singleton _ _) | c₁ cβ‚‚ (d₁::l₁) (dβ‚‚::lβ‚‚) h₁ hβ‚‚ := have d₁ :: (l₁ ++ [c₁]) = dβ‚‚ :: (lβ‚‚ ++ [cβ‚‚]), from hβ‚‚, have l₁ ++ [c₁] = lβ‚‚ ++ [cβ‚‚], from list.no_confusion this (Ξ» _ h, h), absurd this (str_ne_str_left_aux l₁ lβ‚‚ h₁) lemma str_ne_str_left : βˆ€ {c₁ cβ‚‚ : char} (s₁ sβ‚‚ : string), c₁ β‰  cβ‚‚ β†’ str s₁ c₁ β‰  str sβ‚‚ cβ‚‚ | c₁ cβ‚‚ (string_imp.mk l₁) (string_imp.mk lβ‚‚) h₁ hβ‚‚ := have l₁ ++ [c₁] = lβ‚‚ ++ [cβ‚‚], from string_imp.no_confusion hβ‚‚ id, absurd this (str_ne_str_left_aux l₁ lβ‚‚ h₁) private lemma str_ne_str_right_aux : βˆ€ (c₁ cβ‚‚ : char) {l₁ lβ‚‚ : list char}, l₁ β‰  lβ‚‚ β†’ l₁ ++ [c₁] β‰  lβ‚‚ ++ [cβ‚‚] | c₁ cβ‚‚ [] [] h₁ hβ‚‚ := absurd rfl h₁ | c₁ cβ‚‚ (d₁::l₁) [] h₁ hβ‚‚ := have d₁ :: (l₁ ++ [c₁]) = [cβ‚‚], from hβ‚‚, have l₁ ++ [c₁] = [], from list.no_confusion this (Ξ» _ h, h), absurd this.symm (nil_ne_append_singleton _ _) | c₁ cβ‚‚ [] (dβ‚‚::lβ‚‚) h₁ hβ‚‚ := have [c₁] = dβ‚‚ :: (lβ‚‚ ++ [cβ‚‚]), from hβ‚‚, have [] = lβ‚‚ ++ [cβ‚‚], from list.no_confusion this (Ξ» _ h, h), absurd this (nil_ne_append_singleton _ _) | c₁ cβ‚‚ (d₁::l₁) (dβ‚‚::lβ‚‚) h₁ hβ‚‚ := have aux₁ : d₁ :: (l₁ ++ [c₁]) = dβ‚‚ :: (lβ‚‚ ++ [cβ‚‚]), from hβ‚‚, have d₁ = dβ‚‚, from list.no_confusion aux₁ (Ξ» h _, h), have auxβ‚‚ : l₁ β‰  lβ‚‚, from Ξ» h, have d₁ :: l₁ = dβ‚‚ :: lβ‚‚, from eq.subst h (eq.subst this rfl), absurd this h₁, have l₁ ++ [c₁] = lβ‚‚ ++ [cβ‚‚], from list.no_confusion aux₁ (Ξ» _ h, h), absurd this (str_ne_str_right_aux c₁ cβ‚‚ auxβ‚‚) lemma str_ne_str_right : βˆ€ (c₁ cβ‚‚ : char) {s₁ sβ‚‚ : string}, s₁ β‰  sβ‚‚ β†’ str s₁ c₁ β‰  str sβ‚‚ cβ‚‚ | c₁ cβ‚‚ (string_imp.mk l₁) (string_imp.mk lβ‚‚) h₁ hβ‚‚ := have aux : l₁ β‰  lβ‚‚, from Ξ» h, have string_imp.mk l₁ = string_imp.mk lβ‚‚, from eq.subst h rfl, absurd this h₁, have l₁ ++ [c₁] = lβ‚‚ ++ [cβ‚‚], from string_imp.no_confusion hβ‚‚ id, absurd this (str_ne_str_right_aux c₁ cβ‚‚ aux) end string
431c502f97d25b491c713dfb83ccf9b8af54b50d
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Meta/SynthInstance.lean
80d0262fdc9de078acddbe3558894c98ce18239f
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,756
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Leonardo de Moura Type class instance synthesizer using tabled resolution. -/ prelude import Init.Lean.Meta.Basic import Init.Lean.Meta.Instances import Init.Lean.Meta.LevelDefEq import Init.Lean.Meta.AbstractMVars import Init.Lean.Meta.WHNF namespace Lean namespace Meta namespace SynthInstance def mkInferTCGoalsLRAttr : IO TagAttribute := registerTagAttribute `inferTCGoalsLR "instruct type class resolution procedure to solve goals from left to right for this instance" @[init mkInferTCGoalsLRAttr] constant inferTCGoalsLRAttr : TagAttribute := arbitrary _ def hasInferTCGoalsLRAttribute (env : Environment) (constName : Name) : Bool := inferTCGoalsLRAttr.hasTag env constName structure GeneratorNode := (mvar : Expr) (key : Expr) (mctx : MetavarContext) (instances : Array Expr) (currInstanceIdx : Nat) instance GeneratorNode.inhabited : Inhabited GeneratorNode := ⟨⟨arbitrary _, arbitrary _, arbitrary _, arbitrary _, 0⟩⟩ structure ConsumerNode := (mvar : Expr) (key : Expr) (mctx : MetavarContext) (subgoals : List Expr) instance Consumernode.inhabited : Inhabited ConsumerNode := ⟨⟨arbitrary _, arbitrary _, arbitrary _, []⟩⟩ inductive Waiter | consumerNode : ConsumerNode β†’ Waiter | root : Waiter def Waiter.isRoot : Waiter β†’ Bool | Waiter.consumerNode _ => false | Waiter.root => true /- In tabled resolution, we creating a mapping from goals (e.g., `HasCoe Nat ?x`) to answers and waiters. Waiters are consumer nodes that are waiting for answers for a particular node. We implement this mapping using a `HashMap` where the keys are normalized expressions. That is, we replace assignable metavariables with auxiliary free variables of the form `_tc.<idx>`. We do not declare these free variables in any local context, and we should view them as "normalized names" for metavariables. For example, the term `f ?m ?m ?n` is normalized as `f _tc.0 _tc.0 _tc.1`. This approach is structural, and we may visit the same goal more than once if the different occurrences are just definitionally equal, but not structurally equal. Remark: a metavariable is assignable only if its depth is equal to the metavar context depth. -/ namespace MkTableKey structure State := (nextIdx : Nat := 0) (lmap : HashMap MVarId Level := {}) (emap : HashMap MVarId Expr := {}) abbrev M := ReaderT MetavarContext (StateM State) partial def normLevel : Level β†’ M Level | u => if !u.hasMVar then pure u else match u with | Level.succ v _ => do v ← normLevel v; pure $ u.updateSucc! v | Level.max v w _ => do v ← normLevel v; w ← normLevel w; pure $ u.updateMax! v w | Level.imax v w _ => do v ← normLevel v; w ← normLevel w; pure $ u.updateIMax! v w | Level.mvar mvarId _ => do mctx ← read; if !mctx.isLevelAssignable mvarId then pure u else do s ← get; match s.lmap.find? mvarId with | some u' => pure u' | none => do let u' := mkLevelParam $ mkNameNum `_tc s.nextIdx; modify $ fun s => { s with nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u' }; pure u' | u => pure u partial def normExpr : Expr β†’ M Expr | e => if !e.hasMVar then pure e else match e with | Expr.const _ us _ => do us ← us.mapM normLevel; pure $ e.updateConst! us | Expr.sort u _ => do u ← normLevel u; pure $ e.updateSort! u | Expr.app f a _ => do f ← normExpr f; a ← normExpr a; pure $ e.updateApp! f a | Expr.letE _ t v b _ => do t ← normExpr t; v ← normExpr v; b ← normExpr b; pure $ e.updateLet! t v b | Expr.forallE _ d b _ => do d ← normExpr d; b ← normExpr b; pure $ e.updateForallE! d b | Expr.lam _ d b _ => do d ← normExpr d; b ← normExpr b; pure $ e.updateLambdaE! d b | Expr.mdata _ b _ => do b ← normExpr b; pure $ e.updateMData! b | Expr.proj _ _ b _ => do b ← normExpr b; pure $ e.updateProj! b | Expr.mvar mvarId _ => do mctx ← read; if !mctx.isExprAssignable mvarId then pure e else do s ← get; match s.emap.find? mvarId with | some e' => pure e' | none => do let e' := mkFVar $ mkNameNum `_tc s.nextIdx; modify $ fun s => { s with nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e' }; pure e' | _ => pure e end MkTableKey /- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/ def mkTableKey (mctx : MetavarContext) (e : Expr) : Expr := (MkTableKey.normExpr e mctx).run' {} structure Answer := (result : AbstractMVarsResult) (resultType : Expr) instance Answer.inhabited : Inhabited Answer := ⟨⟨arbitrary _, arbitrary _⟩⟩ structure TableEntry := (waiters : Array Waiter) (answers : Array Answer := #[]) /- Remark: the SynthInstance.State is not really an extension of `Meta.State`. The field `postponed` is not needed, and the field `mctx` is misleading since `synthInstance` methods operate over different `MetavarContext`s simultaneously. That being said, we still use `extends` because it makes it simpler to move from `M` to `MetaM`. -/ structure State extends Meta.State := (result : Option Expr := none) (generatorStack : Array GeneratorNode := #[]) (resumeStack : Array (ConsumerNode Γ— Answer) := #[]) (tableEntries : HashMap Expr TableEntry := {}) abbrev SynthM := ReaderT Context (EStateM Exception State) instance SynthM.inhabited {Ξ±} : Inhabited (SynthM Ξ±) := ⟨throw $ Exception.other ""⟩ def getTraceState : SynthM TraceState := do s ← get; pure s.traceState def getOptions : SynthM Options := do ctx ← read; pure ctx.config.opts def addContext (msg : MessageData) : SynthM MessageData := do ctx ← read; s ← get; pure $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } msg instance tracer : SimpleMonadTracerAdapter SynthM := { getOptions := getOptions, getTraceState := getTraceState, addContext := addContext, modifyTraceState := fun f => modify $ fun s => { s with traceState := f s.traceState } } @[inline] def liftMeta {Ξ±} (x : MetaM Ξ±) : SynthM Ξ± := adaptState (fun (s : State) => (s.toState, s)) (fun s' s => { s with toState := s' }) x instance meta2Synth {Ξ±} : HasCoe (MetaM Ξ±) (SynthM Ξ±) := ⟨liftMeta⟩ @[inline] def withMCtx {Ξ±} (mctx : MetavarContext) (x : SynthM Ξ±) : SynthM Ξ± := do mctx' ← getMCtx; modify $ fun s => { s with mctx := mctx }; finally x (modify $ fun s => { s with mctx := mctx' }) /-- Return globals and locals instances that may unify with `type` -/ def getInstances (type : Expr) : MetaM (Array Expr) := forallTelescopeReducing type $ fun _ type => do className? ← isClass type; match className? with | none => throwEx $ Exception.notInstance type | some className => do globalInstances ← getGlobalInstances; result ← globalInstances.getUnify type; result ← result.mapM $ fun c => match c with | Expr.const constName us _ => do us ← us.mapM (fun _ => mkFreshLevelMVar); pure $ c.updateConst! us | _ => panic! "global instance is not a constant"; trace! `Meta.synthInstance.globalInstances (type ++ " " ++ result); localInstances ← getLocalInstances; let result := localInstances.foldl (fun (result : Array Expr) linst => if linst.className == className then result.push linst.fvar else result) result; pure result /-- Create a new generator node for `mvar` and add `waiter` as its waiter. `key` must be `mkTableKey mctx mvarType`. -/ def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit := withMCtx mctx $ do trace! `Meta.synthInstance.newSubgoal key; mvarType ← inferType mvar; mvarType ← instantiateMVars mvarType; instances ← getInstances mvarType; mctx ← getMCtx; if instances.isEmpty then pure () else do let node : GeneratorNode := { mvar := mvar, key := key, mctx := mctx, instances := instances, currInstanceIdx := instances.size }; let entry : TableEntry := { waiters := #[waiter] }; modify $ fun s => { s with generatorStack := s.generatorStack.push node, tableEntries := s.tableEntries.insert key entry } def findEntry? (key : Expr) : SynthM (Option TableEntry) := do s ← get; pure $ s.tableEntries.find? key def getEntry (key : Expr) : SynthM TableEntry := do entry? ← findEntry? key; match entry? with | none => panic! "invalid key at synthInstance" | some entry => pure entry /-- Create a `key` for the goal associated with the given metavariable. That is, we create a key for the type of the metavariable. We must instantiate assigned metavariables before we invoke `mkTableKey`. -/ def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr := withMCtx mctx $ do mvarType ← inferType mvar; mvarType ← instantiateMVars mvarType; pure $ mkTableKey mctx mvarType /- See `getSubgoals` and `getSubgoalsAux` We use the parameter `j` to reduce the number of `instantiate*` invocations. It is the same approach we use at `forallTelescope` and `lambdaTelescope`. Given `getSubgoalsAux args j subgoals instVal type`, we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/ structure SubgoalsResult : Type := (subgoals : List Expr) (instVal : Expr) (instTypeBody : Expr) private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) : Array Expr β†’ Nat β†’ List Expr β†’ Expr β†’ Expr β†’ MetaM SubgoalsResult | args, j, subgoals, instVal, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args; mvarType ← mkForall xs d; mvar ← mkFreshExprMVarAt lctx localInsts mvarType; let arg := mkAppN mvar xs; let instVal := mkApp instVal arg; let subgoals := if c.binderInfo.isInstImplicit then mvar::subgoals else subgoals; let args := args.push (mkAppN mvar xs); getSubgoalsAux args j subgoals instVal b | args, j, subgoals, instVal, type => do let type := type.instantiateRevRange j args.size args; type ← whnf type; if type.isForall then getSubgoalsAux args args.size subgoals instVal type else pure ⟨subgoals, instVal, type⟩ /-- `getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`. The subgoals are in the context of the free variables `xs`, and `(lctx, localInsts)` is the local context and instances before we added the free variables to it. This extra complication is required because 1- We want all metavariables created by `synthInstance` to share the same local context. 2- We want to ensure that applications such as `mvar xs` are higher order patterns. The method `getGoals` create a new metavariable for each parameter of `inst`. For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`. Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these metavariables that are instance implicit arguments, and the expressions: - `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`) - `B (?m_1 xs) ... (?m_n xs)` -/ def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do instType ← inferType inst; result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType; match inst.getAppFn with | Expr.const constName _ _ => do env ← getEnv; if hasInferTCGoalsLRAttribute env constName then pure { result with subgoals := result.subgoals.reverse } else pure result | _ => pure result def tryResolveCore (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext Γ— List Expr)) := do mvarType ← inferType mvar; lctx ← getLCtx; localInsts ← getLocalInstances; forallTelescopeReducing mvarType $ fun xs mvarTypeBody => do ⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst; trace! `Meta.synthInstance.tryResolve (mvarTypeBody ++ " =?= " ++ instTypeBody); condM (isDefEq mvarTypeBody instTypeBody) (do instVal ← mkLambda xs instVal; condM (isDefEq mvar instVal) (do trace! `Meta.synthInstance.tryResolve "success"; mctx ← getMCtx; pure (some (mctx, subgoals))) (do trace! `Meta.synthInstance.tryResolve "failure assigning"; pure none)) (do trace! `Meta.synthInstance.tryResolve "failure"; pure none) /-- Try to synthesize metavariable `mvar` using the instance `inst`. Remark: `mctx` contains `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. A subgoal is created for each instance implicit parameter of `inst`. -/ def tryResolve (mctx : MetavarContext) (mvar : Expr) (inst : Expr) : SynthM (Option (MetavarContext Γ— List Expr)) := traceCtx `Meta.synthInstance.tryResolve $ withMCtx mctx $ tryResolveCore mvar inst /-- Assign a precomputed answer to `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/ def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) := withMCtx mctx $ do (_, _, val) ← openAbstractMVarsResult answer.result; condM (isDefEq mvar val) (do mctx ← getMCtx; pure $ some mctx) (pure none) /-- Move waiters that are waiting for the given answer to the resume stack. -/ def wakeUp (answer : Answer) : Waiter β†’ SynthM Unit | Waiter.root => if answer.result.paramNames.isEmpty && answer.result.numMVars == 0 then do modify $ fun s => { s with result := answer.result.expr } else do (_, _, answerExpr) ← openAbstractMVarsResult answer.result; trace! `Meta.synthInstance ("skip answer containing metavariables " ++ answerExpr); pure () | Waiter.consumerNode cNode => modify $ fun s => { s with resumeStack := s.resumeStack.push (cNode, answer) } def isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool := oldAnswers.all $ fun oldAnswer => do -- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer` -- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq) oldAnswer.resultType != answer.resultType /-- Create a new answer after `cNode` resolved all subgoals. That is, `cNode.subgoals == []`. And then, store it in the tabled entries map, and wakeup waiters. -/ def addAnswer (cNode : ConsumerNode) : SynthM Unit := do answer ← withMCtx cNode.mctx $ do { traceM `Meta.synthInstance.newAnswer $ do { mvarType ← inferType cNode.mvar; pure mvarType }; val ← instantiateMVars cNode.mvar; result ← abstractMVars val; -- assignable metavariables become parameters resultType ← inferType result.expr; pure { result := result, resultType := resultType : Answer } }; -- Remark: `answer` does not contain assignable or assigned metavariables. let key := cNode.key; entry ← getEntry key; when (isNewAnswer entry.answers answer) $ do let newEntry := { entry with answers := entry.answers.push answer }; modify $ fun s => { s with tableEntries := s.tableEntries.insert key newEntry }; entry.waiters.forM (wakeUp answer) /-- Process the next subgoal in the given consumer node. -/ def consume (cNode : ConsumerNode) : SynthM Unit := match cNode.subgoals with | [] => addAnswer cNode | mvar::_ => do let waiter := Waiter.consumerNode cNode; key ← mkTableKeyFor cNode.mctx mvar; entry? ← findEntry? key; match entry? with | none => newSubgoal cNode.mctx key mvar waiter | some entry => modify $ fun s => { s with resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack, tableEntries := s.tableEntries.insert key { entry with waiters := entry.waiters.push waiter } } def getTop : SynthM GeneratorNode := do s ← get; pure s.generatorStack.back @[inline] def modifyTop (f : GeneratorNode β†’ GeneratorNode) : SynthM Unit := modify $ fun s => { s with generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f } /-- Try the next instance in the node on the top of the generator stack. -/ def generate : SynthM Unit := do gNode ← getTop; if gNode.currInstanceIdx == 0 then modify $ fun s => { s with generatorStack := s.generatorStack.pop } else do let key := gNode.key; let idx := gNode.currInstanceIdx - 1; let inst := gNode.instances.get! idx; let mctx := gNode.mctx; let mvar := gNode.mvar; trace! `Meta.synthInstance.generate ("instance " ++ inst); modifyTop $ fun gNode => { gNode with currInstanceIdx := idx }; result? ← tryResolve mctx mvar inst; match result? with | none => pure () | some (mctx, subgoals) => consume { key := key, mvar := mvar, subgoals := subgoals, mctx := mctx } def getNextToResume : SynthM (ConsumerNode Γ— Answer) := do s ← get; let r := s.resumeStack.back; modify $ fun s => { s with resumeStack := s.resumeStack.pop }; pure r /-- Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the next subgoal. -/ def resume : SynthM Unit := do (cNode, answer) ← getNextToResume; match cNode.subgoals with | [] => panic! "resume found no remaining subgoals" | mvar::rest => do result? ← tryAnswer cNode.mctx mvar answer; match result? with | none => pure () | some mctx => do withMCtx mctx $ traceM `Meta.synthInstance.resume $ do { goal ← inferType cNode.mvar; subgoal ← inferType mvar; pure (goal ++ " <== " ++ subgoal) }; consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx := mctx } def step : SynthM Bool := do s ← get; if !s.resumeStack.isEmpty then do resume; pure true else if !s.generatorStack.isEmpty then do generate; pure true else pure false def getResult : SynthM (Option Expr) := do s ← get; pure s.result def synth : Nat β†’ SynthM (Option Expr) | 0 => do trace! `Meta.synthInstance "synthInstance is out of fuel"; pure none | fuel+1 => do trace! `Meta.synthInstance ("remaining fuel " ++ toString fuel); condM step (do result? ← getResult; match result? with | none => synth fuel | some result => pure result) (do trace! `Meta.synthInstance "failed"; pure none) def main (type : Expr) (fuel : Nat) : MetaM (Option Expr) := traceCtx `Meta.synthInstance $ do trace! `Meta.synthInstance ("main goal " ++ type); mvar ← mkFreshExprMVar type; mctx ← getMCtx; let key := mkTableKey mctx type; adaptState' (fun (s : Meta.State) => { toState := s : State }) (fun (s : State) => s.toState) $ do { newSubgoal mctx key mvar Waiter.root; synth fuel } end SynthInstance /- Type class parameters can be annotated with `outParam` annotations. Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF `a_i` is an `outParam`. The result is type correct because we reject type class declarations IF it contains a regular parameter X that depends on an `out` parameter Y. Then, we execute type class resolution as usual. If it succeeds, and metavariables ?m_i have been assigned, we try to unify the original type `C a_1 ... a_n` witht the normalized one. -/ private def preprocess (type : Expr) : MetaM Expr := forallTelescopeReducing type $ fun xs type => do type ← whnf type; mkForall xs type private def preprocessLevels (us : List Level) : MetaM (List Level) := do us ← us.foldlM (fun (r : List Level) (u : Level) => do u ← instantiateLevelMVars u; if u.hasMVar then do u' ← mkFreshLevelMVar; pure (u'::r) else pure (u::r)) []; pure $ us.reverse private partial def preprocessArgs : Expr β†’ Nat β†’ Array Expr β†’ MetaM (Array Expr) | type, i, args => if h : i < args.size then do type ← whnf type; match type with | Expr.forallE _ d b _ => do let arg := args.get ⟨i, h⟩; arg ← if isOutParam d then mkFreshExprMVar d else pure arg; let args := args.set ⟨i, h⟩ arg; preprocessArgs (b.instantiate1 arg) (i+1) args | _ => throw $ Exception.other "type class resolution failed, insufficient number of arguments" -- TODO improve error message else pure args private def preprocessOutParam (type : Expr) : MetaM Expr := forallTelescope type $ fun xs typeBody => match typeBody.getAppFn with | c@(Expr.const constName us _) => do env ← getEnv; if !hasOutParams env constName then pure type else do let args := typeBody.getAppArgs; us ← preprocessLevels us; let c := mkConst constName us; cType ← inferType c; args ← preprocessArgs cType 0 args; mkForall xs (mkAppN c args) | _ => pure type @[init] def maxStepsOption : IO Unit := registerOption `synthInstance.maxSteps { defValue := (10000 : Nat), group := "", descr := "maximum steps for the type class instance synthesis procedure" } private def getMaxSteps (opts : Options) : Nat := opts.getNat `synthInstance.maxSteps 10000 def synthInstance? (type : Expr) : MetaM (Option Expr) := do opts ← getOptions; let fuel := getMaxSteps opts; inputConfig ← getConfig; withConfig (fun config => { config with transparency := TransparencyMode.reducible, foApprox := true, ctxApprox := true }) $ do type ← instantiateMVars type; type ← preprocess type; s ← get; match s.cache.synthInstance.find? type with | some result => pure result | none => do result? ← withNewMCtxDepth $ do { normType ← preprocessOutParam type; trace! `Meta.synthInstance (type ++ " ==> " ++ normType); result? ← SynthInstance.main normType fuel; match result? with | none => pure none | some result => do trace! `Meta.synthInstance ("FOUND result " ++ result); result ← instantiateMVars result; condM (hasAssignableMVar result) (pure none) (pure (some result)) }; result? ← match result? with | none => pure none | some result => do { trace! `Meta.synthInstance ("result " ++ result); resultType ← inferType result; condM (withConfig (fun _ => inputConfig) $ isDefEq type resultType) (do result ← instantiateMVars result; pure (some result)) (pure none) }; if type.hasMVar then pure result? else do modify $ fun s => { s with cache := { s.cache with synthInstance := s.cache.synthInstance.insert type result? } }; pure result? /-- Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if instance cannot be synthesized right now because `type` contains metavariables. -/ def trySynthInstance (type : Expr) : MetaM (LOption Expr) := adaptReader (fun (ctx : Context) => { ctx with config := { ctx.config with isDefEqStuckEx := true } }) $ catch (toLOptionM $ synthInstance? type) (fun ex => match ex with | Exception.isExprDefEqStuck _ _ _ => pure LOption.undef | Exception.isLevelDefEqStuck _ _ _ => pure LOption.undef | _ => throw ex) def synthInstance (type : Expr) : MetaM Expr := do result? ← synthInstance? type; match result? with | some result => pure result | none => throwEx $ Exception.synthInstance type def synthPendingImp (mvarId : MVarId) : MetaM Bool := do mvarDecl ← getMVarDecl mvarId; match mvarDecl.kind with | MetavarKind.synthetic => do c? ← isClass mvarDecl.type; match c? with | none => pure false | some _ => do val? ← synthInstance? mvarDecl.type; match val? with | none => pure false | some val => condM (isExprMVarAssigned mvarId) (pure false) $ do assignExprMVar mvarId val; pure true | _ => pure false @[init] def setSynthPendingRef : IO Unit := synthPendingRef.set synthPendingImp @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta.synthInstance; registerTraceClass `Meta.synthInstance.globalInstances; registerTraceClass `Meta.synthInstance.newSubgoal; registerTraceClass `Meta.synthInstance.tryResolve; registerTraceClass `Meta.synthInstance.resume; registerTraceClass `Meta.synthInstance.generate end Meta end Lean
f7867c69e9d7f523ec23d0d6d438f5ef07835235
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/instructor/lectures/lecture_26.lean
c24d4d23639357e78d8e6cf59a5599832001ac2f
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
9,369
lean
import .lecture_25 import data.set /- Operations on relations -/ /- We now change our attention to binary relations more generally: not just from Ξ² β†’ Ξ² but between different types, Ξ± and Ξ². Not the change in the type of r as defined here. -/ variables {Ξ± Ξ² Ξ³ : Type} (r : Ξ± β†’ Ξ² β†’ Prop) local infix `β‰Ί`:50 := r /- We will call the set of all Ξ± values the "domain" of the relation r, and we will call the set of all Ξ² values the "codomain" of r. Now the (a, b) pairs of r represent the pairs of values for which r a b is true. You can visualized such an (a, b) pair as an arrow from a in the domain to b in the codomain. Not every value in Ξ± needs to be present in the set of "a" values that appear as first elements in the pairs of r. The subset of a values that do appear in the first position of some pair in r is what we will call the domain of definition of the relation. The set of b values that appear in the second positions in all such pairs of r is the set we will call the *range* of the r. Be able to write the formal definitions, which we present next, from your memory and even more from understanding of what they mean. If you understand, then you should be able to write the formal definitions without having memorized them. -/ /- We begin with sets involved in any relation, r : Ξ± β†’ Ξ² β†’ Prop. For simplicity we'll assume that the domain set in examples that follow is specified by the type Ξ±, and that the co-domain set is specificed by the Ξ² type. -/ def dom (r : Ξ± β†’ Ξ² β†’ Prop) : set Ξ± := { a : Ξ± | true } def codom (r : Ξ± β†’ Ξ² β†’ Prop) : set Ξ² := { b : Ξ² | true } def dom_of_def (r : Ξ± β†’ Ξ² β†’ Prop) : set Ξ± := { a : Ξ± | βˆƒ b, r a b } def range (r : Ξ± β†’ Ξ² β†’ Prop) : set Ξ² := { b : Ξ² | βˆƒ (a : Ξ±), r a b } -- EXAMPLE /- Let R by the relation between natural numbers and strings of those lengths. E.g., (5, "hello") would by in the relation because 5 is the length of the string, "hello." -/ def R : β„• β†’ string β†’ Prop := Ξ» n s, n = s.length #check dom R #reduce dom R #check codom R #reduce codom R -- what set? #check dom_of_def R #reduce dom_of_def R -- a set, right? #check range R #reduce range R -- a set, right? /- RESTRICTION OF A RELATION It will often be useful to consider the subrelation obtained by restricting the domain of a relation to elements of a set, s. If a relation relates three cats, c1, c2, and c3, to their ages, say a1, a2 and a3, respectively, then restricting the domain of r to the set, s = {c1, c3}, would give the relation associating c1 and c3 with corresponding ages, but there would be no (c2, a2) pair in the restricted relation because c2 βˆ‰ s. An analogous definition gives us the range restriction of r to a set, s. -/ /- Note that these operations take relations and sets as arguments and "return" new relations (again represented as two_place predicates). Of course, these are logical specifications, not programs, so they don't really compute anything at all, but they do provide formal "specifications" of useful programs that can be implemented. Indeed, the set of relational concepts in this file is really at the heart of the relational specification of programs. -/ def dom_res (r : Ξ± β†’ Ξ² β†’ Prop) (s : set Ξ±) : Ξ± β†’ Ξ² β†’ Prop := Ξ» a b, a ∈ s ∧ r a b def ran_res (r : Ξ± β†’ Ξ² β†’ Prop) (s : set Ξ²) : Ξ± β†’ Ξ² β†’ Prop := _ -- homework /- In a relation in general, an Ξ± value can have zero, one, or more corresponding Ξ² values. As a nice example, consider the binary relation on real numbers defined by x^2 + y^2 = 1^2. From basic algebra, recall that, by the pythagorean theorem, this relation comprises all of the x-y pairs in the unit circle. It's the set of real number (x,y) pairs for which x^2+y^2=1. Now where x is zero, as an example, there is not one but there are two corresponding y values: -1 and 1. That's fine because a relation is *any* subset of the set of all Ξ±-Ξ² pairs. In particular, the "circle" relation contains both (0,1) and (0,-1). Each pair satisfies the specification, that x^2+y^2=1. Be sure you see that this simple algebraic claim is correct. If we think of "applying" a relation to a value, then, we have to get back not a single value, in general, but a set of values that could, in general, be empty, be a singleton set, or have more than one value. In our case here where r is the unit circle relation, what should we expect as the value of (r 0)? Yes, it's the set { 1, -1 }. We will this result set the "image" of 0 under r. I guess you can think of r as being like a bright light shining on 0 from the left and being blocked from projecting through to the corresponding Ξ² values except for where that 0 is. What gets illuminated in this case is the set of Ξ² values, { 1, -1 }. We can then easily extend this concept to the image of a set of Ξ± values. Note that the folloowing operations take a relation and a value and return a set of values. -/ -- image of an "argument" value under r def image_val (a : Ξ±) : set Ξ² := { b : Ξ² | a β‰Ί b } -- image of a set, s, of arguments, under r def image_set (s : set Ξ±) : set Ξ² := { b : Ξ² | βˆƒ a : Ξ±, a ∈ s ∧ a β‰Ί b } /- HOMEWORK Define the concepts of the *pre-image* of a value of type Ξ² or of a set of such values. -/ /- Here's another operation that takes a relation and returns a relation: namely the same as the original but with all the pair arrows reversed. -/ -- inverse of r def inverse : Ξ² β†’ Ξ± β†’ Prop := Ξ» (b : Ξ²) (a : Ξ±), r a b /- Finally we have this beautiful operation that takes two relations as arguments and glues them together into a new end-to-end relation: the *composition* of s with r. The result of applying this relation to an (a : Ξ±) is the (c : Ξ³) that is obtained by applying the relation s to the result of applying the relation r to a. We can thus call the resulting relation "s after r." -/ def composition (s : Ξ² β†’ Ξ³ β†’ Prop) (r : Ξ± β†’ Ξ² β†’ Prop):= Ξ» a c, (βˆƒ b, s b c ∧ r a b) #check @composition /- EXTENDED EXAMPLE -/ /- Let square be the binary relation that associates natural numbers with their squares. -/ def square := (Ξ» a b : β„•, b = a * a) /- Let incr be the binary relation that associates natural numbers with their successors (one more). -/ def incr := (Ξ» b c : β„•, c = b + 1) /- Let square_after_incr be the composition of square and incr, namely the composed function "square after increment" (where incr is short for increment). -/ def square_after_incr := composition square incr /- Think of square_after_incr as specifying a function where an argument, a, enters from the right of incr, moves left through incr, being increased by 1 in the process, then moves left again through through square, being squared in that process. So this relation associates any natural number with the square of its successor. -/ #check square -- binary relation on β„• #check incr -- binary relation on β„• #check square_after_incr -- binary relation on β„• #reduce square_after_incr -- Ξ» (a c : β„•), βˆƒ (b : β„•), -- c = b.mul b ∧ b = a.succ -- another relation on β„• /- Of course there's no computation actually going on here. Rather, the composed relation is again just specified logically. -/ #reduce square_after_incr -- Ξ» (a c : β„•), βˆƒ (b : β„•), c = b.mul b ∧ b = a.succ /- State and prove the conjecture that (3,16) is "in" the square_after_incr relation. Then show that (3,15) is not in this relation. -/ example : square_after_incr 3 16 := begin unfold square_after_incr square incr composition, apply exists.intro 4, split, repeat { exact rfl }, end /- Proof (English). Unfolding all of the definitions we see we are to prove βˆƒ (b : β„•), 16 = b * b ∧ b = 3 + 1. Let b = 4, split the conjunction, and prove each side by simplifying and by the reflexivity of equality. QED. -/ example : Β¬ square_after_incr 3 15 := begin assume h, unfold square_after_incr square incr composition at h, cases h with w pf, cases pf with sq inc, rw inc at sq, cases sq, -- contradiction end /- We'll use proof by negation, assuming that (3,15) is in square_after_incr and showing that this leads to a contriction, i.e., by applying negation introduction. Expanding all the definitions, we are to show that βˆƒ (b : β„•), 15 = b * b ∧ b = 3 + 1 leads to a contradiction. By βˆƒ elimination, we have a witness w and that 15 = w * w and w = 3 + 1. Rewriting w in the first equality using the second, we have 15 = (3 + 1) * (3 + 1). This assumption is inconsent, as proven by case analysis on the possible forms of a proof of such an equality, of which there are none to consider. -/ /- Alternative: We'll use proof by negation. Assume (3,15) ∈ square_after_incr. Expanding definitions, we need to show that assuming that βˆƒ (b : β„•), 15 = b * b ∧ b = 3 + 1 leads to a contradiction. Clearly b must be 4 and that leads to the absurd conclusion that 15 = 16. The original assumption that (3,15) ∈ square_after_incr must have been wrong thus (3,15) βˆ‰ square_after_incr. QED. -/ /- Proof by negation: What we're asked to show is that βˆƒ (b : β„•), 15 = b * b ∧ b = 3 + 1. Clearly there is no such b. QED. -/
8a280f01a2d60936c73c3d592a891257f06dea11
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1827_comment.lean
54815a93407bec3766c6b7fcf2268db0bf4eb4c2
[ "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
486
lean
lemma subst_weirdness1 {Ξ± Ξ² : Type} {x : Ξ±} {P : Ξ  t : Type, t β†’ Prop} (H : Ξ² = Ξ±) (H' : P Ξ± x) : P Ξ² (cast (by cc) x) := by { subst Ξ², exact H' } lemma subst_weirdness2 {Ξ± Ξ² : Type} {x : Ξ±} {P : Ξ  t : Type, t β†’ Prop} (H : Ξ² = Ξ±) (H' : P Ξ± x) : P Ξ² (cast (by cc) x) := by { cases H, exact H' } lemma subst_weirdness {Ξ± Ξ² : Type} {x : Ξ±} {P : Ξ  t : Type, t β†’ Prop} (H : Ξ² = Ξ±) (H' : P Ξ± x) : P Ξ² (cast (by cc) x) := by { subst Ξ±, exact H' }
f9c1763cee994e2851a600ca690b1af9e6e3934b
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebraic_geometry/ringed_space.lean
506bc9d9cdbb67799a463c1771e70dff3165de80
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
6,962
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer, Andrew Yang -/ import algebra.category.Ring.filtered_colimits import algebraic_geometry.sheafed_space import topology.sheaves.stalks import algebra.category.Ring.colimits import algebra.category.Ring.limits /-! # Ringed spaces We introduce the category of ringed spaces, as an alias for `SheafedSpace CommRing`. The facts collected in this file are typically stated for locally ringed spaces, but never actually make use of the locality of stalks. See for instance <https://stacks.math.columbia.edu/tag/01HZ>. -/ universe v open category_theory open topological_space open opposite open Top open Top.presheaf namespace algebraic_geometry /-- The type of Ringed spaces, as an abbreviation for `SheafedSpace CommRing`. -/ abbreviation RingedSpace : Type* := SheafedSpace CommRing namespace RingedSpace open SheafedSpace variables (X : RingedSpace.{v}) /-- If the germ of a section `f` is a unit in the stalk at `x`, then `f` must be a unit on some small neighborhood around `x`. -/ lemma is_unit_res_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (x : U) (h : is_unit (X.presheaf.germ x f)) : βˆƒ (V : opens X) (i : V ⟢ U) (hxV : x.1 ∈ V), is_unit (X.presheaf.map i.op f) := begin obtain ⟨g', heq⟩ := h.exists_right_inv, obtain ⟨V, hxV, g, rfl⟩ := X.presheaf.germ_exist x.1 g', let W := U βŠ“ V, have hxW : x.1 ∈ W := ⟨x.2, hxV⟩, erw [← X.presheaf.germ_res_apply (opens.inf_le_left U V) ⟨x.1, hxW⟩ f, ← X.presheaf.germ_res_apply (opens.inf_le_right U V) ⟨x.1, hxW⟩ g, ← ring_hom.map_mul, ← ring_hom.map_one (X.presheaf.germ (⟨x.1, hxW⟩ : W))] at heq, obtain ⟨W', hxW', i₁, iβ‚‚, heq'⟩ := X.presheaf.germ_eq x.1 hxW hxW _ _ heq, use [W', i₁ ≫ opens.inf_le_left U V, hxW'], rw [ring_hom.map_one, ring_hom.map_mul, ← comp_apply, ← X.presheaf.map_comp, ← op_comp] at heq', exact is_unit_of_mul_eq_one _ _ heq', end /-- If a section `f` is a unit in each stalk, `f` must be a unit. -/ lemma is_unit_of_is_unit_germ (U : opens X) (f : X.presheaf.obj (op U)) (h : βˆ€ x : U, is_unit (X.presheaf.germ x f)) : is_unit f := begin -- We pick a cover of `U` by open sets `V x`, such that `f` is a unit on each `V x`. choose V iVU m h_unit using Ξ» x : U, X.is_unit_res_of_is_unit_germ U f x (h x), have hcover : U ≀ supr V, { intros x hxU, rw [opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, -- Let `g x` denote the inverse of `f` in `U x`. choose g hg using Ξ» x : U, is_unit.exists_right_inv (h_unit x), -- We claim that these local inverses glue together to a global inverse of `f`. obtain ⟨gl, gl_spec, -⟩ := X.sheaf.exists_unique_gluing' V U iVU hcover g _, swap, { intros x y, apply section_ext X.sheaf (V x βŠ“ V y), rintro ⟨z, hzVx, hzVy⟩, rw [germ_res_apply, germ_res_apply], apply (is_unit.mul_right_inj (h ⟨z, (iVU x).le hzVx⟩)).mp, erw [← X.presheaf.germ_res_apply (iVU x) ⟨z, hzVx⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVx⟩ : V x)) (hg x), germ_res_apply, ← X.presheaf.germ_res_apply (iVU y) ⟨z, hzVy⟩ f, ← ring_hom.map_mul, congr_arg (X.presheaf.germ (⟨z, hzVy⟩ : V y)) (hg y), ring_hom.map_one, ring_hom.map_one] }, apply is_unit_of_mul_eq_one f gl, apply X.sheaf.eq_of_locally_eq' V U iVU hcover, intro i, rw [ring_hom.map_one, ring_hom.map_mul, gl_spec], exact hg i, end /-- The basic open of a section `f` is the set of all points `x`, such that the germ of `f` at `x` is a unit. -/ def basic_open {U : opens X} (f : X.presheaf.obj (op U)) : opens X := { val := coe '' { x : U | is_unit (X.presheaf.germ x f) }, property := begin rw is_open_iff_forall_mem_open, rintros _ ⟨x, hx, rfl⟩, obtain ⟨V, i, hxV, hf⟩ := X.is_unit_res_of_is_unit_germ U f x hx, use V.1, refine ⟨_, V.2, hxV⟩, intros y hy, use (⟨y, i.le hy⟩ : U), rw set.mem_set_of_eq, split, { convert ring_hom.is_unit_map (X.presheaf.germ ⟨y, hy⟩) hf, exact (X.presheaf.germ_res_apply i ⟨y, hy⟩ f).symm }, { refl } end } @[simp] lemma mem_basic_open {U : opens X} (f : X.presheaf.obj (op U)) (x : U) : ↑x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ x f) := begin split, { rintro ⟨x, hx, a⟩, cases subtype.eq a, exact hx }, { intro h, exact ⟨x, h, rfl⟩ }, end @[simp] lemma mem_top_basic_open (f : X.presheaf.obj (op ⊀)) (x : X) : x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ ⟨x, show x ∈ (⊀ : opens X), by trivial⟩ f) := mem_basic_open X f ⟨x, _⟩ lemma basic_open_le {U : opens X} (f : X.presheaf.obj (op U)) : X.basic_open f ≀ U := by { rintros _ ⟨x, hx, rfl⟩, exact x.2 } /-- The restriction of a section `f` to the basic open of `f` is a unit. -/ lemma is_unit_res_basic_open {U : opens X} (f : X.presheaf.obj (op U)) : is_unit (X.presheaf.map (@hom_of_le (opens X) _ _ _ (X.basic_open_le f)).op f) := begin apply is_unit_of_is_unit_germ, rintro ⟨_, ⟨x, hx, rfl⟩⟩, convert hx, rw germ_res_apply, refl, end @[simp] lemma basic_open_res {U V : (opens X)α΅’α΅–} (i : U ⟢ V) (f : X.presheaf.obj U) : @basic_open X (unop V) (X.presheaf.map i f) = (unop V) βŠ“ @basic_open X (unop U) f := begin induction U using opposite.rec, induction V using opposite.rec, let g := i.unop, have : i = g.op := rfl, clear_value g, subst this, ext, split, { rintro ⟨x, (hx : is_unit _), rfl⟩, rw germ_res_apply at hx, exact ⟨x.2, g x, hx, rfl⟩ }, { rintros ⟨hxV, x, hx, rfl⟩, refine ⟨⟨x, hxV⟩, (_ : is_unit _), rfl⟩, rwa germ_res_apply } end -- This should fire before `basic_open_res`. @[simp, priority 1100] lemma basic_open_res_eq {U V : (opens X)α΅’α΅–} (i : U ⟢ V) [is_iso i] (f : X.presheaf.obj U) : @basic_open X (unop V) (X.presheaf.map i f) = @RingedSpace.basic_open X (unop U) f := begin apply le_antisymm, { rw X.basic_open_res i f, exact inf_le_right }, { have := X.basic_open_res (inv i) (X.presheaf.map i f), rw [← comp_apply, ← X.presheaf.map_comp, is_iso.hom_inv_id, X.presheaf.map_id] at this, erw this, exact inf_le_right } end @[simp] lemma basic_open_mul {U : opens X} (f g : X.presheaf.obj (op U)) : X.basic_open (f * g) = X.basic_open f βŠ“ X.basic_open g := begin ext1, dsimp [RingedSpace.basic_open], rw ←set.image_inter subtype.coe_injective, congr, ext, simp_rw map_mul, exact is_unit.mul_iff, end lemma basic_open_of_is_unit {U : opens X} {f : X.presheaf.obj (op U)} (hf : is_unit f) : X.basic_open f = U := begin apply le_antisymm, { exact X.basic_open_le f }, intros x hx, erw X.mem_basic_open f (⟨x, hx⟩ : U), exact ring_hom.is_unit_map _ hf end end RingedSpace end algebraic_geometry
d776557561f8f4e9d5f92aa126592bff31272468
bdc27058d2df65f1c05b3dd4ff23a30af9332a2b
/src/hilbert.lean
6911313e5aaa09259c8983041231107e89a4d5d6
[]
no_license
bakerjd99/leanteach2020
19e3dda4167f7bb8785fe0e2fe762a9c53a9214d
2160909674f3aec475eabb51df73af7fa1d91c65
refs/heads/master
1,668,724,511,289
1,594,407,424,000
1,594,407,424,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,293
lean
-- Hilbert's Axioms Formalized import data.real.basic tactic noncomputable theory open_locale classical /- Hilbert uses three undefined types: Points, Lines and Planes. We define Point as a constant. Lines we define as Structures instead of Constants. We do not define Planes since here, we restrict our attention to planar geometry, ignoring solid geometry.-/ constant Point : Type /- A Segment is constructed by specifying two points. The subscripts are written as \1 and \2. -/ structure Segment: Type := (p₁ pβ‚‚ : Point) /- This is the Betweenness relation. It says the Point "y" is in between Point "x" and "z".-/ constant B (x y z : Point) : Prop /- Polymorphism β‡’ make it work for multiple types at the same time. For every type A, we assume there is a congruence relation C. Here, "A" is an implicit argument. Lean will figure it out by reading the type signatures of other arguments. In other languages this is called over-loading.-/ constant C {A : Type} : A β†’ A β†’ Prop /- We define our own operators here. \equiv is used to denote equivalence/congruence. \cdot is used for making Segments.-/ local infix ` ≃ `:55 := C local infix `⬝`: 56 := Segment.mk /- # I. Incidence Axioms ===================== I.1 and I.2 ----------- Hilbert declares that Line is an independent type and then in Axioms I.1 and I.2 he provides a necessary and sufficient condition for constructing a Line from two Points. We believe it is more efficient to directly define Line as a structure that requires two distint Points. -/ structure Line : Type := (p₁ pβ‚‚ : Point) (ne : p₁ β‰  pβ‚‚) /- There are two "lies-on" relations. We specify lies_on_line here as a constant. lies_on_segment is defined later.-/ constant lies_on_line (p : Point) (l : Line) : Prop /- I.1, I.2 is implicit in the following axiom. -/ axiom line_exists (p₁ pβ‚‚ : Point) (ne : p₁ β‰  pβ‚‚) (l : Line) : lies_on_line p₁ l ∧ lies_on_line pβ‚‚ l ↔ l = ⟨p₁, pβ‚‚, ne⟩ -- I.3 (part 1) -- This axiom is implicit in the definition of Line as a structure. -- We do not need to formalize this separately. -- I.3 (part 2) axiom no_line_on_three_points: βˆƒ (a b c : Point), Β¬ βˆƒ (l : Line), (lies_on_line a l) ∧ (lies_on_line b l) ∧ (lies_on_line c l) -- A Ray is constructed by specifying two Points. structure Ray : Type := (base ext : Point) -- For each Ray, we can define a corresponding Line. def line_of_ray (r : Ray) (ne : r.base β‰  r.ext) : Line := ⟨r.base, r.ext, ne⟩ -- An Angle is constructed by specifying three Points. -- Angle ⟨a, b, c, _, _⟩ reperesents the angle ∠abc. structure Angle : Type := (ext₁ base extβ‚‚ : Point) -- For each Angle, we can define two corresponding Rays. def rays_of_angle (Ξ± : Angle) : Ray Γ— Ray := (⟨α.base, Ξ±.extβ‚βŸ©, ⟨α.base, Ξ±.extβ‚‚βŸ©) -- A Triangle is constructed by specifying three Points. structure Triangle : Type := (p₁ pβ‚‚ p₃ : Point) -- For every Triangle, we get three Segments (its sides). def sides_of_triangle (t : Triangle) : vector Segment 3 := ⟨[t.p₁⬝t.pβ‚‚, t.p₂⬝t.p₃, t.p₁⬝t.p₃], rfl⟩ -- For every Triangle, we can define get three Segment Angles. def angles_of_triangle (t : Triangle) : vector Angle 3 := ⟨[⟨t.pβ‚‚, t.p₁, t.pβ‚ƒβŸ©, ⟨t.p₁, t.pβ‚‚, t.pβ‚ƒβŸ©, ⟨t.pβ‚‚, t.p₃, t.pβ‚βŸ©], rfl⟩ -- Note that elements of a vector v can be accessed as v.nth 0 etc. -- Also note that if a vector has lenth n, then asking for element m -- where m β‰₯ n returns element (m mod n) def equilateral (abc : Triangle) : Prop := let sides := sides_of_triangle abc in let ab := sides.nth 0 in let bc := sides.nth 1 in let ac := sides.nth 2 in ab ≃ bc ∧ bc ≃ ac -- # II. Order Axioms --------------------- def collinear_points (a b c : Point) : Prop := βˆƒ (l : Line), lies_on_line a l ∧ lies_on_line b l ∧ lies_on_line c l /- Note: ----- I.1 and I.2 guarantee that a Line exists between each pair of points, but it does not guarantee that the Lines corresponding to ab, ac, and bc are all the same. For that, we need another axiom (II.1). -/ -- II.1 (part 1) @[symm] axiom B_symm (a b c : Point) : B a b c β†’ B c b a -- II.1 (part 2) axiom B_implies_collinear (a b c : Point): B a b c β†’ collinear_points a b c -- II.2 axiom line_continuity (a c : Point) (ne : a β‰  c): let l : Line := ⟨a, c, ne⟩ in βˆƒ (b : Point), lies_on_line b l ∧ B a b c -- II.3 axiom max_one_between (a b c : Point): collinear_points a b c β†’ xor (B a b c) (xor (B a c b) (B c a b)) -- ## Helpful definitions ------------------------- -- Lies-on relation between Point and Segment. def lies_on_segment (x : Point) (s : Segment) (ne : s.p₁ β‰  s.pβ‚‚) : Prop := B s.p₁ x s.pβ‚‚ ∧ lies_on_line x ⟨s.p₁, s.pβ‚‚, ne⟩ -- Criterion for two Segments intersecting at a Point. def intersect_segment (s₁ sβ‚‚ : Segment) (ne1 : s₁.p₁ β‰  s₁.pβ‚‚) (ne2 : sβ‚‚.p₁ β‰  sβ‚‚.pβ‚‚) : Prop := βˆƒ x : Point, lies_on_segment x s₁ ne1 ∧ lies_on_segment x sβ‚‚ ne2 -- Criterion for two Lines intersecting at a Point. def intersect_line (l₁ lβ‚‚ : Line) : Prop := βˆƒ x : Point, lies_on_line x l₁ ∧ lies_on_line x lβ‚‚ -- Criterion for a Segment intersecting with a Line. def intersect_line_segment (l: Line) (s : Segment) (ne : s.p₁ β‰  s.pβ‚‚) : Prop := βˆƒ x : Point, lies_on_line x l ∧ lies_on_segment x s ne -- Condition for a Segment to be a part of a given Line. def segment_of_line (s : Segment) (l : Line) : Prop := lies_on_line s.p₁ l ∧ lies_on_line s.pβ‚‚ l -- Condition for two segments to have only one point in common. We -- can think of these segments as being end-to-end (forming an angle). def segments_hinge (s₁ sβ‚‚ : Segment) (ne₁ : s₁.p₁ β‰  s₁.pβ‚‚) (neβ‚‚ : sβ‚‚.p₁ β‰  sβ‚‚.pβ‚‚) : Prop := βˆ€ x : Point, lies_on_segment x s₁ ne₁ ∧ lies_on_segment x sβ‚‚ neβ‚‚ β†’ x = s₁.pβ‚‚ ∧ x = sβ‚‚.p₁ -- Dinifinition of parallel Lines. def parallel_lines (l₁ lβ‚‚ : Line) : Prop := Β¬βˆƒ (a : Point), lies_on_line a l₁ ∧ lies_on_line a lβ‚‚ -- Condition for two Points to lie on the same side of a Line. def lie_on_same_side (a b : Point) (l : Line) : Prop := decidable.by_cases (Ξ» eq : a = b, true) (Ξ» ne, Β¬ intersect_line_segment l (a⬝b) ne) -- Condition for two Points to lie on opposite sides of a Line. def lie_on_opposite_sides (a b : Point) (l : Line) : Prop := Β¬ lie_on_same_side a b l -- Define a particular side of a Line (using a Point `marker` to mark -- our choice of side). def side_of_line (l : Line) (marker : Point) (x : Point) : Prop := lie_on_same_side x marker l -- Define a particular side of a Point `p` on a Line `⟨p, marker, ne⟩` -- (using a Point `marker` to mark our choice of side). def side_of_point (p marker : Point) (ne : p β‰  marker) : set Point := {x : Point | B p marker x ∨ B p x marker} -- Interior points of an Angle def is_in_interior_of_angle (Ξ± : Angle) (p : Point) (ne1 : Ξ±.base β‰  Ξ±.ext₁) (ne2 : Ξ±.base β‰  Ξ±.extβ‚‚) : Prop := side_of_line ⟨α.base, Ξ±.ext₁, ne1⟩ Ξ±.extβ‚‚ p ∧ side_of_line ⟨α.base, Ξ±.extβ‚‚, ne2⟩ Ξ±.ext₁ p -- II.4 Pasch's axiom -- This can be interpreted as saying "a line that enters a triangle -- from one side, must leave the triangle from one of the reamining -- two sides." axiom pasch (a b c : Point) (l : Line) (ne_ab : a β‰  b) (ne_bc : b β‰  c) (ne_ac : a β‰  c) : Β¬ collinear_points a b c β†’ Β¬ lies_on_line a l β†’ Β¬ lies_on_line b l β†’ Β¬ lies_on_line c l β†’ intersect_line_segment l (a⬝b) ne_ab β†’ intersect_line_segment l (a⬝c) ne_ac ∨ intersect_line_segment l (b⬝c) ne_bc -- # III. Congruence Axioms --------------------------- -- III.1 Part 1 This says that we can extend a given Segment `a⬝b` in -- only two ways: one for each side of `p`. constant segment_copy {a b p marker : Point} : a β‰  b β†’ p β‰  marker β†’ Point axiom segment_copy' (a b p marker : Point) (ne_a_b : a β‰  b) (ne_p_mark : p β‰  marker) : let q : Point := segment_copy ne_a_b ne_p_mark in let pm : Line := ⟨p, marker, ne_p_mark⟩ in lies_on_line q pm ∧ a⬝b ≃ p⬝q -- III.1 Part 2 @[symm] axiom C_segment_symm {s₁ sβ‚‚ : Segment} : s₁ ≃ sβ‚‚ β†’ sβ‚‚ ≃ s₁ axiom segment_swap {x y : Point} : x⬝y ≃ y⬝x -- III.2 @[trans] axiom C_segment_trans {u v w x y z : Point} : (u⬝v ≃ z⬝w) β†’ (u⬝v ≃ x⬝y) β†’ z⬝w ≃ x⬝y -- Congruence of segments is reflexive @[refl] lemma C_segment_refl (a b : Point) : a⬝b ≃ a⬝b := begin transitivity, repeat {apply segment_swap}, end -- III.3 axiom C_segment_add_trans (a b c a' b' c' : Point) (ne_ab : a β‰  b) (ne_bc : b β‰  c) (ne_a'b' : a' β‰  b') (ne_b'c' : b' β‰  c') : segments_hinge (a⬝b) (b⬝c) ne_ab ne_bc β†’ segments_hinge (a'⬝b') (b'⬝c') ne_a'b' ne_b'c' β†’ a⬝b ≃ a'⬝b' β†’ b⬝c ≃ b'⬝c' β†’ a⬝c ≃ a'⬝c' -- III.4 This axiom says that a given angle can be copied over to a -- new location (the point base) in a unique manner (unique as long as -- we keep track of which side of the Line `⟨base, p1⟩` we are on). -- We keep track of the side using `marker`. constant angle_copy (Ξ± : Angle) (base p1 marker : Point) : Point axiom angle_copy' (Ξ± : Angle) (base p1 marker : Point) (ne1 : base β‰  p1) : let p2 : Point := angle_copy Ξ± base p1 marker in let Ξ±' : Angle := ⟨p1, base, p2⟩ in decidable.by_cases Ξ± ≃ Ξ±' ∧ βˆ€ x : Point, is_in_interior_of_angle Ξ±' x ne1 -- III.5 (wikipedia) @[trans] axiom C_angle_trans (Ξ± Ξ² Ξ³ : Angle) : Ξ± ≃ Ξ² β†’ Ξ± ≃ Ξ³ β†’ Ξ² ≃ Ξ³ @[symm] axiom angle_symm (a b c : Point) : (⟨a, b, c⟩ : Angle) ≃ ⟨c, b, a⟩ --- III.5 (from Paper) / III.6 (from wikipedia) axiom congruent_triangle_SAS (a b c x y z : Point) : let abc : Triangle := ⟨a, b, c⟩ in let xyz : Triangle := ⟨x, y, z⟩ in let ang_abc := angles_of_triangle abc in let ang_xyz := angles_of_triangle xyz in a⬝b ≃ x⬝y β†’ a⬝c ≃ x⬝z β†’ ang_abc.nth 0 ≃ ang_xyz.nth 0 β†’ ang_abc.nth 1 ≃ ang_xyz.nth 1 ∧ ang_abc.nth 2 ≃ ang_xyz.nth 2 -- Definition of Congruent Triangles. All sides must be congruent. def congruent_triangle (a b c x y z : Point) : Prop := a⬝b ≃ x⬝y ∧ b⬝c ≃ y⬝z ∧ a⬝c ≃ x⬝z ∧ (⟨b, a, c⟩ : Angle) ≃ ⟨y, x, z⟩ ∧ (⟨a, b, c⟩ : Angle) ≃ ⟨x, y, z⟩ ∧ (⟨b, c, a⟩ : Angle) ≃ ⟨y, z, x⟩ -- First theorem of congruence for triangles. If, for the two -- triangles ABC and Aβ€²Bβ€²Cβ€², the congruences AB≑Aβ€²Bβ€², AC≑Aβ€²Cβ€², ∠Aβ‰‘βˆ Aβ€² -- hold, then the two triangles are congruent to each other. lemma first_congruence (a b c x y z : Point) : a⬝b ≃ x⬝y β†’ a⬝c ≃ x⬝z β†’ (⟨b, a, c⟩ : Angle) ≃ ⟨y, x, z⟩ β†’ congruent_triangle a b c x y z := begin intros, unfold congruent_triangle, intros, have ne_b_c : b β‰  c, sorry, have ne_y_z : y β‰  z, sorry, set bc : Line := ⟨b, c, ne_b_c⟩, set yz : Line := ⟨y, z, ne_y_z⟩, have b_on_bc : lies_on_line b bc, sorry, have c_on_bc : lies_on_line c bc, sorry, have y_on_yz : lies_on_line y yz, sorry, repeat {split}; try {assumption}, { by_contradiction, have sc' := segment_copy' _ _ _ _ _ b_on_bc c_on_bc y_on_yz, simp at sc', set sc := segment_copy _ _ _ _ _ b_on_bc c_on_bc y_on_yz, rcases sc' with ⟨h₁, hβ‚‚, h₃, hβ‚„, hβ‚…βŸ©, set z₁ : Point := sc.1, set zβ‚‚ : Point := sc.2, have SAS := (congruent_triangle_SAS b a c y x z₁ _ h₃ _).1, have h₆ : (⟨y, x, z⟩ : Angle) ≃ ⟨y, x, zβ‚βŸ©, transitivity, exact a_3, assumption, have angle_congruent := angle_congruent, sorry}, have SAS := congruent_triangle_SAS a b c x y z a_1 a_2 a_3, { exact SAS.1}, { exact SAS.2}, end -- # IV. Parallel Axiom ----------------------- -- Euclid's parallel postulate. This axioms puts us in a Euclidean geometry -- and rules out Elliptical/Spherical/Hyperbolic geometry. constant mk_parallel (p : Point) (l : Line): Β¬lies_on_line p l β†’ Line axiom parallel_postulate (a : Point) (l : Line) (h: Β¬lies_on_line a l): let l' : Line := mk_parallel a l h in parallel_lines l l' ∧ lies_on_line a l' -- # V. Angles -------------- -- Two angles having the same vertex and one side in common, whilethe -- sides not common form a straight line, are called supplementary -- angles. Two angleshaving a common vertex and whose sides form -- straight lines are calledvertical angles. An angle which is -- congruent to its supplementary angle is called a right angle. def supplementary_angles (α₁ Ξ±β‚‚ : Angle) (h₁ : α₁.base β‰  α₁.ext₁) (hβ‚‚ : Ξ±β‚‚.base β‰  Ξ±β‚‚.ext₁) : Prop := α₁.base = Ξ±β‚‚.base ∧ (βŸ¨Ξ±β‚.base, α₁.ext₁, hβ‚βŸ© : Line) = βŸ¨Ξ±β‚‚.base, Ξ±β‚‚.ext₁, hβ‚‚βŸ© ∧ collinear_points α₁.base α₁.extβ‚‚ Ξ±β‚‚.extβ‚‚ -- LZ,AD : How to define this rigorously when the point can basically be -- anywhere? -- VK : use *segment_copy*. def mk_supplementary_angle (Ξ± : Angle) (h: Ξ±.base β‰  Ξ±.extβ‚‚): Angle := let l : Line := Line.mk Ξ±.base Ξ±.extβ‚‚ h in let bl : lies_on_line Ξ±.base l := (line_exists Ξ±.base Ξ±.extβ‚‚ h).1 in let el : lies_on_line Ξ±.extβ‚‚ l := (line_exists Ξ±.base Ξ±.extβ‚‚ h).2 in let thing := segment_copy Ξ±.base Ξ±.extβ‚‚ Ξ±.base l l bl el bl in let P : Point := thing.1 in ⟨α.ext₁, Ξ±.base, P⟩ lemma mk_supp_angle_condition (Ξ± : Angle) (h : Ξ±.base β‰  Ξ±.extβ‚‚) : (mk_supplementary_angle Ξ± h).base β‰  (mk_supplementary_angle Ξ± h).ext₁ := begin unfold mk_supplementary_angle, simp, sorry end lemma mk_supplementary_angle_is_supplementary (Ξ± : Angle) (h : Ξ±.base β‰  Ξ±.ext₁): supplementary_angles Ξ± (mk_supplementary_angle Ξ±) h (mk_supp_angle_condition Ξ±) := sorry -- This specifies a Predicate on the type Angle def is_right (Ξ± : Angle) : Prop := Ξ± ≃ mk_supplementary_angle Ξ± structure Circle: Type := (center outer : Point) def radius_segment (c : Circle) : Segment := ⟨c.center, c.outer⟩ def circumference (c : Circle) : set Point := {x : Point | radius_segment c ≃ ⟨c.center, x⟩} -- # Notion of Distance in Hilbert ---------------------------------- -- may be necessary to properly state and prove pythagorean theorem in -- Lean). We start by defining a `measure` on Segments. def Measure : Type := Segment β†’ ℝ -- Next, we define some axioms for working with distance. axiom distance_nonzero (ΞΌ : Measure) (s : Segment) : s.p₁ β‰  s.pβ‚‚ ↔ ΞΌ s > 0 axiom distance_congruent (ΞΌ : Measure) (s₁ sβ‚‚ : Segment) : s₁ ≃ sβ‚‚ ↔ ΞΌ s₁ = ΞΌ sβ‚‚ axiom distance_between (ΞΌ : Measure) (a b c : Point) : B a b c β†’ ΞΌ (a⬝b) + ΞΌ (b⬝c) = ΞΌ (a⬝c) -- Theorems that can be proved in "Foundations of geometry" by Borsuk -- and Szmielew. theorem distance_scale (μ₁ ΞΌβ‚‚ : Measure) (s : Segment) : βˆƒ k : ℝ, k > 0 ∧ μ₁ s = k * ΞΌβ‚‚ s := begin sorry end theorem exists_measure (s : Segment) (x : ℝ) : βˆƒ (ΞΌ : Measure), ΞΌ s = x := begin sorry end -- # Continuity Axioms ---------------------- -- Using a combo of the version here and Wikipedia : -- https://www.math.ust.hk/~mabfchen/Math4221/Hilbert%20Axioms.pdf axiom Archimedes (s₁ sβ‚‚ : Segment) (ΞΌ : Measure) : βˆƒ (n : nat) (q : Point), ΞΌ (s₁.p₁ ⬝ q) = n * ΞΌ sβ‚‚ ∧ B s₁.p₁ s₁.pβ‚‚ q -- Continuity axiom 2 --------------------- -- Axiom of Completeness (VollstΓ€ndigkeit) : To a system of points, -- straight lines,and planes, it is impossible to add other elements -- in such a manner that the systemthus generalized shall form a new -- geometry obeying all of the five groups of axioms.In other words, -- the elements of geometry form a system which is not susceptible -- ofextension, if we regard the five groups of axioms as valid. -- This axiom talks about completeness in a way that we are unsure can -- be actually implemented. -- axiom line_completeness (l : Line) (X : set Point) : Β¬ βˆƒ l' : Line, -- order_preserved X l l' ∧ cong_preserved X l l'
68ea5a3b34d53fcfdf8cb5c8eff3bc50df420f2b
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/DeclarationRange.lean
4d8e4e5e4c5b2639fcffd2b4186ee314c82c0029
[ "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,638
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.MonadEnv import Lean.AuxRecursor namespace Lean structure DeclarationRange where pos : Position /-- A precomputed UTF-16 `character` field as in `Lean.Lsp.Position`. We need to store this because LSP clients want us to report the range in terms of UTF-16, but converting a Unicode codepoint stored in `Lean.Position` to UTF-16 requires loading and mapping the target source file, which is IO-heavy. -/ charUtf16 : Nat endPos : Position /-- See `charUtf16`. -/ endCharUtf16 : Nat deriving Inhabited, DecidableEq, Repr structure DeclarationRanges where range : DeclarationRange selectionRange : DeclarationRange deriving Inhabited, Repr builtin_initialize declRangeExt : MapDeclarationExtension DeclarationRanges ← mkMapDeclarationExtension `declranges def addDeclarationRanges [MonadEnv m] (declName : Name) (declRanges : DeclarationRanges) : m Unit := modifyEnv fun env => declRangeExt.insert env declName declRanges def findDeclarationRangesCore? [Monad m] [MonadEnv m] (declName : Name) : m (Option DeclarationRanges) := return declRangeExt.find? (← getEnv) declName def findDeclarationRanges? [Monad m] [MonadEnv m] (declName : Name) : m (Option DeclarationRanges) := do let env ← getEnv if isAuxRecursor env declName || isNoConfusion env declName || (← isRec declName) then findDeclarationRangesCore? declName.getPrefix else findDeclarationRangesCore? declName end Lean
4c6fe520086f36e5ff48f7d59c41c5c801b808e5
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/measure/haar_of_basis.lean
e8da34d00525df6777649564c6590804d02f3475
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
6,874
lean
/- Copyright (c) 2022 SΓ©bastien GouΓ«zel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: SΓ©bastien GouΓ«zel -/ import measure_theory.measure.haar import analysis.inner_product_space.pi_L2 /-! # Additive Haar measure constructed from a basis Given a basis of a finite-dimensional real vector space, we define the corresponding Lebesgue measure, which gives measure `1` to the parallelepiped spanned by the basis. ## Main definitions * `parallelepiped v` is the parallelepiped spanned by a finite family of vectors. * `basis.parallelepiped` is the parallelepiped associated to a basis, seen as a compact set with nonempty interior. * `basis.add_haar` is the Lebesgue measure associated to a basis, giving measure `1` to the corresponding parallelepiped. In particular, we declare a `measure_space` instance on any finite-dimensional inner product space, by using the Lebesgue measure associated to some orthonormal basis (which is in fact independent of the basis). -/ open set topological_space measure_theory measure_theory.measure finite_dimensional open_locale big_operators noncomputable theory variables {ΞΉ ΞΉ' E F : Type*} [fintype ΞΉ] [fintype ΞΉ'] section add_comm_group variables [add_comm_group E] [module ℝ E] [add_comm_group F] [module ℝ F] /-- The closed parallelepiped spanned by a finite family of vectors. -/ def parallelepiped (v : ΞΉ β†’ E) : set E := (Ξ» (t : ΞΉ β†’ ℝ), βˆ‘ i, t i β€’ v i) '' (Icc 0 1) lemma mem_parallelepiped_iff (v : ΞΉ β†’ E) (x : E) : x ∈ parallelepiped v ↔ βˆƒ (t : ΞΉ β†’ ℝ) (ht : t ∈ Icc (0 : ΞΉ β†’ ℝ) 1), x = βˆ‘ i, t i β€’ v i := by simp [parallelepiped, eq_comm] lemma image_parallelepiped (f : E β†’β‚—[ℝ] F) (v : ΞΉ β†’ E) : f '' (parallelepiped v) = parallelepiped (f ∘ v) := begin simp only [parallelepiped, ← image_comp], congr' 1 with t, simp only [function.comp_app, linear_map.map_sum, linear_map.map_smulβ‚›β‚—, ring_hom.id_apply], end /-- Reindexing a family of vectors does not change their parallelepiped. -/ @[simp] lemma parallelepiped_comp_equiv (v : ΞΉ β†’ E) (e : ΞΉ' ≃ ΞΉ) : parallelepiped (v ∘ e) = parallelepiped v := begin simp only [parallelepiped], let K : (ΞΉ' β†’ ℝ) ≃ (ΞΉ β†’ ℝ) := equiv.Pi_congr_left' (Ξ» (a : ΞΉ'), ℝ) e, have : Icc (0 : (ΞΉ β†’ ℝ)) 1 = K '' (Icc (0 : (ΞΉ' β†’ ℝ)) 1), { rw ← equiv.preimage_eq_iff_eq_image, ext x, simp only [mem_preimage, mem_Icc, pi.le_def, pi.zero_apply, equiv.Pi_congr_left'_apply, pi.one_apply], refine ⟨λ h, ⟨λ i, _, Ξ» i, _⟩, Ξ» h, ⟨λ i, h.1 (e.symm i), Ξ» i, h.2 (e.symm i)⟩⟩, { simpa only [equiv.symm_apply_apply] using h.1 (e i) }, { simpa only [equiv.symm_apply_apply] using h.2 (e i) } }, rw [this, ← image_comp], congr' 1 with x, simpa only [orthonormal_basis.coe_reindex, function.comp_app, equiv.symm_apply_apply, equiv.Pi_congr_left'_apply, equiv.apply_symm_apply] using (e.symm.sum_comp (Ξ» (i : ΞΉ'), x i β€’ v (e i))).symm, end /- The parallelepiped associated to an orthonormal basis of `ℝ` is either `[0, 1]` or `[-1, 0]`. -/ lemma parallelepiped_orthonormal_basis_one_dim (b : orthonormal_basis ΞΉ ℝ ℝ) : parallelepiped b = Icc 0 1 ∨ parallelepiped b = Icc (-1) 0 := begin have e : ΞΉ ≃ fin 1, { apply fintype.equiv_fin_of_card_eq, simp only [← finrank_eq_card_basis b.to_basis, finrank_self] }, have B : parallelepiped (b.reindex e) = parallelepiped b, { convert parallelepiped_comp_equiv b e.symm, ext i, simp only [orthonormal_basis.coe_reindex] }, rw ← B, let F : ℝ β†’ (fin 1 β†’ ℝ) := Ξ» t, (Ξ» i, t), have A : Icc (0 : fin 1 β†’ ℝ) 1 = F '' (Icc (0 : ℝ) 1), { apply subset.antisymm, { assume x hx, refine ⟨x 0, ⟨hx.1 0, hx.2 0⟩, _⟩, ext j, simp only [subsingleton.elim j 0] }, { rintros x ⟨y, hy, rfl⟩, exact ⟨λ j, hy.1, Ξ» j, hy.2⟩ } }, rcases orthonormal_basis_one_dim (b.reindex e) with H|H, { left, simp only [H, parallelepiped, algebra.id.smul_eq_mul, mul_one, A, finset.sum_singleton, ←image_comp, image_id', finset.univ_unique], }, { right, simp only [H, parallelepiped, algebra.id.smul_eq_mul, mul_one], rw A, simp only [←image_comp, mul_neg, mul_one, finset.sum_singleton, image_neg, preimage_neg_Icc, neg_zero, finset.univ_unique] }, end end add_comm_group section normed_space variables [normed_add_comm_group E] [normed_space ℝ E] /-- The parallelepiped spanned by a basis, as a compact set with nonempty interior. -/ def basis.parallelepiped (b : basis ΞΉ ℝ E) : positive_compacts E := { carrier := parallelepiped b, is_compact' := is_compact_Icc.image (continuous_finset_sum finset.univ (Ξ» (i : ΞΉ) (H : i ∈ finset.univ), (continuous_apply i).smul continuous_const)), interior_nonempty' := begin suffices H : set.nonempty (interior (b.equiv_funL.symm.to_homeomorph '' (Icc 0 1))), { dsimp only [parallelepiped], convert H, ext t, exact (b.equiv_fun_symm_apply t).symm }, have A : set.nonempty (interior (Icc (0 : ΞΉ β†’ ℝ) 1)), { rw [← pi_univ_Icc, interior_pi_set (@finite_univ ΞΉ _)], simp only [univ_pi_nonempty_iff, pi.zero_apply, pi.one_apply, interior_Icc, nonempty_Ioo, zero_lt_one, implies_true_iff] }, rwa [← homeomorph.image_interior, nonempty_image_iff], end } variables [measurable_space E] [borel_space E] /-- The Lebesgue measure associated to a basis, giving measure `1` to the parallelepiped spanned by the basis. -/ @[irreducible] def basis.add_haar (b : basis ΞΉ ℝ E) : measure E := measure.add_haar_measure b.parallelepiped instance is_add_haar_measure_basis_add_haar (b : basis ΞΉ ℝ E) : is_add_haar_measure b.add_haar := by { rw basis.add_haar, exact measure.is_add_haar_measure_add_haar_measure _ } lemma basis.add_haar_self (b : basis ΞΉ ℝ E) : b.add_haar (parallelepiped b) = 1 := by { rw [basis.add_haar], exact add_haar_measure_self } end normed_space /-- A finite dimensional inner product space has a canonical measure, the Lebesgue measure giving volume `1` to the parallelepiped spanned by any orthonormal basis. We define the measure using some arbitrary choice of orthonormal basis. The fact that it works with any orthonormal basis is proved in `orthonormal_basis.volume_parallelepiped`. -/ @[priority 100] instance measure_space_of_inner_product_space [inner_product_space ℝ E] [finite_dimensional ℝ E] [measurable_space E] [borel_space E] : measure_space E := { volume := (std_orthonormal_basis ℝ E).to_basis.add_haar } /- This instance should not be necessary, but Lean has difficulties to find it in product situations if we do not declare it explicitly. -/ instance real.measure_space : measure_space ℝ := by apply_instance
2362f010055cb4428fa2a453c8718108acdad6b6
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/implicit.lean
82b522bc7a22e0aa852cfdc997e68a81cb6006cb
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
220
lean
import logic definition f {A : Type} {B : Type} (f : A β†’ B β†’ Prop) ⦃C : Type⦄ {R : C β†’ C β†’ Prop} {c : C} (H : R c c) : R c c := H constant g : Prop β†’ Prop β†’ Prop constant H : true ∧ true check f g H
0c52245ad64df4a4fedaf367834b423f7e705399
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/abs/abs_API_test.lean
55bb9af163b0d8e28018225ff980a6d24e8dfa35
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,276
lean
import game.max.level10 open_locale classical noncomputable theory namespace test variables {a b c : ℝ} -- What ℝ has that a general total order hasn't got, is - . example : -a ≀ -b ↔ b ≀ a := by split; intros; linarith def abs (x : ℝ) := max x (-x) -- useful for rewriting lemma abs_def (x : ℝ) : abs x = max x (-x) := rfl -- needs congr' lemma abs_neg (x : ℝ) : abs (-x) = abs x := begin rw abs_def, rw abs_def, rw max_comm, congr', ring, end -- order level 3 -- Powerful. Teaches them the colon. theorem abs_le : abs a ≀ b ↔ -b ≀ a ∧ a ≀ b := begin rw abs_def, rw max_le_iff, split; intro h; cases h; split; linarith, end theorem abs_of_nonneg (h : 0 ≀ a) : abs a = a := begin rw abs_def, apply max_eq_left, linarith end theorem abs_of_nonpos (h : a ≀ 0) : abs a = -a := begin rw abs_def, apply max_eq_right, linarith end variables (a b) -- want them explicit in the next few theorem abs_add : abs (a + b) ≀ abs a + abs b := begin rw abs_le, cases le_total 0 a with h0a ha0, { -- 0 ≀ a rw abs_of_nonneg h0a, cases le_total 0 b with h0b hb0, { rw abs_of_nonneg h0b, split; linarith }, { rw abs_of_nonpos hb0, split; linarith }, }, { -- a ≀ 0 rw abs_of_nonpos ha0, cases le_total 0 b with h0b hb0, { rw abs_of_nonneg h0b, split; linarith }, { rw abs_of_nonpos hb0, split; linarith }, }, end -- order level 4 -- convert makes this simple theorem abs_sub_le_add_abs : abs (a - b) ≀ abs a + abs b := begin rw ←abs_neg b, convert abs_add a (-b), end -- order level 5 -- combination of ring and linarith; always try and deduce from triangle ineq theorem abs_abs_sub_le_abs_sub : abs (abs a - abs b) ≀ abs (a - b) := begin rw abs_le, split, { have h := abs_sub_le_add_abs a (a - b), ring at h, linarith, }, { have h := abs_sub_le_add_abs (a - b) (-b), rw abs_neg at h, ring at h, linarith } end -- order level 2 theorem abs_mul (a b : ℝ) : abs (a * b) = abs a * abs b := begin cases le_total 0 a with h0a ha0; cases le_total 0 b with h0b hb0, { -- both nonnegative rw abs_of_nonneg h0a, rw abs_of_nonneg h0b, rw abs_of_nonneg, nlinarith, }, { -- b <= 0 <= a rw abs_of_nonneg h0a, rw abs_of_nonpos hb0, rw abs_of_nonpos, { ring}, nlinarith, }, { -- a ≀ 0 ≀ b rw abs_of_nonpos ha0, rw abs_of_nonneg h0b, rw abs_of_nonpos, { ring}, nlinarith, }, { -- both nonnegative rw abs_of_nonpos ha0, rw abs_of_nonpos hb0, rw abs_of_nonneg, { ring}, nlinarith, }, end -- order level 6 (unfinished) lemma le_iff_square_le (ha : 0 ≀ a) (hb : 0 ≀ b): a ≀ b ↔ a^2 ≀ b^2 := begin rw (show a^2 ≀ b^2 ↔ 0 ≀ b^2 - a^2, by split; intros; linarith), rw (show b^2 - a^2 = (b + a) * (b - a), by ring), rw (show a ≀ b ↔ 0 ≀ b - a, by split; intros; linarith), -- should be a lemma have hab : 0 ≀ b + a, by linarith, split, { intros, nlinarith}, { intros, by_cases h : b + a = 0, { linarith }, have ha2 : 0 < b + a, { by_contradiction hab, push_neg at hab, apply h, linarith }, sorry } end end test
e1756997684d8602e4e01cea1eb215c9481e162d
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/measure/content.lean
3ecbc9123f914cafcd36cce7c7d1f749982d2e86
[ "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,261
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.measure.measure_space import measure_theory.measure.regular import topology.sets.compacts /-! # Contents In this file we work with *contents*. A content `Ξ»` is a function from a certain class of subsets (such as the compact subsets) to `ℝβ‰₯0` that is * additive: If `K₁` and `Kβ‚‚` are disjoint sets in the domain of `Ξ»`, then `Ξ»(K₁ βˆͺ Kβ‚‚) = Ξ»(K₁) + Ξ»(Kβ‚‚)`; * subadditive: If `K₁` and `Kβ‚‚` are in the domain of `Ξ»`, then `Ξ»(K₁ βˆͺ Kβ‚‚) ≀ Ξ»(K₁) + Ξ»(Kβ‚‚)`; * monotone: If `K₁ βŠ† Kβ‚‚` are in the domain of `Ξ»`, then `Ξ»(K₁) ≀ Ξ»(Kβ‚‚)`. We show that: * Given a content `Ξ»` on compact sets, let us define a function `Ξ»*` on open sets, by letting `Ξ»* U` be the supremum of `Ξ» K` for `K` included in `U`. This is a countably subadditive map that vanishes at `βˆ…`. In Halmos (1950) this is called the *inner content* `Ξ»*` of `Ξ»`, and formalized as `inner_content`. * Given an inner content, we define an outer measure `ΞΌ*`, by letting `ΞΌ* E` be the infimum of `Ξ»* U` over the open sets `U` containing `E`. This is indeed an outer measure. It is formalized as `outer_measure`. * Restricting this outer measure to Borel sets gives a regular measure `ΞΌ`. We define bundled contents as `content`. In this file we only work on contents on compact sets, and inner contents on open sets, and both contents and inner contents map into the extended nonnegative reals. However, in other applications other choices can be made, and it is not a priori clear what the best interface should be. ## Main definitions For `ΞΌ : content G`, we define * `ΞΌ.inner_content` : the inner content associated to `ΞΌ`. * `ΞΌ.outer_measure` : the outer measure associated to `ΞΌ`. * `ΞΌ.measure` : the Borel measure associated to `ΞΌ`. We prove that, on a locally compact space, the measure `ΞΌ.measure` is regular. ## References * Paul Halmos (1950), Measure Theory, Β§53 * <https://en.wikipedia.org/wiki/Content_(measure_theory)> -/ universes u v w noncomputable theory open set topological_space open_locale nnreal ennreal measure_theory namespace measure_theory variables {G : Type w} [topological_space G] /-- A content is an additive function on compact sets taking values in `ℝβ‰₯0`. It is a device from which one can define a measure. -/ structure content (G : Type w) [topological_space G] := (to_fun : compacts G β†’ ℝβ‰₯0) (mono' : βˆ€ (K₁ Kβ‚‚ : compacts G), (K₁ : set G) βŠ† Kβ‚‚ β†’ to_fun K₁ ≀ to_fun Kβ‚‚) (sup_disjoint' : βˆ€ (K₁ Kβ‚‚ : compacts G), disjoint (K₁ : set G) Kβ‚‚ β†’ to_fun (K₁ βŠ” Kβ‚‚) = to_fun K₁ + to_fun Kβ‚‚) (sup_le' : βˆ€ (K₁ Kβ‚‚ : compacts G), to_fun (K₁ βŠ” Kβ‚‚) ≀ to_fun K₁ + to_fun Kβ‚‚) instance : inhabited (content G) := ⟨{ to_fun := Ξ» K, 0, mono' := by simp, sup_disjoint' := by simp, sup_le' := by simp }⟩ /-- Although the `to_fun` field of a content takes values in `ℝβ‰₯0`, we register a coercion to functions taking values in `ℝβ‰₯0∞` as most constructions below rely on taking suprs and infs, which is more convenient in a complete lattice, and aim at constructing a measure. -/ instance : has_coe_to_fun (content G) (Ξ» _, compacts G β†’ ℝβ‰₯0∞) := ⟨λ ΞΌ s, ΞΌ.to_fun s⟩ namespace content variable (ΞΌ : content G) lemma apply_eq_coe_to_fun (K : compacts G) : ΞΌ K = ΞΌ.to_fun K := rfl lemma mono (K₁ Kβ‚‚ : compacts G) (h : (K₁ : set G) βŠ† Kβ‚‚) : ΞΌ K₁ ≀ ΞΌ Kβ‚‚ := by simp [apply_eq_coe_to_fun, ΞΌ.mono' _ _ h] lemma sup_disjoint (K₁ Kβ‚‚ : compacts G) (h : disjoint (K₁ : set G) Kβ‚‚) : ΞΌ (K₁ βŠ” Kβ‚‚) = ΞΌ K₁ + ΞΌ Kβ‚‚ := by simp [apply_eq_coe_to_fun, ΞΌ.sup_disjoint' _ _ h] lemma sup_le (K₁ Kβ‚‚ : compacts G) : ΞΌ (K₁ βŠ” Kβ‚‚) ≀ ΞΌ K₁ + ΞΌ Kβ‚‚ := by { simp only [apply_eq_coe_to_fun], norm_cast, exact ΞΌ.sup_le' _ _ } lemma lt_top (K : compacts G) : ΞΌ K < ∞ := ennreal.coe_lt_top lemma empty : ΞΌ βŠ₯ = 0 := begin have := ΞΌ.sup_disjoint' βŠ₯ βŠ₯, simpa [apply_eq_coe_to_fun] using this, end /-- Constructing the inner content of a content. From a content defined on the compact sets, we obtain a function defined on all open sets, by taking the supremum of the content of all compact subsets. -/ def inner_content (U : opens G) : ℝβ‰₯0∞ := ⨆ (K : compacts G) (h : (K : set G) βŠ† U), ΞΌ K lemma le_inner_content (K : compacts G) (U : opens G) (h2 : (K : set G) βŠ† U) : ΞΌ K ≀ ΞΌ.inner_content U := le_supr_of_le K $ le_supr _ h2 lemma inner_content_le (U : opens G) (K : compacts G) (h2 : (U : set G) βŠ† K) : ΞΌ.inner_content U ≀ ΞΌ K := suprβ‚‚_le $ Ξ» K' hK', ΞΌ.mono _ _ (subset.trans hK' h2) lemma inner_content_of_is_compact {K : set G} (h1K : is_compact K) (h2K : is_open K) : ΞΌ.inner_content ⟨K, h2K⟩ = ΞΌ ⟨K, h1K⟩ := le_antisymm (suprβ‚‚_le $ Ξ» K' hK', ΞΌ.mono _ ⟨K, h1K⟩ hK') (ΞΌ.le_inner_content _ _ subset.rfl) lemma inner_content_bot : ΞΌ.inner_content βŠ₯ = 0 := begin refine le_antisymm _ (zero_le _), rw ←μ.empty, refine suprβ‚‚_le (Ξ» K hK, _), have : K = βŠ₯, { ext1, rw [subset_empty_iff.mp hK, compacts.coe_bot] }, rw this, refl' end /-- This is "unbundled", because that it required for the API of `induced_outer_measure`. -/ lemma inner_content_mono ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V) (h2 : U βŠ† V) : ΞΌ.inner_content ⟨U, hU⟩ ≀ ΞΌ.inner_content ⟨V, hV⟩ := bsupr_mono $ Ξ» K hK, hK.trans h2 lemma inner_content_exists_compact {U : opens G} (hU : ΞΌ.inner_content U β‰  ∞) {Ξ΅ : ℝβ‰₯0} (hΞ΅ : Ξ΅ β‰  0) : βˆƒ K : compacts G, (K : set G) βŠ† U ∧ ΞΌ.inner_content U ≀ ΞΌ K + Ξ΅ := begin have h'Ξ΅ := ennreal.coe_ne_zero.2 hΞ΅, cases le_or_lt (ΞΌ.inner_content U) Ξ΅, { exact ⟨βŠ₯, empty_subset _, le_add_left h⟩ }, have := ennreal.sub_lt_self hU h.ne_bot h'Ξ΅, conv at this {to_rhs, rw inner_content }, simp only [lt_supr_iff] at this, rcases this with ⟨U, h1U, h2U⟩, refine ⟨U, h1U, _⟩, rw [← tsub_le_iff_right], exact le_of_lt h2U end /-- The inner content of a supremum of opens is at most the sum of the individual inner contents. -/ lemma inner_content_Sup_nat [t2_space G] (U : β„• β†’ opens G) : ΞΌ.inner_content (⨆ (i : β„•), U i) ≀ βˆ‘' (i : β„•), ΞΌ.inner_content (U i) := begin have h3 : βˆ€ (t : finset β„•) (K : β„• β†’ compacts G), ΞΌ (t.sup K) ≀ t.sum (Ξ» i, ΞΌ (K i)), { intros t K, refine finset.induction_on t _ _, { simp only [ΞΌ.empty, nonpos_iff_eq_zero, finset.sum_empty, finset.sup_empty], }, { intros n s hn ih, rw [finset.sup_insert, finset.sum_insert hn], exact le_trans (ΞΌ.sup_le _ _) (add_le_add_left ih _) }}, refine suprβ‚‚_le (Ξ» K hK, _), obtain ⟨t, ht⟩ := K.is_compact.elim_finite_subcover _ (Ξ» i, (U i).is_open) _, swap, { rwa [← opens.coe_supr] }, rcases K.is_compact.finite_compact_cover t (coe ∘ U) (Ξ» i _, (U _).is_open) (by simp only [ht]) with ⟨K', h1K', h2K', h3K'⟩, let L : β„• β†’ compacts G := Ξ» n, ⟨K' n, h1K' n⟩, convert le_trans (h3 t L) _, { ext1, rw [compacts.coe_finset_sup, finset.sup_eq_supr], exact h3K' }, refine le_trans (finset.sum_le_sum _) (ennreal.sum_le_tsum t), intros i hi, refine le_trans _ (le_supr _ (L i)), refine le_trans _ (le_supr _ (h2K' i)), refl' end /-- The inner content of a union of sets is at most the sum of the individual inner contents. This is the "unbundled" version of `inner_content_Sup_nat`. It required for the API of `induced_outer_measure`. -/ lemma inner_content_Union_nat [t2_space G] ⦃U : β„• β†’ set G⦄ (hU : βˆ€ (i : β„•), is_open (U i)) : ΞΌ.inner_content βŸ¨β‹ƒ (i : β„•), U i, is_open_Union hU⟩ ≀ βˆ‘' (i : β„•), ΞΌ.inner_content ⟨U i, hU i⟩ := by { have := ΞΌ.inner_content_Sup_nat (Ξ» i, ⟨U i, hU i⟩), rwa [opens.supr_def] at this } lemma inner_content_comap (f : G β‰ƒβ‚œ G) (h : βˆ€ ⦃K : compacts G⦄, ΞΌ (K.map f f.continuous) = ΞΌ K) (U : opens G) : ΞΌ.inner_content (opens.comap f.to_continuous_map U) = ΞΌ.inner_content U := begin refine (compacts.equiv f).surjective.supr_congr _ (Ξ» K, supr_congr_Prop image_subset_iff _), intro hK, simp only [equiv.coe_fn_mk, subtype.mk_eq_mk, ennreal.coe_eq_coe, compacts.equiv], apply h, end @[to_additive] lemma is_mul_left_invariant_inner_content [group G] [topological_group G] (h : βˆ€ (g : G) {K : compacts G}, ΞΌ (K.map _ $ continuous_mul_left g) = ΞΌ K) (g : G) (U : opens G) : ΞΌ.inner_content (opens.comap (homeomorph.mul_left g).to_continuous_map U) = ΞΌ.inner_content U := by convert ΞΌ.inner_content_comap (homeomorph.mul_left g) (Ξ» K, h g) U @[to_additive] lemma inner_content_pos_of_is_mul_left_invariant [t2_space G] [group G] [topological_group G] (h3 : βˆ€ (g : G) {K : compacts G}, ΞΌ (K.map _ $ continuous_mul_left g) = ΞΌ K) (K : compacts G) (hK : ΞΌ K β‰  0) (U : opens G) (hU : (U : set G).nonempty) : 0 < ΞΌ.inner_content U := begin have : (interior (U : set G)).nonempty, rwa [U.is_open.interior_eq], rcases compact_covered_by_mul_left_translates K.2 this with ⟨s, hs⟩, suffices : ΞΌ K ≀ s.card * ΞΌ.inner_content U, { exact (ennreal.mul_pos_iff.mp $ hK.bot_lt.trans_le this).2 }, have : (K : set G) βŠ† ↑⨆ (g ∈ s), opens.comap (homeomorph.mul_left g).to_continuous_map U, { simpa only [opens.supr_def, opens.coe_comap, subtype.coe_mk] }, refine (ΞΌ.le_inner_content _ _ this).trans _, refine (rel_supr_sum (ΞΌ.inner_content) (ΞΌ.inner_content_bot) (≀) (ΞΌ.inner_content_Sup_nat) _ _).trans _, simp only [ΞΌ.is_mul_left_invariant_inner_content h3, finset.sum_const, nsmul_eq_mul, le_refl] end lemma inner_content_mono' ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V) (h2 : U βŠ† V) : ΞΌ.inner_content ⟨U, hU⟩ ≀ ΞΌ.inner_content ⟨V, hV⟩ := bsupr_mono $ Ξ» K hK, hK.trans h2 section outer_measure /-- Extending a content on compact sets to an outer measure on all sets. -/ protected def outer_measure : outer_measure G := induced_outer_measure (Ξ» U hU, ΞΌ.inner_content ⟨U, hU⟩) is_open_empty ΞΌ.inner_content_bot variables [t2_space G] lemma outer_measure_opens (U : opens G) : ΞΌ.outer_measure U = ΞΌ.inner_content U := induced_outer_measure_eq' (Ξ» _, is_open_Union) ΞΌ.inner_content_Union_nat ΞΌ.inner_content_mono U.2 lemma outer_measure_of_is_open (U : set G) (hU : is_open U) : ΞΌ.outer_measure U = ΞΌ.inner_content ⟨U, hU⟩ := ΞΌ.outer_measure_opens ⟨U, hU⟩ lemma outer_measure_le (U : opens G) (K : compacts G) (hUK : (U : set G) βŠ† K) : ΞΌ.outer_measure U ≀ ΞΌ K := (ΞΌ.outer_measure_opens U).le.trans $ ΞΌ.inner_content_le U K hUK lemma le_outer_measure_compacts (K : compacts G) : ΞΌ K ≀ ΞΌ.outer_measure K := begin rw [content.outer_measure, induced_outer_measure_eq_infi], { exact le_infi (Ξ» U, le_infi $ Ξ» hU, le_infi $ ΞΌ.le_inner_content K ⟨U, hU⟩) }, { exact ΞΌ.inner_content_Union_nat }, { exact ΞΌ.inner_content_mono } end lemma outer_measure_eq_infi (A : set G) : ΞΌ.outer_measure A = β¨… (U : set G) (hU : is_open U) (h : A βŠ† U), ΞΌ.inner_content ⟨U, hU⟩ := induced_outer_measure_eq_infi _ ΞΌ.inner_content_Union_nat ΞΌ.inner_content_mono A lemma outer_measure_interior_compacts (K : compacts G) : ΞΌ.outer_measure (interior K) ≀ ΞΌ K := (ΞΌ.outer_measure_opens $ opens.interior K).le.trans $ ΞΌ.inner_content_le _ _ interior_subset lemma outer_measure_exists_compact {U : opens G} (hU : ΞΌ.outer_measure U β‰  ∞) {Ξ΅ : ℝβ‰₯0} (hΞ΅ : Ξ΅ β‰  0) : βˆƒ K : compacts G, (K : set G) βŠ† U ∧ ΞΌ.outer_measure U ≀ ΞΌ.outer_measure K + Ξ΅ := begin rw [ΞΌ.outer_measure_opens] at hU ⊒, rcases ΞΌ.inner_content_exists_compact hU hΞ΅ with ⟨K, h1K, h2K⟩, exact ⟨K, h1K, le_trans h2K $ add_le_add_right (ΞΌ.le_outer_measure_compacts K) _⟩, end lemma outer_measure_exists_open {A : set G} (hA : ΞΌ.outer_measure A β‰  ∞) {Ξ΅ : ℝβ‰₯0} (hΞ΅ : Ξ΅ β‰  0) : βˆƒ U : opens G, A βŠ† U ∧ ΞΌ.outer_measure U ≀ ΞΌ.outer_measure A + Ξ΅ := begin rcases induced_outer_measure_exists_set _ _ ΞΌ.inner_content_mono hA (ennreal.coe_ne_zero.2 hΞ΅) with ⟨U, hU, h2U, h3U⟩, exact ⟨⟨U, hU⟩, h2U, h3U⟩, swap, exact ΞΌ.inner_content_Union_nat end lemma outer_measure_preimage (f : G β‰ƒβ‚œ G) (h : βˆ€ ⦃K : compacts G⦄, ΞΌ (K.map f f.continuous) = ΞΌ K) (A : set G) : ΞΌ.outer_measure (f ⁻¹' A) = ΞΌ.outer_measure A := begin refine induced_outer_measure_preimage _ ΞΌ.inner_content_Union_nat ΞΌ.inner_content_mono _ (Ξ» s, f.is_open_preimage) _, intros s hs, convert ΞΌ.inner_content_comap f h ⟨s, hs⟩ end lemma outer_measure_lt_top_of_is_compact [locally_compact_space G] {K : set G} (hK : is_compact K) : ΞΌ.outer_measure K < ∞ := begin rcases exists_compact_superset hK with ⟨F, h1F, h2F⟩, calc ΞΌ.outer_measure K ≀ ΞΌ.outer_measure (interior F) : outer_measure.mono' _ h2F ... ≀ ΞΌ ⟨F, h1F⟩ : by apply ΞΌ.outer_measure_le ⟨interior F, is_open_interior⟩ ⟨F, h1F⟩ interior_subset ... < ⊀ : ΞΌ.lt_top _ end @[to_additive] lemma is_mul_left_invariant_outer_measure [group G] [topological_group G] (h : βˆ€ (g : G) {K : compacts G}, ΞΌ (K.map _ $ continuous_mul_left g) = ΞΌ K) (g : G) (A : set G) : ΞΌ.outer_measure ((Ξ» h, g * h) ⁻¹' A) = ΞΌ.outer_measure A := by convert ΞΌ.outer_measure_preimage (homeomorph.mul_left g) (Ξ» K, h g) A lemma outer_measure_caratheodory (A : set G) : measurable_set[ΞΌ.outer_measure.caratheodory] A ↔ βˆ€ (U : opens G), ΞΌ.outer_measure (U ∩ A) + ΞΌ.outer_measure (U \ A) ≀ ΞΌ.outer_measure U := begin rw [opens.forall], apply induced_outer_measure_caratheodory, apply inner_content_Union_nat, apply inner_content_mono' end @[to_additive] lemma outer_measure_pos_of_is_mul_left_invariant [group G] [topological_group G] (h3 : βˆ€ (g : G) {K : compacts G}, ΞΌ (K.map _ $ continuous_mul_left g) = ΞΌ K) (K : compacts G) (hK : ΞΌ K β‰  0) {U : set G} (h1U : is_open U) (h2U : U.nonempty) : 0 < ΞΌ.outer_measure U := by { convert ΞΌ.inner_content_pos_of_is_mul_left_invariant h3 K hK ⟨U, h1U⟩ h2U, exact ΞΌ.outer_measure_opens ⟨U, h1U⟩ } variables [S : measurable_space G] [borel_space G] include S /-- For the outer measure coming from a content, all Borel sets are measurable. -/ lemma borel_le_caratheodory : S ≀ ΞΌ.outer_measure.caratheodory := begin rw [@borel_space.measurable_eq G _ _], refine measurable_space.generate_from_le _, intros U hU, rw ΞΌ.outer_measure_caratheodory, intro U', rw ΞΌ.outer_measure_of_is_open ((U' : set G) ∩ U) (U'.is_open.inter hU), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {L : compacts G // (L : set G) βŠ† U' ∩ U} := ⟨⟨βŠ₯, empty_subset _⟩⟩, rw [ennreal.supr_add], refine supr_le _, rintro ⟨L, hL⟩, simp only [subset_inter_iff] at hL, have : ↑U' \ U βŠ† U' \ L := diff_subset_diff_right hL.2, refine le_trans (add_le_add_left (ΞΌ.outer_measure.mono' this) _) _, rw ΞΌ.outer_measure_of_is_open (↑U' \ L) (is_open.sdiff U'.2 L.2.is_closed), simp only [inner_content, supr_subtype'], rw [opens.coe_mk], haveI : nonempty {M : compacts G // (M : set G) βŠ† ↑U' \ L} := ⟨⟨βŠ₯, empty_subset _⟩⟩, rw [ennreal.add_supr], refine supr_le _, rintro ⟨M, hM⟩, simp only [subset_diff] at hM, have : (↑(L βŠ” M) : set G) βŠ† U', { simp only [union_subset_iff, compacts.coe_sup, hM, hL, and_self] }, rw ΞΌ.outer_measure_of_is_open ↑U' U'.2, refine le_trans (ge_of_eq _) (ΞΌ.le_inner_content _ _ this), exact ΞΌ.sup_disjoint _ _ hM.2.symm, end /-- The measure induced by the outer measure coming from a content, on the Borel sigma-algebra. -/ protected def measure : measure G := ΞΌ.outer_measure.to_measure ΞΌ.borel_le_caratheodory lemma measure_apply {s : set G} (hs : measurable_set s) : ΞΌ.measure s = ΞΌ.outer_measure s := to_measure_apply _ _ hs /-- In a locally compact space, any measure constructed from a content is regular. -/ instance regular [locally_compact_space G] : ΞΌ.measure.regular := begin haveI : ΞΌ.measure.outer_regular, { refine ⟨λ A hA r (hr : _ < _), _⟩, rw [ΞΌ.measure_apply hA, outer_measure_eq_infi] at hr, simp only [infi_lt_iff] at hr, rcases hr with ⟨U, hUo, hAU, hr⟩, rw [← ΞΌ.outer_measure_of_is_open U hUo, ← ΞΌ.measure_apply hUo.measurable_set] at hr, exact ⟨U, hAU, hUo, hr⟩ }, haveI : is_finite_measure_on_compacts ΞΌ.measure, { refine ⟨λ K hK, _⟩, rw [measure_apply _ hK.measurable_set], exact ΞΌ.outer_measure_lt_top_of_is_compact hK }, refine ⟨λ U hU r hr, _⟩, rw [measure_apply _ hU.measurable_set, ΞΌ.outer_measure_of_is_open U hU] at hr, simp only [inner_content, lt_supr_iff] at hr, rcases hr with ⟨K, hKU, hr⟩, refine ⟨K, hKU, K.2, hr.trans_le _⟩, exact (ΞΌ.le_outer_measure_compacts K).trans (le_to_measure_apply _ _ _) end end outer_measure section regular_contents /-- A content `ΞΌ` is called regular if for every compact set `K`, `ΞΌ(K) = inf {ΞΌ(K') : K βŠ‚ int K' βŠ‚ K'`. See Paul Halmos (1950), Measure Theory, Β§54-/ def content_regular := βˆ€ ⦃K : topological_space.compacts G⦄, ΞΌ K = β¨… (K' : topological_space.compacts G) (hK: (K : set G) βŠ† interior (K' : set G) ), ΞΌ K' lemma content_regular_exists_compact (H : content_regular ΞΌ) (K : topological_space.compacts G) {Ξ΅ : nnreal} (hΞ΅ : Ξ΅ β‰  0) : βˆƒ (K' : topological_space.compacts G), (K.carrier βŠ† interior K'.carrier) ∧ ΞΌ K' ≀ ΞΌ K + Ξ΅ := begin by_contra hc, simp only [not_exists, not_and, not_le] at hc, have lower_bound_infi : ΞΌ K + Ξ΅ ≀ β¨… (K' : topological_space.compacts G) (h: (K : set G) βŠ† interior (K' : set G) ), ΞΌ K' := le_infi (Ξ» K', le_infi ( Ξ» K'_hyp, le_of_lt (hc K' K'_hyp))), rw ← H at lower_bound_infi, exact (lt_self_iff_false (ΞΌ K)).mp (lt_of_le_of_lt' lower_bound_infi (ennreal.lt_add_right (ne_top_of_lt (ΞΌ.lt_top K)) (ennreal.coe_ne_zero.mpr hΞ΅))), end variables [measurable_space G] [t2_space G] [borel_space G] /--If `ΞΌ` is a regular content, then the measure induced by `ΞΌ` will agree with `ΞΌ` on compact sets.-/ lemma measure_eq_content_of_regular (H : measure_theory.content.content_regular ΞΌ) (K : topological_space.compacts G) : ΞΌ.measure ↑K = ΞΌ K := begin refine le_antisymm _ _, { apply ennreal.le_of_forall_pos_le_add, intros Ξ΅ Ξ΅pos content_K_finite, obtain ⟨ K', K'_hyp ⟩ := content_regular_exists_compact ΞΌ H K (ne_bot_of_gt Ξ΅pos), calc ΞΌ.measure ↑K ≀ ΞΌ.measure (interior ↑K') : _ ... ≀ ΞΌ K' : _ ... ≀ ΞΌ K + Ξ΅ : K'_hyp.right, { rw [ΞΌ.measure_apply ((is_open_interior).measurable_set), ΞΌ.measure_apply K.is_compact.measurable_set], exact ΞΌ.outer_measure.mono K'_hyp.left }, { rw ΞΌ.measure_apply (is_open.measurable_set is_open_interior), exact ΞΌ.outer_measure_interior_compacts K' } }, { rw (ΞΌ.measure_apply (is_compact.measurable_set K.is_compact)), exact ΞΌ.le_outer_measure_compacts K }, end end regular_contents end content end measure_theory
72d94c73be32d7d6203f9cf0990db3bfa670b9c4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/testing/slim_check/gen.lean
d0e76abcadf900b5a3af311f181abe9254692416
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,820
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 control.random import control.uliftable import data.list.big_operators.lemmas import data.list.perm /-! # `gen` Monad > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This monad is used to formulate randomized computations with a parameter to specify the desired size of the result. This is a port of the Haskell QuickCheck library. ## Main definitions * `gen` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universes u v namespace slim_check /-- Monad to generate random examples to test properties with. It has a `nat` parameter so that the caller can decide on the size of the examples. -/ @[reducible, derive [monad, is_lawful_monad]] def gen (Ξ± : Type u) := reader_t (ulift β„•) rand Ξ± variable (Ξ± : Type u) local infix ` .. `:41 := set.Icc /-- Execute a `gen` inside the `io` monad using `i` as the example size and with a fresh random number generator. -/ def io.run_gen {Ξ±} (x : gen Ξ±) (i : β„•) : io Ξ± := io.run_rand (x.run ⟨i⟩) namespace gen section rand /-- Lift `random.random` to the `gen` monad. -/ def choose_any [random Ξ±] : gen Ξ± := ⟨ Ξ» _, rand.random Ξ± ⟩ variables {Ξ±} [preorder Ξ±] /-- Lift `random.random_r` to the `gen` monad. -/ def choose [bounded_random Ξ±] (x y : Ξ±) (p : x ≀ y) : gen (x .. y) := ⟨ Ξ» _, rand.random_r x y p ⟩ end rand open nat /-- Generate a `nat` example between `x` and `y`. -/ def choose_nat (x y : β„•) (p : x ≀ y) : gen (x .. y) := choose x y p /-- Generate a `nat` example between `x` and `y`. -/ def choose_nat' (x y : β„•) (p : x < y) : gen (set.Ico x y) := have βˆ€ i, x < i β†’ i ≀ y β†’ i.pred < y, from Ξ» i hβ‚€ h₁, show i.pred.succ ≀ y, by rwa succ_pred_eq_of_pos; apply lt_of_le_of_lt (nat.zero_le _) hβ‚€, subtype.map pred (Ξ» i (h : x+1 ≀ i ∧ i ≀ y), ⟨le_pred_of_lt h.1, this _ h.1 h.2⟩) <$> choose (x+1) y p open nat instance : uliftable gen.{u} gen.{v} := reader_t.uliftable' (equiv.ulift.trans equiv.ulift.symm) instance : has_orelse gen.{u} := ⟨ Ξ» Ξ± x y, do b ← uliftable.up $ choose_any bool, if b.down then x else y ⟩ variable {Ξ±} /-- Get access to the size parameter of the `gen` monad. For reasons of universe polymorphism, it is specified in continuation passing style. -/ def sized (cmd : β„• β†’ gen Ξ±) : gen Ξ± := ⟨ Ξ» ⟨sz⟩, reader_t.run (cmd sz) ⟨sz⟩ ⟩ /-- Apply a function to the size parameter. -/ def resize (f : β„• β†’ β„•) (cmd : gen Ξ±) : gen Ξ± := ⟨ Ξ» ⟨sz⟩, reader_t.run cmd ⟨f sz⟩ ⟩ /-- Create `n` examples using `cmd`. -/ def vector_of : βˆ€ (n : β„•) (cmd : gen Ξ±), gen (vector Ξ± n) | 0 _ := return vector.nil | (succ n) cmd := vector.cons <$> cmd <*> vector_of n cmd /-- Create a list of examples using `cmd`. The size is controlled by the size parameter of `gen`. -/ def list_of (cmd : gen Ξ±) : gen (list Ξ±) := sized $ Ξ» sz, do do ⟨ n ⟩ ← uliftable.up $ choose_nat 0 (sz + 1) dec_trivial, v ← vector_of n.val cmd, return v.to_list open ulift /-- Given a list of example generators, choose one to create an example. -/ def one_of (xs : list (gen Ξ±)) (pos : 0 < xs.length) : gen Ξ± := do ⟨⟨n, h, h'⟩⟩ ← uliftable.up $ choose_nat' 0 xs.length pos, list.nth_le xs n h' /-- Given a list of example generators, choose one to create an example. -/ def elements (xs : list Ξ±) (pos : 0 < xs.length) : gen Ξ± := do ⟨⟨n,hβ‚€,hβ‚βŸ©βŸ© ← uliftable.up $ choose_nat' 0 xs.length pos, pure $ list.nth_le xs n h₁ /-- `freq_aux xs i _` takes a weighted list of generator and a number meant to select one of the generators. If we consider `freq_aux [(1, gena), (3, genb), (5, genc)] 4 _`, we choose a generator by splitting the interval 1-9 into 1-1, 2-4, 5-9 so that the width of each interval corresponds to one of the number in the list of generators. Then, we check which interval 4 falls into: it selects `genb`. -/ def freq_aux : Ξ  (xs : list (β„•+ Γ— gen Ξ±)) i, i < (xs.map (subtype.val ∘ prod.fst)).sum β†’ gen Ξ± | [] i h := false.elim (nat.not_lt_zero _ h) | ((i, x) :: xs) j h := if h' : j < i then x else freq_aux xs (j - i) (by { rw tsub_lt_iff_right (le_of_not_gt h'), simpa [list.sum_cons, add_comm] using h }) /-- `freq [(1, gena), (3, genb), (5, genc)] _` will choose one of `gena`, `genb`, `genc` with probabilities proportional to the number accompanying them. In this example, the sum of those numbers is 9, `gena` will be chosen with probability ~1/9, `genb` with ~3/9 (i.e. 1/3) and `genc` with probability 5/9. -/ def freq (xs : list (β„•+ Γ— gen Ξ±)) (pos : 0 < xs.length) : gen Ξ± := let s := (xs.map (subtype.val ∘ prod.fst)).sum in have ha : 1 ≀ s, from (le_trans pos $ list.length_map (subtype.val ∘ prod.fst) xs β–Έ (list.length_le_sum_of_one_le _ (Ξ» i, by { simp, intros, assumption }))), have 0 ≀ s - 1, from le_tsub_of_add_le_right ha, uliftable.adapt_up gen.{0} gen.{u} (choose_nat 0 (s-1) this) $ Ξ» i, freq_aux xs i.1 (by rcases i with ⟨i,hβ‚€,hβ‚βŸ©; rwa le_tsub_iff_right at h₁; exact ha) /-- Generate a random permutation of a given list. -/ def permutation_of {Ξ± : Type u} : Ξ  xs : list Ξ±, gen (subtype $ list.perm xs) | [] := pure ⟨[], list.perm.nil ⟩ | (x :: xs) := do ⟨xs',h⟩ ← permutation_of xs, ⟨⟨n,_,h'⟩⟩ ← uliftable.up $ choose_nat 0 xs'.length dec_trivial, pure ⟨list.insert_nth n x xs', list.perm.trans (list.perm.cons _ h) (list.perm_insert_nth _ _ h').symm ⟩ end gen end slim_check
e963daf3855ffcc97ea991238b10319e53840edc
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/compiler/array_test2.lean
de5ff83c341e0110d0b75a177f4995899de25cdc
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
450
lean
def check (b : Bool) : IO Unit := unless b $ IO.println "failed" def main : IO Unit := let a1 := [2, 3, 5].toArray in let a2 := [4, 7, 9].toArray in let a3 := [4, 7, 8].toArray in do check (Array.isEqv a1 a2 (fun v w => v % 2 == w % 2)); check (!Array.isEqv a1 a3 (fun v w => v % 2 == w % 2)); check (a1 ++ a2 == [2, 3, 5, 4, 7, 9].toArray); check (a1.any (fun a => a > 4)); check (!a1.any (fun a => a >10)); check (a1.all (fun a => a < 10))
acda4e4f7a7487782d405c4e0c6e1463a4b6466c
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/propositional_logic/precedence/propositional_logic_syntax_and_semantics.lean
253707b8148a19e19070ad1c86594799d3e22c28
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
1,204
lean
inductive var : Type | mk : β„• β†’ var -- SYNTAX inductive pExp : Type | pTrue : pExp | pFalse : pExp | pVar : var β†’ pExp | pNot : pExp β†’ pExp | pAnd : pExp β†’ pExp β†’ pExp | pOr : pExp β†’ pExp β†’ pExp | pImp : pExp β†’ pExp β†’ pExp | pIff : pExp β†’ pExp β†’ pExp | pXor : pExp β†’ pExp β†’ pExp -- Utility function def bimp : bool β†’ bool β†’ bool | tt tt := tt | tt ff := ff | ff tt := tt | ff ff := tt def biff : bool β†’ bool β†’ bool | tt tt := tt | tt ff := ff | ff tt := ff | ff ff := tt open pExp -- ABSTRACT SEMANTICS def pEval : pExp β†’ (var β†’ bool) β†’ bool | pTrue _ := tt | pFalse _ := ff | (pVar v) i := i v | (pNot e) i := bnot (pEval e i) | (pAnd e1 e2) i := band (pEval e1 i) (pEval e2 i) | (pOr e1 e2) i := bor (pEval e1 i) (pEval e2 i) | (pImp e1 e2) i := bimp (pEval e1 i) (pEval e2 i) | (pIff e1 e2) i := biff (pEval e1 i) (pEval e2 i) | (pXor e1 e2) i := xor (pEval e1 i) (pEval e2 i) -- CONCRETE SYNTAX ("syntactic sugar") notation e1 ∧ e2 := pAnd e1 e2 --desugaring notation e1 ∨ e2 := pOr e1 e2 notation Β¬ e := pNot e -- notation e1 > e2 := pImp e1 e2 infixr ` >> ` : 25 := pImp notation e1 ↔ e2 := pIff e1 e2 notation e1 βŠ• e2 := pXor e1 e2
b3d52c07fe325b5e56a06ab6724417ea6be33822
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/holor.lean
86e226a66904f54735f01a6db216dfcbdc7b857e
[ "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
14,760
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import algebra.module.pi import algebra.big_operators.basic /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list β„•`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor Ξ± ds₁` and `xβ‚‚ : holor Ξ± dsβ‚‚` is the holor given by `(x₁ βŠ— xβ‚‚) (i₁ ++ iβ‚‚) = x₁ i₁ * xβ‚‚ iβ‚‚`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ universes u open list open_locale big_operators /-- `holor_index ds` is the type of valid index tuples used to identify an entry of a holor of dimensions `ds`. -/ def holor_index (ds : list β„•) : Type := {is : list β„• // forallβ‚‚ (<) is ds} namespace holor_index variables {ds₁ dsβ‚‚ ds₃ : list β„•} def take : Ξ  {ds₁ : list β„•}, holor_index (ds₁ ++ dsβ‚‚) β†’ holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forallβ‚‚_take_append is.1 ds dsβ‚‚ is.2 ⟩ def drop : Ξ  {ds₁ : list β„•}, holor_index (ds₁ ++ dsβ‚‚) β†’ holor_index dsβ‚‚ | ds is := ⟨ list.drop (length ds) is.1, forallβ‚‚_drop_append is.1 ds dsβ‚‚ is.2 ⟩ lemma cast_type (is : list β„•) (eq : ds₁ = dsβ‚‚) (h : forallβ‚‚ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ dsβ‚‚ ++ ds₃) β†’ holor_index (ds₁ ++ (dsβ‚‚ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ dsβ‚‚ ds₃)) def assoc_left : holor_index (ds₁ ++ (dsβ‚‚ ++ ds₃)) β†’ holor_index (ds₁ ++ dsβ‚‚ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ dsβ‚‚ ds₃).symm) lemma take_take : βˆ€ t : holor_index (ds₁ ++ dsβ‚‚ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq $ by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left] lemma drop_take : βˆ€ t : holor_index (ds₁ ++ dsβ‚‚ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : βˆ€ t : holor_index (ds₁ ++ dsβ‚‚ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (Ξ± : Type u) (ds : list β„•) := holor_index ds β†’ Ξ± namespace holor variables {Ξ± : Type} {d : β„•} {ds : list β„•} {ds₁ : list β„•} {dsβ‚‚ : list β„•} {ds₃ : list β„•} instance [inhabited Ξ±] : inhabited (holor Ξ± ds) := ⟨λ t, default⟩ instance [has_zero Ξ±] : has_zero (holor Ξ± ds) := ⟨λ t, 0⟩ instance [has_add Ξ±] : has_add (holor Ξ± ds) := ⟨λ x y t, x t + y t⟩ instance [has_neg Ξ±] : has_neg (holor Ξ± ds) := ⟨λ a t, - a t⟩ instance [add_semigroup Ξ±] : add_semigroup (holor Ξ± ds) := by refine_struct { add := (+), .. }; tactic.pi_instance_derive_field instance [add_comm_semigroup Ξ±] : add_comm_semigroup (holor Ξ± ds) := by refine_struct { add := (+), .. }; tactic.pi_instance_derive_field instance [add_monoid Ξ±] : add_monoid (holor Ξ± ds) := by refine_struct { zero := (0 : holor Ξ± ds), add := (+), nsmul := Ξ» n x i, n β€’ (x i) }; tactic.pi_instance_derive_field instance [add_comm_monoid Ξ±] : add_comm_monoid (holor Ξ± ds) := by refine_struct { zero := (0 : holor Ξ± ds), add := (+), nsmul := add_monoid.nsmul }; tactic.pi_instance_derive_field instance [add_group Ξ±] : add_group (holor Ξ± ds) := by refine_struct { zero := (0 : holor Ξ± ds), add := (+), nsmul := add_monoid.nsmul, zsmul := Ξ» n x i, n β€’ (x i) }; tactic.pi_instance_derive_field instance [add_comm_group Ξ±] : add_comm_group (holor Ξ± ds) := by refine_struct { zero := (0 : holor Ξ± ds), add := (+), nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field /- scalar product -/ instance [has_mul Ξ±] : has_smul Ξ± (holor Ξ± ds) := ⟨λ a x, Ξ» t, a * x t⟩ instance [semiring Ξ±] : module Ξ± (holor Ξ± ds) := pi.module _ _ _ /-- The tensor product of two holors. -/ def mul [s : has_mul Ξ±] (x : holor Ξ± ds₁) (y : holor Ξ± dsβ‚‚) : holor Ξ± (ds₁ ++ dsβ‚‚) := Ξ» t, x (t.take) * y (t.drop) local infix ` βŠ— ` : 70 := mul lemma cast_type (eq : ds₁ = dsβ‚‚) (a : holor Ξ± ds₁) : cast (congr_arg (holor Ξ±) eq) a = (Ξ» t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor Ξ± (ds₁ ++ dsβ‚‚ ++ ds₃) β†’ holor Ξ± (ds₁ ++ (dsβ‚‚ ++ ds₃)) := cast (congr_arg (holor Ξ±) (append_assoc ds₁ dsβ‚‚ ds₃)) def assoc_left : holor Ξ± (ds₁ ++ (dsβ‚‚ ++ ds₃)) β†’ holor Ξ± (ds₁ ++ dsβ‚‚ ++ ds₃) := cast (congr_arg (holor Ξ±) (append_assoc ds₁ dsβ‚‚ ds₃).symm) lemma mul_assoc0 [semigroup Ξ±] (x : holor Ξ± ds₁) (y : holor Ξ± dsβ‚‚) (z : holor Ξ± ds₃) : x βŠ— y βŠ— z = (x βŠ— (y βŠ— z)).assoc_left := funext (assume t : holor_index (ds₁ ++ dsβ‚‚ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup Ξ±] (x : holor Ξ± ds₁) (y : holor Ξ± dsβ‚‚) (z : holor Ξ± ds₃) : mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib Ξ±] (x : holor Ξ± ds₁) (y : holor Ξ± dsβ‚‚) (z : holor Ξ± dsβ‚‚) : x βŠ— (y + z) = x βŠ— y + x βŠ— z := funext (Ξ»t, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib Ξ±] (x : holor Ξ± ds₁) (y : holor Ξ± ds₁) (z : holor Ξ± dsβ‚‚) : (x + y) βŠ— z = x βŠ— z + y βŠ— z := funext $ Ξ»t, add_mul (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t)) @[simp] lemma zero_mul {Ξ± : Type} [ring Ξ±] (x : holor Ξ± dsβ‚‚) : (0 : holor Ξ± ds₁) βŠ— x = 0 := funext (Ξ» t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {Ξ± : Type} [ring Ξ±] (x : holor Ξ± ds₁) : x βŠ— (0 :holor Ξ± dsβ‚‚) = 0 := funext (Ξ» t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid Ξ±] (x : holor Ξ± []) (y : holor Ξ± ds) : x βŠ— y = x ⟨[], forallβ‚‚.nil⟩ β€’ y := by simp [mul, has_smul.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor Ξ± (d :: ds)) (i : β„•) (h : i < d) : holor Ξ± ds := (Ξ» is : holor_index ds, x ⟨ i :: is.1, forallβ‚‚.cons h is.2⟩) /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec [monoid Ξ±] [add_monoid Ξ±] (d : β„•) (j : β„•) : holor Ξ± [d] := Ξ» ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) β†’ Prop) : Ξ  (t : holor_index (d :: ds)), (βˆ€ i is, Ξ  h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) β†’ p t | ⟨[], hforallβ‚‚βŸ© hp := absurd (forallβ‚‚_nil_left_iff.1 hforallβ‚‚) (cons_ne_nil d ds) | ⟨(i :: is), hforallβ‚‚βŸ© hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor Ξ± (d :: ds)) (y : holor Ξ± (d :: ds)) (h : slice x = slice y) : x = y := funext $ Ξ» t : holor_index (d :: ds), holor_index_cons_decomp (Ξ» t, x t = y t) t $ Ξ» i is hiis, have hiisdds: forallβ‚‚ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forallβ‚‚_cons.1 hiisdds).1, have hisds: forallβ‚‚ (<) is ds, from (forallβ‚‚_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (Ξ» t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (Ξ» t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring Ξ±] {i : β„•} {j : β„•} (hid : i < d) (x : holor Ξ± ds) : slice (unit_vec d j βŠ— x) i hid = if i=j then x else 0 := funext $ Ξ» t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add Ξ±] (i : β„•) (hid : i < d) (x : holor Ξ± (d :: ds)) (y : holor Ξ± (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext (Ξ» t, by simp [slice,(+)]) lemma slice_zero [has_zero Ξ±] (i : β„•) (hid : i < d) : slice (0 : holor Ξ± (d :: ds)) i hid = 0 := rfl lemma slice_sum [add_comm_monoid Ξ±] {Ξ² : Type} (i : β„•) (hid : i < d) (s : finset Ξ²) (f : Ξ² β†’ holor Ξ± (d :: ds)) : βˆ‘ x in s, slice (f x) i hid = slice (βˆ‘ x in s, f x) i hid := begin letI := classical.dec_eq Ξ², refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring Ξ±] (x : holor Ξ± (d :: ds)) : βˆ‘ i in (finset.range d).attach, unit_vec d i βŠ— slice x i (nat.succ_le_of_lt (finset.mem_range.1 i.prop)) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i $ finset.mem_range.2 hid), { simp }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b β‰  ⟨i, _⟩), have hbi' : i β‰  b, { simpa only [ne.def, subtype.ext_iff, subtype.coe_mk] using hbi.symm }, simp [hbi'] }, { assume hid' : subtype.mk i _ βˆ‰ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 [has_mul Ξ±]: Ξ  {ds}, holor Ξ± ds β†’ Prop | nil (x : holor Ξ± []) : cprank_max1 x | cons {d} {ds} (x : holor Ξ± [d]) (y : holor Ξ± ds) : cprank_max1 y β†’ cprank_max1 (x βŠ— y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max [has_mul Ξ±] [add_monoid Ξ±] : β„• β†’ Ξ  {ds}, holor Ξ± ds β†’ Prop | zero {ds} : cprank_max 0 (0 : holor Ξ± ds) | succ n {ds} (x : holor Ξ± ds) (y : holor Ξ± ds) : cprank_max1 x β†’ cprank_max n y β†’ cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid Ξ±] [add_monoid Ξ±] (x : holor Ξ± nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid Ξ±] [add_monoid Ξ±] {x : holor Ξ± ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid Ξ±] [add_monoid Ξ±]: βˆ€ {m : β„•} {n : β„•} {x : holor Ξ± ds} {y : holor Ξ± ds}, cprank_max m x β†’ cprank_max n y β†’ cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ xβ‚‚ hx₁ hxβ‚‚) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hxβ‚‚ hy } end lemma cprank_max_mul [ring Ξ±] : βˆ€ (n : β„•) (x : holor Ξ± [d]) (y : holor Ξ± ds), cprank_max n y β†’ cprank_max n (x βŠ— y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ yβ‚‚ hy₁ hyβ‚‚) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x yβ‚‚ hyβ‚‚ } end lemma cprank_max_sum [ring Ξ±] {Ξ²} {n : β„•} (s : finset Ξ²) (f : Ξ² β†’ holor Ξ± ds) : (βˆ€ x ∈ s, cprank_max n (f x)) β†’ cprank_max (s.card * n) (βˆ‘ x in s, f x) := by letI := classical.dec_eq Ξ²; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x βˆ‰ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s, finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (βˆ‘ x in s, f x), { apply ih, assume (x : Ξ²) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring Ξ±] : Ξ  {ds}, βˆ€ x : holor Ξ± ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Ξ  (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 βŠ— slice x i.1 (mem_range.1 i.2)), from Ξ» i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (βˆ‘ i in finset.attach (finset.range d), unit_vec d (i.val)βŠ—slice x (i.val) (mem_range.1 i.2)), from cprank_max_sum (finset.range d).attach _ (Ξ» i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (βˆ‘ i in finset.attach (finset.range d), unit_vec d (i.val)βŠ—slice x (i.val) (mem_range.1 i.2)), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [ring Ξ±] (x : holor Ξ± ds) : nat := @nat.find (Ξ» n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring Ξ±] : Ξ  {ds}, βˆ€ x : holor Ξ± ds, cprank x ≀ ds.prod := Ξ» ds (x : holor Ξ± ds), by letI := classical.dec_pred (Ξ» (n : β„•), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (Ξ» n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
bdd1d70ac1b7d20c6e5f13d4bb0357b9bc8204e3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/simpDefToUnfold.lean
62da0f7912eb25ef1cd947b94a744ff70143d33c
[ "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
382
lean
@[simp] def f (x : Nat) := x + 1 @[simp] def g (x : Nat) := id x def h (x : Nat) := g (g x) namespace Extra attribute [scoped simp] h end Extra theorem ex1 : f (g (h x)) = x + 1 := by simp -- did not unfold h simp [h] theorem ex2 : f (g (h x)) = x + 1 := by open Extra in simp -- unfold f,g,h theorem ex3 : f (g x) = x + 1 := by simp [-f] -- did not unfold f simp
96d4aa7fb3bd0179b55660668c2e2649aaf1529f
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/hw6_quiz/hw6_quiz.lean
922afbf6106d601efe2624c37be862f23b5ec1e4
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
3,268
lean
/- Justin Ngo jmn4fms 2/25/20 Sullivan 2102-001 -/ -- Answers to Y/N questions at bottom of file /-inductive var : Type | P | Q | R open var-/ inductive var : Type | mk : β„• β†’ var def V_0 := var.mk 0 def V_1 := var.mk 1 def V_2 := var.mk 2 -- variables indexed by natural numbers inductive pExp : Type | pTrue : pExp | pFalse : pExp | pNot : pExp β†’ pExp | pAnd : pExp β†’ pExp β†’ pExp | pOr : pExp β†’ pExp β†’ pExp | pImp : pExp β†’ pExp β†’ pExp | pFol : pExp β†’ pExp β†’ pExp | pVar : var β†’ pExp | pIff : pExp β†’ pExp β†’ pExp open pExp def band' : bool β†’ bool β†’ bool | tt tt := tt | tt ff := ff | ff tt := ff | ff ff := ff -- or def bor' : bool β†’ bool β†’ bool | tt tt := tt | tt ff := tt | ff tt := tt | ff ff := ff -- implies def bimp : bool β†’ bool β†’ bool | tt tt := tt | tt ff := ff | ff tt := tt | ff ff := tt -- follows def bfol : bool β†’ bool β†’ bool | tt tt := tt | tt ff := tt | ff tt := ff | ff ff := ff -- if and only if (iff) def biff : bool β†’ bool β†’ bool | tt tt := tt | ff ff := tt | _ _ := ff /- An interpretation is a mapping i.e, a function, from variables to a boolean "meanings" (values) -/ def interp_all_false: var β†’ bool | _ := ff def pEval : pExp β†’ (var β†’ bool) β†’ bool | pTrue _ := tt | pFalse _ := ff /- | (pVar P) := tt | (pVar Q) := ff | (pVar R) := tt -/ |(pVar v) i := i v -- what variable v means comes from the interpretation | (pNot e) i := bnot (pEval e i) | (pAnd e1 e2) i := band (pEval e1 i) (pEval e2 i) | (pOr e1 e2) i := bor (pEval e1 i) (pEval e2 i) | (pImp e1 e2) i := bimp (pEval e1 i) (pEval e2 i) | (pFol e1 e2) i := bfol (pEval e1 i) (pEval e2 i) | (pIff e1 e2) i := biff (pEval e1 i) (pEval e2 i) -- P ↔ Q (if and only if \iff) -- tt tt tt -- ff ff tt -- _ _ ff #eval pEval pTrue #eval pEval pFalse #eval pEval (pNot pTrue) #eval pEval (pNot pFalse) def p1 := pTrue def p2 := pFalse def p25 := pNot p2 def p3 := pAnd pTrue pFalse def p4 := pOr p3 p2 #eval pEval p3 #eval pEval p4 #eval pEval (pImp p3 p4) -- Variable expressions def P := V_0 def Q := V_1 def R := V_2 def p5 := pVar P def p6 := pOr (pVar P) (pVar Q) def p7 := pAnd (pOr (pVar P) (pVar Q)) (pNot (pVar Q)) -- (P ∨ Q) ∧ (-Q) #eval pEval p7 interp_all_false -- needs interpretation as pEval p7 def interp_makes_p7_true : var β†’ bool | (var.mk 0) := tt -- basically variable P | (var.mk 1) := ff -- basically variable Q | (var.mk 2) := ff -- basically variable R | (var.mk _) := ff -- for everything else #eval pEval p7 interp_makes_p7_true /- Example: (Q ∨ R) ∧ (Β¬ R ∧ Β¬ Q) -- Not satisfiable (P ∧ Q) β†’ (Q ∧ P) -- VALID IMPLICATION (no matter P and Q) Β¬(P ∧ Q) β†’ (Β¬ P) ∨ (Β¬ Q) -- DeMorgan Laws Β¬ (P ∨ Q) β†’ (Β¬ P) ∧ (Β¬ Q) -/ /- define my_prop to be the following proposition formalized as an expression of type pExp: (P and Q) iff (Q and P). Finally, answer this question: Is this proposition respectively unsatisfiable, satisfiable, or valid? Just three yes/no answers will do. -/ def my_prop := pIff (pAnd (pVar P) (pVar Q)) (pAnd (pVar Q) (pVar P)) #eval pEval my_prop interp_makes_p7_true /- Is this proposition respectively unsatisfiable? No satisfiable? Yes valid? Yes -/
ae51fab480718fc982edc459093fbc45dd5beddf
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/hit/trunc.hlean
e340a8def73cb271dfab6f6ddcf81e36b5c7fb83
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
5,365
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn n-truncation of types. Ported from Coq HoTT -/ /- The hit n-truncation is primitive, declared in init.hit. -/ import types.sigma types.pointed open is_trunc eq equiv is_equiv function prod sum sigma namespace trunc protected definition elim {n : trunc_index} {A : Type} {P : Type} [Pt : is_trunc n P] (H : A β†’ P) : trunc n A β†’ P := trunc.rec H protected definition elim_on {n : trunc_index} {A : Type} {P : Type} (aa : trunc n A) [Pt : is_trunc n P] (H : A β†’ P) : P := trunc.elim H aa end trunc attribute trunc.elim_on [unfold 4] attribute trunc.rec [recursor 6] attribute trunc.elim [recursor 6] [unfold 6] namespace trunc variables {X Y Z : Type} {P : X β†’ Type} (A B : Type) (n : trunc_index) local attribute is_trunc_eq [instance] variables {A n} definition untrunc_of_is_trunc [reducible] [H : is_trunc n A] : trunc n A β†’ A := trunc.rec id variables (A n) definition is_equiv_tr [instance] [constructor] [H : is_trunc n A] : is_equiv (@tr n A) := adjointify _ (untrunc_of_is_trunc) (Ξ»aa, trunc.rec_on aa (Ξ»a, idp)) (Ξ»a, idp) definition trunc_equiv [constructor] [H : is_trunc n A] : trunc n A ≃ A := (equiv.mk tr _)⁻¹ᡉ definition is_trunc_of_is_equiv_tr [H : is_equiv (@tr n A)] : is_trunc n A := is_trunc_is_equiv_closed n (@tr n _)⁻¹ /- Functoriality -/ definition trunc_functor [unfold 5] (f : X β†’ Y) : trunc n X β†’ trunc n Y := Ξ»xx, trunc.rec_on xx (Ξ»x, tr (f x)) definition trunc_functor_compose (f : X β†’ Y) (g : Y β†’ Z) : trunc_functor n (g ∘ f) ~ trunc_functor n g ∘ trunc_functor n f := Ξ»xx, trunc.rec_on xx (Ξ»x, idp) definition trunc_functor_id : trunc_functor n (@id A) ~ id := Ξ»xx, trunc.rec_on xx (Ξ»x, idp) definition is_equiv_trunc_functor [constructor] (f : X β†’ Y) [H : is_equiv f] : is_equiv (trunc_functor n f) := adjointify _ (trunc_functor n f⁻¹) (Ξ»yy, trunc.rec_on yy (Ξ»y, ap tr !right_inv)) (Ξ»xx, trunc.rec_on xx (Ξ»x, ap tr !left_inv)) definition trunc_homotopy {f g : X β†’ Y} (p : f ~ g) : trunc_functor n f ~ trunc_functor n g := Ξ»xx, trunc.rec_on xx (Ξ»x, ap tr (p x)) section open equiv.ops definition trunc_equiv_trunc [constructor] (f : X ≃ Y) : trunc n X ≃ trunc n Y := equiv.mk _ (is_equiv_trunc_functor n f) end section open prod.ops definition trunc_prod_equiv [constructor] : trunc n (X Γ— Y) ≃ trunc n X Γ— trunc n Y := begin fapply equiv.MK, {exact (Ξ»pp, trunc.rec_on pp (Ξ»p, (tr p.1, tr p.2)))}, {intro p, cases p with xx yy, apply (trunc.rec_on xx), intro x, apply (trunc.rec_on yy), intro y, exact (tr (x,y))}, {intro p, cases p with xx yy, apply (trunc.rec_on xx), intro x, apply (trunc.rec_on yy), intro y, apply idp}, {intro pp, apply (trunc.rec_on pp), intro p, cases p, apply idp} end end /- Propositional truncation -/ -- should this live in hprop? definition merely [reducible] [constructor] (A : Type) : hprop := trunctype.mk (trunc -1 A) _ notation `||`:max A `||`:0 := merely A notation `βˆ₯`:max A `βˆ₯`:0 := merely A definition Exists [reducible] [constructor] (P : X β†’ Type) : hprop := βˆ₯ sigma P βˆ₯ definition or [reducible] [constructor] (A B : Type) : hprop := βˆ₯ A ⊎ B βˆ₯ notation `exists` binders `,` r:(scoped P, Exists P) := r notation `βˆƒ` binders `,` r:(scoped P, Exists P) := r notation A ` \/ ` B := or A B notation A ∨ B := or A B definition merely.intro [reducible] [constructor] (a : A) : βˆ₯ A βˆ₯ := tr a definition exists.intro [reducible] [constructor] (x : X) (p : P x) : βˆƒx, P x := tr ⟨x, p⟩ definition or.intro_left [reducible] [constructor] (x : X) : X ∨ Y := tr (inl x) definition or.intro_right [reducible] [constructor] (y : Y) : X ∨ Y := tr (inr y) definition is_contr_of_merely_hprop [H : is_hprop A] (aa : merely A) : is_contr A := is_contr_of_inhabited_hprop (trunc.rec_on aa id) section open sigma.ops definition trunc_sigma_equiv [constructor] : trunc n (Ξ£ x, P x) ≃ trunc n (Ξ£ x, trunc n (P x)) := equiv.MK (Ξ»pp, trunc.rec_on pp (Ξ»p, tr ⟨p.1, tr p.2⟩)) (Ξ»pp, trunc.rec_on pp (Ξ»p, trunc.rec_on p.2 (Ξ»b, tr ⟨p.1, b⟩))) (Ξ»pp, trunc.rec_on pp (Ξ»p, sigma.rec_on p (Ξ»a bb, trunc.rec_on bb (Ξ»b, by esimp)))) (Ξ»pp, trunc.rec_on pp (Ξ»p, sigma.rec_on p (Ξ»a b, by esimp))) definition trunc_sigma_equiv_of_is_trunc [H : is_trunc n X] : trunc n (Ξ£ x, P x) ≃ Ξ£ x, trunc n (P x) := calc trunc n (Ξ£ x, P x) ≃ trunc n (Ξ£ x, trunc n (P x)) : trunc_sigma_equiv ... ≃ Ξ£ x, trunc n (P x) : !trunc_equiv end /- the (non-dependent) universal property -/ definition trunc_arrow_equiv [constructor] [H : is_trunc n B] : (trunc n A β†’ B) ≃ (A β†’ B) := begin fapply equiv.MK, { intro g a, exact g (tr a)}, { intro f x, exact trunc.rec_on x f}, { intro f, apply eq_of_homotopy, intro a, reflexivity}, { intro g, apply eq_of_homotopy, intro x, exact trunc.rec_on x (Ξ»a, idp)}, end end trunc
d49962be6173ee4faf7e9b5266df924a589b2702
690889011852559ee5ac4dfea77092de8c832e7e
/src/data/zmod/quadratic_reciprocity.lean
23a4b5e54d15a2db145ad44fcc2e8f3dc194048e
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
33,336
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 field_theory.finite data.zmod.basic algebra.pi_instances open function finset nat finite_field zmodp namespace zmodp variables {p q : β„•} (hp : nat.prime p) (hq : nat.prime q) @[simp] lemma card_units_zmodp : fintype.card (units (zmodp p hp)) = p - 1 := by rw [card_units, card_zmodp] theorem fermat_little {p : β„•} (hp : nat.prime p) {a : zmodp p hp} (ha : a β‰  0) : a ^ (p - 1) = 1 := by rw [← units.mk0_val ha, ← @units.coe_one (zmodp p hp), ← units.coe_pow, ← units.ext_iff, ← card_units_zmodp hp, pow_card_eq_one] lemma euler_criterion_units {x : units (zmodp p hp)} : (βˆƒ y : units (zmodp p hp), y ^ 2 = x) ↔ x ^ (p / 2) = 1 := hp.eq_two_or_odd.elim (Ξ» h, by subst h; revert x; exact dec_trivial) (Ξ» hp1, let ⟨g, hg⟩ := is_cyclic.exists_generator (units (zmodp p hp)) in let ⟨n, hn⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm β–Έ hg x in ⟨λ ⟨y, hy⟩, by rw [← hy, ← pow_mul, two_mul_odd_div_two hp1, ← card_units_zmodp hp, pow_card_eq_one], Ξ» hx, have 2 * (p / 2) ∣ n * (p / 2), by rw [two_mul_odd_div_two hp1, ← card_units_zmodp hp, ← order_of_eq_card_of_forall_mem_gpowers hg]; exact order_of_dvd_of_pow_eq_one (by rwa [pow_mul, hn]), let ⟨m, hm⟩ := dvd_of_mul_dvd_mul_right (nat.div_pos hp.two_le dec_trivial) this in ⟨g ^ m, by rwa [← pow_mul, mul_comm, ← hm]⟩⟩) lemma euler_criterion {a : zmodp p hp} (ha : a β‰  0) : (βˆƒ y : zmodp p hp, y ^ 2 = a) ↔ a ^ (p / 2) = 1 := ⟨λ ⟨y, hy⟩, have hy0 : y β‰  0, from Ξ» h, by simp [h, _root_.zero_pow (succ_pos 1)] at hy; cc, by simpa using (units.ext_iff.1 $ (euler_criterion_units hp).1 ⟨units.mk0 _ hy0, show _ = units.mk0 _ ha, by rw [units.ext_iff]; simpa⟩), Ξ» h, let ⟨y, hy⟩ := (euler_criterion_units hp).2 (show units.mk0 _ ha ^ (p / 2) = 1, by simpa [units.ext_iff]) in ⟨y, by simpa [units.ext_iff] using hy⟩⟩ lemma exists_pow_two_eq_neg_one_iff_mod_four_ne_three : (βˆƒ y : zmodp p hp, y ^ 2 = -1) ↔ p % 4 β‰  3 := have (-1 : zmodp p hp) β‰  0, from mt neg_eq_zero.1 one_ne_zero, hp.eq_two_or_odd.elim (Ξ» hp, by subst hp; exact dec_trivial) (Ξ» hp1, (mod_two_eq_zero_or_one (p / 2)).elim (Ξ» hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_zero, eq_self_iff_true, true_iff], assume h, rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl, h] at hp2, exact absurd hp2 dec_trivial, end) (Ξ» hp2, begin rw [euler_criterion hp this, neg_one_pow_eq_pow_mod_two, hp2, _root_.pow_one, iff_false_intro (zmodp.ne_neg_self hp hp1 one_ne_zero).symm, false_iff, not_not], rw [← nat.mod_mul_right_div_self, show 2 * 2 = 4, from rfl] at hp2, rw [← nat.mod_mul_left_mod _ 2, show 2 * 2 = 4, from rfl] at hp1, have hp4 : p % 4 < 4, from nat.mod_lt _ dec_trivial, revert hp1 hp2, revert hp4, generalize : p % 4 = k, revert k, exact dec_trivial end)) lemma pow_div_two_eq_neg_one_or_one {a : zmodp p hp} (ha : a β‰  0) : a ^ (p / 2) = 1 ∨ a ^ (p / 2) = -1 := hp.eq_two_or_odd.elim (Ξ» h, by revert a ha; subst h; exact dec_trivial) (Ξ» hp1, by rw [← mul_self_eq_one_iff, ← _root_.pow_add, ← two_mul, two_mul_odd_div_two hp1]; exact fermat_little hp ha) @[simp] lemma wilsons_lemma {p : β„•} (hp : nat.prime p) : (fact (p - 1) : zmodp p hp) = -1 := begin rw [← finset.prod_range_id_eq_fact, ← @units.coe_one (zmodp p hp), ← units.coe_neg, ← @prod_univ_units_id_eq_neg_one (zmodp p hp), ← prod_hom (coe : units (zmodp p hp) β†’ zmodp p hp), ← prod_hom (coe : β„• β†’ zmodp p hp)], exact eq.symm (prod_bij (Ξ» a _, (a : zmodp p hp).1) (Ξ» a ha, mem_erase.2 ⟨λ h, units.coe_ne_zero a $ fin.eq_of_veq h, by rw [mem_range, ← succ_sub hp.pos, succ_sub_one]; exact a.1.2⟩) (Ξ» a _, by simp) (Ξ» _ _ _ _, units.ext_iff.2 ∘ fin.eq_of_veq) (Ξ» b hb, have b β‰  0 ∧ b < p, by rwa [mem_erase, mem_range, ← succ_sub hp.pos, succ_sub_one] at hb, ⟨units.mk0 _ (show (b : zmodp p hp) β‰  0, from fin.ne_of_vne $ by rw [zmod.val_cast_nat, ← @nat.cast_zero (zmodp p hp), zmod.val_cast_nat]; simp [mod_eq_of_lt this.2, this.1]), mem_univ _, by simp [val_cast_of_lt hp this.2]⟩)) end @[simp] lemma prod_range_prime_erase_zero {p : β„•} (hp : nat.prime p) : ((range p).erase 0).prod (Ξ» x, (x : zmodp p hp)) = -1 := by conv in (range p) { rw [← succ_sub_one p, succ_sub hp.pos] }; rw [prod_hom (coe : β„• β†’ zmodp p hp), finset.prod_range_id_eq_fact, wilsons_lemma] end zmodp namespace quadratic_reciprocity_aux variables {p q : β„•} (hp : nat.prime p) (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p β‰  q) include hp hq hp1 hq1 hpq lemma filter_range_p_mul_q_div_two_eq : (range ((p * q) / 2).succ).filter (coprime p) = (range (q / 2)).bind (Ξ» x, (erase (range p) 0).image (+ p * x)) βˆͺ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p) := finset.ext.2 $ Ξ» x, ⟨λ h, have hxp0 : x % p β‰  0, by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd]; exact (mem_filter.1 h).2, mem_union.2 $ or_iff_not_imp_right.2 (Ξ» h₁, mem_bind.2 ⟨x / p, mem_range.2 $ nat.div_lt_of_lt_mul (by_contradiction (Ξ» hβ‚‚, let ⟨c, hc⟩ := le_iff_exists_add.1 (le_of_not_gt hβ‚‚) in have hcp : c ≀ p / 2, from @nat.le_of_add_le_add_left (p * (q / 2)) _ _ (by rw [← hc, ← odd_mul_odd_div_two hp1 hq1]; exact le_of_lt_succ (mem_range.1 (mem_filter.1 h).1)), h₁ $ mem_image.2 ⟨c, mem_erase.2 ⟨λ h, hxp0 $ by simp [h, hc], mem_range.2 $ lt_succ_of_le $ hcp⟩, by rw hc; simp [mul_comm]⟩)), mem_image.2 ⟨x % p, mem_erase.2 $ by rw [ne.def, ← dvd_iff_mod_eq_zero, ← hp.coprime_iff_not_dvd, mem_range]; exact ⟨(mem_filter.1 h).2, mod_lt _ hp.pos⟩, nat.mod_add_div _ _⟩⟩), Ξ» h, mem_filter.2 $ (mem_union.1 h).elim (Ξ» h, let ⟨m, hm₁, hmβ‚‚βŸ© := mem_bind.1 h in let ⟨k, hk₁, hkβ‚‚βŸ© := mem_image.1 hmβ‚‚ in ⟨mem_range.2 $ hkβ‚‚ β–Έ (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 begin rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add], clear _let_match _let_match, exact calc 2 * k + 2 * (p * m) < 2 * p + 2 * (p * m) : add_lt_add_right ((mul_lt_mul_left dec_trivial).2 (by simp at hk₁; tauto)) _ ... = 2 * (p * (m + 1)) : by simp [mul_add, mul_assoc, mul_comm, mul_left_comm] ... ≀ 2 * (p * (q / 2)) : (mul_le_mul_left (show 0 < 2, from dec_trivial)).2 ((mul_le_mul_left hp.pos).2 $ succ_le_of_lt $ mem_range.1 hm₁) ... ≀ _ : by rw [mul_left_comm, two_mul_odd_div_two hq1, nat.mul_sub_left_distrib, ← nat.sub_add_comm (mul_pos hp.pos hq.pos), add_succ, succ_eq_add_one, nat.add_sub_cancel]; exact le_trans (nat.sub_le_self _ _) (nat.le_add_right _ _), end, by rw [nat.prime.coprime_iff_not_dvd hp, ← hkβ‚‚, ← nat.dvd_add_iff_left (dvd_mul_right _ _), dvd_iff_mod_eq_zero, mod_eq_of_lt]; clear _let_match _let_match; simp at hk₁; tauto⟩) (Ξ» h, let ⟨m, hm₁, hmβ‚‚βŸ© := mem_image.1 h in ⟨mem_range.2 $ hmβ‚‚ β–Έ begin refine (mul_lt_mul_left (show 0 < 2, from dec_trivial)).1 _, rw [mul_succ, two_mul_odd_div_two (nat.odd_mul_odd hp1 hq1), mul_add, ← mul_assoc 2, two_mul_odd_div_two hq1], exact calc 2 * m + (q - 1) * p ≀ 2 * (p / 2) + (q - 1) * p : add_le_add_right ((mul_le_mul_left dec_trivial).2 (le_of_lt_succ (mem_range.1 (by simp * at *)))) _ ... < _ : begin rw [two_mul_odd_div_two hp1, nat.mul_sub_right_distrib, one_mul], rw [← nat.sub_add_comm hp.pos, nat.add_sub_cancel' (le_mul_of_one_le_left' (nat.zero_le _) hq.pos), mul_comm], exact lt_add_of_pos_right _ dec_trivial end, end, by rw [hp.coprime_iff_not_dvd, dvd_iff_mod_eq_zero, ← hmβ‚‚, nat.add_mul_mod_self_right, mod_eq_of_lt (lt_of_lt_of_le _ (nat.div_lt_self hp.pos (show 1 < 2, from dec_trivial)))]; simp at hm₁; clear _let_match; tauto⟩)⟩ lemma prod_filter_range_p_mul_q_div_two_eq : (range (q / 2)).prod (Ξ» n, ((range p).erase 0).prod (+ p * n)) * ((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) = ((range ((p * q) / 2).succ).filter (coprime p)).prod (Ξ» x, x) := calc (range (q / 2)).prod (Ξ» n, ((range p).erase 0).prod (+ p * n)) * ((range (p / 2).succ).erase 0).prod (+ (q / 2) * p) = (range (q / 2)).prod (Ξ» n, (((range p).erase 0).image (+ p * n)).prod (Ξ» x, x)) * (((range (p / 2).succ).erase 0).image (+ (q / 2) * p)).prod (Ξ» x, x) : by simp only [prod_image (Ξ» _ _ _ _ h, add_right_cancel h)]; refl ... = ((range (q / 2)).bind (Ξ» x, (erase (range p) 0).image (+ p * x)) βˆͺ (erase (range (succ (p / 2))) 0).image (+ q / 2 * p)).prod (Ξ» x, x) : have h₁ : disjoint (finset.bind (range (q / 2)) (Ξ» x, ((range p).erase 0).image (+ p * x))) (image (+ q / 2 * p) (erase (range (succ (p / 2))) 0)) := disjoint_iff.2 $ eq_empty_iff_forall_not_mem.2 $ Ξ» x, begin suffices : βˆ€ a, a β‰  0 β†’ a ≀ p / 2 β†’ a + q / 2 * p = x β†’ βˆ€ b, b < q / 2 β†’ βˆ€ c, c β‰  0 β†’ c < p β†’ Β¬c + p * b = x, { simpa [lt_succ_iff] }, assume a ha0 hap ha b hbq c hc0 hcp hc, rw mul_comm at ha, rw [← ((nat.div_mod_unique hp.pos).2 ⟨hc, hcp⟩).1, ← ((nat.div_mod_unique hp.pos).2 ⟨ha, lt_of_le_of_lt hap (nat.div_lt_self hp.pos dec_trivial)⟩).1] at hbq, exact lt_irrefl _ hbq end, have hβ‚‚ : βˆ€ x, x ∈ range (q / 2) β†’ βˆ€ y, y ∈ range (q / 2) β†’ x β‰  y β†’ disjoint (image (+p * x) (erase (range p) 0)) (image (+ p * y) (erase (range p) 0)) := Ξ» x hx y hy hxy, begin suffices : βˆ€ z a, a β‰  0 β†’ a < p β†’ a + p * x = z β†’ βˆ€ bpy b, b β‰  0 β†’ b < p β†’ b + p * y = bpy β†’ z β‰  bpy, { simpa [disjoint_iff_ne] }, assume z a ha0 hap ha bpy b hb0 hbp hb hzb, have : (a + p * x) / p = (b + p * y) / p, { rw [ha, hb, hzb] }, rw [nat.add_mul_div_left _ _ hp.pos, nat.add_mul_div_left _ _ hp.pos, (nat.div_eq_zero_iff hp.pos).2 hap, (nat.div_eq_zero_iff hp.pos).2 hbp] at this, simpa [hxy] end, by rw [prod_union h₁, prod_bind hβ‚‚] ... = (((range ((p * q) / 2).succ)).filter (coprime p)).prod (Ξ» x, x) : prod_congr (filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq).symm (Ξ» _ _, rfl) lemma prod_filter_range_p_mul_q_div_two_mod_p_eq : ((((range ((p * q) / 2).succ).filter (coprime p)).prod (Ξ» x, x) : β„•) : zmodp p hp) = (-1) ^ (q / 2) * ((range (p / 2).succ).erase 0).prod (Ξ» x, x) := begin rw [← prod_filter_range_p_mul_q_div_two_eq hp hq hp1 hq1 hpq, nat.cast_mul, ← prod_hom (coe : β„• β†’ zmodp p hp), ← prod_hom (coe : β„• β†’ zmodp p hp)], conv in ((finset.prod (erase (range p) 0) _ : β„•) : zmodp p hp) { rw ← prod_hom (coe : β„• β†’ zmodp p hp) }, simp end lemma prod_filter_range_p_mul_q_not_coprime_eq : (((((range ((p * q) / 2).succ).filter (coprime p)).filter (Ξ» x, Β¬ coprime q x)).prod (Ξ» x, x) : β„•) : zmodp p hp) = q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (Ξ» x, x) := have hcard : ((range (p / 2).succ).erase 0).card = p / 2 := by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], begin conv in ((q : zmodp p hp) ^ (p / 2)) { rw ← hcard }, rw [← prod_const, ← prod_mul_distrib, ← prod_hom (coe : β„• β†’ zmodp p hp)], exact eq.symm (prod_bij (Ξ» a _, a * q) (Ξ» a ha, have ha' : a ≀ p / 2 ∧ a > 0, by simp [nat.pos_iff_ne_zero, lt_succ_iff] at *; tauto, mem_filter.2 ⟨mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ (calc a * q ≀ q * (p / 2) : by rw mul_comm; exact mul_le_mul_left _ ha'.1 ... ≀ _ : by rw [mul_comm p, odd_mul_odd_div_two hq1 hp1]; exact nat.le_add_right _ _), by rw [hp.coprime_iff_not_dvd, hp.dvd_mul, not_or_distrib]; refine ⟨λ hpa, not_le_of_gt (show p / 2 < p, from nat.div_lt_self hp.pos dec_trivial) (le_trans (le_of_dvd ha'.2 hpa) ha'.1), by rwa [← hp.coprime_iff_not_dvd, coprime_primes hp hq]⟩⟩, by simp [hq.coprime_iff_not_dvd]⟩) (by simp [mul_comm]) (by simp [nat.mul_right_inj hq.pos]) (Ξ» b hb, have hb' : (b ≀ p * q / 2 ∧ coprime p b) ∧ q ∣ b, by simpa [hq.coprime_iff_not_dvd, lt_succ_iff] using hb, have hb0 : b > 0, from nat.pos_of_ne_zero (Ξ» hb0, by simpa [hb0, hp.coprime_iff_not_dvd] using hb'), ⟨b / q, mem_erase.2 ⟨nat.pos_iff_ne_zero.1 (nat.div_pos (le_of_dvd hb0 hb'.2) hq.pos), mem_range.2 $ lt_succ_of_le $ by rw [mul_comm, odd_mul_odd_div_two hq1 hp1] at hb'; have := @nat.div_le_div_right _ _ hb'.1.1 q; rwa [add_comm, nat.add_mul_div_left _ _ hq.pos, ((nat.div_eq_zero_iff hq.pos).2 (nat.div_lt_self hq.pos (lt_succ_self _))), zero_add] at this⟩, by rw nat.div_mul_cancel hb'.2⟩)) end lemma prod_range_p_mul_q_filter_coprime_mod_p (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p β‰  q) : ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (Ξ» x, x) : β„•) : zmodp p hp) = (-1) ^ (q / 2) * q ^ (p / 2) := have hq0 : (q : zmodp p hp) β‰  0, by rwa [← nat.cast_zero, ne.def, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_zero_iff, ← hp.coprime_iff_not_dvd, coprime_primes hp hq], (domain.mul_right_inj (show (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (Ξ» x, x) : zmodp p hp) β‰  0, from mul_ne_zero (pow_ne_zero _ hq0) (suffices h : βˆ€ (x : β„•), Β¬x = 0 β†’ x ≀ p / 2 β†’ Β¬(x : zmodp p hp) = 0, by simpa [prod_eq_zero_iff, lt_succ_iff], assume x hx0 hxp, by rwa [← @nat.cast_zero (zmodp p hp), zmodp.eq_iff_modeq_nat, nat.modeq, zero_mod, mod_eq_of_lt (lt_of_le_of_lt hxp (nat.div_lt_self hp.pos (lt_succ_self _)))]))).1 $ have h₁ : disjoint ((range (succ (p * q / 2))).filter (coprime (p * q))) (filter (Ξ» x, Β¬coprime q x) (filter (coprime p) (range (succ (p * q / 2))))), by {rw [finset.filter_filter], apply finset.disjoint_filter.2, rintros _ _ hpq ⟨_, hq⟩, exact hq (coprime.coprime_mul_left hpq)}, calc ((((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (Ξ» x, x) : β„•) : zmodp p hp) * (q ^ (p / 2) * ((range (p / 2).succ).erase 0).prod (Ξ» x, x) : zmodp p hp) = (((range (succ (p * q / 2))).filter (coprime (p * q)) βˆͺ filter (Ξ» x, Β¬coprime q x) (filter (coprime p) (range (succ (p * q / 2))))).prod (Ξ» x, x) : β„•) : by rw [← prod_filter_range_p_mul_q_not_coprime_eq hp hq hp1 hq1 hpq, ← nat.cast_mul, ← prod_union h₁] ... = (((range ((p * q) / 2).succ).filter (coprime p)).prod (Ξ» x, x) : β„•) : congr_arg coe (prod_congr (by simp [finset.ext, coprime_mul_iff_left]; tauto) (Ξ» _ _, rfl)) ... = _ : by rw [prod_filter_range_p_mul_q_div_two_mod_p_eq hp hq hp1 hq1 hpq]; cases zmodp.pow_div_two_eq_neg_one_or_one hp hq0; simp [h, _root_.pow_succ] lemma card_range_p_mul_q_filter_not_coprime : card (filter (Ξ» x, Β¬coprime p x) (range (succ (p * q / 2)))) = (q / 2).succ := calc card (filter (Ξ» x, Β¬coprime p x) (range (succ (p * q / 2)))) = card ((range (q / 2).succ).image (* p)) : congr_arg card $ finset.ext.2 $ Ξ» x, begin rw [mem_filter, mem_range, hp.coprime_iff_not_dvd, not_not, mem_image], exact ⟨λ ⟨h, ⟨m, hm⟩⟩, ⟨m, mem_range.2 (lt_of_mul_lt_mul_left (by rw ← hm; exact lt_of_lt_of_le h (by rw [succ_le_iff, mul_succ, odd_mul_odd_div_two hp1 hq1]; exact add_lt_add_left (div_lt_self hp.pos (lt_succ_self 1)) _)) (nat.zero_le p)), hm.symm β–Έ mul_comm m p⟩, Ξ» ⟨m, hm₁, hmβ‚‚βŸ©, ⟨lt_succ_of_le (by rw [← hmβ‚‚, odd_mul_odd_div_two hp1 hq1]; exact le_trans (by rw mul_comm; exact mul_le_mul_left _ (le_of_lt_succ (mem_range.1 hm₁))) (le_add_right _ _)), by simp [hmβ‚‚.symm]⟩⟩ end ... = _ : by rw [card_image_of_injective _ (Ξ» _ _ h, (nat.mul_right_inj hp.pos).1 h), card_range] lemma prod_filter_range_p_mul_q_div_two_eq_prod_product : ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (Ξ» x, if (x : zmodp q hq).1 ≀ q / 2 then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = (((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod (Ξ» x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) := have hpqpnat : (((⟨p * q, mul_pos hp.pos hq.pos⟩ : β„•+) : β„•) : β„€) = (p * q : β„€), by simp, have hpqpnat' : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : β„•+) : β„•) = p * q, by simp, have hpq1 : ((⟨p * q, mul_pos hp.pos hq.pos⟩ : β„•+) : β„•) % 2 = 1, from nat.odd_mul_odd hp1 hq1, have hpq1' : p * q > 1, from one_lt_mul hp.pos hq.one_lt, have hhq0 : βˆ€ a : β„•, coprime q a β†’ a β‰  0, from Ξ» a, imp_not_comm.1 $ by simp [hq.coprime_iff_not_dvd] {contextual := tt}, have hpq0 : 0 < p * q / 2, from nat.div_pos (succ_le_of_lt $ one_lt_mul hp.pos hq.one_lt) dec_trivial, have hinj : βˆ€ a₁ aβ‚‚ : β„•, a₁ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) β†’ aβ‚‚ ∈ (range (p * q / 2).succ).filter (coprime (p * q)) β†’ (if (a₁ : zmodp q hq).1 ≀ q / 2 then ((a₁ : zmodp p hp).1, (a₁ : zmodp q hq).1) else ((-a₁ : zmodp p hp).1, (-a₁ : zmodp q hq).1)) = (if (aβ‚‚ : zmodp q hq).1 ≀ q / 2 then ((aβ‚‚ : zmodp p hp).1, (aβ‚‚ : zmodp q hq).1) else ((-aβ‚‚ : zmodp p hp).1, (-aβ‚‚ : zmodp q hq).1)) β†’ a₁ = aβ‚‚, from Ξ» a b ha hb h, have ha' : a ≀ (p * q) / 2 ∧ coprime (p * q) a, by simpa [lt_succ_iff] using ha, have hapq' : a < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : β„•+) : β„•) := lt_of_le_of_lt ha'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial), have hb' : b ≀ (p * q) / 2 ∧ coprime (p * q) b, by simpa [lt_succ_iff, coprime_mul_iff_left] using hb, have hbpq' : b < ((⟨p * q, mul_pos hp.pos hq.pos⟩ : β„•+) : β„•) := lt_of_le_of_lt hb'.1 (div_lt_self (mul_pos hp.pos hq.pos) dec_trivial), have val_inj : βˆ€ {p : β„•} (hp : nat.prime p) (x y : zmodp p hp), x.val = y.val ↔ x = y, from Ξ» _ _ _ _, ⟨fin.eq_of_veq, fin.veq_of_eq⟩, have hbpq0 : (b : zmod (⟨p * q, mul_pos hp.pos hq.pos⟩)) β‰  0, by rw [ne.def, zmod.eq_zero_iff_dvd_nat]; exact Ξ» h, not_coprime_of_dvd_of_dvd hpq1' (dvd_refl (p * q)) h hb'.2, have habneg : Β¬((a : zmodp p hp) = -b ∧ (a : zmodp q hq) = -b), begin rw [← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_coe_nat a, ← int.cast_coe_nat b, ← int.cast_neg, ← int.cast_neg, zmodp.eq_iff_modeq_int, zmodp.eq_iff_modeq_int, @int.modeq.modeq_and_modeq_iff_modeq_mul _ _ p q ((coprime_primes hp hq).2 hpq), ← hpqpnat, ← zmod.eq_iff_modeq_int, int.cast_coe_nat, int.cast_neg, int.cast_coe_nat], assume h, rw [← hpqpnat', ← zmod.val_cast_of_lt hbpq', zmod.le_div_two_iff_lt_neg hpq1 hbpq0, ← h, zmod.val_cast_of_lt hapq', ← not_le] at hb', exact hb'.1 ha'.1, end, have habneg' : Β¬((-a : zmodp p hp) = b ∧ (-a : zmodp q hq) = b), by rwa [← neg_inj', neg_neg, ← @neg_inj' _ _ (-a : zmodp q hq), neg_neg], suffices (a : zmodp p hp) = b ∧ (a : zmodp q hq) = b, by rw [← mod_eq_of_lt hapq', ← mod_eq_of_lt hbpq']; rwa [zmodp.eq_iff_modeq_nat, zmodp.eq_iff_modeq_nat, nat.modeq.modeq_and_modeq_iff_modeq_mul ((coprime_primes hp hq).2 hpq)] at this, by split_ifs at h; simp * at *, have hmem : βˆ€ a : β„•, a ∈ (range (p * q / 2).succ).filter (coprime (p * q)) β†’ (if (a : zmodp q hq).1 ≀ q / 2 then ((a : zmodp p hp).1, (a : zmodp q hq).1) else ((-a : zmodp p hp).1, (-a : zmodp q hq).1)) ∈ ((range p).erase 0).product ((range (succ (q / 2))).erase 0), from Ξ» x, have hxp : βˆ€ {p : β„•} (hp : nat.prime p), (x : zmodp p hp).val = 0 ↔ p ∣ x, from Ξ» p hp, by rw [zmodp.val_cast_nat, nat.dvd_iff_mod_eq_zero], have hxpneg : βˆ€ {p : β„•} (hp : nat.prime p), (-x : zmodp p hp).val = 0 ↔ p ∣ x, from Ξ» p hp, by rw [← int.cast_coe_nat x, ← int.cast_neg, ← int.coe_nat_inj', zmodp.coe_val_cast_int, int.coe_nat_zero, ← int.dvd_iff_mod_eq_zero, dvd_neg, int.coe_nat_dvd], have hxplt : (x : zmodp p hp).val < p := (x : zmodp p hp).2, have hxpltneg : (-x : zmodp p hp).val < p := (-x : zmodp p hp).2, have hneglt : Β¬(x : zmodp q hq).val ≀ q / 2 β†’ (x : zmodp q hq) β‰  0 β†’ (-x : zmodp q hq).val ≀ q / 2, from Ξ» hx₁ hx0, by rwa [zmodp.le_div_two_iff_lt_neg hq hq1 hx0, not_lt] at hx₁, by split_ifs; simp [zmodp.eq_zero_iff_dvd_nat hq, (x : zmodp p hp).2, coprime_mul_iff_left, lt_succ_iff, h, *, hp.coprime_iff_not_dvd, hq.coprime_iff_not_dvd, (x : zmodp p hp).2, (-x : zmodp p hp).2] {contextual := tt}, prod_bij (Ξ» x _, if (x : zmodp q hq).1 ≀ (q / 2) then ((x : zmodp p hp).val, (x : zmodp q hq).val) else ((-x : zmodp p hp).val, (-x : zmodp q hq).val)) hmem (Ξ» a ha, by split_ifs; simp [*, prod.ext_iff] at *) hinj (surj_on_of_inj_on_of_card_le _ hmem hinj (@nat.le_of_add_le_add_right (q / 2 + (p / 2).succ) _ _ (calc card (finset.product (erase (range p) 0) (erase (range (succ (q / 2))) 0)) + (q / 2 + (p / 2).succ) = (p * q) / 2 + 1 : by rw [card_product, card_erase_of_mem (mem_range.2 hp.pos), card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, card_range, pred_succ, ← add_assoc, ← succ_mul, succ_pred_eq_of_pos hp.pos, odd_mul_odd_div_two hp1 hq1, add_succ] ... = card (range (p * q / 2).succ) : by rw card_range ... = card ((range (p * q / 2).succ).filter (coprime (p * q)) βˆͺ ((range (p * q / 2).succ).filter (Ξ» x, Β¬coprime p x)).erase 0 βˆͺ (range (p * q / 2).succ).filter (Ξ» x, Β¬coprime q x)) : congr_arg card (by simp [finset.ext, coprime_mul_iff_left]; tauto) ... ≀ card ((range (p * q / 2).succ).filter (coprime (p * q))) + card (((range (p * q / 2).succ).filter (Ξ» x, Β¬coprime p x)).erase 0) + card ((range (p * q / 2).succ).filter (Ξ» x, Β¬coprime q x)) : le_trans (card_union_le _ _) (add_le_add_right (card_union_le _ _) _) ... = _ : by rw [card_erase_of_mem, card_range_p_mul_q_filter_not_coprime hp hq hp1 hq1 hpq, mul_comm p q, card_range_p_mul_q_filter_not_coprime hq hp hq1 hp1 hpq.symm, pred_succ, add_assoc]; simp [range_succ, hp.coprime_iff_not_dvd, hpq0]))) lemma prod_range_div_two_erase_zero : ((range (p / 2).succ).erase 0).prod (Ξ» x, (x : zmodp p hp)) ^ 2 * (-1) ^ (p / 2) = -1 := have hcard : card (erase (range (succ (p / 2))) 0) = p / 2, by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], have hp2 : p / 2 < p, from div_lt_self hp.pos dec_trivial, have h₁ : (range (p / 2).succ).erase 0 = ((range p).erase 0).filter (Ξ» x, (x : zmodp p hp).val ≀ p / 2) := finset.ext.2 (Ξ» a, ⟨λ h, mem_filter.2 $ by rw [mem_erase, mem_range, lt_succ_iff] at h; exact ⟨mem_erase.2 ⟨h.1, mem_range.2 (lt_of_le_of_lt h.2 hp2)⟩, by rw zmodp.val_cast_of_lt hp (lt_of_le_of_lt h.2 hp2); exact h.2⟩, Ξ» h, mem_erase.2 ⟨by simp at h; tauto, by rw [mem_filter, mem_erase, mem_range] at h; rw [mem_range, lt_succ_iff, ← zmodp.val_cast_of_lt hp h.1.2]; exact h.2⟩⟩), have hmem : βˆ€ x ∈ (range (p / 2).succ).erase 0, x β‰  0 ∧ x ≀ p / 2, from Ξ» x hx, by simpa [lt_succ_iff] using hx, have hmemv : βˆ€ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp).val = x, from Ξ» x hx, zmodp.val_cast_of_lt hp (lt_of_le_of_lt (hmem x hx).2 hp2), have hmem0 : βˆ€ x ∈ (range (p / 2).succ).erase 0, (x : zmodp p hp) β‰  0, from Ξ» x hx, fin.ne_of_vne $ by simp [hmemv x hx, (hmem x hx).1], have hmem0' : βˆ€ x ∈ (range (p / 2).succ).erase 0, (-x : zmodp p hp) β‰  0, from Ξ» x hx, neg_ne_zero.2 (hmem0 x hx), have hβ‚‚ : ((range (p / 2).succ).erase 0).prod (Ξ» x : β„•, (x : zmodp p hp) * -1) = (((range p).erase 0).filter (Ξ» x : β„•, Β¬(x : zmodp p hp).val ≀ p / 2)).prod (Ξ» x, (x : zmodp p hp)) := prod_bij (Ξ» a _, (-a : zmodp p hp).1) (Ξ» a ha, mem_filter.2 ⟨mem_erase.2 ⟨fin.vne_of_ne (hmem0' a ha), mem_range.2 (-a : zmodp p hp).2⟩, by simp [zmodp.le_div_two_iff_lt_neg hp hp1 (hmem0' a ha), hmemv a ha, (hmem a ha).2]; tauto⟩) (by simp) (Ξ» a₁ aβ‚‚ ha₁ haβ‚‚ h, by rw [← hmemv a₁ ha₁, ← hmemv aβ‚‚ haβ‚‚]; exact fin.veq_of_eq (by rw neg_inj (fin.eq_of_veq h))) (Ξ» b hb, have hb' : (b β‰  0 ∧ b < p) ∧ (Β¬(b : zmodp p hp).1 ≀ p / 2), by simpa using hb, have hbv : (b : zmodp p hp).1 = b, from zmodp.val_cast_of_lt hp hb'.1.2, have hb0 : (b : zmodp p hp) β‰  0, from fin.ne_of_vne $ by simp [hbv, hb'.1.1], ⟨(-b : zmodp p hp).1, mem_erase.2 ⟨fin.vne_of_ne (neg_ne_zero.2 hb0 : _), mem_range.2 $ lt_succ_of_le $ by rw [← not_lt, ← zmodp.le_div_two_iff_lt_neg hp hp1 hb0]; exact hb'.2⟩, by simp [hbv]⟩), calc ((((range (p / 2).succ).erase 0).prod (Ξ» x, (x : zmodp p hp)) ^ 2)) * (-1) ^ (p / 2) = ((range (p / 2).succ).erase 0).prod (Ξ» x, (x : zmodp p hp)) * ((range (p / 2).succ).erase 0).prod (Ξ» x, (x : zmodp p hp) * -1) : by rw prod_mul_distrib; simp [_root_.pow_two, hcard, mul_assoc] ... = (((range p).erase 0).filter (Ξ» x : β„•, (x : zmodp p hp).val ≀ p / 2)).prod (Ξ» x, (x : zmodp p hp)) * (((range p).erase 0).filter (Ξ» x : β„•, Β¬(x : zmodp p hp).val ≀ p / 2)).prod (Ξ» x, (x : zmodp p hp)) : by rw [hβ‚‚, h₁] ... = ((range p).erase 0).prod (Ξ» x, (x : zmodp p hp)) : begin rw ← prod_union, { exact finset.prod_congr (by simp [finset.ext, -not_lt, -not_le]; tauto) (Ξ» _ _, rfl) }, { apply disjoint_filter.2, tauto } end ... = -1 : by simp lemma range_p_product_range_q_div_two_prod : (((range p).erase 0).product ((range (q / 2).succ).erase 0)).prod (Ξ» x, ((x.1 : zmodp p hp), (x.2 : zmodp q hq))) = ((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) := have hcard : card (erase (range (succ (q / 2))) 0) = q / 2, by rw [card_erase_of_mem (mem_range.2 (succ_pos _)), card_range, pred_succ], have finset.prod (erase (range (succ (q / 2))) 0) (Ξ» x : β„•, (x : zmodp q hq)) ^ 2 = -((-1 : zmodp q hq) ^ (q / 2)), from (domain.mul_right_inj (show (-1 : zmodp q hq) ^ (q / 2) β‰  0, from pow_ne_zero _ (neg_ne_zero.2 zero_ne_one.symm))).1 $ by rw [prod_range_div_two_erase_zero hq hp hq1 hp1 hpq.symm, ← neg_mul_eq_neg_mul, ← _root_.pow_add, ← two_mul, pow_mul, _root_.pow_two]; simp, have finset.prod (erase (range (succ (q / 2))) 0) (Ξ» x, (x : zmodp q hq)) ^ card (erase (range p) 0) = (- 1) ^ (p / 2) * ((-1) ^ (p / 2 * (q / 2))), by rw [card_erase_of_mem (mem_range.2 hp.pos), card_range, pred_eq_sub_one, ← two_mul_odd_div_two hp1, pow_mul, this, mul_comm (p / 2), pow_mul, ← _root_.mul_pow]; simp, by simp [prod_product, (prod_mk_prod _ _ _).symm, prod_pow, prod_nat_pow, prod_const, *, zmodp.prod_range_prime_erase_zero hp] lemma prod_range_p_mul_q_div_two_ite_eq : ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (Ξ» x, if (x : zmodp q hq).1 ≀ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (Ξ» x, if (x : zmodp q hq).1 ≀ q / 2 then 1 else -1) * ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) := calc ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (Ξ» x, if (x : zmodp q hq).1 ≀ (q / 2) then ((x : zmodp p hp), (x : zmodp q hq)) else -((x : zmodp p hp), (x : zmodp q hq))) = ((range ((p * q) / 2).succ).filter (coprime (p * q))).prod (Ξ» x, (if (x : zmodp q hq).1 ≀ (q / 2) then 1 else -1) * ((x : zmodp p hp), (x : zmodp q hq))) : prod_congr rfl (Ξ» _ _, by split_ifs; simp) ... = _ : by rw [prod_mul_distrib, ← prod_mk_prod, prod_hom (coe : β„• β†’ zmodp p hp), prod_range_p_mul_q_filter_coprime_mod_p hp hq hp1 hq1 hpq, prod_hom (coe : β„• β†’ zmodp q hq), mul_comm p q, prod_range_p_mul_q_filter_coprime_mod_p hq hp hq1 hp1 hpq.symm] end quadratic_reciprocity_aux open quadratic_reciprocity_aux variables {p q : β„•} (hp : nat.prime p) (hq : nat.prime q) namespace zmodp def legendre_sym (a p : β„•) (hp : nat.prime p) : β„€ := if (a : zmodp p hp) = 0 then 0 else if βˆƒ b : zmodp p hp, b ^ 2 = a then 1 else -1 lemma legendre_sym_eq_pow (a p : β„•) (hp : nat.prime p) : (legendre_sym a p hp : zmodp p hp) = (a ^ (p / 2)) := if ha : (a : zmodp p hp) = 0 then by simp [*, legendre_sym, _root_.zero_pow (nat.div_pos hp.two_le (succ_pos 1))] else (nat.prime.eq_two_or_odd hp).elim (Ξ» hp2, begin subst hp2, suffices : βˆ€ a : zmodp 2 nat.prime_two, (((ite (a = 0) 0 (ite (βˆƒ (b : zmodp 2 hp), b ^ 2 = a) 1 (-1))) : β„€) : zmodp 2 nat.prime_two) = a ^ (2 / 2), { exact this a }, exact dec_trivial, end) (Ξ» hp1, have _ := euler_criterion hp ha, have (-1 : zmodp p hp) β‰  1, from (ne_neg_self hp hp1 zero_ne_one.symm).symm, by cases zmodp.pow_div_two_eq_neg_one_or_one hp ha; simp [legendre_sym, *] at *) lemma legendre_sym_eq_one_or_neg_one (a : β„•) (hp : nat.prime p) (ha : (a : zmodp p hp) β‰  0) : legendre_sym a p hp = -1 ∨ legendre_sym a p hp = 1 := by unfold legendre_sym; split_ifs; simp * at * theorem quadratic_reciprocity (hp : nat.prime p) (hq : nat.prime q) (hp1 : p % 2 = 1) (hq1 : q % 2 = 1) (hpq : p β‰  q) : legendre_sym p q hq * legendre_sym q p hp = (-1) ^ ((p / 2) * (q / 2)) := have hneg_one_or_one : ((range (p * q / 2).succ).filter (coprime (p * q))).prod (Ξ» (x : β„•), if (x : zmodp q hq).val ≀ q / 2 then (1 : zmodp p hp Γ— zmodp q hq) else -1) = 1 ∨ ((range (p * q / 2).succ).filter (coprime (p * q))).prod (Ξ» (x : β„•), if (x : zmodp q hq).val ≀ q / 2 then (1 : zmodp p hp Γ— zmodp q hq) else -1) = -1 := finset.induction_on ((range (p * q / 2).succ).filter (coprime (p * q))) (or.inl rfl) (Ξ» a s h, by simp [prod_insert h]; split_ifs; finish), have h : (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp Γ— zmodp q hq) = ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) ∨ (((-1) ^ (q / 2), (-1) ^ (p / 2) * (-1) ^ (p / 2 * (q / 2))) : zmodp p hp Γ— zmodp q hq) = - ((-1) ^ (q / 2) * q ^ (p / 2), (-1) ^ (p / 2) * p ^ (q / 2)) := begin have := prod_filter_range_p_mul_q_div_two_eq_prod_product hp hq hp1 hq1 hpq, rw [prod_range_p_mul_q_div_two_ite_eq hp hq hp1 hq1 hpq, range_p_product_range_q_div_two_prod hp hq hp1 hq1 hpq] at this, cases hneg_one_or_one with h h; simp * at * end, begin have := ne_neg_self hp hp1 one_ne_zero, have := ne_neg_self hq hq1 one_ne_zero, generalize hnp : (-1 : β„€) ^ (p / 2) = np, have hnpp : (-1 : zmodp q hq) ^ (p / 2) = np, by simp [hnp.symm], generalize hnq : (-1 : β„€) ^ (q / 2) = nq, have hnqp : (-1 : zmodp p hp) ^ (q / 2) = nq, by simp [hnq.symm], have hnqq : (-1 : zmodp q hq) ^ (q / 2) = nq, by simp [hnq.symm], cases legendre_sym_eq_one_or_neg_one q hp (zmodp.prime_ne_zero hp hq hpq); cases legendre_sym_eq_one_or_neg_one p hq (zmodp.prime_ne_zero hq hp hpq.symm); cases @neg_one_pow_eq_or β„€ _ (p / 2); cases @neg_one_pow_eq_or β„€ _ (q / 2); simp [*, pow_mul, (legendre_sym_eq_pow p q hq).symm, (legendre_sym_eq_pow q p hp).symm, prod.ext_iff] at *; cc end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_one (hp1 : p % 4 = 1) (hq1 : q % 2 = 1) : (βˆƒ a : zmodp p hp, a ^ 2 = q) ↔ βˆƒ b : zmodp q hq, b ^ 2 = p := if hpq : p = q then by subst hpq else have h1 : ((p / 2) * (q / 2)) % 2 = 0, from (dvd_iff_mod_eq_zero _ _).1 (dvd_mul_of_dvd_left ((dvd_iff_mod_eq_zero _ _).2 $ by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp1]; refl) _), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_one hp1) hq1 hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp (ne.symm hpq))] at this, split_ifs at this; simp *; contradiction end lemma exists_pow_two_eq_prime_iff_of_mod_four_eq_three (hp3 : p % 4 = 3) (hq3 : q % 4 = 3) (hpq : p β‰  q) : (βˆƒ a : zmodp p hp, a ^ 2 = q) ↔ Β¬βˆƒ b : zmodp q hq, b ^ 2 = p := have h1 : ((p / 2) * (q / 2)) % 2 = 1, from nat.odd_mul_odd (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hp3]; refl) (by rw [← mod_mul_right_div_self, show 2 * 2 = 4, from rfl, hq3]; refl), begin have := quadratic_reciprocity hp hq (odd_of_mod_four_eq_three hp3) (odd_of_mod_four_eq_three hq3) hpq, rw [neg_one_pow_eq_pow_mod_two, h1, legendre_sym, legendre_sym, if_neg (zmodp.prime_ne_zero hp hq hpq), if_neg (zmodp.prime_ne_zero hq hp hpq.symm)] at this, split_ifs at this; simp *; contradiction end end zmodp
7b3e795d545ace38b64f31ac4352d528829d0dc8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/testing/slim_check/functions.lean
a39eb555a48f7c6fa8339d7fd50459636cf8486b
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
19,602
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.list.sigma import data.int.range import data.finsupp.basic import data.finsupp.to_dfinsupp import tactic.pretty_cases import testing.slim_check.sampleable import testing.slim_check.testable /-! ## `slim_check`: generators for functions This file defines `sampleable` instances for `Ξ± β†’ Ξ²` functions and `β„€ β†’ β„€` injective functions. Functions are generated by creating a list of pairs and one more value using the list as a lookup table and resorting to the additional value when a value is not found in the table. Injective functions are generated by creating a list of numbers and a permutation of that list. The permutation insures that every input is mapped to a unique output. When an input is not found in the list the input itself is used as an output. Injective functions `f : Ξ± β†’ Ξ±` could be generated easily instead of `β„€ β†’ β„€` by generating a `list Ξ±`, removing duplicates and creating a permutations. One has to be careful when generating the domain to make if vast enough that, when generating arguments to apply `f` to, they argument should be likely to lie in the domain of `f`. This is the reason that injective functions `f : β„€ β†’ β„€` are generated by fixing the domain to the range `[-2*size .. -2*size]`, with `size` the size parameter of the `gen` monad. Much of the machinery provided in this file is applicable to generate injective functions of type `Ξ± β†’ Ξ±` and new instances should be easy to define. Other classes of functions such as monotone functions can generated using similar techniques. For monotone functions, generating two lists, sorting them and matching them should suffice, with appropriate default values. Some care must be taken for shrinking such functions to make sure their defining property is invariant through shrinking. Injective functions are an example of how complicated it can get. -/ universes u v w variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Sort w} namespace slim_check /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `with_default f y` encodes `x ↦ f x` when `x ∈ f` and `x ↦ y` otherwise. We use `Ξ£` to encode mappings instead of `Γ—` because we rely on the association list API defined in `data.list.sigma`. -/ inductive total_function (Ξ± : Type u) (Ξ² : Type v) : Type (max u v) | with_default : list (Ξ£ _ : Ξ±, Ξ²) β†’ Ξ² β†’ total_function instance total_function.inhabited [inhabited Ξ²] : inhabited (total_function Ξ± Ξ²) := ⟨ total_function.with_default βˆ… default ⟩ namespace total_function /-- Apply a total function to an argument. -/ def apply [decidable_eq Ξ±] : total_function Ξ± Ξ² β†’ Ξ± β†’ Ξ² | (total_function.with_default m y) x := (m.lookup x).get_or_else y /-- Implementation of `has_repr (total_function Ξ± Ξ²)`. Creates a string for a given `finmap` and output, `xβ‚€ ↦ yβ‚€, .. xβ‚™ ↦ yβ‚™` for each of the entries. The brackets are provided by the calling function. -/ def repr_aux [has_repr Ξ±] [has_repr Ξ²] (m : list (Ξ£ _ : Ξ±, Ξ²)) : string := string.join $ list.qsort (Ξ» x y, x < y) (m.map $ Ξ» x, sformat!"{repr $ sigma.fst x} ↦ {repr $ sigma.snd x}, ") /-- Produce a string for a given `total_function`. The output is of the form `[xβ‚€ ↦ f xβ‚€, .. xβ‚™ ↦ f xβ‚™, _ ↦ y]`. -/ protected def repr [has_repr Ξ±] [has_repr Ξ²] : total_function Ξ± Ξ² β†’ string | (total_function.with_default m y) := sformat!"[{repr_aux m}_ ↦ {has_repr.repr y}]" instance (Ξ± : Type u) (Ξ² : Type v) [has_repr Ξ±] [has_repr Ξ²] : has_repr (total_function Ξ± Ξ²) := ⟨ total_function.repr ⟩ /-- Create a `finmap` from a list of pairs. -/ def list.to_finmap' (xs : list (Ξ± Γ— Ξ²)) : list (Ξ£ _ : Ξ±, Ξ²) := xs.map prod.to_sigma section variables [sampleable Ξ±] [sampleable Ξ²] /-- Redefine `sizeof` to follow the structure of `sampleable` instances. -/ def total.sizeof : total_function Ξ± Ξ² β†’ β„• | ⟨m, x⟩ := 1 + @sizeof _ sampleable.wf m + sizeof x @[priority 2000] instance : has_sizeof (total_function Ξ± Ξ²) := ⟨ total.sizeof ⟩ variables [decidable_eq Ξ±] /-- Shrink a total function by shrinking the lists that represent it. -/ protected def shrink : shrink_fn (total_function Ξ± Ξ²) | ⟨m, x⟩ := (sampleable.shrink (m, x)).map $ Ξ» ⟨⟨m', x'⟩, h⟩, ⟨⟨list.erase_dupkeys m', x'⟩, lt_of_le_of_lt (by unfold_wf; refine @list.sizeof_erase_dupkeys _ _ _ (@sampleable.wf _ _) _) h ⟩ variables [has_repr Ξ±] [has_repr Ξ²] instance pi.sampleable_ext : sampleable_ext (Ξ± β†’ Ξ²) := { proxy_repr := total_function Ξ± Ξ², interp := total_function.apply, sample := do { xs ← (sampleable.sample (list (Ξ± Γ— Ξ²)) : gen ((list (Ξ± Γ— Ξ²)))), ⟨x⟩ ← (uliftable.up $ sample Ξ² : gen (ulift.{max u v} Ξ²)), pure $ total_function.with_default (list.to_finmap' xs) x }, shrink := total_function.shrink } end section finsupp variables [has_zero Ξ²] /-- Map a total_function to one whose default value is zero so that it represents a finsupp. -/ @[simp] def zero_default : total_function Ξ± Ξ² β†’ total_function Ξ± Ξ² | (with_default A y) := with_default A 0 variables [decidable_eq Ξ±] [decidable_eq Ξ²] /-- The support of a zero default `total_function`. -/ @[simp] def zero_default_supp : total_function Ξ± Ξ² β†’ finset Ξ± | (with_default A y) := list.to_finset $ (A.erase_dupkeys.filter (Ξ» ab, sigma.snd ab β‰  0)).map sigma.fst /-- Create a finitely supported function from a total function by taking the default value to zero. -/ def apply_finsupp (tf : total_function Ξ± Ξ²) : Ξ± β†’β‚€ Ξ² := { support := zero_default_supp tf, to_fun := tf.zero_default.apply, mem_support_to_fun := begin intro a, rcases tf with ⟨A, y⟩, simp only [apply, zero_default_supp, list.mem_map, list.mem_filter, exists_and_distrib_right, list.mem_to_finset, exists_eq_right, sigma.exists, ne.def, zero_default], split, { rintro ⟨od, hval, hod⟩, have := list.mem_lookup (list.nodupkeys_erase_dupkeys A) hval, rw (_ : list.lookup a A = od), { simpa, }, { simpa [list.lookup_erase_dupkeys, with_top.some_eq_coe], }, }, { intro h, use (A.lookup a).get_or_else (0 : Ξ²), rw ← list.lookup_erase_dupkeys at h ⊒, simp only [h, ←list.mem_lookup_iff A.nodupkeys_erase_dupkeys, and_true, not_false_iff, option.mem_def], cases list.lookup a A.erase_dupkeys, { simpa using h, }, { simp, }, } end } variables [sampleable Ξ±] [sampleable Ξ²] instance finsupp.sampleable_ext [has_repr Ξ±] [has_repr Ξ²] : sampleable_ext (Ξ± β†’β‚€ Ξ²) := { proxy_repr := total_function Ξ± Ξ², interp := total_function.apply_finsupp, sample := (do xs ← (sampleable.sample (list (Ξ± Γ— Ξ²)) : gen (list (Ξ± Γ— Ξ²))), ⟨x⟩ ← (uliftable.up $ sample Ξ² : gen (ulift.{max u v} Ξ²)), pure $ total_function.with_default (list.to_finmap' xs) x), shrink := total_function.shrink } -- TODO: support a non-constant codomain type instance dfinsupp.sampleable_ext [has_repr Ξ±] [has_repr Ξ²] : sampleable_ext (Ξ β‚€ a : Ξ±, Ξ²) := { proxy_repr := total_function Ξ± Ξ², interp := finsupp.to_dfinsupp ∘ total_function.apply_finsupp, sample := (do xs ← (sampleable.sample (list (Ξ± Γ— Ξ²)) : gen (list (Ξ± Γ— Ξ²))), ⟨x⟩ ← (uliftable.up $ sample Ξ² : gen (ulift.{max u v} Ξ²)), pure $ total_function.with_default (list.to_finmap' xs) x), shrink := total_function.shrink } end finsupp section sampleable_ext open sampleable_ext @[priority 2000] instance pi_pred.sampleable_ext [sampleable_ext (Ξ± β†’ bool)] : sampleable_ext.{u+1} (Ξ± β†’ Prop) := { proxy_repr := proxy_repr (Ξ± β†’ bool), interp := Ξ» m x, interp (Ξ± β†’ bool) m x, sample := sample (Ξ± β†’ bool), shrink := shrink } @[priority 2000] instance pi_uncurry.sampleable_ext [sampleable_ext (Ξ± Γ— Ξ² β†’ Ξ³)] : sampleable_ext.{(imax (u+1) (v+1) w)} (Ξ± β†’ Ξ² β†’ Ξ³) := { proxy_repr := proxy_repr (Ξ± Γ— Ξ² β†’ Ξ³), interp := Ξ» m x y, interp (Ξ± Γ— Ξ² β†’ Ξ³) m (x, y), sample := sample (Ξ± Γ— Ξ² β†’ Ξ³), shrink := shrink } end sampleable_ext end total_function /-- Data structure specifying a total function using a list of pairs and a default value returned when the input is not in the domain of the partial function. `map_to_self f` encodes `x ↦ f x` when `x ∈ f` and `x ↦ x`, i.e. `x` to itself, otherwise. We use `Ξ£` to encode mappings instead of `Γ—` because we rely on the association list API defined in `data.list.sigma`. -/ inductive injective_function (Ξ± : Type u) : Type u | map_to_self (xs : list (Ξ£ _ : Ξ±, Ξ±)) : xs.map sigma.fst ~ xs.map sigma.snd β†’ list.nodup (xs.map sigma.snd) β†’ injective_function instance : inhabited (injective_function Ξ±) := ⟨ ⟨ [], list.perm.nil, list.nodup_nil ⟩ ⟩ namespace injective_function /-- Apply a total function to an argument. -/ def apply [decidable_eq Ξ±] : injective_function Ξ± β†’ Ξ± β†’ Ξ± | (injective_function.map_to_self m _ _) x := (m.lookup x).get_or_else x /-- Produce a string for a given `total_function`. The output is of the form `[xβ‚€ ↦ f xβ‚€, .. xβ‚™ ↦ f xβ‚™, x ↦ x]`. Unlike for `total_function`, the default value is not a constant but the identity function. -/ protected def repr [has_repr Ξ±] : injective_function Ξ± β†’ string | (injective_function.map_to_self m _ _) := sformat!"[{total_function.repr_aux m}x ↦ x]" instance (Ξ± : Type u) [has_repr Ξ±] : has_repr (injective_function Ξ±) := ⟨ injective_function.repr ⟩ /-- Interpret a list of pairs as a total function, defaulting to the identity function when no entries are found for a given function -/ def list.apply_id [decidable_eq Ξ±] (xs : list (Ξ± Γ— Ξ±)) (x : Ξ±) : Ξ± := ((xs.map prod.to_sigma).lookup x).get_or_else x @[simp] lemma list.apply_id_cons [decidable_eq Ξ±] (xs : list (Ξ± Γ— Ξ±)) (x y z : Ξ±) : list.apply_id ((y, z) :: xs) x = if y = x then z else list.apply_id xs x := by simp only [list.apply_id, list.lookup, eq_rec_constant, prod.to_sigma, list.map]; split_ifs; refl open function _root_.list _root_.prod (to_sigma) open _root_.nat lemma list.apply_id_zip_eq [decidable_eq Ξ±] {xs ys : list Ξ±} (hβ‚€ : list.nodup xs) (h₁ : xs.length = ys.length) (x y : Ξ±) (i : β„•) (hβ‚‚ : xs.nth i = some x) : list.apply_id.{u} (xs.zip ys) x = y ↔ ys.nth i = some y := begin induction xs generalizing ys i, case list.nil : ys i h₁ hβ‚‚ { cases hβ‚‚ }, case list.cons : x' xs xs_ih ys i h₁ hβ‚‚ { cases i, { injection hβ‚‚ with hβ‚€ h₁, subst hβ‚€, cases ys, { cases h₁ }, { simp only [list.apply_id, to_sigma, option.get_or_else_some, nth, lookup_cons_eq, zip_cons_cons, list.map], } }, { cases ys, { cases h₁ }, { cases hβ‚€ with _ _ hβ‚€ h₁, simp only [nth, zip_cons_cons, list.apply_id_cons] at hβ‚‚ ⊒, rw if_neg, { apply xs_ih; solve_by_elim [succ.inj] }, { apply hβ‚€, apply nth_mem hβ‚‚ } } } } end lemma apply_id_mem_iff [decidable_eq Ξ±] {xs ys : list Ξ±} (hβ‚€ : list.nodup xs) (h₁ : xs ~ ys) (x : Ξ±) : list.apply_id.{u} (xs.zip ys) x ∈ ys ↔ x ∈ xs := begin simp only [list.apply_id], cases h₃ : (lookup x (map prod.to_sigma (xs.zip ys))), { dsimp [option.get_or_else], rw h₁.mem_iff }, { have hβ‚‚ : ys.nodup := h₁.nodup_iff.1 hβ‚€, replace h₁ : xs.length = ys.length := h₁.length_eq, dsimp, induction xs generalizing ys, case list.nil : ys h₃ hβ‚‚ h₁ { contradiction }, case list.cons : x' xs xs_ih ys h₃ hβ‚‚ h₁ { cases ys with y ys, { cases h₃ }, dsimp [lookup] at h₃, split_ifs at h₃, { subst x', subst val, simp only [mem_cons_iff, true_or, eq_self_iff_true], }, { cases hβ‚€ with _ _ hβ‚€ hβ‚…, cases hβ‚‚ with _ _ hβ‚‚ hβ‚„, have h₆ := nat.succ.inj h₁, specialize @xs_ih hβ‚… ys h₃ hβ‚„ h₆, simp only [ne.symm h, xs_ih, mem_cons_iff, false_or], suffices : val ∈ ys, tauto!, erw [← option.mem_def, mem_lookup_iff] at h₃, simp only [to_sigma, mem_map, heq_iff_eq, prod.exists] at h₃, rcases h₃ with ⟨a, b, h₃, hβ‚„, hβ‚…βŸ©, subst a, subst b, apply (mem_zip h₃).2, simp only [nodupkeys, keys, comp, prod.fst_to_sigma, map_map], rwa map_fst_zip _ _ (le_of_eq h₆) } } } end lemma list.apply_id_eq_self [decidable_eq Ξ±] {xs ys : list Ξ±} (x : Ξ±) : x βˆ‰ xs β†’ list.apply_id.{u} (xs.zip ys) x = x := begin intro h, dsimp [list.apply_id], rw lookup_eq_none.2, refl, simp only [keys, not_exists, to_sigma, exists_and_distrib_right, exists_eq_right, mem_map, comp_app, map_map, prod.exists], intros y hy, exact h (mem_zip hy).1, end lemma apply_id_injective [decidable_eq Ξ±] {xs ys : list Ξ±} (hβ‚€ : list.nodup xs) (h₁ : xs ~ ys) : injective.{u+1 u+1} (list.apply_id (xs.zip ys)) := begin intros x y h, by_cases hx : x ∈ xs; by_cases hy : y ∈ xs, { rw mem_iff_nth at hx hy, cases hx with i hx, cases hy with j hy, suffices : some x = some y, { injection this }, have hβ‚‚ := h₁.length_eq, rw [list.apply_id_zip_eq hβ‚€ hβ‚‚ _ _ _ hx] at h, rw [← hx, ← hy], congr, apply nth_injective _ (h₁.nodup_iff.1 hβ‚€), { symmetry, rw h, rw ← list.apply_id_zip_eq; assumption }, { rw ← h₁.length_eq, rw nth_eq_some at hx, cases hx with hx hx', exact hx } }, { rw ← apply_id_mem_iff hβ‚€ h₁ at hx hy, rw h at hx, contradiction, }, { rw ← apply_id_mem_iff hβ‚€ h₁ at hx hy, rw h at hx, contradiction, }, { rwa [list.apply_id_eq_self, list.apply_id_eq_self] at h; assumption }, end open total_function (list.to_finmap') open sampleable /-- Remove a slice of length `m` at index `n` in a list and a permutation, maintaining the property that it is a permutation. -/ def perm.slice [decidable_eq Ξ±] (n m : β„•) : (Ξ£' xs ys : list Ξ±, xs ~ ys ∧ ys.nodup) β†’ (Ξ£' xs ys : list Ξ±, xs ~ ys ∧ ys.nodup) | ⟨xs, ys, h, h'⟩ := let xs' := list.slice n m xs in have hβ‚€ : xs' ~ ys.inter xs', from perm.slice_inter _ _ h h', ⟨xs', ys.inter xs', hβ‚€, nodup_inter_of_nodup _ h'⟩ /-- A lazy list, in decreasing order, of sizes that should be sliced off a list of length `n` -/ def slice_sizes : β„• β†’ lazy_list β„•+ | n := if h : 0 < n then have n / 2 < n, from div_lt_self h dec_trivial, lazy_list.cons ⟨_, h⟩ (slice_sizes $ n / 2) else lazy_list.nil /-- Shrink a permutation of a list, slicing a segment in the middle. The sizes of the slice being removed start at `n` (with `n` the length of the list) and then `n / 2`, then `n / 4`, etc down to 1. The slices will be taken at index `0`, `n / k`, `2n / k`, `3n / k`, etc. -/ protected def shrink_perm {Ξ± : Type} [decidable_eq Ξ±] [has_sizeof Ξ±] : shrink_fn (Ξ£' xs ys : list Ξ±, xs ~ ys ∧ ys.nodup) | xs := do let k := xs.1.length, n ← slice_sizes k, i ← lazy_list.of_list $ list.fin_range $ k / n, have ↑i * ↑n < xs.1.length, from nat.lt_of_div_lt_div (lt_of_le_of_lt (by simp only [nat.mul_div_cancel, gt_iff_lt, fin.val_eq_coe, pnat.pos]) i.2), pure ⟨perm.slice (i*n) n xs, by rcases xs with ⟨a,b,c,d⟩; dsimp [sizeof_lt]; unfold_wf; simp only [perm.slice]; unfold_wf; apply list.sizeof_slice_lt _ _ n.2 _ this⟩ instance [has_sizeof Ξ±] : has_sizeof (injective_function Ξ±) := ⟨ Ξ» ⟨xs,_,_⟩, sizeof (xs.map sigma.fst) ⟩ /-- Shrink an injective function slicing a segment in the middle of the domain and removing the corresponding elements in the codomain, hence maintaining the property that one is a permutation of the other. -/ protected def shrink {Ξ± : Type} [has_sizeof Ξ±] [decidable_eq Ξ±] : shrink_fn (injective_function Ξ±) | ⟨xs, hβ‚€, hβ‚βŸ© := do ⟨⟨xs', ys', hβ‚€, hβ‚βŸ©, hβ‚‚βŸ© ← injective_function.shrink_perm ⟨_, _, hβ‚€, hβ‚βŸ©, have h₃ : xs'.length ≀ ys'.length, from le_of_eq (perm.length_eq hβ‚€), have hβ‚„ : ys'.length ≀ xs'.length, from le_of_eq (perm.length_eq hβ‚€.symm), pure ⟨⟨(list.zip xs' ys').map prod.to_sigma, by simp only [comp, map_fst_zip, map_snd_zip, *, prod.fst_to_sigma, prod.snd_to_sigma, map_map], by simp only [comp, map_snd_zip, *, prod.snd_to_sigma, map_map] ⟩, by revert hβ‚‚; dsimp [sizeof_lt]; unfold_wf; simp only [has_sizeof._match_1, map_map, comp, map_fst_zip, *, prod.fst_to_sigma]; unfold_wf; intro hβ‚‚; convert hβ‚‚ ⟩ /-- Create an injective function from one list and a permutation of that list. -/ protected def mk (xs ys : list Ξ±) (h : xs ~ ys) (h' : ys.nodup) : injective_function Ξ± := have hβ‚€ : xs.length ≀ ys.length, from le_of_eq h.length_eq, have h₁ : ys.length ≀ xs.length, from le_of_eq h.length_eq.symm, injective_function.map_to_self (list.to_finmap' (xs.zip ys)) (by { simp only [list.to_finmap', comp, map_fst_zip, map_snd_zip, *, prod.fst_to_sigma, prod.snd_to_sigma, map_map] }) (by { simp only [list.to_finmap', comp, map_snd_zip, *, prod.snd_to_sigma, map_map] }) protected lemma injective [decidable_eq Ξ±] (f : injective_function Ξ±) : injective (apply f) := begin cases f with xs hperm hnodup, generalize hβ‚€ : map sigma.fst xs = xsβ‚€, generalize h₁ : xs.map (@id ((Ξ£ _ : Ξ±, Ξ±) β†’ Ξ±) $ @sigma.snd Ξ± (Ξ» _ : Ξ±, Ξ±)) = xs₁, dsimp [id] at h₁, have hxs : xs = total_function.list.to_finmap' (xsβ‚€.zip xs₁), { rw [← hβ‚€, ← h₁, list.to_finmap'], clear hβ‚€ h₁ xsβ‚€ xs₁ hperm hnodup, induction xs, case list.nil { simp only [zip_nil_right, map_nil] }, case list.cons : xs_hd xs_tl xs_ih { simp only [true_and, to_sigma, eq_self_iff_true, sigma.eta, zip_cons_cons, list.map], exact xs_ih }, }, revert hperm hnodup, rw hxs, intros, apply apply_id_injective, { rwa [← hβ‚€, hxs, hperm.nodup_iff], }, { rwa [← hxs, hβ‚€, h₁] at hperm, }, end instance pi_injective.sampleable_ext : sampleable_ext { f : β„€ β†’ β„€ // function.injective f } := { proxy_repr := injective_function β„€, interp := Ξ» f, ⟨ apply f, f.injective ⟩, sample := gen.sized $ Ξ» sz, do { let xs' := int.range (-(2*sz+2)) (2*sz + 2), ys ← gen.permutation_of xs', have Hinj : injective (Ξ» (r : β„•), -(2*sz + 2 : β„€) + ↑r), from Ξ» x y h, int.coe_nat_inj (add_right_injective _ h), let r : injective_function β„€ := injective_function.mk.{0} xs' ys.1 ys.2 (ys.2.nodup_iff.1 $ nodup_map Hinj (nodup_range _)) in pure r }, shrink := @injective_function.shrink β„€ _ _ } end injective_function open function instance injective.testable (f : Ξ± β†’ Ξ²) [I : testable (named_binder "x" $ βˆ€ x : Ξ±, named_binder "y" $ βˆ€ y : Ξ±, named_binder "H" $ f x = f y β†’ x = y)] : testable (injective f) := I instance monotone.testable [preorder Ξ±] [preorder Ξ²] (f : Ξ± β†’ Ξ²) [I : testable (named_binder "x" $ βˆ€ x : Ξ±, named_binder "y" $ βˆ€ y : Ξ±, named_binder "H" $ x ≀ y β†’ f x ≀ f y)] : testable (monotone f) := I instance antitone.testable [preorder Ξ±] [preorder Ξ²] (f : Ξ± β†’ Ξ²) [I : testable (named_binder "x" $ βˆ€ x : Ξ±, named_binder "y" $ βˆ€ y : Ξ±, named_binder "H" $ x ≀ y β†’ f y ≀ f x)] : testable (antitone f) := I end slim_check
18450c6f7bd35c4decf9cc2d5f17d1bfb3e7d7ec
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebraic_geometry/sheafed_space.lean
019a839fafaed920996791ab89cd317127c05f54
[ "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
4,580
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 algebraic_geometry.presheafed_space import topology.sheaves.sheaf /-! # Sheafed spaces Introduces the category of topological spaces equipped with a sheaf (taking values in an arbitrary target category `C`.) We further describe how to apply functors and natural transformations to the values of the presheaves. -/ universes v u open category_theory open Top open topological_space open opposite open category_theory.limits open category_theory.category category_theory.functor variables (C : Type u) [category.{v} C] [limits.has_products C] local attribute [tidy] tactic.op_induction' namespace algebraic_geometry /-- A `SheafedSpace C` is a topological space equipped with a sheaf of `C`s. -/ structure SheafedSpace extends PresheafedSpace C := (sheaf_condition : presheaf.sheaf_condition) variables {C} namespace SheafedSpace instance coe_carrier : has_coe (SheafedSpace C) Top := { coe := Ξ» X, X.carrier } /-- Extract the `sheaf C (X : Top)` from a `SheafedSpace C`. -/ def sheaf (X : SheafedSpace C) : sheaf C (X : Top.{v}) := ⟨X.presheaf, X.sheaf_condition⟩ @[simp] lemma as_coe (X : SheafedSpace C) : X.carrier = (X : Top.{v}) := rfl @[simp] lemma mk_coe (carrier) (presheaf) (h) : (({ carrier := carrier, presheaf := presheaf, sheaf_condition := h } : SheafedSpace.{v} C) : Top.{v}) = carrier := rfl instance (X : SheafedSpace.{v} C) : topological_space X := X.carrier.str /-- The trivial `punit` valued sheaf on any topological space. -/ noncomputable def punit (X : Top) : SheafedSpace (discrete punit) := { sheaf_condition := presheaf.sheaf_condition_punit _, ..@PresheafedSpace.const (discrete punit) _ X punit.star } noncomputable instance : inhabited (SheafedSpace (discrete _root_.punit)) := ⟨punit (Top.of pempty)⟩ instance : category (SheafedSpace C) := show category (induced_category (PresheafedSpace C) SheafedSpace.to_PresheafedSpace), by apply_instance /-- Forgetting the sheaf condition is a functor from `SheafedSpace C` to `PresheafedSpace C`. -/ def forget_to_PresheafedSpace : (SheafedSpace C) β₯€ (PresheafedSpace C) := induced_functor _ variables {C} section local attribute [simp] id comp @[simp] lemma id_base (X : SheafedSpace C) : ((πŸ™ X) : X ⟢ X).base = (πŸ™ (X : Top.{v})) := rfl lemma id_c (X : SheafedSpace C) : ((πŸ™ X) : X ⟢ X).c = (((functor.left_unitor _).inv) ≫ (whisker_right (nat_trans.op (opens.map_id (X.carrier)).hom) _)) := rfl @[simp] lemma id_c_app (X : SheafedSpace C) (U) : ((πŸ™ X) : X ⟢ X).c.app U = eq_to_hom (by { op_induction U, cases U, refl }) := by { op_induction U, cases U, simp only [id_c], dsimp, simp, } @[simp] lemma comp_base {X Y Z : SheafedSpace C} (f : X ⟢ Y) (g : Y ⟢ Z) : (f ≫ g).base = f.base ≫ g.base := rfl @[simp] lemma comp_c_app {X Y Z : SheafedSpace C} (Ξ± : X ⟢ Y) (Ξ² : Y ⟢ Z) (U) : (Ξ± ≫ Ξ²).c.app U = (Ξ².c).app U ≫ (Ξ±.c).app (op ((opens.map (Ξ².base)).obj (unop U))) ≫ (Top.presheaf.pushforward.comp _ _ _).inv.app U := rfl variables (C) /-- The forgetful functor from `SheafedSpace` to `Top`. -/ def forget : SheafedSpace C β₯€ Top := { obj := Ξ» X, (X : Top.{v}), map := Ξ» X Y f, f.base } end open Top.presheaf /-- The restriction of a sheafed space along an open embedding into the space. -/ noncomputable def restrict {U : Top} (X : SheafedSpace C) (f : U ⟢ (X : Top.{v})) (h : open_embedding f) : SheafedSpace C := { sheaf_condition := Ξ» ΞΉ 𝒰, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv _ _).inv_fun (X.sheaf_condition _)) (sheaf_condition_equalizer_products.fork.iso_of_open_embedding h 𝒰).symm, ..X.to_PresheafedSpace.restrict f h } /-- The global sections, notated Gamma. -/ def Ξ“ : (SheafedSpace C)α΅’α΅– β₯€ C := forget_to_PresheafedSpace.op β‹™ PresheafedSpace.Ξ“ lemma Ξ“_def : (Ξ“ : _ β₯€ C) = forget_to_PresheafedSpace.op β‹™ PresheafedSpace.Ξ“ := rfl @[simp] lemma Ξ“_obj (X : (SheafedSpace C)α΅’α΅–) : Ξ“.obj X = (unop X).presheaf.obj (op ⊀) := rfl lemma Ξ“_obj_op (X : SheafedSpace C) : Ξ“.obj (op X) = X.presheaf.obj (op ⊀) := rfl @[simp] lemma Ξ“_map {X Y : (SheafedSpace C)α΅’α΅–} (f : X ⟢ Y) : Ξ“.map f = f.unop.c.app (op ⊀) ≫ (unop Y).presheaf.map (opens.le_map_top _ _).op := rfl lemma Ξ“_map_op {X Y : SheafedSpace C} (f : X ⟢ Y) : Ξ“.map f.op = f.c.app (op ⊀) ≫ X.presheaf.map (opens.le_map_top _ _).op := rfl end SheafedSpace end algebraic_geometry
d68bd226207916442ff847ed710ca998bc646951
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/omega/nat/sub_elim.lean
c487e5ee8041cc33c7f7fdcb5a81a66271d2d4d1
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
5,702
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Subtraction elimination for linear natural number arithmetic. Works by repeatedly rewriting goals of the preform `P[t-s]` into `P[x] ∧ (t = s + x ∨ (t ≀ s ∧ x = 0))`, where `x` is fresh. -/ import tactic.omega.nat.form namespace omega namespace nat open_locale omega.nat namespace preterm /-- Find subtraction inside preterm and return its operands -/ def sub_terms : preterm β†’ option (preterm Γ— preterm) | (& i) := none | (i ** n) := none | (t +* s) := t.sub_terms <|> s.sub_terms | (t -* s) := t.sub_terms <|> s.sub_terms <|> some (t,s) /-- Find (t - s) inside a preterm and replace it with variable k -/ def sub_subst (t s : preterm) (k : nat) : preterm β†’ preterm | t@(& m) := t | t@(m ** n) := t | (x +* y) := x.sub_subst +* y.sub_subst | (x -* y) := if x = t ∧ y = s then (1 ** k) else x.sub_subst -* y.sub_subst lemma val_sub_subst {k : nat} {x y : preterm} {v : nat β†’ nat} : βˆ€ {t : preterm}, t.fresh_index ≀ k β†’ (sub_subst x y k t).val (update k (x.val v - y.val v) v) = t.val v | (& m) h1 := rfl | (m ** n) h1 := begin have h2 : n β‰  k := ne_of_lt h1, simp only [sub_subst, preterm.val], rw update_eq_of_ne _ h2, end | (t +* s) h1 := begin simp only [sub_subst, val_add], apply fun_mono_2; apply val_sub_subst (le_trans _ h1), apply le_max_left, apply le_max_right end | (t -* s) h1 := begin simp only [sub_subst, val_sub], by_cases h2 : t = x ∧ s = y, { rw if_pos h2, simp only [val_var, one_mul], rw [update_eq, h2.left, h2.right] }, { rw if_neg h2, simp only [val_sub, sub_subst], apply fun_mono_2; apply val_sub_subst (le_trans _ h1), apply le_max_left, apply le_max_right, } end end preterm namespace preform /-- Find subtraction inside preform and return its operands -/ def sub_terms : preform β†’ option (preterm Γ— preterm) | (t =* s) := t.sub_terms <|> s.sub_terms | (t ≀* s) := t.sub_terms <|> s.sub_terms | (Β¬* p) := p.sub_terms | (p ∨* q) := p.sub_terms <|> q.sub_terms | (p ∧* q) := p.sub_terms <|> q.sub_terms /-- Find (t - s) inside a preform and replace it with variable k -/ @[simp] def sub_subst (x y : preterm) (k : nat) : preform β†’ preform | (t =* s) := preterm.sub_subst x y k t =* preterm.sub_subst x y k s | (t ≀* s) := preterm.sub_subst x y k t ≀* preterm.sub_subst x y k s | (Β¬* p) := Β¬* p.sub_subst | (p ∨* q) := p.sub_subst ∨* q.sub_subst | (p ∧* q) := p.sub_subst ∧* q.sub_subst end preform /-- Preform which asserts that the value of variable k is the truncated difference between preterms t and s -/ def is_diff (t s : preterm) (k : nat) : preform := ((t =* (s +* (1 ** k))) ∨* (t ≀* s ∧* ((1 ** k) =* &0))) lemma holds_is_diff {t s : preterm} {k : nat} {v : nat β†’ nat} : v k = t.val v - s.val v β†’ (is_diff t s k).holds v := begin intro h1, simp only [preform.holds, is_diff, if_pos (eq.refl 1), preterm.val_add, preterm.val_var, preterm.val_const], by_cases h2 : t.val v ≀ s.val v, { right, refine ⟨h2,_⟩, rw [h1, one_mul, nat.sub_eq_zero_iff_le], exact h2 }, { left, rw [h1, one_mul, add_comm, nat.sub_add_cancel _], rw not_le at h2, apply le_of_lt h2 } end /-- Helper function for sub_elim -/ def sub_elim_core (t s : preterm) (k : nat) (p : preform) : preform := (preform.sub_subst t s k p) ∧* (is_diff t s k) /-- Return de Brujin index of fresh variable that does not occur in any of the arguments -/ def sub_fresh_index (t s : preterm) (p : preform) : nat := max p.fresh_index (max t.fresh_index s.fresh_index) /-- Return a new preform with all subtractions eliminated -/ def sub_elim (t s : preterm) (p : preform) : preform := sub_elim_core t s (sub_fresh_index t s p) p lemma sub_subst_equiv {k : nat} {x y : preterm} {v : nat β†’ nat} : βˆ€ p : preform, p.fresh_index ≀ k β†’ ((preform.sub_subst x y k p).holds (update k (x.val v - y.val v) v) ↔ (p.holds v)) | (t =* s) h1 := begin simp only [preform.holds, preform.sub_subst], apply pred_mono_2; apply preterm.val_sub_subst (le_trans _ h1), apply le_max_left, apply le_max_right end | (t ≀* s) h1 := begin simp only [preform.holds, preform.sub_subst], apply pred_mono_2; apply preterm.val_sub_subst (le_trans _ h1), apply le_max_left, apply le_max_right end | (Β¬* p) h1 := by { apply not_iff_not_of_iff, apply sub_subst_equiv p h1 } | (p ∨* q) h1 := begin simp only [preform.holds, preform.sub_subst], apply pred_mono_2; apply propext; apply sub_subst_equiv _ (le_trans _ h1), apply le_max_left, apply le_max_right end | (p ∧* q) h1 := begin simp only [preform.holds, preform.sub_subst], apply pred_mono_2; apply propext; apply sub_subst_equiv _ (le_trans _ h1), apply le_max_left, apply le_max_right end lemma sat_sub_elim {t s : preterm} {p : preform} : p.sat β†’ (sub_elim t s p).sat := begin intro h1, simp only [sub_elim, sub_elim_core], cases h1 with v h1, refine ⟨update (sub_fresh_index t s p) (t.val v - s.val v) v, _⟩, constructor, { apply (sub_subst_equiv p _).elim_right h1, apply le_max_left }, { apply holds_is_diff, rw update_eq, apply fun_mono_2; apply preterm.val_constant; intros x h2; rw update_eq_of_ne _ (ne.symm (ne_of_gt _)); apply lt_of_lt_of_le h2; apply le_trans _ (le_max_right _ _), apply le_max_left, apply le_max_right } end lemma unsat_of_unsat_sub_elim (t s : preterm) (p : preform) : (sub_elim t s p).unsat β†’ p.unsat := mt sat_sub_elim end nat end omega
60681320e11c86fd37f087def9055a4b7139bb06
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/preadditive/projective_resolution.lean
d04bcf9f2bbb56297a8893354faeaadf0b2ed971
[ "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
12,990
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.projective import algebra.homology.single import algebra.homology.homotopy_category /-! # Projective resolutions A projective resolution `P : ProjectiveResolution Z` of an object `Z : C` consists of a `β„•`-indexed chain complex `P.complex` of projective objects, along with a chain map `P.Ο€` from `C` to the chain complex consisting just of `Z` in degree zero, so that the augmented chain complex is exact. When `C` is abelian, this exactness condition is equivalent to `Ο€` being a quasi-isomorphism. It turns out that this formulation allows us to set up the basic theory of derived functors without even assuming `C` is abelian. (Typically, however, to show `has_projective_resolutions C` one will assume `enough_projectives C` and `abelian C`. This construction appears in `category_theory.abelian.projectives`.) We show that given `P : ProjectiveResolution X` and `Q : ProjectiveResolution Y`, any morphism `X ⟢ Y` admits a lift to a chain map `P.complex ⟢ Q.complex`. (It is a lift in the sense that the projection maps `P.Ο€` and `Q.Ο€` intertwine the lift and the original morphism.) Moreover, we show that any two such lifts are homotopic. As a consequence, if every object admits a projective resolution, we can construct a functor `projective_resolutions C : C β₯€ homotopy_category C`. -/ noncomputable theory open category_theory open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] open projective section variables [has_zero_object C] [has_zero_morphisms C] [has_equalizers C] [has_images C] /-- A `ProjectiveResolution Z` consists of a bundled `β„•`-indexed chain complex of projective objects, along with a quasi-isomorphism to the complex consisting of just `Z` supported in degree `0`. (We don't actually ask here that the chain map is a quasi-iso, just exactness everywhere: that `Ο€` is a quasi-iso is a lemma when the category is abelian. Should we just ask for it here?) Except in situations where you want to provide a particular projective resolution (for example to compute a derived functor), you will not typically need to use this bundled object, and will instead use * `projective_resolution Z`: the `β„•`-indexed chain complex (equipped with `projective` and `exact` instances) * `projective_resolution.Ο€ Z`: the chain map from `projective_resolution Z` to `(single C _ 0).obj Z` (all the components are equipped with `epi` instances, and when the category is `abelian` we will show `Ο€` is a quasi-iso). -/ @[nolint has_nonempty_instance] structure ProjectiveResolution (Z : C) := (complex : chain_complex C β„•) (Ο€ : homological_complex.hom complex ((chain_complex.singleβ‚€ C).obj Z)) (projective : βˆ€ n, projective (complex.X n) . tactic.apply_instance) (exactβ‚€ : exact (complex.d 1 0) (Ο€.f 0)) (exact : βˆ€ n, exact (complex.d (n+2) (n+1)) (complex.d (n+1) n)) (epi : epi (Ο€.f 0) . tactic.apply_instance) attribute [instance] ProjectiveResolution.projective ProjectiveResolution.epi /-- An object admits a projective resolution. -/ class has_projective_resolution (Z : C) : Prop := (out [] : nonempty (ProjectiveResolution Z)) section variables (C) /-- You will rarely use this typeclass directly: it is implied by the combination `[enough_projectives C]` and `[abelian C]`. By itself it's enough to set up the basic theory of derived functors. -/ class has_projective_resolutions : Prop := (out : βˆ€ Z : C, has_projective_resolution Z) attribute [instance, priority 100] has_projective_resolutions.out end namespace ProjectiveResolution @[simp] lemma Ο€_f_succ {Z : C} (P : ProjectiveResolution Z) (n : β„•) : P.Ο€.f (n+1) = 0 := begin apply zero_of_target_iso_zero, dsimp, refl, end @[simp] lemma complex_d_comp_Ο€_f_zero {Z : C} (P : ProjectiveResolution Z) : P.complex.d 1 0 ≫ P.Ο€.f 0 = 0 := P.exactβ‚€.w @[simp] lemma complex_d_succ_comp {Z : C} (P : ProjectiveResolution Z) (n : β„•) : P.complex.d (n + 2) (n + 1) ≫ P.complex.d (n + 1) n = 0 := (P.exact _).w instance {Z : C} (P : ProjectiveResolution Z) (n : β„•) : category_theory.epi (P.Ο€.f n) := by cases n; apply_instance /-- A projective object admits a trivial projective resolution: itself in degree 0. -/ def self (Z : C) [category_theory.projective Z] : ProjectiveResolution Z := { complex := (chain_complex.singleβ‚€ C).obj Z, Ο€ := πŸ™ ((chain_complex.singleβ‚€ C).obj Z), projective := Ξ» n, begin cases n, { dsimp, apply_instance, }, { dsimp, apply_instance, }, end, exactβ‚€ := by { dsimp, exact exact_zero_mono _ }, exact := Ξ» n, by { dsimp, exact exact_of_zero _ _ }, epi := by { dsimp, apply_instance, }, } /-- Auxiliary construction for `lift`. -/ def lift_f_zero {Y Z : C} (f : Y ⟢ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex.X 0 ⟢ Q.complex.X 0 := factor_thru (P.Ο€.f 0 ≫ f) (Q.Ο€.f 0) /-- Auxiliary construction for `lift`. -/ def lift_f_one {Y Z : C} (f : Y ⟢ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex.X 1 ⟢ Q.complex.X 1 := exact.lift (P.complex.d 1 0 ≫ lift_f_zero f P Q) (Q.complex.d 1 0) (Q.Ο€.f 0) Q.exactβ‚€ (by simp [lift_f_zero, P.exactβ‚€.w_assoc]) /-- Auxiliary lemma for `lift`. -/ @[simp] lemma lift_f_one_zero_comm {Y Z : C} (f : Y ⟢ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : lift_f_one f P Q ≫ Q.complex.d 1 0 = P.complex.d 1 0 ≫ lift_f_zero f P Q := begin dsimp [lift_f_zero, lift_f_one], simp, end /-- Auxiliary construction for `lift`. -/ def lift_f_succ {Y Z : C} (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) (n : β„•) (g : P.complex.X n ⟢ Q.complex.X n) (g' : P.complex.X (n+1) ⟢ Q.complex.X (n+1)) (w : g' ≫ Q.complex.d (n+1) n = P.complex.d (n+1) n ≫ g) : Ξ£' g'' : P.complex.X (n+2) ⟢ Q.complex.X (n+2), g'' ≫ Q.complex.d (n+2) (n+1) = P.complex.d (n+2) (n+1) ≫ g' := ⟨exact.lift (P.complex.d (n+2) (n+1) ≫ g') ((Q.complex.d (n+2) (n+1))) (Q.complex.d (n+1) n) (Q.exact _) (by simp [w]), (by simp)⟩ /-- A morphism in `C` lifts to a chain map between projective resolutions. -/ def lift {Y Z : C} (f : Y ⟢ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : P.complex ⟢ Q.complex := chain_complex.mk_hom _ _ (lift_f_zero f _ _) (lift_f_one f _ _) (lift_f_one_zero_comm f _ _) (Ξ» n ⟨g, g', w⟩, lift_f_succ P Q n g g' w) /-- The resolution maps intertwine the lift of a morphism and that morphism. -/ @[simp, reassoc] lemma lift_commutes {Y Z : C} (f : Y ⟢ Z) (P : ProjectiveResolution Y) (Q : ProjectiveResolution Z) : lift f P Q ≫ Q.Ο€ = P.Ο€ ≫ (chain_complex.singleβ‚€ C).map f := by { ext, dsimp [lift, lift_f_zero], apply factor_thru_comp, } -- Now that we've checked this property of the lift, -- we can seal away the actual definition. attribute [irreducible] lift end ProjectiveResolution end namespace ProjectiveResolution variables [has_zero_object C] [preadditive C] [has_equalizers C] [has_images C] /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_zero {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟢ Q.complex) (comm : f ≫ Q.Ο€ = 0) : P.complex.X 0 ⟢ Q.complex.X 1 := exact.lift (f.f 0) (Q.complex.d 1 0) (Q.Ο€.f 0) Q.exactβ‚€ (congr_fun (congr_arg homological_complex.hom.f comm) 0) /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_one {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟢ Q.complex) (comm : f ≫ Q.Ο€ = 0) : P.complex.X 1 ⟢ Q.complex.X 2 := exact.lift (f.f 1 - P.complex.d 1 0 ≫ lift_homotopy_zero_zero f comm) (Q.complex.d 2 1) (Q.complex.d 1 0) (Q.exact _) (by simp [lift_homotopy_zero_zero]) /-- An auxiliary definition for `lift_homotopy_zero`. -/ def lift_homotopy_zero_succ {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟢ Q.complex) (n : β„•) (g : P.complex.X n ⟢ Q.complex.X (n + 1)) (g' : P.complex.X (n + 1) ⟢ Q.complex.X (n + 2)) (w : f.f (n + 1) = P.complex.d (n + 1) n ≫ g + g' ≫ Q.complex.d (n + 2) (n + 1)) : P.complex.X (n + 2) ⟢ Q.complex.X (n + 3) := exact.lift (f.f (n+2) - P.complex.d (n+2) (n+1) ≫ g') (Q.complex.d (n+3) (n+2)) (Q.complex.d (n+2) (n+1)) (Q.exact _) (by simp [w]) /-- Any lift of the zero morphism is homotopic to zero. -/ def lift_homotopy_zero {Y Z : C} {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (f : P.complex ⟢ Q.complex) (comm : f ≫ Q.Ο€ = 0) : homotopy f 0 := homotopy.mk_inductive _ (lift_homotopy_zero_zero f comm) (by simp [lift_homotopy_zero_zero]) (lift_homotopy_zero_one f comm) (by simp [lift_homotopy_zero_one]) (Ξ» n ⟨g, g', w⟩, ⟨lift_homotopy_zero_succ f n g g' w, by simp [lift_homotopy_zero_succ, w]⟩) /-- Two lifts of the same morphism are homotopic. -/ def lift_homotopy {Y Z : C} (f : Y ⟢ Z) {P : ProjectiveResolution Y} {Q : ProjectiveResolution Z} (g h : P.complex ⟢ Q.complex) (g_comm : g ≫ Q.Ο€ = P.Ο€ ≫ (chain_complex.singleβ‚€ C).map f) (h_comm : h ≫ Q.Ο€ = P.Ο€ ≫ (chain_complex.singleβ‚€ C).map f) : homotopy g h := homotopy.equiv_sub_zero.inv_fun (lift_homotopy_zero _ (by simp [g_comm, h_comm])) /-- The lift of the identity morphism is homotopic to the identity chain map. -/ def lift_id_homotopy (X : C) (P : ProjectiveResolution X) : homotopy (lift (πŸ™ X) P P) (πŸ™ P.complex) := by { apply lift_homotopy (πŸ™ X); simp, } /-- The lift of a composition is homotopic to the composition of the lifts. -/ def lift_comp_homotopy {X Y Z : C} (f : X ⟢ Y) (g : Y ⟢ Z) (P : ProjectiveResolution X) (Q : ProjectiveResolution Y) (R : ProjectiveResolution Z) : homotopy (lift (f ≫ g) P R) (lift f P Q ≫ lift g Q R) := by { apply lift_homotopy (f ≫ g); simp, } -- We don't care about the actual definitions of these homotopies. attribute [irreducible] lift_homotopy_zero lift_homotopy lift_id_homotopy lift_comp_homotopy /-- Any two projective resolutions are homotopy equivalent. -/ def homotopy_equiv {X : C} (P Q : ProjectiveResolution X) : homotopy_equiv P.complex Q.complex := { hom := lift (πŸ™ X) P Q, inv := lift (πŸ™ X) Q P, homotopy_hom_inv_id := begin refine (lift_comp_homotopy (πŸ™ X) (πŸ™ X) P Q P).symm.trans _, simp [category.id_comp], apply lift_id_homotopy, end, homotopy_inv_hom_id := begin refine (lift_comp_homotopy (πŸ™ X) (πŸ™ X) Q P Q).symm.trans _, simp [category.id_comp], apply lift_id_homotopy, end, } @[simp, reassoc] lemma homotopy_equiv_hom_Ο€ {X : C} (P Q : ProjectiveResolution X) : (homotopy_equiv P Q).hom ≫ Q.Ο€ = P.Ο€ := by simp [homotopy_equiv] @[simp, reassoc] lemma homotopy_equiv_inv_Ο€ {X : C} (P Q : ProjectiveResolution X) : (homotopy_equiv P Q).inv ≫ P.Ο€ = Q.Ο€ := by simp [homotopy_equiv] end ProjectiveResolution section variables [has_zero_morphisms C] [has_zero_object C] [has_equalizers C] [has_images C] /-- An arbitrarily chosen projective resolution of an object. -/ abbreviation projective_resolution (Z : C) [has_projective_resolution Z] : chain_complex C β„• := (has_projective_resolution.out Z).some.complex /-- The chain map from the arbitrarily chosen projective resolution `projective_resolution Z` back to the chain complex consisting of `Z` supported in degree `0`. -/ abbreviation projective_resolution.Ο€ (Z : C) [has_projective_resolution Z] : projective_resolution Z ⟢ (chain_complex.singleβ‚€ C).obj Z := (has_projective_resolution.out Z).some.Ο€ /-- The lift of a morphism to a chain map between the arbitrarily chosen projective resolutions. -/ abbreviation projective_resolution.lift {X Y : C} (f : X ⟢ Y) [has_projective_resolution X] [has_projective_resolution Y] : projective_resolution X ⟢ projective_resolution Y := ProjectiveResolution.lift f _ _ end variables (C) [preadditive C] [has_zero_object C] [has_equalizers C] [has_images C] [has_projective_resolutions C] /-- Taking projective resolutions is functorial, if considered with target the homotopy category (`β„•`-indexed chain complexes and chain maps up to homotopy). -/ def projective_resolutions : C β₯€ homotopy_category C (complex_shape.down β„•) := { obj := Ξ» X, (homotopy_category.quotient _ _).obj (projective_resolution X), map := Ξ» X Y f, (homotopy_category.quotient _ _).map (projective_resolution.lift f), map_id' := Ξ» X, begin rw ←(homotopy_category.quotient _ _).map_id, apply homotopy_category.eq_of_homotopy, apply ProjectiveResolution.lift_id_homotopy, end, map_comp' := Ξ» X Y Z f g, begin rw ←(homotopy_category.quotient _ _).map_comp, apply homotopy_category.eq_of_homotopy, apply ProjectiveResolution.lift_comp_homotopy, end, } end category_theory
ee55542a67aae0ced92197dac2e48150f2a6d226
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/order.lean
993f3dddc9a550bd798751e11abc9b71702e05d0
[ "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
28,243
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.tactic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `Ξ±` are ordered, by reverse inclusion. That is, for topologies `t₁` and `tβ‚‚` on `Ξ±`, we write `t₁ ≀ tβ‚‚` if every set open in `tβ‚‚` is also open in `t₁`. (One also calls `t₁` finer than `tβ‚‚`, and `tβ‚‚` coarser than `t₁`.) Any function `f : Ξ± β†’ Ξ²` induces `induced f : topological_space Ξ² β†’ topological_space Ξ±` and `coinduced f : topological_space Ξ± β†’ topological_space Ξ²`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map (Ξ±, t₁) β†’ (Ξ±, tβ‚‚) is continuous iff t₁ ≀ tβ‚‚. * A map f : (Ξ±, t) β†’ (Ξ², u) is continuous iff t ≀ induced f u (`continuous_iff_le_induced`) iff coinduced f t ≀ u (`continuous_iff_coinduced_le`). Topologies on Ξ± form a complete lattice, with βŠ₯ the discrete topology and ⊀ the indiscrete topology. For a function f : Ξ± β†’ Ξ², (coinduced f, induced f) is a Galois connection between topologies on Ξ± and topologies on Ξ². ## Implementation notes There is a Galois insertion between topologies on Ξ± (with the inclusion ordering) and all collections of sets in Ξ±. The complete lattice structure on topologies on Ξ± is defined as the reverse of the one obtained via this Galois insertion. ## Tags finer, coarser, induced topology, coinduced topology -/ open set filter classical open_locale classical topological_space filter universes u v w namespace topological_space variables {Ξ± : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set Ξ±)) : set Ξ± β†’ Prop | basic : βˆ€s∈g, generate_open s | univ : generate_open univ | inter : βˆ€s t, generate_open s β†’ generate_open t β†’ generate_open (s ∩ t) | sUnion : βˆ€k, (βˆ€s∈k, generate_open s) β†’ generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set Ξ±)) : topological_space Ξ± := { is_open := generate_open g, is_open_univ := generate_open.univ, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set Ξ±)} {a : Ξ±} : @nhds Ξ± (generate_from g) a = (β¨…s∈{s | a ∈ s ∧ s ∈ g}, π“Ÿ s) := by rw nhds_def; exact le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, begin revert as, clear_, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≀ π“Ÿ s βŠ“ π“Ÿ t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact Ξ» ⟨t, htk, hat⟩, calc _ ≀ π“Ÿ t : hk t htk hat ... ≀ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end) lemma tendsto_nhds_generate_from {Ξ² : Type*} {m : Ξ± β†’ Ξ²} {f : filter Ξ±} {g : set (set Ξ²)} {b : Ξ²} (h : βˆ€s∈g, b ∈ s β†’ m ⁻¹' s ∈ f) : tendsto m f (@nhds Ξ² (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) /-- Construct a topology on Ξ± given the filter of neighborhoods of each point of Ξ±. -/ protected def mk_of_nhds (n : Ξ± β†’ filter Ξ±) : topological_space Ξ± := { is_open := Ξ»s, βˆ€a∈s, s ∈ n a, is_open_univ := assume x h, univ_mem_sets, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : Ξ± β†’ filter Ξ±) (a : Ξ±) (hβ‚€ : pure ≀ n) (h₁ : βˆ€{a s}, s ∈ n a β†’ βˆƒ t ∈ n a, t βŠ† s ∧ βˆ€a' ∈ t, s ∈ n a') : @nhds Ξ± (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have hβ‚€ : {b | s ∈ n b} βŠ† s := assume b hb, mem_pure_sets.1 $ hβ‚€ b hb, have h₁ : {b | s ∈ n b} ∈ 𝓝 a, { refine mem_nhds_sets (assume b (hb : s ∈ n b), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_sets_of_superset ht h }, exact mem_sets_of_superset h₁ hβ‚€ }, { rcases (@mem_nhds_sets_iff Ξ± (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {Ξ± : Type u} {Ξ² : Type v} /-- The inclusion ordering on topologies on Ξ±. We use it to get a complete lattice instance via the Galois insertion method, but the partial order that we will eventually impose on `topological_space Ξ±` is the reverse one. -/ def tmp_order : partial_order (topological_space Ξ±) := { le := Ξ»t s, t.is_open ≀ s.is_open, le_antisymm := assume t s h₁ hβ‚‚, topological_space_eq $ le_antisymm h₁ hβ‚‚, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ hβ‚‚, @le_trans _ _ a.is_open b.is_open c.is_open h₁ hβ‚‚ } local attribute [instance] tmp_order /- We'll later restate this lemma in terms of the correct order on `topological_space Ξ±`. -/ private lemma generate_from_le_iff_subset_is_open {g : set (set Ξ±)} {t : topological_space Ξ±} : topological_space.generate_from g ≀ t ↔ g βŠ† {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mk_of_closure (s : set (set Ξ±)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space Ξ± := { is_open := Ξ»u, u ∈ s, is_open_univ := hs β–Έ topological_space.generate_open.univ, is_open_inter := hs β–Έ topological_space.generate_open.inter, is_open_sUnion := hs β–Έ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set Ξ±)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm /-- The Galois insertion between `set (set Ξ±)` and `topological_space Ξ±` whose lower part sends a collection of subsets of Ξ± to the topology they generate, and whose upper part sends a topology to its collection of open subsets. -/ def gi_generate_from (Ξ± : Type*) : galois_insertion topological_space.generate_from (Ξ»t:topological_space Ξ±, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := Ξ»g hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {Ξ±} {g₁ gβ‚‚ : set (set Ξ±)} (h : g₁ βŠ† gβ‚‚) : topological_space.generate_from g₁ ≀ topological_space.generate_from gβ‚‚ := (gi_generate_from _).gc.monotone_l h /-- The complete lattice of topological spaces, but built on the inclusion ordering. -/ def tmp_complete_lattice {Ξ± : Type u} : complete_lattice (topological_space Ξ±) := (gi_generate_from Ξ±).lift_complete_lattice /-- The ordering on topologies on the type `Ξ±`. `t ≀ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (topological_space Ξ±) := { le := Ξ» t s, s.is_open ≀ t.is_open, le_antisymm := assume t s h₁ hβ‚‚, topological_space_eq $ le_antisymm hβ‚‚ h₁, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ hβ‚‚, le_trans hβ‚‚ h₁ } lemma le_generate_from_iff_subset_is_open {g : set (set Ξ±)} {t : topological_space Ξ±} : t ≀ topological_space.generate_from g ↔ g βŠ† {s | t.is_open s} := generate_from_le_iff_subset_is_open /-- Topologies on `Ξ±` form a complete lattice, with `βŠ₯` the discrete topology and `⊀` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremem is the topology whose open sets are those sets open in every member of the collection. -/ instance : complete_lattice (topological_space Ξ±) := @order_dual.complete_lattice _ tmp_complete_lattice /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `βŠ₯`. -/ class discrete_topology (Ξ± : Type*) [t : topological_space Ξ±] : Prop := (eq_bot [] : t = βŠ₯) @[simp] lemma is_open_discrete [topological_space Ξ±] [discrete_topology Ξ±] (s : set Ξ±) : is_open s := (discrete_topology.eq_bot Ξ±).symm β–Έ trivial @[simp] lemma is_closed_discrete [topological_space Ξ±] [discrete_topology Ξ±] (s : set Ξ±) : is_closed s := (discrete_topology.eq_bot Ξ±).symm β–Έ trivial lemma continuous_of_discrete_topology [topological_space Ξ±] [discrete_topology Ξ±] [topological_space Ξ²] {f : Ξ± β†’ Ξ²} : continuous f := Ξ»s hs, is_open_discrete _ lemma nhds_bot (Ξ± : Type*) : (@nhds Ξ± βŠ₯) = pure := begin refine le_antisymm _ (@pure_le_nhds Ξ± βŠ₯), assume a s hs, exact @mem_nhds_sets Ξ± βŠ₯ a s trivial hs end lemma nhds_discrete (Ξ± : Type*) [topological_space Ξ±] [discrete_topology Ξ±] : (@nhds Ξ± _) = pure := (discrete_topology.eq_bot Ξ±).symm β–Έ nhds_bot Ξ± lemma le_of_nhds_le_nhds {t₁ tβ‚‚ : topological_space Ξ±} (h : βˆ€x, @nhds Ξ± t₁ x ≀ @nhds Ξ± tβ‚‚ x) : t₁ ≀ tβ‚‚ := assume s, show @is_open Ξ± tβ‚‚ s β†’ @is_open Ξ± t₁ s, by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha } lemma eq_of_nhds_eq_nhds {t₁ tβ‚‚ : topological_space Ξ±} (h : βˆ€x, @nhds Ξ± t₁ x = @nhds Ξ± tβ‚‚ x) : t₁ = tβ‚‚ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma eq_bot_of_singletons_open {t : topological_space Ξ±} (h : βˆ€ x, t.is_open {x}) : t = βŠ₯ := bot_unique $ Ξ» s hs, bUnion_of_singleton s β–Έ is_open_bUnion (Ξ» x _, h x) end lattice section galois_connection variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} /-- Given `f : Ξ± β†’ Ξ²` and a topology on `Ξ²`, the induced topology on `Ξ±` is the collection of sets that are preimages of some open set in `Ξ²`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (t : topological_space Ξ²) : topological_space Ξ± := { is_open := Ξ»s, βˆƒs', t.is_open s' ∧ f ⁻¹' s' = s, is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩, is_open_inter := by rintro s₁ sβ‚‚ ⟨s'₁, hs₁, rfl⟩ ⟨s'β‚‚, hsβ‚‚, rfl⟩; exact ⟨s'₁ ∩ s'β‚‚, t.is_open_inter _ _ hs₁ hsβ‚‚, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set Ξ±) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (Ξ»x h, (hf x h).right)], refine ⟨_, rfl⟩, exact (@is_open_Union Ξ² _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union Ξ² _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space Ξ²] {s : set Ξ±} {f : Ξ± β†’ Ξ²} : @is_open Ξ± (t.induced f) s ↔ (βˆƒt, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_closed_induced_iff [t : topological_space Ξ²] {s : set Ξ±} {f : Ξ± β†’ Ξ²} : @is_closed Ξ± (t.induced f) s ↔ (βˆƒt, is_closed t ∧ s = f ⁻¹' t) := ⟨assume ⟨t, ht, heq⟩, ⟨tᢜ, is_closed_compl_iff.2 ht, by simp only [preimage_compl, heq, compl_compl]⟩, assume ⟨t, ht, heq⟩, ⟨tᢜ, ht, by simp only [preimage_compl, heq.symm]⟩⟩ /-- Given `f : Ξ± β†’ Ξ²` and a topology on `Ξ±`, the coinduced topology on `Ξ²` is defined such that `s:set Ξ²` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β†’ Ξ²) (t : topological_space Ξ±) : topological_space Ξ² := { is_open := Ξ»s, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ sβ‚‚ h₁ hβ‚‚, by rw preimage_inter; exact t.is_open_inter _ _ h₁ hβ‚‚, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space Ξ±} {s : set Ξ²} {f : Ξ± β†’ Ξ²} : @is_open Ξ² (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.rfl variables {t t₁ tβ‚‚ : topological_space Ξ±} {t' : topological_space Ξ²} {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} lemma coinduced_le_iff_le_induced {f : Ξ± β†’ Ξ² } {tΞ± : topological_space Ξ±} {tΞ² : topological_space Ξ²} : tΞ±.coinduced f ≀ tΞ² ↔ tΞ± ≀ tΞ².induced f := iff.intro (assume h s ⟨t, ht, hst⟩, hst β–Έ h _ ht) (assume h s hs, show tΞ±.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) lemma gc_coinduced_induced (f : Ξ± β†’ Ξ²) : galois_connection (topological_space.coinduced f) (topological_space.induced f) := assume f g, coinduced_le_iff_le_induced lemma induced_mono (h : t₁ ≀ tβ‚‚) : t₁.induced g ≀ tβ‚‚.induced g := (gc_coinduced_induced g).monotone_u h lemma coinduced_mono (h : t₁ ≀ tβ‚‚) : t₁.coinduced f ≀ tβ‚‚.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] lemma induced_top : (⊀ : topological_space Ξ±).induced g = ⊀ := (gc_coinduced_induced g).u_top @[simp] lemma induced_inf : (t₁ βŠ“ tβ‚‚).induced g = t₁.induced g βŠ“ tβ‚‚.induced g := (gc_coinduced_induced g).u_inf @[simp] lemma induced_infi {ΞΉ : Sort w} {t : ΞΉ β†’ topological_space Ξ±} : (β¨…i, t i).induced g = (β¨…i, (t i).induced g) := (gc_coinduced_induced g).u_infi @[simp] lemma coinduced_bot : (βŠ₯ : topological_space Ξ±).coinduced f = βŠ₯ := (gc_coinduced_induced f).l_bot @[simp] lemma coinduced_sup : (t₁ βŠ” tβ‚‚).coinduced f = t₁.coinduced f βŠ” tβ‚‚.coinduced f := (gc_coinduced_induced f).l_sup @[simp] lemma coinduced_supr {ΞΉ : Sort w} {t : ΞΉ β†’ topological_space Ξ±} : (⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) := (gc_coinduced_induced f).l_supr lemma induced_id [t : topological_space Ξ±] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h β–Έ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tΞ³ : topological_space Ξ³] {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ³} : (tΞ³.induced g).induced f = tΞ³.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, hβ‚‚βŸ©, hβ‚βŸ©, h₁ β–Έ hβ‚‚ β–Έ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h β–Έ rfl⟩⟩ lemma coinduced_id [t : topological_space Ξ±] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tΞ± : topological_space Ξ±] {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ³} : (tΞ±.coinduced f).coinduced g = tΞ±.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {Ξ± : Type u} {Ξ² : Type v} instance inhabited_topological_space {Ξ± : Type u} : inhabited (topological_space Ξ±) := ⟨⊀⟩ @[priority 100] instance subsingleton.unique_topological_space [subsingleton Ξ±] : unique (topological_space Ξ±) := { default := βŠ₯, uniq := Ξ» t, eq_bot_of_singletons_open $ Ξ» x, subsingleton.set_cases (@is_open_empty _ t) (@is_open_univ _ t) ({x} : set Ξ±) } @[priority 100] instance subsingleton.discrete_topology [t : topological_space Ξ±] [subsingleton Ξ±] : discrete_topology Ξ± := ⟨unique.eq_default t⟩ instance : topological_space empty := βŠ₯ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space pempty := βŠ₯ instance : discrete_topology pempty := ⟨rfl⟩ instance : topological_space unit := βŠ₯ instance : discrete_topology unit := ⟨rfl⟩ instance : topological_space bool := βŠ₯ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space β„• := βŠ₯ instance : discrete_topology β„• := ⟨rfl⟩ instance : topological_space β„€ := βŠ₯ instance : discrete_topology β„€ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} lemma le_generate_from {t : topological_space Ξ±} { g : set (set Ξ±) } (h : βˆ€s∈g, is_open s) : t ≀ generate_from g := le_generate_from_iff_subset_is_open.2 h lemma induced_generate_from_eq {Ξ± Ξ²} {b : set (set Ξ²)} {f : Ξ± β†’ Ξ²} : (generate_from b).induced f = topological_space.generate_from (preimage f '' b) := le_antisymm (le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs, generate_open.basic _ $ mem_image_of_mem _ hs) /-- This construction is left adjoint to the operation sending a topology on `Ξ±` to its neighborhood filter at a fixed point `a : Ξ±`. -/ protected def topological_space.nhds_adjoint (a : Ξ±) (f : filter Ξ±) : topological_space Ξ± := { is_open := Ξ»s, a ∈ s β†’ s ∈ f, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : Ξ±) : galois_connection (topological_space.nhds_adjoint a) (Ξ»t, @nhds Ξ± t a) := assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, Ξ» H s has hs, H _ hs has⟩ } lemma nhds_mono {t₁ tβ‚‚ : topological_space Ξ±} {a : Ξ±} (h : t₁ ≀ tβ‚‚) : @nhds Ξ± t₁ a ≀ @nhds Ξ± tβ‚‚ a := (gc_nhds a).monotone_u h lemma nhds_infi {ΞΉ : Sort*} {t : ΞΉ β†’ topological_space Ξ±} {a : Ξ±} : @nhds Ξ± (infi t) a = (β¨…i, @nhds Ξ± (t i) a) := (gc_nhds a).u_infi lemma nhds_Inf {s : set (topological_space Ξ±)} {a : Ξ±} : @nhds Ξ± (Inf s) a = (β¨…t∈s, @nhds Ξ± t a) := (gc_nhds a).u_Inf lemma nhds_inf {t₁ tβ‚‚ : topological_space Ξ±} {a : Ξ±} : @nhds Ξ± (t₁ βŠ“ tβ‚‚) a = @nhds Ξ± t₁ a βŠ“ @nhds Ξ± tβ‚‚ a := (gc_nhds a).u_inf lemma nhds_top {a : Ξ±} : @nhds Ξ± ⊀ a = ⊀ := (gc_nhds a).u_top local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {Ξ³ : Type*} {f : Ξ± β†’ Ξ²} {ΞΉ : Sort*} lemma continuous_iff_coinduced_le {t₁ : tspace Ξ±} {tβ‚‚ : tspace Ξ²} : cont t₁ tβ‚‚ f ↔ coinduced f t₁ ≀ tβ‚‚ := iff.rfl lemma continuous_iff_le_induced {t₁ : tspace Ξ±} {tβ‚‚ : tspace Ξ²} : cont t₁ tβ‚‚ f ↔ t₁ ≀ induced f tβ‚‚ := iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) theorem continuous_generated_from {t : tspace Ξ±} {b : set (set Ξ²)} (h : βˆ€s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_coinduced_le.2 $ le_generate_from h lemma continuous_induced_dom {t : tspace Ξ²} : cont (induced f t) t f := assume s h, ⟨_, h, rfl⟩ lemma continuous_induced_rng {g : Ξ³ β†’ Ξ±} {tβ‚‚ : tspace Ξ²} {t₁ : tspace Ξ³} (h : cont t₁ tβ‚‚ (f ∘ g)) : cont t₁ (induced f tβ‚‚) g := assume s ⟨t, ht, s_eq⟩, s_eq β–Έ h t ht lemma continuous_induced_rng' [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] {g : Ξ³ β†’ Ξ±} (f : Ξ± β†’ Ξ²) (H : β€Ήtopological_space Ξ±β€Ί = β€Ήtopological_space Ξ²β€Ί.induced f) (h : continuous (f ∘ g)) : continuous g := H.symm β–Έ continuous_induced_rng h lemma continuous_coinduced_rng {t : tspace Ξ±} : cont t (coinduced f t) f := assume s h, h lemma continuous_coinduced_dom {g : Ξ² β†’ Ξ³} {t₁ : tspace Ξ±} {tβ‚‚ : tspace Ξ³} (h : cont t₁ tβ‚‚ (g ∘ f)) : cont (coinduced f t₁) tβ‚‚ g := assume s hs, h s hs lemma continuous_le_dom {t₁ tβ‚‚ : tspace Ξ±} {t₃ : tspace Ξ²} (h₁ : tβ‚‚ ≀ t₁) (hβ‚‚ : cont t₁ t₃ f) : cont tβ‚‚ t₃ f := assume s h, h₁ _ (hβ‚‚ s h) lemma continuous_le_rng {t₁ : tspace Ξ±} {tβ‚‚ t₃ : tspace Ξ²} (h₁ : tβ‚‚ ≀ t₃) (hβ‚‚ : cont t₁ tβ‚‚ f) : cont t₁ t₃ f := assume s h, hβ‚‚ s (h₁ s h) lemma continuous_sup_dom {t₁ tβ‚‚ : tspace Ξ±} {t₃ : tspace Ξ²} (h₁ : cont t₁ t₃ f) (hβ‚‚ : cont tβ‚‚ t₃ f) : cont (t₁ βŠ” tβ‚‚) t₃ f := assume s h, ⟨h₁ s h, hβ‚‚ s h⟩ lemma continuous_sup_rng_left {t₁ : tspace Ξ±} {t₃ tβ‚‚ : tspace Ξ²} : cont t₁ tβ‚‚ f β†’ cont t₁ (tβ‚‚ βŠ” t₃) f := continuous_le_rng le_sup_left lemma continuous_sup_rng_right {t₁ : tspace Ξ±} {t₃ tβ‚‚ : tspace Ξ²} : cont t₁ t₃ f β†’ cont t₁ (tβ‚‚ βŠ” t₃) f := continuous_le_rng le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace Ξ±)} {tβ‚‚ : tspace Ξ²} (h : βˆ€t∈t₁, cont t tβ‚‚ f) : cont (Sup t₁) tβ‚‚ f := continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht lemma continuous_Sup_rng {t₁ : tspace Ξ±} {tβ‚‚ : set (tspace Ξ²)} {t : tspace Ξ²} (h₁ : t ∈ tβ‚‚) (hf : cont t₁ t f) : cont t₁ (Sup tβ‚‚) f := continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf lemma continuous_supr_dom {t₁ : ΞΉ β†’ tspace Ξ±} {tβ‚‚ : tspace Ξ²} (h : βˆ€i, cont (t₁ i) tβ‚‚ f) : cont (supr t₁) tβ‚‚ f := continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq β–Έ h i lemma continuous_supr_rng {t₁ : tspace Ξ±} {tβ‚‚ : ΞΉ β†’ tspace Ξ²} {i : ΞΉ} (h : cont t₁ (tβ‚‚ i) f) : cont t₁ (supr tβ‚‚) f := continuous_Sup_rng ⟨i, rfl⟩ h lemma continuous_inf_rng {t₁ : tspace Ξ±} {tβ‚‚ t₃ : tspace Ξ²} (h₁ : cont t₁ tβ‚‚ f) (hβ‚‚ : cont t₁ t₃ f) : cont t₁ (tβ‚‚ βŠ“ t₃) f := continuous_iff_coinduced_le.2 $ le_inf (continuous_iff_coinduced_le.1 h₁) (continuous_iff_coinduced_le.1 hβ‚‚) lemma continuous_inf_dom_left {t₁ tβ‚‚ : tspace Ξ±} {t₃ : tspace Ξ²} : cont t₁ t₃ f β†’ cont (t₁ βŠ“ tβ‚‚) t₃ f := continuous_le_dom inf_le_left lemma continuous_inf_dom_right {t₁ tβ‚‚ : tspace Ξ±} {t₃ : tspace Ξ²} : cont tβ‚‚ t₃ f β†’ cont (t₁ βŠ“ tβ‚‚) t₃ f := continuous_le_dom inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace Ξ±)} {tβ‚‚ : tspace Ξ²} {t : tspace Ξ±} (h₁ : t ∈ t₁) : cont t tβ‚‚ f β†’ cont (Inf t₁) tβ‚‚ f := continuous_le_dom $ Inf_le h₁ lemma continuous_Inf_rng {t₁ : tspace Ξ±} {tβ‚‚ : set (tspace Ξ²)} (h : βˆ€t∈tβ‚‚, cont t₁ t f) : cont t₁ (Inf tβ‚‚) f := continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb lemma continuous_infi_dom {t₁ : ΞΉ β†’ tspace Ξ±} {tβ‚‚ : tspace Ξ²} {i : ΞΉ} : cont (t₁ i) tβ‚‚ f β†’ cont (infi t₁) tβ‚‚ f := continuous_le_dom $ infi_le _ _ lemma continuous_infi_rng {t₁ : tspace Ξ±} {tβ‚‚ : ΞΉ β†’ tspace Ξ²} (h : βˆ€i, cont t₁ (tβ‚‚ i) f) : cont t₁ (infi tβ‚‚) f := continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i @[continuity] lemma continuous_bot {t : tspace Ξ²} : cont βŠ₯ t f := continuous_iff_le_induced.2 $ bot_le @[continuity] lemma continuous_top {t : tspace Ξ±} : cont t ⊀ f := continuous_iff_coinduced_le.2 $ le_top /- 𝓝 in the induced topology -/ theorem mem_nhds_induced [T : topological_space Ξ±] (f : Ξ² β†’ Ξ±) (a : Ξ²) (s : set Ξ²) : s ∈ @nhds Ξ² (topological_space.induced f T) a ↔ βˆƒ u ∈ 𝓝 (f a), f ⁻¹' u βŠ† s := begin simp only [mem_nhds_sets_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq], split, { rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩, exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ }, rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩, exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ end theorem nhds_induced [T : topological_space Ξ±] (f : Ξ² β†’ Ξ±) (a : Ξ²) : @nhds Ξ² (topological_space.induced f T) a = comap f (𝓝 (f a)) := filter_eq $ by ext s; rw mem_nhds_induced; rw mem_comap_sets lemma induced_iff_nhds_eq [tΞ± : topological_space Ξ±] [tΞ² : topological_space Ξ²] (f : Ξ² β†’ Ξ±) : tΞ² = tΞ±.induced f ↔ βˆ€ b, 𝓝 b = comap f (𝓝 $ f b) := ⟨λ h a, h.symm β–Έ nhds_induced f a, Ξ» h, eq_of_nhds_eq_nhds $ Ξ» x, by rw [h, nhds_induced]⟩ theorem map_nhds_induced_of_surjective [T : topological_space Ξ±] {f : Ξ² β†’ Ξ±} (hf : function.surjective f) (a : Ξ²) : map f (@nhds Ξ² (topological_space.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end constructions section induced open topological_space variables {Ξ± : Type*} {Ξ² : Type*} variables [t : topological_space Ξ²] {f : Ξ± β†’ Ξ²} theorem is_open_induced_eq {s : set Ξ±} : @is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} := iff.rfl theorem is_open_induced {s : set Ξ²} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma map_nhds_induced_eq {a : Ξ±} (h : range f ∈ 𝓝 (f a)) : map f (@nhds Ξ± (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap h] lemma closure_induced [t : topological_space Ξ²] {f : Ξ± β†’ Ξ²} {a : Ξ±} {s : set Ξ±} (hf : βˆ€x y, f x = f y β†’ x = y) : a ∈ @closure Ξ± (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := have ne_bot (comap f (𝓝 (f a) βŠ“ π“Ÿ (f '' s))) ↔ ne_bot (𝓝 (f a) βŠ“ π“Ÿ (f '' s)), from ⟨assume h₁ hβ‚‚, h₁ $ hβ‚‚.symm β–Έ comap_bot, assume h, forall_sets_nonempty_iff_ne_bot.mp $ assume s₁ ⟨sβ‚‚, hsβ‚‚, (hs : f ⁻¹' sβ‚‚ βŠ† s₁)⟩, have f '' s ∈ 𝓝 (f a) βŠ“ π“Ÿ (f '' s), from mem_inf_sets_of_right $ by simp [subset.refl], have sβ‚‚ ∩ f '' s ∈ 𝓝 (f a) βŠ“ π“Ÿ (f '' s), from inter_mem_sets hsβ‚‚ this, let ⟨b, hb₁, ⟨a, ha, haβ‚‚βŸ©βŸ© := h.nonempty_of_mem this in ⟨_, hs $ by rwa [←haβ‚‚] at hbβ‚βŸ©βŸ©, calc a ∈ @closure Ξ± (topological_space.induced f t) s ↔ (@nhds Ξ± (topological_space.induced f t) a) βŠ“ π“Ÿ s β‰  βŠ₯ : by rw [closure_eq_cluster_pts]; refl ... ↔ comap f (𝓝 (f a)) βŠ“ π“Ÿ (f ⁻¹' (f '' s)) β‰  βŠ₯ : by rw [nhds_induced, preimage_image_eq _ hf] ... ↔ comap f (𝓝 (f a) βŠ“ π“Ÿ (f '' s)) β‰  βŠ₯ : by rw [comap_inf, ←comap_principal] ... ↔ _ : by rwa [closure_eq_cluster_pts] end induced section sierpinski variables {Ξ± : Type*} [topological_space Ξ±] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : Ξ± β†’ Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from h _ is_open_singleton_true, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ end sierpinski section infi variables {Ξ± : Type u} {ΞΉ : Type v} {t : ΞΉ β†’ topological_space Ξ±} lemma is_open_supr_iff {s : set Ξ±} : @is_open _ (⨆ i, t i) s ↔ βˆ€ i, @is_open _ (t i) s := begin -- s defines a map from Ξ± to Prop, which is continuous iff s is open. suffices : @continuous _ _ (⨆ i, t i) _ s ↔ βˆ€ i, @continuous _ _ (t i) _ s, { simpa only [continuous_Prop] using this }, simp only [continuous_iff_le_induced, supr_le_iff] end lemma is_closed_infi_iff {s : set Ξ±} : @is_closed _ (⨆ i, t i) s ↔ βˆ€ i, @is_closed _ (t i) s := is_open_supr_iff end infi
e48dd4fddcf145a4a0853eaefeab3fb208181961
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/tacticTests.lean
5f1659b59de363a3f33e1cf150ef80994ccb256d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,712
lean
inductive Le (m : Nat) : Nat β†’ Prop | base : Le m m | succ : (n : Nat) β†’ Le m n β†’ Le m n.succ theorem ex1 (m : Nat) : Le m 0 β†’ m = 0 := by intro h cases h rfl theorem ex2 (m n : Nat) : Le m n β†’ Le m.succ n.succ := by intro h induction h with | base => apply Le.base | succ n m ih => apply Le.succ apply ih theorem ex3 (m : Nat) : Le 0 m := by induction m with | zero => apply Le.base | succ m ih => apply Le.succ apply ih theorem ex4 (m : Nat) : Β¬ Le m.succ 0 := by intro h cases h theorem ex5 {m n : Nat} : Le m n.succ β†’ m = n.succ ∨ Le m n := by intro h cases h with | base => apply Or.inl; rfl | succ => apply Or.inr; assumption theorem ex6 {m n : Nat} : Le m.succ n.succ β†’ Le m n := by revert m induction n with | zero => intros m h; cases h with | base => apply Le.base | succ n h => exact absurd h (ex4 _) | succ n ih => intros m h have aux := ih (m := m) cases ex5 h with | inl h => injection h with h subst h apply Le.base | inr h => apply Le.succ exact ih h theorem ex7 {m n o : Nat} : Le m n β†’ Le n o β†’ Le m o := by intro h induction h with | base => intros; assumption | succ n s ih => intro hβ‚‚ apply ih apply ex6 apply Le.succ assumption theorem ex8 {m n : Nat} : Le m.succ n β†’ Le m n := by intro h apply ex6 apply Le.succ assumption theorem ex9 {m n : Nat} : Le m n β†’ m = n ∨ Le m.succ n := by intro h cases h with | base => apply Or.inl; rfl | succ n s => apply Or.inr apply ex2 assumption /- theorem ex10 (n : Nat) : Β¬ Le n.succ n := by intro h cases h -- TODO: improve cases tactic done -/ theorem ex10 (n : Nat) : n.succ β‰  n := by induction n with | zero => intro h; injection h; done | succ n ih => intro h; injection h with h; apply ih h theorem ex11 (n : Nat) : Β¬ Le n.succ n := by induction n with | zero => intro h; cases h; done | succ n ih => intro h have aux := ex6 h exact absurd aux ih done theorem ex12 (m n : Nat) : Le m n β†’ Le n m β†’ m = n := by revert m induction n with | zero => intro m h1 h2; apply ex1; assumption; done | succ n ih => intro m h1 h2 have ih := ih m cases ex5 h1 with | inl h => assumption | inr h => have ih := ih h have h3 := ex8 h2 have ih := ih h3 subst ih apply absurd h2 (ex11 _) done inductive Foo : Nat β†’ Prop where | foo : Foo 0 | bar : Foo 0 | baz : Foo 1 example (f : Foo 0) : True := by cases f with | _ => trivial example (f : Foo n) (h : n = 0) : True := by induction f with simp at h | _ => trivial
3fd4c710a8f04c74540282fcc51f99cb3acfc92b
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world2/level1.lean
f3e110973381f7a09a560ed85cc4c5eeaee92c11
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
7,918
lean
import mynat.definition -- Imports the natural numbers. import mynat.add -- imports addition. namespace mynat -- hide /- Axiom : add_zero (a : mynat) : a + 0 = a -/ /- Axiom : add_succ (a b : mynat) : a + succ(b) = succ(a + b) -/ /- Tactic : induction ## Summary if `n : mynat` is in our assumptions, then `induction n with d hd` attempts to prove the goal by induction on `n`, with the inductive assumption in the `succ` case being `hd`. ## Details If you have a natural number `n : mynat` in your context (above the `⊒`) then `induction n with d hd` turns your goal into two goals, a base case with `n = 0` and an inductive step where `hd` is a proof of the `n = d` case and your goal is the `n = succ(d)` case. ### Example: If this is our local context: ``` n : mynat ⊒ 2 * n = n + n ``` then `induction n with d hd` will give us two goals: ``` ⊒ 2 * 0 = 0 + 0 ``` and ``` d : mynat, hd : 2 * d = d + d ⊒ 2 * succ d = succ d + succ d ``` -/ /- # Addition World. Welcome to Addition World. If you've done all four levels in tutorial world and know about `rw` and `refl`, then you're in the right place. Here's a reminder of the things you're now equipped with which we'll need in this world. ## Data: * a type called `mynat` * a term `0 : mynat`, interpreted as the number zero. * a function `succ : mynat β†’ mynat`, with `succ n` interpreted as "the number after `n`". * Usual numerical notation 0,1,2 etc (although 2 onwards will be of no use to us until much later ;-) ). * Addition (with notation `a + b`). ## Theorems: * `add_zero (a : mynat) : a + 0 = a`. Use with `rw add_zero`. * `add_succ (a b : mynat) : a + succ(b) = succ(a + b)`. Use with `rw add_succ`. * The principle of mathematical induction. Use with `induction` (see below) ## Tactics: * `refl` : proves goals of the form `X = X` * `rw h` : if h is a proof of `A = B`, changes all A's in the goal to B's. * `induction n with d hd` : we're going to learn this right now. # Important thing: This is a *really* good time to check you understand about the box on the left with the drop down menus. All the theorems and all the tactics above are documented there. You can find all you need to know about what theorems you have collected in Theorem statements -> Addition world. Have a click around and check that you can find statements of the theorems above, and explanations of the tactics above. As we go through the game, these lists will grow. The box on the left will prove invaluable as the number of theorems we prove gets bigger. On the other hand, we only need to learn one more tactic to really start going places, so let's learn about that tactic right now. ## Level 1: the `induction` tactic. OK so let's see induction in action. We're going to prove `zero_add (n : mynat) : 0 + n = n`. That is: for all natural numbers $n$, $0+n=n$. Wait $-$ what is going on here? Didn't we already prove that adding zero to $n$ gave us $n$? No we didn't! We proved $n + 0 = n$, and that proof was called `add_zero`. We're now trying to establish `zero_add`, the proof that $0 + n = n$. But aren't these two theorems the same? No they're not! It is *true* that `x + y = y + x`, but we haven't *proved* it yet, and in fact we will need both `add_zero` and `zero_add` in order to prove this. In fact `x + y = y + x` is the boss level for addition world, and `induction` is the only other tactic you'll need to beat it. Now `add_zero` is one of Peano's axioms, so we don't need to prove it, we already have it (indeed, if you've opened the Addition World theorem statements on the left, you can even see it). To prove `0 + n = n` we need to use induction on $n$. While we're here, note that `zero_add` is about zero add something, and `add_zero` is about something add zero. The names of the proofs tell you what the theorems are. Anyway, let's prove `0 + n = n`. Delete `sorry` and replace it with `induction n with d hd,` and **don't forget the comma**. Hit enter, wait for Lean to finish thinking, and let's see what we have. When Lean has finished thinking, we see that we now have *two goals*! The induction tactic has generated for us a base case with `n = 0` (the goal at the top) and an inductive step (the goal underneath). The golden rule: **Tactics operate on the first goal** -- the goal at the top. So let's just worry about that top goal now, the base case `⊒ 0 + 0 = 0`. Remember that `add_zero` (the proof we have already) is the proof of `x + 0 = x` (for any $x$) so we can try `rw add_zero,` . What do you think the goal will change to? Remember to just keep focussing on the top goal, ignore the other one for now, it's not changing and we're not working on it. You should be able to solve the top goal yourself now with `refl`. When you solved this base case goal, we are now be back down to one goal -- the inductive step. Take a look at the text below the lemma to see an explanation of this goal. -/ /- Lemma For all natural numbers $n$, we have $$0 + n = n.$$ -/ lemma zero_add (n : mynat) : 0 + n = n := begin [nat_num_game] induction n with d hd, rw add_zero, refl, rw add_succ, rw hd, refl end /- We're in the successor case, and your top right box should look something like this: ``` case mynat.succ d : mynat, hd : 0 + d = d ⊒ 0 + succ d = succ d ``` *Important:* make sure that you only have one goal at this point. You should have proved `0 + 0 = 0` by now. Tactics only operate on the top goal. The first line just reminds us we're doing the inductive step. We have a fixed natural number `d`, and the inductive hypothesis `hd : 0 + d = d` saying that we have a proof of `0 + d = d`. Our goal is to prove `0 + succ d = succ d`. In words, we're showing that if the lemma is true for `d`, then it's also true for the number after `d`. That's the inductive step. Once we've proved this inductive step, we will have proved `zero_add` by the principle of mathematical induction. To prove our goal, we need to use `add_succ`. We know that `add_succ 0 d` is the result that `0 + succ d = succ (0 + d)`, so the first thing we need to do is to replace the left hand side `0 + succ d` of our goal with the right hand side. We do this with the `rw` command. You can write `rw add_succ,` (or even `rw add_succ 0 d,` if you want to give Lean all the inputs instead of making it figure them out itself). Don't forget the comma though. Hit enter. The goal should change to `⊒ succ (0 + d) = succ d` Now remember our inductive hypothesis `hd : 0 + d = d`. We need to rewrite this too! Type `rw hd,` (don't forget the comma). The goal will now change to `⊒ succ d = succ d` This goal can be solved with the `refl` tactic. After you apply it, Lean will inform you that there are no goals left. You are done! ## Now venture off on your own. Those three tactics -- * `induction n with d hd,` * `rw h,` * `refl,` will get you quite a long way through this game. Using only these tactics you can beat Addition World level 4 (the boss level of Addition World), all of Multiplication World including the boss level `a * b = b * a`, and even all of Power World including the fiendish final boss. This route will give you a good grounding in these three basic tactics; after that, if you are still interested, there are other worlds to master, where you can learn more tactics. But we're getting ahead of ourselves, you still have to beat the rest of Addition World. We're going to stop explaining stuff carefully now. If you get stuck or want to know more about Lean (e.g. how to do much harder maths in Lean), ask in `#new members` at <a href="https://leanprover.zulipchat.com" target="blank">the Lean chat</a> (login required, real name preferred). Kevin or Mohammad or one of the other people there might be able to help. Good luck! Click on "next level" to solve some levels on your own. -/ end mynat -- hide
42ff1a2fa114299971a12b65e584127178cfe2d8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/toDeclEtaBug.lean
2f03606e26f255ba6bd42dc102286bd3791141eb
[ "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
344
lean
import Lean open Lean Compiler LCNF Testing @[inline] def f (c b : Bool) (x : Nat) : Nat := if c && b then x + 1 else x + 2 -- TODO: uncomment after the new compiler is executed by default -- @[cpass] def cseSizeTest : PassInstaller := Testing.assertNoFun |>.install `specialize `noFun def g (c : Nat) : Nat := f true false c
305207026f98467ed6c19fad3b136a1c762b399e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/matchGenBug.lean
9cb3522499d3250b2d14aa0b38eef096f0313b80
[ "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
617
lean
theorem foo (x : Nat) (h : x > 0) : x β‰  0 := match x with | 0 => sorry | h+1 => sorry inductive Mem : Ξ± β†’ List Ξ± β†’ Prop where | head (a : Ξ±) (as : List Ξ±) : Mem a (a::as) | tail (a b : Ξ±) (bs : List Ξ±) : Mem a bs β†’ Mem a (b::bs) infix:50 (priority := high) "∈" => Mem theorem mem_split {a : Ξ±} {as : List Ξ±} (h : a ∈ as) : βˆƒ s t, as = s ++ a :: t := by induction as with | nil => cases h | cons b bs ih => cases h with | head bs => exact ⟨[], ⟨bs, rfl⟩⟩ | tail b bs h => match bs, ih h with | _, ⟨s, t, rfl⟩ => exists b::s, t
eac84cb9ba4cf0744eb53a54b157914c859c2f2e
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/notation.lean
17d6e0a87db23c5d2cec9b11550bdcb506fb4d47
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
393
lean
-- open num constant b : num #check b + b + b #check true ∧ false ∧ true #check (true ∧ false) ∧ true #check (2:num) + (2 + 2) #check (2 + 2) + (2:num) #check (1:num) = (2 + 3)*2 #check (2:num) + 3 * 2 = 3 * 2 + 2 #check (true ∨ false) = (true ∨ false) ∧ true #check true ∧ (false ∨ true) constant A : Type constant a : A notation 1 := a #check a open nat #check β„• β†’ β„•
a487c6560e59a5b737ae688d63e55f0a63eb24fa
26b8b0964ca8e1c2e203585ba5940f83fe05e48a
/src/tidy/automatic_induction.lean
38ee3ec4efc2f4e486a686e9b6bc517d814d7fcd
[]
no_license
jcommelin/lean-tidy
ef3cd32a3804221d93f0dff9e180bb2c52f4b143
9cecf497e90db64b5ea140ad6ae1603976dcd402
refs/heads/master
1,585,129,919,276
1,533,512,680,000
1,533,512,680,000
143,677,361
0
0
null
1,616,803,481,000
1,533,530,576,000
Lean
UTF-8
Lean
false
false
1,291
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .at_least_one open tactic meta def automatic_induction_at (h : expr) : tactic string := do t' ← infer_type h, t' ← whnf t', (do n ← num_goals, cases h, n' ← num_goals, guard (n' < n), pp ← pp h, return ("cases " ++ pp.to_string) ) <|> (do let use_cases := match t' with | `(unit) := tt | `(punit) := tt | `(ulift _) := tt | `(plift _) := tt | `(prod _ _) := tt | `(and _ _) := tt | `(sigma _) := tt | `(subtype _) := tt | `(Exists _) := tt | `(fin 0) := tt | _ := ff end, if use_cases then do cases h, pp ← pp h, return ("cases " ++ pp.to_string) else match t' with | `(eq _ _) := do induction h, pp ← pp h, return ("induction " ++ pp.to_string) | `(quot _) := do induction h, pp ← pp h, return ("induction " ++ pp.to_string) | _ := failed end ) /- Applies `cases` or `induction` fairly aggressively on hypotheses. -/ meta def automatic_induction : tactic string := do l ← local_context, results ← at_least_one (l.reverse.map(Ξ» h, automatic_induction_at h)), return (string.intercalate ", " results)
4da6b6c57e0631080fb57f88bce0516643c0fd3f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/finset/lattice.lean
0fb837ec6292b147bf2e706eac8364c211382a8c
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
54,351
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.finset.fold import data.finset.option import data.finset.prod import data.multiset.lattice import order.complete_lattice import order.lexicographic /-! # Lattice operations on finsets -/ variables {Ξ± Ξ² Ξ³ ΞΉ : Type*} namespace finset open multiset order_dual /-! ### sup -/ section sup -- TODO: define with just `[has_bot Ξ±]` where some lemmas hold without requiring `[order_bot Ξ±]` variables [semilattice_sup Ξ±] [order_bot Ξ±] /-- Supremum of a finite set: `sup {a, b, c} f = f a βŠ” f b βŠ” f c` -/ def sup (s : finset Ξ²) (f : Ξ² β†’ Ξ±) : Ξ± := s.fold (βŠ”) βŠ₯ f variables {s s₁ sβ‚‚ : finset Ξ²} {f g : Ξ² β†’ Ξ±} lemma sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (βˆ… : finset Ξ²).sup f = βŠ₯ := fold_empty @[simp] lemma sup_cons {b : Ξ²} (h : b βˆ‰ s) : (cons b s h).sup f = f b βŠ” s.sup f := fold_cons h @[simp] lemma sup_insert [decidable_eq Ξ²] {b : Ξ²} : (insert b s : finset Ξ²).sup f = f b βŠ” s.sup f := fold_insert_idem lemma sup_image [decidable_eq Ξ²] (s : finset Ξ³) (f : Ξ³ β†’ Ξ²) (g : Ξ² β†’ Ξ±) : (s.image f).sup g = s.sup (g ∘ f) := fold_image_idem @[simp] lemma sup_map (s : finset Ξ³) (f : Ξ³ β†ͺ Ξ²) (g : Ξ² β†’ Ξ±) : (s.map f).sup g = s.sup (g ∘ f) := fold_map @[simp] lemma sup_singleton {b : Ξ²} : ({b} : finset Ξ²).sup f = f b := sup_singleton lemma sup_union [decidable_eq Ξ²] : (s₁ βˆͺ sβ‚‚).sup f = s₁.sup f βŠ” sβ‚‚.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ Ξ» a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] lemma sup_sup : s.sup (f βŠ” g) = s.sup f βŠ” s.sup g := begin refine finset.cons_induction_on s _ (Ξ» b t _ h, _), { rw [sup_empty, sup_empty, sup_empty, bot_sup_eq] }, { rw [sup_cons, sup_cons, sup_cons, h], exact sup_sup_sup_comm _ _ _ _ } end theorem sup_congr {f g : Ξ² β†’ Ξ±} (hs : s₁ = sβ‚‚) (hfg : βˆ€a∈sβ‚‚, f a = g a) : s₁.sup f = sβ‚‚.sup g := by subst hs; exact finset.fold_congr hfg @[simp] lemma sup_le_iff {a : Ξ±} : s.sup f ≀ a ↔ (βˆ€b ∈ s, f b ≀ a) := begin apply iff.trans multiset.sup_le, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, Ξ» k a' b hb h, h β–Έ k _ hb⟩, end @[simp] lemma sup_bUnion [decidable_eq Ξ²] (s : finset Ξ³) (t : Ξ³ β†’ finset Ξ²) : (s.bUnion t).sup f = s.sup (Ξ» x, (t x).sup f) := eq_of_forall_ge_iff $ Ξ» c, by simp [@forall_swap _ Ξ²] lemma sup_const {s : finset Ξ²} (h : s.nonempty) (c : Ξ±) : s.sup (Ξ» _, c) = c := eq_of_forall_ge_iff $ Ξ» b, sup_le_iff.trans h.forall_const @[simp] lemma sup_bot (s : finset Ξ²) : s.sup (Ξ» _, βŠ₯) = (βŠ₯ : Ξ±) := begin obtain rfl | hs := s.eq_empty_or_nonempty, { exact sup_empty }, { exact sup_const hs _ } end lemma sup_ite (p : Ξ² β†’ Prop) [decidable_pred p] : s.sup (Ξ» i, ite (p i) (f i) (g i)) = (s.filter p).sup f βŠ” (s.filter (Ξ» i, Β¬ p i)).sup g := fold_ite _ lemma sup_le {a : Ξ±} : (βˆ€b ∈ s, f b ≀ a) β†’ s.sup f ≀ a := sup_le_iff.2 lemma le_sup {b : Ξ²} (hb : b ∈ s) : f b ≀ s.sup f := sup_le_iff.1 le_rfl _ hb lemma sup_mono_fun {g : Ξ² β†’ Ξ±} (h : βˆ€b∈s, f b ≀ g b) : s.sup f ≀ s.sup g := sup_le (Ξ» b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ βŠ† sβ‚‚) : s₁.sup f ≀ sβ‚‚.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total Ξ± (≀)] {a : Ξ±} (ha : βŠ₯ < a) : s.sup f < a ↔ (βˆ€ b ∈ s, f b < a) := ⟨(Ξ» hs b hb, lt_of_le_of_lt (le_sup hb) hs), finset.cons_induction_on s (Ξ» _, ha) (Ξ» c t hc, by simpa only [sup_cons, sup_lt_iff, mem_cons, forall_eq_or_imp] using and.imp_right)⟩ @[simp] lemma le_sup_iff [is_total Ξ± (≀)] {a : Ξ±} (ha : βŠ₯ < a) : a ≀ s.sup f ↔ βˆƒ b ∈ s, a ≀ f b := ⟨finset.cons_induction_on s (Ξ» h, absurd h (not_le_of_lt ha)) (Ξ» c t hc ih, by simpa using @or.rec _ _ (βˆƒ b, (b = c ∨ b ∈ t) ∧ a ≀ f b) (Ξ» h, ⟨c, or.inl rfl, h⟩) (Ξ» h, let ⟨b, hb, hle⟩ := ih h in ⟨b, or.inr hb, hle⟩)), (Ξ» ⟨b, hb, hle⟩, trans hle (le_sup hb))⟩ @[simp] lemma lt_sup_iff [is_total Ξ± (≀)] {a : Ξ±} : a < s.sup f ↔ βˆƒ b ∈ s, a < f b := ⟨finset.cons_induction_on s (Ξ» h, absurd h not_lt_bot) (Ξ» c t hc ih, by simpa using @or.rec _ _ (βˆƒ b, (b = c ∨ b ∈ t) ∧ a < f b) (Ξ» h, ⟨c, or.inl rfl, h⟩) (Ξ» h, let ⟨b, hb, hlt⟩ := ih h in ⟨b, or.inr hb, hlt⟩)), (Ξ» ⟨b, hb, hlt⟩, lt_of_lt_of_le hlt (le_sup hb))⟩ lemma sup_comm (s : finset Ξ²) (t : finset Ξ³) (f : Ξ² β†’ Ξ³ β†’ Ξ±) : s.sup (Ξ» b, t.sup (f b)) = t.sup (Ξ» c, s.sup (Ξ» b, f b c)) := begin refine eq_of_forall_ge_iff (Ξ» a, _), simp_rw sup_le_iff, exact ⟨λ h c hc b hb, h b hb c hc, Ξ» h b hb c hc, h c hc b hb⟩, end @[simp] lemma sup_attach (s : finset Ξ²) (f : Ξ² β†’ Ξ±) : s.attach.sup (Ξ» x, f x) = s.sup f := (s.attach.sup_map (function.embedding.subtype _) f).symm.trans $ congr_arg _ attach_map_val /-- See also `finset.product_bUnion`. -/ lemma sup_product_left (s : finset Ξ²) (t : finset Ξ³) (f : Ξ² Γ— Ξ³ β†’ Ξ±) : (s.product t).sup f = s.sup (Ξ» i, t.sup $ Ξ» i', f ⟨i, i'⟩) := begin refine le_antisymm _ (sup_le (Ξ» i hi, sup_le $ Ξ» i' hi', le_sup $ mem_product.2 ⟨hi, hi'⟩)), refine sup_le _, rintro ⟨i, i'⟩ hi, rw mem_product at hi, refine le_trans _ (le_sup hi.1), convert le_sup hi.2, end lemma sup_product_right (s : finset Ξ²) (t : finset Ξ³) (f : Ξ² Γ— Ξ³ β†’ Ξ±) : (s.product t).sup f = t.sup (Ξ» i', s.sup $ Ξ» i, f ⟨i, i'⟩) := by rw [sup_product_left, sup_comm] @[simp] lemma sup_erase_bot [decidable_eq Ξ±] (s : finset Ξ±) : (s.erase βŠ₯).sup id = s.sup id := begin refine (sup_mono (s.erase_subset _)).antisymm (finset.sup_le_iff.2 $ Ξ» a ha, _), obtain rfl | ha' := eq_or_ne a βŠ₯, { exact bot_le }, { exact le_sup (mem_erase.2 ⟨ha', ha⟩) } end lemma sup_sdiff_right {Ξ± Ξ² : Type*} [generalized_boolean_algebra Ξ±] (s : finset Ξ²) (f : Ξ² β†’ Ξ±) (a : Ξ±) : s.sup (Ξ» b, f b \ a) = s.sup f \ a := begin refine finset.cons_induction_on s _ (Ξ» b t _ h, _), { rw [sup_empty, sup_empty, bot_sdiff] }, { rw [sup_cons, sup_cons, h, sup_sdiff] } end lemma comp_sup_eq_sup_comp [semilattice_sup Ξ³] [order_bot Ξ³] {s : finset Ξ²} {f : Ξ² β†’ Ξ±} (g : Ξ± β†’ Ξ³) (g_sup : βˆ€ x y, g (x βŠ” y) = g x βŠ” g y) (bot : g βŠ₯ = βŠ₯) : g (s.sup f) = s.sup (g ∘ f) := finset.cons_induction_on s bot (Ξ» c t hc ih, by rw [sup_cons, sup_cons, g_sup, ih]) lemma comp_sup_eq_sup_comp_of_is_total [is_total Ξ± (≀)] {Ξ³ : Type} [semilattice_sup Ξ³] [order_bot Ξ³] (g : Ξ± β†’ Ξ³) (mono_g : monotone g) (bot : g βŠ₯ = βŠ₯) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot /-- Computing `sup` in a subtype (closed under `sup`) is the same as computing it in `Ξ±`. -/ lemma sup_coe {P : Ξ± β†’ Prop} {Pbot : P βŠ₯} {Psup : βˆ€{{x y}}, P x β†’ P y β†’ P (x βŠ” y)} (t : finset Ξ²) (f : Ξ² β†’ {x : Ξ± // P x}) : (@sup _ _ (subtype.semilattice_sup Psup) (subtype.order_bot Pbot) t f : Ξ±) = t.sup (Ξ» x, f x) := by { rw [comp_sup_eq_sup_comp coe]; intros; refl } @[simp] lemma sup_to_finset {Ξ± Ξ²} [decidable_eq Ξ²] (s : finset Ξ±) (f : Ξ± β†’ multiset Ξ²) : (s.sup f).to_finset = s.sup (Ξ» x, (f x).to_finset) := comp_sup_eq_sup_comp multiset.to_finset to_finset_union rfl theorem subset_range_sup_succ (s : finset β„•) : s βŠ† range (s.sup id).succ := Ξ» n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset β„•) : βˆƒn : β„•, s βŠ† range n := ⟨_, s.subset_range_sup_succ⟩ lemma sup_induction {p : Ξ± β†’ Prop} (hb : p βŠ₯) (hp : βˆ€ a₁, p a₁ β†’ βˆ€ aβ‚‚, p aβ‚‚ β†’ p (a₁ βŠ” aβ‚‚)) (hs : βˆ€ b ∈ s, p (f b)) : p (s.sup f) := begin induction s using finset.cons_induction with c s hc ih, { exact hb, }, { rw sup_cons, apply hp, { exact hs c (mem_cons.2 (or.inl rfl)), }, { exact ih (Ξ» b h, hs b (mem_cons.2 (or.inr h))), }, }, end lemma sup_le_of_le_directed {Ξ± : Type*} [semilattice_sup Ξ±] [order_bot Ξ±] (s : set Ξ±) (hs : s.nonempty) (hdir : directed_on (≀) s) (t : finset Ξ±) : (βˆ€ x ∈ t, βˆƒ y ∈ s, x ≀ y) β†’ βˆƒ x, x ∈ s ∧ t.sup id ≀ x := begin classical, apply finset.induction_on t, { simpa only [forall_prop_of_true, and_true, forall_prop_of_false, bot_le, not_false_iff, sup_empty, forall_true_iff, not_mem_empty], }, { intros a r har ih h, have incs : ↑r βŠ† ↑(insert a r), by { rw finset.coe_subset, apply finset.subset_insert, }, -- x ∈ s is above the sup of r obtain ⟨x, ⟨hxs, hsx_sup⟩⟩ := ih (Ξ» x hx, h x $ incs hx), -- y ∈ s is above a obtain ⟨y, hys, hay⟩ := h a (finset.mem_insert_self a r), -- z ∈ s is above x and y obtain ⟨z, hzs, ⟨hxz, hyz⟩⟩ := hdir x hxs y hys, use [z, hzs], rw [sup_insert, id.def, _root_.sup_le_iff], exact ⟨le_trans hay hyz, le_trans hsx_sup hxz⟩, }, end -- If we acquire sublattices -- the hypotheses should be reformulated as `s : subsemilattice_sup_bot` lemma sup_mem (s : set Ξ±) (w₁ : βŠ₯ ∈ s) (wβ‚‚ : βˆ€ x y ∈ s, x βŠ” y ∈ s) {ΞΉ : Type*} (t : finset ΞΉ) (p : ΞΉ β†’ Ξ±) (h : βˆ€ i ∈ t, p i ∈ s) : t.sup p ∈ s := @sup_induction _ _ _ _ _ _ (∈ s) w₁ wβ‚‚ h @[simp] lemma sup_eq_bot_iff (f : Ξ² β†’ Ξ±) (S : finset Ξ²) : S.sup f = βŠ₯ ↔ βˆ€ s ∈ S, f s = βŠ₯ := begin classical, induction S using finset.induction with a S haS hi; simp [*], end end sup lemma disjoint_sup_right [distrib_lattice Ξ±] [order_bot Ξ±] {a : Ξ±} {s : finset Ξ²} {f : Ξ² β†’ Ξ±} : disjoint a (s.sup f) ↔ βˆ€ i ∈ s, disjoint a (f i) := ⟨λ h i hi, h.mono_right (le_sup hi), sup_induction (disjoint_bot_right) $ ball_cond_comm.mpr $ @disjoint.sup_right _ _ _ _⟩ lemma disjoint_sup_left [distrib_lattice Ξ±] [order_bot Ξ±] {a : Ξ±} {s : finset Ξ²} {f : Ξ² β†’ Ξ±} : disjoint (s.sup f) a ↔ βˆ€ i ∈ s, disjoint (f i) a := by { simp_rw @disjoint.comm _ _ _ _ a, exact disjoint_sup_right } lemma sup_eq_supr [complete_lattice Ξ²] (s : finset Ξ±) (f : Ξ± β†’ Ξ²) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) lemma sup_id_eq_Sup [complete_lattice Ξ±] (s : finset Ξ±) : s.sup id = Sup s := by simp [Sup_eq_supr, sup_eq_supr] lemma sup_eq_Sup_image [complete_lattice Ξ²] (s : finset Ξ±) (f : Ξ± β†’ Ξ²) : s.sup f = Sup (f '' s) := begin classical, rw [←finset.coe_image, ←sup_id_eq_Sup, sup_image, function.comp.left_id], end /-! ### inf -/ section inf -- TODO: define with just `[has_top Ξ±]` where some lemmas hold without requiring `[order_top Ξ±]` variables [semilattice_inf Ξ±] [order_top Ξ±] /-- Infimum of a finite set: `inf {a, b, c} f = f a βŠ“ f b βŠ“ f c` -/ def inf (s : finset Ξ²) (f : Ξ² β†’ Ξ±) : Ξ± := s.fold (βŠ“) ⊀ f variables {s s₁ sβ‚‚ : finset Ξ²} {f g : Ξ² β†’ Ξ±} lemma inf_def : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (βˆ… : finset Ξ²).inf f = ⊀ := fold_empty @[simp] lemma inf_cons {b : Ξ²} (h : b βˆ‰ s) : (cons b s h).inf f = f b βŠ“ s.inf f := @sup_cons (order_dual Ξ±) _ _ _ _ _ _ h @[simp] lemma inf_insert [decidable_eq Ξ²] {b : Ξ²} : (insert b s : finset Ξ²).inf f = f b βŠ“ s.inf f := fold_insert_idem lemma inf_image [decidable_eq Ξ²] (s : finset Ξ³) (f : Ξ³ β†’ Ξ²) (g : Ξ² β†’ Ξ±) : (s.image f).inf g = s.inf (g ∘ f) := fold_image_idem @[simp] lemma inf_map (s : finset Ξ³) (f : Ξ³ β†ͺ Ξ²) (g : Ξ² β†’ Ξ±) : (s.map f).inf g = s.inf (g ∘ f) := fold_map @[simp] lemma inf_singleton {b : Ξ²} : ({b} : finset Ξ²).inf f = f b := inf_singleton lemma inf_union [decidable_eq Ξ²] : (s₁ βˆͺ sβ‚‚).inf f = s₁.inf f βŠ“ sβ‚‚.inf f := @sup_union (order_dual Ξ±) _ _ _ _ _ _ _ lemma inf_inf : s.inf (f βŠ“ g) = s.inf f βŠ“ s.inf g := @sup_sup (order_dual Ξ±) _ _ _ _ _ _ theorem inf_congr {f g : Ξ² β†’ Ξ±} (hs : s₁ = sβ‚‚) (hfg : βˆ€a∈sβ‚‚, f a = g a) : s₁.inf f = sβ‚‚.inf g := by subst hs; exact finset.fold_congr hfg @[simp] lemma inf_bUnion [decidable_eq Ξ²] (s : finset Ξ³) (t : Ξ³ β†’ finset Ξ²) : (s.bUnion t).inf f = s.inf (Ξ» x, (t x).inf f) := @sup_bUnion (order_dual Ξ±) _ _ _ _ _ _ _ _ lemma inf_const {s : finset Ξ²} (h : s.nonempty) (c : Ξ±) : s.inf (Ξ» _, c) = c := @sup_const (order_dual Ξ±) _ _ _ _ h _ @[simp] lemma inf_top (s : finset Ξ²) : s.inf (Ξ» _, ⊀) = (⊀ : Ξ±) := @sup_bot (order_dual Ξ±) _ _ _ _ lemma le_inf_iff {a : Ξ±} : a ≀ s.inf f ↔ βˆ€ b ∈ s, a ≀ f b := @sup_le_iff (order_dual Ξ±) _ _ _ _ _ _ lemma inf_le {b : Ξ²} (hb : b ∈ s) : s.inf f ≀ f b := le_inf_iff.1 le_rfl _ hb lemma le_inf {a : Ξ±} : (βˆ€b ∈ s, a ≀ f b) β†’ a ≀ s.inf f := le_inf_iff.2 lemma inf_mono_fun {g : Ξ² β†’ Ξ±} (h : βˆ€b∈s, f b ≀ g b) : s.inf f ≀ s.inf g := le_inf (Ξ» b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ βŠ† sβ‚‚) : sβ‚‚.inf f ≀ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) @[simp] lemma lt_inf_iff [is_total Ξ± (≀)] {a : Ξ±} (ha : a < ⊀) : a < s.inf f ↔ (βˆ€ b ∈ s, a < f b) := @sup_lt_iff (order_dual Ξ±) _ _ _ _ _ _ _ ha @[simp] lemma inf_le_iff [is_total Ξ± (≀)] {a : Ξ±} (ha : a < ⊀) : s.inf f ≀ a ↔ (βˆƒ b ∈ s, f b ≀ a) := @le_sup_iff (order_dual Ξ±) _ _ _ _ _ _ _ ha @[simp] lemma inf_lt_iff [is_total Ξ± (≀)] {a : Ξ±} : s.inf f < a ↔ (βˆƒ b ∈ s, f b < a) := @lt_sup_iff (order_dual Ξ±) _ _ _ _ _ _ _ lemma inf_attach (s : finset Ξ²) (f : Ξ² β†’ Ξ±) : s.attach.inf (Ξ» x, f x) = s.inf f := @sup_attach (order_dual Ξ±) _ _ _ _ _ lemma inf_comm (s : finset Ξ²) (t : finset Ξ³) (f : Ξ² β†’ Ξ³ β†’ Ξ±) : s.inf (Ξ» b, t.inf (f b)) = t.inf (Ξ» c, s.inf (Ξ» b, f b c)) := @sup_comm (order_dual Ξ±) _ _ _ _ _ _ _ lemma inf_product_left (s : finset Ξ²) (t : finset Ξ³) (f : Ξ² Γ— Ξ³ β†’ Ξ±) : (s.product t).inf f = s.inf (Ξ» i, t.inf $ Ξ» i', f ⟨i, i'⟩) := @sup_product_left (order_dual Ξ±) _ _ _ _ _ _ _ lemma inf_product_right (s : finset Ξ²) (t : finset Ξ³) (f : Ξ² Γ— Ξ³ β†’ Ξ±) : (s.product t).inf f = t.inf (Ξ» i', s.inf $ Ξ» i, f ⟨i, i'⟩) := @sup_product_right (order_dual Ξ±) _ _ _ _ _ _ _ @[simp] lemma inf_erase_top [decidable_eq Ξ±] (s : finset Ξ±) : (s.erase ⊀).inf id = s.inf id := @sup_erase_bot (order_dual Ξ±) _ _ _ _ lemma sup_sdiff_left {Ξ± Ξ² : Type*} [boolean_algebra Ξ±] (s : finset Ξ²) (f : Ξ² β†’ Ξ±) (a : Ξ±) : s.sup (Ξ» b, a \ f b) = a \ s.inf f := begin refine finset.cons_induction_on s _ (Ξ» b t _ h, _), { rw [sup_empty, inf_empty, sdiff_top] }, { rw [sup_cons, inf_cons, h, sdiff_inf] } end lemma inf_sdiff_left {Ξ± Ξ² : Type*} [boolean_algebra Ξ±] {s : finset Ξ²} (hs : s.nonempty) (f : Ξ² β†’ Ξ±) (a : Ξ±) : s.inf (Ξ» b, a \ f b) = a \ s.sup f := begin induction hs using finset.nonempty.cons_induction with b b t _ _ h, { rw [sup_singleton, inf_singleton] }, { rw [sup_cons, inf_cons, h, sdiff_sup] } end lemma inf_sdiff_right {Ξ± Ξ² : Type*} [boolean_algebra Ξ±] {s : finset Ξ²} (hs : s.nonempty) (f : Ξ² β†’ Ξ±) (a : Ξ±) : s.inf (Ξ» b, f b \ a) = s.inf f \ a := begin induction hs using finset.nonempty.cons_induction with b b t _ _ h, { rw [inf_singleton, inf_singleton] }, { rw [inf_cons, inf_cons, h, inf_sdiff] } end lemma comp_inf_eq_inf_comp [semilattice_inf Ξ³] [order_top Ξ³] {s : finset Ξ²} {f : Ξ² β†’ Ξ±} (g : Ξ± β†’ Ξ³) (g_inf : βˆ€ x y, g (x βŠ“ y) = g x βŠ“ g y) (top : g ⊀ = ⊀) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp (order_dual Ξ±) _ (order_dual Ξ³) _ _ _ _ _ _ _ g_inf top lemma comp_inf_eq_inf_comp_of_is_total [h : is_total Ξ± (≀)] {Ξ³ : Type} [semilattice_inf Ξ³] [order_top Ξ³] (g : Ξ± β†’ Ξ³) (mono_g : monotone g) (top : g ⊀ = ⊀) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top /-- Computing `inf` in a subtype (closed under `inf`) is the same as computing it in `Ξ±`. -/ lemma inf_coe {P : Ξ± β†’ Prop} {Ptop : P ⊀} {Pinf : βˆ€{{x y}}, P x β†’ P y β†’ P (x βŠ“ y)} (t : finset Ξ²) (f : Ξ² β†’ {x : Ξ± // P x}) : (@inf _ _ (subtype.semilattice_inf Pinf) (subtype.order_top Ptop) t f : Ξ±) = t.inf (Ξ» x, f x) := @sup_coe (order_dual Ξ±) _ _ _ _ Ptop Pinf t f lemma inf_induction {p : Ξ± β†’ Prop} (ht : p ⊀) (hp : βˆ€ a₁, p a₁ β†’ βˆ€ aβ‚‚, p aβ‚‚ β†’ p (a₁ βŠ“ aβ‚‚)) (hs : βˆ€ b ∈ s, p (f b)) : p (s.inf f) := @sup_induction (order_dual Ξ±) _ _ _ _ _ _ ht hp hs lemma inf_mem (s : set Ξ±) (w₁ : ⊀ ∈ s) (wβ‚‚ : βˆ€ x y ∈ s, x βŠ“ y ∈ s) {ΞΉ : Type*} (t : finset ΞΉ) (p : ΞΉ β†’ Ξ±) (h : βˆ€ i ∈ t, p i ∈ s) : t.inf p ∈ s := @inf_induction _ _ _ _ _ _ (∈ s) w₁ wβ‚‚ h @[simp] lemma inf_eq_top_iff (f : Ξ² β†’ Ξ±) (S : finset Ξ²) : S.inf f = ⊀ ↔ βˆ€ s ∈ S, f s = ⊀ := @finset.sup_eq_bot_iff (order_dual Ξ±) _ _ _ _ _ end inf section distrib_lattice variables [distrib_lattice Ξ±] lemma sup_inf_distrib_left [order_bot Ξ±] (s : finset ΞΉ) (f : ΞΉ β†’ Ξ±) (a : Ξ±) : a βŠ“ s.sup f = s.sup (Ξ» i, a βŠ“ f i) := begin induction s using finset.cons_induction with i s hi h, { simp_rw [finset.sup_empty, inf_bot_eq] }, { rw [sup_cons, sup_cons, inf_sup_left, h] } end lemma sup_inf_distrib_right [order_bot Ξ±] (s : finset ΞΉ) (f : ΞΉ β†’ Ξ±) (a : Ξ±) : s.sup f βŠ“ a = s.sup (Ξ» i, f i βŠ“ a) := by { rw [_root_.inf_comm, s.sup_inf_distrib_left], simp_rw _root_.inf_comm } lemma inf_sup_distrib_left [order_top Ξ±] (s : finset ΞΉ) (f : ΞΉ β†’ Ξ±) (a : Ξ±) : a βŠ” s.inf f = s.inf (Ξ» i, a βŠ” f i) := @sup_inf_distrib_left (order_dual Ξ±) _ _ _ _ _ _ lemma inf_sup_distrib_right [order_top Ξ±] (s : finset ΞΉ) (f : ΞΉ β†’ Ξ±) (a : Ξ±) : s.inf f βŠ” a = s.inf (Ξ» i, f i βŠ” a) := @sup_inf_distrib_right (order_dual Ξ±) _ _ _ _ _ _ end distrib_lattice lemma inf_eq_infi [complete_lattice Ξ²] (s : finset Ξ±) (f : Ξ± β†’ Ξ²) : s.inf f = (β¨…a∈s, f a) := @sup_eq_supr _ (order_dual Ξ²) _ _ _ lemma inf_id_eq_Inf [complete_lattice Ξ±] (s : finset Ξ±) : s.inf id = Inf s := @sup_id_eq_Sup (order_dual Ξ±) _ _ lemma inf_eq_Inf_image [complete_lattice Ξ²] (s : finset Ξ±) (f : Ξ± β†’ Ξ²) : s.inf f = Inf (f '' s) := @sup_eq_Sup_image _ (order_dual Ξ²) _ _ _ section sup' variables [semilattice_sup Ξ±] lemma sup_of_mem {s : finset Ξ²} (f : Ξ² β†’ Ξ±) {b : Ξ²} (h : b ∈ s) : βˆƒ (a : Ξ±), s.sup (coe ∘ f : Ξ² β†’ with_bot Ξ±) = ↑a := Exists.imp (Ξ» a, Exists.fst) (@le_sup (with_bot Ξ±) _ _ _ _ _ _ h (f b) rfl) /-- Given nonempty finset `s` then `s.sup' H f` is the supremum of its image under `f` in (possibly unbounded) join-semilattice `Ξ±`, where `H` is a proof of nonemptiness. If `Ξ±` has a bottom element you may instead use `finset.sup` which does not require `s` nonempty. -/ def sup' (s : finset Ξ²) (H : s.nonempty) (f : Ξ² β†’ Ξ±) : Ξ± := option.get $ let ⟨b, hb⟩ := H in option.is_some_iff_exists.2 (sup_of_mem f hb) variables {s : finset Ξ²} (H : s.nonempty) (f : Ξ² β†’ Ξ±) @[simp] lemma coe_sup' : ((s.sup' H f : Ξ±) : with_bot Ξ±) = s.sup (coe ∘ f) := by rw [sup', ←with_bot.some_eq_coe, option.some_get] @[simp] lemma sup'_cons {b : Ξ²} {hb : b βˆ‰ s} {h : (cons b s hb).nonempty} : (cons b s hb).sup' h f = f b βŠ” s.sup' H f := by { rw ←with_bot.coe_eq_coe, simp only [coe_sup', sup_cons, with_bot.coe_sup], } @[simp] lemma sup'_insert [decidable_eq Ξ²] {b : Ξ²} {h : (insert b s).nonempty} : (insert b s).sup' h f = f b βŠ” s.sup' H f := by { rw ←with_bot.coe_eq_coe, simp only [coe_sup', sup_insert, with_bot.coe_sup], } @[simp] lemma sup'_singleton {b : Ξ²} {h : ({b} : finset Ξ²).nonempty} : ({b} : finset Ξ²).sup' h f = f b := rfl lemma sup'_le {a : Ξ±} (hs : βˆ€ b ∈ s, f b ≀ a) : s.sup' H f ≀ a := by { rw [←with_bot.coe_le_coe, coe_sup'], exact sup_le (Ξ» b h, with_bot.coe_le_coe.2 $ hs b h), } lemma le_sup' {b : Ξ²} (h : b ∈ s) : f b ≀ s.sup' ⟨b, h⟩ f := by { rw [←with_bot.coe_le_coe, coe_sup'], exact le_sup h, } @[simp] lemma sup'_const (a : Ξ±) : s.sup' H (Ξ» b, a) = a := begin apply le_antisymm, { apply sup'_le, intros, exact le_rfl, }, { apply le_sup' (Ξ» b, a) H.some_spec, } end @[simp] lemma sup'_le_iff {a : Ξ±} : s.sup' H f ≀ a ↔ βˆ€ b ∈ s, f b ≀ a := iff.intro (Ξ» h b hb, trans (le_sup' f hb) h) (sup'_le H f) @[simp] lemma sup'_lt_iff [is_total Ξ± (≀)] {a : Ξ±} : s.sup' H f < a ↔ (βˆ€ b ∈ s, f b < a) := begin rw [←with_bot.coe_lt_coe, coe_sup', sup_lt_iff (with_bot.bot_lt_coe a)], exact ball_congr (Ξ» b hb, with_bot.coe_lt_coe), end @[simp] lemma le_sup'_iff [is_total Ξ± (≀)] {a : Ξ±} : a ≀ s.sup' H f ↔ (βˆƒ b ∈ s, a ≀ f b) := begin rw [←with_bot.coe_le_coe, coe_sup', le_sup_iff (with_bot.bot_lt_coe a)], exact bex_congr (Ξ» b hb, with_bot.coe_le_coe), end @[simp] lemma lt_sup'_iff [is_total Ξ± (≀)] {a : Ξ±} : a < s.sup' H f ↔ (βˆƒ b ∈ s, a < f b) := begin rw [←with_bot.coe_lt_coe, coe_sup', lt_sup_iff], exact bex_congr (Ξ» b hb, with_bot.coe_lt_coe), end lemma sup'_bUnion [decidable_eq Ξ²] {s : finset Ξ³} (Hs : s.nonempty) {t : Ξ³ β†’ finset Ξ²} (Ht : βˆ€ b, (t b).nonempty) : (s.bUnion t).sup' (Hs.bUnion (Ξ» b _, Ht b)) f = s.sup' Hs (Ξ» b, (t b).sup' (Ht b) f) := eq_of_forall_ge_iff $ Ξ» c, by simp [@forall_swap _ Ξ²] lemma comp_sup'_eq_sup'_comp [semilattice_sup Ξ³] {s : finset Ξ²} (H : s.nonempty) {f : Ξ² β†’ Ξ±} (g : Ξ± β†’ Ξ³) (g_sup : βˆ€ x y, g (x βŠ” y) = g x βŠ” g y) : g (s.sup' H f) = s.sup' H (g ∘ f) := begin rw [←with_bot.coe_eq_coe, coe_sup'], let g' : with_bot Ξ± β†’ with_bot Ξ³ := with_bot.rec_bot_coe βŠ₯ (Ξ» x, ↑(g x)), show g' ↑(s.sup' H f) = s.sup (Ξ» a, g' ↑(f a)), rw coe_sup', refine comp_sup_eq_sup_comp g' _ rfl, intros f₁ fβ‚‚, cases f₁, { rw [with_bot.none_eq_bot, bot_sup_eq], exact bot_sup_eq.symm, }, { cases fβ‚‚, refl, exact congr_arg coe (g_sup f₁ fβ‚‚), }, end lemma sup'_induction {p : Ξ± β†’ Prop} (hp : βˆ€ a₁, p a₁ β†’ βˆ€ aβ‚‚, p aβ‚‚ β†’ p (a₁ βŠ” aβ‚‚)) (hs : βˆ€ b ∈ s, p (f b)) : p (s.sup' H f) := begin show @with_bot.rec_bot_coe Ξ± (Ξ» _, Prop) true p ↑(s.sup' H f), rw coe_sup', refine sup_induction trivial _ hs, rintro (_|a₁) h₁ aβ‚‚ hβ‚‚, { rw [with_bot.none_eq_bot, bot_sup_eq], exact hβ‚‚ }, cases aβ‚‚, exacts [h₁, hp a₁ h₁ aβ‚‚ hβ‚‚] end lemma exists_mem_eq_sup' [is_total Ξ± (≀)] : βˆƒ b, b ∈ s ∧ s.sup' H f = f b := begin refine H.cons_induction (Ξ» c, _) (Ξ» c s hc hs ih, _), { exact ⟨c, mem_singleton_self c, rfl⟩, }, { rcases ih with ⟨b, hb, h'⟩, rw [sup'_cons hs, h'], cases total_of (≀) (f b) (f c) with h h, { exact ⟨c, mem_cons.2 (or.inl rfl), sup_eq_left.2 h⟩, }, { exact ⟨b, mem_cons.2 (or.inr hb), sup_eq_right.2 h⟩, }, }, end lemma sup'_mem (s : set Ξ±) (w : βˆ€ x y ∈ s, x βŠ” y ∈ s) {ΞΉ : Type*} (t : finset ΞΉ) (H : t.nonempty) (p : ΞΉ β†’ Ξ±) (h : βˆ€ i ∈ t, p i ∈ s) : t.sup' H p ∈ s := sup'_induction H p w h @[congr] lemma sup'_congr {t : finset Ξ²} {f g : Ξ² β†’ Ξ±} (h₁ : s = t) (hβ‚‚ : βˆ€ x ∈ s, f x = g x) : s.sup' H f = t.sup' (h₁ β–Έ H) g := begin subst s, refine eq_of_forall_ge_iff (Ξ» c, _), simp only [sup'_le_iff, hβ‚‚] { contextual := tt } end end sup' section inf' variables [semilattice_inf Ξ±] lemma inf_of_mem {s : finset Ξ²} (f : Ξ² β†’ Ξ±) {b : Ξ²} (h : b ∈ s) : βˆƒ (a : Ξ±), s.inf (coe ∘ f : Ξ² β†’ with_top Ξ±) = ↑a := @sup_of_mem (order_dual Ξ±) _ _ _ f _ h /-- Given nonempty finset `s` then `s.inf' H f` is the infimum of its image under `f` in (possibly unbounded) meet-semilattice `Ξ±`, where `H` is a proof of nonemptiness. If `Ξ±` has a top element you may instead use `finset.inf` which does not require `s` nonempty. -/ def inf' (s : finset Ξ²) (H : s.nonempty) (f : Ξ² β†’ Ξ±) : Ξ± := @sup' (order_dual Ξ±) _ _ s H f variables {s : finset Ξ²} (H : s.nonempty) (f : Ξ² β†’ Ξ±) @[simp] lemma coe_inf' : ((s.inf' H f : Ξ±) : with_top Ξ±) = s.inf (coe ∘ f) := @coe_sup' (order_dual Ξ±) _ _ _ H f @[simp] lemma inf'_cons {b : Ξ²} {hb : b βˆ‰ s} {h : (cons b s hb).nonempty} : (cons b s hb).inf' h f = f b βŠ“ s.inf' H f := @sup'_cons (order_dual Ξ±) _ _ _ H f _ _ _ @[simp] lemma inf'_insert [decidable_eq Ξ²] {b : Ξ²} {h : (insert b s).nonempty} : (insert b s).inf' h f = f b βŠ“ s.inf' H f := @sup'_insert (order_dual Ξ±) _ _ _ H f _ _ _ @[simp] lemma inf'_singleton {b : Ξ²} {h : ({b} : finset Ξ²).nonempty} : ({b} : finset Ξ²).inf' h f = f b := rfl lemma le_inf' {a : Ξ±} (hs : βˆ€ b ∈ s, a ≀ f b) : a ≀ s.inf' H f := @sup'_le (order_dual Ξ±) _ _ _ H f _ hs lemma inf'_le {b : Ξ²} (h : b ∈ s) : s.inf' ⟨b, h⟩ f ≀ f b := @le_sup' (order_dual Ξ±) _ _ _ f _ h @[simp] lemma inf'_const (a : Ξ±) : s.inf' H (Ξ» b, a) = a := @sup'_const (order_dual Ξ±) _ _ _ _ _ @[simp] lemma le_inf'_iff {a : Ξ±} : a ≀ s.inf' H f ↔ βˆ€ b ∈ s, a ≀ f b := @sup'_le_iff (order_dual Ξ±) _ _ _ H f _ @[simp] lemma lt_inf'_iff [is_total Ξ± (≀)] {a : Ξ±} : a < s.inf' H f ↔ (βˆ€ b ∈ s, a < f b) := @sup'_lt_iff (order_dual Ξ±) _ _ _ H f _ _ @[simp] lemma inf'_le_iff [is_total Ξ± (≀)] {a : Ξ±} : s.inf' H f ≀ a ↔ (βˆƒ b ∈ s, f b ≀ a) := @le_sup'_iff (order_dual Ξ±) _ _ _ H f _ _ @[simp] lemma inf'_lt_iff [is_total Ξ± (≀)] {a : Ξ±} : s.inf' H f < a ↔ (βˆƒ b ∈ s, f b < a) := @lt_sup'_iff (order_dual Ξ±) _ _ _ H f _ _ lemma inf'_bUnion [decidable_eq Ξ²] {s : finset Ξ³} (Hs : s.nonempty) {t : Ξ³ β†’ finset Ξ²} (Ht : βˆ€ b, (t b).nonempty) : (s.bUnion t).inf' (Hs.bUnion (Ξ» b _, Ht b)) f = s.inf' Hs (Ξ» b, (t b).inf' (Ht b) f) := @sup'_bUnion (order_dual Ξ±) _ _ _ _ _ _ Hs _ Ht lemma comp_inf'_eq_inf'_comp [semilattice_inf Ξ³] {s : finset Ξ²} (H : s.nonempty) {f : Ξ² β†’ Ξ±} (g : Ξ± β†’ Ξ³) (g_inf : βˆ€ x y, g (x βŠ“ y) = g x βŠ“ g y) : g (s.inf' H f) = s.inf' H (g ∘ f) := @comp_sup'_eq_sup'_comp (order_dual Ξ±) _ (order_dual Ξ³) _ _ _ H f g g_inf lemma inf'_induction {p : Ξ± β†’ Prop} (hp : βˆ€ a₁, p a₁ β†’ βˆ€ aβ‚‚, p aβ‚‚ β†’ p (a₁ βŠ“ aβ‚‚)) (hs : βˆ€ b ∈ s, p (f b)) : p (s.inf' H f) := @sup'_induction (order_dual Ξ±) _ _ _ H f _ hp hs lemma exists_mem_eq_inf' [is_total Ξ± (≀)] : βˆƒ b, b ∈ s ∧ s.inf' H f = f b := @exists_mem_eq_sup' (order_dual Ξ±) _ _ _ H f _ lemma inf'_mem (s : set Ξ±) (w : βˆ€ x y ∈ s, x βŠ“ y ∈ s) {ΞΉ : Type*} (t : finset ΞΉ) (H : t.nonempty) (p : ΞΉ β†’ Ξ±) (h : βˆ€ i ∈ t, p i ∈ s) : t.inf' H p ∈ s := inf'_induction H p w h @[congr] lemma inf'_congr {t : finset Ξ²} {f g : Ξ² β†’ Ξ±} (h₁ : s = t) (hβ‚‚ : βˆ€ x ∈ s, f x = g x) : s.inf' H f = t.inf' (h₁ β–Έ H) g := @sup'_congr (order_dual Ξ±) _ _ _ H _ _ _ h₁ hβ‚‚ end inf' section sup variables [semilattice_sup Ξ±] [order_bot Ξ±] lemma sup'_eq_sup {s : finset Ξ²} (H : s.nonempty) (f : Ξ² β†’ Ξ±) : s.sup' H f = s.sup f := le_antisymm (sup'_le H f (Ξ» b, le_sup)) (sup_le (Ξ» b, le_sup' f)) lemma sup_closed_of_sup_closed {s : set Ξ±} (t : finset Ξ±) (htne : t.nonempty) (h_subset : ↑t βŠ† s) (h : βˆ€ a b ∈ s, a βŠ” b ∈ s) : t.sup id ∈ s := sup'_eq_sup htne id β–Έ sup'_induction _ _ h h_subset lemma exists_mem_eq_sup [is_total Ξ± (≀)] (s : finset Ξ²) (h : s.nonempty) (f : Ξ² β†’ Ξ±) : βˆƒ b, b ∈ s ∧ s.sup f = f b := sup'_eq_sup h f β–Έ exists_mem_eq_sup' h f lemma coe_sup_of_nonempty {s : finset Ξ²} (h : s.nonempty) (f : Ξ² β†’ Ξ±) : (↑(s.sup f) : with_bot Ξ±) = s.sup (coe ∘ f) := by simp only [←sup'_eq_sup h, coe_sup' h] end sup section inf variables [semilattice_inf Ξ±] [order_top Ξ±] lemma inf'_eq_inf {s : finset Ξ²} (H : s.nonempty) (f : Ξ² β†’ Ξ±) : s.inf' H f = s.inf f := @sup'_eq_sup (order_dual Ξ±) _ _ _ _ H f lemma inf_closed_of_inf_closed {s : set Ξ±} (t : finset Ξ±) (htne : t.nonempty) (h_subset : ↑t βŠ† s) (h : βˆ€ a b ∈ s, a βŠ“ b ∈ s) : t.inf id ∈ s := @sup_closed_of_sup_closed (order_dual Ξ±) _ _ _ t htne h_subset h lemma exists_mem_eq_inf [is_total Ξ± (≀)] (s : finset Ξ²) (h : s.nonempty) (f : Ξ² β†’ Ξ±) : βˆƒ a, a ∈ s ∧ s.inf f = f a := @exists_mem_eq_sup (order_dual Ξ±) _ _ _ _ _ h f lemma coe_inf_of_nonempty {s : finset Ξ²} (h : s.nonempty) (f : Ξ² β†’ Ξ±): (↑(s.inf f) : with_top Ξ±) = s.inf (Ξ» i, f i) := @coe_sup_of_nonempty (order_dual Ξ±) _ _ _ _ h f end inf section sup variables {C : Ξ² β†’ Type*} [Ξ  (b : Ξ²), semilattice_sup (C b)] [Ξ  (b : Ξ²), order_bot (C b)] @[simp] protected lemma sup_apply (s : finset Ξ±) (f : Ξ± β†’ Ξ  (b : Ξ²), C b) (b : Ξ²) : s.sup f b = s.sup (Ξ» a, f a b) := comp_sup_eq_sup_comp (Ξ» x : Ξ  b : Ξ², C b, x b) (Ξ» i j, rfl) rfl end sup section inf variables {C : Ξ² β†’ Type*} [Ξ  (b : Ξ²), semilattice_inf (C b)] [Ξ  (b : Ξ²), order_top (C b)] @[simp] protected lemma inf_apply (s : finset Ξ±) (f : Ξ± β†’ Ξ  (b : Ξ²), C b) (b : Ξ²) : s.inf f b = s.inf (Ξ» a, f a b) := @finset.sup_apply _ _ (Ξ» b, order_dual (C b)) _ _ s f b end inf section sup' variables {C : Ξ² β†’ Type*} [Ξ  (b : Ξ²), semilattice_sup (C b)] @[simp] protected lemma sup'_apply {s : finset Ξ±} (H : s.nonempty) (f : Ξ± β†’ Ξ  (b : Ξ²), C b) (b : Ξ²) : s.sup' H f b = s.sup' H (Ξ» a, f a b) := comp_sup'_eq_sup'_comp H (Ξ» x : Ξ  b : Ξ², C b, x b) (Ξ» i j, rfl) end sup' section inf' variables {C : Ξ² β†’ Type*} [Ξ  (b : Ξ²), semilattice_inf (C b)] @[simp] protected lemma inf'_apply {s : finset Ξ±} (H : s.nonempty) (f : Ξ± β†’ Ξ  (b : Ξ²), C b) (b : Ξ²) : s.inf' H f b = s.inf' H (Ξ» a, f a b) := @finset.sup'_apply _ _ (Ξ» b, order_dual (C b)) _ _ H f b end inf' /-! ### max and min of finite sets -/ section max_min variables [linear_order Ξ±] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option Ξ±`. If you want to get an element of `Ξ±`, see `s.max'`. -/ protected def max : finset Ξ± β†’ option Ξ± := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset Ξ±) : s.max = @sup (with_bot Ξ±) Ξ± _ _ s some := rfl @[simp] theorem max_empty : (βˆ… : finset Ξ±).max = none := rfl @[simp] theorem max_insert {a : Ξ±} {s : finset Ξ±} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : Ξ±} : finset.max {a} = some a := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset Ξ±} {a : Ξ±} (h : a ∈ s) : βˆƒ b, b ∈ s.max := (@le_sup (with_bot Ξ±) _ _ _ _ _ _ h _ rfl).imp $ Ξ» b, Exists.fst theorem max_of_nonempty {s : finset Ξ±} (h : s.nonempty) : βˆƒ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset Ξ±} : s.max = none ↔ s = βˆ… := ⟨λ h, s.eq_empty_or_nonempty.elim id (Ξ» H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), Ξ» h, h.symm β–Έ max_empty⟩ theorem mem_of_max {s : finset Ξ±} : βˆ€ {a : Ξ±}, a ∈ s.max β†’ a ∈ s := finset.induction_on s (Ξ» _ H, by cases H) (Ξ» b s _ (ih : βˆ€ {a}, a ∈ s.max β†’ a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset Ξ±} {a b : Ξ±} (h₁ : a ∈ s) (hβ‚‚ : b ∈ s.max) : a ≀ b := by rcases @le_sup (with_bot Ξ±) _ _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases hβ‚‚.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option Ξ±`. If you want to get an element of `Ξ±`, see `s.min'`. -/ protected def min : finset Ξ± β†’ option Ξ± := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset Ξ±) : s.min = @inf (with_top Ξ±) Ξ± _ _ s some := rfl @[simp] theorem min_empty : (βˆ… : finset Ξ±).min = none := rfl @[simp] theorem min_insert {a : Ξ±} {s : finset Ξ±} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : Ξ±} : finset.min {a} = some a := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset Ξ±} {a : Ξ±} (h : a ∈ s) : βˆƒ b, b ∈ s.min := (@inf_le (with_top Ξ±) _ _ _ _ _ _ h _ rfl).imp $ Ξ» b, Exists.fst theorem min_of_nonempty {s : finset Ξ±} (h : s.nonempty) : βˆƒ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset Ξ±} : s.min = none ↔ s = βˆ… := ⟨λ h, s.eq_empty_or_nonempty.elim id (Ξ» H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), Ξ» h, h.symm β–Έ min_empty⟩ theorem mem_of_min {s : finset Ξ±} : βˆ€ {a : Ξ±}, a ∈ s.min β†’ a ∈ s := @mem_of_max (order_dual Ξ±) _ s theorem min_le_of_mem {s : finset Ξ±} {a b : Ξ±} (h₁ : b ∈ s) (hβ‚‚ : a ∈ s.min) : a ≀ b := by rcases @inf_le (with_top Ξ±) _ _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases hβ‚‚.symm.trans hb; assumption /-- Given a nonempty finset `s` in a linear order `Ξ± `, then `s.min' h` is its minimum, as an element of `Ξ±`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `option Ξ±`. -/ def min' (s : finset Ξ±) (H : s.nonempty) : Ξ± := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- Given a nonempty finset `s` in a linear order `Ξ± `, then `s.max' h` is its maximum, as an element of `Ξ±`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `option Ξ±`. -/ def max' (s : finset Ξ±) (H : s.nonempty) : Ξ± := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset Ξ±) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≀ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : βˆ€ y ∈ s, x ≀ y) : x ≀ s.min' H := H2 _ $ min'_mem _ _ theorem is_least_min' : is_least ↑s (s.min' H) := ⟨min'_mem _ _, min'_le _⟩ @[simp] lemma le_min'_iff {x} : x ≀ s.min' H ↔ βˆ€ y ∈ s, x ≀ y := le_is_glb_iff (is_least_min' s H).is_glb /-- `{a}.min' _` is `a`. -/ @[simp] lemma min'_singleton (a : Ξ±) : ({a} : finset Ξ±).min' (singleton_nonempty _) = a := by simp [min'] theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ s) : x ≀ s.max' ⟨x, H2⟩ := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : βˆ€ y ∈ s, y ≀ x) : s.max' H ≀ x := H2 _ $ max'_mem _ _ theorem is_greatest_max' : is_greatest ↑s (s.max' H) := ⟨max'_mem _ _, le_max' _⟩ @[simp] lemma max'_le_iff {x} : s.max' H ≀ x ↔ βˆ€ y ∈ s, y ≀ x := is_lub_le_iff (is_greatest_max' s H).is_lub @[simp] lemma max'_lt_iff {x} : s.max' H < x ↔ βˆ€ y ∈ s, y < x := ⟨λ Hlt y hy, (s.le_max' y hy).trans_lt Hlt, Ξ» H, H _ $ s.max'_mem _⟩ @[simp] lemma lt_min'_iff {x} : x < s.min' H ↔ βˆ€ y ∈ s, x < y := @max'_lt_iff (order_dual Ξ±) _ _ H _ lemma max'_eq_sup' : s.max' H = s.sup' H id := eq_of_forall_ge_iff $ Ξ» a, (max'_le_iff _ _).trans (sup'_le_iff _ _).symm lemma min'_eq_inf' : s.min' H = s.inf' H id := @max'_eq_sup' (order_dual Ξ±) _ s H /-- `{a}.max' _` is `a`. -/ @[simp] lemma max'_singleton (a : Ξ±) : ({a} : finset Ξ±).max' (singleton_nonempty _) = a := by simp [max'] theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i β‰  j) : s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ := is_glb_lt_is_lub_of_ne (s.is_least_min' _).is_glb (s.is_greatest_max' _).is_lub H1 H2 H3 /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ lemma min'_lt_max'_of_card (hβ‚‚ : 1 < card s) : s.min' (finset.card_pos.mp $ lt_trans zero_lt_one hβ‚‚) < s.max' (finset.card_pos.mp $ lt_trans zero_lt_one hβ‚‚) := begin rcases one_lt_card.1 hβ‚‚ with ⟨a, ha, b, hb, hab⟩, exact s.min'_lt_max' ha hb hab end lemma max'_eq_of_dual_min' {s : finset Ξ±} (hs : s.nonempty) : max' s hs = of_dual (min' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual Ξ±) (s : finset (order_dual Ξ±))), refl, end lemma min'_eq_of_dual_max' {s : finset Ξ±} (hs : s.nonempty) : min' s hs = of_dual (max' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual Ξ±) (s : finset (order_dual Ξ±))), refl, end @[simp] lemma of_dual_max_eq_min_of_dual {a b : Ξ±} : of_dual (max a b) = min (of_dual a) (of_dual b) := rfl @[simp] lemma of_dual_min_eq_max_of_dual {a b : Ξ±} : of_dual (min a b) = max (of_dual a) (of_dual b) := rfl lemma max'_subset {s t : finset Ξ±} (H : s.nonempty) (hst : s βŠ† t) : s.max' H ≀ t.max' (H.mono hst) := le_max' _ _ (hst (s.max'_mem H)) lemma min'_subset {s t : finset Ξ±} (H : s.nonempty) (hst : s βŠ† t) : t.min' (H.mono hst) ≀ s.min' H := min'_le _ _ (hst (s.min'_mem H)) lemma max'_insert (a : Ξ±) (s : finset Ξ±) (H : s.nonempty) : (insert a s).max' (s.insert_nonempty a) = max (s.max' H) a := (is_greatest_max' _ _).unique $ by { rw [coe_insert, max_comm], exact (is_greatest_max' _ _).insert _ } lemma min'_insert (a : Ξ±) (s : finset Ξ±) (H : s.nonempty) : (insert a s).min' (s.insert_nonempty a) = min (s.min' H) a := (is_least_min' _ _).unique $ by { rw [coe_insert, min_comm], exact (is_least_min' _ _).insert _ } lemma lt_max'_of_mem_erase_max' [decidable_eq Ξ±] {a : Ξ±} (ha : a ∈ s.erase (s.max' H)) : a < s.max' H := lt_of_le_of_ne (le_max' _ _ (mem_of_mem_erase ha)) $ ne_of_mem_of_not_mem ha $ not_mem_erase _ _ lemma min'_lt_of_mem_erase_min' [decidable_eq Ξ±] {a : Ξ±} (ha : a ∈ s.erase (s.min' H)) : s.min' H < a := @lt_max'_of_mem_erase_max' (order_dual Ξ±) _ s H _ a ha @[simp] lemma max'_image [linear_order Ξ²] {f : Ξ± β†’ Ξ²} (hf : monotone f) (s : finset Ξ±) (h : (s.image f).nonempty) : (s.image f).max' h = f (s.max' ((nonempty.image_iff f).mp h)) := begin refine le_antisymm (max'_le _ _ _ (Ξ» y hy, _)) (le_max' _ _ (mem_image.mpr ⟨_, max'_mem _ _, rfl⟩)), obtain ⟨x, hx, rfl⟩ := mem_image.mp hy, exact hf (le_max' _ _ hx) end @[simp] lemma min'_image [linear_order Ξ²] {f : Ξ± β†’ Ξ²} (hf : monotone f) (s : finset Ξ±) (h : (s.image f).nonempty) : (s.image f).min' h = f (s.min' ((nonempty.image_iff f).mp h)) := begin refine le_antisymm (min'_le _ _ (mem_image.mpr ⟨_, min'_mem _ _, rfl⟩)) (le_min' _ _ _ (Ξ» y hy, _)), obtain ⟨x, hx, rfl⟩ := mem_image.mp hy, exact hf (min'_le _ _ hx) end /-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all `s : finset Ξ±` provided that: * it is true on the empty `finset`, * for every `s : finset Ξ±` and an element `a` strictly greater than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_max [decidable_eq Ξ±] {p : finset Ξ± β†’ Prop} (s : finset Ξ±) (h0 : p βˆ…) (step : βˆ€ a s, (βˆ€ x ∈ s, x < a) β†’ p s β†’ p (insert a s)) : p s := begin induction s using finset.strong_induction_on with s ihs, rcases s.eq_empty_or_nonempty with rfl|hne, { exact h0 }, { have H : s.max' hne ∈ s, from max'_mem s hne, rw ← insert_erase H, exact step _ _ (Ξ» x, s.lt_max'_of_mem_erase_max' hne) (ihs _ $ erase_ssubset H) } end /-- Induction principle for `finset`s in a linearly ordered type: a predicate is true on all `s : finset Ξ±` provided that: * it is true on the empty `finset`, * for every `s : finset Ξ±` and an element `a` strictly less than all elements of `s`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_min [decidable_eq Ξ±] {p : finset Ξ± β†’ Prop} (s : finset Ξ±) (h0 : p βˆ…) (step : βˆ€ a s, (βˆ€ x ∈ s, a < x) β†’ p s β†’ p (insert a s)) : p s := @induction_on_max (order_dual Ξ±) _ _ _ s h0 step end max_min section max_min_induction_value variables [linear_order Ξ±] [linear_order Ξ²] /-- Induction principle for `finset`s in any type from which a given function `f` maps to a linearly ordered type : a predicate is true on all `s : finset Ξ±` provided that: * it is true on the empty `finset`, * for every `s : finset Ξ±` and an element `a` such that for elements of `s` denoted by `x` we have `f x ≀ f a`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_max_value [decidable_eq ΞΉ] (f : ΞΉ β†’ Ξ±) {p : finset ΞΉ β†’ Prop} (s : finset ΞΉ) (h0 : p βˆ…) (step : βˆ€ a s, a βˆ‰ s β†’ (βˆ€ x ∈ s, f x ≀ f a) β†’ p s β†’ p (insert a s)) : p s := begin induction s using finset.strong_induction_on with s ihs, rcases (s.image f).eq_empty_or_nonempty with hne|hne, { simp only [image_eq_empty] at hne, simp only [hne, h0] }, { have H : (s.image f).max' hne ∈ (s.image f), from max'_mem (s.image f) hne, simp only [mem_image, exists_prop] at H, rcases H with ⟨a, has, hfa⟩, rw ← insert_erase has, refine step _ _ (not_mem_erase a s) (Ξ» x hx, _) (ihs _ $ erase_ssubset has), rw hfa, exact le_max' _ _ (mem_image_of_mem _ $ mem_of_mem_erase hx) } end /-- Induction principle for `finset`s in any type from which a given function `f` maps to a linearly ordered type : a predicate is true on all `s : finset Ξ±` provided that: * it is true on the empty `finset`, * for every `s : finset Ξ±` and an element `a` such that for elements of `s` denoted by `x` we have `f a ≀ f x`, `p s` implies `p (insert a s)`. -/ @[elab_as_eliminator] lemma induction_on_min_value [decidable_eq ΞΉ] (f : ΞΉ β†’ Ξ±) {p : finset ΞΉ β†’ Prop} (s : finset ΞΉ) (h0 : p βˆ…) (step : βˆ€ a s, a βˆ‰ s β†’ (βˆ€ x ∈ s, f a ≀ f x) β†’ p s β†’ p (insert a s)) : p s := @induction_on_max_value (order_dual Ξ±) ΞΉ _ _ _ _ s h0 step end max_min_induction_value section exists_max_min variables [linear_order Ξ±] lemma exists_max_image (s : finset Ξ²) (f : Ξ² β†’ Ξ±) (h : s.nonempty) : βˆƒ x ∈ s, βˆ€ x' ∈ s, f x' ≀ f x := begin cases max_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, Ξ» x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩, end lemma exists_min_image (s : finset Ξ²) (f : Ξ² β†’ Ξ±) (h : s.nonempty) : βˆƒ x ∈ s, βˆ€ x' ∈ s, f x ≀ f x' := @exists_max_image (order_dual Ξ±) Ξ² _ s f h end exists_max_min end finset namespace multiset lemma map_finset_sup [decidable_eq Ξ±] [decidable_eq Ξ²] (s : finset Ξ³) (f : Ξ³ β†’ multiset Ξ²) (g : Ξ² β†’ Ξ±) (hg : function.injective g) : map g (s.sup f) = s.sup (map g ∘ f) := finset.comp_sup_eq_sup_comp _ (Ξ» _ _, map_union hg) (map_zero _) lemma count_finset_sup [decidable_eq Ξ²] (s : finset Ξ±) (f : Ξ± β†’ multiset Ξ²) (b : Ξ²) : count b (s.sup f) = s.sup (Ξ»a, count b (f a)) := begin letI := classical.dec_eq Ξ±, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end lemma mem_sup {Ξ± Ξ²} [decidable_eq Ξ²] {s : finset Ξ±} {f : Ξ± β†’ multiset Ξ²} {x : Ξ²} : x ∈ s.sup f ↔ βˆƒ v ∈ s, x ∈ f v := begin classical, apply s.induction_on, { simp }, { intros a s has hxs, rw [finset.sup_insert, multiset.sup_eq_union, multiset.mem_union], split, { intro hxi, cases hxi with hf hf, { refine ⟨a, _, hf⟩, simp only [true_or, eq_self_iff_true, finset.mem_insert] }, { rcases hxs.mp hf with ⟨v, hv, hfv⟩, refine ⟨v, _, hfv⟩, simp only [hv, or_true, finset.mem_insert] } }, { rintros ⟨v, hv, hfv⟩, rw [finset.mem_insert] at hv, rcases hv with rfl | hv, { exact or.inl hfv }, { refine or.inr (hxs.mpr ⟨v, hv, hfv⟩) } } }, end end multiset namespace finset lemma mem_sup {Ξ± Ξ²} [decidable_eq Ξ²] {s : finset Ξ±} {f : Ξ± β†’ finset Ξ²} {x : Ξ²} : x ∈ s.sup f ↔ βˆƒ v ∈ s, x ∈ f v := begin change _ ↔ βˆƒ v ∈ s, x ∈ (f v).val, rw [←multiset.mem_sup, ←multiset.mem_to_finset, sup_to_finset], simp_rw [val_to_finset], end lemma sup_eq_bUnion {Ξ± Ξ²} [decidable_eq Ξ²] (s : finset Ξ±) (t : Ξ± β†’ finset Ξ²) : s.sup t = s.bUnion t := by { ext, rw [mem_sup, mem_bUnion], } @[simp] lemma sup_singleton'' [decidable_eq Ξ±] (s : finset Ξ²) (f : Ξ² β†’ Ξ±) : s.sup (Ξ» b, {f b}) = s.image f := by { ext a, rw [mem_sup, mem_image], simp only [mem_singleton, eq_comm] } @[simp] lemma sup_singleton' [decidable_eq Ξ±] (s : finset Ξ±) : s.sup singleton = s := (s.sup_singleton'' _).trans image_id end finset section lattice variables {ΞΉ' : Sort*} [complete_lattice Ξ±] /-- Supremum of `s i`, `i : ΞΉ`, is equal to the supremum over `t : finset ΞΉ` of suprema `⨆ i ∈ t, s i`. This version assumes `ΞΉ` is a `Type*`. See `supr_eq_supr_finset'` for a version that works for `ΞΉ : Sort*`. -/ lemma supr_eq_supr_finset (s : ΞΉ β†’ Ξ±) : (⨆i, s i) = (⨆t:finset ΞΉ, ⨆i∈t, s i) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {b} $ le_supr_of_le b $ le_supr_of_le (by simp) $ le_rfl) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end /-- Supremum of `s i`, `i : ΞΉ`, is equal to the supremum over `t : finset ΞΉ` of suprema `⨆ i ∈ t, s i`. This version works for `ΞΉ : Sort*`. See `supr_eq_supr_finset` for a version that assumes `ΞΉ : Type*` but has no `plift`s. -/ lemma supr_eq_supr_finset' (s : ΞΉ' β†’ Ξ±) : (⨆i, s i) = (⨆t:finset (plift ΞΉ'), ⨆i∈t, s (plift.down i)) := by rw [← supr_eq_supr_finset, ← equiv.plift.surjective.supr_comp]; refl /-- Infimum of `s i`, `i : ΞΉ`, is equal to the infimum over `t : finset ΞΉ` of infima `β¨… i ∈ t, s i`. This version assumes `ΞΉ` is a `Type*`. See `infi_eq_infi_finset'` for a version that works for `ΞΉ : Sort*`. -/ lemma infi_eq_infi_finset (s : ΞΉ β†’ Ξ±) : (β¨…i, s i) = (β¨…t:finset ΞΉ, β¨…i∈t, s i) := @supr_eq_supr_finset (order_dual Ξ±) _ _ _ /-- Infimum of `s i`, `i : ΞΉ`, is equal to the infimum over `t : finset ΞΉ` of infima `β¨… i ∈ t, s i`. This version works for `ΞΉ : Sort*`. See `infi_eq_infi_finset` for a version that assumes `ΞΉ : Type*` but has no `plift`s. -/ lemma infi_eq_infi_finset' (s : ΞΉ' β†’ Ξ±) : (β¨…i, s i) = (β¨…t:finset (plift ΞΉ'), β¨…i∈t, s (plift.down i)) := @supr_eq_supr_finset' (order_dual Ξ±) _ _ _ end lattice namespace set variables {ΞΉ' : Sort*} /-- Union of an indexed family of sets `s : ΞΉ β†’ set Ξ±` is equal to the union of the unions of finite subfamilies. This version assumes `ΞΉ : Type*`. See also `Union_eq_Union_finset'` for a version that works for `ΞΉ : Sort*`. -/ lemma Union_eq_Union_finset (s : ΞΉ β†’ set Ξ±) : (⋃i, s i) = (⋃t:finset ΞΉ, ⋃i∈t, s i) := supr_eq_supr_finset s /-- Union of an indexed family of sets `s : ΞΉ β†’ set Ξ±` is equal to the union of the unions of finite subfamilies. This version works for `ΞΉ : Sort*`. See also `Union_eq_Union_finset` for a version that assumes `ΞΉ : Type*` but avoids `plift`s in the right hand side. -/ lemma Union_eq_Union_finset' (s : ΞΉ' β†’ set Ξ±) : (⋃i, s i) = (⋃t:finset (plift ΞΉ'), ⋃i∈t, s (plift.down i)) := supr_eq_supr_finset' s /-- Intersection of an indexed family of sets `s : ΞΉ β†’ set Ξ±` is equal to the intersection of the intersections of finite subfamilies. This version assumes `ΞΉ : Type*`. See also `Inter_eq_Inter_finset'` for a version that works for `ΞΉ : Sort*`. -/ lemma Inter_eq_Inter_finset (s : ΞΉ β†’ set Ξ±) : (β‹‚i, s i) = (β‹‚t:finset ΞΉ, β‹‚i∈t, s i) := infi_eq_infi_finset s /-- Intersection of an indexed family of sets `s : ΞΉ β†’ set Ξ±` is equal to the intersection of the intersections of finite subfamilies. This version works for `ΞΉ : Sort*`. See also `Inter_eq_Inter_finset` for a version that assumes `ΞΉ : Type*` but avoids `plift`s in the right hand side. -/ lemma Inter_eq_Inter_finset' (s : ΞΉ' β†’ set Ξ±) : (β‹‚i, s i) = (β‹‚t:finset (plift ΞΉ'), β‹‚i∈t, s (plift.down i)) := infi_eq_infi_finset' s end set namespace finset open function /-! ### Interaction with big lattice/set operations -/ section lattice lemma supr_coe [has_Sup Ξ²] (f : Ξ± β†’ Ξ²) (s : finset Ξ±) : (⨆ x ∈ (↑s : set Ξ±), f x) = ⨆ x ∈ s, f x := rfl lemma infi_coe [has_Inf Ξ²] (f : Ξ± β†’ Ξ²) (s : finset Ξ±) : (β¨… x ∈ (↑s : set Ξ±), f x) = β¨… x ∈ s, f x := rfl variables [complete_lattice Ξ²] theorem supr_singleton (a : Ξ±) (s : Ξ± β†’ Ξ²) : (⨆ x ∈ ({a} : finset Ξ±), s x) = s a := by simp theorem infi_singleton (a : Ξ±) (s : Ξ± β†’ Ξ²) : (β¨… x ∈ ({a} : finset Ξ±), s x) = s a := by simp lemma supr_option_to_finset (o : option Ξ±) (f : Ξ± β†’ Ξ²) : (⨆ x ∈ o.to_finset, f x) = ⨆ x ∈ o, f x := by simp lemma infi_option_to_finset (o : option Ξ±) (f : Ξ± β†’ Ξ²) : (β¨… x ∈ o.to_finset, f x) = β¨… x ∈ o, f x := @supr_option_to_finset _ (order_dual Ξ²) _ _ _ variables [decidable_eq Ξ±] theorem supr_union {f : Ξ± β†’ Ξ²} {s t : finset Ξ±} : (⨆ x ∈ s βˆͺ t, f x) = (⨆x∈s, f x) βŠ” (⨆x∈t, f x) := by simp [supr_or, supr_sup_eq] theorem infi_union {f : Ξ± β†’ Ξ²} {s t : finset Ξ±} : (β¨… x ∈ s βˆͺ t, f x) = (β¨… x ∈ s, f x) βŠ“ (β¨… x ∈ t, f x) := @supr_union Ξ± (order_dual Ξ²) _ _ _ _ _ lemma supr_insert (a : Ξ±) (s : finset Ξ±) (t : Ξ± β†’ Ξ²) : (⨆ x ∈ insert a s, t x) = t a βŠ” (⨆ x ∈ s, t x) := by { rw insert_eq, simp only [supr_union, finset.supr_singleton] } lemma infi_insert (a : Ξ±) (s : finset Ξ±) (t : Ξ± β†’ Ξ²) : (β¨… x ∈ insert a s, t x) = t a βŠ“ (β¨… x ∈ s, t x) := @supr_insert Ξ± (order_dual Ξ²) _ _ _ _ _ lemma supr_finset_image {f : Ξ³ β†’ Ξ±} {g : Ξ± β†’ Ξ²} {s : finset Ξ³} : (⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) := by rw [← supr_coe, coe_image, supr_image, supr_coe] lemma sup_finset_image {Ξ² Ξ³ : Type*} [semilattice_sup Ξ²] [order_bot Ξ²] (f : Ξ³ β†’ Ξ±) (g : Ξ± β†’ Ξ²) (s : finset Ξ³) : (s.image f).sup g = s.sup (g ∘ f) := begin classical, induction s using finset.induction_on with a s' ha ih; simp * end lemma infi_finset_image {f : Ξ³ β†’ Ξ±} {g : Ξ± β†’ Ξ²} {s : finset Ξ³} : (β¨… x ∈ s.image f, g x) = (β¨… y ∈ s, g (f y)) := by rw [← infi_coe, coe_image, infi_image, infi_coe] lemma supr_insert_update {x : Ξ±} {t : finset Ξ±} (f : Ξ± β†’ Ξ²) {s : Ξ²} (hx : x βˆ‰ t) : (⨆ (i ∈ insert x t), function.update f x s i) = (s βŠ” ⨆ (i ∈ t), f i) := begin simp only [finset.supr_insert, update_same], rcongr i hi, apply update_noteq, rintro rfl, exact hx hi end lemma infi_insert_update {x : Ξ±} {t : finset Ξ±} (f : Ξ± β†’ Ξ²) {s : Ξ²} (hx : x βˆ‰ t) : (β¨… (i ∈ insert x t), update f x s i) = (s βŠ“ β¨… (i ∈ t), f i) := @supr_insert_update Ξ± (order_dual Ξ²) _ _ _ _ f _ hx lemma supr_bUnion (s : finset Ξ³) (t : Ξ³ β†’ finset Ξ±) (f : Ξ± β†’ Ξ²) : (⨆ y ∈ s.bUnion t, f y) = ⨆ (x ∈ s) (y ∈ t x), f y := by simp [@supr_comm _ Ξ±, supr_and] lemma infi_bUnion (s : finset Ξ³) (t : Ξ³ β†’ finset Ξ±) (f : Ξ± β†’ Ξ²) : (β¨… y ∈ s.bUnion t, f y) = β¨… (x ∈ s) (y ∈ t x), f y := @supr_bUnion _ (order_dual Ξ²) _ _ _ _ _ _ end lattice theorem set_bUnion_coe (s : finset Ξ±) (t : Ξ± β†’ set Ξ²) : (⋃ x ∈ (↑s : set Ξ±), t x) = ⋃ x ∈ s, t x := rfl theorem set_bInter_coe (s : finset Ξ±) (t : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ (↑s : set Ξ±), t x) = β‹‚ x ∈ s, t x := rfl theorem set_bUnion_singleton (a : Ξ±) (s : Ξ± β†’ set Ξ²) : (⋃ x ∈ ({a} : finset Ξ±), s x) = s a := supr_singleton a s theorem set_bInter_singleton (a : Ξ±) (s : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ ({a} : finset Ξ±), s x) = s a := infi_singleton a s @[simp] lemma set_bUnion_preimage_singleton (f : Ξ± β†’ Ξ²) (s : finset Ξ²) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := set.bUnion_preimage_singleton f s lemma set_bUnion_option_to_finset (o : option Ξ±) (f : Ξ± β†’ set Ξ²) : (⋃ x ∈ o.to_finset, f x) = ⋃ x ∈ o, f x := supr_option_to_finset o f lemma set_bInter_option_to_finset (o : option Ξ±) (f : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ o.to_finset, f x) = β‹‚ x ∈ o, f x := infi_option_to_finset o f lemma subset_set_bUnion_of_mem {s : finset Ξ±} {f : Ξ± β†’ set Ξ²} {x : Ξ±} (h : x ∈ s) : f x βŠ† ⋃ (y ∈ s), f y := show f x ≀ (⨆ y ∈ s, f y), from le_supr_of_le x $ le_supr _ h variables [decidable_eq Ξ±] lemma set_bUnion_union (s t : finset Ξ±) (u : Ξ± β†’ set Ξ²) : (⋃ x ∈ s βˆͺ t, u x) = (⋃ x ∈ s, u x) βˆͺ (⋃ x ∈ t, u x) := supr_union lemma set_bInter_inter (s t : finset Ξ±) (u : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ s βˆͺ t, u x) = (β‹‚ x ∈ s, u x) ∩ (β‹‚ x ∈ t, u x) := infi_union lemma set_bUnion_insert (a : Ξ±) (s : finset Ξ±) (t : Ξ± β†’ set Ξ²) : (⋃ x ∈ insert a s, t x) = t a βˆͺ (⋃ x ∈ s, t x) := supr_insert a s t lemma set_bInter_insert (a : Ξ±) (s : finset Ξ±) (t : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ insert a s, t x) = t a ∩ (β‹‚ x ∈ s, t x) := infi_insert a s t lemma set_bUnion_finset_image {f : Ξ³ β†’ Ξ±} {g : Ξ± β†’ set Ξ²} {s : finset Ξ³} : (⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) := supr_finset_image lemma set_bInter_finset_image {f : Ξ³ β†’ Ξ±} {g : Ξ± β†’ set Ξ²} {s : finset Ξ³} : (β‹‚ x ∈ s.image f, g x) = (β‹‚ y ∈ s, g (f y)) := infi_finset_image lemma set_bUnion_insert_update {x : Ξ±} {t : finset Ξ±} (f : Ξ± β†’ set Ξ²) {s : set Ξ²} (hx : x βˆ‰ t) : (⋃ (i ∈ insert x t), @update _ _ _ f x s i) = (s βˆͺ ⋃ (i ∈ t), f i) := supr_insert_update f hx lemma set_bInter_insert_update {x : Ξ±} {t : finset Ξ±} (f : Ξ± β†’ set Ξ²) {s : set Ξ²} (hx : x βˆ‰ t) : (β‹‚ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∩ β‹‚ (i ∈ t), f i) := infi_insert_update f hx lemma set_bUnion_bUnion (s : finset Ξ³) (t : Ξ³ β†’ finset Ξ±) (f : Ξ± β†’ set Ξ²) : (⋃ y ∈ s.bUnion t, f y) = ⋃ (x ∈ s) (y ∈ t x), f y := supr_bUnion s t f lemma set_bInter_bUnion (s : finset Ξ³) (t : Ξ³ β†’ finset Ξ±) (f : Ξ± β†’ set Ξ²) : (β‹‚ y ∈ s.bUnion t, f y) = β‹‚ (x ∈ s) (y ∈ t x), f y := infi_bUnion s t f end finset
b3620ef4eb67822b9a8f81eb03568916da6c7215
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Module/kernels.lean
1b53ef3cd63fd8b60de3030910d7188d5352d7d5
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,180
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.category.Module.epi_mono import category_theory.concrete_category.elementwise /-! # The concrete (co)kernels in the category of modules are (co)kernels in the categorical sense. -/ open category_theory open category_theory.limits universes u v namespace Module variables {R : Type u} [ring R] section variables {M N : Module.{v} R} (f : M ⟢ N) /-- The kernel cone induced by the concrete kernel. -/ def kernel_cone : kernel_fork f := kernel_fork.of_ΞΉ (as_hom f.ker.subtype) $ by tidy /-- The kernel of a linear map is a kernel in the categorical sense. -/ def kernel_is_limit : is_limit (kernel_cone f) := fork.is_limit.mk _ (Ξ» s, linear_map.cod_restrict f.ker (fork.ΞΉ s) (Ξ» c, linear_map.mem_ker.2 $ by { rw [←@function.comp_apply _ _ _ f (fork.ΞΉ s) c, ←coe_comp, fork.condition, has_zero_morphisms.comp_zero (fork.ΞΉ s) N], refl })) (Ξ» s, linear_map.subtype_comp_cod_restrict _ _ _) (Ξ» s m h, linear_map.ext $ Ξ» x, subtype.ext_iff_val.2 (by simpa [←h])) /-- The cokernel cocone induced by the projection onto the quotient. -/ def cokernel_cocone : cokernel_cofork f := cokernel_cofork.of_Ο€ (as_hom f.range.mkq) $ linear_map.range_mkq_comp _ /-- The projection onto the quotient is a cokernel in the categorical sense. -/ def cokernel_is_colimit : is_colimit (cokernel_cocone f) := cofork.is_colimit.mk _ (Ξ» s, f.range.liftq (cofork.Ο€ s) $ linear_map.range_le_ker_iff.2 $ cokernel_cofork.condition s) (Ξ» s, f.range.liftq_mkq (cofork.Ο€ s) _) (Ξ» s m h, begin haveI : epi (as_hom f.range.mkq) := (epi_iff_range_eq_top _).mpr (submodule.range_mkq _), apply (cancel_epi (as_hom f.range.mkq)).1, convert h, exact submodule.liftq_mkq _ _ _ end) end /-- The category of R-modules has kernels, given by the inclusion of the kernel submodule. -/ lemma has_kernels_Module : has_kernels (Module R) := ⟨λ X Y f, has_limit.mk ⟨_, kernel_is_limit f⟩⟩ /-- The category or R-modules has cokernels, given by the projection onto the quotient. -/ lemma has_cokernels_Module : has_cokernels (Module R) := ⟨λ X Y f, has_colimit.mk ⟨_, cokernel_is_colimit f⟩⟩ open_locale Module local attribute [instance] has_kernels_Module local attribute [instance] has_cokernels_Module variables {G H : Module.{v} R} (f : G ⟢ H) /-- The categorical kernel of a morphism in `Module` agrees with the usual module-theoretical kernel. -/ noncomputable def kernel_iso_ker {G H : Module.{v} R} (f : G ⟢ H) : kernel f β‰… Module.of R (f.ker) := limit.iso_limit_cone ⟨_, kernel_is_limit f⟩ -- We now show this isomorphism commutes with the inclusion of the kernel into the source. @[simp, elementwise] lemma kernel_iso_ker_inv_kernel_ΞΉ : (kernel_iso_ker f).inv ≫ kernel.ΞΉ f = f.ker.subtype := limit.iso_limit_cone_inv_Ο€ _ _ @[simp, elementwise] lemma kernel_iso_ker_hom_ker_subtype : (kernel_iso_ker f).hom ≫ f.ker.subtype = kernel.ΞΉ f := is_limit.cone_point_unique_up_to_iso_inv_comp _ (limit.is_limit _) walking_parallel_pair.zero /-- The categorical cokernel of a morphism in `Module` agrees with the usual module-theoretical quotient. -/ noncomputable def cokernel_iso_range_quotient {G H : Module.{v} R} (f : G ⟢ H) : cokernel f β‰… Module.of R (H β§Έ f.range) := colimit.iso_colimit_cocone ⟨_, cokernel_is_colimit f⟩ -- We now show this isomorphism commutes with the projection of target to the cokernel. @[simp, elementwise] lemma cokernel_Ο€_cokernel_iso_range_quotient_hom : cokernel.Ο€ f ≫ (cokernel_iso_range_quotient f).hom = f.range.mkq := by { convert colimit.iso_colimit_cocone_ΞΉ_hom _ _; refl, } @[simp, elementwise] lemma range_mkq_cokernel_iso_range_quotient_inv : β†Ώf.range.mkq ≫ (cokernel_iso_range_quotient f).inv = cokernel.Ο€ f := by { convert colimit.iso_colimit_cocone_ΞΉ_inv ⟨_, cokernel_is_colimit f⟩ _; refl, } lemma cokernel_Ο€_ext {M N : Module.{u} R} (f : M ⟢ N) {x y : N} (m : M) (w : x = y + f m) : cokernel.Ο€ f x = cokernel.Ο€ f y := by { subst w, simp, } end Module
293c740d9e7574d5f11d0d2146413ba90edddd45
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/smt_assert_define.lean
e1b0aa138067276d03eea5237764cf4f26b5db16
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
877
lean
open smt_tactic constant p : nat β†’ nat β†’ Prop constant f : nat β†’ nat axiom pf (a : nat) : p (f a) (f a) β†’ p a a lemma ex1 (a b c : nat) : a = b + 0 β†’ a + c = b + c := by using_smt $ do pr ← tactic.to_expr `(add_zero b), note `h pr, trace_state, return () lemma ex2(a b c : nat) : a = b β†’ p (f a) (f b) β†’ p a b := by using_smt $ do intros, t ← tactic.to_expr `(p (f a) (f a)), assert `h t, -- assert automatically closed the new goal trace_state, tactic.trace "-----", pr ← tactic.to_expr `(pf _ h), note `h2 pr, trace_state, return () def foo := 0 lemma fooex : foo = 0 := rfl lemma ex3 (a b c : nat) : a = b + foo β†’ a + c = b + c := begin [smt] intros, add_fact fooex, ematch end lemma ex4 (a b c : nat) : a = b β†’ p (f a) (f b) β†’ p a b := begin [smt] intros, assert h : p (f a) (f a), add_fact (pf _ h) end
19fd9bea198d18d2a7c5cd8c865026e9832010e6
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/category_theory/groupoid.lean
dbcfabfc6a99eadeec4fb283eb749295b0a73df5
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
945
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 u v class groupoid (obj : Type u) extends category.{u v} obj := (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+1 u} C abbreviation small_groupoid (C : Type u) : Type (u+1) := groupoid.{u u} C instance of_groupoid {C : Type u} [groupoid.{u v} C] {X Y : C} (f : X ⟢ Y) : is_iso f := { inv := groupoid.inv f } end category_theory
574cb7c92b43ec5b904399628e2a900f01c0b028
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/meta/expr.lean
92d1a340df755d1e858115774e3dcc7283cd4514
[]
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
10,088
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.string.defs import Mathlib.tactic.derive_inhabited import Mathlib.PostPort namespace Mathlib /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ namespace binder_info /-! ### Declarations about `binder_info` -/ protected instance inhabited : Inhabited binder_info := { default := default } /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info β†’ string Γ— string := sorry end binder_info namespace name /-! ### Declarations about `name` -/ /-- Find the largest prefix `n` of a `name` such that `f n β‰  none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name β†’ Option name) : name β†’ name := sorry /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ /-- Auxilliary definition for `pop_nth_prefix` -/ /-- Pops the top `n` prefixes from the given name. -/ /-- Pop the prefix of a name -/ /-- Auxilliary definition for `from_components` -/ /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : List string β†’ name := from_components_aux anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ /-- Append a string to the last component of a name -/ def append_suffix : name β†’ string β†’ name := sorry /-- The first component of a name, turning a number to a string -/ /-- Tests whether the first component of a name is `"_private"` -/ /-- Get the last component of a name, and convert it to a string. -/ /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name β†’ Bool) : name β†’ Bool := sorry /-- Appends `'` to the end of a name. -/ /-- `last_string n` returns the rightmost component of `n`, ignoring numeral components. For example, ``last_string `a.b.c.33`` will return `` `c ``. -/ def last_string : name β†’ string := sorry /-- Constructs a (non-simple) name from a string. Example: ``name.from_string "foo.bar" = `foo.bar`` -/ /-- In surface Lean, we can write anonymous Ξ  binders (i.e. binders where the argument is not named) using the function arrow notation: ```lean inductive test : Type | intro : unit β†’ test ``` After elaboration, however, every binder must have a name, so Lean generates one. In the example, the binder in the type of `intro` is anonymous, so Lean gives it the name `αΎ°`: ```lean test.intro : βˆ€ (αΎ° : unit), test ``` When there are multiple anonymous binders, they are named `αΎ°_1`, `αΎ°_2` etc. Thus, when we want to know whether the user named a binder, we can check whether the name follows this scheme. Note, however, that this is not reliable. When the user writes (for whatever reason) ```lean inductive test : Type | intro : βˆ€ (αΎ° : unit), test ``` we cannot tell that the binder was, in fact, named. The function `name.is_likely_generated_binder_name` checks if a name is of the form `αΎ°`, `αΎ°_1`, etc. -/ /-- Check whether a simple name was likely generated by Lean to name an anonymous binder. Such names are either `αΎ°` or `αΎ°_n` for some natural `n`. See note [likely generated binder names]. -/ /-- Check whether a name was likely generated by Lean to name an anonymous binder. Such names are either `αΎ°` or `αΎ°_n` for some natural `n`. See note [likely generated binder names]. -/ end name namespace level /-! ### Declarations about `level` -/ /-- Tests whether a universe level is non-zero for all assignments of its variables -/ /-- `l.fold_mvar f` folds a function `f : name β†’ Ξ± β†’ Ξ±` over each `n : name` appearing in a `level.mvar n` in `l`. -/ end level /-! ### Declarations about `binder` -/ /-- The type of binders containing a name, the binding info and the binding type -/ namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ end binder /-! ### Converting between expressions and numerals There are a number of ways to convert between expressions and numerals, depending on the input and output types and whether you want to infer the necessary type classes. See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`. -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ /-- `nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`. The `pexpr` does not hold any typing information: `to_expr ``((%%(nat.to_pexpr 5) : β„€))` will create a native integer numeral `(5 : β„€)`. -/ namespace expr /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`. -/ /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ /-- `is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ end expr /-! ### Declarations about `expr` -/ namespace expr /-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/ /-- Clean an expression by removing `id`s listed in `clean_ids`. -/ /-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/ /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ /-- Match a variable. -/ /-- Match a sort. -/ /-- Match a constant. -/ /-- Match a metavariable. -/ /-- Match a local constant. -/ /-- Match an application. -/ /-- Match an abstraction. -/ /-- Match a Ξ  type. -/ /-- Match a let. -/ /-- Match a macro. -/ /-- Tests whether an expression is a meta-variable. -/ /-- Tests whether an expression is a sort. -/ /-- Get the universe levels of a `const` expression -/ /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ /-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to `implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/ /-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants. -/ /-- Returns a list of all local constants in an expression (without duplicates). -/ /-- Returns the set of all local constants in an expression. -/ /-- Returns the unique names of all local constants in an expression. -/ /-- Returns a name_set of all constants in an expression. -/ /-- Returns a list of all meta-variables in an expression (without duplicates). -/ /-- Returns the set of all meta-variables in an expression. -/ /-- Returns a list of all universe meta-variables in an expression (without duplicates). -/ /-- Test `t` contains the specified subexpression `e`, or a metavariable. This represents the notion that `e` "may occur" in `t`, possibly after subsequent unification. -/ -- We can't use `t.has_meta_var` here, as that detects universe metavariables, too. /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true. -/ /-- Returns true if `e` contains a `sorry`. -/ /-- `app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`. -/ /-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/ -- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ /-- head-reduce a single let expression -/ /-- head-reduce all let expressions -/ /-- Instantiate lambdas in the second argument by expressions from the first. -/ /-- Repeatedly apply `expr.subst`. -/ /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. This is very similar to `expr.substs`, but this also reduces head let-expressions. -/ /-- Some declarations work with open expressions, i.e. an expr that has free variables.
ae573e7d4f3eed742af999674166fa71f80b2a75
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/clifford_algebra/even.lean
a374a0ead86937f0cc563e52a715167b2f41b13a
[ "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
10,322
lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.clifford_algebra.fold import linear_algebra.clifford_algebra.grading /-! # The universal property of the even subalgebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `clifford_algebra.even Q`: The even subalgebra of `clifford_algebra Q`. * `clifford_algebra.even_hom`: The type of bilinear maps that satisfy the universal property of the even subalgebra * `clifford_algebra.even.lift`: The universal property of the even subalgebra, which states that every bilinear map `f` with `f v v = Q v` and `f u v * f v w = Q v β€’ f u w` is in unique correspondence with an algebra morphism from `clifford_algebra.even Q`. ## Implementation notes The approach here is outlined in "Computing with the universal properties of the Clifford algebra and the even subalgebra" (to appear). The broad summary is that we have two tricks available to us for implementing complex recursors on top of `clifford_algebra.lift`: the first is to use morphisms as the output type, such as `A = module.End R N` which is how we obtained `clifford_algebra.foldr`; and the second is to use `N = (N', S)` where `N'` is the value we wish to compute, and `S` is some auxiliary state passed between one recursor invocation and the next. For the universal property of the even subalgebra, we apply a variant of the first trick again by choosing `S` to itself be a submodule of morphisms. -/ namespace clifford_algebra variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] variables {Q : quadratic_form R M} -- put this after `Q` since we want to talk about morphisms from `clifford_algebra Q` to `A` and -- that order is more natural variables {A B : Type*} [ring A] [ring B] [algebra R A] [algebra R B] open_locale direct_sum variables (Q) /-- The even submodule `clifford_algebra.even_odd Q 0` is also a subalgebra. -/ def even : subalgebra R (clifford_algebra Q) := (even_odd Q 0).to_subalgebra set_like.graded_monoid.one_mem (Ξ» x y hx hy, add_zero (0 : zmod 2) β–Έ set_like.graded_monoid.mul_mem hx hy) @[simp] lemma even_to_submodule : (even Q).to_submodule = even_odd Q 0 := rfl variables (A) /-- The type of bilinear maps which are accepted by `clifford_algebra.even.lift`. -/ @[ext] structure even_hom : Type (max u_2 u_3) := (bilin : M β†’β‚—[R] M β†’β‚—[R] A) (contract (m : M) : bilin m m = algebra_map R A (Q m)) (contract_mid (m₁ mβ‚‚ m₃ : M) : bilin m₁ mβ‚‚ * bilin mβ‚‚ m₃ = Q mβ‚‚ β€’ bilin m₁ m₃) variables {A Q} /-- Compose an `even_hom` with an `alg_hom` on the output. -/ @[simps] def even_hom.comprβ‚‚ (g : even_hom Q A) (f : A →ₐ[R] B) : even_hom Q B := { bilin := g.bilin.comprβ‚‚ f.to_linear_map, contract := Ξ» m, (f.congr_arg $ g.contract _).trans $ f.commutes _, contract_mid := Ξ» m₁ mβ‚‚ m₃, (f.map_mul _ _).symm.trans $ (f.congr_arg $ g.contract_mid _ _ _).trans $ f.map_smul _ _ } variables (Q) /-- The embedding of pairs of vectors into the even subalgebra, as a bilinear map. -/ @[simps bilin_apply_apply_coe] def even.ΞΉ : even_hom Q (even Q) := { bilin := linear_map.mkβ‚‚ R (Ξ» m₁ mβ‚‚, ⟨ι Q m₁ * ΞΉ Q mβ‚‚, ΞΉ_mul_ΞΉ_mem_even_odd_zero _ _ _⟩) (Ξ» _ _ _, by { simp only [linear_map.map_add, add_mul], refl }) (Ξ» _ _ _, by { simp only [linear_map.map_smul, smul_mul_assoc], refl }) (Ξ» _ _ _, by { simp only [linear_map.map_add, mul_add], refl }) (Ξ» _ _ _, by { simp only [linear_map.map_smul, mul_smul_comm], refl }), contract := Ξ» m, subtype.ext $ ΞΉ_sq_scalar Q m, contract_mid := Ξ» m₁ mβ‚‚ m₃, subtype.ext $ calc ΞΉ Q m₁ * ΞΉ Q mβ‚‚ * (ΞΉ Q mβ‚‚ * ΞΉ Q m₃) = ΞΉ Q m₁ * ((ΞΉ Q mβ‚‚ * ΞΉ Q mβ‚‚) * ΞΉ Q m₃) : by simp only [mul_assoc] ... = Q mβ‚‚ β€’ (ΞΉ Q m₁ * ΞΉ Q m₃) : by rw [algebra.smul_def, ΞΉ_sq_scalar, algebra.left_comm] } instance : inhabited (even_hom Q (even Q)) := ⟨even.ΞΉ Q⟩ variables (f : even_hom Q A) /-- Two algebra morphisms from the even subalgebra are equal if they agree on pairs of generators. See note [partially-applied ext lemmas]. -/ @[ext] lemma even.alg_hom_ext ⦃f g : even Q →ₐ[R] A⦄ (h : (even.ΞΉ Q).comprβ‚‚ f = (even.ΞΉ Q).comprβ‚‚ g) : f = g := begin rw even_hom.ext_iff at h, ext ⟨x, hx⟩, refine even_induction _ _ _ _ _ hx, { intro r, exact (f.commutes r).trans (g.commutes r).symm }, { intros x y hx hy ihx ihy, have := congr_arg2 (+) ihx ihy, exact (f.map_add _ _).trans (this.trans $ (g.map_add _ _).symm) }, { intros m₁ mβ‚‚ x hx ih, have := congr_arg2 (*) (linear_map.congr_fun (linear_map.congr_fun h m₁) mβ‚‚) ih, exact (f.map_mul _ _).trans (this.trans $ (g.map_mul _ _).symm) }, end variables {Q} namespace even.lift /-- An auxiliary submodule used to store the half-applied values of `f`. This is the span of elements `f'` such that `βˆƒ x mβ‚‚, βˆ€ m₁, f' m₁ = f m₁ mβ‚‚ * x`. -/ private def S : submodule R (M β†’β‚—[R] A) := submodule.span R {f' | βˆƒ x mβ‚‚, f' = linear_map.lcomp R _ (f.bilin.flip mβ‚‚) (linear_map.mul_right R x)} /-- An auxiliary bilinear map that is later passed into `clifford_algebra.fold`. Our desired result is stored in the `A` part of the accumulator, while auxiliary recursion state is stored in the `S f` part. -/ private def f_fold : M β†’β‚—[R] (A Γ— S f) β†’β‚—[R] (A Γ— S f) := linear_map.mkβ‚‚ R (Ξ» m acc, /- We could write this `snd` term in a point-free style as follows, but it wouldn't help as we don't have any prod or subtype combinators to deal with n-linear maps of this degree. ```lean (linear_map.lcomp R _ (algebra.lmul R A).to_linear_map.flip).comp $ (linear_map.llcomp R M A A).flip.comp f.flip : M β†’β‚—[R] A β†’β‚—[R] M β†’β‚—[R] A) ``` -/ (acc.2 m, ⟨(linear_map.mul_right R acc.1).comp (f.bilin.flip m), submodule.subset_span $ ⟨_, _, rfl⟩⟩)) (Ξ» m₁ mβ‚‚ a, prod.ext (linear_map.map_add _ m₁ mβ‚‚) (subtype.ext $ linear_map.ext $ Ξ» m₃, show f.bilin m₃ (m₁ + mβ‚‚) * a.1 = f.bilin m₃ m₁ * a.1 + f.bilin m₃ mβ‚‚ * a.1, by rw [map_add, add_mul])) (Ξ» c m a, prod.ext (linear_map.map_smul _ c m) (subtype.ext $ linear_map.ext $ Ξ» m₃, show f.bilin m₃ (c β€’ m) * a.1 = c β€’ (f.bilin m₃ m * a.1), by rw [linear_map.map_smul, smul_mul_assoc])) (Ξ» m a₁ aβ‚‚, prod.ext rfl (subtype.ext $ linear_map.ext $ Ξ» m₃, mul_add _ _ _)) (Ξ» c m a, prod.ext rfl (subtype.ext $ linear_map.ext $ Ξ» m₃, mul_smul_comm _ _ _)) @[simp] private lemma fst_f_fold_f_fold (m₁ mβ‚‚ : M) (x : A Γ— S f) : (f_fold f m₁ (f_fold f mβ‚‚ x)).fst = f.bilin m₁ mβ‚‚ * x.fst := rfl @[simp] private lemma snd_f_fold_f_fold (m₁ mβ‚‚ m₃ : M) (x : A Γ— S f) : ((f_fold f m₁ (f_fold f mβ‚‚ x)).snd : M β†’β‚—[R] A) m₃ = f.bilin m₃ m₁ * (x.snd : M β†’β‚—[R] A) mβ‚‚ := rfl private lemma f_fold_f_fold (m : M) (x : A Γ— S f) : f_fold f m (f_fold f m x) = Q m β€’ x := begin obtain ⟨a, ⟨g, hg⟩⟩ := x, ext : 2, { change f.bilin m m * a = Q m β€’ a, rw [algebra.smul_def, f.contract] }, { ext m₁, change f.bilin _ _ * g m = Q m β€’ g m₁, apply submodule.span_induction' _ _ _ _ hg, { rintros _ ⟨b, m₃, rfl⟩, change f.bilin _ _ * (f.bilin _ _ * b) = Q m β€’ (f.bilin _ _ * b), rw [←smul_mul_assoc, ←mul_assoc, f.contract_mid] }, { change f.bilin m₁ m * 0 = Q m β€’ 0, rw [mul_zero, smul_zero] }, { rintros x hx y hy ihx ihy, rw [linear_map.add_apply, linear_map.add_apply, mul_add, smul_add, ihx, ihy] }, { rintros x hx c ihx, rw [linear_map.smul_apply, linear_map.smul_apply, mul_smul_comm, ihx, smul_comm] } }, end /-- The final auxiliary construction for `clifford_algebra.even.lift`. This map is the forwards direction of that equivalence, but not in the fully-bundled form. -/ @[simps apply {attrs := []}] def aux (f : even_hom Q A) : clifford_algebra.even Q β†’β‚—[R] A := begin refine _ βˆ˜β‚— (even Q).val.to_linear_map, exact linear_map.fst _ _ _ βˆ˜β‚— foldr Q (f_fold f) (f_fold_f_fold f) (1, 0), end @[simp] lemma aux_one : aux f 1 = 1 := (congr_arg prod.fst (foldr_one _ _ _ _)) @[simp] lemma aux_ΞΉ (m₁ mβ‚‚ : M) : aux f ((even.ΞΉ Q).bilin m₁ mβ‚‚) = f.bilin m₁ mβ‚‚ := (congr_arg prod.fst (foldr_mul _ _ _ _ _ _)).trans begin rw [foldr_ΞΉ, foldr_ΞΉ], exact mul_one _, end @[simp] lemma aux_algebra_map (r) (hr) : aux f ⟨algebra_map R _ r, hr⟩ = algebra_map R _ r := (congr_arg prod.fst (foldr_algebra_map _ _ _ _ _)).trans (algebra.algebra_map_eq_smul_one r).symm @[simp] lemma aux_mul (x y : even Q) : aux f (x * y) = aux f x * aux f y := begin cases x, cases y, refine (congr_arg prod.fst (foldr_mul _ _ _ _ _ _)).trans _, dsimp only, refine even_induction Q _ _ _ _ x_property, { intros r, rw [foldr_algebra_map, aux_algebra_map], exact (algebra.smul_def r _), }, { intros x y hx hy ihx ihy, rw [linear_map.map_add, prod.fst_add, ihx, ihy, ←add_mul, ←linear_map.map_add], refl, }, { rintros m₁ mβ‚‚ x (hx : x ∈ even Q) ih, rw [aux_apply, foldr_mul, foldr_mul, foldr_ΞΉ, foldr_ΞΉ, fst_f_fold_f_fold, ih, ←mul_assoc, subtype.coe_mk, foldr_mul, foldr_mul, foldr_ΞΉ, foldr_ΞΉ, fst_f_fold_f_fold], refl } end end even.lift open even.lift variables (Q) {A} /-- Every algebra morphism from the even subalgebra is in one-to-one correspondence with a bilinear map that sends duplicate arguments to the quadratic form, and contracts across multiplication. -/ @[simps symm_apply_bilin] def even.lift : even_hom Q A ≃ (clifford_algebra.even Q →ₐ[R] A) := { to_fun := Ξ» f, alg_hom.of_linear_map (aux f) (aux_one f) (aux_mul f), inv_fun := Ξ» F, (even.ΞΉ Q).comprβ‚‚ F, left_inv := Ξ» f, even_hom.ext _ _ $ linear_map.extβ‚‚ $ even.lift.aux_ΞΉ f, right_inv := Ξ» F, even.alg_hom_ext Q $ even_hom.ext _ _ $ linear_map.extβ‚‚ $ even.lift.aux_ΞΉ _ } @[simp] lemma even.lift_ΞΉ (f : even_hom Q A) (m₁ mβ‚‚ : M) : even.lift Q f ((even.ΞΉ Q).bilin m₁ mβ‚‚) = f.bilin m₁ mβ‚‚ := even.lift.aux_ΞΉ _ _ _ end clifford_algebra
53d6f41128a92e5ab552e38ce6edc71f44b2d985
26ac254ecb57ffcb886ff709cf018390161a9225
/src/tactic/linarith/verification.lean
d585abc59cd920253f9f8e7c4893fc1445b139d3
[ "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
7,205
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import tactic.linarith.elimination import tactic.linarith.parsing /-! # Deriving a proof of false `linarith` uses an untrusted oracle to produce a certificate of unsatisfiability. It needs to do some proof reconstruction work to turn this into a proof term. This file implements the reconstruction. ## Main declarations The public facing declaration in this file is `prove_false_by_linarith`. -/ namespace linarith open ineq tactic native /-! ### Auxiliary functions for assembling proofs -/ /-- `mul_expr n e` creates a `pexpr` representing `n*e`. When elaborated, the coefficient will be a native numeral of the same type as `e`. -/ meta def mul_expr (n : β„•) (e : expr) : pexpr := if n = 1 then ``(%%e) else ``(%%(nat.to_pexpr n) * %%e) private meta def add_exprs_aux : pexpr β†’ list pexpr β†’ pexpr | p [] := p | p [a] := ``(%%p + %%a) | p (h::t) := add_exprs_aux ``(%%p + %%h) t /-- `add_exprs l` creates a `pexpr` representing the sum of the elements of `l`, associated left. If `l` is empty, it will be the `pexpr` 0. Otherwise, it does not include 0 in the sum. -/ meta def add_exprs : list pexpr β†’ pexpr | [] := ``(0) | (h::t) := add_exprs_aux h t /-- If our goal is to add together two inequalities `t1 R1 0` and `t2 R2 0`, `ineq_const_nm R1 R2` produces the strength of the inequality in the sum `R`, along with the name of a lemma to apply in order to conclude `t1 + t2 R 0`. -/ meta def ineq_const_nm : ineq β†’ ineq β†’ (name Γ— ineq) | eq eq := (``eq_of_eq_of_eq, eq) | eq le := (``le_of_eq_of_le, le) | eq lt := (``lt_of_eq_of_lt, lt) | le eq := (``le_of_le_of_eq, le) | le le := (`add_nonpos, le) | le lt := (`add_neg_of_nonpos_of_neg, lt) | lt eq := (``lt_of_lt_of_eq, lt) | lt le := (`add_neg_of_neg_of_nonpos, lt) | lt lt := (`add_neg, lt) /-- `mk_lt_zero_pf_aux c pf npf coeff` assumes that `pf` is a proof of `t1 R1 0` and `npf` is a proof of `t2 R2 0`. It uses `mk_single_comp_zero_pf` to prove `t1 + coeff*t2 R 0`, and returns `R` along with this proof. -/ meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : β„•) : tactic (ineq Γ— expr) := do (iq, h') ← mk_single_comp_zero_pf coeff npf, let (nm, niq) := ineq_const_nm c iq, prod.mk niq <$> mk_app nm [pf, h'] /-- `mk_lt_zero_pf coeffs pfs` takes a list of proofs of the form `tα΅’ Rα΅’ 0`, paired with coefficients `cα΅’`. It produces a proof that `βˆ‘cα΅’ * tα΅’ R 0`, where `R` is as strong as possible. -/ meta def mk_lt_zero_pf : list (expr Γ— β„•) β†’ tactic expr | [] := fail "no linear hypotheses found" | [(h, c)] := prod.snd <$> mk_single_comp_zero_pf c h | ((h, c)::t) := do (iq, h') ← mk_single_comp_zero_pf c h, prod.snd <$> t.mfoldl (Ξ» pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.1 ce.2) (iq, h') /-- If `prf` is a proof of `t R s`, `term_of_ineq_prf prf` returns `t`. -/ meta def term_of_ineq_prf (prf : expr) : tactic expr := prod.fst <$> (infer_type prf >>= get_rel_sides) /-- If `prf` is a proof of `t R s`, `ineq_prf_tp prf` returns the type of `t`. -/ meta def ineq_prf_tp (prf : expr) : tactic expr := term_of_ineq_prf prf >>= infer_type /-- `mk_neg_one_lt_zero_pf tp` returns a proof of `-1 < 0`, where the numerals are natively of type `tp`. -/ meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr := do zero_lt_one ← mk_mapp `zero_lt_one [tp, none], mk_app `neg_neg_of_pos [zero_lt_one] /-- If `e` is a proof that `t = 0`, `mk_neg_eq_zero_pf e` returns a proof that `-t = 0`. -/ meta def mk_neg_eq_zero_pf (e : expr) : tactic expr := to_expr ``(neg_eq_zero.mpr %%e) /-- `prove_eq_zero_using tac e` tries to use `tac` to construct a proof of `e = 0`. -/ meta def prove_eq_zero_using (tac : tactic unit) (e : expr) : tactic expr := do tgt ← to_expr ``(%%e = 0), prod.snd <$> solve_aux tgt (tac >> done) /-- `add_neg_eq_pfs l` inspects the list of proofs `l` for proofs of the form `t = 0`. For each such proof, it adds a proof of `-t = 0` to the list. -/ meta def add_neg_eq_pfs : list expr β†’ tactic (list expr) | [] := return [] | (h::t) := do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h, match iq with | ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl | _ := list.cons h <$> add_neg_eq_pfs t end /-! #### The main method -/ /-- `prove_false_by_linarith` is the main workhorse of `linarith`. Given a list `l` of proofs of `tα΅’ Rα΅’ 0`, it tries to derive a contradiction from `l` and use this to produce a proof of `false`. An oracle is used to search for a certificate of unsatisfiability. In the current implementation, this is the Fourier Motzkin elimination routine in `elimination.lean`, but other oracles could easily be swapped in. The returned certificate is a map `m` from hypothesis indices to natural number coefficients. If our set of hypotheses has the form `{tα΅’ Rα΅’ 0}`, then the elimination process should have guaranteed that 1.\ `βˆ‘ (m i)*tα΅’ = 0`, with at least one `i` such that `m i > 0` and `Rα΅’` is `<`. We have also that 2.\ `βˆ‘ (m i)*tα΅’ < 0`, since for each `i`, `(m i)*tα΅’ ≀ 0` and at least one is strictly negative. So we conclude a contradiction `0 < 0`. It remains to produce proofs of (1) and (2). (1) is verified by calling the `discharger` tactic of the `linarith_config` object, which is typically `ring`. We prove (2) by folding over the set of hypotheses. -/ meta def prove_false_by_linarith (cfg : linarith_config) : list expr β†’ tactic expr | [] := fail "no args to linarith" | l@(h::t) := do -- for the elimination to work properly, we must add a proof of `-1 < 0` to the list, -- along with negated equality proofs. l' ← add_neg_eq_pfs l, hz ← ineq_prf_tp h >>= mk_neg_one_lt_zero_pf, let inputs := hz::l', -- perform the elimination and fail if no contradiction is found. (comps, max_var) ← linear_forms_and_max_var cfg.transparency inputs, certificate ← fourier_motzkin.produce_certificate comps max_var | fail "linarith failed to find a contradiction", linarith_trace "linarith has found a contradiction", let enum_inputs := inputs.enum, -- construct a list pairing nonzero coeffs with the proof of their corresponding comparison let zip := enum_inputs.filter_map $ Ξ» ⟨n, e⟩, prod.mk e <$> certificate.find n, mls ← zip.mmap (Ξ» ⟨e, n⟩, do e ← term_of_ineq_prf e, return (mul_expr n e)), -- `sm` is the sum of input terms, scaled to cancel out all variables. sm ← to_expr $ add_exprs mls, pformat! "The expression\n {sm}\nshould be both 0 and negative" >>= linarith_trace, -- we prove that `sm = 0`, typically with `ring`. sm_eq_zero ← prove_eq_zero_using cfg.discharger sm, linarith_trace "We have proved that it is zero", -- we also prove that `sm < 0`. sm_lt_zero ← mk_lt_zero_pf zip, linarith_trace "We have proved that it is negative", -- this is a contradiction. pftp ← infer_type sm_lt_zero, (_, nep, _) ← rewrite_core sm_eq_zero pftp, pf' ← mk_eq_mp nep sm_lt_zero, mk_app `lt_irrefl [pf'] end linarith
149af6353f9482e90d49445785c969f73b77ca5f
54ce0561cebde424526f41d45f490ed56be2bd0c
/src/game/ch2_Natural_Numbers/3_Multiplication.lean
04b9640003be5422d93f305f5318c6c710c19542
[]
no_license
melembroucarlitos/Tao_Analysis-LEAN
cf7b3298d317891a09e4bf21cfe7c7ffcb57b9a9
3f4fc7e090d96b6cef64896492fba4bef124794b
refs/heads/master
1,692,952,385,694
1,636,287,522,000
1,636,287,522,000
400,630,166
3
0
null
1,635,910,807,000
1,630,096,823,000
Lean
UTF-8
Lean
false
false
165
lean
-- Level name : Multiplication /- # Hey yall ## This is just to a placeholder to make sure all is working these are some words and these are some other words -/
fbb633e2534d6ce73ef37fcd8c312bcf2e16c269
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/set_theory/ordinal.lean
99474128c78e2245309fcb32aa5afe942bf37f38
[ "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
138,353
lean
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Ordinal arithmetic. Ordinals are defined as equivalences of well-ordered sets by order isomorphism. -/ import order.order_iso set_theory.cardinal data.sum noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} {t : Ξ³ β†’ Ξ³ β†’ Prop} /-- If `r` is a relation on `Ξ±` and `s` in a relation on `Ξ²`, then `f : r β‰Όi s` is an order embedding whose range is an initial segment. That is, whenever `b < f a` in `Ξ²` then `b` is in the range of `f`. -/ structure initial_seg {Ξ± Ξ² : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) extends r β‰Όo s := (init : βˆ€ a b, s b (to_order_embedding a) β†’ βˆƒ a', to_order_embedding a' = b) local infix ` β‰Όi `:25 := initial_seg namespace initial_seg instance : has_coe (r β‰Όi s) (r β‰Όo s) := ⟨initial_seg.to_order_embedding⟩ @[simp] theorem coe_fn_mk (f : r β‰Όo s) (o) : (@initial_seg.mk _ _ r s f o : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_fn_to_order_embedding (f : r β‰Όi s) : (f.to_order_embedding : Ξ± β†’ Ξ²) = f := rfl theorem coe_coe_fn (f : r β‰Όi s) : ((f : r β‰Όo s) : Ξ± β†’ Ξ²) = f := rfl theorem init' (f : r β‰Όi s) {a : Ξ±} {b : Ξ²} : s b (f a) β†’ βˆƒ a', f a' = b := f.init _ _ theorem init_iff (f : r β‰Όi s) {a : Ξ±} {b : Ξ²} : s b (f a) ↔ βˆƒ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r β‰Όo s).ord'.2 (e.symm β–Έ h)⟩, Ξ» ⟨a', e, h⟩, e β–Έ (f : r β‰Όo s).ord'.1 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃o s) : r β‰Όi s := ⟨f, Ξ» a b h, ⟨f.symm b, order_iso.apply_symm_apply f _⟩⟩ /-- The identity function shows that `β‰Όi` is reflexive -/ @[refl] protected def refl (r : Ξ± β†’ Ξ± β†’ Prop) : r β‰Όi r := ⟨order_embedding.refl _, Ξ» a b h, ⟨_, rfl⟩⟩ /-- Composition of functions shows that `β‰Όi` is transitive -/ @[trans] protected def trans (f : r β‰Όi s) (g : s β‰Όi t) : r β‰Όi t := ⟨f.1.trans g.1, Ξ» a c h, begin simp at h ⊒, rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.1.ord'.2 h, rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem of_iso_apply (f : r ≃o s) (x : Ξ±) : of_iso f x = f x := rfl @[simp] theorem refl_apply (x : Ξ±) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply (f : r β‰Όi s) (g : s β‰Όi t) (a : Ξ±) : (f.trans g) a = g (f a) := rfl theorem unique_of_extensional [is_extensional Ξ² s] : well_founded r β†’ subsingleton (r β‰Όi s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : Ξ± β†’ Ξ²) = g, { cases f, cases g, congr, exact order_embedding.eq_of_to_fun_eq this }, funext a, have := h a, induction this with a H IH, refine @is_extensional.ext _ s _ _ _ (Ξ» x, ⟨λ h, _, Ξ» h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r β‰Όo s).ord'.1 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r β‰Όo s).ord'.1 h' } end⟩ instance [is_well_order Ξ² s] : subsingleton (r β‰Όi s) := ⟨λ a, @subsingleton.elim _ (unique_of_extensional (@order_embedding.well_founded _ _ r s a (is_well_order.wf s))) a⟩ protected theorem eq [is_well_order Ξ² s] (f g : r β‰Όi s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order Ξ± r] (f : r β‰Όi s) (g : s β‰Όi r) : left_inverse g f := initial_seg.eq (f.trans g) (initial_seg.refl _) /-- If we have order embeddings between `Ξ±` and `Ξ²` whose images are initial segments, and Ξ² is a well-order then `Ξ±` and `Ξ²` are order-isomorphic. -/ def antisymm [is_well_order Ξ² s] (f : r β‰Όi s) (g : s β‰Όi r) : r ≃o s := by haveI := f.to_order_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.ord⟩ @[simp] theorem antisymm_to_fun [is_well_order Ξ² s] (f : r β‰Όi s) (g : s β‰Όi r) : (antisymm f g : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem antisymm_symm [is_well_order Ξ± r] [is_well_order Ξ² s] (f : r β‰Όi s) (g : s β‰Όi r) : (antisymm f g).symm = antisymm g f := order_iso.eq_of_to_fun_eq rfl theorem eq_or_principal [is_well_order Ξ² s] (f : r β‰Όi s) : surjective f ∨ βˆƒ b, βˆ€ x, s x b ↔ βˆƒ y, f y = x := or_iff_not_imp_right.2 $ Ξ» h b, acc.rec_on ((is_well_order.wf s).apply b) $ Ξ» x H IH, not_forall_not.1 $ Ξ» hn, h ⟨x, Ξ» y, ⟨(IH _), Ξ» ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (Ξ» hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set Ξ²) (f : r β‰Όi s) (H : βˆ€ a, f a ∈ p) : r β‰Όi subrel s p := ⟨order_embedding.cod_restrict p f H, Ξ» a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r β‰Όi s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl def le_add (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) : r β‰Όi sum.lex r s := ⟨⟨⟨sum.inl, Ξ» _ _, sum.inl.inj⟩, Ξ» a b, sum.lex_inl_inl.symm⟩, Ξ» a b, by cases b; [exact Ξ» _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩ @[simp] theorem le_add_apply (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg structure principal_seg {Ξ± Ξ² : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) extends r β‰Όo s := (top : Ξ²) (down : βˆ€ b, s b top ↔ βˆƒ a, to_order_embedding a = b) local infix ` β‰Ίi `:25 := principal_seg namespace principal_seg instance : has_coe (r β‰Ίi s) (r β‰Όo s) := ⟨principal_seg.to_order_embedding⟩ @[simp] theorem coe_fn_mk (f : r β‰Όo s) (t o) : (@principal_seg.mk _ _ r s f t o : Ξ± β†’ Ξ²) = f := rfl @[simp] theorem coe_fn_to_order_embedding (f : r β‰Ίi s) : (f.to_order_embedding : Ξ± β†’ Ξ²) = f := rfl theorem coe_coe_fn (f : r β‰Ίi s) : ((f : r β‰Όo s) : Ξ± β†’ Ξ²) = f := rfl theorem down' (f : r β‰Ίi s) {b : Ξ²} : s b f.top ↔ βˆƒ a, f a = b := f.down _ theorem lt_top (f : r β‰Ίi s) (a : Ξ±) : s (f a) f.top := f.down'.2 ⟨_, rfl⟩ theorem init [is_trans Ξ² s] (f : r β‰Ίi s) {a : Ξ±} {b : Ξ²} (h : s b (f a)) : βˆƒ a', f a' = b := f.down'.1 $ trans h $ f.lt_top _ instance has_coe_initial_seg [is_trans Ξ² s] : has_coe (r β‰Ίi s) (r β‰Όi s) := ⟨λ f, ⟨f.to_order_embedding, Ξ» a b, f.init⟩⟩ theorem coe_coe_fn' [is_trans Ξ² s] (f : r β‰Ίi s) : ((f : r β‰Όi s) : Ξ± β†’ Ξ²) = f := rfl theorem init_iff [is_trans Ξ² s] (f : r β‰Ίi s) {a : Ξ±} {b : Ξ²} : s b (f a) ↔ βˆƒ a', f a' = b ∧ r a' a := initial_seg.init_iff f theorem irrefl (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (f : r β‰Ίi r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end def lt_le (f : r β‰Ίi s) (g : s β‰Όi t) : r β‰Ίi t := ⟨@order_embedding.trans _ _ _ r s t f g, g f.top, Ξ» a, by simp only [g.init_iff, f.down', exists_and_distrib_left.symm, exists_swap, order_embedding.trans_apply, exists_eq_right']; refl⟩ @[simp] theorem lt_le_apply [is_trans Ξ² s] [is_trans Ξ³ t] (f : r β‰Ίi s) (g : s β‰Όi t) (a : Ξ±) : (f.lt_le g) a = g (f a) := order_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top (f : r β‰Ίi s) (g : s β‰Όi t) : (f.lt_le g).top = g f.top := rfl @[trans] protected def trans [is_trans Ξ³ t] (f : r β‰Ίi s) (g : s β‰Ίi t) : r β‰Ίi t := lt_le f g @[simp] theorem trans_apply [is_trans Ξ² s] [is_trans Ξ³ t] (f : r β‰Ίi s) (g : s β‰Ίi t) (a : Ξ±) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans Ξ² s] [is_trans Ξ³ t] (f : r β‰Ίi s) (g : s β‰Ίi t) : (f.trans g).top = g f.top := rfl def equiv_lt (f : r ≃o s) (g : s β‰Ίi t) : r β‰Ίi t := ⟨@order_embedding.trans _ _ _ r s t f g, g.top, Ξ» c, by simp only [g.down', coe_fn_coe_base, order_embedding.trans_apply]; exact ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, order_iso.apply_symm_apply, order_iso.coe_coe_fn]⟩, Ξ» ⟨a, h⟩, ⟨f a, h⟩⟩⟩ def lt_equiv {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} {t : Ξ³ β†’ Ξ³ β†’ Prop} (f : principal_seg r s) (g : s ≃o t) : principal_seg r t := ⟨@order_embedding.trans _ _ _ r s t f g, g f.top, begin intro x, rw [←g.right_inv x], simp only [order_iso.to_equiv_to_fun, coe_fn_coe_base, order_embedding.trans_apply], rw [←order_iso.ord'' g, f.down', exists_congr], intro y, exact ⟨congr_arg g, Ξ» h, g.to_equiv.bijective.1 h⟩ end⟩ @[simp] theorem equiv_lt_apply [is_trans Ξ³ t] (f : r ≃o s) (g : s β‰Ίi t) (a : Ξ±) : (equiv_lt f g) a = g (f a) := order_embedding.trans_apply _ _ _ @[simp] theorem equiv_lt_top (f : r ≃o s) (g : s β‰Ίi t) : (equiv_lt f g).top = g.top := rfl instance [is_well_order Ξ² s] : subsingleton (r β‰Ίi s) := ⟨λ f g, begin have ef : (f : Ξ± β†’ Ξ²) = g, { show ((f : r β‰Όi s) : Ξ± β†’ Ξ²) = g, rw @subsingleton.elim _ _ (f : r β‰Όi s) g, refl }, have et : f.top = g.top, { refine @is_extensional.ext _ s _ _ _ (Ξ» x, _), simp only [f.down, g.down, ef, coe_fn_to_order_embedding] }, cases f, cases g, have := order_embedding.eq_of_to_fun_eq ef; congr' end⟩ theorem top_eq [is_well_order Ξ³ t] (e : r ≃o s) (f : r β‰Ίi t) (g : s β‰Ίi t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl lemma top_lt_top {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} {t : Ξ³ β†’ Ξ³ β†’ Prop} [is_trans Ξ² s] [is_well_order Ξ³ t] (f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top := by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top } /-- Any element of a well order yields a principal segment -/ def of_element {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (a : Ξ±) : subrel r {b | r b a} β‰Ίi r := ⟨subrel.order_embedding _ _, a, Ξ» b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, Ξ» ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (a : Ξ±) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) (a : Ξ±) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set Ξ²) (f : r β‰Ίi s) (H : βˆ€ a, f a ∈ p) (Hβ‚‚ : f.top ∈ p) : r β‰Ίi subrel s p := ⟨order_embedding.cod_restrict p f H, ⟨f.top, Hβ‚‚βŸ©, Ξ» ⟨b, h⟩, f.down'.trans $ exists_congr $ Ξ» a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r β‰Ίi s) (H Hβ‚‚ a) : cod_restrict p f H Hβ‚‚ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r β‰Ίi s) (H Hβ‚‚) : (cod_restrict p f H Hβ‚‚).top = ⟨f.top, Hβ‚‚βŸ© := rfl end principal_seg def initial_seg.lt_or_eq [is_well_order Ξ² s] (f : r β‰Όi s) : (r β‰Ίi s) βŠ• (r ≃o s) := if h : surjective f then sum.inr (order_iso.of_surjective f h) else have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ @[simp] theorem initial_seg.lt_or_eq_apply_left [is_well_order Ξ² s] (f : r β‰Όi s) {g} (h : f.lt_or_eq = sum.inl g) (a : Ξ±) : g a = f a := begin unfold initial_seg.lt_or_eq at h, by_cases sj : surjective f, { rw dif_pos sj at h, cases h }, { rw dif_neg sj at h, cases h, refl } end @[simp] theorem initial_seg.lt_or_eq_apply_right [is_well_order Ξ² s] (f : r β‰Όi s) {g} (h : f.lt_or_eq = sum.inr g) (a : Ξ±) : g a = f a := begin unfold initial_seg.lt_or_eq at h, by_cases sj : surjective f, {rw dif_pos sj at h, cases h, refl}, {rw dif_neg sj at h, cases h} end def initial_seg.le_lt [is_well_order Ξ² s] [is_trans Ξ³ t] (f : r β‰Όi s) (g : s β‰Ίi t) : r β‰Ίi t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order Ξ² s] [is_trans Ξ³ t] (f : r β‰Όi s) (g : s β‰Ίi t) (a : Ξ±) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left h] }, { simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right h] } end namespace order_embedding def collapse_F [is_well_order Ξ² s] (f : r β‰Όo s) : Ξ  a, {b // Β¬ s (f a) b} := (order_embedding.well_founded f $ is_well_order.wf s).fix $ Ξ» a IH, begin let S := {b | βˆ€ a h, s (IH a h).1 b}, have : f a ∈ S, from Ξ» a' h, ((trichotomous _ _) .resolve_left $ Ξ» h', (IH a' h).2 $ trans (f.ord'.1 h) h') .resolve_left $ Ξ» h', (IH a' h).2 $ h' β–Έ f.ord'.1 h, exact ⟨(is_well_order.wf s).min S (set.ne_empty_of_mem this), (is_well_order.wf s).not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order Ξ² s] (f : r β‰Όo s) {a : Ξ±} : βˆ€ {a'}, r a' a β†’ s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | βˆ€ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order Ξ² s] (f : r β‰Όo s) (a : Ξ±) {b} (h : βˆ€ a' (h : r a' a), s (collapse_F f a').1 b) : Β¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | βˆ€ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding. -/ def collapse [is_well_order Ξ² s] (f : r β‰Όo s) : r β‰Όi s := by haveI := order_embedding.is_well_order f; exact ⟨order_embedding.of_monotone (Ξ» a, (collapse_F f a).1) (Ξ» a b, collapse_F.lt f), Ξ» a b, acc.rec_on ((is_well_order.wf s).apply b) (Ξ» b H IH a h, begin let S := {a | Β¬ s (collapse_F f a).1 b}, have : S β‰  βˆ… := set.ne_empty_of_mem (asymm h), existsi (is_well_order.wf r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_order.wf r).min_mem S this }, { refine collapse_F.not_lt f _ (Ξ» a' h', _), by_contradiction hn, exact (is_well_order.wf r).not_lt_min S this hn h' } end) a⟩ theorem collapse_apply [is_well_order Ξ² s] (f : r β‰Όo s) (a) : collapse f a = (collapse_F f a).1 := rfl end order_embedding section well_ordering_thm parameter {Οƒ : Type u} open function theorem nonempty_embedding_to_cardinal : nonempty (Οƒ β†ͺ cardinal.{u}) := embedding.total.resolve_left $ Ξ» ⟨⟨f, hf⟩⟩, let g : Οƒ β†’ cardinal.{u} := inv_fun f in let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in have g x ≀ sum g, from le_sum.{u u} g x, not_le_of_gt (by rw hx; exact cantor _) this /-- An embedding of any type to the set of cardinals. -/ def embedding_to_cardinal : Οƒ β†ͺ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal /-- The relation whose existence is given by the well-ordering theorem -/ def well_ordering_rel : Οƒ β†’ Οƒ β†’ Prop := embedding_to_cardinal ⁻¹'o (<) instance well_ordering_rel.is_well_order : is_well_order Οƒ well_ordering_rel := (order_embedding.preimage _ _).is_well_order end well_ordering_thm structure Well_order : Type (u+1) := (Ξ± : Type u) (r : Ξ± β†’ Ξ± β†’ Prop) (wo : is_well_order Ξ± r) attribute [instance] Well_order.wo instance ordinal.is_equivalent : setoid Well_order := { r := Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃o s), iseqv := ⟨λ⟨α, r, _⟩, ⟨order_iso.refl _⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨eβ‚βŸ© ⟨eβ‚‚βŸ©, ⟨e₁.trans eβ‚‚βŸ©βŸ© } /-- `ordinal.{u}` is the type of well orders in `Type u`, quotient by order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent namespace ordinal /-- The order type of a well order is an ordinal. -/ def type (r : Ξ± β†’ Ξ± β†’ Prop) [wo : is_well_order Ξ± r] : ordinal := ⟦⟨α, r, wo⟩⟧ /-- The order type of an element inside a well order. -/ def typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (a : Ξ±) : ordinal := type (subrel r {b | r b a}) theorem type_def (r : Ξ± β†’ Ξ± β†’ Prop) [wo : is_well_order Ξ± r] : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl @[simp] theorem type_def' (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {wo} : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl theorem type_eq {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] : type r = type s ↔ nonempty (r ≃o s) := quotient.eq @[simp] lemma type_out (o : ordinal) : type o.out.r = o := by { refine eq.trans _ (by rw [←quotient.out_eq o]), cases quotient.out o, refl } @[elab_as_eliminator] theorem induction_on {C : ordinal β†’ Prop} (o : ordinal) (H : βˆ€ Ξ± r [is_well_order Ξ± r], C (type r)) : C o := quot.induction_on o $ Ξ» ⟨α, r, wo⟩, @H Ξ± r wo /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≀ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ protected def le (a b : ordinal) : Prop := quotient.lift_onβ‚‚ a b (Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r β‰Όi s)) $ Ξ» βŸ¨Ξ±β‚, r₁, oβ‚βŸ© βŸ¨Ξ±β‚‚, rβ‚‚, oβ‚‚βŸ© βŸ¨Ξ²β‚, s₁, pβ‚βŸ© βŸ¨Ξ²β‚‚, sβ‚‚, pβ‚‚βŸ© ⟨f⟩ ⟨g⟩, propext ⟨ Ξ» ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, Ξ» ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩ instance : has_le ordinal := ⟨ordinal.le⟩ theorem type_le {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] : type r ≀ type s ↔ nonempty (r β‰Όi s) := iff.rfl theorem type_le' {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] : type r ≀ type s ↔ nonempty (r β‰Όo s) := ⟨λ ⟨f⟩, ⟨f⟩, Ξ» ⟨f⟩, ⟨f.collapse⟩⟩ /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ def lt (a b : ordinal) : Prop := quotient.lift_onβ‚‚ a b (Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r β‰Ίi s)) $ Ξ» βŸ¨Ξ±β‚, r₁, oβ‚βŸ© βŸ¨Ξ±β‚‚, rβ‚‚, oβ‚‚βŸ© βŸ¨Ξ²β‚, s₁, pβ‚βŸ© βŸ¨Ξ²β‚‚, sβ‚‚, pβ‚‚βŸ© ⟨f⟩ ⟨g⟩, by exactI propext ⟨ Ξ» ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, Ξ» ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩ instance : has_lt ordinal := ⟨ordinal.lt⟩ @[simp] theorem type_lt {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] : type r < type s ↔ nonempty (r β‰Ίi s) := iff.rfl instance : partial_order ordinal := { le := (≀), lt := (<), le_refl := quot.ind $ by exact Ξ» ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := Ξ» a b c, quotient.induction_on₃ a b c $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := Ξ» a b, quotient.induction_onβ‚‚ a b $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, Ξ» ⟨g⟩, (f.lt_le g).irrefl _⟩, Ξ» ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (Ξ» g, ⟨g⟩) (Ξ» g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := Ξ» x b, show x ≀ b β†’ b ≀ x β†’ x = b, from quotient.induction_onβ‚‚ x b $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨hβ‚βŸ© ⟨hβ‚‚βŸ©, by exactI quot.sound ⟨initial_seg.antisymm h₁ hβ‚‚βŸ© } def initial_seg_out {Ξ± Ξ² : ordinal} (h : Ξ± ≀ Ξ²) : initial_seg Ξ±.out.r Ξ².out.r := begin rw [←quotient.out_eq Ξ±, ←quotient.out_eq Ξ²] at h, revert h, cases quotient.out Ξ±, cases quotient.out Ξ², exact classical.choice end def principal_seg_out {Ξ± Ξ² : ordinal} (h : Ξ± < Ξ²) : principal_seg Ξ±.out.r Ξ².out.r := begin rw [←quotient.out_eq Ξ±, ←quotient.out_eq Ξ²] at h, revert h, cases quotient.out Ξ±, cases quotient.out Ξ², exact classical.choice end def order_iso_out {Ξ± Ξ² : ordinal} (h : Ξ± = Ξ²) : order_iso Ξ±.out.r Ξ².out.r := begin rw [←quotient.out_eq Ξ±, ←quotient.out_eq Ξ²] at h, revert h, cases quotient.out Ξ±, cases quotient.out Ξ², exact classical.choice ∘ quotient.exact end theorem typein_lt_type (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (a : Ξ±) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ @[simp] theorem typein_top {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : r β‰Ίi s) : typein s f.top = type r := eq.symm $ quot.sound ⟨order_iso.of_surjective (order_embedding.cod_restrict _ f f.lt_top) (Ξ» ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : r β‰Όi s) (a : Ξ±) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨order_iso.of_surjective (order_embedding.cod_restrict _ ((subrel.order_embedding _ _).trans f) (Ξ» ⟨x, h⟩, by rw [order_embedding.trans_apply]; exact f.to_order_embedding.ord'.1 h)) (Ξ» ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_order_embedding.ord'.2 h⟩, subtype.eq $ order_embedding.trans_apply _ _ _⟩)⟩ @[simp] theorem typein_lt_typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {a b : Ξ±} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, exact this }, rw ← this, exact f.top.2 end, Ξ» h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (Ξ» x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {o} (h : o < type r) : βˆƒ a, typein r a = o := induction_on o (Ξ» Ξ² s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h lemma injective_typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : injective (typein r) := injective_of_increasing r (<) (typein r) (Ξ» x y, (typein_lt_typein r).2) theorem typein_inj (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {a b} : typein r a = typein r b ↔ a = b := injective.eq_iff (injective_typein r) /-- `enum r o h` is the `o`-th element of `Ξ±` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `Ξ±`. -/ def enum (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (o) : o < type r β†’ Ξ± := quot.rec_on o (Ξ» ⟨β, s, _⟩ h, (classical.choice h).top) $ Ξ» ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (Ξ» (Hβ‚‚ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : βˆ€ {o e} (H : o < type r), @@eq.rec (Ξ» (o : ordinal), o < type r β†’ Ξ±) (Ξ» (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this Hβ‚‚).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice Hβ‚‚)) end theorem enum_type {Ξ± Ξ²} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : s β‰Ίi r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (order_iso.refl _) _ _ @[simp] theorem enum_typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (a : Ξ±) {h : typein r a < type r} : enum r (typein r a) h = a := enum_type (principal_seg.of_element r a) @[simp] theorem typein_enum (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; rw enum_typein def typein_iso (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : r ≃o subrel (<) (< type r) := ⟨⟨λ x, ⟨typein r x, typein_lt_type r x⟩, Ξ» x, enum r x.1 x.2, Ξ» y, enum_typein r y, Ξ» ⟨y, hy⟩, subtype.eq (typein_enum r hy)⟩, Ξ» a b, (typein_lt_typein r).symm⟩ theorem enum_lt {r : Ξ± β†’ Ξ± β†’ Prop} [is_well_order Ξ± r] {o₁ oβ‚‚ : ordinal} (h₁ : o₁ < type r) (hβ‚‚ : oβ‚‚ < type r) : r (enum r o₁ h₁) (enum r oβ‚‚ hβ‚‚) ↔ o₁ < oβ‚‚ := by rw [← typein_lt_typein r, typein_enum, typein_enum] lemma order_iso_enum' {Ξ± Ξ² : Type u} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : order_iso r s) (o : ordinal) : βˆ€(hr : o < type r) (hs : o < type s), f (enum r o hr) = enum s o hs := begin refine induction_on o _, rintros Ξ³ t wo ⟨g⟩ ⟨h⟩, resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl end lemma order_iso_enum {Ξ± Ξ² : Type u} {r : Ξ± β†’ Ξ± β†’ Prop} {s : Ξ² β†’ Ξ² β†’ Prop} [is_well_order Ξ± r] [is_well_order Ξ² s] (f : order_iso r s) (o : ordinal) (hr : o < type r) : f (enum r o hr) = enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) := order_iso_enum' _ _ _ _ theorem wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ Ξ» Ξ± r wo, by exactI suffices βˆ€ a, acc (<) (typein r a), from ⟨_, Ξ» o h, let ⟨a, e⟩ := typein_surj r h in e β–Έ this a⟩, Ξ» a, acc.rec_on (wo.wf.apply a) $ Ξ» x H IH, ⟨_, Ξ» o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), wf⟩ /-- The cardinal of an ordinal is the cardinal of any set with that order type. -/ def card (o : ordinal) : cardinal := quot.lift_on o (Ξ» ⟨α, r, _⟩, mk Ξ±) $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩ @[simp] theorem card_type (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : card (type r) = mk Ξ± := rfl lemma card_typein {r : Ξ± β†’ Ξ± β†’ Prop} [wo : is_well_order Ξ± r] (x : Ξ±) : mk {y // r y x} = (typein r x).card := rfl theorem card_le_card {o₁ oβ‚‚ : ordinal} : o₁ ≀ oβ‚‚ β†’ card o₁ ≀ card oβ‚‚ := induction_on o₁ $ Ξ» Ξ± r _, induction_on oβ‚‚ $ Ξ» Ξ² s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ instance : has_zero ordinal := ⟨⟦⟨pempty, empty_relation, by apply_instance⟩⟧⟩ theorem zero_eq_type_empty : 0 = @type empty empty_relation _ := quotient.sound ⟨⟨empty_equiv_pempty.symm, Ξ» _ _, iff.rfl⟩⟩ @[simp] theorem card_zero : card 0 = 0 := rfl theorem zero_le (o : ordinal) : 0 ≀ o := induction_on o $ Ξ» Ξ± r _, ⟨⟨⟨embedding.of_not_nonempty $ Ξ» ⟨a⟩, a.elim, Ξ» a, a.elim⟩, Ξ» a, a.elim⟩⟩ @[simp] theorem le_zero {o : ordinal} : o ≀ 0 ↔ o = 0 := by simp only [le_antisymm_iff, zero_le, and_true] theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o β‰  0 := by simp only [lt_iff_le_and_ne, zero_le, true_and, ne.def, eq_comm] instance : has_one ordinal := ⟨⟦⟨punit, empty_relation, by apply_instance⟩⟧⟩ theorem one_eq_type_unit : 1 = @type unit empty_relation _ := quotient.sound ⟨⟨punit_equiv_punit, Ξ» _ _, iff.rfl⟩⟩ @[simp] theorem card_one : card 1 = 1 := rfl instance : has_add ordinal.{u} := ⟨λo₁ oβ‚‚, quotient.lift_onβ‚‚ o₁ oβ‚‚ (Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α βŠ• Ξ², sum.lex r s, by exactI sum.lex.is_well_order⟩⟧ : Well_order β†’ Well_order β†’ ordinal) $ Ξ» βŸ¨Ξ±β‚, r₁, oβ‚βŸ© βŸ¨Ξ±β‚‚, rβ‚‚, oβ‚‚βŸ© βŸ¨Ξ²β‚, s₁, pβ‚βŸ© βŸ¨Ξ²β‚‚, sβ‚‚, pβ‚‚βŸ© ⟨f⟩ ⟨g⟩, quot.sound ⟨order_iso.sum_lex_congr f g⟩⟩ @[simp] theorem type_add {Ξ± Ξ² : Type u} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) [is_well_order Ξ± r] [is_well_order Ξ² s] : type r + type s = type (sum.lex r s) := rfl /-- The ordinal successor is the smallest ordinal larger than `o`. It is defined as `o + 1`. -/ def succ (o : ordinal) : ordinal := o + 1 theorem succ_eq_add_one (o) : succ o = o + 1 := rfl theorem lt_succ_self (o : ordinal.{u}) : o < succ o := induction_on o $ Ξ» Ξ± r _, ⟨⟨⟨⟨λ x, sum.inl x, Ξ» _ _, sum.inl.inj⟩, Ξ» _ _, sum.lex_inl_inl.symm⟩, sum.inr punit.star, Ξ» b, sum.rec_on b (Ξ» x, ⟨λ _, ⟨x, rfl⟩, Ξ» _, sum.lex.sep _ _ _ _⟩) (Ξ» x, sum.lex_inr_inr.trans ⟨false.elim, Ξ» ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩ theorem succ_pos (o : ordinal) : 0 < succ o := lt_of_le_of_lt (zero_le _) (lt_succ_self _) theorem succ_ne_zero (o : ordinal) : succ o β‰  0 := ne_of_gt $ succ_pos o theorem succ_le {a b : ordinal} : succ a ≀ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), induction_on a $ Ξ» Ξ± r hr, induction_on b $ Ξ» Ξ² s hs ⟨⟨f, t, hf⟩⟩, begin refine ⟨⟨@order_embedding.of_monotone (Ξ± βŠ• punit) Ξ² _ _ (@sum.lex.is_well_order _ _ _ _ hr _).1.1 (@is_asymm_of_is_trans_of_is_irrefl _ _ hs.1.2.2 hs.1.2.1) (sum.rec _ _) (Ξ» a b, _), Ξ» a b, _⟩⟩, { exact f }, { exact Ξ» _, t }, { rcases a with a|_; rcases b with b|_, { simpa only [sum.lex_inl_inl] using f.ord'.1 }, { intro _, rw hf, exact ⟨_, rfl⟩ }, { exact false.elim ∘ sum.lex_inr_inl }, { exact false.elim ∘ sum.lex_inr_inr.1 } }, { rcases a with a|_, { intro h, have := @principal_seg.init _ _ _ _ hs.1.2.2 ⟨f, t, hf⟩ _ _ h, cases this with w h, exact ⟨sum.inl w, h⟩ }, { intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } } end⟩ @[simp] theorem card_add (o₁ oβ‚‚ : ordinal) : card (o₁ + oβ‚‚) = card o₁ + card oβ‚‚ := induction_on o₁ $ Ξ» Ξ± r _, induction_on oβ‚‚ $ Ξ» Ξ² s _, rfl @[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 := by simp only [succ, card_add, card_one] @[simp] theorem card_nat (n : β„•) : card.{u} n = n := by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]] theorem nat_cast_succ (n : β„•) : (succ n : ordinal) = n.succ := rfl instance : add_monoid ordinal.{u} := { add := (+), zero := 0, zero_add := Ξ» o, induction_on o $ Ξ» Ξ± r _, eq.symm $ quotient.sound ⟨⟨(pempty_sum Ξ±).symm, Ξ» a b, sum.lex_inr_inr.symm⟩⟩, add_zero := Ξ» o, induction_on o $ Ξ» Ξ± r _, eq.symm $ quotient.sound ⟨⟨(sum_pempty Ξ±).symm, Ξ» a b, sum.lex_inl_inl.symm⟩⟩, add_assoc := Ξ» o₁ oβ‚‚ o₃, quotient.induction_on₃ o₁ oβ‚‚ o₃ $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨sum_assoc _ _ _, Ξ» a b, begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp only [sum_assoc_apply_in1, sum_assoc_apply_in2, sum_assoc_apply_in3, sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ } theorem add_succ (o₁ oβ‚‚ : ordinal) : o₁ + succ oβ‚‚ = succ (o₁ + oβ‚‚) := (add_assoc _ _ _).symm @[simp] theorem succ_zero : succ 0 = 1 := zero_add _ theorem one_le_iff_pos {o : ordinal} : 1 ≀ o ↔ 0 < o := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {o : ordinal} : 1 ≀ o ↔ o β‰  0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem add_le_add_left {a b : ordinal} : a ≀ b β†’ βˆ€ c, c + a ≀ c + b := induction_on a $ Ξ» α₁ r₁ _, induction_on b $ Ξ» Ξ±β‚‚ rβ‚‚ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ Ξ» Ξ² s _, ⟨⟨⟨(embedding.refl _).sum_congr f, Ξ» a b, match a, b with | sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm | sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep | sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl | sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm end⟩, Ξ» a b H, match a, b, H with | _, sum.inl b, _ := ⟨sum.inl b, rfl⟩ | sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim | sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in ⟨sum.inr w, congr_arg sum.inr h⟩ end⟩⟩ theorem le_add_right (a b : ordinal) : a ≀ a + b := by simpa only [add_zero] using add_le_add_left (zero_le b) a theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≀ a + c ↔ b ≀ c := ⟨induction_on a $ Ξ» Ξ± r hr, induction_on b $ Ξ» β₁ s₁ hs₁, induction_on c $ Ξ» Ξ²β‚‚ sβ‚‚ hsβ‚‚ ⟨f⟩, ⟨ have fl : βˆ€ a, f (sum.inl a) = sum.inl a := Ξ» a, by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply] using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hsβ‚‚) ((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r sβ‚‚) a, have βˆ€ b, {b' // f (sum.inr b) = sum.inr b'}, begin intro b, cases e : f (sum.inr b), { rw ← fl at e, have := f.inj e, contradiction }, { exact ⟨_, rfl⟩ } end, let g (b) := (this b).1 in have fr : βˆ€ b, f (sum.inr b) = sum.inr (g b), from Ξ» b, (this b).2, ⟨⟨⟨g, Ξ» x y h, by injection f.inj (by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩, Ξ» a b, by simpa only [sum.lex_inr_inr, fr, order_embedding.coe_fn_to_embedding, initial_seg.coe_fn_to_order_embedding, function.embedding.coe_fn_mk] using @order_embedding.ord _ _ _ _ f.to_order_embedding (sum.inr a) (sum.inr b)⟩, Ξ» a b H, begin rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩, { rw fl at h, cases h }, { rw fr at h, exact ⟨a', sum.inr.inj h⟩ } end⟩⟩, Ξ» h, add_le_add_left h _⟩ theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c := by simp only [le_antisymm_iff, add_le_add_iff_left] /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. -/ def lift (o : ordinal.{u}) : ordinal.{max u v} := quotient.lift_on o (Ξ» ⟨α, r, wo⟩, @type _ _ (@order_embedding.is_well_order _ _ (@equiv.ulift.{u v} Ξ± ⁻¹'o r) r (order_iso.preimage equiv.ulift.{u v} r) wo)) $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(order_iso.preimage equiv.ulift r).trans $ f.trans (order_iso.preimage equiv.ulift s).symm⟩ theorem lift_type {Ξ±} (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : βˆƒ wo', lift (type r) = @type _ (@equiv.ulift.{u v} Ξ± ⁻¹'o r) wo' := ⟨_, rfl⟩ theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ Ξ» a, induction_on a $ Ξ» Ξ± r _, quotient.sound ⟨(order_iso.preimage equiv.ulift r).trans (order_iso.preimage equiv.ulift r).symm⟩ theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ Ξ» Ξ± r _, quotient.sound ⟨order_iso.preimage equiv.ulift r⟩ @[simp] theorem lift_id : βˆ€ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : ordinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := induction_on a $ Ξ» Ξ± r _, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans $ (order_iso.preimage equiv.ulift _).trans (order_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {Ξ± : Type u} {Ξ² : Type v} {r s} [is_well_order Ξ± r] [is_well_order Ξ² s] : lift.{u (max v w)} (type r) ≀ lift.{v (max u w)} (type s) ↔ nonempty (r β‰Όi s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (order_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (order_iso.preimage equiv.ulift s))⟩, Ξ» ⟨f⟩, ⟨(initial_seg.of_iso (order_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (order_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {Ξ± : Type u} {Ξ² : Type v} {r s} [is_well_order Ξ± r] [is_well_order Ξ² s] : lift.{u (max v w)} (type r) = lift.{v (max u w)} (type s) ↔ nonempty (r ≃o s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(order_iso.preimage equiv.ulift r).symm.trans $ f.trans (order_iso.preimage equiv.ulift s)⟩, Ξ» ⟨f⟩, ⟨(order_iso.preimage equiv.ulift r).trans $ f.trans (order_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {Ξ± : Type u} {Ξ² : Type v} {r s} [is_well_order Ξ± r] [is_well_order Ξ² s] : lift.{u (max v w)} (type r) < lift.{v (max u w)} (type s) ↔ nonempty (r β‰Ίi s) := by haveI := @order_embedding.is_well_order _ _ (@equiv.ulift.{u (max v w)} Ξ± ⁻¹'o r) r (order_iso.preimage equiv.ulift.{u (max v w)} r) _; haveI := @order_embedding.is_well_order _ _ (@equiv.ulift.{v (max u w)} Ξ² ⁻¹'o s) s (order_iso.preimage equiv.ulift.{v (max u w)} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (order_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (order_iso.preimage equiv.ulift s))⟩, Ξ» ⟨f⟩, ⟨(f.equiv_lt (order_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (order_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≀ lift b ↔ a ≀ b := induction_on a $ Ξ» Ξ± r _, induction_on b $ Ξ» Ξ² s _, by rw ← lift_umax; exactI lift_type_le @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp only [le_antisymm_iff, lift_le] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp only [lt_iff_le_not_le, lift_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans ⟨pempty_equiv_pempty, Ξ» a b, iff.rfl⟩⟩ theorem zero_eq_lift_type_empty : 0 = lift.{0 u} (@type empty empty_relation _) := by rw [← zero_eq_type_empty, lift_zero] @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans ⟨punit_equiv_punit, Ξ» a b, iff.rfl⟩⟩ theorem one_eq_lift_type_unit : 1 = lift.{0 u} (@type unit empty_relation _) := by rw [← one_eq_type_unit, lift_one] @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_onβ‚‚ a b $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans (order_iso.sum_lex_congr (order_iso.preimage equiv.ulift _) (order_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := by unfold succ; simp only [lift_add, lift_one] @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ Ξ» Ξ± r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≀ a.lift) : βˆƒ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in quotient.induction_on c (Ξ» Ξ±, induction_on b $ Ξ» Ξ² s _ e', begin resetI, rw [mk_def, card_type, ← cardinal.lift_id'.{(max u v) u} (mk Ξ²), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := order_iso.preimage f s, haveI := g.to_order_embedding.is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≀ lift a) : βˆƒ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≀ lift a ↔ βˆƒ a', lift a' = b ∧ a' ≀ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm β–Έ h⟩, Ξ» ⟨a', e, h⟩, e β–Έ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ βˆƒ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm β–Έ h⟩, Ξ» ⟨a', e, h⟩, e β–Έ lift_lt.2 h⟩ /-- `Ο‰` is the first infinite ordinal, defined as the order type of `β„•`. -/ def omega : ordinal.{u} := lift $ @type β„• (<) _ localized "notation `Ο‰` := ordinal.omega.{0}" in ordinal theorem card_omega : card omega = cardinal.omega := rfl @[simp] theorem lift_omega : lift omega = omega := lift_lift _ theorem add_le_add_right {a b : ordinal} : a ≀ b β†’ βˆ€ c, a + c ≀ b + c := induction_on a $ Ξ» α₁ r₁ hr₁, induction_on b $ Ξ» Ξ±β‚‚ rβ‚‚ hrβ‚‚ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ Ξ» Ξ² s hs, (@type_le' _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr₁ hs) (@sum.lex.is_well_order _ _ _ _ hrβ‚‚ hs)).2 ⟨⟨embedding.sum_congr f (embedding.refl _), Ξ» a b, begin split; intro H, { cases H; constructor; [rwa ← fo, assumption] }, { cases a with a a; cases b with b b; cases H; constructor; [rwa fo, assumption] } end⟩⟩ theorem le_add_left (a b : ordinal) : a ≀ b + a := by simpa only [zero_add] using add_le_add_right (zero_le b) a theorem le_total (a b : ordinal) : a ≀ b ∨ b ≀ a := match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl hβ‚‚ := induction_on a (Ξ» α₁ r₁ _, induction_on b $ Ξ» Ξ±β‚‚ rβ‚‚ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ rβ‚‚) g.top f.top with h|h|h; [exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)] end) h₁ hβ‚‚ end instance : decidable_linear_order ordinal := { le_total := le_total, decidable_le := classical.dec_rel _, ..ordinal.partial_order } @[simp] lemma typein_le_typein (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {x x' : Ξ±} : typein r x ≀ typein r x' ↔ Β¬r x' x := by rw [←not_lt, typein_lt_typein] lemma enum_le_enum (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] {o o' : ordinal} (ho : o < type r) (ho' : o' < type r) : Β¬r (enum r o' ho') (enum r o ho) ↔ o ≀ o' := by rw [←@not_lt _ _ o' o, enum_lt ho'] theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≀ b := by rw [← not_le, succ_le, not_lt] theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c := by rw [← not_le, ← not_le, add_le_add_iff_left] theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b β†’ a < c := lt_imp_lt_of_le_imp_le (Ξ» h, add_le_add_right h _) @[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b := by rw [lt_succ, succ_le] @[simp] theorem succ_le_succ {a b : ordinal} : succ a ≀ succ b ↔ a ≀ b := le_iff_le_iff_lt_iff_lt.2 succ_lt_succ theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b := by simp only [le_antisymm_iff, succ_le_succ] theorem add_le_add_iff_right {a b : ordinal} (n : β„•) : a + n ≀ b + n ↔ a ≀ b := by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero], rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]] theorem add_right_cancel {a b : ordinal} (n : β„•) : a + n = b + n ↔ a = b := by simp only [le_antisymm_iff, add_le_add_iff_right] @[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 := ⟨induction_on o $ Ξ» Ξ± r _ h, begin refine le_antisymm (le_of_not_lt $ Ξ» hn, ne_zero_iff_nonempty.2 _ h) (zero_le _), rw [← succ_le, succ_zero] at hn, cases hn with f, exact ⟨f punit.star⟩ end, Ξ» e, by simp only [e, card_zero]⟩ @[simp] theorem type_ne_zero_iff_nonempty [is_well_order Ξ± r] : type r β‰  0 ↔ nonempty Ξ± := (not_congr (@card_eq_zero (type r))).symm.trans ne_zero_iff_nonempty @[simp] theorem type_eq_zero_iff_empty [is_well_order Ξ± r] : type r = 0 ↔ Β¬ nonempty Ξ± := (not_iff_comm.1 type_ne_zero_iff_nonempty).symm instance : zero_ne_one_class ordinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ type_ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem zero_lt_one : (0 : ordinal) < 1 := lt_iff_le_and_ne.2 ⟨zero_le _, zero_ne_one⟩ /-- The ordinal predecessor of `o` is `o'` if `o = succ o'`, and `o` otherwise. -/ def pred (o : ordinal.{u}) : ordinal.{u} := if h : βˆƒ a, o = succ a then classical.some h else o @[simp] theorem pred_succ (o) : pred (succ o) = o := by have h : βˆƒ a, succ o = succ a := ⟨_, rfl⟩; simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm theorem pred_le_self (o) : pred o ≀ o := if h : βˆƒ a, o = succ a then let ⟨a, e⟩ := h in by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _) else by rw [pred, dif_neg h] theorem pred_eq_iff_not_succ {o} : pred o = o ↔ Β¬ βˆƒ a, o = succ a := ⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e, Ξ» h, dif_neg h⟩ theorem pred_lt_iff_is_succ {o} : pred o < o ↔ βˆƒ a, o = succ a := iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le]) (iff_not_comm.1 pred_eq_iff_not_succ).symm theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ βˆƒ a, o = succ a := ⟨λ e, ⟨_, e.symm⟩, Ξ» ⟨a, e⟩, by simp only [e, pred_succ]⟩ theorem succ_lt_of_not_succ {o} (h : Β¬ βˆƒ a, o = succ a) {b} : succ b < o ↔ b < o := ⟨lt_trans (lt_succ_self _), Ξ» l, lt_of_le_of_ne (succ_le.2 l) (Ξ» e, h ⟨_, e.symm⟩)⟩ theorem lt_pred {a b} : a < pred b ↔ succ a < b := if h : βˆƒ a, b = succ a then let ⟨c, e⟩ := h in by rw [e, pred_succ, succ_lt_succ] else by simp only [pred, dif_neg h, succ_lt_of_not_succ h] theorem pred_le {a b} : pred a ≀ b ↔ a ≀ succ b := le_iff_le_iff_lt_iff_lt.2 lt_pred @[simp] theorem lift_is_succ {o} : (βˆƒ a, lift o = succ a) ↔ (βˆƒ a, o = succ a) := ⟨λ ⟨a, h⟩, let ⟨b, e⟩ := lift_down $ show a ≀ lift o, from le_of_lt $ h.symm β–Έ lt_succ_self _ in ⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩, Ξ» ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩ @[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) := if h : βˆƒ a, o = succ a then by cases h with a e; simp only [e, pred_succ, lift_succ] else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)] /-- A limit ordinal is an ordinal which is not zero and not a successor. -/ def is_limit (o : ordinal) : Prop := o β‰  0 ∧ βˆ€ a < o, succ a < o theorem not_zero_is_limit : Β¬ is_limit 0 | ⟨h, _⟩ := h rfl theorem not_succ_is_limit (o) : Β¬ is_limit (succ o) | ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _)) theorem not_succ_of_is_limit {o} (h : is_limit o) : Β¬ βˆƒ a, o = succ a | ⟨a, e⟩ := not_succ_is_limit a (e β–Έ h) theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o := ⟨lt_trans (lt_succ_self _), h.2 _⟩ theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≀ succ a ↔ o ≀ a := le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h theorem limit_le {o} (h : is_limit o) {a} : o ≀ a ↔ βˆ€ x < o, x ≀ a := ⟨λ h x l, le_trans (le_of_lt l) h, Ξ» H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ Ξ» hn, not_lt_of_le (H _ hn) (lt_succ_self _)⟩ theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ βˆƒ x < o, a < x := by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a) @[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o := and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0) ⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h), Ξ» H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in by rw [← e, ← lift_succ, lift_lt]; rw [← e, lift_lt] at h; exact H a' h⟩ theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o := lt_of_le_of_ne (zero_le _) h.1.symm theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o := by simpa only [succ_zero] using h.2 _ h.pos theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : βˆ€ n : β„•, (n : ordinal) < o | 0 := h.pos | (n+1) := h.2 _ (is_limit.nat_lt n) theorem zero_or_succ_or_limit (o : ordinal) : o = 0 ∨ (βˆƒ a, o = succ a) ∨ is_limit o := if o0 : o = 0 then or.inl o0 else if h : βˆƒ a, o = succ a then or.inr (or.inl h) else or.inr $ or.inr ⟨o0, Ξ» a, (succ_lt_of_not_succ h).2⟩ instance : is_well_order ordinal (<) := ⟨wf⟩ @[elab_as_eliminator] def limit_rec_on {C : ordinal β†’ Sort*} (o : ordinal) (H₁ : C 0) (Hβ‚‚ : βˆ€ o, C o β†’ C (succ o)) (H₃ : βˆ€ o, is_limit o β†’ (βˆ€ o' < o, C o') β†’ C o) : C o := wf.fix (Ξ» o IH, if o0 : o = 0 then by rw o0; exact H₁ else if h : βˆƒ a, o = succ a then by rw ← succ_pred_iff_is_succ.2 h; exact Hβ‚‚ _ (IH _ $ pred_lt_iff_is_succ.2 h) else H₃ _ ⟨o0, Ξ» a, (succ_lt_of_not_succ h).2⟩ IH) o @[simp] theorem limit_rec_on_zero {C} (H₁ Hβ‚‚ H₃) : @limit_rec_on C 0 H₁ Hβ‚‚ H₃ = H₁ := by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl @[simp] theorem limit_rec_on_succ {C} (o H₁ Hβ‚‚ H₃) : @limit_rec_on C (succ o) H₁ Hβ‚‚ H₃ = Hβ‚‚ o (@limit_rec_on C o H₁ Hβ‚‚ H₃) := begin have h : βˆƒ a, succ o = succ a := ⟨_, rfl⟩, rw [limit_rec_on, well_founded.fix_eq, dif_neg (succ_ne_zero o), dif_pos h], generalize : limit_rec_on._proof_2 (succ o) h = hβ‚‚, generalize : limit_rec_on._proof_3 (succ o) h = h₃, revert hβ‚‚ h₃, generalize e : pred (succ o) = o', intros, rw pred_succ at e, subst o', refl end @[simp] theorem limit_rec_on_limit {C} (o H₁ Hβ‚‚ H₃ h) : @limit_rec_on C o H₁ Hβ‚‚ H₃ = H₃ o h (Ξ» x h, @limit_rec_on C x H₁ Hβ‚‚ H₃) := by rw [limit_rec_on, well_founded.fix_eq, dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl lemma has_succ_of_is_limit {Ξ±} {r : Ξ± β†’ Ξ± β†’ Prop} [wo : is_well_order Ξ± r] (h : (type r).is_limit) (x : Ξ±) : βˆƒy, r x y := begin use enum r (typein r x).succ (h.2 _ (typein_lt_type r x)), convert (enum_lt (typein_lt_type r x) _).mpr (lt_succ_self _), rw [enum_typein] end lemma type_subrel_lt (o : ordinal.{u}) : type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u u+1} o := begin refine quotient.induction_on o _, rintro ⟨α, r, wo⟩, resetI, apply quotient.sound, constructor, symmetry, refine (order_iso.preimage equiv.ulift r).trans (typein_iso r) end lemma mk_initial_seg (o : ordinal.{u}) : #{o' : ordinal | o' < o} = cardinal.lift.{u u+1} o.card := by rw [lift_card, ←type_subrel_lt, card_type] /-- A normal ordinal function is a strictly increasing function which is order-continuous. -/ def is_normal (f : ordinal β†’ ordinal) : Prop := (βˆ€ o, f o < f (succ o)) ∧ βˆ€ o, is_limit o β†’ βˆ€ a, f o ≀ a ↔ βˆ€ b < o, f b ≀ a theorem is_normal.limit_le {f} (H : is_normal f) : βˆ€ {o}, is_limit o β†’ βˆ€ {a}, f o ≀ a ↔ βˆ€ b < o, f b ≀ a := H.2 theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} : a < f o ↔ βˆƒ b < o, a < f b := not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b := strict_mono.lt_iff_lt $ Ξ» a b, limit_rec_on b (not.elim (not_lt_of_le $ zero_le _)) (Ξ» b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim (Ξ» h, lt_trans (IH h) (H.1 _)) (Ξ» e, e β–Έ H.1 _)) (Ξ» b l IH h, lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 (le_refl _) _ (l.2 _ h))) theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≀ f b ↔ a ≀ b := le_iff_le_iff_lt_iff_lt.2 H.lt_iff theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b := by simp only [le_antisymm_iff, H.le_iff] theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≀ f a := limit_rec_on a (zero_le _) (Ξ» a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _)) (Ξ» a l IH, (limit_le l).2 $ Ξ» b h, le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h) theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal β†’ Prop) (p0 : βˆƒ x, p x) (S) (Hβ‚‚ : βˆ€ o, S ≀ o ↔ βˆ€ a, p a β†’ a ≀ o) {o} : f S ≀ o ↔ βˆ€ a, p a β†’ f a ≀ o := ⟨λ h a pa, le_trans (H.le_iff.2 ((Hβ‚‚ _).1 (le_refl _) _ pa)) h, Ξ» h, begin revert Hβ‚‚, apply limit_rec_on S, { intro Hβ‚‚, cases p0 with x px, have := le_zero.1 ((Hβ‚‚ _).1 (zero_le _) _ px), rw this at px, exact h _ px }, { intros S _ Hβ‚‚, rcases not_ball.1 (mt (Hβ‚‚ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, hβ‚‚βŸ©, exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 hβ‚‚) (h _ h₁) }, { intros S L _ Hβ‚‚, apply (H.2 _ L _).2, intros a h', rcases not_ball.1 (mt (Hβ‚‚ a).2 (not_le.2 h')) with ⟨b, h₁, hβ‚‚βŸ©, exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 hβ‚‚) (h _ h₁) } end⟩ theorem is_normal.le_set' {f} (H : is_normal f) (p : Ξ± β†’ Prop) (g : Ξ± β†’ ordinal) (p0 : βˆƒ x, p x) (S) (Hβ‚‚ : βˆ€ o, S ≀ o ↔ βˆ€ a, p a β†’ g a ≀ o) {o} : f S ≀ o ↔ βˆ€ a, p a β†’ f (g a) ≀ o := (H.le_set (Ξ» x, βˆƒ y, p y ∧ x = g y) (let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _ (Ξ» o, (Hβ‚‚ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm β–Έ H y h1, Ξ» H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans ⟨λ H a h, H (g a) ⟨a, h, rfl⟩, Ξ» H a ⟨y, h1, h2⟩, h2.symm β–Έ H y h1⟩ theorem is_normal.refl : is_normal id := ⟨λ x, lt_succ_self _, Ξ» o l a, limit_le l⟩ theorem is_normal.trans {f g} (H₁ : is_normal f) (Hβ‚‚ : is_normal g) : is_normal (Ξ» x, f (g x)) := ⟨λ x, H₁.lt_iff.2 (Hβ‚‚.1 _), Ξ» o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (Ξ» c, Hβ‚‚.2 _ l _)⟩ theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) : is_limit (f o) := ⟨ne_of_gt $ lt_of_le_of_lt (zero_le _) $ H.lt_iff.2 l.pos, Ξ» a h, let ⟨b, h₁, hβ‚‚βŸ© := (H.limit_lt l).1 h in lt_of_le_of_lt (succ_le.2 hβ‚‚) (H.lt_iff.2 h₁)⟩ theorem add_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a + b ≀ c ↔ βˆ€ b' < b, a + b' ≀ c := ⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h, Ξ» H, le_of_not_lt $ induction_on a (Ξ» Ξ± r _, induction_on b $ Ξ» Ξ² s _ h H l, begin resetI, suffices : βˆ€ x : Ξ², sum.lex r s (sum.inr x) (enum _ _ l), { cases enum _ _ l with x x, { cases this (enum s 0 h.pos) }, { exact irrefl _ (this _) } }, intros x, rw [← typein_lt_typein (sum.lex r s), typein_enum], have := H _ (h.2 _ (typein_lt_type s x)), rw [add_succ, succ_le] at this, refine lt_of_le_of_lt (type_le'.2 ⟨order_embedding.of_monotone (Ξ» a, _) (Ξ» a b, _)⟩) this, { rcases a with ⟨a | b, h⟩, { exact sum.inl a }, { exact sum.inr ⟨b, by cases h; assumption⟩ } }, { rcases a with ⟨a | a, hβ‚βŸ©; rcases b with ⟨b | b, hβ‚‚βŸ©; cases h₁; cases hβ‚‚; rintro ⟨⟩; constructor; assumption } end) h H⟩ theorem add_is_normal (a : ordinal) : is_normal ((+) a) := ⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _), Ξ» b l c, add_le_of_limit l⟩ theorem add_is_limit (a) {b} : is_limit b β†’ is_limit (a + b) := (add_is_normal a).is_limit def typein.principal_seg {Ξ± : Type u} (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : @principal_seg Ξ± ordinal.{u} r (<) := ⟨order_embedding.of_monotone (typein r) (Ξ» a b, (typein_lt_typein r).2), type r, Ξ» b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, Ξ» ⟨a, e⟩, e β–Έ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : (typein.principal_seg r : Ξ± β†’ ordinal) = typein r := rfl /-- The minimal element of a nonempty family of ordinals -/ def min {ΞΉ} (I : nonempty ΞΉ) (f : ΞΉ β†’ ordinal) : ordinal := wf.min (set.range f) (let ⟨i⟩ := I in set.ne_empty_of_mem (set.mem_range_self i)) theorem min_eq {ΞΉ} (I) (f : ΞΉ β†’ ordinal) : βˆƒ i, min I f = f i := let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩ theorem min_le {ΞΉ I} (f : ΞΉ β†’ ordinal) (i) : min I f ≀ f i := le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i) theorem le_min {ΞΉ I} {f : ΞΉ β†’ ordinal} {a} : a ≀ min I f ↔ βˆ€ i, a ≀ f i := ⟨λ h i, le_trans h (min_le _ _), Ξ» h, let ⟨i, e⟩ := min_eq I f in e.symm β–Έ h i⟩ /-- The minimal element of a nonempty set of ordinals -/ def omin (S : set ordinal.{u}) (H : βˆƒ x, x ∈ S) : ordinal.{u} := @min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val theorem omin_mem (S H) : omin S H ∈ S := let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in (show omin S H = i, from e).symm β–Έ h theorem le_omin {S H a} : a ≀ omin S H ↔ βˆ€ i ∈ S, a ≀ i := le_min.trans set_coe.forall theorem omin_le {S H i} (h : i ∈ S) : omin S H ≀ i := le_omin.1 (le_refl _) _ h @[simp] theorem lift_min {ΞΉ} (I) (f : ΞΉ β†’ ordinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ Ξ» a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ Ξ» j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{u v}, Ξ» a b, lift_inj.1⟩, Ξ» a b, lift_lt.symm⟩, Ξ» a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal β†’ ordinal) = lift := rfl /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ def univ := lift.{(u+1) v} (@type ordinal.{u} (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := βŸ¨β†‘lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine Ξ» b, induction_on b _, introsI Ξ² s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊒, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, intros Ξ± r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(order_iso.of_surjective (order_embedding.of_monotone _ _) _).symm⟩, { exact Ξ» b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine Ξ» a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.ord'.1 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, intros Ξ± r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal β†’ ordinal) = lift.{u (max (u+1) v)} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ := by simp only [lift.principal_seg_top, univ_id] /-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≀ a`. -/ def sub (a b : ordinal.{u}) : ordinal.{u} := omin {o | a ≀ b+o} ⟨a, le_add_left _ _⟩ instance : has_sub ordinal := ⟨sub⟩ theorem le_add_sub (a b : ordinal) : a ≀ b + (a - b) := omin_mem {o | a ≀ b+o} _ theorem sub_le {a b c : ordinal} : a - b ≀ c ↔ a ≀ b + c := ⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _), Ξ» h, omin_le h⟩ theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le sub_le theorem add_sub_cancel (a b : ordinal) : a + b - a = b := le_antisymm (sub_le.2 $ le_refl _) ((add_le_add_iff_left a).1 $ le_add_sub _ _) theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b := h β–Έ add_sub_cancel _ _ theorem sub_le_self (a b : ordinal) : a - b ≀ a := sub_le.2 $ le_add_left _ _ theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≀ a) : b + (a - b) = a := le_antisymm begin rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l, { simp only [e, add_zero, h] }, { rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self }, { exact (add_le_of_limit l).2 (Ξ» c l, le_of_lt (lt_sub.1 l)) } end (le_add_sub _ _) @[simp] theorem sub_zero (a : ordinal) : a - 0 = a := by simpa only [zero_add] using add_sub_cancel 0 a @[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 := by rw ← le_zero; apply sub_le_self @[simp] theorem sub_self (a : ordinal) : a - a = 0 := by simpa only [add_zero] using add_sub_cancel a 0 theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≀ b := ⟨λ h, by simpa only [h, add_zero] using le_add_sub a b, Ξ» h, by rwa [← le_zero, sub_le, add_zero]⟩ theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) := eq_of_forall_ge_iff $ Ξ» d, by rw [sub_le, sub_le, sub_le, add_assoc] theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c := by rw [← sub_sub, add_sub_cancel] theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) := ⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero, Ξ» c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩ @[simp] theorem one_add_omega : 1 + omega.{u} = omega := begin refine le_antisymm _ (le_add_left _ _), rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add], have : is_well_order unit empty_relation := by apply_instance, refine ⟨order_embedding.collapse (order_embedding.of_monotone _ _)⟩, { apply sum.rec, exact Ξ» _, 0, exact nat.succ }, { intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H; [cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] } end @[simp] theorem one_add_of_omega_le {o} (h : omega ≀ o) : 1 + o = o := by rw [← add_sub_cancel_of_le h, ← add_assoc, one_add_omega] instance : monoid ordinal.{u} := { mul := Ξ» a b, quotient.lift_onβ‚‚ a b (Ξ» ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β Γ— Ξ±, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧ : Well_order β†’ Well_order β†’ ordinal) $ Ξ» βŸ¨Ξ±β‚, r₁, oβ‚βŸ© βŸ¨Ξ±β‚‚, rβ‚‚, oβ‚‚βŸ© βŸ¨Ξ²β‚, s₁, pβ‚βŸ© βŸ¨Ξ²β‚‚, sβ‚‚, pβ‚‚βŸ© ⟨f⟩ ⟨g⟩, quot.sound ⟨order_iso.prod_lex_congr g f⟩, one := 1, mul_assoc := Ξ» a b c, quotient.induction_on₃ a b c $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, Ξ» a b, begin rcases a with ⟨⟨a₁, aβ‚‚βŸ©, aβ‚ƒβŸ©, rcases b with ⟨⟨b₁, bβ‚‚βŸ©, bβ‚ƒβŸ©, simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc] end⟩⟩, mul_one := Ξ» a, induction_on a $ Ξ» Ξ± r _, quotient.sound ⟨⟨punit_prod _, Ξ» a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩; simp only [prod.lex_def, empty_relation, false_or]; dsimp only; simp only [eq_self_iff_true, true_and]; refl⟩⟩, one_mul := Ξ» a, induction_on a $ Ξ» Ξ± r _, quotient.sound ⟨⟨prod_punit _, Ξ» a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩; simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ } @[simp] theorem type_mul {Ξ± Ξ² : Type u} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) [is_well_order Ξ± r] [is_well_order Ξ² s] : type r * type s = type (prod.lex s r) := rfl @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_onβ‚‚ a b $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans (order_iso.prod_lex_congr (order_iso.preimage equiv.ulift _) (order_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem card_mul (a b) : card (a * b) = card a * card b := quotient.induction_onβ‚‚ a b $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩, mul_comm (mk Ξ²) (mk Ξ±) @[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 := induction_on a $ Ξ» Ξ± _ _, by exactI type_eq_zero_iff_empty.2 (Ξ» ⟨⟨e, _⟩⟩, e.elim) @[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 := induction_on a $ Ξ» Ξ± _ _, by exactI type_eq_zero_iff_empty.2 (Ξ» ⟨⟨_, e⟩⟩, e.elim) theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin rintro ⟨a₁|a₁, aβ‚‚βŸ© ⟨b₁|b₁, bβ‚‚βŸ©; simp only [prod.lex_def, sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr, sum_prod_distrib_apply_left, sum_prod_distrib_apply_right]; simp only [sum.inl.inj_iff, true_or, false_and, false_or] end⟩⟩ @[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a := by simp only [mul_add, mul_one] @[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _ theorem mul_le_mul_left {a b} (c : ordinal) : a ≀ b β†’ c * a ≀ c * b := quotient.induction_on₃ a b c $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨order_embedding.of_monotone (Ξ» a, (f a.1, a.2)) (Ξ» a b h, _)⟩, clear_, cases h with a₁ b₁ aβ‚‚ bβ‚‚ h' a b₁ bβ‚‚ h', { exact prod.lex.left _ _ _ (f.to_order_embedding.ord'.1 h') }, { exact prod.lex.right _ _ h' } end theorem mul_le_mul_right {a b} (c : ordinal) : a ≀ b β†’ a * c ≀ b * c := quotient.induction_on₃ a b c $ Ξ» ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨order_embedding.of_monotone (Ξ» a, (a.1, f a.2)) (Ξ» a b h, _)⟩, cases h with a₁ b₁ aβ‚‚ bβ‚‚ h' a b₁ bβ‚‚ h', { exact prod.lex.left _ _ _ h' }, { exact prod.lex.right _ _ (f.to_order_embedding.ord'.1 h') } end theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≀ c) (hβ‚‚ : b ≀ d) : a * b ≀ c * d := le_trans (mul_le_mul_left _ hβ‚‚) (mul_le_mul_right _ h₁) private lemma mul_le_of_limit_aux {Ξ± Ξ² r s} [is_well_order Ξ± r] [is_well_order Ξ² s] {c} (h : is_limit (type s)) (H : βˆ€ b' < type s, type r * b' ≀ c) (l : c < type r * type s) : false := begin suffices : βˆ€ a b, prod.lex s r (b, a) (enum _ _ l), { cases enum _ _ l with b a, exact irrefl _ (this _ _) }, intros a b, rw [← typein_lt_typein (prod.lex s r), typein_enum], have := H _ (h.2 _ (typein_lt_type s b)), rw [mul_succ] at this, have := lt_of_lt_of_le ((add_lt_add_iff_left _).2 (typein_lt_type _ a)) this, refine lt_of_le_of_lt _ this, refine (type_le'.2 _), constructor, refine order_embedding.of_monotone (Ξ» a, _) (Ξ» a b, _), { rcases a with ⟨⟨b', a'⟩, h⟩, by_cases e : b = b', { refine sum.inr ⟨a', _⟩, subst e, cases h with _ _ _ _ h _ _ _ h, { exact (irrefl _ h).elim }, { exact h } }, { refine sum.inl (⟨b', _⟩, a'), cases h with _ _ _ _ h _ _ _ h, { exact h }, { exact (e rfl).elim } } }, { rcases a with ⟨⟨b₁, aβ‚βŸ©, hβ‚βŸ©, rcases b with ⟨⟨bβ‚‚, aβ‚‚βŸ©, hβ‚‚βŸ©, intro h, by_cases e₁ : b = b₁; by_cases eβ‚‚ : b = bβ‚‚, { substs b₁ bβ‚‚, simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true, dif_pos, sum.lex_inr_inr] using h }, { subst b₁, simp only [subrel_val, prod.lex_def, eβ‚‚, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true, or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊒, cases hβ‚‚; [exact asymm h hβ‚‚_h, exact eβ‚‚ rfl] }, { simp only [eβ‚‚, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] }, { simpa only [dif_neg e₁, dif_neg eβ‚‚, prod.lex_def, subrel_val, subtype.mk_eq_mk, sum.lex_inl_inl] using h } } end theorem mul_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a * b ≀ c ↔ βˆ€ b' < b, a * b' ≀ c := ⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h, Ξ» H, le_of_not_lt $ induction_on a (Ξ» Ξ± r _, induction_on b $ Ξ» Ξ² s _, by exactI mul_le_of_limit_aux) h H⟩ theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) := ⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h, Ξ» b l c, mul_le_of_limit l⟩ theorem lt_mul_of_limit {a b c : ordinal.{u}} (h : is_limit c) : a < b * c ↔ βˆƒ c' < c, a < b * c' := by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h) theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c := (mul_is_normal a0).lt_iff theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≀ a * c ↔ b ≀ c := (mul_is_normal a0).le_iff theorem mul_lt_mul_of_pos_left {a b c : ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b := (mul_lt_mul_iff_left c0).2 h theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (hβ‚‚ : 0 < b) : 0 < a * b := by simpa only [mul_zero] using mul_lt_mul_of_pos_left hβ‚‚ h₁ theorem mul_ne_zero {a b : ordinal} : a β‰  0 β†’ b β‰  0 β†’ a * b β‰  0 := by simpa only [pos_iff_ne_zero] using mul_pos theorem le_of_mul_le_mul_left {a b c : ordinal} (h : c * a ≀ c * b) (h0 : 0 < c) : a ≀ b := le_imp_le_of_lt_imp_lt (Ξ» h', mul_lt_mul_of_pos_left h' h0) h theorem mul_left_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c := (mul_is_normal a0).inj theorem mul_is_limit {a b : ordinal} (a0 : 0 < a) : is_limit b β†’ is_limit (a * b) := (mul_is_normal a0).is_limit theorem mul_is_limit_left {a b : ordinal} (l : is_limit a) (b0 : 0 < b) : is_limit (a * b) := begin rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb, { exact (lt_irrefl _).elim b0 }, { rw mul_succ, exact add_is_limit _ l }, { exact mul_is_limit l.pos lb } end /-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/ protected def div (a b : ordinal.{u}) : ordinal.{u} := if h : b = 0 then 0 else omin {o | a < b * succ o} ⟨a, succ_le.1 $ by simpa only [succ_zero, one_mul] using mul_le_mul_right (succ a) (succ_le.2 (pos_iff_ne_zero.2 h))⟩ instance : has_div ordinal := ⟨ordinal.div⟩ @[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl -- TODO This should be a theorem but Lean fails to synthesize the placeholder def div_def (a) {b : ordinal} (h : b β‰  0) : a / b = omin {o | a < b * succ o} _ := dif_neg h theorem lt_mul_succ_div (a) {b : ordinal} (h : b β‰  0) : a < b * succ (a / b) := by rw div_def a h; exact omin_mem {o | a < b * succ o} _ theorem lt_mul_div_add (a) {b : ordinal} (h : b β‰  0) : a < b * (a / b) + b := by simpa only [mul_succ] using lt_mul_succ_div a h theorem div_le {a b c : ordinal} (b0 : b β‰  0) : a / b ≀ c ↔ a < b * succ c := ⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h), Ξ» h, by rw div_def a b0; exact omin_le h⟩ theorem lt_div {a b c : ordinal} (c0 : c β‰  0) : a < b / c ↔ c * succ a ≀ b := by rw [← not_le, div_le c0, not_lt] theorem le_div {a b c : ordinal} (c0 : c β‰  0) : a ≀ b / c ↔ c * a ≀ b := begin apply limit_rec_on a, { simp only [mul_zero, zero_le] }, { intros, rw [succ_le, lt_div c0] }, { simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} } end theorem div_lt {a b c : ordinal} (b0 : b β‰  0) : a / b < c ↔ a < b * c := lt_iff_lt_of_le_iff_le $ le_div b0 theorem div_le_of_le_mul {a b c : ordinal} (h : a ≀ b * c) : a / b ≀ c := if b0 : b = 0 then by simp only [b0, div_zero, zero_le] else (div_le b0).2 $ lt_of_le_of_lt h $ mul_lt_mul_of_pos_left (lt_succ_self _) (pos_iff_ne_zero.2 b0) theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c β†’ c * a < b := lt_imp_lt_of_le_imp_le div_le_of_le_mul @[simp] theorem zero_div (a : ordinal) : 0 / a = 0 := le_zero.1 $ div_le_of_le_mul $ zero_le _ theorem mul_div_le (a b : ordinal) : b * (a / b) ≀ a := if b0 : b = 0 then by simp only [b0, zero_mul, zero_le] else (le_div b0).1 (le_refl _) theorem mul_add_div (a) {b : ordinal} (b0 : b β‰  0) (c) : (b * a + c) / b = a + c / b := begin apply le_antisymm, { apply (div_le b0).2, rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left], apply lt_mul_div_add _ b0 }, { rw [le_div b0, mul_add, add_le_add_iff_left], apply mul_div_le } end theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 := by rw [← le_zero, div_le $ pos_iff_ne_zero.1 $ lt_of_le_of_lt (zero_le _) h]; simpa only [succ_zero, mul_one] using h @[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b β‰  0) : b * a / b = a := by simpa only [add_zero, zero_div] using mul_add_div a b0 0 @[simp] theorem div_one (a : ordinal) : a / 1 = a := by simpa only [one_mul] using mul_div_cancel a one_ne_zero @[simp] theorem div_self {a : ordinal} (h : a β‰  0) : a / a = 1 := by simpa only [mul_one] using mul_div_cancel 1 h theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c := if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else eq_of_forall_ge_iff $ Ξ» d, by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0] theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) := begin split; intro h, { by_cases h' : b = 0, { rw [h', add_zero] at h, right, exact ⟨h', h⟩ }, left, rw [←add_sub_cancel a b], apply sub_is_limit h, suffices : a + 0 < a + b, simpa only [add_zero], rwa [add_lt_add_iff_left, pos_iff_ne_zero] }, rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero] end /-- Divisibility is defined by right multiplication: `a ∣ b` if there exists `c` such that `b = a * c`. -/ instance : has_dvd ordinal := ⟨λ a b, βˆƒ c, b = a * c⟩ theorem dvd_def {a b : ordinal} : a ∣ b ↔ βˆƒ c, b = a * c := iff.rfl theorem dvd_mul (a b : ordinal) : a ∣ a * b := ⟨_, rfl⟩ theorem dvd_trans : βˆ€ {a b c : ordinal}, a ∣ b β†’ b ∣ c β†’ a ∣ c | a _ _ ⟨b, rfl⟩ ⟨c, rfl⟩ := ⟨b * c, mul_assoc _ _ _⟩ theorem dvd_mul_of_dvd {a b : ordinal} (c) (h : a ∣ b) : a ∣ b * c := dvd_trans h (dvd_mul _ _) theorem dvd_add_iff : βˆ€ {a b c : ordinal}, a ∣ b β†’ (a ∣ b + c ↔ a ∣ c) | a _ c ⟨b, rfl⟩ := ⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, Ξ» ⟨d, e⟩, by rw [e, ← mul_add]; apply dvd_mul⟩ theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c β†’ a ∣ b + c := (dvd_add_iff h₁).2 theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩ theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 := ⟨λ ⟨h, e⟩, by simp only [e, zero_mul], Ξ» e, e.symm β–Έ dvd_zero _⟩ theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩ theorem div_mul_cancel : βˆ€ {a b : ordinal}, a β‰  0 β†’ a ∣ b β†’ a * (b / a) = b | a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0] theorem le_of_dvd : βˆ€ {a b : ordinal}, b β‰  0 β†’ a ∣ b β†’ a ≀ b | a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a (one_le_iff_ne_zero.2 (Ξ» h : b = 0, by simpa only [h, mul_zero] using b0)) theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (hβ‚‚ : b ∣ a) : a = b := if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else if b0 : b = 0 then by subst b; exact zero_dvd.1 hβ‚‚ else le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 hβ‚‚) /-- `a % b` is the unique ordinal `o'` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩ theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl @[simp] theorem mod_zero (a : ordinal) : a % 0 = a := by simp only [mod_def, div_zero, zero_mul, sub_zero] theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a := by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero] @[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 := by simp only [mod_def, zero_div, mul_zero, sub_self] theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a := add_sub_cancel_of_le $ mul_div_le _ _ theorem mod_lt (a) {b : ordinal} (h : b β‰  0) : a % b < b := (add_lt_add_iff_left (b * (a / b))).1 $ by rw div_add_mod; exact lt_mul_div_add a h @[simp] theorem mod_self (a : ordinal) : a % a = 0 := if a0 : a = 0 then by simp only [a0, zero_mod] else by simp only [mod_def, div_self a0, mul_one, sub_self] @[simp] theorem mod_one (a : ordinal) : a % 1 = 0 := by simp only [mod_def, div_one, one_mul, sub_self] end ordinal namespace cardinal open ordinal /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. -/ def ord (c : cardinal) : ordinal := begin let ΞΉ := Ξ» Ξ±, {r // is_well_order Ξ± r}, have : Ξ  Ξ±, ΞΉ Ξ± := Ξ» Ξ±, ⟨well_ordering_rel, by apply_instance⟩, let F := Ξ» Ξ±, ordinal.min ⟨this _⟩ (Ξ» i:ΞΉ Ξ±, ⟦⟨α, i.1, i.2⟩⟧), refine quot.lift_on c F _, suffices : βˆ€ {Ξ± Ξ²}, Ξ± β‰ˆ Ξ² β†’ F Ξ± ≀ F Ξ², from Ξ» Ξ± Ξ² h, le_antisymm (this h) (this (setoid.symm h)), intros Ξ± Ξ² h, cases h with f, refine ordinal.le_min.2 (Ξ» i, _), haveI := @order_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(order_iso.preimage f i.1) i.2, rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from quot.sound ⟨order_iso.preimage f i.1⟩, exact ordinal.min_le (Ξ» i:ΞΉ Ξ±, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩ end -- TODO This should be a theorem but Lean fails to synthesize the placeholders def ord_eq_min (Ξ± : Type u) : ord (mk Ξ±) = @ordinal.min _ _ (Ξ» i:{r // is_well_order Ξ± r}, ⟦⟨α, i.1, i.2⟩⟧) := rfl theorem ord_eq (Ξ±) : βˆƒ (r : Ξ± β†’ Ξ± β†’ Prop) [wo : is_well_order Ξ± r], ord (mk Ξ±) = @type Ξ± r wo := let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq {r // is_well_order Ξ± r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (Ξ» i:{r // is_well_order Ξ± r}, ⟦⟨α, i.1, i.2⟩⟧) in ⟨r, wo, h⟩ theorem ord_le_type (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] : ord (mk Ξ±) ≀ ordinal.type r := @ordinal.min_le {r // is_well_order Ξ± r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (Ξ» i:{r // is_well_order Ξ± r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩ theorem ord_le {c o} : ord c ≀ o ↔ c ≀ o.card := quotient.induction_on c $ Ξ» Ξ±, induction_on o $ Ξ» Ξ² s _, let ⟨r, _, e⟩ := ord_eq Ξ± in begin resetI, simp only [mk_def, card_type], split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := order_embedding.preimage f s, haveI := order_embedding.is_well_order g, exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) } end theorem lt_ord {c o} : o < ord c ↔ o.card < c := by rw [← not_le, ← not_le, ord_le] @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ Ξ» Ξ±, let ⟨r, _, e⟩ := ord_eq Ξ± in by simp only [mk_def, e, card_type] theorem ord_card_le (o : ordinal) : o.card.ord ≀ o := ord_le.2 (le_refl _) lemma lt_ord_succ_card (o : ordinal) : o < o.card.succ.ord := by { rw [lt_ord], apply cardinal.lt_succ_self } @[simp] theorem ord_le_ord {c₁ cβ‚‚} : ord c₁ ≀ ord cβ‚‚ ↔ c₁ ≀ cβ‚‚ := by simp only [ord_le, card_ord] @[simp] theorem ord_lt_ord {c₁ cβ‚‚} : ord c₁ < ord cβ‚‚ ↔ c₁ < cβ‚‚ := by simp only [lt_ord, card_ord] @[simp] theorem ord_zero : ord 0 = 0 := le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _) @[simp] theorem ord_nat (n : β„•) : ord n = n := le_antisymm (ord_le.2 $ by simp only [card_nat]) $ begin induction n with n IH, { apply ordinal.zero_le }, { exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := eq_of_forall_ge_iff $ Ξ» o, le_iff_le_iff_lt_iff_lt.2 $ begin split; intro h, { rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩, rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] }, { rw lt_ord at h, rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩, rw [← lift_card, lift_lt] at h, rwa [ordinal.lift_lt, lt_ord] } end lemma mk_ord_out (c : cardinal) : mk c.ord.out.Ξ± = c := by rw [←card_type c.ord.out.r, type_out, card_ord] lemma card_typein_lt (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (x : Ξ±) (h : ord (mk Ξ±) = type r) : card (typein r x) < mk Ξ± := by { rw [←ord_lt_ord, h], refine lt_of_le_of_lt (ord_card_le _) (typein_lt_type r x) } lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.Ξ±) : card (typein c.ord.out.r x) < c := by { convert card_typein_lt c.ord.out.r x _, rw [mk_ord_out], rw [type_out, mk_ord_out] } lemma ord_injective : injective ord := by { intros c c' h, rw [←card_ord c, ←card_ord c', h] } def ord.order_embedding : @order_embedding cardinal ordinal (<) (<) := order_embedding.of_monotone cardinal.ord $ Ξ» a b, cardinal.ord_lt_ord.2 @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal β†’ ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ def univ := lift.{(u+1) v} (mk ordinal) theorem univ_id : univ.{u (u+1)} = mk ordinal := lift_id _ @[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{u (u+1)} c < univ.{u (u+1)} := by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{u (max (u+1) v)} c < univ.{u v} := by simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ Ξ» o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down'.1 (by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩, simp only [lift.principal_seg_coe], rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ βˆƒ c', c = lift.{u (u+1)} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down'.1 (by simpa only [lift.principal_seg_top]) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, Ξ» ⟨c', e⟩, e.symm β–Έ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ βˆƒ c', c = lift.{u (max (u+1) v)} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp only [e.symm, lift_lift]⟩ end, Ξ» ⟨c', e⟩, e.symm β–Έ lift_lt_univ' _⟩ end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl /-- The supremum of a family of ordinals -/ def sup {ΞΉ} (f : ΞΉ β†’ ordinal) : ordinal := omin {c | βˆ€ i, f i ≀ c} ⟨(sup (cardinal.succ ∘ card ∘ f)).ord, Ξ» i, le_of_lt $ cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩ theorem le_sup {ΞΉ} (f : ΞΉ β†’ ordinal) : βˆ€ i, f i ≀ sup f := omin_mem {c | βˆ€ i, f i ≀ c} _ theorem sup_le {ΞΉ} {f : ΞΉ β†’ ordinal} {a} : sup f ≀ a ↔ βˆ€ i, f i ≀ a := ⟨λ h i, le_trans (le_sup _ _) h, Ξ» h, omin_le h⟩ theorem lt_sup {ΞΉ} {f : ΞΉ β†’ ordinal} {a} : a < sup f ↔ βˆƒ i, a < f i := by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a) theorem is_normal.sup {f} (H : is_normal f) {ΞΉ} {g : ΞΉ β†’ ordinal} (h : nonempty ΞΉ) : f (sup g) = sup (f ∘ g) := eq_of_forall_ge_iff $ Ξ» a, by rw [sup_le, comp, H.le_set' (Ξ»_:ΞΉ, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)]; intros; simp only [sup_le, true_implies_iff] theorem sup_ord {ΞΉ} (f : ΞΉ β†’ cardinal) : sup (Ξ» i, (f i).ord) = (cardinal.sup f).ord := eq_of_forall_ge_iff $ Ξ» a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le] lemma sup_succ {ΞΉ} (f : ΞΉ β†’ ordinal) : sup (Ξ» i, succ (f i)) ≀ succ (sup f) := by { rw [ordinal.sup_le], intro i, rw ordinal.succ_le_succ, apply ordinal.le_sup } lemma unbounded_range_of_sup_ge {Ξ± Ξ² : Type u} (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (f : Ξ² β†’ Ξ±) (h : sup.{u u} (typein r ∘ f) β‰₯ type r) : unbounded r (range f) := begin apply (not_bounded_iff _).mp, rintro ⟨x, hx⟩, apply not_lt_of_ge h, refine lt_of_le_of_lt _ (typein_lt_type r x), rw [sup_le], intro y, apply le_of_lt, rw typein_lt_typein, apply hx, apply mem_range_self end /-- The supremum of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. (This is not a special case of `sup` over the subtype, because `{a // a < o} : Type (u+1)` and `sup` only works over families in `Type u`.) -/ def bsup (o : ordinal.{u}) : (Ξ  a < o, ordinal.{max u v}) β†’ ordinal.{max u v} := match o, o.out, o.out_eq with | _, ⟨α, r, _⟩, rfl, f := by exactI sup (Ξ» a, f (typein r a) (typein_lt_type _ _)) end theorem bsup_le {o f a} : bsup.{u v} o f ≀ a ↔ βˆ€ i h, f i h ≀ a := match o, o.out, o.out_eq, f : βˆ€ o w (e : ⟦w⟧ = o) (f : Ξ  (a : ordinal.{u}), a < o β†’ ordinal.{(max u v)}), bsup._match_1 o w e f ≀ a ↔ βˆ€ i h, f i h ≀ a with | _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI ⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), Ξ» H b, H _ _⟩ end theorem bsup_type (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] (f) : bsup (type r) f = sup (Ξ» a, f (typein r a) (typein_lt_type _ _)) := eq_of_forall_ge_iff $ Ξ» o, by rw [bsup_le, sup_le]; exact ⟨λ H b, H _ _, Ξ» H i h, by simpa only [typein_enum] using H (enum r i h)⟩ theorem le_bsup {o} (f : Ξ  a < o, ordinal) (i h) : f i h ≀ bsup o f := bsup_le.1 (le_refl _) _ _ theorem lt_bsup {o : ordinal} {f : Ξ  a < o, ordinal} (hf : βˆ€{a a'} (ha : a < o) (ha' : a' < o), a < a' β†’ f a ha < f a' ha') (ho : o.is_limit) (i h) : f i h < bsup o f := lt_of_lt_of_le (hf _ _ $ lt_succ_self i) (le_bsup f i.succ $ ho.2 _ h) theorem bsup_id {o} (ho : is_limit o) : bsup.{u u} o (Ξ» x _, x) = o := begin apply le_antisymm, rw [bsup_le], intro i, apply le_of_lt, rw [←not_lt], intro h, apply lt_irrefl (bsup.{u u} o (Ξ» x _, x)), apply lt_of_le_of_lt _ (lt_bsup _ ho _ h), refl, intros, assumption end theorem is_normal.bsup {f} (H : is_normal f) {o : ordinal} : βˆ€ (g : Ξ  a < o, ordinal) (h : o β‰  0), f (bsup o g) = bsup o (Ξ» a h, f (g a h)) := induction_on o $ Ξ» Ξ± r _ g h, by resetI; rw [bsup_type, H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type] theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) : bsup.{u} o (Ξ»x _, f x) = f o := by { rw [←is_normal.bsup.{u u} H (Ξ» x _, x) h.1, bsup_id h] } /-- The ordinal exponential, defined by transfinite recursion. -/ def power (a b : ordinal) : ordinal := if a = 0 then 1 - b else limit_rec_on b 1 (Ξ» _ IH, IH * a) (Ξ» b _, bsup.{u u} b) instance : has_pow ordinal ordinal := ⟨power⟩ local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a := by simp only [pow, power, if_pos rfl] @[simp] theorem zero_power {a : ordinal} (a0 : a β‰  0) : 0 ^ a = 0 := by rwa [zero_power', sub_eq_zero_iff_le, one_le_iff_ne_zero] @[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 := by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero], simp only [pow, power, if_neg h, limit_rec_on_zero]] @[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a := if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero] else by simp only [pow, power, limit_rec_on_succ, if_neg h] theorem power_limit {a b : ordinal} (a0 : a β‰  0) (h : is_limit b) : a ^ b = bsup.{u u} b (Ξ» c _, a ^ c) := by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl theorem power_le_of_limit {a b c : ordinal} (a0 : a β‰  0) (h : is_limit b) : a ^ b ≀ c ↔ βˆ€ b' < b, a ^ b' ≀ c := by rw [power_limit a0 h, bsup_le] theorem lt_power_of_limit {a b c : ordinal} (b0 : b β‰  0) (h : is_limit c) : a < b ^ c ↔ βˆƒ c' < c, a < b ^ c' := by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and] @[simp] theorem power_one (a : ordinal) : a ^ 1 = a := by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul] @[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 := begin apply limit_rec_on a, { simp only [power_zero] }, { intros _ ih, simp only [power_succ, ih, mul_one] }, refine Ξ» b l IH, eq_of_forall_ge_iff (Ξ» c, _), rw [power_le_of_limit one_ne_zero l], exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos, Ξ» H b' h, by rwa IH _ h⟩, end theorem power_pos {a : ordinal} (b) (a0 : 0 < a) : 0 < a ^ b := begin have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]}, apply limit_rec_on b, { exact h0 }, { intros b IH, rw [power_succ], exact mul_pos IH a0 }, { exact Ξ» b l _, (lt_power_of_limit (pos_iff_ne_zero.1 a0) l).2 ⟨0, l.pos, h0⟩ }, end theorem power_ne_zero {a : ordinal} (b) (a0 : a β‰  0) : a ^ b β‰  0 := pos_iff_ne_zero.1 $ power_pos b $ pos_iff_ne_zero.2 a0 theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) := have a0 : 0 < a, from lt_trans zero_lt_one h, ⟨λ b, by simpa only [mul_one, power_succ] using (mul_lt_mul_iff_left (power_pos b a0)).2 h, Ξ» b l c, power_le_of_limit (ne_of_gt a0) l⟩ theorem power_lt_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b < a ^ c ↔ b < c := (power_is_normal a1).lt_iff theorem power_le_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b ≀ a ^ c ↔ b ≀ c := (power_is_normal a1).le_iff theorem power_right_inj {a b c : ordinal} (a1 : 1 < a) : a ^ b = a ^ c ↔ b = c := (power_is_normal a1).inj theorem power_is_limit {a b : ordinal} (a1 : 1 < a) : is_limit b β†’ is_limit (a ^ b) := (power_is_normal a1).is_limit theorem power_is_limit_left {a b : ordinal} (l : is_limit a) (hb : b β‰  0) : is_limit (a ^ b) := begin rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l', { exact absurd e hb }, { rw power_succ, exact mul_is_limit (power_pos _ l.pos) l }, { exact power_is_limit l.one_lt l' } end theorem power_le_power_right {a b c : ordinal} (h₁ : 0 < a) (hβ‚‚ : b ≀ c) : a ^ b ≀ a ^ c := begin cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁, { exact (power_le_power_iff_right h₁).2 hβ‚‚ }, { subst a, simp only [one_power] } end theorem power_le_power_left {a b : ordinal} (c) (ab : a ≀ b) : a ^ c ≀ b ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, { subst c, simp only [power_zero] }, { simp only [zero_power c0, zero_le] } }, { apply limit_rec_on c, { simp only [power_zero] }, { intros c IH, simpa only [power_succ] using mul_le_mul IH ab }, { exact Ξ» c l IH, (power_le_of_limit a0 l).2 (Ξ» b' h, le_trans (IH _ h) (power_le_power_right (lt_of_lt_of_le (pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } } end theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≀ a ^ b := (power_is_normal a1).le_self _ theorem power_lt_power_left_of_succ {a b c : ordinal} (ab : a < b) : a ^ succ c < b ^ succ c := by rw [power_succ, power_succ]; exact lt_of_le_of_lt (mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab) (mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (zero_le _) ab))) theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]}, have : b+c β‰  0 := ne_of_gt (lt_of_lt_of_le (pos_iff_ne_zero.2 c0) (le_add_left _ _)), simp only [zero_power c0, zero_power this, mul_zero] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_power, mul_one] }, apply limit_rec_on c, { simp only [add_zero, power_zero, mul_one] }, { intros c IH, rw [add_succ, power_succ, IH, power_succ, mul_assoc] }, { intros c l IH, refine eq_of_forall_ge_iff (Ξ» d, (((power_is_normal a1).trans (add_is_normal b)).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (((mul_is_normal $ power_pos b (pos_iff_ne_zero.2 a0)).trans (power_is_normal a1)).limit_le l).symm } end theorem power_dvd_power (a) {b c : ordinal} (h : b ≀ c) : a ^ b ∣ a ^ c := by rw [← add_sub_cancel_of_le h, power_add]; apply dvd_mul theorem power_dvd_power_iff {a b c : ordinal} (a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≀ c := ⟨λ h, le_of_not_lt $ Ξ» hn, not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $ le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h, power_dvd_power _⟩ theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c := begin by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]}, by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]}, simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_power] }, apply limit_rec_on c, { simp only [mul_zero, power_zero] }, { intros c IH, rw [mul_succ, power_add, IH, power_succ] }, { intros c l IH, refine eq_of_forall_ge_iff (Ξ» d, (((power_is_normal a1).trans (mul_is_normal (pos_iff_ne_zero.2 b0))).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (power_le_of_limit (power_ne_zero _ a0) l).symm } end /-- The ordinal logarithm is the solution `u` to the equation `x = b ^ u * v + w` where `v < b` and `w < b`. -/ def log (b : ordinal) (x : ordinal) : ordinal := if h : 1 < b then pred $ omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩ else 0 @[simp] theorem log_not_one_lt {b : ordinal} (b1 : Β¬ 1 < b) (x : ordinal) : log b x = 0 := by simp only [log, dif_neg b1] theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x = pred (omin {o | x < b^o} (log._proof_1 b x b1)) := by simp only [log, dif_pos b1] @[simp] theorem log_zero (b : ordinal) : log b 0 = 0 := if b1 : 1 < b then by rw [log_def b1, ← le_zero, pred_le]; apply omin_le; change 0<b^succ 0; rw [succ_zero, power_one]; exact lt_trans zero_lt_one b1 else by simp only [log_not_one_lt b1] theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) = omin {o | x < b^o} (log._proof_1 b x b1) := begin let t := omin {o | x < b^o} (log._proof_1 b x b1), have : x < b ^ t := omin_mem {o | x < b^o} _, rcases zero_or_succ_or_limit t with h|h|h, { refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim, simpa only [h, power_zero] }, { rw [show log b x = pred t, from log_def b1 x, succ_pred_iff_is_succ.2 h] }, { rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, hβ‚‚βŸ©, exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a hβ‚‚) } end theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) : x < b ^ succ (log b x) := begin cases lt_or_eq_of_le (zero_le x) with x0 x0, { rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ }, { subst x, apply power_pos _ (lt_trans zero_lt_one b1) } end theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) : b ^ log b x ≀ x := begin by_cases b0 : b = 0, { rw [b0, zero_power'], refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine le_of_not_lt (Ξ» h, not_le_of_lt (lt_succ_self (log b x)) _), have := @omin_le {o | x < b^o} _ _ h, rwa ← succ_log_def b1 x0 at this }, { rw [← b1, one_power], exact one_le_iff_pos.2 x0 } end theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : c ≀ log b x ↔ b ^ c ≀ x := ⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0), Ξ» h, le_of_not_lt $ Ξ» hn, not_le_of_lt (lt_power_succ_log b1 x) $ le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩ theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : log b x < c ↔ x < b ^ c := lt_iff_lt_of_le_iff_le (le_log b1 x0) theorem log_le_log (b) {x y : ordinal} (xy : x ≀ y) : log b x ≀ log b y := if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else have x0 : 0 < x, from pos_iff_ne_zero.2 x0, if b1 : 1 < b then (le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy else by simp only [log_not_one_lt b1, zero_le] theorem log_le_self (b x : ordinal) : log b x ≀ x := if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else if b1 : 1 < b then le_trans (le_power_self _ b1) (power_log_le b (pos_iff_ne_zero.2 x0)) else by simp only [log_not_one_lt b1, zero_le] @[simp] theorem nat_cast_mul {m n : β„•} : ((m * n : β„•) : ordinal) = m * n := by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero], rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]] @[simp] theorem nat_cast_power {m n : β„•} : ((pow m n : β„•) : ordinal) = m ^ n := by induction n with n IH; [simp only [nat.pow_zero, nat.cast_zero, power_zero, nat.cast_one], rw [nat.pow_succ, nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]] @[simp] theorem nat_cast_le {m n : β„•} : (m : ordinal) ≀ n ↔ m ≀ n := by rw [← cardinal.ord_nat, ← cardinal.ord_nat, cardinal.ord_le_ord, cardinal.nat_cast_le] @[simp] theorem nat_cast_lt {m n : β„•} : (m : ordinal) < n ↔ m < n := by simp only [lt_iff_le_not_le, nat_cast_le] @[simp] theorem nat_cast_inj {m n : β„•} : (m : ordinal) = n ↔ m = n := by simp only [le_antisymm_iff, nat_cast_le] @[simp] theorem nat_cast_eq_zero {n : β„•} : (n : ordinal) = 0 ↔ n = 0 := @nat_cast_inj n 0 @[simp] theorem nat_cast_ne_zero {n : β„•} : (n : ordinal) β‰  0 ↔ n β‰  0 := not_congr nat_cast_eq_zero @[simp] theorem nat_cast_pos {n : β„•} : (0 : ordinal) < n ↔ 0 < n := @nat_cast_lt 0 n @[simp] theorem nat_cast_sub {m n : β„•} : ((m - n : β„•) : ordinal) = m - n := (_root_.le_total m n).elim (Ξ» h, by rw [nat.sub_eq_zero_iff_le.2 h, sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl) (Ξ» h, (add_left_cancel n).1 $ by rw [← nat.cast_add, nat.add_sub_cancel' h, add_sub_cancel_of_le (nat_cast_le.2 h)]) @[simp] theorem nat_cast_div {m n : β„•} : ((m / n : β„•) : ordinal) = m / n := if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else have n0':_, from nat_cast_ne_zero.2 n0, le_antisymm (by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm]; apply nat.div_mul_le_self) (by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul, nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)]; apply nat.lt_succ_self) @[simp] theorem nat_cast_mod {m n : β„•} : ((m % n : β„•) : ordinal) = m % n := by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add, add_comm, nat.mod_add_div] @[simp] theorem nat_le_card {o} {n : β„•} : (n : cardinal) ≀ card o ↔ (n : ordinal) ≀ o := ⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h, Ξ» h, card_nat n β–Έ card_le_card h⟩ @[simp] theorem nat_lt_card {o} {n : β„•} : (n : cardinal) < card o ↔ (n : ordinal) < o := by rw [← succ_le, ← cardinal.succ_le, cardinal.nat_succ, nat_le_card]; refl @[simp] theorem card_lt_nat {o} {n : β„•} : card o < n ↔ o < n := lt_iff_lt_of_le_iff_le nat_le_card @[simp] theorem card_le_nat {o} {n : β„•} : card o ≀ n ↔ o ≀ n := le_iff_le_iff_lt_iff_lt.2 nat_lt_card @[simp] theorem card_eq_nat {o} {n : β„•} : card o = n ↔ o = n := by simp only [le_antisymm_iff, card_le_nat, nat_le_card] @[simp] theorem type_fin (n : β„•) : @type (fin n) (<) _ = n := by rw [← card_eq_nat, card_type, mk_fin] @[simp] theorem lift_nat_cast (n : β„•) : lift n = n := by induction n with n ih; [simp only [nat.cast_zero, lift_zero], simp only [nat.cast_succ, lift_add, ih, lift_one]] theorem lift_type_fin (n : β„•) : lift (@type (fin n) (<) _) = n := by simp only [type_fin, lift_nat_cast] theorem fintype_card (r : Ξ± β†’ Ξ± β†’ Prop) [is_well_order Ξ± r] [fintype Ξ±] : type r = fintype.card Ξ± := by rw [← card_eq_nat, card_type, fintype_card] end ordinal namespace cardinal open ordinal @[simp] theorem ord_omega : ord.{u} omega = ordinal.omega := le_antisymm (ord_le.2 $ le_refl _) $ le_of_forall_lt $ Ξ» o h, begin rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩, rw [lt_ord, ← lift_card, ← lift_omega.{0 u}, lift_lt, ← typein_enum (<) h'], exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩ end @[simp] theorem add_one_of_omega_le {c} (h : omega ≀ c) : c + 1 = c := by rw [add_comm, ← card_ord c, ← card_one, ← card_add, one_add_of_omega_le]; rwa [← ord_omega, ord_le_ord] end cardinal namespace ordinal theorem lt_omega {o : ordinal.{u}} : o < omega ↔ βˆƒ n : β„•, o = n := by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat] theorem nat_lt_omega (n : β„•) : (n : ordinal) < omega := lt_omega.2 ⟨_, rfl⟩ theorem omega_pos : 0 < omega := nat_lt_omega 0 theorem omega_ne_zero : omega β‰  0 := ne_of_gt omega_pos theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1 theorem omega_is_limit : is_limit omega := ⟨omega_ne_zero, Ξ» o h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e]; exact nat_lt_omega (n+1)⟩ theorem omega_le {o : ordinal.{u}} : omega ≀ o ↔ βˆ€ n : β„•, (n : ordinal) ≀ o := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, Ξ» H, le_of_forall_lt $ Ξ» a h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e, ← succ_le]; exact H (n+1)⟩ theorem nat_lt_limit {o} (h : is_limit o) : βˆ€ n : β„•, (n : ordinal) < o | 0 := lt_of_le_of_ne (zero_le o) h.1.symm | (n+1) := h.2 _ (nat_lt_limit n) theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≀ o := omega_le.2 $ Ξ» n, le_of_lt $ nat_lt_limit h n theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega := begin rcases lt_omega.1 h with ⟨n, rfl⟩, clear h, induction n with n IH, { rw [nat.cast_zero, zero_add] }, { rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] } end theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega end theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a β‰  0 ∧ omega ∣ a := begin refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, Ξ» h, _⟩, { refine (limit_le l).2 (Ξ» x hx, le_of_lt _), rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero, mul_succ, add_le_of_limit omega_is_limit], intros b hb, rcases lt_omega.1 hb with ⟨n, rfl⟩, exact le_trans (add_le_add_right (mul_div_le _ _) _) (le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) }, { rcases h with ⟨a0, b, rfl⟩, refine mul_is_limit_left omega_is_limit (pos_iff_ne_zero.2 $ mt _ a0), intro e, simp only [e, mul_zero] } end local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega end theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b := begin refine le_antisymm _ (le_add_left _ _), revert h, apply limit_rec_on b, { intro h, rw [power_zero, ← succ_zero, lt_succ, le_zero] at h, rw [h, zero_add] }, { intros b _ h, rw [power_succ] at h, rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩, refine le_trans (add_le_add_right (le_of_lt ax) _) _, rw [power_succ, ← mul_add, add_omega xo] }, { intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩, refine (((add_is_normal a).trans (power_is_normal one_lt_omega)) .limit_le l).2 (Ξ» y yb, _), let z := max x y, have := IH z (max_lt xb yb) (lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)), exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _) (le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) } end theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (hβ‚‚ : b < omega ^ c) : a + b < omega ^ c := by rwa [← add_omega_power h₁, add_lt_add_iff_left] theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (hβ‚‚ : omega ^ b ≀ c) : a + c = c := by rw [← add_sub_cancel_of_le hβ‚‚, ← add_assoc, add_omega_power h₁] theorem add_absorp_iff {o : ordinal} (o0 : o > 0) : (βˆ€ a < o, a + o = o) ↔ βˆƒ a, o = omega ^ a := ⟨λ H, ⟨log omega o, begin refine ((lt_or_eq_of_le (power_log_le _ o0)) .resolve_left $ Ξ» h, _).symm, have := H _ h, have := lt_power_succ_log one_lt_omega o, rw [power_succ, lt_mul_of_limit omega_is_limit] at this, rcases this with ⟨a, ao, h'⟩, rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao, revert h', apply not_lt_of_le, suffices e : omega ^ log omega o * ↑n + o = o, { simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o }, induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]}, simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH] end⟩, Ξ» ⟨b, e⟩, e.symm β–Έ Ξ» a, add_omega_power⟩ theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a) (l : is_limit c) (IH : βˆ€ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c := le_antisymm ((mul_le_of_limit l).2 $ Ξ» c' h, begin apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)), rw IH _ h, apply le_trans (add_le_add_left _ _), { rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) }, { rw ← ba, exact le_add_right _ _ } end) (mul_le_mul_right _ (le_add_right _ _)) theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := begin apply limit_rec_on c, { simp only [succ_zero, mul_one] }, { intros c IH, rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] }, { intros c l IH, have := add_mul_limit_aux ba l IH, rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] } end theorem add_mul_limit {a b c : ordinal} (ba : b + a = a) (l : is_limit c) : (a + b) * c = a * c := add_mul_limit_aux ba l (Ξ» c' _, add_mul_succ c' ba) theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega := le_antisymm ((mul_le_of_limit omega_is_limit).2 $ Ξ» b hb, le_of_lt (mul_lt_omega ha hb)) (by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0)) theorem mul_lt_omega_power {a b c : ordinal} (c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c := if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l, { exact (lt_irrefl _).elim c0 }, { rw power_succ at ha, rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt omega_is_limit).1 ha with ⟨n, hn, an⟩, refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _, rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)], exact mul_lt_omega hn hb }, { rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩, refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _, rw [← power_succ, power_lt_power_iff_right one_lt_omega], exact l.2 _ hx } end theorem mul_omega_dvd {a : ordinal} (a0 : 0 < a) (ha : a < omega) : βˆ€ {b}, omega ∣ b β†’ a * b = b | _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha] theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) : a * omega ^ omega ^ b = omega ^ omega ^ b := begin by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊒, exact mul_omega a0 h}, refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)), rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h with ⟨x, xb, ax⟩, refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _, rw [← power_add, add_omega_power xb] end theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega := le_antisymm ((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2 (Ξ» b hb, le_of_lt (power_lt_omega h hb))) (le_power_self _ a1) theorem CNF_aux {b o : ordinal} (b0 : b β‰  0) (o0 : o β‰  0) : o % b ^ log b o < o := lt_of_lt_of_le (mod_lt _ $ power_ne_zero _ b0) (power_log_le _ $ pos_iff_ne_zero.2 o0) @[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b β‰  0) {C : ordinal β†’ Sort*} (H0 : C 0) (H : βˆ€ o, o β‰  0 β†’ o % b ^ log b o < o β†’ C (o % b ^ log b o) β†’ C o) : βˆ€ o, C o | o := if o0 : o = 0 then by rw o0; exact H0 else have _, from CNF_aux b0 o0, H o o0 this (CNF_rec (o % b ^ log b o)) using_well_founded {dec_tac := `[assumption]} @[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 := by rw [CNF_rec, dif_pos rfl]; refl @[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) : @CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) := by rw [CNF_rec, dif_neg o0] /-- The Cantor normal form of an ordinal is the list of coefficients in the base-`b` expansion of `o`. CNF b (b ^ u₁ * v₁ + b ^ uβ‚‚ * vβ‚‚) = [(u₁, v₁), (uβ‚‚, vβ‚‚)] -/ def CNF (b := omega) (o : ordinal) : list (ordinal Γ— ordinal) := if b0 : b = 0 then [] else CNF_rec b0 [] (Ξ» o o0 h IH, (log b o, o / b ^ log b o) :: IH) o @[simp] theorem zero_CNF (o) : CNF 0 o = [] := dif_pos rfl @[simp] theorem CNF_zero (b) : CNF b 0 = [] := if b0 : b = 0 then dif_pos b0 else (dif_neg b0).trans $ CNF_rec_zero _ theorem CNF_ne_zero {b o : ordinal} (b0 : b β‰  0) (o0 : o β‰  0) : CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) := by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0] theorem one_CNF {o : ordinal} (o0 : o β‰  0) : CNF 1 o = [(0, o)] := by rw [CNF_ne_zero one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one, CNF_zero, div_one] theorem CNF_foldr {b : ordinal} (b0 : b β‰  0) (o) : (CNF b o).foldr (Ξ» p r, b ^ p.1 * p.2 + r) 0 = o := CNF_rec b0 (by rw CNF_zero; refl) (Ξ» o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o theorem CNF_pairwise_aux (b := omega) (o) : (βˆ€ p ∈ CNF b o, prod.fst p ≀ log b o) ∧ (CNF b o).pairwise (Ξ» p q, q.1 < p.1) := begin by_cases b0 : b = 0, { simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact Ξ» _, false.elim }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine CNF_rec b0 _ _ o, { simp only [CNF_zero, list.pairwise.nil, and_true], exact Ξ» _, false.elim }, intros o o0 H IH, cases IH with IH₁ IHβ‚‚, simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IHβ‚‚, and_true], refine ⟨⟨le_refl _, Ξ» p m, _⟩, Ξ» p m, _⟩, { exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) }, { refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _), { rw pos_iff_ne_zero, intro e, rw e at m, simpa only [CNF_zero] using m }, { exact mod_lt _ (power_ne_zero _ b0) } } }, { by_cases o0 : o = 0, { simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact Ξ» _, false.elim }, rw [← b1, one_CNF o0], simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and, list.pairwise_singleton] } end theorem CNF_pairwise (b := omega) (o) : (CNF b o).pairwise (Ξ» p q, prod.fst q < p.1) := (CNF_pairwise_aux _ _).2 theorem CNF_fst_le_log (b := omega) (o) : βˆ€ p ∈ CNF b o, prod.fst p ≀ log b o := (CNF_pairwise_aux _ _).1 theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≀ o := le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _) theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) : βˆ€ p ∈ CNF b o, prod.snd p < b := begin have b0 := ne_of_gt (lt_trans zero_lt_one b1), refine CNF_rec b0 (Ξ» _, by rw [CNF_zero]; exact false.elim) _ o, intros o o0 H IH, simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, list.forall_mem_cons', iff_true_intro IH, and_true], rw [div_lt (power_ne_zero _ b0), ← power_succ], exact lt_power_succ_log b1 _, end theorem CNF_sorted (b := omega) (o) : ((CNF b o).map prod.fst).sorted (>) := by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o /-- The next fixed point function, the least fixed point of the normal function `f` above `a`. -/ def nfp (f : ordinal β†’ ordinal) (a : ordinal) := sup (Ξ» n : β„•, f^[n] a) theorem iterate_le_nfp (f a n) : f^[n] a ≀ nfp f a := le_sup _ n theorem le_nfp_self (f a) : a ≀ nfp f a := iterate_le_nfp f a 0 theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} : f b < nfp f a ↔ b < nfp f a := lt_sup.trans $ iff.trans (by exact ⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩, Ξ» ⟨n, h⟩, ⟨n+1, by rw nat.iterate_succ'; exact H.lt_iff.2 h⟩⟩) lt_sup.symm theorem is_normal.nfp_le {f} (H : is_normal f) {a b} : nfp f a ≀ f b ↔ nfp f a ≀ b := le_iff_le_iff_lt_iff_lt.2 H.lt_nfp theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b} (ab : a ≀ b) (h : f b ≀ b) : nfp f a ≀ b := sup_le.2 $ Ξ» i, begin induction i with i IH generalizing a, {exact ab}, exact IH (le_trans (H.le_iff.2 ab) h), end theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a := begin refine le_antisymm _ (H.le_self _), cases le_or_lt (f a) a with aa aa, { rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) }, rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l, { refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1), simp only [e, zero_le] }, { have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]), rw [e, lt_succ] at this, have ab : a ≀ b, { rw [← lt_succ, ← e], exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) }, refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this)) (le_trans this (le_of_lt _)), simp only [e, lt_succ_self] }, { exact (H.2 _ l _).2 (Ξ» b h, le_of_lt (H.lt_nfp.2 h)) } end theorem is_normal.le_nfp {f} (H : is_normal f) {a b} : f b ≀ nfp f a ↔ b ≀ nfp f a := ⟨le_trans (H.le_self _), Ξ» h, by simpa only [H.nfp_fp] using H.le_iff.2 h⟩ theorem nfp_eq_self {f : ordinal β†’ ordinal} {a} (h : f a = a) : nfp f a = a := le_antisymm (sup_le.mpr $ Ξ» i, by rw [nat.iterateβ‚€ h]) (le_nfp_self f a) /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. -/ def deriv (f : ordinal β†’ ordinal) (o : ordinal) : ordinal := limit_rec_on o (nfp f 0) (Ξ» a IH, nfp f (succ IH)) (Ξ» a l, bsup.{u u} a) @[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := limit_rec_on_succ _ _ _ _ theorem deriv_limit (f) {o} : is_limit o β†’ deriv f o = bsup.{u u} o (Ξ» a _, deriv f a) := limit_rec_on_limit _ _ _ _ theorem deriv_is_normal (f) : is_normal (deriv f) := ⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self, Ξ» o l a, by rw [deriv_limit _ l, bsup_le]⟩ theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o := begin apply limit_rec_on o, { rw [deriv_zero, H.nfp_fp] }, { intros o ih, rw [deriv_succ, H.nfp_fp] }, intros o l IH, rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1], refine eq_of_forall_ge_iff (Ξ» c, _), simp only [bsup_le, IH] {contextual:=tt} end theorem is_normal.fp_iff_deriv {f} (H : is_normal f) {a} : f a ≀ a ↔ βˆƒ o, a = deriv f o := ⟨λ ha, begin suffices : βˆ€ o (_:a ≀ deriv f o), βˆƒ o, a = deriv f o, from this a ((deriv_is_normal _).le_self _), intro o, apply limit_rec_on o, { intros h₁, refine ⟨0, le_antisymm h₁ _⟩, rw deriv_zero, exact H.nfp_le_fp (zero_le _) ha }, { intros o IH h₁, cases le_or_lt a (deriv f o), {exact IH h}, refine ⟨succ o, le_antisymm h₁ _⟩, rw deriv_succ, exact H.nfp_le_fp (succ_le.2 h) ha }, { intros o l IH h₁, cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩}, rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h, exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) } end, Ξ» ⟨o, e⟩, e.symm β–Έ le_of_eq (H.deriv_fp _)⟩ end ordinal namespace cardinal section using_ordinals open ordinal theorem ord_is_limit {c} (co : omega ≀ c) : (ord c).is_limit := begin refine ⟨λ h, omega_ne_zero _, Ξ» a, lt_imp_lt_of_le_imp_le _⟩, { rw [← ordinal.le_zero, ord_le] at h, simpa only [card_zero, le_zero] using le_trans co h }, { intro h, rw [ord_le] at h ⊒, rwa [← @add_one_of_omega_le (card a), ← card_succ], rw [← ord_le, ← le_succ_of_is_limit, ord_le], { exact le_trans co h }, { rw ord_omega, exact omega_is_limit } } end def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @order_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx Ο‰ = Ο‰`, `aleph_idx ℡₁ = Ο‰ + 1` and so on.) -/ def aleph_idx : cardinal β†’ ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal β†’ ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_order_embedding.ord'.symm @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≀ aleph_idx b ↔ a ≀ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a β†’ βˆƒ c, aleph_idx c = b := aleph_idx.initial_seg.init _ _ def aleph_idx.order_iso : @order_iso cardinal.{u} ordinal.{u} (<) (<) := @order_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ Ξ» ⟨o, e⟩, begin have : βˆ€ c, aleph_idx c < o := Ξ» c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI Ξ± r _ h, let s := sup.{u u} (Ξ» a:Ξ±, inv_fun aleph_idx (ordinal.typein r a)), apply not_le_of_gt (lt_succ_self s), have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.inj, simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using le_sup.{u u} (Ξ» a, inv_fun aleph_idx (ordinal.typein r a)) (ordinal.enum r _ (h (succ s))), end @[simp] theorem aleph_idx.order_iso_coe : (aleph_idx.order_iso : cardinal β†’ ordinal) = aleph_idx := rfl @[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.order_iso⟩ @[simp] theorem mk_cardinal : mk cardinal = univ.{u (u+1)} := by simpa only [card_type, card_univ] using congr_arg card type_cardinal def aleph'.order_iso := cardinal.aleph_idx.order_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' Ο‰ = Ο‰`, `aleph' (Ο‰ + 1) = ℡₁, etc. -/ def aleph' : ordinal β†’ cardinal := aleph'.order_iso @[simp] theorem aleph'.order_iso_coe : (aleph'.order_iso : ordinal β†’ cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ oβ‚‚ : ordinal.{u}} : aleph' o₁ < aleph' oβ‚‚ ↔ o₁ < oβ‚‚ := aleph'.order_iso.ord'.symm @[simp] theorem aleph'_le {o₁ oβ‚‚ : ordinal.{u}} : aleph' o₁ ≀ aleph' oβ‚‚ ↔ o₁ ≀ oβ‚‚ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c := cardinal.aleph_idx.order_iso.to_equiv.symm_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o := cardinal.aleph_idx.order_iso.to_equiv.apply_symm_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by rw [← le_zero, ← aleph'_aleph_idx 0, aleph'_le]; apply ordinal.zero_le @[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ := le_antisymm (cardinal.aleph_idx_le.1 $ by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx]; apply cardinal.lt_succ_self) (cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _) @[simp] theorem aleph'_nat : βˆ€ n : β„•, aleph' n = n | 0 := aleph'_zero | (n+1) := show aleph' (ordinal.succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} : aleph' o ≀ c ↔ βˆ€ o' < o, aleph' o' ≀ c := ⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h, Ξ» h, begin rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l], intros x h', rw [← aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ @[simp] theorem aleph'_omega : aleph' ordinal.omega = omega := eq_of_forall_ge_iff $ Ξ» c, begin simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le], exact forall_swap.trans (forall_congr $ Ξ» n, by simp only [forall_eq, aleph'_nat]), end /-- aleph' and aleph_idx form an equivalence between `ordinal` and `cardinal` -/ @[simp] def aleph'_equiv : ordinal ≃ cardinal := ⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩ /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = Ο‰`, `aleph 1 = succ Ο‰` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o) @[simp] theorem aleph_lt {o₁ oβ‚‚ : ordinal.{u}} : aleph o₁ < aleph oβ‚‚ ↔ o₁ < oβ‚‚ := aleph'_lt.trans (ordinal.add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ oβ‚‚ : ordinal.{u}} : aleph o₁ ≀ aleph oβ‚‚ ↔ o₁ ≀ oβ‚‚ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ := by rw [aleph, ordinal.add_succ, aleph'_succ]; refl @[simp] theorem aleph_zero : aleph 0 = omega := by simp only [aleph, add_zero, aleph'_omega] theorem omega_le_aleph' {o : ordinal} : omega ≀ aleph' o ↔ ordinal.omega ≀ o := by rw [← aleph'_omega, aleph'_le] theorem omega_le_aleph (o : ordinal) : omega ≀ aleph o := by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord := ord_is_limit $ omega_le_aleph _ theorem exists_aleph {c : cardinal} : omega ≀ c ↔ βˆƒ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ordinal.omega, by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx]; rwa [← omega_le_aleph', aleph'_aleph_idx]⟩, Ξ» ⟨o, e⟩, e.symm β–Έ omega_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _, Ξ» o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ordinal.omega /- properties of mul -/ theorem mul_eq_self {c : cardinal} (h : omega ≀ c) : c * c = c := begin refine le_antisymm _ (by simpa only [mul_one] using mul_le_mul_left c (le_trans (le_of_lt one_lt_omega) h)), refine acc.rec_on (cardinal.wf.apply c) (Ξ» c _, quotient.induction_on c $ Ξ» Ξ± IH ol, _) h, rcases ord_eq Ξ± with ⟨r, wo, e⟩, resetI, let := decidable_linear_order_of_STO' r, have : is_well_order Ξ± (<) := wo, let g : Ξ± Γ— Ξ± β†’ Ξ± := Ξ» p, max p.1 p.2, let f : Ξ± Γ— Ξ± β†ͺ ordinal Γ— (Ξ± Γ— Ξ±) := ⟨λ p:Ξ±Γ—Ξ±, (typein (<) (g p), p), Ξ» p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), have : is_well_order _ s := (order_embedding.preimage _ _).is_well_order, suffices : type s ≀ type r, {exact card_le_card this}, refine le_of_forall_lt (Ξ» o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≀ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _, { have : {q|s q p} βŠ† (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}), { intros q h, simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h, exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set Ξ±) ≃ ({x | r x (g p)} βŠ• punit), { exact ⟨(set.embedding_of_subset this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr punit_equiv_punit), apply @irrefl _ r }, cases lt_or_ge (card (typein (<) (g p)).succ) omega with qo qo, { exact lt_of_lt_of_le (mul_lt_omega qo qo) ol }, { suffices, {exact lt_of_le_of_lt (IH _ this qo) this}, rw ← lt_ord, apply (ord_is_limit ol).2, rw [mk_def, e], apply typein_lt_type } end end using_ordinals theorem mul_eq_max {a b : cardinal} (ha : omega ≀ a) (hb : omega ≀ b) : a * b = max a b := le_antisymm (mul_eq_self (le_trans ha (le_max_left a b)) β–Έ mul_le_mul (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa only [mul_one] using mul_le_mul_left a (le_trans (le_of_lt one_lt_omega) hb)) (by simpa only [one_mul] using mul_le_mul_right b (le_trans (le_of_lt one_lt_omega) ha)) theorem mul_lt_of_lt {a b c : cardinal} (hc : omega ≀ c) (h1 : a < c) (h2 : b < c) : a * b < c := lt_of_le_of_lt (mul_le_mul (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (Ξ» h, lt_of_lt_of_le (mul_lt_omega h h) hc) (Ξ» h, by rw mul_eq_self h; exact max_lt h1 h2) lemma mul_le_max_of_omega_le_left {a b : cardinal} (h : omega ≀ a) : a * b ≀ max a b := begin convert mul_le_mul (le_max_left a b) (le_max_right a b), rw [mul_eq_self], refine le_trans h (le_max_left a b) end lemma mul_eq_max_of_omega_le_left {a b : cardinal} (h : omega ≀ a) (h' : b β‰  0) : a * b = max a b := begin apply le_antisymm, apply mul_le_max_of_omega_le_left h, cases le_or_gt omega b with hb hb, rw [mul_eq_max h hb], have : b ≀ a, exact le_trans (le_of_lt hb) h, rw [max_eq_left this], convert mul_le_mul_left _ (one_le_iff_ne_zero.mpr h'), rw [mul_one], end lemma mul_eq_left {a b : cardinal} (ha : omega ≀ a) (hb : b ≀ a) (hb' : b β‰  0) : a * b = a := by { rw [mul_eq_max_of_omega_le_left ha hb', max_eq_left hb] } lemma mul_eq_right {a b : cardinal} (hb : omega ≀ b) (ha : a ≀ b) (ha' : a β‰  0) : a * b = b := by { rw [mul_comm, mul_eq_left hb ha ha'] } lemma le_mul_left {a b : cardinal} (h : b β‰  0) : a ≀ b * a := by { convert mul_le_mul_right _ (one_le_iff_ne_zero.mpr h), rw [one_mul] } lemma le_mul_right {a b : cardinal} (h : b β‰  0) : a ≀ a * b := by { rw [mul_comm], exact le_mul_left h } lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max omega b ≀ a ∧ b β‰  0) ∨ b = 1 ∨ a = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { have : a β‰  0, { rintro rfl, exact not_lt_of_le ha omega_pos }, left, use ha, { rw [← not_lt], intro hb, apply ne_of_gt _ h, refine lt_of_lt_of_le hb (le_mul_left this) }, { rintro rfl, apply this, rw [_root_.mul_zero] at h, subst h }}, right, by_cases h2a : a = 0, { right, exact h2a }, have hb : b β‰  0, { rintro rfl, apply h2a, rw [mul_zero] at h, subst h }, left, rw [← h, mul_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction, rw [← ne] at h2a, rw [← one_le_iff_ne_zero] at h2a hb, norm_cast at h2a hb h ⊒, apply le_antisymm _ hb, rw [← not_lt], intro h2b, apply ne_of_gt _ h, rw [gt], conv_lhs { rw [← mul_one n] }, rwa [mul_lt_mul_left], apply nat.lt_of_succ_le h2a }, { rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl), { rw [mul_eq_max_of_omega_le_left ha hb, max_eq_left hab] }, all_goals {simp}} end /- properties of add -/ theorem add_eq_self {c : cardinal} (h : omega ≀ c) : c + c = c := le_antisymm (by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using mul_le_mul_right c (le_trans (le_of_lt $ nat_lt_omega 2) h)) (le_add_left c c) theorem add_eq_max {a b : cardinal} (ha : omega ≀ a) : a + b = max a b := le_antisymm (add_eq_self (le_trans ha (le_max_left a b)) β–Έ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (le_add_right _ _) (le_add_left _ _) theorem add_lt_of_lt {a b c : cardinal} (hc : omega ≀ c) (h1 : a < c) (h2 : b < c) : a + b < c := lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (Ξ» h, lt_of_lt_of_le (add_lt_omega h h) hc) (Ξ» h, by rw add_eq_self h; exact max_lt h1 h2) lemma eq_of_add_eq_of_omega_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : omega ≀ c) : b = c := begin apply le_antisymm, { rw [← h], apply cardinal.le_add_left }, rw[← not_lt], intro hb, have : a + b < c := add_lt_of_lt hc ha hb, simpa [h, lt_irrefl] using this end lemma add_eq_left {a b : cardinal} (ha : omega ≀ a) (hb : b ≀ a) : a + b = a := by { rw [add_eq_max ha, max_eq_left hb] } lemma add_eq_right {a b : cardinal} (hb : omega ≀ b) (ha : a ≀ b) : a + b = b := by { rw [add_comm, add_eq_left hb ha] } lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max omega b ≀ a ∨ b = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { left, use ha, rw [← not_lt], intro hb, apply ne_of_gt _ h, exact lt_of_lt_of_le hb (le_add_left b a) }, right, rw [← h, add_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊒, rw [← add_left_inj, h, add_zero] }, { rintro (⟨h1, h2⟩|h3), rw [add_eq_max h1, max_eq_left h2], rw [h3, add_zero] } end lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max omega a ≀ b ∨ a = 0) := by { rw [add_comm, add_eq_left_iff] } lemma add_one_eq {a : cardinal} (ha : omega ≀ a) : a + 1 = a := have 1 ≀ a, from le_trans (le_of_lt one_lt_omega) ha, add_eq_left ha this protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < omega) : b = c := begin cases le_or_lt omega b with hb hb, { have : a < b := lt_of_lt_of_le ha hb, rw [add_eq_right hb (le_of_lt this), eq_comm] at h, rw [eq_of_add_eq_of_omega_le h this hb] }, { have hc : c < omega, { rw [← not_le], intro hc, apply lt_irrefl omega, apply lt_of_le_of_lt (le_trans hc (le_add_left _ a)), rw [← h], apply add_lt_omega ha hb }, rw [lt_omega] at *, rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩, norm_cast at h ⊒, apply eq_of_add_eq_add_left h } end protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < omega) : a = c := by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb } /- properties about power -/ theorem pow_le {ΞΊ ΞΌ : cardinal.{u}} (H1 : omega ≀ ΞΊ) (H2 : ΞΌ < omega) : ΞΊ ^ ΞΌ ≀ ΞΊ := let ⟨n, H3⟩ := lt_omega.1 H2 in H3.symm β–Έ (quotient.induction_on ΞΊ (Ξ» Ξ± H1, nat.rec_on n (le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero]; from one_lt_omega) H1) (Ξ» n ih, trans_rel_left _ (by rw [nat.cast_succ, power_add, power_one]; from mul_le_mul_right _ ih) (mul_eq_self H1))) H1) lemma power_self_eq {c : cardinal} (h : omega ≀ c) : c ^ c = 2 ^ c := begin apply le_antisymm, { apply le_trans (power_le_power_right $ le_of_lt $ cantor c), rw [power_mul, mul_eq_self h] }, { convert power_le_power_right (le_trans (le_of_lt $ nat_lt_omega 2) h), apply nat.cast_two.symm } end lemma power_nat_le {c : cardinal.{u}} {n : β„•} (h : omega ≀ c) : c ^ (n : cardinal.{u}) ≀ c := pow_le h (nat_lt_omega n) lemma powerlt_omega {c : cardinal} (h : omega ≀ c) : c ^< omega = c := begin apply le_antisymm, { rw [powerlt_le], intro c', rw [lt_omega], rintro ⟨n, rfl⟩, apply power_nat_le h }, convert le_powerlt one_lt_omega, rw [power_one] end lemma powerlt_omega_le (c : cardinal) : c ^< omega ≀ max c omega := begin cases le_or_gt omega c, { rw [powerlt_omega h], apply le_max_left }, rw [powerlt_le], intros c' hc', refine le_trans (le_of_lt $ power_lt_omega h hc') (le_max_right _ _) end /- compute cardinality of various types -/ theorem mk_list_eq_mk {Ξ± : Type u} (H1 : omega ≀ mk Ξ±) : mk (list Ξ±) = mk Ξ± := eq.symm $ le_antisymm ⟨⟨λ x, [x], Ξ» x y H, (list.cons.inj H).1⟩⟩ $ calc mk (list Ξ±) = sum (Ξ» n : β„•, mk Ξ± ^ (n : cardinal.{u})) : mk_list_eq_sum_pow Ξ± ... ≀ sum (Ξ» n : β„•, mk Ξ±) : sum_le_sum _ _ $ Ξ» n, pow_le H1 $ nat_lt_omega n ... = sum (Ξ» n : ulift.{u} β„•, mk Ξ±) : quotient.sound ⟨@sigma_congr_left _ _ (Ξ» _, quotient.out (mk Ξ±)) equiv.ulift.symm⟩ ... = omega * mk Ξ± : sum_const _ _ ... = max (omega) (mk Ξ±) : mul_eq_max (le_refl _) H1 ... = mk Ξ± : max_eq_right H1 lemma mk_bounded_set_le_of_omega_le (Ξ± : Type u) (c : cardinal) (hΞ± : omega ≀ mk Ξ±) : mk {t : set Ξ± // mk t ≀ c} ≀ mk Ξ± ^ c := begin refine le_trans _ (by rw [←add_one_eq hΞ±]), refine quotient.induction_on c _, clear c, intro Ξ², fapply mk_le_of_surjective, { intro f, use sum.inl ⁻¹' range f, refine le_trans (mk_preimage_of_injective _ _ (Ξ» x y, sum.inl.inj)) _, apply mk_range_le }, rintro ⟨s, ⟨g⟩⟩, use Ξ» y, if h : βˆƒ(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩, apply subtype.eq, ext, split, { rintro ⟨y, h⟩, dsimp only at h, by_cases h' : βˆƒ (z : s), g z = y, { rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 }, { rw [dif_neg h'] at h, cases h }}, { intro h, have : βˆƒ(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩, use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr', suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this, apply g.2, exact classical.some_spec this } end lemma mk_bounded_set_le (Ξ± : Type u) (c : cardinal) : mk {t : set Ξ± // mk t ≀ c} ≀ max (mk Ξ±) omega ^ c := begin transitivity mk {t : set (ulift.{u} nat βŠ• Ξ±) // mk t ≀ c}, { refine ⟨embedding.subtype_map _ _⟩, apply embedding.image, use sum.inr, apply sum.inr.inj, intros s hs, exact le_trans mk_image_le hs }, refine le_trans (mk_bounded_set_le_of_omega_le (ulift.{u} nat βŠ• Ξ±) c (le_add_right omega (mk Ξ±))) _, rw [max_comm, ←add_eq_max]; refl end lemma mk_bounded_subset_le {Ξ± : Type u} (s : set Ξ±) (c : cardinal.{u}) : mk {t : set Ξ± // t βŠ† s ∧ mk t ≀ c} ≀ max (mk s) omega ^ c := begin refine le_trans _ (mk_bounded_set_le s c), refine ⟨embedding.cod_restrict _ _ _⟩, use Ξ» t, subtype.val ⁻¹' t.1, { rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊒, refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_val]; assumption }, rintro ⟨t, h1t, h2t⟩, exact le_trans (mk_preimage_of_injective _ _ subtype.val_injective) h2t end /- compl -/ lemma mk_compl_of_omega_le {Ξ± : Type*} (s : set Ξ±) (h : omega ≀ #Ξ±) (h2 : #s < #Ξ±) : #(-s : set Ξ±) = #Ξ± := by { refine eq_of_add_eq_of_omega_le _ h2 h, exact mk_sum_compl s } lemma mk_compl_finset_of_omega_le {Ξ± : Type*} (s : finset Ξ±) (h : omega ≀ #Ξ±) : #(-s.to_set : set Ξ±) = #Ξ± := by { apply mk_compl_of_omega_le _ h, exact lt_of_lt_of_le (finset_card_lt_omega s) h } lemma mk_compl_eq_mk_compl_infinite {Ξ± : Type*} {s t : set Ξ±} (h : omega ≀ #Ξ±) (hs : #s < #Ξ±) (ht : #t < #Ξ±) : #(-s : set Ξ±) = #(-t : set Ξ±) := by { rw [mk_compl_of_omega_le s h hs, mk_compl_of_omega_le t h ht] } lemma mk_compl_eq_mk_compl_finite_lift {Ξ± : Type u} {Ξ² : Type v} {s : set Ξ±} {t : set Ξ²} (hΞ± : #Ξ± < omega) (h1 : lift.{u (max v w)} (#Ξ±) = lift.{v (max u w)} (#Ξ²)) (h2 : lift.{u (max v w)} (#s) = lift.{v (max u w)} (#t)) : lift.{u (max v w)} (#(-s : set Ξ±)) = lift.{v (max u w)} (#(-t : set Ξ²)) := begin have hΞ±' := hΞ±, have h1' := h1, rw [← mk_sum_compl s, ← mk_sum_compl t] at h1, rw [← mk_sum_compl s, add_lt_omega_iff] at hΞ±, lift #s to β„• using hΞ±.1 with n hn, lift #(- s : set Ξ±) to β„• using hΞ±.2 with m hm, have : #(- t : set Ξ²) < omega, { refine lt_of_le_of_lt (mk_subtype_le _) _, rw [← lift_lt, lift_omega, ← h1', ← lift_omega.{u (max v w)}, lift_lt], exact hΞ±' }, lift #(- t : set Ξ²) to β„• using this with k hk, simp [nat_eq_lift_eq_iff] at h2, rw [nat_eq_lift_eq_iff.{v (max u w)}] at h2, simp [h2.symm] at h1 ⊒, norm_cast at h1, simp at h1, exact h1 end lemma mk_compl_eq_mk_compl_finite {Ξ± Ξ² : Type u} {s : set Ξ±} {t : set Ξ²} (hΞ± : #Ξ± < omega) (h1 : #Ξ± = #Ξ²) (h : #s = #t) : #(-s : set Ξ±) = #(-t : set Ξ²) := by { rw [← lift_inj], apply mk_compl_eq_mk_compl_finite_lift hΞ±; rw [lift_inj]; assumption } lemma mk_compl_eq_mk_compl_finite_same {Ξ± : Type*} {s t : set Ξ±} (hΞ± : #Ξ± < omega) (h : #s = #t) : #(-s : set Ξ±) = #(-t : set Ξ±) := mk_compl_eq_mk_compl_finite hΞ± rfl h /- extend an injection to an equiv -/ theorem extend_function {Ξ± Ξ² : Type*} {s : set Ξ±} (f : s β†ͺ Ξ²) (h : nonempty ((-s : set Ξ±) ≃ (- range f : set Ξ²))) : βˆƒ (g : Ξ± ≃ Ξ²), βˆ€ x : s, g x = f x := begin intros, have := h, cases this with g, let h : Ξ± ≃ Ξ² := (set.sum_compl (s : set Ξ±)).symm.trans ((sum_congr (equiv.set.range f f.2) g).trans (set.sum_compl (range f))), refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx, equiv.symm] end theorem extend_function_finite {Ξ± Ξ² : Type*} {s : set Ξ±} (f : s β†ͺ Ξ²) (hs : #Ξ± < omega) (h : nonempty (Ξ± ≃ Ξ²)) : βˆƒ (g : Ξ± ≃ Ξ²), βˆ€ x : s, g x = f x := begin apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift hs h], rw [mk_range_eq_lift], exact f.2 end theorem extend_function_of_lt {Ξ± Ξ² : Type*} {s : set Ξ±} (f : s β†ͺ Ξ²) (hs : #s < #Ξ±) (h : nonempty (Ξ± ≃ Ξ²)) : βˆƒ (g : Ξ± ≃ Ξ²), βˆ€ x : s, g x = f x := begin cases (le_or_lt omega (#Ξ±)) with hΞ± hΞ±, { apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, cases cardinal.eq.mp (mk_compl_of_omega_le s hΞ± hs) with g2, cases cardinal.eq.mp (mk_compl_of_omega_le (range f) _ _) with g3, { constructor, exact g2.trans (g.trans g3.symm) }, { rw [← lift_le, ← h], refine le_trans _ (lift_le.mpr hΞ±), simp }, rwa [← lift_lt, ← h, mk_range_eq_lift, lift_lt], exact f.2 }, { exact extend_function_finite f hΞ± h } end end cardinal
1044a91117346ba6e39cf52b68a145f03ddab0a8
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/07_Induction_and_Recursion.org.22.lean
9dc6fca03181ed94def0a01c15b2da69349d2806
[]
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
283
lean
/- page 109 -/ import standard import data.nat logic open bool nat definition mult : nat β†’ nat β†’ nat := have plus : nat β†’ nat β†’ nat | 0 b := b | (succ a) b := succ (plus a b), have mult : nat β†’ nat β†’ nat | 0 b := 0 | (succ a) b := plus (mult a b) b, mult
24c52431906e1e2bff443a14aab0144ddfc3eb10
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/galois_connection.lean
655031dd3eca424f6ad61880942ef97c9613d2de
[ "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
7,523
lean
/- Copyright (c) 2016 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes HΓΆlzl Galois connections - order theoretic adjoints. -/ import standard local attribute classical.prop_decidable [instance] eq.ops algebra set function complete_lattice /- Move to set? -/ definition kern_image {X Y : Type} (f : X β†’ Y) (S : set X) : set Y := {y | βˆ€x, f x = y β†’ x ∈ S } /- Order theoretic definitions -/ /- TODO: move to order? -/ section order variables {A B : Type} {S : set A} {a a' : A} {b b' : B} {f : A β†’ B} [weak_order A] [weak_order B] definition increasing (f : A β†’ A) := βˆ€β¦ƒa⦄, a ≀ f a definition decreasing (f : A β†’ A) := βˆ€β¦ƒa⦄, f a ≀ a definition upper_bounds (S : set A) : set A := { x | βˆ€β‚€ s ∈ S, s ≀ x } definition lower_bounds (S : set A) : set A := { x | βˆ€β‚€ s ∈ S, x ≀ s } definition is_least (S : set A) (a : A) := a ∈ S ∧ a ∈ lower_bounds S definition is_greatest (S : set A) (a : A) := a ∈ S ∧ a ∈ upper_bounds S definition monotone (f : A β†’ B) := βˆ€β¦ƒa b⦄, a ≀ b β†’ f a ≀ f b lemma eq_of_is_least_of_is_least (Ha : is_least S a) (Hb : is_least S a') : a = a' := le.antisymm begin apply (and.elim_right Ha), apply (and.elim_left Hb) end begin apply (and.elim_right Hb), apply (and.elim_left Ha) end lemma is_least_iff_eq_of_is_least (Ha : is_least S a) : is_least S a' ↔ a = a' := iff.intro (eq_of_is_least_of_is_least Ha) begin intro H, cases H, apply Ha end lemma eq_of_is_greatest_of_is_greatest (Ha : is_greatest S a) (Hb : is_greatest S a') : a = a' := le.antisymm begin apply (and.elim_right Hb), apply (and.elim_left Ha) end begin apply (and.elim_right Ha), apply (and.elim_left Hb) end lemma is_greatest_iff_eq_of_is_greatest (Ha : is_greatest S a) : is_greatest S a' ↔ a = a' := iff.intro (eq_of_is_greatest_of_is_greatest Ha) begin intro H, cases H, apply Ha end definition is_lub (S : set A) := is_least (upper_bounds S) definition is_glb (S : set A) := is_greatest (lower_bounds S) lemma eq_of_is_lub_of_is_lub : is_lub S a β†’ is_lub S a' β†’ a = a' := !eq_of_is_least_of_is_least lemma is_lub_iff_eq_of_is_lub : is_lub S a β†’ (is_lub S a' ↔ a = a') := !is_least_iff_eq_of_is_least lemma eq_of_is_glb_of_is_glb : is_glb S a β†’ is_glb S a' β†’ a = a' := !eq_of_is_greatest_of_is_greatest lemma is_glb_iff_eq_of_is_glb : is_glb S a β†’ (is_glb S a' ↔ a = a') := !is_greatest_iff_eq_of_is_greatest lemma mem_upper_bounds_image (Hf : monotone f) (Ha : a ∈ upper_bounds S) : f a ∈ upper_bounds (f ' S) := bounded_forall_image_of_bounded_forall (take x H, Hf (Ha `x ∈ S`)) lemma mem_lower_bounds_image (Hf : monotone f) (Ha : a ∈ lower_bounds S) : f a ∈ lower_bounds (f ' S) := bounded_forall_image_of_bounded_forall (take x H, Hf (Ha `x ∈ S`)) end order definition galois_connection {A B : Type} [weak_order A] [weak_order B] (l : A β†’ B) (u : B β†’ A) := βˆ€{a b}, l a ≀ b ↔ a ≀ u b namespace galois_connection section parameters {A B : Type} [weak_order A] [weak_order B] (l : A β†’ B) (u : B β†’ A) lemma monotone_intro (Mu : monotone u) (Ml : monotone l) (Iul : increasing (u ∘ l)) (Dlu : decreasing (l ∘ u)) : galois_connection l u := begin intros a b, apply iff.intro, { intro H, apply le.trans, apply Iul, apply Mu, assumption }, { intro H, apply le.trans, apply Ml, assumption, apply Dlu } end parameter (gc : galois_connection l u) include gc lemma l_le {a : A} {b : B} : a ≀ u b β†’ l a ≀ b := and.elim_right !gc lemma le_u {a : A} {b : B} : l a ≀ b β†’ a ≀ u b := and.elim_left !gc lemma increasing_u_l : increasing (u ∘ l) := take a, le_u !le.refl lemma decreasing_l_u : decreasing (l ∘ u) := take a, l_le !le.refl lemma monotone_u : monotone u := take a b H, le_u (le.trans !decreasing_l_u H) lemma monotone_l : monotone l := take a b H, l_le (le.trans H !increasing_u_l) lemma u_l_u_eq_u : u ∘ l ∘ u = u := funext (take x, le.antisymm (monotone_u !decreasing_l_u) !increasing_u_l) lemma l_u_l_eq_l : l ∘ u ∘ l = l := funext (take x, le.antisymm !decreasing_l_u (monotone_l !increasing_u_l)) lemma u_mem_upper_bounds {S : set A} {b : B} (H : b ∈ upper_bounds (l ' S)) : u b ∈ upper_bounds S := take c, suppose c ∈ S, le_u (H (!mem_image_of_mem `c ∈ S`)) lemma l_mem_lower_bounds {S : set B} {a : A} (H : a ∈ lower_bounds (u ' S)) : l a ∈ lower_bounds S := take c, suppose c ∈ S, l_le (H (!mem_image_of_mem `c ∈ S`)) lemma is_lub_l_image {S : set A} {a : A} (H : is_lub S a) : is_lub (l ' S) (l a) := and.intro (mem_upper_bounds_image monotone_l (and.elim_left `is_lub S a`)) (take b Hb, l_le (and.elim_right `is_lub S a` _ (u_mem_upper_bounds Hb))) lemma is_glb_u_image {S : set B} {b : B} (H : is_glb S b) : is_glb (u ' S) (u b) := and.intro (mem_lower_bounds_image monotone_u (and.elim_left `is_glb S b`)) (take a Ha, le_u (and.elim_right `is_glb S b` _ (l_mem_lower_bounds Ha))) lemma is_glb_l {a : A} : is_glb { b | a ≀ u b } (l a) := begin apply and.intro, { intro b, apply l_le }, { intro b H, apply H, apply increasing_u_l } end lemma is_lub_u {b : B} : is_lub { a | l a ≀ b } (u b) := begin apply and.intro, { intro a, apply le_u }, { intro a H, apply H, apply decreasing_l_u } end end /- Constructing Galois connections -/ protected lemma id {A : Type} [weak_order A] : @galois_connection A A _ _ id id := take a b, iff.intro (Ξ»x, x) (Ξ»x, x) protected lemma dual {A B : Type} [woA : weak_order A] [woB : weak_order B] (l : A β†’ B) (u : B β†’ A) (gc : galois_connection l u) : @galois_connection B A (weak_order_dual woB) (weak_order_dual woA) u l := take a b, begin apply iff.symm, rewrite le_dual_eq_le, rewrite le_dual_eq_le, exact gc, end protected lemma compose {A B C : Type} [weak_order A] [weak_order B] [weak_order C] (l1 : A β†’ B) (u1 : B β†’ A) (l2 : B β†’ C) (u2 : C β†’ B) (gc1 : galois_connection l1 u1) (gc2 : galois_connection l2 u2) : galois_connection (l2 ∘ l1) (u1 ∘ u2) := by intros; rewrite gc2; rewrite gc1 section variables {A B : Type} {f : A β†’ B} protected lemma image_preimage : galois_connection (image f) (preimage f) := @image_subset_iff A B f protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := begin intros X Y, apply iff.intro, all_goals (intro H x Hx), { intro x' eq, apply H, cases eq, exact Hx }, { apply H, esimp [preimage, mem, set_of] at Hx, exact Hx, -- TODO: why is esimp necessary? exact rfl } end end end galois_connection /- Bounds on complete lattices -/ /- TODO: move to complete lattices? -/ section variables {A : Type} (S : set A) {a b : A} [complete_lattice A] lemma is_lub_sup : is_lub '{a, b} (sup a b) := and.intro begin xrewrite [+bounded_forall_insert_iff, bounded_forall_empty_iff, and_true], exact (and.intro !le_sup_left !le_sup_right) end begin intro x Hx, xrewrite [+bounded_forall_insert_iff at Hx, bounded_forall_empty_iff at Hx, and_true at Hx], apply sup_le, apply (and.elim_left Hx), apply (and.elim_right Hx), end lemma is_lub_Sup : is_lub S (⨆S) := and.intro (take x, le_Sup) (take x, Sup_le) lemma is_lub_iff_Sup_eq {a : A} : is_lub S a ↔ (⨆S) = a := !is_lub_iff_eq_of_is_lub !is_lub_Sup lemma is_glb_Inf : is_glb S (β¨…S) := and.intro (take a, Inf_le) (take a, le_Inf) lemma is_glb_iff_Inf_eq : is_glb S a ↔ (β¨…S) = a := !is_glb_iff_eq_of_is_glb !is_glb_Inf end
c6fec4d89f4b7c8bcfbaf83fb0b99df06c3c6058
618003631150032a5676f229d13a079ac875ff77
/test/equiv_rw.lean
79ac8bf1cd42f6265f4ff2deaab6482b67923108
[ "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
8,885
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.equiv_rw import control.equiv_functor.instances -- these make equiv_rw more powerful! -- Uncomment this line to observe the steps of constructing appropriate equivalences. -- set_option trace.equiv_rw_type true -- Rewriting a hypothesis along an equivalence. example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (f : Ξ± β†’ β„•) (h : βˆ€ b : Ξ², f (e.symm b) = 0) (i : Ξ±) : f i = 0 := begin equiv_rw e at i, apply h, end -- Check that dependent hypotheses are reverted and reintroduced. example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (Z : Ξ± β†’ Type) (f : Ξ  a, Z a β†’ β„•) (h : βˆ€ (b : Ξ²) (x : Z (e.symm b)), f (e.symm b) x = 0) (i : Ξ±) (x : Z i) : f i x = 0 := begin equiv_rw e at i, guard_hyp i := Ξ², guard_target f (e.symm i) x = 0, guard_hyp x := Z ((e.symm) i), exact h i x, end -- Rewriting the goal along an equivalence. example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (b : Ξ²) : Ξ± := begin equiv_rw e, exact b, end -- Fail if the equivalence can't be used. example {Ξ± Ξ² Ξ³ : Type} (e : Ξ² ≃ Ξ³) (a : Ξ±) : Ξ± := begin success_if_fail { equiv_rw e at a }, success_if_fail { equiv_rw e }, exact a, end -- Verify that `equiv_rw` will rewrite under `equiv_functor` instances. example {Ξ± Ξ² : Type} (u : unique Ξ±) (e : Ξ± ≃ Ξ²) : Ξ² := begin equiv_rw e at u, apply inhabited.default, end example {Ξ± Ξ² : Type} (p : equiv.perm Ξ±) (e : Ξ± ≃ Ξ²) : equiv.perm Ξ² := begin equiv_rw e at p, exact p, end -- We can rewrite the goal under functors. example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (b : Ξ²) : option Ξ± := begin equiv_rw e, exact some b, end -- We can rewrite hypotheses under functors. example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (b : option Ξ±) : option Ξ² := begin equiv_rw e at b, exact b, end -- We can rewrite hypotheses under compositions of functors. example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (b : list (list Ξ±)) : list Ξ² := begin equiv_rw e at b, exact b.join, end -- Check that we can rewrite in the target position of function types. example {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (f : Ξ³ β†’ Ξ²) : Ξ³ β†’ Ξ± := begin equiv_rw e, exact f, end -- Check that we can rewrite in the source position of function types. example {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (f : Ξ² β†’ Ξ³) : Ξ± β†’ Ξ³ := begin equiv_rw e, exact f, end -- Rewriting under multiple functors. example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (b : Ξ²) : list (option Ξ±) := begin equiv_rw e, exact [none, some b], end -- Rewriting under multiple functors, including functions. example {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (b : Ξ²) : Ξ³ β†’ list (option Ξ±) := begin equiv_rw e, exact (Ξ» g, [none, some b]), end -- Rewriting in multiple positions. example {Ξ± Ξ² : Type*} [has_add Ξ²] (e : Ξ± ≃ Ξ²) : Ξ± β†’ Ξ± := begin have : (Ξ± β†’ Ξ±) ≃ _, { apply equiv.arrow_congr, apply e, apply e, }, equiv_rw e, exact (@id Ξ²), end -- Rewriting in multiple positions. example {Ξ± Ξ² : Type} [has_add Ξ²] (e : Ξ± ≃ Ξ²) : Ξ² β†’ Ξ± β†’ Ξ± := begin equiv_rw e, exact (+), end -- Rewriting in multiple positions. example {Ξ± Ξ² : Type} [has_add Ξ²] (e : Ξ± ≃ Ξ²) : Ξ± β†’ Ξ± β†’ Ξ± := begin equiv_rw e, exact (+), end example {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (s : Ξ² βŠ• Ξ³) : Ξ± βŠ• Ξ³ := begin equiv_rw e, exact s, end example {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (s : Ξ² βŠ• Ξ³) : (Ξ± βŠ• Ξ³) Γ— (Ξ³ βŠ• Ξ±) := begin equiv_rw e, exact (s, s.swap), end example {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (s : Ξ± βŠ• Ξ³) : (Ξ² βŠ• Ξ³) Γ— (Ξ³ βŠ• Ξ²) := begin equiv_rw e at s, exact (s, s.swap), end example {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (s : (Ξ± βŠ• Ξ³) Γ— Ξ²) : (Ξ² βŠ• Ξ³) := begin success_if_fail { equiv_rw e at s {max_depth := 4} }, equiv_rw e at s, exact s.1, end -- Test generating the actual equivalence using `equiv_rw_type`. example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (b : Ξ²) : Ξ± Γ— (β„• βŠ• β„•) := begin have e' : Ξ± Γ— (β„• βŠ• β„•) ≃ _ := by equiv_rw_type e, apply e'.inv_fun, exact (b, sum.inl 0) end example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (P : Ξ± β†’ Prop) (h : { a // P a }) : Ξ² := begin equiv_rw e at h, exact h.val, end example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (P : Ξ± β†’ Prop) (h : βˆ€ a, P a) (b : Ξ²) : { a // P a } := begin equiv_rw e, use b, apply h, end example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (P : Ξ± β†’ Prop) (h : βˆ€ a : Ξ±, P a) (b : Ξ²) : P (e.symm b) := begin equiv_rw e.symm at b, exact h b, end example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (P : Ξ± β†’ Sort*) (h : Ξ  a : Ξ±, P a) (b : Ξ²) : P (e.symm b) := begin -- this is a bit perverse, as `equiv_rw e.symm at b` is more natural, -- but this tests rewriting in the argument of a dependent function equiv_rw e at h, exact h _, end -- a poor example, rewriting in the base of a dependent pair example {Ξ± Ξ² : Type} (P : Ξ± β†’ Type) (h : Ξ£ a, P a) (e : Ξ± ≃ Ξ²) : Ξ² := begin equiv_rw e at h, exact h.1 end -- rewriting in the argument of a dependent function can't be done in one step example {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (P : Ξ± β†’ Type*) (h : Ξ  a : Ξ±, (P a) Γ— (option Ξ±)) (b : Ξ²) : option Ξ² := begin equiv_rw e at h, have t := h b, equiv_rw e at t, exact t.2, end -- Demonstrate using `equiv_rw` to build new instances of `equiv_functor` -- Observe that the next three declarations could easily be implemented by a tactic. -- This has been automated in the `transport` branch, -- so we won't attempt to write a deriver handler until we join with that. def semigroup.map {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) : semigroup Ξ± β†’ semigroup Ξ² := begin intro S, refine_struct { .. }, -- transport data fields using `equiv_rw` { have mul := S.mul, equiv_rw e at mul, -- This `equiv_rw` performs the following steps: -- have e' := (equiv.arrow_congr' e (equiv.arrow_congr' e e)), -- have h := (e'.symm_apply_apply mul).symm, -- revert h, -- generalize : (e' mul) = mul', -- intro h, -- clear_dependent mul, -- rename mul' mul, exact mul, }, -- transport axioms by simplifying, and applying the original axiom { intros, dsimp, simp, apply S.mul_assoc, } end example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (S : semigroup Ξ±) : (semigroup.map e S).mul = (equiv.arrow_congr' e (equiv.arrow_congr' e e)) has_mul.mul := rfl example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (S : semigroup Ξ±) (x y : Ξ²) : begin haveI := semigroup.map e S, exact x * y = e (e.symm x * e.symm y) end := rfl attribute [ext] semigroup lemma semigroup.id_map (Ξ± : Type) : semigroup.map (equiv.refl Ξ±) = id := by { ext, refl, } lemma semigroup.map_map {Ξ± Ξ² Ξ³ : Type} (e : Ξ± ≃ Ξ²) (f : Ξ² ≃ Ξ³) : semigroup.map (e.trans f) = (semigroup.map f) ∘ (semigroup.map e) := by { ext, dsimp [semigroup.map], simp, } -- TODO (after joining the `transport` branch) create a derive handler for this instance : equiv_functor semigroup := { map := Ξ» Ξ± Ξ² e, semigroup.map e, map_refl' := semigroup.id_map, map_trans' := Ξ» Ξ± Ξ² Ξ³ e f, semigroup.map_map e f, } -- Verify that we can now use `equiv_rw` under `semigroup`: example {Ξ± : Type} [I : semigroup Ξ±] {Ξ² : Type} (e : Ξ± ≃ Ξ²) : semigroup Ξ² := begin equiv_rw e at I, exact I, end -- Now we do `monoid`, to try out a structure with constants. -- The constructions and proofs here are written as uniformly as possible. -- This example is the blueprint for the `transport` tactic. mk_simp_attribute transport_simps "simps useful inside `transport`" attribute [transport_simps] eq_rec_constant eq_mpr_rfl equiv.to_fun_as_coe equiv.arrow_congr'_apply equiv.symm_apply_apply equiv.apply_eq_iff_eq_symm_apply def monoid.map {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (S : monoid Ξ±) : monoid Ξ² := begin refine_struct { .. }, { have mul := S.mul, equiv_rw e at mul, exact mul, }, { try { unfold_projs }, simp only [] with transport_simps, have mul_assoc := S.mul_assoc, equiv_rw e at mul_assoc, solve_by_elim, }, { have one := S.one, equiv_rw e at one, exact one, }, { try { unfold_projs }, simp only [] with transport_simps, have one_mul := S.one_mul, equiv_rw e at one_mul, solve_by_elim, }, { try { unfold_projs }, simp only [] with transport_simps, have mul_one := S.mul_one, equiv_rw e at mul_one, solve_by_elim, }, end example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (S : monoid Ξ±) : (monoid.map e S).mul = (equiv.arrow_congr' e (equiv.arrow_congr' e e)) has_mul.mul := rfl example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (S : monoid Ξ±) (x y : Ξ²) : begin haveI := monoid.map e S, exact x * y = e (e.symm x * e.symm y) end := rfl example {Ξ± Ξ² : Type} (e : Ξ± ≃ Ξ²) (S : monoid Ξ±) : begin haveI := monoid.map e S, exact (1 : Ξ²) = e (1 : Ξ±) end := rfl
ab4da81974e08c25a92b3c87eb8b7a83ef7d39ac
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/standard/function.lean
3a31501883ec296dfa0c1e747e35019013945437
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
1,628
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura namespace function section parameters {A : Type} {B : Type} {C : Type} {D : Type} {E : Type} abbreviation compose (f : B β†’ C) (g : A β†’ B) : A β†’ C := Ξ»x, f (g x) abbreviation id (a : A) : A := a abbreviation on_fun (f : B β†’ B β†’ C) (g : A β†’ B) : A β†’ A β†’ C := Ξ»x y, f (g x) (g y) abbreviation combine (f : A β†’ B β†’ C) (op : C β†’ D β†’ E) (g : A β†’ B β†’ D) : A β†’ B β†’ E := Ξ»x y, op (f x y) (g x y) end abbreviation const {A : Type} (B : Type) (a : A) : B β†’ A := Ξ»x, a abbreviation dcompose {A : Type} {B : A β†’ Type} {C : Ξ  {x : A}, B x β†’ Type} (f : Ξ  {x : A} (y : B x), C y) (g : Ξ x, B x) : Ξ x, C (g x) := Ξ»x, f (g x) abbreviation flip {A : Type} {B : Type} {C : A β†’ B β†’ Type} (f : Ξ x y, C x y) : Ξ y x, C x y := Ξ»y x, f x y abbreviation app {A : Type} {B : A β†’ Type} (f : Ξ x, B x) (x : A) : B x := f x -- Yet another trick to anotate an expression with a type abbreviation is_typeof (A : Type) (a : A) : A := a precedence `∘`:60 precedence `∘'`:60 precedence `on`:1 precedence `$`:1 precedence `-[`:1 precedence `]-`:1 precedence `⟨`:1 infixr ∘ := compose infixr ∘' := dcompose infixl on := on_fun notation `typeof` t `:` T := is_typeof T t infixr $ := app notation f `-[` op `]-` g := combine f op g -- Trick for using any binary function as infix operator notation a `⟨` f `⟩` b := f a b end
c1149952baaec27d38ec05d3cbcca65d38cc5706
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/upto.lean
f0975f5c3700e998d6b4a92da655ad5cc66d258a
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,300
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.data.nat.basic import Mathlib.PostPort namespace Mathlib /-! # `nat.upto` `nat.upto p`, with `p` a predicate on `β„•`, is a subtype of elements `n : β„•` such that no value (strictly) below `n` satisfies `p`. This type has the property that `>` is well-founded when `βˆƒ i, p i`, which allows us to implement searches on `β„•`, starting at `0` and with an unknown upper-bound. It is similar to the well founded relation constructed to define `nat.find` with the difference that, in `nat.upto p`, `p` does not need to be decidable. In fact, `nat.find` could be slightly altered to factor decidability out of its well founded relation and would then fulfill the same purpose as this file. -/ namespace nat /-- The subtype of natural numbers `i` which have the property that no `j` less than `i` satisfies `p`. This is an initial segment of the natural numbers, up to and including the first value satisfying `p`. We will be particularly interested in the case where there exists a value satisfying `p`, because in this case the `>` relation is well-founded. -/ def upto (p : β„• β†’ Prop) := Subtype fun (i : β„•) => βˆ€ (j : β„•), j < i β†’ Β¬p j namespace upto /-- Lift the "greater than" relation on natural numbers to `nat.upto`. -/ protected def gt (p : β„• β†’ Prop) (x : upto p) (y : upto p) := subtype.val x > subtype.val y protected instance has_lt {p : β„• β†’ Prop} : HasLess (upto p) := { Less := fun (x y : upto p) => subtype.val x < subtype.val y } /-- The "greater than" relation on `upto p` is well founded if (and only if) there exists a value satisfying `p`. -/ protected theorem wf {p : β„• β†’ Prop} : (βˆƒ (x : β„•), p x) β†’ well_founded (upto.gt p) := sorry /-- Zero is always a member of `nat.upto p` because it has no predecessors. -/ def zero {p : β„• β†’ Prop} : upto p := { val := 0, property := sorry } /-- The successor of `n` is in `nat.upto p` provided that `n` doesn't satisfy `p`. -/ def succ {p : β„• β†’ Prop} (x : upto p) (h : Β¬p (subtype.val x)) : upto p := { val := Nat.succ (subtype.val x), property := sorry }
2a724c2c495e51973695e3beffceeb7af8b66169
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/MetavarContext.lean
a21889ea8dcc0ccc15b40ac4fc2dd1d7e34627ac
[ "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
62,534
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.MonadCache import Lean.LocalContext namespace Lean /-! The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown above. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called "tmp" metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we may want to allow TC to invoke tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics in the future. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constraint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the synthesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variable `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contains `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction between temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ /-- `LocalInstance` represents a local typeclass instance registered by and for the elaborator. It stores the name of the typeclass in `className`, and the concrete typeclass instance in `fvar`. Note that the kernel does not care about this information, since typeclasses are entirely eliminated during elaboration. -/ structure LocalInstance where className : Name fvar : Expr deriving Inhabited abbrev LocalInstances := Array LocalInstance instance : BEq LocalInstance where beq i₁ iβ‚‚ := i₁.fvar == iβ‚‚.fvar /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts inductive MetavarKind where | natural | synthetic | syntheticOpaque deriving Inhabited, Repr def MetavarKind.isSyntheticOpaque : MetavarKind β†’ Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind β†’ Bool | MetavarKind.natural => true | _ => false structure MetavarDecl where userName : Name := Name.anonymous lctx : LocalContext type : Expr /-- The nesting depth of this metavariable. We do not want unification subproblems to influence the results of parent problems. The depth keeps track of this information and ensures that unification subproblems cannot leak information out, by unifying based on depth. -/ depth : Nat localInstances : LocalInstances kind : MetavarKind numScopeArgs : Nat := 0 -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` index : Nat -- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext` deriving Inhabited /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => (mkMVar mvarIdPending))`. `mvarIdPending` is a `syntheticOpaque` metavariable that has not been synthesized yet. The delayed assignment becomes a real one as soon as `mvarIdPending` has been fully synthesized. `fvars` are variables in the `mvarIdPending` local context. See the comment below `assignDelayedMVar ` for the rationale of delayed assignments. Recall that we use a locally nameless approach when dealing with binders. Suppose we are trying to synthesize `?n` in the expression `e`, in the context of `(fun x => e)`. The metavariable `?n` might depend on the bound variable `x`. However, since we are locally nameless, the bound variable `x` is in fact represented by some free variable `fvar_x`. Thus, when we exit the scope, we must rebind the value of `fvar_x` in `?n` to the de-bruijn index of the bound variable `x`. -/ structure DelayedMetavarAssignment where fvars : Array Expr mvarIdPending : MVarId open Std (HashMap PersistentHashMap) structure MetavarContext where depth : Nat := 0 mvarCounter : Nat := 0 -- Counter for setting the field `index` at `MetavarDecl` lDepth : PersistentHashMap LMVarId Nat := {} decls : PersistentHashMap MVarId MetavarDecl := {} userNames : PersistentHashMap Name MVarId := {} lAssignment : PersistentHashMap LMVarId Level := {} eAssignment : PersistentHashMap MVarId Expr := {} dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {} class MonadMCtx (m : Type β†’ Type) where getMCtx : m MetavarContext modifyMCtx : (MetavarContext β†’ MetavarContext) β†’ m Unit export MonadMCtx (getMCtx modifyMCtx) instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where getMCtx := liftM (getMCtx : m _) modifyMCtx := fun f => liftM (modifyMCtx f : m _) abbrev setMCtx [MonadMCtx m] (mctx : MetavarContext) : m Unit := modifyMCtx fun _ => mctx abbrev getLevelMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m (Option Level) := return (← getMCtx).lAssignment.find? mvarId def MetavarContext.getExprAssignmentCore? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId def getExprMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : MVarId) : m (Option Expr) := return (← getMCtx).getExprAssignmentCore? mvarId def getDelayedMVarAssignment? [Monad m] [MonadMCtx m] (mvarId : MVarId) : m (Option DelayedMetavarAssignment) := return (← getMCtx).dAssignment.find? mvarId /-- Given a sequence of delayed assignments ``` mvarId₁ := mvarIdβ‚‚ ...; ... mvarIdβ‚™ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedMVarRoot [Monad m] [MonadMCtx m] (mvarId : MVarId) : m MVarId := do match (← getDelayedMVarAssignment? mvarId) with | some d => getDelayedMVarRoot d.mvarIdPending | none => return mvarId def isLevelMVarAssigned [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m Bool := return (← getMCtx).lAssignment.contains mvarId /-- Return `true` if the give metavariable is already assigned. -/ def _root_.Lean.MVarId.isAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := return (← getMCtx).eAssignment.contains mvarId @[deprecated MVarId.isAssigned] def isExprMVarAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isAssigned def _root_.Lean.MVarId.isDelayedAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := return (← getMCtx).dAssignment.contains mvarId @[deprecated MVarId.isDelayedAssigned] def isMVarDelayedAssigned [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isDelayedAssigned def isLevelMVarAssignable [Monad m] [MonadMCtx m] (mvarId : LMVarId) : m Bool := do let mctx ← getMCtx match mctx.lDepth.find? mvarId with | some d => return d == mctx.depth | _ => panic! "unknown universe metavariable" def MetavarContext.getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def _root_.Lean.MVarId.isAssignable [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do let mctx ← getMCtx let decl := mctx.getDecl mvarId return decl.depth == mctx.depth @[deprecated MVarId.isAssignable] def isExprMVarAssignable [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Bool := do mvarId.isAssignable /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar [Monad m] [MonadMCtx m] : Level β†’ m Bool | .succ lvl => pure lvl.hasMVar <&&> hasAssignedLevelMVar lvl | .max lvl₁ lvlβ‚‚ => (pure lvl₁.hasMVar <&&> hasAssignedLevelMVar lvl₁) <||> (pure lvlβ‚‚.hasMVar <&&> hasAssignedLevelMVar lvlβ‚‚) | .imax lvl₁ lvlβ‚‚ => (pure lvl₁.hasMVar <&&> hasAssignedLevelMVar lvl₁) <||> (pure lvlβ‚‚.hasMVar <&&> hasAssignedLevelMVar lvlβ‚‚) | .mvar mvarId => isLevelMVarAssigned mvarId | .zero => pure false | .param _ => pure false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar [Monad m] [MonadMCtx m] : Expr β†’ m Bool | .const _ lvls => lvls.anyM hasAssignedLevelMVar | .sort lvl => hasAssignedLevelMVar lvl | .app f a => (pure f.hasMVar <&&> hasAssignedMVar f) <||> (pure a.hasMVar <&&> hasAssignedMVar a) | .letE _ t v b _ => (pure t.hasMVar <&&> hasAssignedMVar t) <||> (pure v.hasMVar <&&> hasAssignedMVar v) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .forallE _ d b _ => (pure d.hasMVar <&&> hasAssignedMVar d) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .lam _ d b _ => (pure d.hasMVar <&&> hasAssignedMVar d) <||> (pure b.hasMVar <&&> hasAssignedMVar b) | .fvar _ => return false | .bvar _ => return false | .lit _ => return false | .mdata _ e => pure e.hasMVar <&&> hasAssignedMVar e | .proj _ _ e => pure e.hasMVar <&&> hasAssignedMVar e | .mvar mvarId => mvarId.isAssigned <||> mvarId.isDelayedAssigned /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar [Monad m] [MonadMCtx m] : Level β†’ m Bool | .succ lvl => pure lvl.hasMVar <&&> hasAssignableLevelMVar lvl | .max lvl₁ lvlβ‚‚ => (pure lvl₁.hasMVar <&&> hasAssignableLevelMVar lvl₁) <||> (pure lvlβ‚‚.hasMVar <&&> hasAssignableLevelMVar lvlβ‚‚) | .imax lvl₁ lvlβ‚‚ => (pure lvl₁.hasMVar <&&> hasAssignableLevelMVar lvl₁) <||> (pure lvlβ‚‚.hasMVar <&&> hasAssignableLevelMVar lvlβ‚‚) | .mvar mvarId => isLevelMVarAssignable mvarId | .zero => return false | .param _ => return false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar [Monad m] [MonadMCtx m] : Expr β†’ m Bool | .const _ lvls => lvls.anyM hasAssignableLevelMVar | .sort lvl => hasAssignableLevelMVar lvl | .app f a => (pure f.hasMVar <&&> hasAssignableMVar f) <||> (pure a.hasMVar <&&> hasAssignableMVar a) | .letE _ t v b _ => (pure t.hasMVar <&&> hasAssignableMVar t) <||> (pure v.hasMVar <&&> hasAssignableMVar v) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .forallE _ d b _ => (pure d.hasMVar <&&> hasAssignableMVar d) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .lam _ d b _ => (pure d.hasMVar <&&> hasAssignableMVar d) <||> (pure b.hasMVar <&&> hasAssignableMVar b) | .fvar _ => return false | .bvar _ => return false | .lit _ => return false | .mdata _ e => pure e.hasMVar <&&> hasAssignableMVar e | .proj _ _ e => pure e.hasMVar <&&> hasAssignableMVar e | .mvar mvarId => mvarId.isAssignable /-- Add `mvarId := u` to the universe metavariable assignment. This method does not check whether `mvarId` is already assigned, nor it checks whether a cycle is being introduced. This is a low-level API, and it is safer to use `isLevelDefEq (mkLevelMVar mvarId) u`. -/ def assignLevelMVar [MonadMCtx m] (mvarId : LMVarId) (val : Level) : m Unit := modifyMCtx fun m => { m with lAssignment := m.lAssignment.insert mvarId val } /-- Add `mvarId := x` to the metavariable assignment. This method does not check whether `mvarId` is already assigned, nor it checks whether a cycle is being introduced, or whether the expression has the right type. This is a low-level API, and it is safer to use `isDefEq (mkMVar mvarId) x`. -/ def _root_.Lean.MVarId.assign [MonadMCtx m] (mvarId : MVarId) (val : Expr) : m Unit := modifyMCtx fun m => { m with eAssignment := m.eAssignment.insert mvarId val } @[deprecated MVarId.assign] def assignExprMVar [MonadMCtx m] (mvarId : MVarId) (val : Expr) : m Unit := mvarId.assign val def assignDelayedMVar [MonadMCtx m] (mvarId : MVarId) (fvars : Array Expr) (mvarIdPending : MVarId) : m Unit := modifyMCtx fun m => { m with dAssignment := m.dAssignment.insert mvarId { fvars, mvarIdPending } } /-- Notes on artificial eta-expanded terms due to metavariables. We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator. This kind of term may be generated when instantiating metavariable assignments. This module tries to avoid their generation because they often introduce unnecessary dependencies and may affect automation. When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y` are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression `fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`. We address this issue by create a synthetic metavariable `?n : Nat β†’ Nat` and adding the delayed assignment `?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to `?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`. To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module. This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`. -/ partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level β†’ m Level | lvl@(Level.succ lvl₁) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvlβ‚‚) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvlβ‚‚) | lvl@(Level.imax lvl₁ lvlβ‚‚) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvlβ‚‚) | lvl@(Level.mvar mvarId) => do match (← getLevelMVarAssignment? mvarId) with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl assignLevelMVar mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld Ο‰ m] [MonadLiftT (ST Ο‰) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => do match e with | .proj _ _ s => return e.updateProj! (← instantiateExprMVars s) | .forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | .lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | .letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | .const _ lvls => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | .sort lvl => return e.updateSort! (← instantiateLevelMVars lvl) | .mdata _ b => return e.updateMData! (← instantiateExprMVars b) | .app .. => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT ExprStructEq Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | .mvar mvarId => match (← getDelayedMVarAssignment? mvarId) with | none => instApp | some { fvars, mvarIdPending } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars (mkMVar mvarIdPending) if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure result | _ => instApp | e@(.mvar mvarId) => checkCache { val := e : ExprStructEq } fun _ => do match (← getExprMVarAssignment? mvarId) with | some newE => do let newE' ← instantiateExprMVars newE mvarId.assign newE' pure newE' | none => pure e | e => pure e instance : MonadMCtx (StateRefT MetavarContext (ST Ο‰)) where getMCtx := get modifyMCtx := modify def instantiateMVarsCore (mctx : MetavarContext) (e : Expr) : Expr Γ— MetavarContext := let instantiate {Ο‰} (e : Expr) : (MonadCacheT ExprStructEq Expr <| StateRefT MetavarContext (ST Ο‰)) Expr := instantiateExprMVars e runST fun _ => instantiate e |>.run |>.run mctx def instantiateMVars [Monad m] [MonadMCtx m] (e : Expr) : m Expr := do if !e.hasMVar then return e else let (r, mctx) := instantiateMVarsCore (← getMCtx) e modifyMCtx fun _ => mctx return r def instantiateLCtxMVars [Monad m] [MonadMCtx m] (lctx : LocalContext) : m LocalContext := lctx.foldlM (init := {}) fun lctx ldecl => do match ldecl with | .cdecl _ fvarId userName type bi => let type ← instantiateMVars type return lctx.mkLocalDecl fvarId userName type bi | .ldecl _ fvarId userName type value nonDep => let type ← instantiateMVars type let value ← instantiateMVars value return lctx.mkLetDecl fvarId userName type value nonDep def instantiateMVarDeclMVars [Monad m] [MonadMCtx m] (mvarId : MVarId) : m Unit := do let mvarDecl := (← getMCtx).getDecl mvarId let lctx ← instantiateLCtxMVars mvarDecl.lctx let type ← instantiateMVars mvarDecl.type modifyMCtx fun mctx => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx, type } } def instantiateLocalDeclMVars [Monad m] [MonadMCtx m] (localDecl : LocalDecl) : m LocalDecl := do match localDecl with | .cdecl idx id n type bi => return .cdecl idx id n (← instantiateMVars type) bi | .ldecl idx id n type val nonDep => return .ldecl idx id n (← instantiateMVars type) (← instantiateMVars val) nonDep namespace DependsOn structure State where visited : ExprSet := {} mctx : MetavarContext private abbrev M := StateM State instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } private def shouldVisit (e : Expr) : M Bool := do if !e.hasMVar && !e.hasFVar then return false else if (← get).visited.contains e then return false else modify fun s => { s with visited := s.visited.insert e } return true @[specialize] private partial def dep (pf : FVarId β†’ Bool) (pm : MVarId β†’ Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitApp : Expr β†’ M Bool | .app f a .. => visitApp f <||> visit a | e => visit e, visitMain : Expr β†’ M Bool | .proj _ _ s => visit s | .forallE _ d b _ => visit d <||> visit b | .lam _ d b _ => visit d <||> visit b | .letE _ t v b _ => visit t <||> visit v <||> visit b | .mdata _ b => visit b | e@(.app ..) => do let f := e.getAppFn if f.isMVar then let e' ← instantiateMVars e if e'.getAppFn != f then visitMain e' else if pm f.mvarId! then return true else visitApp e else visitApp e | .mvar mvarId => do match (← getExprMVarAssignment? mvarId) with | some a => visit a | none => if pm mvarId then return true else let lctx := (← getMCtx).getDecl mvarId |>.lctx return lctx.any fun decl => pf decl.fvarId | .fvar fvarId => return pf fvarId | _ => pure false visit e @[inline] partial def main (pf : FVarId β†’ Bool) (pm : MVarId β†’ Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep pf pm e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `pf x` is `true`, or an unassigned metavariable `?m` s.t. `pm ?m` is true. For each metavariable `?m` (that does not satisfy `pm` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn [Monad m] [MonadMCtx m] (e : Expr) (pf : FVarId β†’ Bool := fun _ => false) (pm : MVarId β†’ Bool := fun _ => false) : m Bool := do let (result, { mctx, .. }) := DependsOn.main pf pm e |>.run { mctx := (← getMCtx) } setMCtx mctx return result /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `pf x` is `true` or an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ @[inline] def findLocalDeclDependsOn [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (pf : FVarId β†’ Bool := fun _ => false) (pm : MVarId β†’ Bool := fun _ => false) : m Bool := do match localDecl with | .cdecl (type := t) .. => findExprDependsOn t pf pm | .ldecl (type := t) (value := v) .. => let (result, { mctx, .. }) := (DependsOn.main pf pm t <||> DependsOn.main pf pm v).run { mctx := (← getMCtx) } setMCtx mctx return result def exprDependsOn [Monad m] [MonadMCtx m] (e : Expr) (fvarId : FVarId) : m Bool := findExprDependsOn e (fvarId == Β·) /-- Return true iff `e` depends on the free variable `fvarId` -/ def dependsOn [Monad m] [MonadMCtx m] (e : Expr) (fvarId : FVarId) : m Bool := exprDependsOn e fvarId /-- Return true iff `e` depends on the free variable `fvarId` -/ def localDeclDependsOn [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (fvarId : FVarId) : m Bool := findLocalDeclDependsOn localDecl (fvarId == Β·) /-- Similar to `exprDependsOn`, but `x` can be a free variable or an unassigned metavariable. -/ def exprDependsOn' [Monad m] [MonadMCtx m] (e : Expr) (x : Expr) : m Bool := if x.isFVar then findExprDependsOn e (x.fvarId! == Β·) else if x.isMVar then findExprDependsOn e (pm := (x.mvarId! == Β·)) else return false /-- Similar to `localDeclDependsOn`, but `x` can be a free variable or an unassigned metavariable. -/ def localDeclDependsOn' [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (x : Expr) : m Bool := if x.isFVar then findLocalDeclDependsOn localDecl (x.fvarId! == Β·) else if x.isMVar then findLocalDeclDependsOn localDecl (pm := (x.mvarId! == Β·)) else return false /-- Return true iff `e` depends on a free variable `x` s.t. `pf x`, or an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ def dependsOnPred [Monad m] [MonadMCtx m] (e : Expr) (pf : FVarId β†’ Bool := fun _ => false) (pm : MVarId β†’ Bool := fun _ => false) : m Bool := findExprDependsOn e pf pm /-- Return true iff the local declaration `localDecl` depends on a free variable `x` s.t. `pf x`, an unassigned metavariable `?m` s.t. `pm ?m` is true. -/ def localDeclDependsOnPred [Monad m] [MonadMCtx m] (localDecl : LocalDecl) (pf : FVarId β†’ Bool := fun _ => false) (pm : MVarId β†’ Bool := fun _ => false) : m Bool := do findLocalDeclDependsOn localDecl pf pm namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit β†’ MetavarContext := fun _ => {} /-- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with mvarCounter := mctx.mvarCounter + 1 decls := mctx.decls.insert mvarId { depth := mctx.depth index := mctx.mvarCounter userName lctx localInstances type kind numScopeArgs } userNames := if userName.isAnonymous then mctx.userNames else mctx.userNames.insert userName mvarId } def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /-- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : LMVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := mctx.userNames.find? userName def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } /-- Set the metavariable user facing name. -/ def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } userNames := let userNames := mctx.userNames.erase decl.userName if userName.isAnonymous then userNames else userNames.insert userName mvarId } /-- Low-level version of `setMVarUserName`. It does not update the table `userNames`. Thus, `findUserName?` cannot see the modification. It is meant for `mkForallFVars'` where we temporarily set the user facing name of metavariables to get more meaningful binder names. -/ def setMVarUserNameTemporarily (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } } /-- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with type := type } } def findLevelDepth? (mctx : MetavarContext) (mvarId : LMVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : LMVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } instance : MonadMCtx (StateRefT MetavarContext (ST Ο‰)) where getMCtx := get modifyMCtx := modify namespace MkBinding inductive Exception where | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (varName : String) instance : ToString Exception where toString | Exception.revertFailure _ lctx toRevert varName => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString varName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString varName ++ "' from local context)" /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State where mctx : MetavarContext nextMacroScope : MacroScope ngen : NameGenerator cache : HashMap ExprStructEq Expr := {} structure Context where mainModule : Name preserveOrder : Bool /-- When creating binders for abstracted metavariables, we use the following `BinderInfo`. -/ binderInfoForMVars : BinderInfo := BinderInfo.implicit /-- Set of unassigned metavariables being abstracted. -/ mvarIdsToAbstract : MVarIdSet := {} abbrev MCore := EStateM Exception State abbrev M := ReaderT Context MCore instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } private def mkFreshBinderName (n : Name := `x) : M Name := do let fresh ← modifyGet fun s => (s.nextMacroScope, { s with nextMacroScope := s.nextMacroScope + 1 }) return addMacroScope (← read).mainModule n fresh def preserveOrder : M Bool := return (← read).preserveOrder instance : MonadHashMapCacheAdapter ExprStructEq Expr M where getCache := do let s ← get; pure s.cache modifyCache := fun f => modify fun s => { s with cache := f s.cache } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := Id.run do let mut d : LocalDecl := lctx.getFVar! xs[0]! for x in xs[1:] do if x.isFVar then let curr := lctx.getFVar! x if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {Ξ± : Type} in def f (a : Ξ±) : List Ξ± := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {Ξ± : Type} β†’ List Ξ±`. The `_` is elaborated as a new fresh variable `?m` that contains `Ξ± : Type`, `a : Ξ±`, and `f : Ξ± β†’ List Ξ±` in its context, When we try to create the lambda `fun {Ξ± : Type} (a : Ξ±) => ?m`, we first need to create an auxiliary `?n` which do not contain `Ξ±` and `a` in its context. That is, we create the metavariable `?n : {Ξ± : Type} β†’ (a : Ξ±) β†’ (f : Ξ± β†’ List Ξ±) β†’ List Ξ±`, add the delayed assignment `?n #[Ξ±, a, f] := ?m Ξ± a f`, and create the lambda `fun {Ξ± : Type} (a : Ξ±) => ?n Ξ± a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ def collectForwardDeps (lctx : LocalContext) (toRevert : Array Expr) : M (Array Expr) := do if toRevert.size == 0 then pure toRevert else if (← preserveOrder) then -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i]! i.forM fun j => do let prevFVar := toRevert[j]! let prevDecl := lctx.getFVar! prevFVar if (← localDeclDependsOn prevDecl fvar.fvarId!) then throw (Exception.revertFailure (← getMCtx) lctx toRevert prevDecl.userName.toString) let newToRevert := if (← preserveOrder) then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => do if initSize.any fun i => decl.fvarId == newToRevert[i]!.fvarId! then return newToRevert else if toRevert.any fun x => decl.fvarId == x.fvarId! then return newToRevert.push decl.toExpr else if (← findLocalDeclDependsOn decl (newToRevert.any fun x => x.fvarId! == Β·)) then return newToRevert.push decl.toExpr else return newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (init := lctx) fun x lctx => if x.isFVar then lctx.erase x.fvarId! else lctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (init := #[]) fun scope x => if !x.isFVar then scope else if lctx.contains x.fvarId! then scope.push x else scope /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache (x : M Ξ±) : M Ξ± := do let cache ← modifyGet fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (init := mvar) fun e x => if !x.isFVar then e else match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x mutual private partial def visit (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e private partial def elim (xs : Array Expr) (e : Expr) : M Expr := match e with | .proj _ _ s => return e.updateProj! (← visit xs s) | .forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b) | .lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b) | .letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b) | .mdata _ b => return e.updateMData! (← visit xs b) | .app .. => e.withApp fun f args => elimApp xs f args | .mvar _ => elimApp xs e #[] | e => return e private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (init := e) fun i e => do let x := xs[i]! if x.isFVar then match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => let type := type.headBeta let type ← abstractRangeAux xs i type return Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 return mkForall n BinderInfo.default type e | _ => pure e else let mvarDecl := (← get).mctx.getDecl x.mvarId! let type := mvarDecl.type.headBeta let type ← abstractRangeAux xs i type let id ← if mvarDecl.userName.isAnonymous then mkFreshBinderName else pure mvarDecl.userName return Lean.mkForall id (← read).binderInfoForMVars type e where abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim xs e pure (e.abstractRange i xs) private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr Γ— Array Expr) := do let mvarDecl := (← getMCtx).getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then let args ← args.mapM (visit xs) return (mkAppN (mkMVar mvarId) args, #[]) else /- `newMVarKind` is the kind for the new auxiliary metavariable. There is an alternative approach where we use ``` let newMVarKind := if !mctx.isExprAssignable mvarId || mvarDecl.isSyntheticOpaque then MetavarKind.syntheticOpaque else MetavarKind.natural ``` In this approach, we use the natural kind for the new auxiliary metavariable if the original metavariable is synthetic and assignable. Since we mainly use synthetic metavariables for pending type class (TC) resolution problems, this approach may minimize the number of TC resolution problems that may need to be resolved. A potential disadvantage is that `isDefEq` will not eagerly use `synthPending` for natural metavariables. That being said, we should try this approach as soon as we have an extensive test suite. -/ let newMVarKind := if !(← mvarId.isAssignable) then MetavarKind.syntheticOpaque else mvarDecl.kind let args ← args.mapM (visit xs) let toRevert ← collectForwardDeps mvarLCtx toRevert let newMVarLCtx := reduceLocalContext mvarLCtx toRevert -- Note that `toRevert` only contains free variables since it is the result of `getInScope` let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x -- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs` let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId := { name := (← get).ngen.curr } let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } if !mvarDecl.kind.isSyntheticOpaque then mvarId.assign result else /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := ?mvarPending`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, `newMVarId` is also `syntheticOpaque` and we add the delayed assignment delayed assignment ``` ?newMVar #[y_1, ..., y_m, x_1, ... x_n] := ?m ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectForwardDeps`. -/ let (mvarIdPending, nestedFVars) ← match (← getDelayedMVarAssignment? mvarId) with | none => pure (mvarId, #[]) | some { fvars, mvarIdPending } => pure (mvarIdPending, fvars) assignDelayedMVar newMVarId (toRevert ++ nestedFVars) mvarIdPending return (mkAppN result args, toRevert) private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId => match (← getExprMVarAssignment? mvarId) with | some newF => if newF.isLambda then let args ← args.mapM (visit xs) elim xs <| newF.betaRev args.reverse else elimApp xs newF args | none => if (← read).mvarIdsToAbstract.contains mvarId then return mkAppN f (← args.mapM (visit xs)) else return (← elimMVar xs mvarId args).1 | _ => return mkAppN (← visit xs f) (← args.mapM (visit xs)) end partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then return e else withFreshCache do elim xs e partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr Γ— Array Expr) := withFreshCache do elimMVar xs mvarId #[] /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` expressions are created only for used variables. If `usedLetOnly == false` then `let` expressions are created only for used (let-) variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr Γ— Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (init := (e, 0)) fun i (e, num) => do let x := xs[i]! if x.isFVar then match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then return (Lean.mkLambda n bi type e, num + 1) else return (Lean.mkForall n bi type e, num + 1) else return (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => if !usedLetOnly || e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value return (mkLet n type value e nonDep, num + 1) else return (e.lowerLooseBVars 1 1, num) else let mvarDecl := (← get).mctx.getDecl x.mvarId! let type := mvarDecl.type.headBeta let type ← abstractRange xs i type let id ← if mvarDecl.userName.isAnonymous then mkFreshBinderName else pure mvarDecl.userName if isLambda then return (Lean.mkLambda id (← read).binderInfoForMVars type e, num + 1) else return (Lean.mkForall id (← read).binderInfoForMVars type e, num + 1) end MkBinding structure MkBindingM.Context where mainModule : Name lctx : LocalContext abbrev MkBindingM := ReaderT MkBindingM.Context MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun ctx => MkBinding.elimMVarDeps xs e { preserveOrder, mainModule := ctx.mainModule } def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr Γ— Array Expr) := fun ctx => MkBinding.revert xs mvarId { preserveOrder, mainModule := ctx.mainModule } def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM (Expr Γ— Nat) := fun ctx => let mvarIdsToAbstract := xs.foldl (init := {}) fun s x => if x.isMVar then s.insert x.mvarId! else s MkBinding.mkBinding isLambda ctx.lctx xs e usedOnly usedLetOnly { preserveOrder := false, binderInfoForMVars, mvarIdsToAbstract, mainModule := ctx.mainModule } @[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM Expr := return (← mkBinding (isLambda := true) xs e usedOnly usedLetOnly binderInfoForMVars).1 @[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MkBindingM Expr := return (← mkBinding (isLambda := false) xs e usedOnly usedLetOnly binderInfoForMVars).1 @[inline] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MkBindingM Expr := fun ctx => MkBinding.abstractRange xs n e { preserveOrder := false, mainModule := ctx.mainModule } @[inline] def collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MkBindingM (Array Expr) := fun ctx => MkBinding.collectForwardDeps ctx.lctx toRevert { preserveOrder, mainModule := ctx.mainModule } /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed [Monad m] [MonadMCtx m] (lctx : LocalContext) : Expr β†’ m Bool | .mdata _ e => isWellFormed lctx e | .proj _ _ e => isWellFormed lctx e | e@(.app f a) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx f <&&> isWellFormed lctx a) | e@(.lam _ d b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx d <&&> isWellFormed lctx b) | e@(.forallE _ d b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx d <&&> isWellFormed lctx b) | e@(.letE _ t v b _) => pure (!e.hasExprMVar && !e.hasFVar) <||> (isWellFormed lctx t <&&> isWellFormed lctx v <&&> isWellFormed lctx b) | .const .. => return true | .bvar .. => return true | .sort .. => return true | .lit .. => return true | .mvar mvarId => do let mvarDecl := (← getMCtx).getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then return true else match (← getExprMVarAssignment? mvarId) with | none => return false | some v => isWellFormed lctx v | .fvar fvarId => return lctx.contains fvarId namespace LevelMVarToParam structure Context where paramNamePrefix : Name alreadyUsedPred : Name β†’ Bool except : LMVarId β†’ Bool structure State where mctx : MetavarContext paramNames : Array Name := #[] nextParamIdx : Nat cache : HashMap ExprStructEq Expr := {} abbrev M := ReaderT Context <| StateM State instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : MonadCache ExprStructEq Expr M where findCached? e := return (← get).cache.find? e cache e v := modify fun s => { s with cache := s.cache.insert e v } partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | .succ v => return u.updateSucc! (← visitLevel v) | .max v₁ vβ‚‚ => return u.updateMax! (← visitLevel v₁) (← visitLevel vβ‚‚) | .imax v₁ vβ‚‚ => return u.updateIMax! (← visitLevel v₁) (← visitLevel vβ‚‚) | .zero => return u | .param .. => return u | .mvar mvarId => match (← getLevelMVarAssignment? mvarId) with | some v => visitLevel v | none => if (← read).except mvarId then return u else let p ← mkParamName let p := mkLevelParam p assignLevelMVar mvarId p return p partial def main (e : Expr) : M Expr := if !e.hasMVar then return e else checkCache { val := e : ExprStructEq } fun _ => do match e with | .proj _ _ s => return e.updateProj! (← main s) | .forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | .lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | .letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | .app .. => e.withApp fun f args => visitApp f args | .mdata _ b => return e.updateMData! (← main b) | .const _ us => return e.updateConst! (← us.mapM visitLevel) | .sort u => return e.updateSort! (← visitLevel u) | .mvar .. => visitApp e #[] | e => return e where visitApp (f : Expr) (args : Array Expr) : M Expr := do match f with | .mvar mvarId .. => match (← getExprMVarAssignment? mvarId) with | some v => return (← visitApp v args).headBeta | none => return mkAppN f (← args.mapM main) | _ => return mkAppN (← main f) (← args.mapM main) end LevelMVarToParam structure UnivMVarParamResult where mctx : MetavarContext newParamNames : Array Name nextParamIdx : Nat expr : Expr def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name β†’ Bool) (except : LMVarId β†’ Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { except, paramNamePrefix, alreadyUsedPred } { mctx, nextParamIdx } { mctx := s.mctx newParamNames := s.paramNames nextParamIdx := s.nextParamIdx expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId end MetavarContext end Lean
a33d8e341c32b0da39f193d417d3eba7083aed8f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_discr_tree_bug.lean
d7a0b41166a570c5ef4a3ede8d5ea3684fe7a303
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
578
lean
open subtype nat constant f : Ξ  (a : nat), {b : nat | b > a} β†’ nat definition f_flat (a : nat) (b : nat) (p : b > a) : nat := f a (tag b p) definition greater [reducible] (a : nat) := {b : nat | b > a} set_option blast.recursion.structure true definition f_flat_def [simp] (a : nat) (b : nat) (p : b > a) : f a (tag b p) = f_flat a b p := rfl definition has_property_tag [simp] {A : Type} {p : A β†’ Prop} (a : A) (h : p a) : has_property (tag a h) = h := rfl lemma to_f_flat : βˆ€ (a : nat) (b : greater a), f a b = f_flat a (elt_of b) (has_property b) := by rec_simp
6a52ec552fb74452ddd70504d37723b0bc411363
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/abelian/right_derived.lean
e3d6b76f6386007817a21326154e7c66de5aeb3b
[ "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
14,012
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Scott Morrison -/ import category_theory.abelian.injective_resolution import algebra.homology.additive import category_theory.limits.constructions.epi_mono import category_theory.abelian.homology import category_theory.abelian.exact /-! # Right-derived functors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the right-derived functors `F.right_derived n : C β₯€ D` for any additive functor `F` out of a category with injective resolutions. The definition is ``` injective_resolutions C β‹™ F.map_homotopy_category _ β‹™ homotopy_category.homology_functor D _ n ``` that is, we pick an injective resolution (thought of as an object of the homotopy category), we apply `F` objectwise, and compute `n`-th homology. We show that these right-derived functors can be calculated on objects using any choice of injective resolution, and on morphisms by any choice of lift to a cochain map between chosen injective resolutions. Similarly we define natural transformations between right-derived functors coming from natural transformations between the original additive functors, and show how to compute the components. ## Main results * `category_theory.functor.right_derived_obj_injective_zero`: the `0`-th derived functor of `F` on an injective object `X` is isomorphic to `F.obj X`. * `category_theory.functor.right_derived_obj_injective_succ`: injective objects have no higher right derived functor. * `category_theory.nat_trans.right_derived`: the natural isomorphism between right derived functors induced by natural transformation. Now, we assume `preserves_finite_limits F`, then * `category_theory.abelian.functor.preserves_exact_of_preserves_finite_limits_of_mono`: if `f` is mono and `exact f g`, then `exact (F.map f) (F.map g)`. * `category_theory.abelian.functor.right_derived_zero_iso_self`: if there are enough injectives, then there is a natural isomorphism `(F.right_derived 0) β‰… F`. -/ noncomputable theory open category_theory open category_theory.limits namespace category_theory universes v u variables {C : Type u} [category.{v} C] {D : Type*} [category D] variables [abelian C] [has_injective_resolutions C] [abelian D] /-- The right derived functors of an additive functor. -/ def functor.right_derived (F : C β₯€ D) [F.additive] (n : β„•) : C β₯€ D := injective_resolutions C β‹™ F.map_homotopy_category _ β‹™ homotopy_category.homology_functor D _ n /-- We can compute a right derived functor using a chosen injective resolution. -/ @[simps] def functor.right_derived_obj_iso (F : C β₯€ D) [F.additive] (n : β„•) {X : C} (P : InjectiveResolution X) : (F.right_derived n).obj X β‰… (homology_functor D _ n).obj ((F.map_homological_complex _).obj P.cocomplex) := (homotopy_category.homology_functor D _ n).map_iso (homotopy_category.iso_of_homotopy_equiv (F.map_homotopy_equiv (InjectiveResolution.homotopy_equiv _ P))) β‰ͺ≫ (homotopy_category.homology_factors D _ n).app _ /-- The 0-th derived functor of `F` on an injective object `X` is just `F.obj X`. -/ @[simps] def functor.right_derived_obj_injective_zero (F : C β₯€ D) [F.additive] (X : C) [injective X] : (F.right_derived 0).obj X β‰… F.obj X := F.right_derived_obj_iso 0 (InjectiveResolution.self X) β‰ͺ≫ (homology_functor _ _ _).map_iso ((cochain_complex.singleβ‚€_map_homological_complex F).app X) β‰ͺ≫ (cochain_complex.homology_functor_0_singleβ‚€ D).app (F.obj X) open_locale zero_object /-- The higher derived functors vanish on injective objects. -/ @[simps inv] def functor.right_derived_obj_injective_succ (F : C β₯€ D) [F.additive] (n : β„•) (X : C) [injective X] : (F.right_derived (n+1)).obj X β‰… 0 := F.right_derived_obj_iso (n+1) (InjectiveResolution.self X) β‰ͺ≫ (homology_functor _ _ _).map_iso ((cochain_complex.singleβ‚€_map_homological_complex F).app X) β‰ͺ≫ (cochain_complex.homology_functor_succ_singleβ‚€ D n).app (F.obj X) β‰ͺ≫ (functor.zero_obj _).iso_zero /-- We can compute a right derived functor on a morphism using a descent of that morphism to a cochain map between chosen injective resolutions. -/ lemma functor.right_derived_map_eq (F : C β₯€ D) [F.additive] (n : β„•) {X Y : C} (f : Y ⟢ X) {P : InjectiveResolution X} {Q : InjectiveResolution Y} (g : Q.cocomplex ⟢ P.cocomplex) (w : Q.ΞΉ ≫ g = (cochain_complex.singleβ‚€ C).map f ≫ P.ΞΉ) : (F.right_derived n).map f = (F.right_derived_obj_iso n Q).hom ≫ (homology_functor D _ n).map ((F.map_homological_complex _).map g) ≫ (F.right_derived_obj_iso n P).inv := begin dsimp only [functor.right_derived, functor.right_derived_obj_iso], dsimp, simp only [category.comp_id, category.id_comp], rw [←homology_functor_map, homotopy_category.homology_functor_map_factors], simp only [←functor.map_comp], congr' 1, apply homotopy_category.eq_of_homotopy, apply functor.map_homotopy, apply homotopy.trans, exact homotopy_category.homotopy_out_map _, apply InjectiveResolution.desc_homotopy f, { simp, }, { simp only [InjectiveResolution.homotopy_equiv_hom_ΞΉ_assoc], rw [←category.assoc, w, category.assoc], simp only [InjectiveResolution.homotopy_equiv_inv_ΞΉ], }, end /-- The natural transformation between right-derived functors induced by a natural transformation.-/ @[simps] def nat_trans.right_derived {F G : C β₯€ D} [F.additive] [G.additive] (Ξ± : F ⟢ G) (n : β„•) : F.right_derived n ⟢ G.right_derived n := whisker_left (injective_resolutions C) (whisker_right (nat_trans.map_homotopy_category Ξ± _) (homotopy_category.homology_functor D _ n)) @[simp] lemma nat_trans.right_derived_id (F : C β₯€ D) [F.additive] (n : β„•) : nat_trans.right_derived (πŸ™ F) n = πŸ™ (F.right_derived n) := by { simp [nat_trans.right_derived], refl, } @[simp, nolint simp_nf] lemma nat_trans.right_derived_comp {F G H : C β₯€ D} [F.additive] [G.additive] [H.additive] (Ξ± : F ⟢ G) (Ξ² : G ⟢ H) (n : β„•) : nat_trans.right_derived (Ξ± ≫ Ξ²) n = nat_trans.right_derived Ξ± n ≫ nat_trans.right_derived Ξ² n := by simp [nat_trans.right_derived] /-- A component of the natural transformation between right-derived functors can be computed using a chosen injective resolution. -/ lemma nat_trans.right_derived_eq {F G : C β₯€ D} [F.additive] [G.additive] (Ξ± : F ⟢ G) (n : β„•) {X : C} (P : InjectiveResolution X) : (nat_trans.right_derived Ξ± n).app X = (F.right_derived_obj_iso n P).hom ≫ (homology_functor D _ n).map ((nat_trans.map_homological_complex Ξ± _).app P.cocomplex) ≫ (G.right_derived_obj_iso n P).inv := begin symmetry, dsimp [nat_trans.right_derived, functor.right_derived_obj_iso], simp only [category.comp_id, category.id_comp], rw [←homology_functor_map, homotopy_category.homology_functor_map_factors], simp only [←functor.map_comp], congr' 1, apply homotopy_category.eq_of_homotopy, simp only [nat_trans.map_homological_complex_naturality_assoc, ←functor.map_comp], apply homotopy.comp_left_id, rw [←functor.map_id], apply functor.map_homotopy, apply homotopy_equiv.homotopy_hom_inv_id, end end category_theory section universes w v u open category_theory.limits category_theory category_theory.functor variables {C : Type u} [category.{w} C] {D : Type u} [category.{w} D] variables (F : C β₯€ D) {X Y Z : C} {f : X ⟢ Y} {g : Y ⟢ Z} namespace category_theory.abelian.functor open category_theory.preadditive variables [abelian C] [abelian D] [additive F] /-- If `preserves_finite_limits F` and `mono f`, then `exact (F.map f) (F.map g)` if `exact f g`. -/ lemma preserves_exact_of_preserves_finite_limits_of_mono [preserves_finite_limits F] [mono f] (ex : exact f g) : exact (F.map f) (F.map g) := abelian.exact_of_is_kernel _ _ (by simp [← functor.map_comp, ex.w]) $ limits.is_limit_fork_map_of_is_limit' _ ex.w (abelian.is_limit_of_exact_of_mono _ _ ex) lemma exact_of_map_injective_resolution (P: InjectiveResolution X) [preserves_finite_limits F] : exact (F.map (P.ΞΉ.f 0)) (((F.map_homological_complex (complex_shape.up β„•)).obj P.cocomplex).d_from 0) := preadditive.exact_of_iso_of_exact' (F.map (P.ΞΉ.f 0)) (F.map (P.cocomplex.d 0 1)) _ _ (iso.refl _) (iso.refl _) (homological_complex.X_next_iso ((F.map_homological_complex _).obj P.cocomplex) rfl).symm (by simp) (by rw [iso.refl_hom, category.id_comp, iso.symm_hom, homological_complex.d_from_eq]; congr') (preserves_exact_of_preserves_finite_limits_of_mono _ (P.exactβ‚€)) /-- Given `P : InjectiveResolution X`, a morphism `(F.right_derived 0).obj X ⟢ F.obj X` given `preserves_finite_limits F`. -/ def right_derived_zero_to_self_app [enough_injectives C] [preserves_finite_limits F] {X : C} (P : InjectiveResolution X) : (F.right_derived 0).obj X ⟢ F.obj X := (right_derived_obj_iso F 0 P).hom ≫ (homology_iso_kernel_desc _ _ _).hom ≫ kernel.map _ _ (cokernel.desc _ (πŸ™ _) (by simp)) (πŸ™ _) (by { ext, simp }) ≫ (as_iso (kernel.lift _ _ (exact_of_map_injective_resolution F P).w)).inv /-- Given `P : InjectiveResolution X`, a morphism `F.obj X ⟢ (F.right_derived 0).obj X`. -/ def right_derived_zero_to_self_app_inv [enough_injectives C] {X : C} (P : InjectiveResolution X) : F.obj X ⟢ (F.right_derived 0).obj X := homology.lift _ _ _ (F.map (P.ΞΉ.f 0) ≫ cokernel.Ο€ _) begin have : (complex_shape.up β„•).rel 0 1 := rfl, rw [category.assoc, cokernel.Ο€_desc, homological_complex.d_from_eq _ this, map_homological_complex_obj_d, ← category.assoc, ← functor.map_comp], simp only [InjectiveResolution.ΞΉ_f_zero_comp_complex_d, functor.map_zero, zero_comp], end ≫ (right_derived_obj_iso F 0 P).inv lemma right_derived_zero_to_self_app_comp_inv [enough_injectives C] [preserves_finite_limits F] {X : C} (P : InjectiveResolution X) : right_derived_zero_to_self_app F P ≫ right_derived_zero_to_self_app_inv F P = πŸ™ _ := begin dsimp [right_derived_zero_to_self_app, right_derived_zero_to_self_app_inv], rw [← category.assoc, iso.comp_inv_eq, category.id_comp, category.assoc, category.assoc, ← iso.eq_inv_comp, iso.inv_hom_id], ext, rw [category.assoc, category.assoc, homology.lift_ΞΉ, category.id_comp, homology.Ο€'_ΞΉ, category.assoc, ←category.assoc _ _ (cokernel.Ο€ _), abelian.kernel.lift.inv, ← category.assoc, ← category.assoc _ (kernel.ΞΉ _), limits.kernel.lift_ΞΉ, category.assoc, category.assoc, ← category.assoc (homology_iso_kernel_desc _ _ _).hom _ _, ← homology.ΞΉ, ←category.assoc, homology.Ο€'_ΞΉ, category.assoc, ←category.assoc (cokernel.Ο€ _), cokernel.Ο€_desc, whisker_eq], convert category.id_comp (cokernel.Ο€ _), end lemma right_derived_zero_to_self_app_inv_comp [enough_injectives C] [preserves_finite_limits F] {X : C} (P : InjectiveResolution X) : right_derived_zero_to_self_app_inv F P ≫ right_derived_zero_to_self_app F P = πŸ™ _ := begin dsimp [right_derived_zero_to_self_app, right_derived_zero_to_self_app_inv], rw [← category.assoc _ (F.right_derived_obj_iso 0 P).hom, category.assoc _ _ (F.right_derived_obj_iso 0 P).hom, iso.inv_hom_id, category.comp_id, ← category.assoc, ← category.assoc, is_iso.comp_inv_eq, category.id_comp], ext, simp only [limits.kernel.lift_ΞΉ_assoc, category.assoc, limits.kernel.lift_ΞΉ, homology.lift], rw [← category.assoc, ← category.assoc, category.assoc _ _ (homology_iso_kernel_desc _ _ _).hom], simp, end /-- Given `P : InjectiveResolution X`, the isomorphism `(F.right_derived 0).obj X β‰… F.obj X` if `preserves_finite_limits F`. -/ def right_derived_zero_to_self_app_iso [enough_injectives C] [preserves_finite_limits F] {X : C} (P : InjectiveResolution X) : (F.right_derived 0).obj X β‰… F.obj X := { hom := right_derived_zero_to_self_app _ P, inv := right_derived_zero_to_self_app_inv _ P, hom_inv_id' := right_derived_zero_to_self_app_comp_inv _ P, inv_hom_id' := right_derived_zero_to_self_app_inv_comp _ P } /-- Given `P : InjectiveResolution X` and `Q : InjectiveResolution Y` and a morphism `f : X ⟢ Y`, naturality of the square given by `right_derived_zero_to_self_natural`. -/ lemma right_derived_zero_to_self_natural [enough_injectives C] {X : C} {Y : C} (f : X ⟢ Y) (P : InjectiveResolution X) (Q : InjectiveResolution Y) : F.map f ≫ right_derived_zero_to_self_app_inv F Q = right_derived_zero_to_self_app_inv F P ≫ (F.right_derived 0).map f := begin dsimp [right_derived_zero_to_self_app_inv], simp only [category_theory.functor.map_id, category.id_comp, ← category.assoc], rw [iso.comp_inv_eq, right_derived_map_eq F 0 f (InjectiveResolution.desc f Q P) (by simp), category.assoc, category.assoc, category.assoc, category.assoc, iso.inv_hom_id, category.comp_id, ← category.assoc (F.right_derived_obj_iso 0 P).inv, iso.inv_hom_id, category.id_comp], dsimp only [homology_functor_map], ext, rw [category.assoc, homology.lift_ΞΉ, category.assoc, homology.map_ΞΉ, ←category.assoc (homology.lift _ _ _ _ _) _ _, homology.lift_ΞΉ, category.assoc, cokernel.Ο€_desc, ←category.assoc, ← functor.map_comp, ← category.assoc, homological_complex.hom.sq_from_left, map_homological_complex_map_f, ← functor.map_comp, show f ≫ Q.ΞΉ.f 0 = P.ΞΉ.f 0 ≫ (InjectiveResolution.desc f Q P).f 0, from homological_complex.congr_hom (InjectiveResolution.desc_commutes f Q P).symm 0], end /-- Given `preserves_finite_limits F`, the natural isomorphism `(F.right_derived 0) β‰… F`. -/ def right_derived_zero_iso_self [enough_injectives C] [preserves_finite_limits F] : (F.right_derived 0) β‰… F := iso.symm $ nat_iso.of_components (Ξ» X, (right_derived_zero_to_self_app_iso _ (InjectiveResolution.of X)).symm) (Ξ» X Y f, right_derived_zero_to_self_natural _ _ _ _) end category_theory.abelian.functor end
55d820d19942fcf5cd692912ad9ddc00e10141d7
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/simplifier_light.lean
c27c5873466ff61d78f5e25d0e85a3c422baf441
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
1,668
lean
-- Test [light] annotation -- Remark: it will take some additional work to get ⁻¹ to rewrite well -- when there is a proof obligation. import algebra.ring algebra.field data.set data.finset open algebra attribute neg [light 3] attribute inv [light 3] attribute add.right_inv [simp] attribute add_neg_cancel_left [simp] attribute mul.right_inv [simp] attribute mul_inv_cancel_left [simp] open simplifier.unit simplifier.ac namespace ag universe l constants (A : Type.{l}) (s1 : add_comm_group A) (s2 : has_one A) attribute s1 [instance] attribute s2 [instance] constants (x y z w v : A) #simplify eq env 0 x + y + - x + -y + z + -z #simplify eq env 0 -100 + -v + -v + x + -v + y + - x + -y + z + -z + v + v + v + 100 end ag namespace mg universe l constants (A : Type.{l}) (s1 : comm_group A) (s2 : has_add A) attribute s1 [instance] attribute s2 [instance] constants (x y z w v : A) #simplify eq env 0 x⁻¹ * y⁻¹ * z⁻¹ * 100⁻¹ * x * y * z * 100 end mg namespace s open set universe l constants (A : Type.{l}) (x y z v w : set A) attribute compl [light 2] -- TODO(dhs, leo): Where do we put this group of simp rules? attribute union_compl_self [simp] lemma union_comp_self_left [simp] {X : Type} (s t : set X) : s βˆͺ (-s βˆͺ t)= univ := sorry attribute union_comm [simp] attribute union_assoc [simp] attribute union_left_comm [simp] #simplify eq env 0 x βˆͺ y βˆͺ z βˆͺ -x attribute inter_compl_self [simp] lemma inter_compl_self_left [simp] {X : Type} (s t : set X) : s ∩ (-s ∩ t)= empty := sorry attribute inter_comm [simp] attribute inter_assoc [simp] attribute inter_left_comm [simp] #simplify eq env 0 x ∩ y ∩ z ∩ -x end s
a2d3a5c285d829e728db4e4166c8c11e4b8461a8
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/group_with_zero/power.lean
a2d9c2570006d03c94000991fb6edb3a1937e505
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,012
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.group_power /-! # Powers of elements of groups with an adjoined zero element In this file we define integer power functions for groups with an adjoined zero element. This generalises the integer power function on a division ring. -/ section zero variables {M : Type*} [monoid_with_zero M] @[simp] lemma zero_pow' : βˆ€ n : β„•, n β‰  0 β†’ (0 : M) ^ n = 0 | 0 h := absurd rfl h | (k+1) h := by { rw [pow_succ], exact zero_mul _ } lemma ne_zero_pow {a : M} {n : β„•} (hn : n β‰  0) : a ^ n β‰  0 β†’ a β‰  0 := by { contrapose!, rintro rfl, exact zero_pow' n hn } @[simp] lemma zero_pow_eq_zero [nontrivial M] {n : β„•} : (0 : M) ^ n = 0 ↔ 0 < n := begin split; intro h, { rw [pos_iff_ne_zero], rintro rfl, simpa using h }, { exact zero_pow' n h.ne.symm } end end zero section group_with_zero variables {Gβ‚€ : Type*} [group_with_zero Gβ‚€] section nat_pow @[simp, field_simps] theorem inv_powβ‚€ (a : Gβ‚€) (n : β„•) : (a⁻¹) ^ n = (a ^ n)⁻¹ := begin induction n with n ih, { rw [pow_zero, pow_zero], exact inv_one.symm }, { rw [pow_succ', pow_succ, ih, mul_inv_revβ‚€] } end theorem pow_subβ‚€ (a : Gβ‚€) {m n : β„•} (ha : a β‰  0) (h : n ≀ m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a ^ (m - n) * a ^ n = a ^ m, by rw [←pow_add, h1], by simpa only [div_eq_mul_inv] using eq_div_of_mul_eq (pow_ne_zero _ ha) h2 theorem pow_inv_commβ‚€ (a : Gβ‚€) (m n : β„•) : (a⁻¹) ^ m * a ^ n = a ^ n * (a⁻¹) ^ m := (commute.refl a).inv_leftβ‚€.pow_pow m n end nat_pow end group_with_zero section int_pow open int variables {Gβ‚€ : Type*} [group_with_zero Gβ‚€] local attribute [ematch] le_of_lt @[simp] theorem one_fpow : βˆ€ (n : β„€), (1 : Gβ‚€) ^ n = 1 | (n : β„•) := by rw [gpow_coe_nat, one_pow] | -[1+ n] := by rw [gpow_neg_succ_of_nat, one_pow, inv_one] lemma zero_fpow : βˆ€ z : β„€, z β‰  0 β†’ (0 : Gβ‚€) ^ z = 0 | (n : β„•) h := by { rw [gpow_coe_nat, zero_pow'], simpa using h } | -[1+n] h := by simp lemma fzero_pow_eq (n : β„€) : (0 : Gβ‚€) ^ n = if n = 0 then 1 else 0 := begin split_ifs with h, { rw [h, gpow_zero] }, { rw [zero_fpow _ h] } end @[simp] theorem fpow_neg (a : Gβ‚€) : βˆ€ (n : β„€), a ^ -n = (a ^ n)⁻¹ | (n+1:β„•) := div_inv_monoid.gpow_neg' _ _ | 0 := by { change a ^ (0 : β„€) = (a ^ (0 : β„€))⁻¹, simp } | -[1+ n] := by { rw [gpow_neg_succ_of_nat, inv_invβ‚€, ← gpow_coe_nat], refl } theorem fpow_neg_one (x : Gβ‚€) : x ^ (-1:β„€) = x⁻¹ := by { rw [← congr_arg has_inv.inv (pow_one x), fpow_neg, ← gpow_coe_nat], refl } theorem inv_fpow (a : Gβ‚€) : βˆ€n:β„€, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : β„•) := by rw [gpow_coe_nat, gpow_coe_nat, inv_powβ‚€] | -[1+ n] := by rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, inv_powβ‚€] lemma fpow_add_one {a : Gβ‚€} (ha : a β‰  0) : βˆ€ n : β„€, a ^ (n + 1) = a ^ n * a | (n : β„•) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq, ha] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, fpow_neg, neg_add, neg_add_cancel_right, fpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_revβ‚€, mul_assoc, inv_mul_cancel ha, mul_one] lemma fpow_sub_one {a : Gβ‚€} (ha : a β‰  0) (n : β„€) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : by rw [mul_assoc, mul_inv_cancel ha, mul_one] ... = a^n * a⁻¹ : by rw [← fpow_add_one ha, sub_add_cancel] lemma fpow_add {a : Gβ‚€} (ha : a β‰  0) (m n : β„€) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, fpow_add_one ha, ihn, mul_assoc] }, { rw [fpow_sub_one ha, ← mul_assoc, ← ihn, ← fpow_sub_one ha, add_sub_assoc] } end lemma fpow_add' {a : Gβ‚€} {m n : β„€} (h : a β‰  0 ∨ m + n β‰  0 ∨ m = 0 ∧ n = 0) : a ^ (m + n) = a ^ m * a ^ n := begin by_cases hm : m = 0, { simp [hm] }, by_cases hn : n = 0, { simp [hn] }, by_cases ha : a = 0, { subst a, simp only [false_or, eq_self_iff_true, not_true, ne.def, hm, hn, false_and, or_false] at h, rw [zero_fpow _ h, zero_fpow _ hm, zero_mul] }, { exact fpow_add ha m n } end theorem fpow_one_add {a : Gβ‚€} (h : a β‰  0) (i : β„€) : a ^ (1 + i) = a * a ^ i := by rw [fpow_add h, gpow_one] theorem semiconj_by.fpow_right {a x y : Gβ‚€} (h : semiconj_by a x y) : βˆ€ m : β„€, semiconj_by a (x^m) (y^m) | (n : β„•) := by simp [h.pow_right n] | -[1+n] := by simp [(h.pow_right (n + 1)).inv_rightβ‚€] theorem commute.fpow_right {a b : Gβ‚€} (h : commute a b) : βˆ€ m : β„€, commute a (b^m) := h.fpow_right theorem commute.fpow_left {a b : Gβ‚€} (h : commute a b) (m : β„€) : commute (a^m) b := (h.symm.fpow_right m).symm theorem commute.fpow_fpow {a b : Gβ‚€} (h : commute a b) (m n : β„€) : commute (a^m) (b^n) := (h.fpow_left m).fpow_right n theorem commute.fpow_self (a : Gβ‚€) (n : β„€) : commute (a^n) a := (commute.refl a).fpow_left n theorem commute.self_fpow (a : Gβ‚€) (n : β„€) : commute a (a^n) := (commute.refl a).fpow_right n theorem commute.fpow_fpow_self (a : Gβ‚€) (m n : β„€) : commute (a^m) (a^n) := (commute.refl a).fpow_fpow m n theorem fpow_bit0 (a : Gβ‚€) (n : β„€) : a ^ bit0 n = a ^ n * a ^ n := begin apply fpow_add', right, by_cases hn : n = 0, { simp [hn] }, { simp [← two_mul, hn, two_ne_zero] } end theorem fpow_bit1 (a : Gβ‚€) (n : β„€) : a ^ bit1 n = a ^ n * a ^ n * a := begin rw [← fpow_bit0, bit1, fpow_add', gpow_one], right, left, apply bit1_ne_zero end theorem fpow_mul (a : Gβ‚€) : βˆ€ m n : β„€, a ^ (m * n) = (a ^ m) ^ n | (m : β„•) (n : β„•) := by { rw [gpow_coe_nat, gpow_coe_nat, ← pow_mul, ← gpow_coe_nat], refl } | (m : β„•) -[1+ n] := by { rw [gpow_coe_nat, gpow_neg_succ_of_nat, ← pow_mul, coe_nat_mul_neg_succ, fpow_neg, inv_injβ‚€, ← gpow_coe_nat], refl } | -[1+ m] (n : β„•) := by { rw [gpow_coe_nat, gpow_neg_succ_of_nat, ← inv_powβ‚€, ← pow_mul, neg_succ_mul_coe_nat, fpow_neg, inv_powβ‚€, inv_injβ‚€, ← gpow_coe_nat], refl } | -[1+ m] -[1+ n] := by { rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, neg_succ_mul_neg_succ, inv_powβ‚€, inv_invβ‚€, ← pow_mul, ← gpow_coe_nat], refl } theorem fpow_mul' (a : Gβ‚€) (m n : β„€) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, fpow_mul] @[simp, norm_cast] lemma units.coe_gpowβ‚€ (u : units Gβ‚€) : βˆ€ (n : β„€), ((u ^ n : units Gβ‚€) : Gβ‚€) = u ^ n | (n : β„•) := by { rw [gpow_coe_nat, gpow_coe_nat], exact u.coe_pow n } | -[1+k] := by rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, units.coe_inv', u.coe_pow] lemma fpow_ne_zero_of_ne_zero {a : Gβ‚€} (ha : a β‰  0) : βˆ€ (z : β„€), a ^ z β‰  0 | (n : β„•) := by { rw gpow_coe_nat, exact pow_ne_zero _ ha } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_ne_zero (pow_ne_zero _ ha) } lemma fpow_sub {a : Gβ‚€} (ha : a β‰  0) (z1 z2 : β„€) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 := by rw [sub_eq_add_neg, fpow_add ha, fpow_neg, div_eq_mul_inv] lemma commute.mul_fpow {a b : Gβ‚€} (h : commute a b) : βˆ€ (i : β„€), (a * b) ^ i = (a ^ i) * (b ^ i) | (n : β„•) := by simp [h.mul_pow n] | -[1+n] := by simp [h.mul_pow, (h.pow_pow _ _).eq, mul_inv_revβ‚€] lemma mul_fpow {Gβ‚€ : Type*} [comm_group_with_zero Gβ‚€] (a b : Gβ‚€) (m : β„€): (a * b) ^ m = (a ^ m) * (b ^ m) := (commute.all a b).mul_fpow m theorem fpow_bit0' (a : Gβ‚€) (n : β„€) : a ^ bit0 n = (a * a) ^ n := (fpow_bit0 a n).trans ((commute.refl a).mul_fpow n).symm theorem fpow_bit1' (a : Gβ‚€) (n : β„€) : a ^ bit1 n = (a * a) ^ n * a := by rw [fpow_bit1, (commute.refl a).mul_fpow] lemma fpow_eq_zero {x : Gβ‚€} {n : β„€} (h : x ^ n = 0) : x = 0 := classical.by_contradiction $ Ξ» hx, fpow_ne_zero_of_ne_zero hx n h lemma fpow_ne_zero {x : Gβ‚€} (n : β„€) : x β‰  0 β†’ x ^ n β‰  0 := mt fpow_eq_zero theorem fpow_neg_mul_fpow_self (n : β„€) {x : Gβ‚€} (h : x β‰  0) : x ^ (-n) * x ^ n = 1 := begin rw [fpow_neg], exact inv_mul_cancel (fpow_ne_zero n h) end theorem one_div_pow {a : Gβ‚€} (n : β„•) : (1 / a) ^ n = 1 / a ^ n := by simp only [one_div, inv_powβ‚€] theorem one_div_fpow {a : Gβ‚€} (n : β„€) : (1 / a) ^ n = 1 / a ^ n := by simp only [one_div, inv_fpow] @[simp] lemma inv_fpow' {a : Gβ‚€} (n : β„€) : (a ⁻¹) ^ n = a ^ (-n) := by { rw [inv_fpow, ← fpow_neg_one, ← fpow_mul], simp } end int_pow section variables {Gβ‚€ : Type*} [comm_group_with_zero Gβ‚€] @[simp] theorem div_pow (a b : Gβ‚€) (n : β„•) : (a / b) ^ n = a ^ n / b ^ n := by simp only [div_eq_mul_inv, mul_pow, inv_powβ‚€] @[simp] theorem div_fpow (a : Gβ‚€) {b : Gβ‚€} (n : β„€) : (a / b) ^ n = a ^ n / b ^ n := by simp only [div_eq_mul_inv, mul_fpow, inv_fpow] lemma div_sq_cancel {a : Gβ‚€} (ha : a β‰  0) (b : Gβ‚€) : a ^ 2 * b / a = a * b := by rw [sq, mul_assoc, mul_div_cancel_left _ ha] end /-- If a monoid homomorphism `f` between two `group_with_zero`s maps `0` to `0`, then it maps `x^n`, `n : β„€`, to `(f x)^n`. -/ lemma monoid_with_zero_hom.map_fpow {Gβ‚€ Gβ‚€' : Type*} [group_with_zero Gβ‚€] [group_with_zero Gβ‚€'] (f : monoid_with_zero_hom Gβ‚€ Gβ‚€') (x : Gβ‚€) : βˆ€ n : β„€, f (x ^ n) = f x ^ n | (n : β„•) := by { rw [gpow_coe_nat, gpow_coe_nat], exact f.to_monoid_hom.map_pow x n } | -[1+n] := begin rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat], exact ((f.map_inv _).trans $ congr_arg _ $ f.to_monoid_hom.map_pow x _) end -- I haven't been able to find a better home for this: -- it belongs with other lemmas on `linear_ordered_field`, but -- we need to wait until `fpow` has been defined in this file. section variables {R : Type*} [linear_ordered_field R] {a : R} lemma pow_minus_two_nonneg : 0 ≀ a^(-2 : β„€) := begin simp only [inv_nonneg, fpow_neg], change 0 ≀ a ^ ((2 : β„•) : β„€), rw gpow_coe_nat, apply sq_nonneg, end end
f5b92164d725fcbd6ad7e10ed9da0467db3a2c58
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category_theory/adjunction/fully_faithful.lean
58265b011b118dda6f78253ea84cec8e877d479b
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
2,282
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.adjunction.basic import category_theory.yoneda open category_theory namespace category_theory universes v₁ vβ‚‚ u₁ uβ‚‚ open category open opposite variables {C : Type u₁} [π’ž : category.{v₁} C] variables {D : Type uβ‚‚} [π’Ÿ : category.{vβ‚‚} D] include π’ž π’Ÿ variables {L : C β₯€ D} {R : D β₯€ C} (h : L ⊣ R) -- Lemma 4.5.13 from [Riehl][riehl2017] -- Proof in https://stacks.math.columbia.edu/tag/0036 -- or at https://math.stackexchange.com/a/2727177 instance unit_is_iso_of_L_fully_faithful [full L] [faithful L] : is_iso (adjunction.unit h) := @nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ (adjunction.unit h) $ Ξ» X, @yoneda.is_iso _ _ _ _ ((adjunction.unit h).app X) { inv := { app := Ξ» Y f, L.preimage ((h.hom_equiv (unop Y) (L.obj X)).symm f) }, inv_hom_id' := begin ext1, ext1, dsimp, simp only [adjunction.hom_equiv_counit, preimage_comp, preimage_map, category.assoc], rw ←h.unit_naturality, simp, end, hom_inv_id' := begin ext1, ext1, dsimp, apply L.injectivity, simp, end }. instance counit_is_iso_of_R_fully_faithful [full R] [faithful R] : is_iso (adjunction.counit h) := @nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ (adjunction.counit h) $ Ξ» X, @is_iso_of_op _ _ _ _ _ $ @coyoneda.is_iso _ _ _ _ ((adjunction.counit h).app X).op { inv := { app := Ξ» Y f, R.preimage ((h.hom_equiv (R.obj X) Y) f) }, inv_hom_id' := begin ext1, ext1, dsimp, simp only [adjunction.hom_equiv_unit, preimage_comp, preimage_map], rw ←h.counit_naturality, simp, end, hom_inv_id' := begin ext1, ext1, dsimp, apply R.injectivity, simp, end } -- TODO also prove the converses? -- def L_full_of_unit_is_iso [is_iso (adjunction.unit h)] : full L := sorry -- def L_faithful_of_unit_is_iso [is_iso (adjunction.unit h)] : faithful L := sorry -- def R_full_of_counit_is_iso [is_iso (adjunction.counit h)] : full R := sorry -- def R_faithful_of_counit_is_iso [is_iso (adjunction.counit h)] : faithful R := sorry -- TODO also do the statements from Riehl 4.5.13 for full and faithful separately? end category_theory
8b28b17261f2ae892d223598ffa8ff23bdb7fe13
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/hott/axioms/ua.lean
302648177e0b17daa378d5340f5b5a8850cfbd2d
[ "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
1,427
lean
-- Copyright (c) 2014 Jakob von Raumer. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jakob von Raumer -- Ported from Coq HoTT import hott.path hott.equiv open path Equiv --Ensure that the types compared are in the same universe section universe variable l variables {A B : Type.{l}} definition isequiv_path (H : A β‰ˆ B) := (@IsEquiv.transport Type (Ξ»X, X) A B H) definition equiv_path (H : A β‰ˆ B) : A ≃ B := Equiv.mk _ (isequiv_path H) end inductive ua_type [class] : Type := mk : (Ξ  (A B : Type), IsEquiv (@equiv_path A B)) β†’ ua_type namespace ua_type context universe k parameters [F : ua_type.{k}] {A B: Type.{k}} -- Make the Equivalence given by the axiom an instance protected definition inst [instance] : IsEquiv (@equiv_path.{k} A B) := rec_on F (Ξ» H, H A B) -- This is the version of univalence axiom we will probably use most often definition ua : A ≃ B β†’ A β‰ˆ B := @IsEquiv.inv _ _ (@equiv_path A B) inst end end ua_type -- One consequence of UA is that we can transport along equivalencies of types namespace Equiv universe variable l protected definition subst [UA : ua_type] (P : Type β†’ Type) {A B : Type.{l}} (H : A ≃ B) : P A β†’ P B := path.transport P (ua_type.ua H) -- We can use this for calculation evironments calc_subst subst end Equiv
3321c8ba2dda043f7b80b601cc9de5b1adf41292
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/interactive/t10.lean
fbf8b46de5e0e2f6f1ff53e65bfbad7f621c366e
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
348
lean
(* simple_tac = Repeat(OrElse(conj_hyp_tac(), conj_tac(), assumption_tac())) *) theorem T2 (A B : Bool) : A /\ B β†’ B /\ A := fun H : A /\ B, let H1 : A := _, H2 : B := _, main : B /\ A := _ in main. simple_tac. done. simple2_tac. done. simple_tac. done. print "echo command after failure"
33db4ee82724ad46d89be8de9f735d3bbfa6e2f9
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/instances/ennreal.lean
602e4d559466fe66385f4050b8b1aa88a8b74ebe
[ "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
47,901
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 topology.instances.nnreal import topology.algebra.ordered.liminf_limsup /-! # Extended non-negative reals -/ noncomputable theory open classical set filter metric open_locale classical topological_space ennreal nnreal big_operators filter variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} namespace ennreal variables {a b c d : ℝβ‰₯0∞} {r p q : ℝβ‰₯0} variables {x y z : ℝβ‰₯0∞} {Ξ΅ Ρ₁ Ξ΅β‚‚ : ℝβ‰₯0∞} {s : set ℝβ‰₯0∞} section topological_space open topological_space /-- Topology on `ℝβ‰₯0∞`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊀}`, while this topology doesn't have singleton elements. -/ instance : topological_space ℝβ‰₯0∞ := preorder.topology ℝβ‰₯0∞ instance : order_topology ℝβ‰₯0∞ := ⟨rfl⟩ instance : t2_space ℝβ‰₯0∞ := by apply_instance -- short-circuit type class inference instance : second_countable_topology ℝβ‰₯0∞ := βŸ¨βŸ¨β‹ƒq β‰₯ (0:β„š), {{a : ℝβ‰₯0∞ | a < nnreal.of_real q}, {a : ℝβ‰₯0∞ | ↑(nnreal.of_real q) < a}}, (countable_encodable _).bUnion $ assume a ha, (countable_singleton _).insert _, le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) (le_generate_from $ Ξ» s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:β„š | 0 ≀ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:β„š | 0 ≀ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end)⟩⟩ lemma embedding_coe : embedding (coe : ℝβ‰₯0 β†’ ℝβ‰₯0∞) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ℝβ‰₯0∞ _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝβ‰₯0 | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : ℝβ‰₯0 | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals ℝβ‰₯0 _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ℝβ‰₯0∞ | a β‰  ⊀} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma open_embedding_coe : open_embedding (coe : ℝβ‰₯0 β†’ ℝβ‰₯0∞) := ⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩ lemma coe_range_mem_nhds : range (coe : ℝβ‰₯0 β†’ ℝβ‰₯0∞) ∈ 𝓝 (r : ℝβ‰₯0∞) := is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _ @[norm_cast] lemma tendsto_coe {f : filter Ξ±} {m : Ξ± β†’ ℝβ‰₯0} {a : ℝβ‰₯0} : tendsto (Ξ»a, (m a : ℝβ‰₯0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe : continuous (coe : ℝβ‰₯0 β†’ ℝβ‰₯0∞) := embedding_coe.continuous lemma continuous_coe_iff {Ξ±} [topological_space Ξ±] {f : Ξ± β†’ ℝβ‰₯0} : continuous (Ξ»a, (f a : ℝβ‰₯0∞)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝβ‰₯0} : 𝓝 (r : ℝβ‰₯0∞) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma nhds_coe_coe {r p : ℝβ‰₯0} : 𝓝 ((r : ℝβ‰₯0∞), (p : ℝβ‰₯0∞)) = (𝓝 (r, p)).map (Ξ»p:ℝβ‰₯0×ℝβ‰₯0, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe_iff.2 continuous_id).comp nnreal.continuous_of_real lemma tendsto_of_real {f : filter Ξ±} {m : Ξ± β†’ ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (Ξ»a, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ℝβ‰₯0∞} (ha : a β‰  ⊀) : tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) := begin lift a to ℝβ‰₯0 using ha, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a β‰  ∞} := Ξ» a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha) lemma tendsto_to_real {a : ℝβ‰₯0∞} (ha : a β‰  ⊀) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) := nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha /-- The set of finite `ℝβ‰₯0∞` numbers is homeomorphic to `ℝβ‰₯0`. -/ def ne_top_homeomorph_nnreal : {a | a β‰  ∞} β‰ƒβ‚œ ℝβ‰₯0 := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_subtype_mk _ continuous_coe, .. ne_top_equiv_nnreal } /-- The set of finite `ℝβ‰₯0∞` numbers is homeomorphic to `ℝβ‰₯0`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} β‰ƒβ‚œ ℝβ‰₯0 := by refine (homeomorph.set_congr $ set.ext $ Ξ» x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] lemma nhds_top : 𝓝 ∞ = β¨… a β‰  ∞, π“Ÿ (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 ∞ = β¨… r : ℝβ‰₯0, π“Ÿ (Ioi r) := nhds_top.trans $ infi_ne_top _ lemma tendsto_nhds_top_iff_nnreal {m : Ξ± β†’ ℝβ‰₯0∞} {f : filter Ξ±} : tendsto m f (𝓝 ⊀) ↔ βˆ€ x : ℝβ‰₯0, βˆ€αΆ  a in f, ↑x < m a := by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi] lemma tendsto_nhds_top_iff_nat {m : Ξ± β†’ ℝβ‰₯0∞} {f : filter Ξ±} : tendsto m f (𝓝 ⊀) ↔ βˆ€ n : β„•, βˆ€αΆ  a in f, ↑n < m a := tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n, Ξ» h x, let ⟨n, hn⟩ := exists_nat_gt x in (h n).mono (Ξ» y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩ lemma tendsto_nhds_top {m : Ξ± β†’ ℝβ‰₯0∞} {f : filter Ξ±} (h : βˆ€ n : β„•, βˆ€αΆ  a in f, ↑n < m a) : tendsto m f (𝓝 ⊀) := tendsto_nhds_top_iff_nat.2 h lemma tendsto_nat_nhds_top : tendsto (Ξ» n : β„•, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ Ξ» n, mem_at_top_sets.2 ⟨n+1, Ξ» m hm, ennreal.coe_nat_lt_coe_nat.2 $ nat.lt_of_succ_le hm⟩ @[simp, norm_cast] lemma tendsto_coe_nhds_top {f : Ξ± β†’ ℝβ‰₯0} {l : filter Ξ±} : tendsto (Ξ» x, (f x : ℝβ‰₯0∞)) l (𝓝 ∞) ↔ tendsto f l at_top := by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff]; [simp, apply_instance, apply_instance] lemma nhds_zero : 𝓝 (0 : ℝβ‰₯0∞) = β¨…a β‰  0, π“Ÿ (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] @[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝβ‰₯0} : (𝓝[Ioi r] (r : ℝβ‰₯0∞)).ne_bot := nhds_within_Ioi_self_ne_bot' ennreal.coe_lt_top @[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[Ioi 0] (0 : ℝβ‰₯0∞)).ne_bot := nhds_within_Ioi_coe_ne_bot -- using Icc because -- β€’ don't have 'Ioo (x - Ξ΅) (x + Ξ΅) ∈ 𝓝 x' unless x > 0 -- β€’ (x - y ≀ Ξ΅ ↔ x ≀ Ξ΅ + y) is true, while (x - y < Ξ΅ ↔ x < Ξ΅ + y) is not lemma Icc_mem_nhds : x β‰  ⊀ β†’ 0 < Ξ΅ β†’ Icc (x - Ξ΅) (x + Ξ΅) ∈ 𝓝 x := begin assume xt Ξ΅0, rw _root_.mem_nhds_iff, by_cases x0 : x = 0, { use Iio (x + Ξ΅), have : Iio (x + Ξ΅) βŠ† Icc (x - Ξ΅) (x + Ξ΅), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt Ξ΅0⟩ }, { use Ioo (x - Ξ΅) (x + Ξ΅), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 Ξ΅0 Ξ΅0 ⟩ } end lemma nhds_of_ne_top : x β‰  ⊀ β†’ 𝓝 x = β¨…Ξ΅ > 0, π“Ÿ (Icc (x - Ξ΅) (x + Ξ΅)) := begin assume xt, refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume Ξ΅ Ξ΅0, exact Icc_mem_nhds xt Ξ΅0, -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), simp only [mem_set_of_eq] at hs, rcases hs with ⟨xs, ⟨a, ha⟩⟩, cases ha, { rw ha at *, rcases exists_between xs with ⟨b, ⟨ab, bx⟩⟩, have xb_pos : x - b > 0 := zero_lt_sub_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel (by rwa lt_top_iff_ne_top) (le_of_lt bx), refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal_sets, le_principal_iff], assume y, rintros ⟨h₁, hβ‚‚βŸ©, rw xxb at h₁, calc a < b : ab ... ≀ y : h₁ }, { rw ha at *, rcases exists_between xs with ⟨b, ⟨xb, ba⟩⟩, have bx_pos : b - x > 0 := zero_lt_sub_iff_lt.2 xb, have xbx : x + (b - x) = b := add_sub_cancel_of_le (le_of_lt xb), refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal_sets, le_principal_iff], assume y, rintros ⟨h₁, hβ‚‚βŸ©, rw xbx at hβ‚‚, calc y ≀ b : hβ‚‚ ... < a : ba }, end /-- Characterization of neighborhoods for `ℝβ‰₯0∞` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter Ξ±} {u : Ξ± β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} (ha : a β‰  ⊀) : tendsto u f (𝓝 a) ↔ βˆ€ Ξ΅ > 0, βˆ€αΆ  x in f, (u x) ∈ Icc (a - Ξ΅) (a + Ξ΅) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_at_top [nonempty Ξ²] [semilattice_sup Ξ²] {f : Ξ² β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} (ha : a β‰  ⊀) : tendsto f at_top (𝓝 a) ↔ βˆ€Ξ΅>0, βˆƒN, βˆ€nβ‰₯N, (f n) ∈ Icc (a - Ξ΅) (a + Ξ΅) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] instance : has_continuous_add ℝβ‰₯0∞ := begin refine ⟨continuous_iff_continuous_at.2 _⟩, rintro ⟨(_|a), b⟩, { exact tendsto_nhds_top_mono' continuous_at_fst (Ξ» p, le_add_right le_rfl) }, rcases b with (_|b), { exact tendsto_nhds_top_mono' continuous_at_snd (Ξ» p, le_add_left le_rfl) }, simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] end protected lemma tendsto_at_top_zero [hΞ² : nonempty Ξ²] [semilattice_sup Ξ²] {f : Ξ² β†’ ℝβ‰₯0∞} : filter.at_top.tendsto f (𝓝 0) ↔ βˆ€ Ξ΅ > 0, βˆƒ N, βˆ€ n β‰₯ N, f n ≀ Ξ΅ := begin rw ennreal.tendsto_at_top zero_ne_top, { simp_rw [set.mem_Icc, zero_add, zero_sub, zero_le _, true_and], }, { exact hΞ², }, end protected lemma tendsto_mul (ha : a β‰  0 ∨ b β‰  ⊀) (hb : b β‰  0 ∨ a β‰  ⊀) : tendsto (Ξ»p:ℝβ‰₯0βˆžΓ—β„β‰₯0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : βˆ€b:ℝβ‰₯0∞, b β‰  0 β†’ tendsto (Ξ»p:ℝβ‰₯0βˆžΓ—β„β‰₯0∞, p.1 * p.2) (𝓝 ((⊀:ℝβ‰₯0∞), b)) (𝓝 ⊀), begin refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _, rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨Ρ, hΞ΅, hΞ΅b⟩, replace hΞ΅ : 0 < Ξ΅, from coe_pos.1 hΞ΅, filter_upwards [prod_is_open.mem_nhds (lt_mem_nhds $ @coe_lt_top (n / Ξ΅)) (lt_mem_nhds hΞ΅b)], rintros ⟨a₁, aβ‚‚βŸ© ⟨h₁, hβ‚‚βŸ©, dsimp at h₁ hβ‚‚ ⊒, rw [← div_mul_cancel n hΞ΅.ne', coe_mul], exact mul_lt_mul h₁ hβ‚‚ end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ℝβ‰₯0∞) ⊀, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter Ξ±} {ma : Ξ± β†’ ℝβ‰₯0∞} {mb : Ξ± β†’ ℝβ‰₯0∞} {a b : ℝβ‰₯0∞} (hma : tendsto ma f (𝓝 a)) (ha : a β‰  0 ∨ b β‰  ⊀) (hmb : tendsto mb f (𝓝 b)) (hb : b β‰  0 ∨ a β‰  ⊀) : tendsto (Ξ»a, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((Ξ»p:ℝβ‰₯0βˆžΓ—β„β‰₯0∞, p.1 * p.2) ∘ (Ξ»a, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) protected lemma tendsto.const_mul {f : filter Ξ±} {m : Ξ± β†’ ℝβ‰₯0∞} {a b : ℝβ‰₯0∞} (hm : tendsto m f (𝓝 b)) (hb : b β‰  0 ∨ a β‰  ⊀) : tendsto (Ξ»b, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a β‰  0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter Ξ±} {m : Ξ± β†’ ℝβ‰₯0∞} {a b : ℝβ‰₯0∞} (hm : tendsto m f (𝓝 a)) (ha : a β‰  0 ∨ b β‰  ⊀) : tendsto (Ξ»x, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha protected lemma continuous_at_const_mul {a b : ℝβ‰₯0∞} (h : a β‰  ⊀ ∨ b β‰  0) : continuous_at ((*) a) b := tendsto.const_mul tendsto_id h.symm protected lemma continuous_at_mul_const {a b : ℝβ‰₯0∞} (h : a β‰  ⊀ ∨ b β‰  0) : continuous_at (Ξ» x, x * a) b := tendsto.mul_const tendsto_id h.symm protected lemma continuous_const_mul {a : ℝβ‰₯0∞} (ha : a β‰  ⊀) : continuous ((*) a) := continuous_iff_continuous_at.2 $ Ξ» x, ennreal.continuous_at_const_mul (or.inl ha) protected lemma continuous_mul_const {a : ℝβ‰₯0∞} (ha : a β‰  ⊀) : continuous (Ξ» x, x * a) := continuous_iff_continuous_at.2 $ Ξ» x, ennreal.continuous_at_mul_const (or.inl ha) lemma le_of_forall_lt_one_mul_le {x y : ℝβ‰₯0∞} (h : βˆ€ a < 1, a * x ≀ y) : x ≀ y := begin have : tendsto (* x) (𝓝[Iio 1] 1) (𝓝 (1 * x)) := (ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left, rw one_mul at this, haveI : (𝓝[Iio 1] (1 : ℝβ‰₯0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ennreal.zero_lt_one, exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h) end lemma infi_mul_left' {ΞΉ} {f : ΞΉ β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} (h : a = ⊀ β†’ (β¨… i, f i) = 0 β†’ βˆƒ i, f i = 0) (h0 : a = 0 β†’ nonempty ΞΉ) : (β¨… i, a * f i) = a * β¨… i, f i := begin by_cases H : a = ⊀ ∧ (β¨… i, f i) = 0, { rcases h H.1 H.2 with ⟨i, hi⟩, rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot], exact Ξ» b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ }, { rw not_and_distrib at H, by_cases hΞΉ : nonempty ΞΉ, { resetI, exact (map_infi_of_continuous_at_of_monotone' (ennreal.continuous_at_const_mul H) ennreal.mul_left_mono).symm }, { rw [infi_of_empty hΞΉ, infi_of_empty hΞΉ, mul_top, if_neg], exact mt h0 hΞΉ } } end lemma infi_mul_left {ΞΉ} [nonempty ΞΉ] {f : ΞΉ β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} (h : a = ⊀ β†’ (β¨… i, f i) = 0 β†’ βˆƒ i, f i = 0) : (β¨… i, a * f i) = a * β¨… i, f i := infi_mul_left' h (Ξ» _, β€Ήnonempty ΞΉβ€Ί) lemma infi_mul_right' {ΞΉ} {f : ΞΉ β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} (h : a = ⊀ β†’ (β¨… i, f i) = 0 β†’ βˆƒ i, f i = 0) (h0 : a = 0 β†’ nonempty ΞΉ) : (β¨… i, f i * a) = (β¨… i, f i) * a := by simpa only [mul_comm a] using infi_mul_left' h h0 lemma infi_mul_right {ΞΉ} [nonempty ΞΉ] {f : ΞΉ β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} (h : a = ⊀ β†’ (β¨… i, f i) = 0 β†’ βˆƒ i, f i = 0) : (β¨… i, f i * a) = (β¨… i, f i) * a := infi_mul_right' h (Ξ» _, β€Ήnonempty ΞΉβ€Ί) protected lemma continuous_inv : continuous (has_inv.inv : ℝβ‰₯0∞ β†’ ℝβ‰₯0∞) := continuous_iff_continuous_at.2 $ Ξ» a, tendsto_order.2 ⟨begin assume b hb, simp only [@ennreal.lt_inv_iff_lt_inv b], exact gt_mem_nhds (ennreal.lt_inv_iff_lt_inv.1 hb), end, begin assume b hb, simp only [gt_iff_lt, @ennreal.inv_lt_iff_inv_lt _ b], exact lt_mem_nhds (ennreal.inv_lt_iff_inv_lt.1 hb) end⟩ @[simp] protected lemma tendsto_inv_iff {f : filter Ξ±} {m : Ξ± β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} : tendsto (Ξ» x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [function.comp, ennreal.inv_inv] using (ennreal.continuous_inv.tendsto a⁻¹).comp h, (ennreal.continuous_inv.tendsto a).comp⟩ protected lemma tendsto.div {f : filter Ξ±} {ma : Ξ± β†’ ℝβ‰₯0∞} {mb : Ξ± β†’ ℝβ‰₯0∞} {a b : ℝβ‰₯0∞} (hma : tendsto ma f (𝓝 a)) (ha : a β‰  0 ∨ b β‰  0) (hmb : tendsto mb f (𝓝 b)) (hb : b β‰  ⊀ ∨ a β‰  ⊀) : tendsto (Ξ»a, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter Ξ±} {m : Ξ± β†’ ℝβ‰₯0∞} {a b : ℝβ‰₯0∞} (hm : tendsto m f (𝓝 b)) (hb : b β‰  ⊀ ∨ a β‰  ⊀) : tendsto (Ξ»b, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter Ξ±} {m : Ξ± β†’ ℝβ‰₯0∞} {a b : ℝβ‰₯0∞} (hm : tendsto m f (𝓝 a)) (ha : a β‰  0 ∨ b β‰  0) : tendsto (Ξ»x, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (Ξ» n : β„•, (n : ℝβ‰₯0∞)⁻¹) at_top (𝓝 0) := ennreal.inv_top β–Έ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma bsupr_add {ΞΉ} {s : set ΞΉ} (hs : s.nonempty) {f : ΞΉ β†’ ℝβ‰₯0∞} : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := begin simp only [← Sup_image], symmetry, rw [image_comp (+ a)], refine is_lub.Sup_eq ((is_lub_Sup $ f '' s).is_lub_of_tendsto _ (hs.image _) _), exacts [Ξ» x _ y _ hxy, add_le_add hxy le_rfl, tendsto.add (tendsto_id' inf_le_left) tendsto_const_nhds] end lemma Sup_add {s : set ℝβ‰₯0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := by rw [Sup_eq_supr, bsupr_add hs] lemma supr_add {ΞΉ : Sort*} {s : ΞΉ β†’ ℝβ‰₯0∞} [h : nonempty ΞΉ] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by rw Sup_range ... = (⨆b∈range s, b + a) : Sup_add ⟨s x, x, rfl⟩ ... = _ : supr_range lemma add_supr {ΞΉ : Sort*} {s : ΞΉ β†’ ℝβ‰₯0∞} [h : nonempty ΞΉ] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr {ΞΉ : Sort*} {f g : ΞΉ β†’ ℝβ‰₯0∞} (h : βˆ€i j, βˆƒk, f i + g j ≀ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hΞΉ : nonempty ΞΉ, { letI := hΞΉ, refine le_antisymm _ (supr_le $ Ξ» a, add_le_add (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using Ξ» i j:ΞΉ, show f i + g j ≀ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : βˆ€f:ΞΉ β†’ ℝβ‰₯0∞, (⨆i, f i) = 0 := Ξ» f, supr_eq_zero.mpr (Ξ» i, (hΞΉ ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ΞΉ : Sort*} [semilattice_sup ΞΉ] {f g : ΞΉ β†’ ℝβ‰₯0∞} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i βŠ” j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {Ξ±} {ΞΉ} [semilattice_sup ΞΉ] {s : finset Ξ±} {f : Ξ± β†’ ΞΉ β†’ ℝβ‰₯0∞} (hf : βˆ€a, monotone (f a)) : βˆ‘ a in s, supr (f a) = (⨆ n, βˆ‘ a in s, f a n) := begin refine finset.induction_on s _ _, { simp, }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end lemma mul_Sup {s : set ℝβ‰₯0∞} {a : ℝβ‰₯0∞} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : βˆ€x∈s, x = (0:ℝβ‰₯0∞), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm β–Έ le_refl 0), have hβ‚‚ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, hβ‚‚, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₁ : Sup s β‰  0 := pos_iff_ne_zero.1 (lt_of_lt_of_le (pos_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((Ξ»b, a * b) '' s) = a * Sup s := is_lub.Sup_eq ((is_lub_Sup s).is_lub_of_tendsto (assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h) ⟨x, hx⟩ (ennreal.tendsto.const_mul (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end lemma mul_supr {ΞΉ : Sort*} {f : ΞΉ β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ΞΉ : Sort*} {f : ΞΉ β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] protected lemma tendsto_coe_sub : βˆ€{b:ℝβ‰₯0∞}, tendsto (Ξ»b:ℝβ‰₯0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine (forall_ennreal.2 $ and.intro (assume a, _) _), { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm], exact tendsto_const_nhds.sub tendsto_id }, simp, exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ΞΉ : Sort*} [nonempty ΞΉ] {b : ΞΉ β†’ ℝβ‰₯0∞} (hr : a < ⊀) : a - (⨆i, b i) = (β¨…i, a - b i) := let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((Ξ»b, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto (assume x _ y _, sub_le_sub (le_refl _)) (range_nonempty _) (ennreal.tendsto_coe_sub.comp (tendsto_id' inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _ end topological_space section tsum variables {f g : Ξ± β†’ ℝβ‰₯0∞} @[norm_cast] protected lemma has_sum_coe {f : Ξ± β†’ ℝβ‰₯0} {r : ℝβ‰₯0} : has_sum (Ξ»a, (f a : ℝβ‰₯0∞)) ↑r ↔ has_sum f r := have (Ξ»s:finset Ξ±, βˆ‘ a in s, ↑(f a)) = (coe : ℝβ‰₯0 β†’ ℝβ‰₯0∞) ∘ (Ξ»s:finset Ξ±, βˆ‘ a in s, f a), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : Ξ± β†’ ℝβ‰₯0} (h : has_sum f r) : βˆ‘'a, (f a : ℝβ‰₯0∞) = r := (ennreal.has_sum_coe.2 h).tsum_eq protected lemma coe_tsum {f : Ξ± β†’ ℝβ‰₯0} : summable f β†’ ↑(tsum f) = βˆ‘'a, (f a : ℝβ‰₯0∞) | ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset Ξ±, βˆ‘ a in s, f a) := tendsto_at_top_supr $ Ξ» s t, finset.sum_le_sum_of_subset @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : Ξ² β†’ ℝβ‰₯0} : βˆ‘' b, (f b:ℝβ‰₯0∞) β‰  ∞ ↔ summable f := begin refine ⟨λ h, _, Ξ» h, ennreal.coe_tsum h β–Έ ennreal.coe_ne_top⟩, lift (βˆ‘' b, (f b:ℝβ‰₯0∞)) to ℝβ‰₯0 using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : βˆ‘'a, f a = (⨆s:finset Ξ±, βˆ‘ a in s, f a) := ennreal.has_sum.tsum_eq protected lemma tsum_eq_supr_sum' {ΞΉ : Type*} (s : ΞΉ β†’ finset Ξ±) (hs : βˆ€ t, βˆƒ i, t βŠ† s i) : βˆ‘' a, f a = ⨆ i, βˆ‘ a in s i, f a := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ΞΉ, (Ξ» t : finset Ξ±, βˆ‘ a in t, f a) (s i)) = ⨆s:finset Ξ±, βˆ‘ a in s, f a, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {Ξ² : Ξ± β†’ Type*} (f : Ξ a, Ξ² a β†’ ℝβ‰₯0∞) : βˆ‘'p:Ξ£a, Ξ² a, f p.1 p.2 = βˆ‘'a b, f a b := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {Ξ² : Ξ± β†’ Type*} (f : (Ξ£ a, Ξ² a) β†’ ℝβ‰₯0∞) : βˆ‘'p:(Ξ£a, Ξ² a), f p = βˆ‘'a b, f ⟨a, b⟩ := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : Ξ± β†’ Ξ² β†’ ℝβ‰₯0∞} : βˆ‘'p:Ξ±Γ—Ξ², f p.1 p.2 = βˆ‘'a, βˆ‘'b, f a b := tsum_prod' ennreal.summable $ Ξ» _, ennreal.summable protected lemma tsum_comm {f : Ξ± β†’ Ξ² β†’ ℝβ‰₯0∞} : βˆ‘'a, βˆ‘'b, f a b = βˆ‘'b, βˆ‘'a, f a b := tsum_comm' ennreal.summable (Ξ» _, ennreal.summable) (Ξ» _, ennreal.summable) protected lemma tsum_add : βˆ‘'a, (f a + g a) = (βˆ‘'a, f a) + (βˆ‘'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : βˆ€a, f a ≀ g a) : βˆ‘'a, f a ≀ βˆ‘'a, g a := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma sum_le_tsum {f : Ξ± β†’ ℝβ‰₯0∞} (s : finset Ξ±) : βˆ‘ x in s, f x ≀ βˆ‘' x, f x := sum_le_tsum s (Ξ» x hx, zero_le _) ennreal.summable protected lemma tsum_eq_supr_nat' {f : β„• β†’ ℝβ‰₯0∞} {N : β„• β†’ β„•} (hN : tendsto N at_top at_top) : βˆ‘'i:β„•, f i = (⨆i:β„•, βˆ‘ a in finset.range (N i), f a) := ennreal.tsum_eq_supr_sum' _ $ Ξ» t, let ⟨n, hn⟩ := t.exists_nat_subset_range, ⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in ⟨k, finset.subset.trans hn (finset.range_mono hk)⟩ protected lemma tsum_eq_supr_nat {f : β„• β†’ ℝβ‰₯0∞} : βˆ‘'i:β„•, f i = (⨆i:β„•, βˆ‘ a in finset.range i, f a) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma tsum_eq_liminf_sum_nat {f : β„• β†’ ℝβ‰₯0∞} : βˆ‘' i, f i = filter.at_top.liminf (Ξ» n, βˆ‘ i in finset.range n, f i) := begin rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat], congr, refine funext (Ξ» n, le_antisymm _ _), { refine le_binfi (Ξ» i hi, finset.sum_le_sum_of_subset_of_nonneg _ (Ξ» _ _ _, zero_le _)), simpa only [finset.range_subset, add_le_add_iff_right] using hi, }, { refine le_trans (infi_le _ n) _, simp [le_refl n, le_refl ((finset.range n).sum f)], }, end protected lemma le_tsum (a : Ξ±) : f a ≀ βˆ‘'a, f a := le_tsum' ennreal.summable a protected lemma tsum_eq_top_of_eq_top : (βˆƒ a, f a = ∞) β†’ βˆ‘' a, f a = ∞ | ⟨a, ha⟩ := top_unique $ ha β–Έ ennreal.le_tsum a @[simp] protected lemma tsum_top [nonempty Ξ±] : βˆ‘' a : Ξ±, ∞ = ∞ := let ⟨a⟩ := β€Ήnonempty Ξ±β€Ί in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩ protected lemma ne_top_of_tsum_ne_top (h : βˆ‘' a, f a β‰  ∞) (a : Ξ±) : f a β‰  ∞ := Ξ» ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : βˆ‘'i, a * f i = a * βˆ‘'i, f i := if h : βˆ€i, f i = 0 then by simp [h] else let ⟨i, (hi : f i β‰  0)⟩ := not_forall.mp h in have sum_ne_0 : βˆ‘'i, f i β‰  0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≀ βˆ‘'i, f i : ennreal.le_tsum _, have tendsto (Ξ»s:finset Ξ±, βˆ‘ j in s, a * f j) at_top (𝓝 (a * βˆ‘'i, f i)), by rw [← show (*) a ∘ (Ξ»s:finset Ξ±, βˆ‘ j in s, f j) = Ξ»s, βˆ‘ j in s, a * f j, from funext $ Ξ» s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), has_sum.tsum_eq this protected lemma tsum_mul_right : (βˆ‘'i, f i * a) = (βˆ‘'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] @[simp] lemma tsum_supr_eq {Ξ± : Type*} (a : Ξ±) {f : Ξ± β†’ ℝβ‰₯0∞} : βˆ‘'b:Ξ±, (⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (βˆ‘ b in s, ⨆ (h : a = b), f b) ≀ βˆ‘ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≀ (⨆ (h : a = a), f a) : le_supr (Ξ»h:a=a, f a) rfl ... ≀ (βˆ‘'b:Ξ±, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : β„• β†’ ℝβ‰₯0∞} (r : ℝβ‰₯0∞) : has_sum f r ↔ tendsto (Ξ»n:β„•, βˆ‘ i in finset.range n, f i) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end lemma tendsto_nat_tsum (f : β„• β†’ ℝβ‰₯0∞) : tendsto (Ξ»n:β„•, βˆ‘ i in finset.range n, f i) at_top (𝓝 (βˆ‘' n, f n)) := by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum } lemma to_nnreal_apply_of_tsum_ne_top {Ξ± : Type*} {f : Ξ± β†’ ℝβ‰₯0∞} (hf : βˆ‘' i, f i β‰  ∞) (x : Ξ±) : (((ennreal.to_nnreal ∘ f) x : ℝβ‰₯0) : ℝβ‰₯0∞) = f x := coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _ lemma summable_to_nnreal_of_tsum_ne_top {Ξ± : Type*} {f : Ξ± β†’ ℝβ‰₯0∞} (hf : βˆ‘' i, f i β‰  ∞) : summable (ennreal.to_nnreal ∘ f) := by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf lemma tendsto_cofinite_zero_of_tsum_lt_top {Ξ±} {f : Ξ± β†’ ℝβ‰₯0∞} (hf : βˆ‘' x, f x < ∞) : tendsto f cofinite (𝓝 0) := begin have f_ne_top : βˆ€ n, f n β‰  ∞, from ennreal.ne_top_of_tsum_ne_top hf.ne, have h_f_coe : f = Ξ» n, ((f n).to_nnreal : ennreal), from funext (Ξ» n, (coe_to_nnreal (f_ne_top n)).symm), rw [h_f_coe, ←@coe_zero, tendsto_coe], exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf.ne), end lemma tendsto_at_top_zero_of_tsum_lt_top {f : β„• β†’ ℝβ‰₯0∞} (hf : βˆ‘' x, f x < ∞) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_lt_top hf } protected lemma tsum_apply {ΞΉ Ξ± : Type*} {f : ΞΉ β†’ Ξ± β†’ ℝβ‰₯0∞} {x : Ξ±} : (βˆ‘' i, f i) x = βˆ‘' i, f i x := tsum_apply $ pi.summable.mpr $ Ξ» _, ennreal.summable lemma tsum_sub {f : β„• β†’ ℝβ‰₯0∞} {g : β„• β†’ ℝβ‰₯0∞} (h₁ : βˆ‘' i, g i < ∞) (hβ‚‚ : g ≀ f) : βˆ‘' i, (f i - g i) = (βˆ‘' i, f i) - (βˆ‘' i, g i) := begin have h₃: βˆ‘' i, (f i - g i) = βˆ‘' i, (f i - g i + g i) - βˆ‘' i, g i, { rw [ennreal.tsum_add, add_sub_self h₁]}, have hβ‚„:(Ξ» i, (f i - g i) + (g i)) = f, { ext n, rw ennreal.sub_add_cancel_of_le (hβ‚‚ n)}, rw hβ‚„ at h₃, apply h₃, end end tsum end ennreal namespace nnreal open_locale nnreal /-- Comparison test of convergence of `ℝβ‰₯0`-valued series. -/ lemma exists_le_has_sum_of_le {f g : Ξ² β†’ ℝβ‰₯0} {r : ℝβ‰₯0} (hgf : βˆ€b, g b ≀ f b) (hfr : has_sum f r) : βˆƒp≀r, has_sum g p := have βˆ‘'b, (g b : ℝβ‰₯0∞) ≀ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq β–Έ ennreal.summable.has_sum⟩ /-- Comparison test of convergence of `ℝβ‰₯0`-valued series. -/ lemma summable_of_le {f g : Ξ² β†’ ℝβ‰₯0} (hgf : βˆ€b, g b ≀ f b) : summable f β†’ summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat {f : β„• β†’ ℝβ‰₯0} {r : ℝβ‰₯0} : has_sum f r ↔ tendsto (Ξ»n:β„•, βˆ‘ i in finset.range n, f i) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma not_summable_iff_tendsto_nat_at_top {f : β„• β†’ ℝβ‰₯0} : Β¬ summable f ↔ tendsto (Ξ» n : β„•, βˆ‘ i in finset.range n, f i) at_top at_top := begin split, { intros h, refine ((tendsto_of_monotone _).resolve_right h).comp _, exacts [finset.sum_mono_set _, tendsto_finset_range] }, { rintros hnat ⟨r, hr⟩, exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) } end lemma summable_iff_not_tendsto_nat_at_top {f : β„• β†’ ℝβ‰₯0} : summable f ↔ Β¬ tendsto (Ξ» n : β„•, βˆ‘ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top] lemma summable_of_sum_range_le {f : β„• β†’ ℝβ‰₯0} {c : ℝβ‰₯0} (h : βˆ€ n, βˆ‘ i in finset.range n, f i ≀ c) : summable f := begin apply summable_iff_not_tendsto_nat_at_top.2 (Ξ» H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : β„• β†’ ℝβ‰₯0} {c : ℝβ‰₯0} (h : βˆ€ n, βˆ‘ i in finset.range n, f i ≀ c) : βˆ‘' n, f n ≀ c := le_of_tendsto' (has_sum_iff_tendsto_nat.1 (summable_of_sum_range_le h).has_sum) h lemma tsum_comp_le_tsum_of_inj {Ξ² : Type*} {f : Ξ± β†’ ℝβ‰₯0} (hf : summable f) {i : Ξ² β†’ Ξ±} (hi : function.injective i) : βˆ‘' x, f (i x) ≀ βˆ‘' x, f x := tsum_le_tsum_of_inj i hi (Ξ» c hc, zero_le _) (Ξ» b, le_refl _) (summable_comp_injective hf hi) hf lemma summable_sigma {Ξ² : Ξ  x : Ξ±, Type*} {f : (Ξ£ x, Ξ² x) β†’ ℝβ‰₯0} : summable f ↔ (βˆ€ x, summable (Ξ» y, f ⟨x, y⟩)) ∧ summable (Ξ» x, βˆ‘' y, f ⟨x, y⟩) := begin split, { simp only [← nnreal.summable_coe, nnreal.coe_tsum], exact Ξ» h, ⟨h.sigma_factor, h.sigma⟩ }, { rintro ⟨h₁, hβ‚‚βŸ©, simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁] using hβ‚‚ } end lemma indicator_summable {f : Ξ± β†’ ℝβ‰₯0} (hf : summable f) (s : set Ξ±) : summable (s.indicator f) := begin refine nnreal.summable_of_le (Ξ» a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf, split_ifs, exact le_refl (f a), exact zero_le_coe, end lemma tsum_indicator_ne_zero {f : Ξ± β†’ ℝβ‰₯0} (hf : summable f) {s : set Ξ±} (h : βˆƒ a ∈ s, f a β‰  0) : βˆ‘' x, (s.indicator f) x β‰  0 := Ξ» h', let ⟨a, ha, hap⟩ := h in hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm (((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a)) open finset /-- For `f : β„• β†’ ℝβ‰₯0`, then `βˆ‘' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add (f : β„• β†’ ℝβ‰₯0) : tendsto (Ξ» i, βˆ‘' k, f (k + i)) at_top (𝓝 0) := begin rw ← tendsto_coe, convert tendsto_sum_nat_add (Ξ» i, (f i : ℝ)), norm_cast, end end nnreal namespace ennreal lemma tendsto_sum_nat_add (f : β„• β†’ ℝβ‰₯0∞) (hf : βˆ‘' i, f i β‰  ∞) : tendsto (Ξ» i, βˆ‘' k, f (k + i)) at_top (𝓝 0) := begin lift f to β„• β†’ ℝβ‰₯0 using ennreal.ne_top_of_tsum_ne_top hf, replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf, simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero], exact_mod_cast nnreal.tendsto_sum_nat_add f end end ennreal lemma tsum_comp_le_tsum_of_inj {Ξ² : Type*} {f : Ξ± β†’ ℝ} (hf : summable f) (hn : βˆ€ a, 0 ≀ f a) {i : Ξ² β†’ Ξ±} (hi : function.injective i) : tsum (f ∘ i) ≀ tsum f := begin let g : Ξ± β†’ ℝβ‰₯0 := Ξ» a, ⟨f a, hn a⟩, have hg : summable g, by rwa ← nnreal.summable_coe, convert nnreal.coe_le_coe.2 (nnreal.tsum_comp_le_tsum_of_inj hg hi); { rw nnreal.coe_tsum, congr } end /-- Comparison test of convergence of series of non-negative real numbers. -/ lemma summable_of_nonneg_of_le {f g : Ξ² β†’ ℝ} (hg : βˆ€b, 0 ≀ g b) (hgf : βˆ€b, g b ≀ f b) (hf : summable f) : summable g := let f' (b : Ξ²) : ℝβ‰₯0 := ⟨f b, le_trans (hg b) (hgf b)⟩ in let g' (b : Ξ²) : ℝβ‰₯0 := ⟨g b, hg b⟩ in have summable f', from nnreal.summable_coe.1 hf, have summable g', from nnreal.summable_of_le (assume b, (@nnreal.coe_le_coe (g' b) (f' b)).2 $ hgf b) this, show summable (Ξ»b, g' b : Ξ² β†’ ℝ), from nnreal.summable_coe.2 this /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat_of_nonneg {f : β„• β†’ ℝ} (hf : βˆ€i, 0 ≀ f i) (r : ℝ) : has_sum f r ↔ tendsto (Ξ» n : β„•, βˆ‘ i in finset.range n, f i) at_top (𝓝 r) := begin lift f to β„• β†’ ℝβ‰₯0 using hf, simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'], exact exists_congr (Ξ» hr, nnreal.has_sum_iff_tendsto_nat) end lemma ennreal.of_real_tsum_of_nonneg {f : Ξ± β†’ ℝ} (hf_nonneg : βˆ€ n, 0 ≀ f n) (hf : summable f) : ennreal.of_real (βˆ‘' n, f n) = βˆ‘' n, ennreal.of_real (f n) := by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq (nnreal.has_sum_of_real_of_nonneg hf_nonneg hf)] lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : β„• β†’ ℝ} (hf : βˆ€ n, 0 ≀ f n) : Β¬ summable f ↔ tendsto (Ξ» n : β„•, βˆ‘ i in finset.range n, f i) at_top at_top := begin lift f to β„• β†’ ℝβ‰₯0 using hf, exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top end lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : β„• β†’ ℝ} (hf : βˆ€ n, 0 ≀ f n) : summable f ↔ Β¬ tendsto (Ξ» n : β„•, βˆ‘ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf] lemma summable_sigma_of_nonneg {Ξ² : Ξ  x : Ξ±, Type*} {f : (Ξ£ x, Ξ² x) β†’ ℝ} (hf : βˆ€ x, 0 ≀ f x) : summable f ↔ (βˆ€ x, summable (Ξ» y, f ⟨x, y⟩)) ∧ summable (Ξ» x, βˆ‘' y, f ⟨x, y⟩) := by { lift f to (Ξ£ x, Ξ² x) β†’ ℝβ‰₯0 using hf, exact_mod_cast nnreal.summable_sigma } lemma summable_of_sum_range_le {f : β„• β†’ ℝ} {c : ℝ} (hf : βˆ€ n, 0 ≀ f n) (h : βˆ€ n, βˆ‘ i in finset.range n, f i ≀ c) : summable f := begin apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (Ξ» H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : β„• β†’ ℝ} {c : ℝ} (hf : βˆ€ n, 0 ≀ f n) (h : βˆ€ n, βˆ‘ i in finset.range n, f i ≀ c) : βˆ‘' n, f n ≀ c := le_of_tendsto' ((has_sum_iff_tendsto_nat_of_nonneg hf _).1 (summable_of_sum_range_le hf h).has_sum) h /-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable series and at least one term of `f` is strictly smaller than the corresponding term in `g`, then the series of `f` is strictly smaller than the series of `g`. -/ lemma tsum_lt_tsum_of_nonneg {i : β„•} {f g : β„• β†’ ℝ} (h0 : βˆ€ (b : β„•), 0 ≀ f b) (h : βˆ€ (b : β„•), f b ≀ g b) (hi : f i < g i) (hg : summable g) : βˆ‘' n, f n < βˆ‘' n, g n := tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg section variables [emetric_space Ξ²] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : Ξ²} {r : ℝβ‰₯0∞} (x y : ball a r) : edist x.1 y.1 β‰  ⊀ := lt_top_iff_ne_top.1 $ calc edist x y ≀ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≀ ⊀ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : Ξ²) (r : ℝβ‰₯0∞) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : Ξ²) (r : ℝβ‰₯0∞) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r β†’ Ξ²) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm end section variable [pseudo_emetric_space Ξ±] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter Ξ²} {f : Ξ² β†’ Ξ±} {y : Ξ±} : tendsto f l (𝓝 y) ↔ tendsto (Ξ» x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ℝβ‰₯0∞ Ξ² _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty Ξ²] [semilattice_sup Ξ²] {s : Ξ² β†’ Ξ±} : cauchy_seq s ↔ (βˆƒ (b: Ξ² β†’ ℝβ‰₯0∞), (βˆ€ n m N : Ξ², N ≀ n β†’ N ≀ m β†’ edist (s n) (s m) ≀ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m β‰₯ N`-/ let b := Ξ»N, Sup ((Ξ»(p : Ξ² Γ— Ξ²), edist (s p.1) (s p.2))''{p | p.1 β‰₯ N ∧ p.2 β‰₯ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : βˆ€ n m N, N ≀ n β†’ N ≀ m β†’ edist (s n) (s m) ≀ b N, { refine Ξ»m n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λΡ Ξ΅pos, _⟩, rcases exists_between Ξ΅pos with ⟨δ, Ξ΄pos, Ξ΄lt⟩, rcases hs Ξ΄ Ξ΄pos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, Ξ»n hn, _⟩, have : b n ≀ Ξ΄ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p q (le_trans hn hp) (le_trans hn hq)) end, simpa using lt_of_le_of_lt this Ξ΄lt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : β„• β†’ ℝ, b_bound : βˆ€ (n m N : β„•), N ≀ n β†’ N ≀ m β†’ edist (s n) (s m) ≀ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λΡ Ξ΅pos, _), have : βˆ€αΆ  n in at_top, b n < Ξ΅ := (tendsto_order.1 b_lim ).2 _ Ξ΅pos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, Ξ»m n hm hn, calc edist (s m) (s n) ≀ b N : b_bound m n N hm hn ... < Ξ΅ : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : Ξ± β†’ ℝβ‰₯0∞} (C : ℝβ‰₯0∞) (hC : C β‰  ⊀) (h : βˆ€x y, f x ≀ f y + C * edist x y) : continuous f := begin refine continuous_iff_continuous_at.2 (Ξ»x, tendsto_order.2 ⟨_, _⟩), show βˆ€e, e < f x β†’ βˆ€αΆ  y in 𝓝 x, e < f y, { assume e he, let Ξ΅ := min (f x - e) 1, have : Ξ΅ < ⊀ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < Ξ΅ := by simp [Ξ΅, hC, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (Ξ΅/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]), have I : C * (C⁻¹ * (Ξ΅/2)) < Ξ΅, { by_cases C_zero : C = 0, { simp [C_zero, β€Ή0 < Ξ΅β€Ί] }, { calc C * (C⁻¹ * (Ξ΅/2)) = (C * C⁻¹) * (Ξ΅/2) : by simp [mul_assoc] ... = Ξ΅/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < Ξ΅ : ennreal.half_lt_self (β€Ή0 < Ξ΅β€Ί.ne') (β€ΉΞ΅ < βŠ€β€Ί.ne) }}, have : ball x (C⁻¹ * (Ξ΅/2)) βŠ† {y : Ξ± | e < f y}, { rintros y hy, by_cases htop : f y = ⊀, { simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] }, { simp at hy, have : e + Ξ΅ < f y + Ξ΅ := calc e + Ξ΅ ≀ e + (f x - e) : add_le_add_left (min_le_left _ _) _ ... = f x : by simp [le_of_lt he] ... ≀ f y + C * edist x y : h x y ... = f y + C * edist y x : by simp [edist_comm] ... ≀ f y + C * (C⁻¹ * (Ξ΅/2)) : add_le_add_left (canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)) _ ... < f y + Ξ΅ : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I, show e < f y, from (ennreal.add_lt_add_iff_right β€ΉΞ΅ < βŠ€β€Ί).1 this }}, apply filter.mem_sets_of_superset (ball_mem_nhds _ (β€Ή0 < C⁻¹ * (Ξ΅/2)β€Ί)) this }, show βˆ€e, f x < e β†’ βˆ€αΆ  y in 𝓝 x, f y < e, { assume e he, let Ξ΅ := min (e - f x) 1, have : Ξ΅ < ⊀ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < Ξ΅ := by simp [Ξ΅, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (Ξ΅/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, mul_eq_zero]), have I : C * (C⁻¹ * (Ξ΅/2)) < Ξ΅, { by_cases C_zero : C = 0, simp [C_zero, β€Ή0 < Ξ΅β€Ί], calc C * (C⁻¹ * (Ξ΅/2)) = (C * C⁻¹) * (Ξ΅/2) : by simp [mul_assoc] ... = Ξ΅/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < Ξ΅ : ennreal.half_lt_self (β€Ή0 < Ξ΅β€Ί.ne') (β€ΉΞ΅ < βŠ€β€Ί.ne) }, have : ball x (C⁻¹ * (Ξ΅/2)) βŠ† {y : Ξ± | f y < e}, { rintros y hy, have htop : f x β‰  ⊀ := ne_top_of_lt he, show f y < e, from calc f y ≀ f x + C * edist y x : h y x ... ≀ f x + C * (C⁻¹ * (Ξ΅/2)) : add_le_add_left (canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy)) _ ... < f x + Ξ΅ : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I ... ≀ f x + (e - f x) : add_le_add_left (min_le_left _ _) _ ... = e : by simp [le_of_lt he] }, apply filter.mem_sets_of_superset (ball_mem_nhds _ (β€Ή0 < C⁻¹ * (Ξ΅/2)β€Ί)) this }, end theorem continuous_edist : continuous (Ξ»p:Ξ±Γ—Ξ±, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by norm_num), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≀ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≀ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end theorem continuous.edist [topological_space Ξ²] {f g : Ξ² β†’ Ξ±} (hf : continuous f) (hg : continuous g) : continuous (Ξ»b, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg : _) theorem filter.tendsto.edist {f g : Ξ² β†’ Ξ±} {x : filter Ξ²} {a b : Ξ±} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (Ξ»x, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : β„• β†’ Ξ±} (d : β„• β†’ ℝβ‰₯0∞) (hf : βˆ€ n, edist (f n) (f n.succ) ≀ d n) (hd : tsum d β‰  ∞) : cauchy_seq f := begin lift d to (β„• β†’ nnreal) using (Ξ» i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end lemma emetric.is_closed_ball {a : Ξ±} {r : ℝβ‰₯0∞} : is_closed (closed_ball a r) := is_closed_le (continuous_id.edist continuous_const) continuous_const @[simp] lemma emetric.diam_closure (s : set Ξ±) : diam (closure s) = diam s := begin refine le_antisymm (diam_le $ Ξ» x hx y hy, _) (diam_mono subset_closure), have : edist x y ∈ closure (Iic (diam s)), from map_mem_closure2 (@continuous_edist Ξ± _) hx hy (Ξ» _ _, edist_le_diam_of_mem), rwa closure_Iic at this end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : β„• β†’ ℝβ‰₯0∞`, then the distance from `f n` to the limit is bounded by `βˆ‘'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : β„• β†’ Ξ±} (d : β„• β†’ ℝβ‰₯0∞) (hf : βˆ€ n, edist (f n) (f n.succ) ≀ d n) {a : Ξ±} (ha : tendsto f at_top (𝓝 a)) (n : β„•) : edist (f n) a ≀ βˆ‘' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, Ξ» m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (Ξ» k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (Ξ» _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : β„• β†’ ℝβ‰₯0∞`, then the distance from `f 0` to the limit is bounded by `βˆ‘'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendstoβ‚€ {f : β„• β†’ Ξ±} (d : β„• β†’ ℝβ‰₯0∞) (hf : βˆ€ n, edist (f n) (f n.succ) ≀ d n) {a : Ξ±} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≀ βˆ‘' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
b9e8c64b910787c3819941284f8ee944af27bf19
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/real/cau_seq.lean
7b571cae9dec883b87fec40f1e21ac24b26600e1
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
24,826
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.big_operators algebra.ordered_field /-! # Cauchy sequences A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology. This is a concrete implementation that is useful for simplicity and computability reasons. ## Important definitions * `is_absolute_value`: a type class stating that `f : Ξ² β†’ Ξ±` satisfies the axioms of an abs val * `is_cau_seq`: a predicate that says `f : β„• β†’ Ξ²` is Cauchy. ## Tags sequence, cauchy, abs val, absolute value -/ /-- A function f is an absolute value if it is nonnegative, zero only at 0, additive, and multiplicative. -/ class is_absolute_value {Ξ±} [discrete_linear_ordered_field Ξ±] {Ξ²} [ring Ξ²] (f : Ξ² β†’ Ξ±) : Prop := (abv_nonneg : βˆ€ x, 0 ≀ f x) (abv_eq_zero : βˆ€ {x}, f x = 0 ↔ x = 0) (abv_add : βˆ€ x y, f (x + y) ≀ f x + f y) (abv_mul : βˆ€ x y, f (x * y) = f x * f y) namespace is_absolute_value variables {Ξ± : Type*} [discrete_linear_ordered_field Ξ±] {Ξ² : Type*} [ring Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl theorem abv_one' (h : (1:Ξ²) β‰  0) : abv 1 = 1 := (domain.mul_left_inj $ mt (abv_eq_zero abv).1 h).1 $ by rw [← abv_mul abv, mul_one, mul_one] theorem abv_one {Ξ² : Type*} [domain Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] : abv 1 = 1 := abv_one' abv one_ne_zero theorem abv_pos {a : Ξ²} : 0 < abv a ↔ a β‰  0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv] theorem abv_neg (a : Ξ²) : abv (-a) = abv a := by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _), ← abv_mul abv, ← abv_mul abv]; simp theorem abv_sub (a b : Ξ²) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv_neg abv] theorem abv_inv {Ξ² : Type*} [field Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] (a : Ξ²) : abv a⁻¹ = (abv a)⁻¹ := classical.by_cases (Ξ» h : a = 0, by simp [h, abv_zero abv]) (Ξ» h, (domain.mul_left_inj (mt (abv_eq_zero abv).1 h)).1 $ by rw [← abv_mul abv]; simp [h, mt (abv_eq_zero abv).1 h, abv_one abv]) theorem abv_div {Ξ² : Type*} [field Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] (a b : Ξ²) : abv (a / b) = abv a / abv b := by rw [division_def, abv_mul abv, abv_inv abv]; refl lemma abv_sub_le (a b c : Ξ²) : abv (a - c) ≀ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg] using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : Ξ²) : abv a - abv b ≀ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b lemma abs_abv_sub_le_abv_sub (a b : Ξ²) : abs (abv a - abv b) ≀ abv (a - b) := abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _, by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩ lemma abv_pow {Ξ² : Type*} [domain Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] (a : Ξ²) (n : β„•) : abv (a ^ n) = abv a ^ n := by induction n; simp [abv_mul abv, _root_.pow_succ, abv_one abv, *] end is_absolute_value instance abs_is_absolute_value {Ξ±} [discrete_linear_ordered_field Ξ±] : is_absolute_value (abs : Ξ± β†’ Ξ±) := { abv_nonneg := abs_nonneg, abv_eq_zero := Ξ» _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value theorem exists_forall_ge_and {Ξ±} [linear_order Ξ±] {P Q : Ξ± β†’ Prop} : (βˆƒ i, βˆ€ j β‰₯ i, P j) β†’ (βˆƒ i, βˆ€ j β‰₯ i, Q j) β†’ βˆƒ i, βˆ€ j β‰₯ i, P j ∧ Q j | ⟨a, hβ‚βŸ© ⟨b, hβ‚‚βŸ© := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, Ξ» j hj, ⟨h₁ _ (le_trans ac hj), hβ‚‚ _ (le_trans bc hj)⟩⟩ section variables {Ξ± : Type*} [discrete_linear_ordered_field Ξ±] {Ξ² : Type*} [ring Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] theorem rat_add_continuous_lemma {Ξ΅ : Ξ±} (Ξ΅0 : 0 < Ξ΅) : βˆƒ Ξ΄ > 0, βˆ€ {a₁ aβ‚‚ b₁ bβ‚‚ : Ξ²}, abv (a₁ - b₁) < Ξ΄ β†’ abv (aβ‚‚ - bβ‚‚) < Ξ΄ β†’ abv (a₁ + aβ‚‚ - (b₁ + bβ‚‚)) < Ξ΅ := ⟨Ρ / 2, half_pos Ξ΅0, Ξ» a₁ aβ‚‚ b₁ bβ‚‚ h₁ hβ‚‚, by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ hβ‚‚)⟩ theorem rat_mul_continuous_lemma {Ξ΅ K₁ Kβ‚‚ : Ξ±} (Ξ΅0 : 0 < Ξ΅) : βˆƒ Ξ΄ > 0, βˆ€ {a₁ aβ‚‚ b₁ bβ‚‚ : Ξ²}, abv a₁ < K₁ β†’ abv bβ‚‚ < Kβ‚‚ β†’ abv (a₁ - b₁) < Ξ΄ β†’ abv (aβ‚‚ - bβ‚‚) < Ξ΄ β†’ abv (a₁ * aβ‚‚ - b₁ * bβ‚‚) < Ξ΅ := begin have K0 : (0 : Ξ±) < max 1 (max K₁ Kβ‚‚) := lt_of_lt_of_le zero_lt_one (le_max_left _ _), have Ξ΅K := div_pos (half_pos Ξ΅0) K0, refine ⟨_, Ξ΅K, Ξ» a₁ aβ‚‚ b₁ bβ‚‚ ha₁ hbβ‚‚ h₁ hβ‚‚, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ Kβ‚‚) (le_max_right 1 _)), replace hbβ‚‚ := lt_of_lt_of_le hbβ‚‚ (le_trans (le_max_right K₁ _) (le_max_right 1 _)), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hbβ‚‚ (abv_nonneg abv _) Ξ΅K) (mul_lt_mul' (le_of_lt hβ‚‚) ha₁ (abv_nonneg abv _) Ξ΅K), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) this end theorem rat_inv_continuous_lemma {Ξ² : Type*} [field Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] {Ξ΅ K : Ξ±} (Ξ΅0 : 0 < Ξ΅) (K0 : 0 < K) : βˆƒ Ξ΄ > 0, βˆ€ {a b : Ξ²}, K ≀ abv a β†’ K ≀ abv b β†’ abv (a - b) < Ξ΄ β†’ abv (a⁻¹ - b⁻¹) < Ξ΅ := begin have KK := mul_pos K0 K0, have Ξ΅K := mul_pos Ξ΅0 KK, refine ⟨_, Ξ΅K, Ξ» a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel Ξ΅ (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos Ξ΅0 KK) KK end end /-- A sequence is Cauchy if the distance between its entries tends to zero. -/ def is_cau_seq {Ξ± : Type*} [discrete_linear_ordered_field Ξ±] {Ξ² : Type*} [ring Ξ²] (abv : Ξ² β†’ Ξ±) (f : β„• β†’ Ξ²) := βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, abv (f j - f i) < Ξ΅ namespace is_cau_seq variables {Ξ± : Type*} [discrete_linear_ordered_field Ξ±] {Ξ² : Type*} [ring Ξ²] {abv : Ξ² β†’ Ξ±} [is_absolute_value abv] {f : β„• β†’ Ξ²} theorem cauchyβ‚‚ (hf : is_cau_seq abv f) {Ξ΅:Ξ±} (Ξ΅0 : Ξ΅ > 0) : βˆƒ i, βˆ€ j k β‰₯ i, abv (f j - f k) < Ξ΅ := begin refine (hf _ (half_pos Ξ΅0)).imp (Ξ» i hi j k ij ik, _), rw ← add_halves Ξ΅, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end theorem cauchy₃ (hf : is_cau_seq abv f) {Ξ΅:Ξ±} (Ξ΅0 : Ξ΅ > 0) : βˆƒ i, βˆ€ j β‰₯ i, βˆ€ k β‰₯ j, abv (f k - f j) < Ξ΅ := let ⟨i, H⟩ := hf.cauchyβ‚‚ Ξ΅0 in ⟨i, Ξ» j ij k jk, H _ _ (le_trans ij jk) ij⟩ end is_cau_seq def cau_seq {Ξ± : Type*} [discrete_linear_ordered_field Ξ±] (Ξ² : Type*) [ring Ξ²] (abv : Ξ² β†’ Ξ±) := {f : β„• β†’ Ξ² // is_cau_seq abv f} namespace cau_seq variables {Ξ± : Type*} [discrete_linear_ordered_field Ξ±] section ring variables {Ξ² : Type*} [ring Ξ²] {abv : Ξ² β†’ Ξ±} instance : has_coe_to_fun (cau_seq Ξ² abv) := ⟨_, subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq Ξ² abv) _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq Ξ² abv} (h : βˆ€ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq Ξ² abv) : is_cau_seq abv f := f.2 theorem cauchy (f : cau_seq Ξ² abv) : βˆ€ {Ξ΅}, Ξ΅ > 0 β†’ βˆƒ i, βˆ€ j β‰₯ i, abv (f j - f i) < Ξ΅ := f.2 def of_eq (f : cau_seq Ξ² abv) (g : β„• β†’ Ξ²) (e : βˆ€ i, f i = g i) : cau_seq Ξ² abv := ⟨g, Ξ» Ξ΅, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ variable [is_absolute_value abv] theorem cauchyβ‚‚ (f : cau_seq Ξ² abv) {Ξ΅:Ξ±} : Ξ΅ > 0 β†’ βˆƒ i, βˆ€ j k β‰₯ i, abv (f j - f k) < Ξ΅ := f.2.cauchyβ‚‚ theorem cauchy₃ (f : cau_seq Ξ² abv) {Ξ΅:Ξ±} : Ξ΅ > 0 β†’ βˆƒ i, βˆ€ j β‰₯ i, βˆ€ k β‰₯ j, abv (f k - f j) < Ξ΅ := f.2.cauchy₃ theorem bounded (f : cau_seq Ξ² abv) : βˆƒ r, βˆ€ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := (finset.range (i+1)).sum (Ξ» j, abv (f j)), have : βˆ€ j ≀ i, abv (f j) ≀ R, { intros j ij, change (Ξ» j, abv (f j)) j ≀ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, Ξ» j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end theorem bounded' (f : cau_seq Ξ² abv) (x : Ξ±) : βˆƒ r > x, βˆ€ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), Ξ» i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ instance : has_add (cau_seq Ξ² abv) := ⟨λ f g, ⟨λ i, (f i + g i : Ξ²), Ξ» Ξ΅ Ξ΅0, let ⟨δ, Ξ΄0, Hδ⟩ := rat_add_continuous_lemma abv Ξ΅0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ Ξ΄0) (g.cauchy₃ Ξ΄0) in ⟨i, Ξ» j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ (le_refl _) in HΞ΄ (H₁ _ ij) (Hβ‚‚ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq Ξ² abv) (i : β„•) : (f + g) i = f i + g i := rfl variable (abv) /-- The constant Cauchy sequence. -/ def const (x : Ξ²) : cau_seq Ξ² abv := ⟨λ i, x, Ξ» Ξ΅ Ξ΅0, ⟨0, Ξ» j ij, by simpa [abv_zero abv] using Ξ΅0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : Ξ²) (i : β„•) : (const x : β„• β†’ Ξ²) i = x := rfl theorem const_inj {x y : Ξ²} : (const x : cau_seq Ξ² abv) = const y ↔ x = y := ⟨λ h, congr_arg (Ξ» f:cau_seq Ξ² abv, (f:β„•β†’Ξ²) 0) h, congr_arg _⟩ instance : has_zero (cau_seq Ξ² abv) := ⟨const 0⟩ instance : has_one (cau_seq Ξ² abv) := ⟨const 1⟩ instance : inhabited (cau_seq Ξ² abv) := ⟨0⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq Ξ² abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq Ξ² abv) i = 1 := rfl theorem const_add (x y : Ξ²) : const (x + y) = const x + const y := ext $ Ξ» i, rfl instance : has_mul (cau_seq Ξ² abv) := ⟨λ f g, ⟨λ i, (f i * g i : Ξ²), Ξ» Ξ΅ Ξ΅0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, Ξ΄0, Hδ⟩ := rat_mul_continuous_lemma abv Ξ΅0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ Ξ΄0) (g.cauchy₃ Ξ΄0) in ⟨i, Ξ» j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ (le_refl _) in HΞ΄ (hF j) (hG i) (H₁ _ ij) (Hβ‚‚ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq Ξ² abv) (i : β„•) : (f * g) i = f i * g i := rfl theorem const_mul (x y : Ξ²) : const (x * y) = const x * const y := ext $ Ξ» i, rfl instance : has_neg (cau_seq Ξ² abv) := ⟨λ f, of_eq (const (-1) * f) (Ξ» x, -f x) (Ξ» i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq Ξ² abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : Ξ²) : const (-x) = -const x := ext $ Ξ» i, rfl instance : ring (cau_seq Ξ² abv) := by refine {neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, ..}; { intros, apply ext, simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm] } instance {Ξ² : Type*} [comm_ring Ξ²] {abv : Ξ² β†’ Ξ±} [is_absolute_value abv] : comm_ring (cau_seq Ξ² abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } theorem const_sub (x y : Ξ²) : const (x - y) = const x - const y := by rw [sub_eq_add_neg, const_add, const_neg, sub_eq_add_neg] @[simp] theorem sub_apply (f g : cau_seq Ξ² abv) (i : β„•) : (f - g) i = f i - g i := rfl /-- `lim_zero f` holds when `f` approaches 0. -/ def lim_zero (f : cau_seq Ξ² abv) := βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, abv (f j) < Ξ΅ theorem add_lim_zero {f g : cau_seq Ξ² abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | Ξ΅ Ξ΅0 := (exists_forall_ge_and (hf _ $ half_pos Ξ΅0) (hg _ $ half_pos Ξ΅0)).imp $ Ξ» i H j ij, let ⟨H₁, Hβ‚‚βŸ© := H _ ij in by simpa [add_halves Ξ΅] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ Hβ‚‚) theorem mul_lim_zero_right (f : cau_seq Ξ² abv) {g} (hg : lim_zero g) : lim_zero (f * g) | Ξ΅ Ξ΅0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos Ξ΅0 F0).imp $ Ξ» i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem mul_lim_zero_left {f} (g : cau_seq Ξ² abv) (hg : lim_zero f) : lim_zero (f * g) | Ξ΅ Ξ΅0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in (hg _ $ div_pos Ξ΅0 G0).imp $ Ξ» i H j ij, by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _); rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq Ξ² abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero_right _ hf theorem sub_lim_zero {f g : cau_seq Ξ² abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := add_lim_zero hf (neg_lim_zero hg) theorem lim_zero_sub_rev {f g : cau_seq Ξ² abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) := by simpa using neg_lim_zero hfg theorem zero_lim_zero : lim_zero (0 : cau_seq Ξ² abv) | Ξ΅ Ξ΅0 := ⟨0, Ξ» j ij, by simpa [abv_zero abv] using Ξ΅0⟩ theorem const_lim_zero {x : Ξ²} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ Ξ» Ξ΅ Ξ΅0, let ⟨i, hi⟩ := H _ Ξ΅0 in le_of_lt $ hi _ (le_refl _), Ξ» e, e.symm β–Έ zero_lim_zero⟩ instance equiv : setoid (cau_seq Ξ² abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], Ξ» f g h, by simpa using neg_lim_zero h, Ξ» f g h fg gh, by simpa [sub_eq_add_neg] using add_lim_zero fg gh⟩⟩ theorem equiv_def₃ {f g : cau_seq Ξ² abv} (h : f β‰ˆ g) {Ξ΅:Ξ±} (Ξ΅0 : 0 < Ξ΅) : βˆƒ i, βˆ€ j β‰₯ i, βˆ€ k β‰₯ j, abv (f k - g j) < Ξ΅ := (exists_forall_ge_and (h _ $ half_pos Ξ΅0) (f.cauchy₃ $ half_pos Ξ΅0)).imp $ Ξ» i H j ij k jk, let ⟨h₁, hβ‚‚βŸ© := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (hβ‚‚ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq Ξ² abv} (h : f β‰ˆ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, Ξ» l, by simpa using add_lim_zero h l⟩ theorem abv_pos_of_not_lim_zero {f : cau_seq Ξ² abv} (hf : Β¬ lim_zero f) : βˆƒ K > 0, βˆƒ i, βˆ€ j β‰₯ i, K ≀ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (Ξ» Ξ΅ Ξ΅0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos Ξ΅0) with i hi, rcases nk _ (half_pos Ξ΅0) i with ⟨j, ij, hj⟩, refine ⟨j, Ξ» k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : β„• β†’ Ξ²) (g : cau_seq Ξ² abv) (h : βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, abv (f j - g j) < Ξ΅) : is_cau_seq abv f | Ξ΅ Ξ΅0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos Ξ΅0)) (g.cauchy₃ $ half_pos Ξ΅0) in ⟨i, Ξ» j ij, begin cases hi _ (le_refl _) with h₁ hβ‚‚, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (hβ‚‚ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : Β¬ f β‰ˆ 0) : Β¬ lim_zero f := assume : lim_zero f, have lim_zero (f - 0), by simpa, hf this lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f β‰ˆ 0) : g * f β‰ˆ 0 := have lim_zero (f - 0), from hf, have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa, show lim_zero (g*f - 0), by simpa lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : Β¬ f β‰ˆ 0) (hg : Β¬ g β‰ˆ 0) : Β¬ (f * g) β‰ˆ 0 := assume : lim_zero (f*g - 0), have hlz : lim_zero (f*g), by simpa, have hf' : Β¬ lim_zero f, by simpa using (show Β¬ lim_zero (f - 0), from hf), have hg' : Β¬ lim_zero g, by simpa using (show Β¬ lim_zero (g - 0), from hg), begin rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩, rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩, have : a1 * a2 > 0, from mul_pos ha1 ha2, cases hlz _ this with N hN, let i := max N (max N1 N2), have hN' := hN i (le_max_left _ _), have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)), have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)), apply not_le_of_lt hN', change _ ≀ abv (_ * _), rw is_absolute_value.abv_mul abv, apply mul_le_mul; try { assumption }, { apply le_of_lt ha2 }, { apply is_absolute_value.abv_nonneg abv } end theorem const_equiv {x y : Ξ²} : const x β‰ˆ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] end ring section comm_ring variables {Ξ² : Type*} [comm_ring Ξ²] {abv : Ξ² β†’ Ξ±} [is_absolute_value abv] lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f β‰ˆ 0) : f * g β‰ˆ 0 := by rw mul_comm; apply mul_equiv_zero _ hf end comm_ring section integral_domain variables {Ξ² : Type*} [integral_domain Ξ²] (abv : Ξ² β†’ Ξ±) [is_absolute_value abv] lemma one_not_equiv_zero : Β¬ (const abv 1) β‰ˆ (const abv 0) := assume h, have βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ k, k β‰₯ i β†’ abv (1 - 0) < Ξ΅, from h, have h1 : abv 1 ≀ 0, from le_of_not_gt $ assume h2 : abv 1 > 0, exists.elim (this _ h2) $ Ξ» i hi, lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _), have h2 : abv 1 β‰₯ 0, from is_absolute_value.abv_nonneg _ _, have abv 1 = 0, from le_antisymm h1 h2, have (1 : Ξ²) = 0, from (is_absolute_value.abv_eq_zero abv).1 this, absurd this one_ne_zero end integral_domain section field variables {Ξ² : Type*} [field Ξ²] {abv : Ξ² β†’ Ξ±} [is_absolute_value abv] theorem inv_aux {f : cau_seq Ξ² abv} (hf : Β¬ lim_zero f) : βˆ€ Ξ΅ > 0, βˆƒ i, βˆ€ j β‰₯ i, abv ((f j)⁻¹ - (f i)⁻¹) < Ξ΅ | Ξ΅ Ξ΅0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, Ξ΄0, Hδ⟩ := rat_inv_continuous_lemma abv Ξ΅0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ Ξ΄0) in ⟨i, Ξ» j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in HΞ΄ (H _ ij).1 iK (H' _ ij)⟩ def inv (f) (hf : Β¬ lim_zero f) : cau_seq Ξ² abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq Ξ² abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq Ξ² abv} (hf) : inv f hf * f β‰ˆ 1 := Ξ» Ξ΅ Ξ΅0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, Ξ» j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using Ξ΅0⟩ theorem const_inv {x : Ξ²} (hx : x β‰  0) : const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := ext (assume n, by simp[inv_apply, const_apply]) end field section abs local notation `const` := const abs /-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/ def pos (f : cau_seq Ξ± abs) : Prop := βˆƒ K > 0, βˆƒ i, βˆ€ j β‰₯ i, K ≀ f j theorem not_lim_zero_of_pos {f : cau_seq Ξ± abs} : pos f β†’ Β¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, hβ‚‚βŸ© := h _ (le_refl _) in not_lt_of_le h₁ (abs_lt.1 hβ‚‚).2 theorem const_pos {x : Ξ±} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)), Ξ» h, ⟨x, h, 0, Ξ» j _, le_refl _⟩⟩ theorem add_pos {f g : cau_seq Ξ± abs} : pos f β†’ pos g β†’ pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, Ξ» j ij, let ⟨h₁, hβ‚‚βŸ© := h _ ij in add_le_add h₁ hβ‚‚βŸ© theorem pos_add_lim_zero {f g : cau_seq Ξ± abs} : pos f β†’ lim_zero g β†’ pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, Ξ» j ij, begin cases h j ij with h₁ hβ‚‚, have := add_le_add h₁ (le_of_lt (abs_lt.1 hβ‚‚).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ theorem mul_pos {f g : cau_seq Ξ± abs} : pos f β†’ pos g β†’ pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, Ξ» j ij, let ⟨h₁, hβ‚‚βŸ© := h _ ij in mul_le_mul h₁ hβ‚‚ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq Ξ± abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (Ξ» h, ⟨K, K0, i, Ξ» j ij, _⟩); have := (hi _ ij).1; cases hi _ (le_refl _) with h₁ hβ‚‚, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ hβ‚‚ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ hβ‚‚ _ ij).2) h₁ } end instance : has_lt (cau_seq Ξ± abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq Ξ± abs) := ⟨λ f g, f < g ∨ f β‰ˆ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq Ξ± abs} (fg : f < g) (gh : g β‰ˆ h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq Ξ± abs} (fg : f β‰ˆ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq Ξ± abs} (fg : f < g) (gh : g < h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh theorem lt_irrefl {f : cau_seq Ξ± abs} : Β¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) lemma le_of_eq_of_le {f g h : cau_seq Ξ± abs} (hfg : f β‰ˆ g) (hgh : g ≀ h) : f ≀ h := hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg) (or.inr ∘ setoid.trans hfg) lemma le_of_le_of_eq {f g h : cau_seq Ξ± abs} (hfg : f ≀ g) (hgh : g β‰ˆ h) : f ≀ h := hfg.elim (Ξ» h, or.inl (cau_seq.lt_of_lt_of_eq h hgh)) (Ξ» h, or.inr (setoid.trans h hgh)) instance : preorder (cau_seq Ξ± abs) := { lt := (<), le := Ξ» f g, f < g ∨ f β‰ˆ g, le_refl := Ξ» f, or.inr (setoid.refl _), le_trans := Ξ» f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := Ξ» f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, Ξ» ⟨h₁, hβ‚‚βŸ©, h₁.resolve_right (mt (Ξ» h, or.inr (setoid.symm h)) hβ‚‚)⟩ } theorem le_antisymm {f g : cau_seq Ξ± abs} (fg : f ≀ g) (gf : g ≀ f) : f β‰ˆ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq Ξ± abs) : f < g ∨ f β‰ˆ g ∨ g < f := (trichotomy (g - f)).imp_right (Ξ» h, h.imp (Ξ» h, setoid.symm h) (Ξ» h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq Ξ± abs) : f ≀ g ∨ g ≀ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : Ξ±} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_le {x y : Ξ±} : const x ≀ const y ↔ x ≀ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv lemma le_of_exists {f g : cau_seq Ξ± abs} (h : βˆƒ i, βˆ€ j β‰₯ i, f j ≀ g j) : f ≀ g := let ⟨i, hi⟩ := h in (or.assoc.2 (cau_seq.lt_total f g)).elim id (Ξ» hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in not_lt_of_ge (hi (max i j) (le_max_left _ _)) (sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _)))))) theorem exists_gt (f : cau_seq Ξ± abs) : βˆƒ a : Ξ±, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, Ξ» i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq Ξ± abs) : βˆƒ a : Ξ±, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ end abs end cau_seq
c57d7b2dacda6a4b8c57c2bd8d46addf4e390221
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/polynomial.lean
41202aaff5cda7cb7f8ff8e11fbf995d81cb7c23
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,608
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 data.polynomial.algebra_map import data.polynomial.inductions import data.polynomial.splits import ring_theory.polynomial.vieta import analysis.normed.field.basic /-! # Polynomials and limits > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove the following lemmas. * `polynomial.continuous_evalβ‚‚: `polynomial.evalβ‚‚` defines a continuous function. * `polynomial.continuous_aeval: `polynomial.aeval` defines a continuous function; we also prove convenience lemmas `polynomial.continuous_at_aeval`, `polynomial.continuous_within_at_aeval`, `polynomial.continuous_on_aeval`. * `polynomial.continuous`: `polynomial.eval` defines a continuous functions; we also prove convenience lemmas `polynomial.continuous_at`, `polynomial.continuous_within_at`, `polynomial.continuous_on`. * `polynomial.tendsto_norm_at_top`: `Ξ» x, β€–polynomial.eval (z x) pβ€–` tends to infinity provided that `Ξ» x, β€–z xβ€–` tends to infinity and `0 < degree p`; * `polynomial.tendsto_abv_evalβ‚‚_at_top`, `polynomial.tendsto_abv_at_top`, `polynomial.tendsto_abv_aeval_at_top`: a few versions of the previous statement for `is_absolute_value abv` instead of norm. ## Tags polynomial, continuity -/ open is_absolute_value filter namespace polynomial open_locale polynomial section topological_semiring variables {R S : Type*} [semiring R] [topological_space R] [topological_semiring R] (p : R[X]) @[continuity] protected lemma continuous_evalβ‚‚ [semiring S] (p : S[X]) (f : S β†’+* R) : continuous (Ξ» x, p.evalβ‚‚ f x) := begin simp only [evalβ‚‚_eq_sum, finsupp.sum], exact continuous_finset_sum _ (Ξ» c hc, continuous_const.mul (continuous_pow _)) end @[continuity] protected lemma continuous : continuous (Ξ» x, p.eval x) := p.continuous_evalβ‚‚ _ protected lemma continuous_at {a : R} : continuous_at (Ξ» x, p.eval x) a := p.continuous.continuous_at protected lemma continuous_within_at {s a} : continuous_within_at (Ξ» x, p.eval x) s a := p.continuous.continuous_within_at protected lemma continuous_on {s} : continuous_on (Ξ» x, p.eval x) s := p.continuous.continuous_on end topological_semiring section topological_algebra variables {R A : Type*} [comm_semiring R] [semiring A] [algebra R A] [topological_space A] [topological_semiring A] (p : R[X]) @[continuity] protected lemma continuous_aeval : continuous (Ξ» x : A, aeval x p) := p.continuous_evalβ‚‚ _ protected lemma continuous_at_aeval {a : A} : continuous_at (Ξ» x : A, aeval x p) a := p.continuous_aeval.continuous_at protected lemma continuous_within_at_aeval {s a} : continuous_within_at (Ξ» x : A, aeval x p) s a := p.continuous_aeval.continuous_within_at protected lemma continuous_on_aeval {s} : continuous_on (Ξ» x : A, aeval x p) s := p.continuous_aeval.continuous_on end topological_algebra lemma tendsto_abv_evalβ‚‚_at_top {R S k Ξ± : Type*} [semiring R] [ring S] [linear_ordered_field k] (f : R β†’+* S) (abv : S β†’ k) [is_absolute_value abv] (p : R[X]) (hd : 0 < degree p) (hf : f p.leading_coeff β‰  0) {l : filter Ξ±} {z : Ξ± β†’ S} (hz : tendsto (abv ∘ z) l at_top) : tendsto (Ξ» x, abv (p.evalβ‚‚ f (z x))) l at_top := begin revert hf, refine degree_pos_induction_on p hd _ _ _; clear hd p, { rintros c - hc, rw [leading_coeff_mul_X, leading_coeff_C] at hc, simpa [abv_mul abv] using hz.const_mul_at_top ((abv_pos abv).2 hc) }, { intros p hpd ihp hf, rw [leading_coeff_mul_X] at hf, simpa [abv_mul abv] using (ihp hf).at_top_mul_at_top hz }, { intros p a hd ihp hf, rw [add_comm, leading_coeff_add_of_degree_lt (degree_C_le.trans_lt hd)] at hf, refine tendsto_at_top_of_add_const_right (abv (-f a)) _, refine tendsto_at_top_mono (Ξ» _, abv_add abv _ _) _, simpa using ihp hf } end lemma tendsto_abv_at_top {R k Ξ± : Type*} [ring R] [linear_ordered_field k] (abv : R β†’ k) [is_absolute_value abv] (p : R[X]) (h : 0 < degree p) {l : filter Ξ±} {z : Ξ± β†’ R} (hz : tendsto (abv ∘ z) l at_top) : tendsto (Ξ» x, abv (p.eval (z x))) l at_top := tendsto_abv_evalβ‚‚_at_top _ _ _ h (mt leading_coeff_eq_zero.1 $ ne_zero_of_degree_gt h) hz lemma tendsto_abv_aeval_at_top {R A k Ξ± : Type*} [comm_semiring R] [ring A] [algebra R A] [linear_ordered_field k] (abv : A β†’ k) [is_absolute_value abv] (p : R[X]) (hd : 0 < degree p) (hβ‚€ : algebra_map R A p.leading_coeff β‰  0) {l : filter Ξ±} {z : Ξ± β†’ A} (hz : tendsto (abv ∘ z) l at_top) : tendsto (Ξ» x, abv (aeval (z x) p)) l at_top := tendsto_abv_evalβ‚‚_at_top _ abv p hd hβ‚€ hz variables {Ξ± R : Type*} [normed_ring R] [is_absolute_value (norm : R β†’ ℝ)] lemma tendsto_norm_at_top (p : R[X]) (h : 0 < degree p) {l : filter Ξ±} {z : Ξ± β†’ R} (hz : tendsto (Ξ» x, β€–z xβ€–) l at_top) : tendsto (Ξ» x, β€–p.eval (z x)β€–) l at_top := p.tendsto_abv_at_top norm h hz lemma exists_forall_norm_le [proper_space R] (p : R[X]) : βˆƒ x, βˆ€ y, β€–p.eval xβ€– ≀ β€–p.eval yβ€– := if hp0 : 0 < degree p then p.continuous.norm.exists_forall_le $ p.tendsto_norm_at_top hp0 tendsto_norm_cocompact_at_top else ⟨p.coeff 0, by rw [eq_C_of_degree_le_zero (le_of_not_gt hp0)]; simp⟩ section roots open_locale polynomial nnreal variables {F K : Type*} [comm_ring F] [normed_field K] open multiset lemma eq_one_of_roots_le {p : F[X]} {f : F β†’+* K} {B : ℝ} (hB : B < 0) (h1 : p.monic) (h2 : splits f p) (h3 : βˆ€ z ∈ (map f p).roots, β€–zβ€– ≀ B) : p = 1 := h1.nat_degree_eq_zero_iff_eq_one.mp begin contrapose !hB, rw [← h1.nat_degree_map f, nat_degree_eq_card_roots' h2] at hB, obtain ⟨z, hz⟩ := card_pos_iff_exists_mem.mp (zero_lt_iff.mpr hB), exact le_trans (norm_nonneg _) (h3 z hz), end lemma coeff_le_of_roots_le {p : F[X]} {f : F β†’+* K} {B : ℝ} (i : β„•) (h1 : p.monic) (h2 : splits f p) (h3 : βˆ€ z ∈ (map f p).roots, β€–zβ€– ≀ B) : β€– (map f p).coeff i β€– ≀ B^(p.nat_degree - i) * p.nat_degree.choose i := begin obtain hB | hB := lt_or_le B 0, { rw [eq_one_of_roots_le hB h1 h2 h3, polynomial.map_one, nat_degree_one, zero_tsub, pow_zero, one_mul, coeff_one], split_ifs; norm_num [h] }, rw ← h1.nat_degree_map f, obtain hi | hi := lt_or_le (map f p).nat_degree i, { rw [coeff_eq_zero_of_nat_degree_lt hi, norm_zero], positivity }, rw [coeff_eq_esymm_roots_of_splits ((splits_id_iff_splits f).2 h2) hi, (h1.map _).leading_coeff, one_mul, norm_mul, norm_pow, norm_neg, norm_one, one_pow, one_mul], apply ((norm_multiset_sum_le _).trans $ sum_le_card_nsmul _ _ $ Ξ» r hr, _).trans, { rw [multiset.map_map, card_map, card_powerset_len, ←nat_degree_eq_card_roots' h2, nat.choose_symm hi, mul_comm, nsmul_eq_mul] }, simp_rw multiset.mem_map at hr, obtain ⟨_, ⟨s, hs, rfl⟩, rfl⟩ := hr, rw mem_powerset_len at hs, lift B to ℝβ‰₯0 using hB, rw [←coe_nnnorm, ←nnreal.coe_pow, nnreal.coe_le_coe, ←nnnorm_hom_apply, ←monoid_hom.coe_coe, monoid_hom.map_multiset_prod], refine (prod_le_pow_card _ B $ Ξ» x hx, _).trans_eq (by rw [card_map, hs.2]), obtain ⟨z, hz, rfl⟩ := multiset.mem_map.1 hx, exact h3 z (mem_of_le hs.1 hz), end /-- The coefficients of the monic polynomials of bounded degree with bounded roots are uniformely bounded. -/ lemma coeff_bdd_of_roots_le {B : ℝ} {d : β„•} (f : F β†’+* K) {p : F[X]} (h1 : p.monic) (h2 : splits f p) (h3 : p.nat_degree ≀ d) (h4 : βˆ€ z ∈ (map f p).roots, β€–zβ€– ≀ B) (i : β„•) : β€–(map f p).coeff iβ€– ≀ (max B 1) ^ d * d.choose (d / 2) := begin obtain hB | hB := le_or_lt 0 B, { apply (coeff_le_of_roots_le i h1 h2 h4).trans, calc _ ≀ (max B 1) ^ (p.nat_degree - i) * (p.nat_degree.choose i) : mul_le_mul_of_nonneg_right (pow_le_pow_of_le_left hB (le_max_left _ _) _) _ ... ≀ (max B 1) ^ d * (p.nat_degree.choose i) : mul_le_mul_of_nonneg_right ((pow_mono (le_max_right _ _)) (le_trans (nat.sub_le _ _) h3)) _ ... ≀ (max B 1) ^ d * d.choose (d / 2) : mul_le_mul_of_nonneg_left (nat.cast_le.mpr ((i.choose_mono h3).trans (i.choose_le_middle d))) _, all_goals { positivity, }}, { rw [eq_one_of_roots_le hB h1 h2 h4, polynomial.map_one, coeff_one], refine trans _ (one_le_mul_of_one_le_of_one_le (one_le_pow_of_one_le (le_max_right B 1) d) _), { split_ifs; norm_num, }, { exact_mod_cast nat.succ_le_iff.mpr (nat.choose_pos (d.div_le_self 2)), }}, end end roots end polynomial
026102f82ded220e58754f196dcc758fb397b659
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/topology/basic.lean
f3b6500e439b2886e93bf866355039c6d8f3741f
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,508
lean
/- Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Mario Carneiro, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial import data.support noncomputable theory /-! # Basic theory of topological spaces. The main definition is the type class `topological space Ξ±` which endows a type `Ξ±` with a topology. Then `set Ξ±` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `Ξ±` gets a neighborhood filter `𝓝 x`. A filter `F` on `Ξ±`Β has `x` as a cluster point if `cluster_pt x F : 𝓝 x βŠ“ F β‰  βŠ₯`. A map `f : ΞΉ β†’ Ξ±` clusters at `x` along `F : filter ΞΉ` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `Ξ±`. For topological spaces `Ξ±` and `Ξ²`, a function `f : Ξ± β†’ Ξ²` and a point `a : Ξ±`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `π“Ÿ s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ open set filter classical open_locale classical filter universes u v w /-! ###Β Topological spaces -/ /-- A topology on `Ξ±`. -/ @[protect_proj] structure topological_space (Ξ± : Type u) := (is_open : set Ξ± β†’ Prop) (is_open_univ : is_open univ) (is_open_inter : βˆ€s t, is_open s β†’ is_open t β†’ is_open (s ∩ t)) (is_open_sUnion : βˆ€s, (βˆ€t∈s, is_open t) β†’ is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {Ξ± : Type u} (T : set (set Ξ±)) (empty_mem : βˆ… ∈ T) (sInter_mem : βˆ€ A βŠ† T, β‹‚β‚€ A ∈ T) (union_mem : βˆ€ A B ∈ T, A βˆͺ B ∈ T) : topological_space Ξ± := { is_open := Ξ» X, Xᢜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := Ξ» s t hs ht, by simpa [set.compl_inter] using union_mem sᢜ tᢜ hs ht, is_open_sUnion := Ξ» s hs, by rw set.compl_sUnion; exact sInter_mem (set.compl '' s) (Ξ» z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {Ξ± : Type u} {Ξ² : Type v} {ΞΉ : Sort w} {a : Ξ±} {s s₁ sβ‚‚ : set Ξ±} {p p₁ pβ‚‚ : Ξ± β†’ Prop} @[ext] lemma topological_space_eq : βˆ€ {f g : topological_space Ξ±}, f.is_open = g.is_open β†’ f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space Ξ±] include t /-- `is_open s` means that `s` is open in the ambient topological space on `Ξ±` -/ def is_open (s : set Ξ±) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set Ξ±) := topological_space.is_open_univ t lemma is_open_inter (h₁ : is_open s₁) (hβ‚‚ : is_open sβ‚‚) : is_open (s₁ ∩ sβ‚‚) := topological_space.is_open_inter t s₁ sβ‚‚ h₁ hβ‚‚ lemma is_open_sUnion {s : set (set Ξ±)} (h : βˆ€t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma topological_space_eq_iff {t t' : topological_space Ξ±} : t = t' ↔ βˆ€ s, @is_open Ξ± t s ↔ @is_open Ξ± t' s := ⟨λ h s, h β–Έ iff.rfl, Ξ» h, by { ext, exact h _ }⟩ lemma is_open_fold {s : set Ξ±} {t : topological_space Ξ±} : t.is_open s = @is_open Ξ± t s := rfl variables [topological_space Ξ±] lemma is_open_Union {f : ΞΉ β†’ set Ξ±} (h : βˆ€i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (h : βˆ€i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open_union (h₁ : is_open s₁) (hβ‚‚ : is_open sβ‚‚) : is_open (s₁ βˆͺ sβ‚‚) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨hβ‚‚, hβ‚βŸ©) @[simp] lemma is_open_empty : is_open (βˆ… : set Ξ±) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set Ξ±)} (hs : finite s) : (βˆ€t ∈ s, is_open t) β†’ is_open (β‹‚β‚€ s) := finite.induction_on hs (Ξ» _, by rw sInter_empty; exact is_open_univ) $ Ξ» a s has hs ih h, by rw sInter_insert; exact is_open_inter (h _ $ mem_insert _ _) (ih $ Ξ» t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (hs : finite s) : (βˆ€i∈s, is_open (f i)) β†’ is_open (β‹‚i∈s, f i) := finite.induction_on hs (Ξ» _, by rw bInter_empty; exact is_open_univ) (Ξ» a s has hs ih h, by rw bInter_insert; exact is_open_inter (h a (mem_insert _ _)) (ih (Ξ» i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype Ξ²] {s : Ξ² β†’ set Ξ±} (h : βˆ€ i, is_open (s i)) : is_open (β‹‚ i, s i) := suffices is_open (β‹‚ (i : Ξ²) (hi : i ∈ @univ Ξ²), s i), by simpa, is_open_bInter finite_univ (Ξ» i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p β†’ set Ξ±} (h : βˆ€ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : Ξ± | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : Β¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open_and : is_open {a | p₁ a} β†’ is_open {a | pβ‚‚ a} β†’ is_open {a | p₁ a ∧ pβ‚‚ a} := is_open_inter /-- A set is closed if its complement is open -/ class is_closed (s : set Ξ±) : Prop := (is_open_compl : is_open sᢜ) @[simp] lemma is_open_compl_iff {s : set Ξ±} : is_open sᢜ ↔ is_closed s := ⟨λ h, ⟨h⟩, Ξ» h, h.is_open_compl⟩ @[simp] lemma is_closed_empty : is_closed (βˆ… : set Ξ±) := by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ } @[simp] lemma is_closed_univ : is_closed (univ : set Ξ±) := by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty } lemma is_closed_union : is_closed s₁ β†’ is_closed sβ‚‚ β†’ is_closed (s₁ βˆͺ sβ‚‚) := Ξ» h₁ hβ‚‚, by { rw [← is_open_compl_iff] at *, rw compl_union, exact is_open_inter h₁ hβ‚‚ } lemma is_closed_sInter {s : set (set Ξ±)} : (βˆ€t ∈ s, is_closed t) β†’ is_closed (β‹‚β‚€ s) := by simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion lemma is_closed_Inter {f : ΞΉ β†’ set Ξ±} (h : βˆ€i, is_closed (f i)) : is_closed (β‹‚i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq β–Έ h i lemma is_closed_bInter {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (h : βˆ€ i ∈ s, is_closed (f i)) : is_closed (β‹‚ i ∈ s, f i) := is_closed_Inter $ Ξ» i, is_closed_Inter $ h i @[simp] lemma is_closed_compl_iff {s : set Ξ±} : is_closed sᢜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open.is_closed_compl {s : set Ξ±} (hs : is_open s) : is_closed sᢜ := is_closed_compl_iff.2 hs lemma is_open_diff {s t : set Ξ±} (h₁ : is_open s) (hβ‚‚ : is_closed t) : is_open (s \ t) := is_open_inter h₁ $ is_open_compl_iff.mpr hβ‚‚ lemma is_closed_inter (h₁ : is_closed s₁) (hβ‚‚ : is_closed sβ‚‚) : is_closed (s₁ ∩ sβ‚‚) := by { rw [← is_open_compl_iff] at *, rw compl_inter, exact is_open_union h₁ hβ‚‚ } lemma is_closed_bUnion {s : set Ξ²} {f : Ξ² β†’ set Ξ±} (hs : finite s) : (βˆ€i∈s, is_closed (f i)) β†’ is_closed (⋃i∈s, f i) := finite.induction_on hs (Ξ» _, by rw bUnion_empty; exact is_closed_empty) (Ξ» a s has hs ih h, by rw bUnion_insert; exact is_closed_union (h a (mem_insert _ _)) (ih (Ξ» i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype Ξ²] {s : Ξ² β†’ set Ξ±} (h : βˆ€ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : Ξ²) (hi : i ∈ @univ Ξ²), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (Ξ» i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p β†’ set Ξ±} (h : βˆ€ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : Ξ± β†’ Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x β†’ q x} := have {x | p x β†’ q x} = {x | p x}ᢜ βˆͺ {x | q x}, from set.ext $ Ξ» x, imp_iff_not_or, by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq lemma is_open_neg : is_closed {a | p a} β†’ is_open {a | Β¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set Ξ±) : set Ξ± := ⋃₀ {t | is_open t ∧ t βŠ† s} lemma mem_interior {s : set Ξ±} {x : Ξ±} : x ∈ interior s ↔ βˆƒ t βŠ† s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set Ξ±} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, hβ‚‚βŸ©, h₁ lemma interior_subset {s : set Ξ±} : interior s βŠ† s := sUnion_subset $ assume t ⟨h₁, hβ‚‚βŸ©, hβ‚‚ lemma interior_maximal {s t : set Ξ±} (h₁ : t βŠ† s) (hβ‚‚ : is_open t) : t βŠ† interior s := subset_sUnion_of_mem ⟨hβ‚‚, hβ‚βŸ© lemma is_open.interior_eq {s : set Ξ±} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set Ξ±} : interior s = s ↔ is_open s := ⟨assume h, h β–Έ is_open_interior, is_open.interior_eq⟩ lemma subset_interior_iff_open {s : set Ξ±} : s βŠ† interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set Ξ±} (h₁ : is_open s) : s βŠ† interior t ↔ s βŠ† t := ⟨assume h, subset.trans h interior_subset, assume hβ‚‚, interior_maximal hβ‚‚ hβ‚βŸ© lemma interior_mono {s t : set Ξ±} (h : s βŠ† t) : interior s βŠ† interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (βˆ… : set Ξ±) = βˆ… := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set Ξ±) = univ := is_open_univ.interior_eq @[simp] lemma interior_interior {s : set Ξ±} : interior (interior s) = interior s := is_open_interior.interior_eq @[simp] lemma interior_inter {s t : set Ξ±} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior) lemma interior_union_is_closed_of_interior_empty {s t : set Ξ±} (h₁ : is_closed s) (hβ‚‚ : interior t = βˆ…) : interior (s βˆͺ t) = interior s := have interior (s βˆͺ t) βŠ† s, from assume x ⟨u, ⟨(hu₁ : is_open u), (huβ‚‚ : u βŠ† s βˆͺ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hxβ‚‚ : x βˆ‰ s, have u \ s βŠ† t, from assume x ⟨h₁, hβ‚‚βŸ©, or.resolve_left (huβ‚‚ h₁) hβ‚‚, have u \ s βŠ† interior t, by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁), have u \ s βŠ† βˆ…, by rwa hβ‚‚ at this, this ⟨hx₁, hxβ‚‚βŸ©, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ βˆ€ x ∈ s, βˆƒ t βŠ† s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] /-! ###Β Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set Ξ±) : set Ξ± := β‹‚β‚€ {t | is_closed t ∧ s βŠ† t} @[simp] lemma is_closed_closure {s : set Ξ±} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, hβ‚‚βŸ©, h₁ lemma subset_closure {s : set Ξ±} : s βŠ† closure s := subset_sInter $ assume t ⟨h₁, hβ‚‚βŸ©, hβ‚‚ lemma closure_minimal {s t : set Ξ±} (h₁ : s βŠ† t) (hβ‚‚ : is_closed t) : closure s βŠ† t := sInter_subset_of_mem ⟨hβ‚‚, hβ‚βŸ© lemma is_closed.closure_eq {s : set Ξ±} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set Ξ±} (hs : is_closed s) : closure s βŠ† s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set Ξ±} (h₁ : is_closed t) : closure s βŠ† t ↔ s βŠ† t := ⟨subset.trans subset_closure, assume h, closure_minimal h hβ‚βŸ© @[mono] lemma closure_mono {s t : set Ξ±} (h : s βŠ† t) : closure s βŠ† closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (Ξ± : Type*) [topological_space Ξ±] : monotone (@closure Ξ± _) := Ξ» _ _, closure_mono lemma diff_subset_closure_iff {s t : set Ξ±} : s \ t βŠ† closure t ↔ s βŠ† closure t := by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure] lemma closure_inter_subset_inter_closure (s t : set Ξ±) : closure (s ∩ t) βŠ† closure s ∩ closure t := (monotone_closure Ξ±).map_inf_le s t lemma is_closed_of_closure_subset {s : set Ξ±} (h : closure s βŠ† s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set Ξ±} : closure s = s ↔ is_closed s := ⟨assume h, h β–Έ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set Ξ±} : closure s βŠ† s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (βˆ… : set Ξ±) = βˆ… := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set Ξ±) : closure s = βˆ… ↔ s = βˆ… := ⟨subset_eq_empty subset_closure, Ξ» h, h.symm β–Έ closure_empty⟩ @[simp] lemma closure_nonempty_iff {s : set Ξ±} : (closure s).nonempty ↔ s.nonempty := by simp only [← ne_empty_iff_nonempty, ne.def, closure_empty_iff] alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure @[simp] lemma closure_univ : closure (univ : set Ξ±) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set Ξ±} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set Ξ±} : closure (s βˆͺ t) = closure s βˆͺ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure) ((monotone_closure Ξ±).le_map_sup s t) lemma interior_subset_closure {s : set Ξ±} : interior s βŠ† closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set Ξ±} : closure s = (interior sᢜ)ᢜ := begin rw [interior, closure, compl_sUnion, compl_image_set_of], simp only [compl_subset_compl, is_open_compl_iff], end @[simp] lemma interior_compl {s : set Ξ±} : interior sᢜ = (closure s)ᢜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set Ξ±} : closure sᢜ = (interior s)ᢜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set Ξ±} {a : Ξ±} : a ∈ closure s ↔ βˆ€ o, is_open o β†’ a ∈ o β†’ (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ Ξ» os, have s βŠ† oᢜ, from Ξ» x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, Ξ» H c ⟨h₁, hβ‚‚βŸ©, classical.by_contradiction $ Ξ» nc, let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (hβ‚‚ hs)⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set Ξ±) : Prop := βˆ€ x, x ∈ closure s lemma dense_iff_closure_eq {s : set Ξ±} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set Ξ±} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set Ξ±} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set Ξ±) := Ξ» x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set Ξ±} : dense s ↔ βˆ€ U, is_open U β†’ U.nonempty β†’ (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.nonempty_iff {s : set Ξ±} (hs : dense s) : s.nonempty ↔ nonempty Ξ± := ⟨λ ⟨x, hx⟩, ⟨x⟩, Ξ» ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty Ξ±] {s : set Ξ±} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ sβ‚‚ : set Ξ±} (h : s₁ βŠ† sβ‚‚) (hd : dense s₁) : dense sβ‚‚ := Ξ» x, closure_mono h (hd x) /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set Ξ±) : set Ξ± := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set Ξ±} : frontier s = closure s ∩ closure sᢜ := by rw [closure_compl, frontier, diff_eq] /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set Ξ±) : frontier sᢜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] @[simp] lemma frontier_univ : frontier (univ : set Ξ±) = βˆ… := by simp [frontier] @[simp] lemma frontier_empty : frontier (βˆ… : set Ξ±) = βˆ… := by simp [frontier] lemma frontier_inter_subset (s t : set Ξ±) : frontier (s ∩ t) βŠ† (frontier s ∩ closure t) βˆͺ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set Ξ±) : frontier (s βˆͺ t) βŠ† (frontier s ∩ closure tᢜ) βˆͺ (closure sᢜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᢜ tᢜ lemma is_closed.frontier_eq {s : set Ξ±} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set Ξ±} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set Ξ±} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set Ξ±} (h : is_closed s) : interior (frontier s) = βˆ… := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) βŠ† interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) βŠ† frontier s := interior_subset, have : interior (frontier s) βŠ† (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set Ξ±) : closure s = interior s βˆͺ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set Ξ±) : closure s = s βˆͺ frontier s := (union_diff_cancel' interior_subset subset_closure).symm /-! ###Β Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ @[irreducible] def nhds (a : Ξ±) : filter Ξ± := (β¨… s ∈ {s : set Ξ± | a ∈ s ∧ is_open s}, π“Ÿ s) localized "notation `𝓝` := nhds" in topological_space /-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : Ξ±) (s : set Ξ±) : filter Ξ± := 𝓝 a βŠ“ π“Ÿ s localized "notation `𝓝[` s `] ` x:100 := nhds_within x s" in topological_space lemma nhds_def (a : Ξ±) : 𝓝 a = (β¨… s ∈ {s : set Ξ± | a ∈ s ∧ is_open s}, π“Ÿ s) := by rw nhds /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : Ξ±) : (𝓝 a).has_basis (Ξ» s : set Ξ±, a ∈ s ∧ is_open s) (Ξ» x, x) := begin rw nhds_def, exact has_basis_binfi_principal (Ξ» s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open_inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ end /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≀ 𝓝 a ↔ βˆ€ s : set Ξ±, a ∈ s β†’ is_open s β†’ s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set Ξ±} (h : a ∈ s) (o : is_open s) (sf : π“Ÿ s ≀ f) : 𝓝 a ≀ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_sets_iff {a : Ξ±} {s : set Ξ±} : s ∈ 𝓝 a ↔ βˆƒtβŠ†s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, Ξ» ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : Ξ±} {p : Ξ± β†’ Prop} : (βˆ€αΆ  x in 𝓝 a, p x) ↔ βˆƒ (t : set Ξ±), (βˆ€ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_sets_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : Ξ±} {f : Ξ± β†’ Ξ²} : map f (𝓝 a) = (β¨… s ∈ {s : set Ξ± | a ∈ s ∧ is_open s}, π“Ÿ (image f s)) := ((nhds_basis_opens a).map f).eq_binfi lemma mem_of_nhds {a : Ξ±} {s : set Ξ±} : s ∈ 𝓝 a β†’ a ∈ s := Ξ» H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : Ξ± β†’ Prop} {a : Ξ±} (h : βˆ€αΆ  y in 𝓝 a, p y) : p a := mem_of_nhds h lemma mem_nhds_sets {a : Ξ±} {s : set Ξ±} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_open.eventually_mem {a : Ξ±} {s : set Ξ±} (hs : is_open s) (ha : a ∈ s) : βˆ€αΆ  x in 𝓝 a, x ∈ s := mem_nhds_sets hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : Ξ±) : (𝓝 a).has_basis (Ξ» s : set Ξ±, s ∈ 𝓝 a ∧ is_open s) (Ξ» x, x) := begin convert nhds_basis_opens a, ext s, split, { rintros ⟨s_in, s_op⟩, exact ⟨mem_of_nhds s_in, s_op⟩ }, { rintros ⟨a_in, s_op⟩, exact ⟨mem_nhds_sets s_op a_in, s_op⟩ }, end /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : Ξ± β†’ Prop} {a : Ξ±} (h : βˆ€αΆ  y in 𝓝 a, p y) : βˆ€αΆ  y in 𝓝 a, βˆ€αΆ  x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, Ξ» x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : Ξ± β†’ Prop} {a : Ξ±} : (βˆ€αΆ  y in 𝓝 a, βˆ€αΆ  x in 𝓝 y, p x) ↔ βˆ€αΆ  x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, Ξ» h, h.eventually_nhds⟩ @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ Ξ» s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : Ξ± β†’ Ξ²} {a : Ξ±} : (βˆ€αΆ  y in 𝓝 a, f =αΆ [𝓝 y] g) ↔ f =αΆ [𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : Ξ± β†’ Ξ²} {a : Ξ±} (h : f =αΆ [𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le Ξ²] {f g : Ξ± β†’ Ξ²} {a : Ξ±} : (βˆ€αΆ  y in 𝓝 a, f ≀ᢠ[𝓝 y] g) ↔ f ≀ᢠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : Ξ± β†’ Ξ²} {a : Ξ±} (h : f =αΆ [𝓝 a] g) : βˆ€αΆ  y in 𝓝 a, f =αΆ [𝓝 y] g := h.eventually_nhds /-- If `f x ≀ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≀ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le Ξ²] {f g : Ξ± β†’ Ξ²} {a : Ξ±} (h : f ≀ᢠ[𝓝 a] g) : βˆ€αΆ  y in 𝓝 a, f ≀ᢠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : Ξ±) (P : set Ξ± β†’ Prop) (hP : βˆ€ s t, s βŠ† t β†’ P s β†’ P t) : (βˆ€ s ∈ 𝓝 x, P s) ↔ (βˆ€ s, is_open s β†’ x ∈ s β†’ P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : Ξ±) (f : set Ξ± β†’ set Ξ²) (hf : βˆ€ s t, s βŠ† t β†’ f s βŠ† f t) (l : filter Ξ²) : (βˆ€ s ∈ 𝓝 x, f s ∈ l) ↔ (βˆ€ s, is_open s β†’ x ∈ s β†’ f s ∈ l) := all_mem_nhds _ _ (Ξ» s t ssubt h, mem_sets_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel Ξ² Ξ±} {l : filter Ξ²} {a : Ξ±} : rtendsto r l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ r.core s ∈ l) := all_mem_nhds_filter _ _ (Ξ» s t, id) _ theorem rtendsto'_nhds {r : rel Ξ² Ξ±} {l : filter Ξ²} {a : Ξ±} : rtendsto' r l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : Ξ² β†’. Ξ±} {l : filter Ξ²} {a : Ξ±} : ptendsto f l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : Ξ² β†’. Ξ±} {l : filter Ξ²} {a : Ξ±} : ptendsto' f l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : Ξ² β†’ Ξ±} {l : filter Ξ²} {a : Ξ±} : tendsto f l (𝓝 a) ↔ (βˆ€ s, is_open s β†’ a ∈ s β†’ f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (Ξ» s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : Ξ±} {f : filter Ξ²} : tendsto (Ξ»b:Ξ², a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha lemma pure_le_nhds : pure ≀ (𝓝 : Ξ± β†’ filter Ξ±) := assume a s hs, mem_pure_sets.2 $ mem_of_nhds hs lemma tendsto_pure_nhds {Ξ± : Type*} [topological_space Ξ²] (f : Ξ± β†’ Ξ²) (a : Ξ±) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {Ξ± : Type*} [order_top Ξ±] [topological_space Ξ²] (f : Ξ± β†’ Ξ²) : tendsto f at_top (𝓝 $ f ⊀) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : Ξ±} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x βŠ“ F β‰  βŠ₯. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : Ξ±) (F : filter Ξ±) : Prop := ne_bot (𝓝 x βŠ“ F) lemma cluster_pt.ne_bot {x : Ξ±} {F : filter Ξ±} (h : cluster_pt x F) : ne_bot (𝓝 x βŠ“ F) := h lemma filter.has_basis.cluster_pt_iff {ΞΉa ΞΉF} {pa : ΞΉa β†’ Prop} {sa : ΞΉa β†’ set Ξ±} {pF : ΞΉF β†’ Prop} {sF : ΞΉF β†’ set Ξ±} {F : filter Ξ±} (ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) : cluster_pt a F ↔ βˆ€ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty := ha.inf_basis_ne_bot_iff hF lemma cluster_pt_iff {x : Ξ±} {F : filter Ξ±} : cluster_pt x F ↔ βˆ€ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. -/ lemma cluster_pt_principal_iff {x : Ξ±} {s : set Ξ±} : cluster_pt x (π“Ÿ s) ↔ βˆ€ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : Ξ±} {s : set Ξ±} : cluster_pt x (π“Ÿ s) ↔ βˆƒαΆ  y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : Ξ±} {f : filter Ξ±} (H : f ≀ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : Ξ±} {f : filter Ξ±} (H : f ≀ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : Ξ±} {f : filter Ξ±} (H : 𝓝 x ≀ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : Ξ±} {f g : filter Ξ±} (H : cluster_pt x f) (h : f ≀ g) : cluster_pt x g := ⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩ lemma cluster_pt.of_inf_left {x : Ξ±} {f g : filter Ξ±} (H : cluster_pt x $ f βŠ“ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : Ξ±} {f g : filter Ξ±} (H : cluster_pt x $ f βŠ“ g) : cluster_pt x g := H.mono inf_le_right lemma ultrafilter.cluster_pt_iff {x : Ξ±} {f : ultrafilter Ξ±} : cluster_pt x f ↔ ↑f ≀ 𝓝 x := ⟨f.le_of_inf_ne_bot', Ξ» h, cluster_pt.of_le_nhds h⟩ /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ΞΉ :Type*} (x : Ξ±) (F : filter ΞΉ) (u : ΞΉ β†’ Ξ±) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ΞΉ :Type*} (x : Ξ±) (F : filter ΞΉ) (u : ΞΉ β†’ Ξ±) : map_cluster_pt x F u ↔ βˆ€ s ∈ 𝓝 x, βˆƒαΆ  a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ΞΉ Ξ΄ :Type*} {F : filter ΞΉ} {Ο† : Ξ΄ β†’ ΞΉ} {p : filter Ξ΄} {x : Ξ±} {u : ΞΉ β†’ Ξ±} [ne_bot p] (h : tendsto Ο† p F) (H : tendsto (u ∘ Ο†) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ Ο†) p = map u (map Ο† p) : map_map ... ≀ map u F : map_mono h, have : map (u ∘ Ο†) p ≀ 𝓝 x βŠ“ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set Ξ±} : interior s = {a | s ∈ 𝓝 a} := set.ext $ Ξ» x, by simp only [mem_interior, mem_nhds_sets_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set Ξ±} : interior s = {a | 𝓝 a ≀ π“Ÿ s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set Ξ±} {a : Ξ±} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] @[simp] lemma interior_mem_nhds {s : set Ξ±} {a : Ξ±} : interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a := ⟨λ h, mem_sets_of_superset h interior_subset, Ξ» h, mem_nhds_sets is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩ lemma interior_set_of_eq {p : Ξ± β†’ Prop} : interior {x | p x} = {x | βˆ€αΆ  y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : Ξ± β†’ Prop} : is_open {x | βˆ€αΆ  y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set Ξ±} : s βŠ† interior V ↔ βˆ€ x ∈ s, V ∈ 𝓝 x := show (βˆ€ x, x ∈ s β†’ x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set Ξ±} : is_open s ↔ βˆ€a∈s, 𝓝 a ≀ π“Ÿ s := calc is_open s ↔ s βŠ† interior s : subset_interior_iff_open.symm ... ↔ (βˆ€a∈s, 𝓝 a ≀ π“Ÿ s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set Ξ±} : is_open s ↔ βˆ€a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ Ξ» _, imp_congr_right $ Ξ» _, le_principal_iff theorem is_open_iff_ultrafilter {s : set Ξ±} : is_open s ↔ (βˆ€ (x ∈ s) (l : ultrafilter Ξ±), ↑l ≀ 𝓝 x β†’ s ∈ l) := by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter] lemma mem_closure_iff_frequently {s : set Ξ±} {a : Ξ±} : a ∈ closure s ↔ βˆƒαΆ  x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter Ξ±} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (Ξ» p, is_closed_union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set Ξ±} {a : Ξ±} : a ∈ closure s ↔ cluster_pt a (π“Ÿ s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma mem_closure_iff_nhds_ne_bot {s : set Ξ±} : a ∈ closure s ↔ 𝓝 a βŠ“ π“Ÿ s β‰  βŠ₯ := mem_closure_iff_cluster_pt.trans ne_bot_iff lemma closure_eq_cluster_pts {s : set Ξ±} : closure s = {a | cluster_pt a (π“Ÿ s)} := set.ext $ Ξ» x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set Ξ±} {a : Ξ±} : a ∈ closure s ↔ βˆ€ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set Ξ±} {a : Ξ±} : a ∈ closure s ↔ βˆ€ t ∈ 𝓝 a, βˆƒ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_comap_ne_bot {A : set Ξ±} {x : Ξ±} : x ∈ closure A ↔ ne_bot (comap (coe : A β†’ Ξ±) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_nhds_basis' {a : Ξ±} {p : Ξ² β†’ Prop} {s : Ξ² β†’ set Ξ±} (h : (𝓝 a).has_basis p s) {t : set Ξ±} : a ∈ closure t ↔ βˆ€ i, p i β†’ (s i ∩ t).nonempty := mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $ by simp only [exists_prop, forall_const] theorem mem_closure_iff_nhds_basis {a : Ξ±} {p : Ξ² β†’ Prop} {s : Ξ² β†’ set Ξ±} (h : (𝓝 a).has_basis p s) {t : set Ξ±} : a ∈ closure t ↔ βˆ€ i, p i β†’ βˆƒ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans $ by simp only [set.nonempty, mem_inter_eq, exists_prop, and_comm] /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set Ξ±} {x : Ξ±} : x ∈ closure s ↔ βˆƒ (u : ultrafilter Ξ±), s ∈ u ∧ ↑u ≀ 𝓝 x := by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm] lemma is_closed_iff_cluster_pt {s : set Ξ±} : is_closed s ↔ βˆ€a, cluster_pt a (π“Ÿ s) β†’ a ∈ s := calc is_closed s ↔ closure s βŠ† s : closure_subset_iff_is_closed.symm ... ↔ (βˆ€a, cluster_pt a (π“Ÿ s) β†’ a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set Ξ±} : is_closed s ↔ βˆ€ x, (βˆ€ U ∈ 𝓝 x, (U ∩ s).nonempty) β†’ x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma closure_inter_open {s t : set Ξ±} (h : is_open s) : s ∩ closure t βŠ† closure (s ∩ t) := begin rintro a ⟨hs, ht⟩, have : s ∈ 𝓝 a := mem_nhds_sets h hs, rw mem_closure_iff_nhds_ne_bot at ht ⊒, rwa [← inf_principal, ← inf_assoc, inf_eq_left.2 (le_principal_iff.2 this)], end lemma closure_inter_open' {s t : set Ξ±} (h : is_open t) : closure s ∩ t βŠ† closure (s ∩ t) := by simpa only [inter_comm] using closure_inter_open h /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set Ξ±} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := Ξ» x, (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set Ξ±} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s β–Έ ht.inter_of_open_left hs hto lemma dense.inter_nhds_nonempty {s t : set Ξ±} (hs : dense s) {x : Ξ±} (ht : t ∈ 𝓝 x) : (s ∩ t).nonempty := let ⟨U, hsub, ho, hx⟩ := mem_nhds_sets_iff.1 ht in (hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ Ξ» y hy, ⟨hy.2, hsub hy.1⟩ lemma closure_diff {s t : set Ξ±} : closure s \ closure t βŠ† closure (s \ t) := calc closure s \ closure t = (closure t)ᢜ ∩ closure s : by simp only [diff_eq, inter_comm] ... βŠ† closure ((closure t)ᢜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... βŠ† closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma filter.frequently.mem_of_closed {a : Ξ±} {s : set Ξ±} (h : βˆƒαΆ  x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : Ξ² β†’ Ξ±} {b : filter Ξ²} {a : Ξ±} {s : set Ξ±} (hs : is_closed s) (h : βˆƒαΆ  x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show βˆƒαΆ  x in b, (Ξ» y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : Ξ² β†’ Ξ±} {b : filter Ξ²} {a : Ξ±} {s : set Ξ±} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : βˆ€αΆ  x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_tendsto {f : Ξ² β†’ Ξ±} {b : filter Ξ²} {a : Ξ±} {s : set Ξ±} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : βˆ€αΆ  x in b, f x ∈ s) : a ∈ closure s := is_closed_closure.mem_of_tendsto hf $ h.mono (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : Ξ² β†’ Ξ±} {l : filter Ξ²} {s : set Ξ²} {a : Ξ±} (h : βˆ€ x βˆ‰ s, f x = a) : tendsto f (l βŠ“ π“Ÿ s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : π“Ÿ sᢜ ≀ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm β–Έ mem_of_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty Ξ±] (f : filter Ξ±) : Ξ± := epsilon $ Ξ»a, f ≀ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter Ξ±) [ne_bot f] : Ξ± := @Lim _ _ (nonempty_of_ne_bot f) f /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter Ξ±`. -/ def ultrafilter.Lim : ultrafilter Ξ± β†’ Ξ± := Ξ» F, Lim' F /-- If `f` is a filter in `Ξ²` and `g : Ξ² β†’ Ξ±` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty Ξ±] (f : filter Ξ²) (g : Ξ² β†’ Ξ±) : Ξ± := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty Ξ±]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty Ξ±]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter Ξ±} (h : βˆƒa, f ≀ 𝓝 a) : f ≀ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty Ξ±]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty Ξ±]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter Ξ²} {g : Ξ² β†’ Ξ±} (h : βˆƒ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim /-! ### Locally finite families -/ /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set Ξ±` is locally finite if at every point `x:Ξ±`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : Ξ² β†’ set Ξ±) := βˆ€x:Ξ±, βˆƒt ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty } lemma locally_finite.point_finite {f : Ξ² β†’ set Ξ±} (hf : locally_finite f) (x : Ξ±) : finite {b | x ∈ f b} := let ⟨t, hxt, ht⟩ := hf x in ht.subset $ Ξ» b hb, ⟨x, hb, mem_of_nhds hxt⟩ lemma locally_finite_of_fintype [fintype Ξ²] (f : Ξ² β†’ set Ξ±) : locally_finite f := assume x, ⟨univ, univ_mem_sets, finite.of_fintype _⟩ lemma locally_finite.subset {f₁ fβ‚‚ : Ξ² β†’ set Ξ±} (hfβ‚‚ : locally_finite fβ‚‚) (hf : βˆ€b, f₁ b βŠ† fβ‚‚ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, htβ‚‚βŸ© := hfβ‚‚ a in ⟨t, ht₁, htβ‚‚.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma locally_finite.comp_injective {ΞΉ} {f : Ξ² β†’ set Ξ±} {g : ΞΉ β†’ Ξ²} (hf : locally_finite f) (hg : function.injective g) : locally_finite (f ∘ g) := Ξ» x, let ⟨t, htx, htf⟩ := hf x in ⟨t, htx, htf.preimage (hg.inj_on _)⟩ lemma locally_finite.closure {f : Ξ² β†’ set Ξ±} (hf : locally_finite f) : locally_finite (Ξ» i, closure (f i)) := begin intro x, rcases hf x with ⟨s, hsx, hsf⟩, refine ⟨interior s, interior_mem_nhds.2 hsx, hsf.subset $ Ξ» i hi, _⟩, exact (hi.mono (closure_inter_open' is_open_interior)).of_closure.mono (inter_subset_inter_right _ interior_subset) end lemma locally_finite.is_closed_Union {f : Ξ² β†’ set Ξ±} (h₁ : locally_finite f) (hβ‚‚ : βˆ€i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_compl_iff.1 $ is_open_iff_nhds.mpr $ assume a, assume h : a βˆ‰ (⋃i, f i), have βˆ€i, a ∈ (f i)ᢜ, from assume i hi, h $ mem_Union.2 ⟨i, hi⟩, have βˆ€i, (f i)ᢜ ∈ (𝓝 a), by simp only [mem_nhds_sets_iff]; exact assume i, ⟨(f i)ᢜ, subset.refl _, (hβ‚‚ i).is_open_compl, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | (f i ∩ t).nonempty })⟩ := h₁ a in calc 𝓝 a ≀ π“Ÿ (t ∩ (β‹‚ i∈{i | (f i ∩ t).nonempty }, (f i)ᢜ)) : by simp * ... ≀ π“Ÿ (⋃i, f i)ᢜ : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, exists_imp_distrib, ne_empty_iff_nonempty, set.nonempty], exact assume x xt ht i xfi, ht i x xfi xt xfi end lemma locally_finite.closure_Union {f : Ξ² β†’ set Ξ±} (h : locally_finite f) : closure (⋃ i, f i) = ⋃ i, closure (f i) := subset.antisymm (closure_minimal (Union_subset_Union $ Ξ» _, subset_closure) $ h.closure.is_closed_Union $ Ξ» _, is_closed_closure) (Union_subset $ Ξ» i, closure_mono $ subset_Union _ _) end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*} variables [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ structure continuous (f : Ξ± β†’ Ξ²) : Prop := (is_open_preimage : βˆ€s, is_open s β†’ is_open (f ⁻¹' s)) lemma continuous_def {f : Ξ± β†’ Ξ²} : continuous f ↔ (βˆ€s, is_open s β†’ is_open (f ⁻¹' s)) := ⟨λ hf s hs, hf.is_open_preimage s hs, Ξ» h, ⟨h⟩⟩ lemma is_open.preimage {f : Ξ± β†’ Ξ²} (hf : continuous f) {s : set Ξ²} (h : is_open s) : is_open (f ⁻¹' s) := hf.is_open_preimage s h /-- A function between topological spaces is continuous at a point `xβ‚€` if `f x` tends to `f xβ‚€` when `x` tends to `xβ‚€`. -/ def continuous_at (f : Ξ± β†’ Ξ²) (x : Ξ±) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : Ξ± β†’ Ξ²} {x : Ξ±} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at_congr {f g : Ξ± β†’ Ξ²} {x : Ξ±} (h : f =αΆ [𝓝 x] g) : continuous_at f x ↔ continuous_at g x := by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds] lemma continuous_at.congr {f g : Ξ± β†’ Ξ²} {x : Ξ±} (hf : continuous_at f x) (h : f =αΆ [𝓝 x] g) : continuous_at g x := (continuous_at_congr h).1 hf lemma continuous_at.preimage_mem_nhds {f : Ξ± β†’ Ξ²} {x : Ξ±} {t : set Ξ²} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma eventually_eq_zero_nhds {Mβ‚€} [has_zero Mβ‚€] {a : Ξ±} {f : Ξ± β†’ Mβ‚€} : f =αΆ [𝓝 a] 0 ↔ a βˆ‰ closure (function.support f) := by rw [← mem_compl_eq, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl lemma cluster_pt.map {x : Ξ±} {la : filter Ξ±} {lb : filter Ξ²} (H : cluster_pt x la) {f : Ξ± β†’ Ξ²} (hfc : continuous_at f x) (hf : tendsto f la lb) : cluster_pt (f x) lb := ⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩ lemma preimage_interior_subset_interior_preimage {f : Ξ± β†’ Ξ²} {s : set Ξ²} (hf : continuous f) : f⁻¹' (interior s) βŠ† interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf) lemma continuous_id : continuous (id : Ξ± β†’ Ξ±) := continuous_def.2 $ assume s h, h lemma continuous.comp {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := continuous_def.2 $ assume s h, (h.preimage hg).preimage hf lemma continuous.iterate {f : Ξ± β†’ Ξ±} (h : continuous f) (n : β„•) : continuous (f^[n]) := nat.rec_on n continuous_id (Ξ» n ihn, ihn.comp h) lemma continuous_at.comp {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} {x : Ξ±} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : Ξ± β†’ Ξ²} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ Ξ» t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩ /-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ lemma continuous.tendsto' {f : Ξ± β†’ Ξ²} (hf : continuous f) (x : Ξ±) (y : Ξ²) (h : f x = y) : tendsto f (𝓝 x) (𝓝 y) := h β–Έ hf.tendsto x lemma continuous.continuous_at {f : Ξ± β†’ Ξ²} {x : Ξ±} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : Ξ± β†’ Ξ²} : continuous f ↔ βˆ€ x, continuous_at f x := ⟨continuous.tendsto, assume hf : βˆ€x, tendsto f (𝓝 x) (𝓝 (f x)), continuous_def.2 $ assume s, assume hs : is_open s, have βˆ€a, f a ∈ s β†’ s ∈ 𝓝 (f a), from Ξ» a ha, mem_nhds_sets hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ Ξ» a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_at_const {x : Ξ±} {b : Ξ²} : continuous_at (Ξ» a:Ξ±, b) x := tendsto_const_nhds lemma continuous_const {b : Ξ²} : continuous (Ξ»a:Ξ±, b) := continuous_iff_continuous_at.mpr $ assume a, continuous_at_const lemma continuous_at_id {x : Ξ±} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : Ξ± β†’ Ξ±} {x : Ξ±} (hf : continuous_at f x) (hx : f x = x) (n : β„•) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ Ξ» n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm β–Έ ihn) hf lemma continuous_iff_is_closed {f : Ξ± β†’ Ξ²} : continuous f ↔ (βˆ€s, is_closed s β†’ is_closed (f ⁻¹' s)) := ⟨assume hf s hs, by simpa using (continuous_def.1 hf sᢜ hs.is_open_compl).is_closed_compl, assume hf, continuous_def.2 $ assume s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : Ξ± β†’ Ξ²} (hf : continuous f) {s : set Ξ²} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma continuous_at_iff_ultrafilter {f : Ξ± β†’ Ξ²} {x} : continuous_at f x ↔ βˆ€ g : ultrafilter Ξ±, ↑g ≀ 𝓝 x β†’ tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : Ξ± β†’ Ξ²} : continuous f ↔ βˆ€ x (g : ultrafilter Ξ±), ↑g ≀ 𝓝 x β†’ tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] /-! ### Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : Ξ± β†’. Ξ²) := βˆ€ s, is_open s β†’ is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : Ξ± β†’. Ξ²} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : Ξ± β†’. Ξ²} : pcontinuous f ↔ βˆ€ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_sets_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal_sets], assume h : f.preimage s βŠ† t, change t ∈ 𝓝 x, apply mem_sets_of_superset _ h, have h' : βˆ€ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_sets_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ lemma set.maps_to.closure {s : set Ξ±} {t : set Ξ²} {f : Ξ± β†’ Ξ²} (h : maps_to f s t) (hc : continuous f) : maps_to f (closure s) (closure t) := begin simp only [maps_to, mem_closure_iff_cluster_pt], exact Ξ» x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h) end lemma image_closure_subset_closure_image {f : Ξ± β†’ Ξ²} {s : set Ξ±} (h : continuous f) : f '' closure s βŠ† closure (f '' s) := ((maps_to_image f s).closure h).image_subset lemma closure_subset_preimage_closure_image {f : Ξ± β†’ Ξ²} {s : set Ξ±} (h : continuous f) : closure s βŠ† f ⁻¹' (closure (f '' s)) := by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h } lemma map_mem_closure {s : set Ξ±} {t : set Ξ²} {f : Ξ± β†’ Ξ²} {a : Ξ±} (hf : continuous f) (ha : a ∈ closure s) (ht : βˆ€a∈s, f a ∈ t) : f a ∈ closure t := set.maps_to.closure ht hf ha /-! ### Function with dense range -/ section dense_range variables {ΞΊ ΞΉ : Type*} (f : ΞΊ β†’ Ξ²) (g : Ξ² β†’ Ξ³) /-- `f : ΞΉ β†’ Ξ²` has dense range if its range (image) is a dense subset of Ξ². -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := Ξ» x, by simp [hf.range_eq] lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma continuous.range_subset_closure_image_dense {f : Ξ± β†’ Ξ²} (hf : continuous f) {s : set Ξ±} (hs : dense s) : range f βŠ† closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : Ξ± β†’ Ξ²} (hf' : dense_range f) (hf : continuous f) {s : set Ξ±} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : Ξ± β†’ Ξ²} (hf' : dense_range f) (hf : continuous f) {s : set Ξ±} (hs : dense s) {t : set Ξ²} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : Ξ² β†’ Ξ³} {f : ΞΊ β†’ Ξ²} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty ΞΊ ↔ nonempty Ξ² := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty Ξ²] (hf : dense_range f) : nonempty ΞΊ := hf.nonempty_iff.mpr h /-- Given a function `f : Ξ± β†’ Ξ²` with dense range and `b : Ξ²`, returns some `a : Ξ±`. -/ def dense_range.some (hf : dense_range f) (b : Ξ²) : ΞΊ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ end dense_range end continuous
f2a16fea971a54309f7d06083a9945fe2403fe6f
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/real/nnreal.lean
95350c393afc916d36525e8e54d3fb3d37575719
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
14,242
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import data.real.basic order.lattice section discrete_field @[simp] lemma inv_eq_zero {Ξ±} [discrete_field Ξ±] (a : Ξ±) : a⁻¹ = 0 ↔ a = 0 := classical.by_cases (assume : a = 0, by simp [*])(assume : a β‰  0, by simp [*, inv_ne_zero]) end discrete_field namespace set @[simp] lemma image_eq_empty {Ξ± Ξ²} {f : Ξ± β†’ Ξ²} {s : set Ξ±} : f '' s = βˆ… ↔ s = βˆ… := begin simp [eq_empty_iff_forall_not_mem], exact iff.intro (assume h a has, h (f a) a has rfl) (assume h b a has eq, h a has) end end set noncomputable theory open lattice local attribute [instance] classical.prop_decidable def nnreal := {r : ℝ // 0 ≀ r} local notation ` ℝβ‰₯0 ` := nnreal namespace nnreal instance : has_coe ℝβ‰₯0 ℝ := ⟨subtype.val⟩ protected lemma eq {n m : ℝβ‰₯0} : (n : ℝ) = (m : ℝ) β†’ n = m := subtype.eq protected lemma eq_iff {n m : ℝβ‰₯0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) protected def of_real (r : ℝ) : ℝβ‰₯0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≀ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr instance : has_zero ℝβ‰₯0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝβ‰₯0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝβ‰₯0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝβ‰₯0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝβ‰₯0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝβ‰₯0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝβ‰₯0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩ instance : has_le ℝβ‰₯0 := ⟨λ r s, (r:ℝ) ≀ s⟩ instance : has_bot ℝβ‰₯0 := ⟨0⟩ instance : inhabited ℝβ‰₯0 := ⟨0⟩ @[simp] protected lemma coe_zero : ((0 : ℝβ‰₯0) : ℝ) = 0 := rfl @[simp] protected lemma coe_one : ((1 : ℝβ‰₯0) : ℝ) = 1 := rfl @[simp] protected lemma coe_add (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ + rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ + rβ‚‚ := rfl @[simp] protected lemma coe_mul (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ * rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ * rβ‚‚ := rfl @[simp] protected lemma coe_div (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ / rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ / rβ‚‚ := rfl @[simp] protected lemma coe_inv (r : ℝβ‰₯0) : ((r⁻¹ : ℝβ‰₯0) : ℝ) = r⁻¹ := rfl @[simp] protected lemma coe_sub (r₁ rβ‚‚ : ℝβ‰₯0) (h : rβ‚‚ ≀ r₁) : ((r₁ - rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ - rβ‚‚ := max_eq_left $ le_sub.2 $ by simp [show (rβ‚‚ : ℝ) ≀ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma zero_div (r : ℝβ‰₯0) : 0 / r = 0 := nnreal.eq (zero_div _) @[simp] protected lemma coe_eq_zero (r : ℝβ‰₯0) : ↑r = (0 : ℝ) ↔ r = 0 := @nnreal.eq_iff r 0 instance : comm_semiring ℝβ‰₯0 := begin refine { zero := 0, add := (+), one := 1, mul := (*), ..}; { intros; apply nnreal.eq; simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib, add_comm_monoid.zero] } end lemma sum_coe {Ξ±} {s : finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(s.sum f) = s.sum (Ξ»a, (f a : ℝ)) := eq.symm $ finset.sum_hom _ rfl (assume a b, rfl) lemma prod_coe {Ξ±} {s : finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(s.prod f) = s.prod (Ξ»a, (f a : ℝ)) := eq.symm $ finset.prod_hom _ rfl (assume a b, rfl) lemma smul_coe (r : ℝβ‰₯0) : βˆ€n, ↑(add_monoid.smul n r) = add_monoid.smul n (r:ℝ) | 0 := rfl | (n + 1) := by simp [add_monoid.add_smul, smul_coe n] @[simp] protected lemma coe_nat_cast : βˆ€(n : β„•), (↑(↑n : ℝβ‰₯0) : ℝ) = n | 0 := rfl | (n + 1) := by simp [coe_nat_cast n] instance : decidable_linear_order ℝβ‰₯0 := { le := (≀), lt := Ξ»a b, (a : ℝ) < b, lt_iff_le_not_le := assume a b, @lt_iff_le_not_le ℝ _ a b, le_refl := assume a, le_refl (a : ℝ), le_trans := assume a b c, @le_trans ℝ _ a b c, le_antisymm := assume a b hab hba, nnreal.eq $ le_antisymm hab hba, le_total := assume a b, le_total (a : ℝ) b, decidable_le := Ξ»a b, by apply_instance } protected lemma coe_le (r₁ rβ‚‚ : ℝβ‰₯0) : r₁ ≀ rβ‚‚ ↔ (r₁ : ℝ) ≀ rβ‚‚ := iff.refl _ protected lemma coe_lt (r₁ rβ‚‚ : ℝβ‰₯0) : r₁ < rβ‚‚ ↔ (r₁ : ℝ) < rβ‚‚ := iff.refl _ instance : canonically_ordered_monoid ℝβ‰₯0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≀ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm β–Έ show a ≀ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.decidable_linear_order} instance : order_bot ℝβ‰₯0 := { bot := βŠ₯, bot_le := zero_le, .. nnreal.decidable_linear_order } instance : distrib_lattice ℝβ‰₯0 := by apply_instance instance : semilattice_inf_bot ℝβ‰₯0 := { .. nnreal.lattice.order_bot, .. nnreal.lattice.distrib_lattice } instance : semilattice_sup_bot ℝβ‰₯0 := { .. nnreal.lattice.order_bot, .. nnreal.lattice.distrib_lattice } instance : linear_ordered_semiring ℝβ‰₯0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c, mul_le_mul_of_nonneg_left := assume a b c, @mul_le_mul_of_nonneg_left ℝ _ a b c, mul_le_mul_of_nonneg_right := assume a b c, @mul_le_mul_of_nonneg_right ℝ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_lt_one := @zero_lt_one ℝ _, .. nnreal.decidable_linear_order, .. nnreal.canonically_ordered_monoid, .. nnreal.comm_semiring } instance : canonically_ordered_comm_semiring ℝβ‰₯0 := { zero_ne_one := assume h, @zero_ne_one ℝ _ $ congr_arg subtype.val $ h, mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp, .. nnreal.linear_ordered_semiring, .. nnreal.canonically_ordered_monoid, .. nnreal.comm_semiring } instance : densely_ordered ℝβ‰₯0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝβ‰₯0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝβ‰₯0} : bdd_above ((coe : nnreal β†’ ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≀ max b 0, from le_max_left_of_le $ hb _ $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq β–Έ hb _ $ hx⟩) lemma bdd_below_coe (s : set ℝβ‰₯0) : bdd_below ((coe : nnreal β†’ ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq β–Έ q.2⟩ instance : has_Sup ℝβ‰₯0 := ⟨λs, ⟨Sup ((coe : nnreal β†’ ℝ) '' s), begin by_cases h : s = βˆ…, { simp [h, set.image_empty, real.Sup_empty] }, rcases set.ne_empty_iff_exists_mem.1 h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝβ‰₯0 := ⟨λs, ⟨Inf ((coe : nnreal β†’ ℝ) '' s), begin by_cases h : s = βˆ…, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (by simp [h]) (assume r ⟨q, _, eq⟩, eq β–Έ q.2) end⟩⟩ lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal β†’ ℝ) '' s) := rfl lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal β†’ ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝβ‰₯0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : nnreal β†’ ℝ) '' s) ≀ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq β–Έ h _ hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≀ Inf ((coe : nnreal β†’ ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq β–Έ h _ hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, .. nnreal.linear_ordered_semiring, .. lattice.lattice_of_decidable_linear_order, .. nnreal.lattice.order_bot } instance : archimedean nnreal := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≀ (add_monoid.smul n y : nnreal), by simp [*, smul_coe]⟩ ⟩ lemma le_of_forall_epsilon_le {a b : nnreal} (h : βˆ€Ξ΅, Ξ΅ > 0 β†’ a ≀ b + Ξ΅) : a ≀ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨Ρ, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end lemma lt_iff_exists_rat_btwn (a b : nnreal) : a < b ↔ (βˆƒq:β„š, 0 ≀ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≀ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (βŠ₯ : nnreal) = 0 := rfl lemma mul_sup (a b c : ℝβ‰₯0) : a * (b βŠ” c) = (a * b) βŠ” (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {Ξ±} {f : Ξ± β†’ ℝβ‰₯0} {s : finset Ξ±} (r : ℝβ‰₯0) : r * s.sup f = s.sup (Ξ»a, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end section of_real @[simp] lemma zero_le_coe {q : nnreal} : 0 ≀ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma zero_lt_of_real (r : ℝ) : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt, lt_max_iff, lt_irrefl] @[simp] lemma of_real_coe {r : nnreal} : nnreal.of_real r = r := nnreal.eq $ by simp [nnreal.of_real, max_eq_left] @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hr : 0 ≀ r) (hp : 0 ≀ p) : nnreal.of_real r ≀ nnreal.of_real p ↔ r ≀ p := by simp [nnreal.coe_le, nnreal.of_real, hr, hp, max_eq_left] @[simp] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≀ r) (hp : 0 ≀ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := nnreal.eq $ by simp [nnreal.of_real, hr, hp, max_eq_left, add_nonneg] lemma of_real_of_nonpos {r : ℝ} (h : r ≀ 0) : nnreal.of_real r = 0 := by simp [nnreal.of_real, max_eq_right h]; refl lemma of_real_le_of_real {r p : ℝ} (h : r ≀ p) : nnreal.of_real r ≀ nnreal.of_real p := (nnreal.coe_le _ _).2 $ max_le_max h $ le_refl _ lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≀ nnreal.of_real r + nnreal.of_real p := (nnreal.coe_le _ _).2 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe end of_real section mul lemma mul_eq_mul_left {a b c : nnreal} (h : a β‰  0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end end mul section sub lemma sub_eq_zero {r p : nnreal} (h : r ≀ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le] using h @[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≀ q ↔ r ≀ q + p := match le_total p r with | or.inl h := by rw [nnreal.coe_le, nnreal.coe_le, nnreal.coe_sub _ _ h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≀ p + q, from le_add_right h, by simpa [nnreal.coe_le, nnreal.coe_le, sub_eq_zero h] end lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] @[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≀ a) : (a - b) + b = a := nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub _ _ h, sub_add_cancel] end sub section inv lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl @[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero @[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 := by rw [← nnreal.eq_iff, nnreal.coe_inv, nnreal.coe_zero, inv_eq_zero, ← nnreal.coe_zero, nnreal.eq_iff] @[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r := by simp [zero_lt_iff_ne_zero] @[simp] lemma inv_mul_cancel {r : ℝβ‰₯0} (h : r β‰  0) : r⁻¹ * r = 1 := nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h @[simp] lemma mul_inv_cancel {r : ℝβ‰₯0} (h : r β‰  0) : r * r⁻¹ = 1 := by rw [mul_comm, inv_mul_cancel h] @[simp] lemma inv_inv {r : ℝβ‰₯0} : r⁻¹⁻¹ = r := nnreal.eq inv_inv' @[simp] lemma inv_le {r p : ℝβ‰₯0} (h : r β‰  0) : r⁻¹ ≀ p ↔ 1 ≀ r * p := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝβ‰₯0} (h : 1 ≀ r * p) : r⁻¹ ≀ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝβ‰₯0} (h : p β‰  0) : (r ≀ p⁻¹ ↔ r * p ≀ 1) := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] end inv end nnreal
633620b24c8451cb08dd2728d604fafeb5299c76
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/lean/run/compiler_proj_bug.lean
c23b8abb4e5fb92b77dfaa4cb76a5fd2f2994ee4
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
122
lean
structure S := (a : Nat) (h : a > 0) (b : Nat) def f (s : S) := s.b - s.a #exit #eval f {a := 5, b := 30, h := sorry }
01b752375f63bba7988051ae1ee7f1380e950d44
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/tactic/reassoc_axiom.lean
b9ab9f71252f97386aaaeaf5df35118978ecde18
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,015
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import category_theory.category.basic /-! # Tools to reformulate category-theoretic axioms in a more associativity-friendly way ## The `reassoc` attribute The `reassoc` attribute can be applied to a lemma ```lean @[reassoc] lemma some_lemma : foo ≫ bar = baz := ... ``` and produce ```lean lemma some_lemma_assoc {Y : C} (f : X ⟢ Y) : foo ≫ bar ≫ f = baz ≫ f := ... ``` The name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If `simp` is added first, the generated lemma will also have the `simp` attribute. ## The `reassoc_axiom` command When declaring a class of categories, the axioms can be reformulated to be more amenable to manipulation in right associated expressions: ```lean class some_class (C : Type) [category C] := (foo : Ξ  X : C, X ⟢ X) (bar : βˆ€ {X Y : C} (f : X ⟢ Y), foo X ≫ f = f ≫ foo Y) reassoc_axiom some_class.bar ``` Here too, the `reassoc` attribute can be used instead. It works well when combined with `simp`: ```lean attribute [simp, reassoc] some_class.bar ``` -/ namespace tactic open interactive lean.parser category_theory /-- From an expression `f ≫ g`, extract the expression representing the category instance. -/ meta def get_cat_inst : expr β†’ tactic expr | `(@category_struct.comp _ %%struct_inst _ _ _ _ _) := pure struct_inst | _ := failed /-- (internals for `@[reassoc]`) Given a lemma of the form `βˆ€ ..., f ≫ g = h`, proves a new lemma of the form `h : βˆ€ ... {W} (k), f ≫ (g ≫ k) = h ≫ k`, and returns the type and proof of this lemma. -/ meta def prove_reassoc (h : expr) : tactic (expr Γ— expr) := do (vs,t) ← infer_type h >>= open_pis, (lhs,rhs) ← match_eq t, struct_inst ← get_cat_inst lhs <|> get_cat_inst rhs <|> fail "no composition found in statement", `(@quiver.hom _ %%hom_inst %%X %%Y) ← infer_type lhs, C ← infer_type X, X' ← mk_local' `X' binder_info.implicit C, ft ← to_expr ``(@quiver.hom _ %%hom_inst %%Y %%X'), f' ← mk_local_def `f' ft, t' ← to_expr ``(@category_struct.comp _ %%struct_inst _ _ _%%lhs %%f' = @category_struct.comp _ %%struct_inst _ _ _ %%rhs %%f'), let c' := h.mk_app vs, (_,pr) ← solve_aux t' (rewrite_target c'; reflexivity), pr ← instantiate_mvars pr, let s := simp_lemmas.mk, s ← s.add_simp ``category.assoc, s ← s.add_simp ``category.id_comp, s ← s.add_simp ``category.comp_id, (t'', pr', _) ← simplify s [] t', pr' ← mk_eq_mp pr' pr, t'' ← pis (vs ++ [X',f']) t'', pr' ← lambdas (vs ++ [X',f']) pr', pure (t'',pr') /-- (implementation for `@[reassoc]`) Given a declaration named `n` of the form `βˆ€ ..., f ≫ g = h`, proves a new lemma named `n'` of the form `βˆ€ ... {W} (k), f ≫ (g ≫ k) = h ≫ k`. -/ meta def reassoc_axiom (n : name) (n' : name := n.append_suffix "_assoc") : tactic unit := do d ← get_decl n, let ls := d.univ_params.map level.param, let c := @expr.const tt n ls, (t'',pr') ← prove_reassoc c, add_decl $ declaration.thm n' d.univ_params t'' (pure pr'), copy_attribute `simp n n' /-- The `reassoc` attribute can be applied to a lemma ```lean @[reassoc] lemma some_lemma : foo ≫ bar = baz := ... ``` to produce ```lean lemma some_lemma_assoc {Y : C} (f : X ⟢ Y) : foo ≫ bar ≫ f = baz ≫ f := ... ``` The name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If `simp` is added first, the generated lemma will also have the `simp` attribute. -/ @[user_attribute] meta def reassoc_attr : user_attribute unit (option name) := { name := `reassoc, descr := "create a companion lemma for associativity-aware rewriting", parser := optional ident, after_set := some (Ξ» n _ _, do some n' ← reassoc_attr.get_param n | reassoc_axiom n (n.append_suffix "_assoc"), reassoc_axiom n $ n.get_prefix ++ n' ) } add_tactic_doc { name := "reassoc", category := doc_category.attr, decl_names := [`tactic.reassoc_attr], tags := ["category theory"] } /-- When declaring a class of categories, the axioms can be reformulated to be more amenable to manipulation in right associated expressions: ```lean class some_class (C : Type) [category C] := (foo : Ξ  X : C, X ⟢ X) (bar : βˆ€ {X Y : C} (f : X ⟢ Y), foo X ≫ f = f ≫ foo Y) reassoc_axiom some_class.bar ``` The above will produce: ```lean lemma some_class.bar_assoc {Z : C} (g : Y ⟢ Z) : foo X ≫ f ≫ g = f ≫ foo Y ≫ g := ... ``` Here too, the `reassoc` attribute can be used instead. It works well when combined with `simp`: ```lean attribute [simp, reassoc] some_class.bar ``` -/ @[user_command] meta def reassoc_cmd (_ : parse $ tk "reassoc_axiom") : lean.parser unit := do n ← ident, of_tactic $ do n ← resolve_constant n, reassoc_axiom n add_tactic_doc { name := "reassoc_axiom", category := doc_category.cmd, decl_names := [`tactic.reassoc_cmd], tags := ["category theory"] } namespace interactive setup_tactic_parser /-- `reassoc h`, for assumption `h : x ≫ y = z`, creates a new assumption `h : βˆ€ {W} (f : Z ⟢ W), x ≫ y ≫ f = z ≫ f`. `reassoc! h`, does the same but deletes the initial `h` assumption. (You can also add the attribute `@[reassoc]` to lemmas to generate new declarations generalized in this way.) -/ meta def reassoc (del : parse (tk "!")?) (ns : parse ident*) : tactic unit := do ns.mmap' (Ξ» n, do h ← get_local n, (t,pr) ← prove_reassoc h, assertv n t pr, when del.is_some (tactic.clear h) ) end interactive def calculated_Prop {Ξ±} (Ξ² : Prop) (hh : Ξ±) := Ξ² meta def derive_reassoc_proof : tactic unit := do `(calculated_Prop %%v %%h) ← target, (t,pr) ← prove_reassoc h, unify v t, exact pr end tactic /-- With `h : x ≫ y ≫ z = x` (with universal quantifiers tolerated), `reassoc_of h : βˆ€ {X'} (f : W ⟢ X'), x ≫ y ≫ z ≫ f = x ≫ f`. The type and proof of `reassoc_of h` is generated by `tactic.derive_reassoc_proof` which make `reassoc_of` meta-programming adjacent. It is not called as a tactic but as an expression. The goal is to avoid creating assumptions that are dismissed after one use: ```lean example (X Y Z W : C) (x : X ⟢ Y) (y : Y ⟢ Z) (z z' : Z ⟢ W) (w : X ⟢ Z) (h : x ≫ y = w) (h' : y ≫ z = y ≫ z') : x ≫ y ≫ z = w ≫ z' := begin rw [h',reassoc_of h], end ``` -/ theorem category_theory.reassoc_of {Ξ±} (hh : Ξ±) {Ξ²} (x : tactic.calculated_Prop Ξ² hh . tactic.derive_reassoc_proof) : Ξ² := x /-- `reassoc_of h` takes local assumption `h` and add a ` ≫ f` term on the right of both sides of the equality. Instead of creating a new assumption from the result, `reassoc_of h` stands for the proof of that reassociated statement. This keeps complicated assumptions that are used only once or twice from polluting the local context. In the following, assumption `h` is needed in a reassociated form. Instead of proving it as a new goal and adding it as an assumption, we use `reassoc_of h` as a rewrite rule which works just as well. ```lean example (X Y Z W : C) (x : X ⟢ Y) (y : Y ⟢ Z) (z z' : Z ⟢ W) (w : X ⟢ Z) (h : x ≫ y = w) (h' : y ≫ z = y ≫ z') : x ≫ y ≫ z = w ≫ z' := begin -- reassoc_of h : βˆ€ {X' : C} (f : W ⟢ X'), x ≫ y ≫ f = w ≫ f rw [h',reassoc_of h], end ``` Although `reassoc_of` is not a tactic or a meta program, its type is generated through meta-programming to make it usable inside normal expressions. -/ add_tactic_doc { name := "category_theory.reassoc_of", category := doc_category.tactic, decl_names := [`category_theory.reassoc_of], tags := ["category theory"] }
bc4a9e6ec2f78e3abffb55f23b5340a78e3fec2a
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/tactic.lean
9b414c2682dc234e88c9bc2b8ac63de66017b0ab
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
6,608
lean
/- Copyright (c) 2021 RΓ©my Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: RΓ©my Degenne -/ import measure_theory.measure.measure_space_def import tactic.auto_cases import tactic.tidy import tactic.with_local_reducibility /-! # Tactics for measure theory Currently we have one domain-specific tactic for measure theory: `measurability`. This tactic is to a large extent a copy of the `continuity` tactic by Reid Barton. -/ /-! ### `measurability` tactic Automatically solve goals of the form `measurable f`, `ae_measurable f ΞΌ` and `measurable_set s`. Mark lemmas with `@[measurability]` to add them to the set of lemmas used by `measurability`. Note: `to_additive` doesn't know yet how to copy the attribute to the additive version. -/ /-- User attribute used to mark tactics used by `measurability`. -/ @[user_attribute] meta def measurability : user_attribute := { name := `measurability, descr := "lemmas usable to prove (ae)-measurability" } /- Mark some measurability lemmas already defined in `measure_theory.measurable_space_def` and `measure_theory.measure_space_def` -/ attribute [measurability] measurable_id measurable_id' ae_measurable_id ae_measurable_id' measurable_const ae_measurable_const ae_measurable.measurable_mk measurable_set.empty measurable_set.univ measurable_set.compl subsingleton.measurable_set measurable_set.Union measurable_set.Inter measurable_set.Union_Prop measurable_set.Inter_Prop measurable_set.union measurable_set.inter measurable_set.diff measurable_set.symm_diff measurable_set.ite measurable_set.cond measurable_set.disjointed measurable_set.const measurable_set.insert measurable_set_eq set.finite.measurable_set finset.measurable_set set.countable.measurable_set measurable_space.measurable_set_top namespace tactic /-- Tactic to apply `measurable.comp` when appropriate. Applying `measurable.comp` is not always a good idea, so we have some extra logic here to try to avoid bad cases. * If the function we're trying to prove measurable is actually constant, and that constant is a function application `f z`, then measurable.comp would produce new goals `measurable f`, `measurable (Ξ» _, z)`, which is silly. We avoid this by failing if we could apply `measurable_const`. * measurable.comp will always succeed on `measurable (Ξ» x, f x)` and produce new goals `measurable (Ξ» x, x)`, `measurable f`. We detect this by failing if a new goal can be closed by applying measurable_id. -/ meta def apply_measurable.comp : tactic unit := `[fail_if_success { exact measurable_const }; refine measurable.comp _ _; fail_if_success { exact measurable_id }] /-- Tactic to apply `measurable.comp_ae_measurable` when appropriate. Applying `measurable.comp_ae_measurable` is not always a good idea, so we have some extra logic here to try to avoid bad cases. * If the function we're trying to prove measurable is actually constant, and that constant is a function application `f z`, then `measurable.comp_ae_measurable` would produce new goals `measurable f`, `ae_measurable (Ξ» _, z) ΞΌ`, which is silly. We avoid this by failing if we could apply `ae_measurable_const`. * `measurable.comp_ae_measurable` will always succeed on `ae_measurable (Ξ» x, f x) ΞΌ` and can produce new goals (`measurable (Ξ» x, x)`, `ae_measurable f ΞΌ`) or (`measurable f`, `ae_measurable (Ξ» x, x) ΞΌ`). We detect those by failing if a new goal can be closed by applying `measurable_id` or `ae_measurable_id`. -/ meta def apply_measurable.comp_ae_measurable : tactic unit := `[fail_if_success { exact ae_measurable_const }; refine measurable.comp_ae_measurable _ _; fail_if_success { exact measurable_id }; fail_if_success { exact ae_measurable_id }] /-- We don't want the intro1 tactic to apply to a goal of the form `measurable f`, `ae_measurable f ΞΌ` or `measurable_set s`. This tactic tests the target to see if it matches that form. -/ meta def goal_is_not_measurable : tactic unit := do t ← tactic.target, match t with | `(measurable %%l) := failed | `(ae_measurable %%l %%r) := failed | `(measurable_set %%l) := failed | _ := skip end /-- List of tactics used by `measurability` internally. -/ meta def measurability_tactics (md : transparency := semireducible) : list (tactic string) := [ propositional_goal >> apply_assumption >> pure "apply_assumption", goal_is_not_measurable >> intro1 >>= Ξ» ns, pure ("intro " ++ ns.to_string), apply_rules [] [``measurability] 50 { md := md } >> pure "apply_rules with measurability", apply_measurable.comp >> pure "refine measurable.comp _ _", apply_measurable.comp_ae_measurable >> pure "refine measurable.comp_ae_measurable _ _", `[ refine measurable.ae_measurable _ ] >> pure "refine measurable.ae_measurable _", `[ refine measurable.ae_strongly_measurable _ ] >> pure "refine measurable.ae_strongly_measurable _" ] namespace interactive setup_tactic_parser /-- Solve goals of the form `measurable f`, `ae_measurable f ΞΌ`, `ae_strongly_measurable f ΞΌ` or `measurable_set s`. `measurability?` reports back the proof term it found. -/ meta def measurability (bang : parse $ optional (tk "!")) (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) : tactic unit := let md := if bang.is_some then semireducible else reducible, measurability_core := tactic.tidy { tactics := measurability_tactics md, ..cfg }, trace_fn := if trace.is_some then show_term else id in trace_fn measurability_core /-- Version of `measurability` for use with auto_param. -/ meta def measurability' : tactic unit := measurability none none {} /-- `measurability` solves goals of the form `measurable f`, `ae_measurable f ΞΌ`, `ae_strongly_measurable f ΞΌ` or `measurable_set s` by applying lemmas tagged with the `measurability` user attribute. You can also use `measurability!`, which applies lemmas with `{ md := semireducible }`. The default behaviour is more conservative, and only unfolds `reducible` definitions when attempting to match lemmas with the goal. `measurability?` reports back the proof term it found. -/ add_tactic_doc { name := "measurability / measurability'", category := doc_category.tactic, decl_names := [`tactic.interactive.measurability, `tactic.interactive.measurability'], tags := ["lemma application"] } end interactive end tactic
642e27e81fb8f7edacc1b5e7acdd7bebf197b97f
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/topology/uniform_space/abstract_completion.lean
96d09c238efb6751fc7c9913c31698e193a65532
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
11,192
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.uniform_embedding /-! # Abstract theory of Hausdorff completions of uniform spaces This file characterizes Hausdorff completions of a uniform space Ξ± as complete Hausdorff spaces equipped with a map from Ξ± which has dense image and induce the original uniform structure on Ξ±. Assuming these properties we "extend" uniformly continuous maps from Ξ± to complete Hausdorff spaces to the completions of Ξ±. This is the universal property expected from a completion. It is then used to extend uniformly continuous maps from Ξ± to Ξ±' to maps between completions of Ξ± and Ξ±'. This file does not construct any such completion, it only study consequences of their existence. The first advantage is that formal properties are clearly highlighted without interference from construction details. The second advantage is that this framework can then be used to compare different completion constructions. See `topology/uniform_space/compare_reals` for an example. Of course the comparison comes from the universal property as usual. A general explicit construction of completions is done in `uniform_space/completion`, leading to a functor from uniform spaces to complete Hausdorff uniform spaces that is left adjoint to the inclusion, see `uniform_space/UniformSpace` for the category packaging. ## Implementation notes A tiny technical advantage of using a characteristic predicate such as the properties listed in `abstract_completion` instead of stating the universal property is that the universal property derived from the predicate is more universe polymorphic. ## References We don't know any traditional text discussing this. Real world mathematics simply silently identify the results of any two constructions that lead to something one could reasonnably call a completion. ## Tags uniform spaces, completion, universal property -/ noncomputable theory local attribute [instance, priority 10] classical.prop_decidable open filter set function universes u /-- A completion of `Ξ±` is the data of a complete separated uniform space (from the same universe) and a map from `Ξ±` with dense range and inducing the original uniform structure on `Ξ±`. -/ structure abstract_completion (Ξ± : Type u) [uniform_space Ξ±] := (space : Type u) (coe : Ξ± β†’ space) (uniform_struct : uniform_space space) (complete : complete_space space) (separation : separated_space space) (uniform_inducing : uniform_inducing coe) (dense : dense_range coe) local attribute [instance] abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation namespace abstract_completion variables {Ξ± : Type*} [uniform_space Ξ±] (pkg : abstract_completion Ξ±) local notation `hatΞ±` := pkg.space local notation `ΞΉ` := pkg.coe lemma dense' : closure (range ΞΉ) = univ := pkg.dense.closure_range lemma dense_inducing : dense_inducing ΞΉ := ⟨pkg.uniform_inducing.inducing, pkg.dense⟩ lemma uniform_continuous_coe : uniform_continuous ΞΉ := uniform_inducing.uniform_continuous pkg.uniform_inducing lemma continuous_coe : continuous ΞΉ := pkg.uniform_continuous_coe.continuous @[elab_as_eliminator] lemma induction_on {p : hatΞ± β†’ Prop} (a : hatΞ±) (hp : is_closed {a | p a}) (ih : βˆ€ a, p (ΞΉ a)) : p a := is_closed_property pkg.dense hp ih a variables {Ξ² : Type*} [uniform_space Ξ²] protected lemma funext [t2_space Ξ²] {f g : hatΞ± β†’ Ξ²} (hf : continuous f) (hg : continuous g) (h : βˆ€ a, f (ΞΉ a) = g (ΞΉ a)) : f = g := funext $ assume a, pkg.induction_on a (is_closed_eq hf hg) h section extend /-- Extension of maps to completions -/ protected def extend (f : Ξ± β†’ Ξ²) : hatΞ± β†’ Ξ² := if uniform_continuous f then pkg.dense_inducing.extend f else Ξ» x, f (classical.inhabited_of_nonempty $ pkg.dense.nonempty.2 ⟨x⟩).default variables {f : Ξ± β†’ Ξ²} lemma extend_def (hf : uniform_continuous f) : pkg.extend f = pkg.dense_inducing.extend f := if_pos hf lemma extend_coe [t2_space Ξ²] (hf : uniform_continuous f) (a : Ξ±) : (pkg.extend f) (ΞΉ a) = f a := begin rw pkg.extend_def hf, exact pkg.dense_inducing.extend_eq_of_cont hf.continuous a end variables [complete_space Ξ²] [separated_space Ξ²] lemma uniform_continuous_extend : uniform_continuous (pkg.extend f) := begin by_cases hf : uniform_continuous f, { rw pkg.extend_def hf, exact uniform_continuous_uniformly_extend (pkg.uniform_inducing) (pkg.dense) hf }, { change uniform_continuous (ite _ _ _), rw if_neg hf, exact uniform_continuous_of_const (assume a b, by congr) } end lemma continuous_extend : continuous (pkg.extend f) := pkg.uniform_continuous_extend.continuous lemma extend_unique (hf : uniform_continuous f) {g : hatΞ± β†’ Ξ²} (hg : uniform_continuous g) (h : βˆ€ a : Ξ±, f a = g (ΞΉ a)) : pkg.extend f = g := begin apply pkg.funext pkg.continuous_extend hg.continuous, simpa only [pkg.extend_coe hf] using h end @[simp] lemma extend_comp_coe {f : hatΞ± β†’ Ξ²} (hf : uniform_continuous f) : pkg.extend (f ∘ ΞΉ) = f := funext $ Ξ» x, pkg.induction_on x (is_closed_eq pkg.continuous_extend hf.continuous) (Ξ» y, pkg.extend_coe (hf.comp $ pkg.uniform_continuous_coe) y) end extend section map_sec variables (pkg' : abstract_completion Ξ²) local notation `hatΞ²` := pkg'.space local notation `ΞΉ'` := pkg'.coe /-- Lifting maps to completions -/ protected def map (f : Ξ± β†’ Ξ²) : hatΞ± β†’ hatΞ² := pkg.extend (ΞΉ' ∘ f) local notation `map` := pkg.map pkg' variables (f : Ξ± β†’ Ξ²) lemma uniform_continuous_map : uniform_continuous (map f) := pkg.uniform_continuous_extend lemma continuous_map : continuous (map f) := pkg.continuous_extend variables {f} @[simp] lemma map_coe (hf : uniform_continuous f) (a : Ξ±) : map f (ΞΉ a) = ΞΉ' (f a) := pkg.extend_coe (pkg'.uniform_continuous_coe.comp hf) a lemma map_unique {f : Ξ± β†’ Ξ²} {g : hatΞ± β†’ hatΞ²} (hg : uniform_continuous g) (h : βˆ€ a, ΞΉ' (f a) = g (ΞΉ a)) : map f = g := pkg.funext (pkg.continuous_map _ _) hg.continuous $ begin intro a, change pkg.extend (ΞΉ' ∘ f) _ = _, simp only [(∘), h], rw [pkg.extend_coe (hg.comp pkg.uniform_continuous_coe)] end @[simp] lemma map_id : pkg.map pkg id = id := pkg.map_unique pkg uniform_continuous_id (assume a, rfl) variables {Ξ³ : Type*} [uniform_space Ξ³] lemma extend_map [complete_space Ξ³] [separated_space Ξ³] {f : Ξ² β†’ Ξ³} {g : Ξ± β†’ Ξ²} (hf : uniform_continuous f) (hg : uniform_continuous g) : pkg'.extend f ∘ map g = pkg.extend (f ∘ g) := pkg.funext (pkg'.continuous_extend.comp (pkg.continuous_map pkg' _)) pkg.continuous_extend $ Ξ» a, by rw [pkg.extend_coe (hf.comp hg), comp_app, pkg.map_coe pkg' hg, pkg'.extend_coe hf] variables (pkg'' : abstract_completion Ξ³) lemma map_comp {g : Ξ² β†’ Ξ³} {f : Ξ± β†’ Ξ²} (hg : uniform_continuous g) (hf : uniform_continuous f) : (pkg'.map pkg'' g) ∘ (pkg.map pkg' f) = pkg.map pkg'' (g ∘ f) := pkg.extend_map pkg' (pkg''.uniform_continuous_coe.comp hg) hf end map_sec section compare -- We can now compare two completion packages for the same uniform space variables (pkg' : abstract_completion Ξ±) /-- The comparison map between two completions of the same uniform space. -/ def compare : pkg.space β†’ pkg'.space := pkg.extend pkg'.coe lemma uniform_continuous_compare : uniform_continuous (pkg.compare pkg') := pkg.uniform_continuous_extend lemma compare_coe (a : Ξ±) : pkg.compare pkg' (pkg.coe a) = pkg'.coe a := pkg.extend_coe pkg'.uniform_continuous_coe a lemma inverse_compare : (pkg.compare pkg') ∘ (pkg'.compare pkg) = id := begin have uc := pkg.uniform_continuous_compare pkg', have uc' := pkg'.uniform_continuous_compare pkg, apply pkg'.funext (uc.comp uc').continuous continuous_id, intro a, rw [comp_app, pkg'.compare_coe pkg, pkg.compare_coe pkg'], refl end /-- The bijection between two completions of the same uniform space. -/ def compare_equiv : pkg.space ≃ pkg'.space := { to_fun := pkg.compare pkg', inv_fun := pkg'.compare pkg, left_inv := congr_fun (pkg'.inverse_compare pkg), right_inv := congr_fun (pkg.inverse_compare pkg') } lemma uniform_continuous_compare_equiv : uniform_continuous (pkg.compare_equiv pkg') := pkg.uniform_continuous_compare pkg' lemma uniform_continuous_compare_equiv_symm : uniform_continuous (pkg.compare_equiv pkg').symm := pkg'.uniform_continuous_compare pkg end compare section prod variables (pkg' : abstract_completion Ξ²) local notation `hatΞ²` := pkg'.space local notation `ΞΉ'` := pkg'.coe /-- Products of completions -/ protected def prod : abstract_completion (Ξ± Γ— Ξ²) := { space := hatΞ± Γ— hatΞ², coe := Ξ» p, ⟨ι p.1, ΞΉ' p.2⟩, uniform_struct := prod.uniform_space, complete := by apply_instance, separation := by apply_instance, uniform_inducing := uniform_inducing.prod pkg.uniform_inducing pkg'.uniform_inducing, dense := pkg.dense.prod pkg'.dense } end prod section extensionβ‚‚ variables (pkg' : abstract_completion Ξ²) local notation `hatΞ²` := pkg'.space local notation `ΞΉ'` := pkg'.coe variables {Ξ³ : Type*} [uniform_space Ξ³] open function /-- Extend two variable map to completions. -/ protected def extendβ‚‚ (f : Ξ± β†’ Ξ² β†’ Ξ³) : hatΞ± β†’ hatΞ² β†’ Ξ³ := curry $ (pkg.prod pkg').extend (uncurry f) variables [separated_space Ξ³] {f : Ξ± β†’ Ξ² β†’ Ξ³} lemma extensionβ‚‚_coe_coe (hf : uniform_continuous $ uncurry f) (a : Ξ±) (b : Ξ²) : pkg.extendβ‚‚ pkg' f (ΞΉ a) (ΞΉ' b) = f a b := show (pkg.prod pkg').extend (uncurry f) ((pkg.prod pkg').coe (a, b)) = uncurry f (a, b), from (pkg.prod pkg').extend_coe hf _ variables [complete_space Ξ³] (f) lemma uniform_continuous_extensionβ‚‚ : uniform_continuousβ‚‚ (pkg.extendβ‚‚ pkg' f) := begin rw [uniform_continuousβ‚‚_def, abstract_completion.extendβ‚‚, uncurry_curry], apply uniform_continuous_extend end end extensionβ‚‚ section mapβ‚‚ variables (pkg' : abstract_completion Ξ²) local notation `hatΞ²` := pkg'.space local notation `ΞΉ'` := pkg'.coe variables {Ξ³ : Type*} [uniform_space Ξ³] (pkg'' : abstract_completion Ξ³) local notation `hatΞ³` := pkg''.space local notation `ΞΉ''` := pkg''.coe local notation f `βˆ˜β‚‚` g := bicompr f g /-- Lift two variable maps to completions. -/ protected def mapβ‚‚ (f : Ξ± β†’ Ξ² β†’ Ξ³) : hatΞ± β†’ hatΞ² β†’ hatΞ³ := pkg.extendβ‚‚ pkg' (pkg''.coe βˆ˜β‚‚ f) lemma uniform_continuous_mapβ‚‚ (f : Ξ± β†’ Ξ² β†’ Ξ³) : uniform_continuousβ‚‚ (pkg.mapβ‚‚ pkg' pkg'' f) := pkg.uniform_continuous_extensionβ‚‚ pkg' _ lemma continuous_mapβ‚‚ {Ξ΄} [topological_space Ξ΄] {f : Ξ± β†’ Ξ² β†’ Ξ³} {a : Ξ΄ β†’ hatΞ±} {b : Ξ΄ β†’ hatΞ²} (ha : continuous a) (hb : continuous b) : continuous (Ξ»d:Ξ΄, pkg.mapβ‚‚ pkg' pkg'' f (a d) (b d)) := ((pkg.uniform_continuous_mapβ‚‚ pkg' pkg'' f).continuous.comp (continuous.prod_mk ha hb) : _) lemma mapβ‚‚_coe_coe (a : Ξ±) (b : Ξ²) (f : Ξ± β†’ Ξ² β†’ Ξ³) (hf : uniform_continuousβ‚‚ f) : pkg.mapβ‚‚ pkg' pkg'' f (ΞΉ a) (ΞΉ' b) = ΞΉ'' (f a b) := pkg.extensionβ‚‚_coe_coe pkg' (pkg''.uniform_continuous_coe.comp hf) a b end mapβ‚‚ end abstract_completion
25efb86d4f4e5af4318ac55b704354b368887da8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/field_theory/intermediate_field.lean
5908a0709bfedc1352ed7894ba8b6f4b66512fc8
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
21,916
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.minpoly import field_theory.subfield import field_theory.tower /-! # Intermediate fields Let `L / K` be a field extension, given as an instance `algebra K L`. This file defines the type of fields in between `K` and `L`, `intermediate_field K L`. An `intermediate_field K L` is a subfield of `L` which contains (the image of) `K`, i.e. it is a `subfield L` and a `subalgebra K L`. ## Main definitions * `intermediate_field K L` : the type of intermediate fields between `K` and `L`. * `subalgebra.to_intermediate_field`: turns a subalgebra closed under `⁻¹` into an intermediate field * `subfield.to_intermediate_field`: turns a subfield containing the image of `K` into an intermediate field * `intermediate_field.map`: map an intermediate field along an `alg_hom` * `intermediate_field.restrict_scalars`: restrict the scalars of an intermediate field to a smaller field in a tower of fields. ## Implementation notes Intermediate fields are defined with a structure extending `subfield` and `subalgebra`. A `subalgebra` is closed under all operations except `⁻¹`, ## Tags intermediate field, field extension -/ open finite_dimensional polynomial open_locale big_operators polynomial variables (K L L' : Type*) [field K] [field L] [field L'] [algebra K L] [algebra K L'] /-- `S : intermediate_field K L` is a subset of `L` such that there is a field tower `L / S / K`. -/ structure intermediate_field extends subalgebra K L := (neg_mem' : βˆ€ x ∈ carrier, -x ∈ carrier) (inv_mem' : βˆ€ x ∈ carrier, x⁻¹ ∈ carrier) /-- Reinterpret an `intermediate_field` as a `subalgebra`. -/ add_decl_doc intermediate_field.to_subalgebra variables {K L L'} (S : intermediate_field K L) namespace intermediate_field /-- Reinterpret an `intermediate_field` as a `subfield`. -/ def to_subfield : subfield L := { ..S.to_subalgebra, ..S } instance : set_like (intermediate_field K L) L := ⟨λ S, S.to_subalgebra.carrier, by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨h⟩, congr, }⟩ instance : subfield_class (intermediate_field K L) L := { add_mem := Ξ» s _ _, s.add_mem', zero_mem := Ξ» s, s.zero_mem', neg_mem := neg_mem', mul_mem := Ξ» s _ _, s.mul_mem', one_mem := Ξ» s, s.one_mem', inv_mem := inv_mem' } @[simp] lemma mem_carrier {s : intermediate_field K L} {x : L} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two intermediate fields are equal if they have the same elements. -/ @[ext] theorem ext {S T : intermediate_field K L} (h : βˆ€ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h @[simp] lemma coe_to_subalgebra : (S.to_subalgebra : set L) = S := rfl @[simp] lemma coe_to_subfield : (S.to_subfield : set L) = S := rfl @[simp] lemma mem_mk (s : set L) (hK : βˆ€ x, algebra_map K L x ∈ s) (ho hm hz ha hn hi) (x : L) : x ∈ intermediate_field.mk (subalgebra.mk s ho hm hz ha hK) hn hi ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subalgebra (s : intermediate_field K L) (x : L) : x ∈ s.to_subalgebra ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subfield (s : intermediate_field K L) (x : L) : x ∈ s.to_subfield ↔ x ∈ s := iff.rfl /-- Copy of an intermediate field with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : intermediate_field K L) (s : set L) (hs : s = ↑S) : intermediate_field K L := { to_subalgebra := S.to_subalgebra.copy s (hs : s = (S.to_subalgebra).carrier), neg_mem' := have hs' : (S.to_subalgebra.copy s hs).carrier = (S.to_subalgebra).carrier := hs, hs'.symm β–Έ S.neg_mem', inv_mem' := have hs' : (S.to_subalgebra.copy s hs).carrier = (S.to_subalgebra).carrier := hs, hs'.symm β–Έ S.inv_mem' } @[simp] lemma coe_copy (S : intermediate_field K L) (s : set L) (hs : s = ↑S) : (S.copy s hs : set L) = s := rfl lemma copy_eq (S : intermediate_field K L) (s : set L) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs section inherited_lemmas /-! ### Lemmas inherited from more general structures The declarations in this section derive from the fact that an `intermediate_field` is also a subalgebra or subfield. Their use should be replaceable with the corresponding lemma from a subobject class. -/ /-- An intermediate field contains the image of the smaller field. -/ theorem algebra_map_mem (x : K) : algebra_map K L x ∈ S := S.algebra_map_mem' x /-- An intermediate field is closed under scalar multiplication. -/ theorem smul_mem {y : L} : y ∈ S β†’ βˆ€ {x : K}, x β€’ y ∈ S := S.to_subalgebra.smul_mem /-- An intermediate field contains the ring's 1. -/ protected theorem one_mem : (1 : L) ∈ S := one_mem S /-- An intermediate field contains the ring's 0. -/ protected theorem zero_mem : (0 : L) ∈ S := zero_mem S /-- An intermediate field is closed under multiplication. -/ protected theorem mul_mem {x y : L} : x ∈ S β†’ y ∈ S β†’ x * y ∈ S := mul_mem /-- An intermediate field is closed under addition. -/ protected theorem add_mem {x y : L} : x ∈ S β†’ y ∈ S β†’ x + y ∈ S := add_mem /-- An intermediate field is closed under subtraction -/ protected theorem sub_mem {x y : L} : x ∈ S β†’ y ∈ S β†’ x - y ∈ S := sub_mem /-- An intermediate field is closed under negation. -/ protected theorem neg_mem {x : L} : x ∈ S β†’ -x ∈ S := neg_mem /-- An intermediate field is closed under inverses. -/ protected theorem inv_mem {x : L} : x ∈ S β†’ x⁻¹ ∈ S := inv_mem /-- An intermediate field is closed under division. -/ protected theorem div_mem {x y : L} : x ∈ S β†’ y ∈ S β†’ x / y ∈ S := div_mem /-- Product of a list of elements in an intermediate_field is in the intermediate_field. -/ protected lemma list_prod_mem {l : list L} : (βˆ€ x ∈ l, x ∈ S) β†’ l.prod ∈ S := list_prod_mem /-- Sum of a list of elements in an intermediate field is in the intermediate_field. -/ protected lemma list_sum_mem {l : list L} : (βˆ€ x ∈ l, x ∈ S) β†’ l.sum ∈ S := list_sum_mem /-- Product of a multiset of elements in an intermediate field is in the intermediate_field. -/ protected lemma multiset_prod_mem (m : multiset L) : (βˆ€ a ∈ m, a ∈ S) β†’ m.prod ∈ S := multiset_prod_mem m /-- Sum of a multiset of elements in a `intermediate_field` is in the `intermediate_field`. -/ protected lemma multiset_sum_mem (m : multiset L) : (βˆ€ a ∈ m, a ∈ S) β†’ m.sum ∈ S := multiset_sum_mem m /-- Product of elements of an intermediate field indexed by a `finset` is in the intermediate_field. -/ protected lemma prod_mem {ΞΉ : Type*} {t : finset ΞΉ} {f : ΞΉ β†’ L} (h : βˆ€ c ∈ t, f c ∈ S) : ∏ i in t, f i ∈ S := prod_mem h /-- Sum of elements in a `intermediate_field` indexed by a `finset` is in the `intermediate_field`. -/ protected lemma sum_mem {ΞΉ : Type*} {t : finset ΞΉ} {f : ΞΉ β†’ L} (h : βˆ€ c ∈ t, f c ∈ S) : βˆ‘ i in t, f i ∈ S := sum_mem h protected lemma pow_mem {x : L} (hx : x ∈ S) (n : β„€) : x^n ∈ S := zpow_mem hx n protected lemma zsmul_mem {x : L} (hx : x ∈ S) (n : β„€) : n β€’ x ∈ S := zsmul_mem hx n protected lemma coe_int_mem (n : β„€) : (n : L) ∈ S := coe_int_mem S n protected lemma coe_add (x y : S) : (↑(x + y) : L) = ↑x + ↑y := rfl protected lemma coe_neg (x : S) : (↑(-x) : L) = -↑x := rfl protected lemma coe_mul (x y : S) : (↑(x * y) : L) = ↑x * ↑y := rfl protected lemma coe_inv (x : S) : (↑(x⁻¹) : L) = (↑x)⁻¹ := rfl protected lemma coe_zero : ((0 : S) : L) = 0 := rfl protected lemma coe_one : ((1 : S) : L) = 1 := rfl protected lemma coe_pow (x : S) (n : β„•) : (↑(x ^ n) : L) = ↑x ^ n := submonoid_class.coe_pow x n end inherited_lemmas lemma coe_nat_mem (n : β„•) : (n : L) ∈ S := by simpa using coe_int_mem S n end intermediate_field /-- Turn a subalgebra closed under inverses into an intermediate field -/ def subalgebra.to_intermediate_field (S : subalgebra K L) (inv_mem : βˆ€ x ∈ S, x⁻¹ ∈ S) : intermediate_field K L := { neg_mem' := Ξ» x, S.neg_mem, inv_mem' := inv_mem, .. S } @[simp] lemma to_subalgebra_to_intermediate_field (S : subalgebra K L) (inv_mem : βˆ€ x ∈ S, x⁻¹ ∈ S) : (S.to_intermediate_field inv_mem).to_subalgebra = S := by { ext, refl } @[simp] lemma to_intermediate_field_to_subalgebra (S : intermediate_field K L) : S.to_subalgebra.to_intermediate_field (Ξ» x, S.inv_mem) = S := by { ext, refl } /-- Turn a subalgebra satisfying `is_field` into an intermediate_field -/ def subalgebra.to_intermediate_field' (S : subalgebra K L) (hS : is_field S) : intermediate_field K L := S.to_intermediate_field $ Ξ» x hx, begin by_cases hx0 : x = 0, { rw [hx0, inv_zero], exact S.zero_mem }, letI hS' := hS.to_field, obtain ⟨y, hy⟩ := hS.mul_inv_cancel (show (⟨x, hx⟩ : S) β‰  0, from subtype.ne_of_val_ne hx0), rw [subtype.ext_iff, S.coe_mul, S.coe_one, subtype.coe_mk, mul_eq_one_iff_inv_eqβ‚€ hx0] at hy, exact hy.symm β–Έ y.2, end @[simp] lemma to_subalgebra_to_intermediate_field' (S : subalgebra K L) (hS : is_field S) : (S.to_intermediate_field' hS).to_subalgebra = S := by { ext, refl } @[simp] lemma to_intermediate_field'_to_subalgebra (S : intermediate_field K L) : S.to_subalgebra.to_intermediate_field' (field.to_is_field S) = S := by { ext, refl } /-- Turn a subfield of `L` containing the image of `K` into an intermediate field -/ def subfield.to_intermediate_field (S : subfield L) (algebra_map_mem : βˆ€ x, algebra_map K L x ∈ S) : intermediate_field K L := { algebra_map_mem' := algebra_map_mem, .. S } namespace intermediate_field /-- An intermediate field inherits a field structure -/ instance to_field : field S := S.to_subfield.to_field @[simp, norm_cast] lemma coe_sum {ΞΉ : Type*} [fintype ΞΉ] (f : ΞΉ β†’ S) : (β†‘βˆ‘ i, f i : L) = βˆ‘ i, (f i : L) := begin classical, induction finset.univ using finset.induction_on with i s hi H, { simp }, { rw [finset.sum_insert hi, add_mem_class.coe_add, H, finset.sum_insert hi] } end @[simp, norm_cast] lemma coe_prod {ΞΉ : Type*} [fintype ΞΉ] (f : ΞΉ β†’ S) : (β†‘βˆ i, f i : L) = ∏ i, (f i : L) := begin classical, induction finset.univ using finset.induction_on with i s hi H, { simp }, { rw [finset.prod_insert hi, mul_mem_class.coe_mul, H, finset.prod_insert hi] } end /-! `intermediate_field`s inherit structure from their `subalgebra` coercions. -/ instance module' {R} [semiring R] [has_smul R K] [module R L] [is_scalar_tower R K L] : module R S := S.to_subalgebra.module' instance module : module K S := S.to_subalgebra.module instance is_scalar_tower {R} [semiring R] [has_smul R K] [module R L] [is_scalar_tower R K L] : is_scalar_tower R K S := S.to_subalgebra.is_scalar_tower @[simp] lemma coe_smul {R} [semiring R] [has_smul R K] [module R L] [is_scalar_tower R K L] (r : R) (x : S) : ↑(r β€’ x) = (r β€’ x : L) := rfl instance algebra' {K'} [comm_semiring K'] [has_smul K' K] [algebra K' L] [is_scalar_tower K' K L] : algebra K' S := S.to_subalgebra.algebra' instance algebra : algebra K S := S.to_subalgebra.algebra instance to_algebra {R : Type*} [semiring R] [algebra L R] : algebra S R := S.to_subalgebra.to_algebra instance is_scalar_tower_bot {R : Type*} [semiring R] [algebra L R] : is_scalar_tower S L R := is_scalar_tower.subalgebra _ _ _ S.to_subalgebra instance is_scalar_tower_mid {R : Type*} [semiring R] [algebra L R] [algebra K R] [is_scalar_tower K L R] : is_scalar_tower K S R := is_scalar_tower.subalgebra' _ _ _ S.to_subalgebra /-- Specialize `is_scalar_tower_mid` to the common case where the top field is `L` -/ instance is_scalar_tower_mid' : is_scalar_tower K S L := S.is_scalar_tower_mid /-- If `f : L β†’+* L'` fixes `K`, `S.map f` is the intermediate field between `L'` and `K` such that `x ∈ S ↔ f x ∈ S.map f`. -/ def map (f : L →ₐ[K] L') (S : intermediate_field K L) : intermediate_field K L' := { inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, S.inv_mem hx, map_invβ‚€ f x⟩ }, neg_mem' := Ξ» x hx, (S.to_subalgebra.map f).neg_mem hx, .. S.to_subalgebra.map f} @[simp] lemma coe_map (f : L →ₐ[K] L') : (S.map f : set L') = f '' S := rfl lemma map_map {K L₁ Lβ‚‚ L₃ : Type*} [field K] [field L₁] [algebra K L₁] [field Lβ‚‚] [algebra K Lβ‚‚] [field L₃] [algebra K L₃] (E : intermediate_field K L₁) (f : L₁ →ₐ[K] Lβ‚‚) (g : Lβ‚‚ →ₐ[K] L₃) : (E.map f).map g = E.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ /-- Given an equivalence `e : L ≃ₐ[K] L'` of `K`-field extensions and an intermediate field `E` of `L/K`, `intermediate_field_equiv_map e E` is the induced equivalence between `E` and `E.map e` -/ def intermediate_field_map (e : L ≃ₐ[K] L') (E : intermediate_field K L) : E ≃ₐ[K] (E.map e.to_alg_hom) := e.subalgebra_map E.to_subalgebra /- We manually add these two simp lemmas because `@[simps]` before `intermediate_field_map` led to a timeout. -/ @[simp] lemma intermediate_field_map_apply_coe (e : L ≃ₐ[K] L') (E : intermediate_field K L) (a : E) : ↑(intermediate_field_map e E a) = e a := rfl @[simp] lemma intermediate_field_map_symm_apply_coe (e : L ≃ₐ[K] L') (E : intermediate_field K L) (a : E.map e.to_alg_hom) : ↑((intermediate_field_map e E).symm a) = e.symm a := rfl end intermediate_field namespace alg_hom variables (f : L →ₐ[K] L') /-- The range of an algebra homomorphism, as an intermediate field. -/ @[simps to_subalgebra] def field_range : intermediate_field K L' := { .. f.range, .. (f : L β†’+* L').field_range } @[simp] lemma coe_field_range : ↑f.field_range = set.range f := rfl @[simp] lemma field_range_to_subfield : f.field_range.to_subfield = (f : L β†’+* L').field_range := rfl variables {f} @[simp] lemma mem_field_range {y : L'} : y ∈ f.field_range ↔ βˆƒ x, f x = y := iff.rfl end alg_hom namespace intermediate_field /-- The embedding from an intermediate field of `L / K` to `L`. -/ def val : S →ₐ[K] L := S.to_subalgebra.val @[simp] theorem coe_val : ⇑S.val = coe := rfl @[simp] lemma val_mk {x : L} (hx : x ∈ S) : S.val ⟨x, hx⟩ = x := rfl lemma range_val : S.val.range = S.to_subalgebra := S.to_subalgebra.range_val lemma aeval_coe {R : Type*} [comm_ring R] [algebra R K] [algebra R L] [is_scalar_tower R K L] (x : S) (P : R[X]) : aeval (x : L) P = aeval x P := begin refine polynomial.induction_on' P (Ξ» f g hf hg, _) (Ξ» n r, _), { rw [aeval_add, aeval_add, add_mem_class.coe_add, hf, hg] }, { simp only [mul_mem_class.coe_mul, aeval_monomial, submonoid_class.coe_pow, mul_eq_mul_right_iff], left, refl } end lemma coe_is_integral_iff {R : Type*} [comm_ring R] [algebra R K] [algebra R L] [is_scalar_tower R K L] {x : S} : is_integral R (x : L) ↔ _root_.is_integral R x := begin refine ⟨λ h, _, Ξ» h, _⟩, { obtain ⟨P, hPmo, hProot⟩ := h, refine ⟨P, hPmo, (injective_iff_map_eq_zero _).1 (algebra_map β†₯S L).injective _ _⟩, letI : is_scalar_tower R S L := is_scalar_tower.of_algebra_map_eq (congr_fun rfl), rwa [evalβ‚‚_eq_eval_map, ← evalβ‚‚_at_apply, evalβ‚‚_eq_eval_map, polynomial.map_map, ← is_scalar_tower.algebra_map_eq, ← evalβ‚‚_eq_eval_map] }, { obtain ⟨P, hPmo, hProot⟩ := h, refine ⟨P, hPmo, _⟩, rw [← aeval_def, aeval_coe, aeval_def, hProot, zero_mem_class.coe_zero] }, end /-- The map `E β†’ F` when `E` is an intermediate field contained in the intermediate field `F`. This is the intermediate field version of `subalgebra.inclusion`. -/ def inclusion {E F : intermediate_field K L} (hEF : E ≀ F) : E →ₐ[K] F := subalgebra.inclusion hEF lemma inclusion_injective {E F : intermediate_field K L} (hEF : E ≀ F) : function.injective (inclusion hEF) := subalgebra.inclusion_injective hEF @[simp] lemma inclusion_self {E : intermediate_field K L}: inclusion (le_refl E) = alg_hom.id K E := subalgebra.inclusion_self @[simp] lemma inclusion_inclusion {E F G : intermediate_field K L} (hEF : E ≀ F) (hFG : F ≀ G) (x : E) : inclusion hFG (inclusion hEF x) = inclusion (le_trans hEF hFG) x := subalgebra.inclusion_inclusion hEF hFG x @[simp] lemma coe_inclusion {E F : intermediate_field K L} (hEF : E ≀ F) (e : E) : (inclusion hEF e : L) = e := rfl variables {S} lemma to_subalgebra_injective {S S' : intermediate_field K L} (h : S.to_subalgebra = S'.to_subalgebra) : S = S' := by { ext, rw [← mem_to_subalgebra, ← mem_to_subalgebra, h] } variables (S) lemma set_range_subset : set.range (algebra_map K L) βŠ† S := S.to_subalgebra.range_subset lemma field_range_le : (algebra_map K L).field_range ≀ S.to_subfield := Ξ» x hx, S.to_subalgebra.range_subset (by rwa [set.mem_range, ← ring_hom.mem_field_range]) @[simp] lemma to_subalgebra_le_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra ≀ S'.to_subalgebra ↔ S ≀ S' := iff.rfl @[simp] lemma to_subalgebra_lt_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra < S'.to_subalgebra ↔ S < S' := iff.rfl variables {S} section tower /-- Lift an intermediate_field of an intermediate_field -/ def lift {F : intermediate_field K L} (E : intermediate_field K F) : intermediate_field K L := E.map (val F) instance has_lift {F : intermediate_field K L} : has_lift_t (intermediate_field K F) (intermediate_field K L) := ⟨lift⟩ section restrict_scalars variables (K) [algebra L' L] [is_scalar_tower K L' L] /-- Given a tower `L / β†₯E / L' / K` of field extensions, where `E` is an `L'`-intermediate field of `L`, reinterpret `E` as a `K`-intermediate field of `L`. -/ def restrict_scalars (E : intermediate_field L' L) : intermediate_field K L := { carrier := E.carrier, ..E.to_subfield, ..E.to_subalgebra.restrict_scalars K } @[simp] lemma coe_restrict_scalars {E : intermediate_field L' L} : (restrict_scalars K E : set L) = (E : set L) := rfl @[simp] lemma restrict_scalars_to_subalgebra {E : intermediate_field L' L} : (E.restrict_scalars K).to_subalgebra = E.to_subalgebra.restrict_scalars K := set_like.coe_injective rfl @[simp] lemma restrict_scalars_to_subfield {E : intermediate_field L' L} : (E.restrict_scalars K).to_subfield = E.to_subfield := set_like.coe_injective rfl @[simp] lemma mem_restrict_scalars {E : intermediate_field L' L} {x : L} : x ∈ restrict_scalars K E ↔ x ∈ E := iff.rfl lemma restrict_scalars_injective : function.injective (restrict_scalars K : intermediate_field L' L β†’ intermediate_field K L) := Ξ» U V H, ext $ Ξ» x, by rw [← mem_restrict_scalars K, H, mem_restrict_scalars] end restrict_scalars /-- This was formerly an instance called `lift2_alg`, but an instance above already provides it. -/ example {F : intermediate_field K L} {E : intermediate_field F L} : algebra K E := by apply_instance end tower section finite_dimensional variables (F E : intermediate_field K L) instance finite_dimensional_left [finite_dimensional K L] : finite_dimensional K F := left K F L instance finite_dimensional_right [finite_dimensional K L] : finite_dimensional F L := right K F L @[simp] lemma dim_eq_dim_subalgebra : module.rank K F.to_subalgebra = module.rank K F := rfl @[simp] lemma finrank_eq_finrank_subalgebra : finrank K F.to_subalgebra = finrank K F := rfl variables {F} {E} @[simp] lemma to_subalgebra_eq_iff : F.to_subalgebra = E.to_subalgebra ↔ F = E := by { rw [set_like.ext_iff, set_like.ext'_iff, set.ext_iff], refl } lemma eq_of_le_of_finrank_le [finite_dimensional K L] (h_le : F ≀ E) (h_finrank : finrank K E ≀ finrank K F) : F = E := to_subalgebra_injective $ subalgebra.to_submodule.injective $ eq_of_le_of_finrank_le h_le h_finrank lemma eq_of_le_of_finrank_eq [finite_dimensional K L] (h_le : F ≀ E) (h_finrank : finrank K F = finrank K E) : F = E := eq_of_le_of_finrank_le h_le h_finrank.ge lemma eq_of_le_of_finrank_le' [finite_dimensional K L] (h_le : F ≀ E) (h_finrank : finrank F L ≀ finrank E L) : F = E := begin apply eq_of_le_of_finrank_le h_le, have h1 := finrank_mul_finrank K F L, have h2 := finrank_mul_finrank K E L, have h3 : 0 < finrank E L := finrank_pos, nlinarith, end lemma eq_of_le_of_finrank_eq' [finite_dimensional K L] (h_le : F ≀ E) (h_finrank : finrank F L = finrank E L) : F = E := eq_of_le_of_finrank_le' h_le h_finrank.le end finite_dimensional lemma is_algebraic_iff {x : S} : is_algebraic K x ↔ is_algebraic K (x : L) := (is_algebraic_algebra_map_iff (algebra_map S L).injective).symm lemma is_integral_iff {x : S} : is_integral K x ↔ is_integral K (x : L) := by rw [←is_algebraic_iff_is_integral, is_algebraic_iff, is_algebraic_iff_is_integral] lemma minpoly_eq (x : S) : minpoly K x = minpoly K (x : L) := begin by_cases hx : is_integral K x, { exact minpoly.eq_of_algebra_map_eq (algebra_map S L).injective hx rfl }, { exact (minpoly.eq_zero hx).trans (minpoly.eq_zero (mt is_integral_iff.mpr hx)).symm }, end end intermediate_field /-- If `L/K` is algebraic, the `K`-subalgebras of `L` are all fields. -/ def subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) : subalgebra K L ≃o intermediate_field K L := { to_fun := Ξ» S, S.to_intermediate_field (Ξ» x hx, S.inv_mem_of_algebraic (alg (⟨x, hx⟩ : S))), inv_fun := Ξ» S, S.to_subalgebra, left_inv := Ξ» S, to_subalgebra_to_intermediate_field _ _, right_inv := to_intermediate_field_to_subalgebra, map_rel_iff' := Ξ» S S', iff.rfl } @[simp] lemma mem_subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) {S : subalgebra K L} {x : L} : x ∈ subalgebra_equiv_intermediate_field alg S ↔ x ∈ S := iff.rfl @[simp] lemma mem_subalgebra_equiv_intermediate_field_symm (alg : algebra.is_algebraic K L) {S : intermediate_field K L} {x : L} : x ∈ (subalgebra_equiv_intermediate_field alg).symm S ↔ x ∈ S := iff.rfl
eb532633ee545013ccc6a058e2d119d6fd11384a
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebraic_geometry/pullbacks.lean
4102594f7dae647990c50b721f4c39743f224421
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
24,215
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.gluing import category_theory.limits.opposites import algebraic_geometry.Gamma_Spec_adjunction /-! # Fibred products of schemes In this file we construct the fibred product of schemes via gluing. We roughly follow [har77] Theorem 3.3. In particular, the main construction is to show that for an open cover `{ Uα΅’ }` of `X`, if there exist fibred products `Uα΅’ Γ—[Z] Y` for each `i`, then there exists a fibred product `X Γ—[Z] Y`. Then, for constructing the fibred product for arbitrary schemes `X, Y, Z`, we can use the construction to reduce to the case where `X, Y, Z` are all affine, where fibred products are constructed via tensor products. -/ universes v u noncomputable theory open category_theory category_theory.limits algebraic_geometry namespace algebraic_geometry.Scheme namespace pullback variables {C : Type u} [category.{v} C] variables {X Y Z : Scheme.{u}} (𝒰 : open_cover.{u} X) (f : X ⟢ Z) (g : Y ⟢ Z) variables [βˆ€ i, has_pullback (𝒰.map i ≫ f) g] /-- The intersection of `Uα΅’ Γ—[Z] Y` and `Uβ±Ό Γ—[Z] Y` is given by (Uα΅’ Γ—[Z] Y) Γ—[X] Uβ±Ό -/ def V (i j : 𝒰.J) : Scheme := pullback ((pullback.fst : pullback ((𝒰.map i) ≫ f) g ⟢ _) ≫ (𝒰.map i)) (𝒰.map j) /-- The canonical transition map `(Uα΅’ Γ—[Z] Y) Γ—[X] Uβ±Ό ⟢ (Uβ±Ό Γ—[Z] Y) Γ—[X] Uα΅’` given by the fact that pullbacks are associative and symmetric. -/ def t (i j : 𝒰.J) : V 𝒰 f g i j ⟢ V 𝒰 f g j i := begin haveI : has_pullback (pullback.snd ≫ 𝒰.map i ≫ f) g := has_pullback_assoc_symm (𝒰.map j) (𝒰.map i) (𝒰.map i ≫ f) g, haveI : has_pullback (pullback.snd ≫ 𝒰.map j ≫ f) g := has_pullback_assoc_symm (𝒰.map i) (𝒰.map j) (𝒰.map j ≫ f) g, refine (pullback_symmetry _ _).hom ≫ _, refine (pullback_assoc _ _ _ _).inv ≫ _, change pullback _ _ ⟢ pullback _ _, refine _ ≫ (pullback_symmetry _ _).hom, refine _ ≫ (pullback_assoc _ _ _ _).hom, refine pullback.map _ _ _ _ (pullback_symmetry _ _).hom (πŸ™ _) (πŸ™ _) _ _, rw [pullback_symmetry_hom_comp_snd_assoc, pullback.condition_assoc, category.comp_id], rw [category.comp_id, category.id_comp] end @[simp, reassoc] lemma t_fst_fst (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.fst ≫ pullback.fst = pullback.snd := by { delta t, simp } @[simp, reassoc] lemma t_fst_snd (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.snd := by { delta t, simp } @[simp, reassoc] lemma t_snd (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.snd = pullback.fst ≫ pullback.fst := by { delta t, simp } lemma t_id (i : 𝒰.J) : t 𝒰 f g i i = πŸ™ _ := begin apply pullback.hom_ext; rw category.id_comp, apply pullback.hom_ext, { rw ← cancel_mono (𝒰.map i), simp [pullback.condition] }, { simp }, { rw ← cancel_mono (𝒰.map i), simp [pullback.condition] } end /-- The inclusion map of `V i j = (Uα΅’ Γ—[Z] Y) Γ—[X] Uβ±Ό ⟢ Uα΅’ Γ—[Z] Y`-/ abbreviation fV (i j : 𝒰.J) : V 𝒰 f g i j ⟢ pullback ((𝒰.map i) ≫ f) g := pullback.fst /-- The map `((Xα΅’ Γ—[Z] Y) Γ—[X] Xβ±Ό) Γ—[Xα΅’ Γ—[Z] Y] ((Xα΅’ Γ—[Z] Y) Γ—[X] Xβ‚–)` ⟢ `((Xβ±Ό Γ—[Z] Y) Γ—[X] Xβ‚–) Γ—[Xβ±Ό Γ—[Z] Y] ((Xβ±Ό Γ—[Z] Y) Γ—[X] Xα΅’)` needed for gluing -/ def t' (i j k : 𝒰.J) : pullback (fV 𝒰 f g i j) (fV 𝒰 f g i k) ⟢ pullback (fV 𝒰 f g j k) (fV 𝒰 f g j i) := begin refine (pullback_right_pullback_fst_iso _ _ _).hom ≫ _, refine _ ≫ (pullback_symmetry _ _).hom, refine _ ≫ (pullback_right_pullback_fst_iso _ _ _).inv, refine pullback.map _ _ _ _ (t 𝒰 f g i j) (πŸ™ _) (πŸ™ _) _ _, { simp [← pullback.condition] }, { simp } end section end @[simp, reassoc] lemma t'_fst_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.snd := by { delta t', simp } @[simp, reassoc] lemma t'_fst_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := by { delta t', simp } @[simp, reassoc] lemma t'_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.snd := by { delta t', simp } @[simp, reassoc] lemma t'_snd_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.snd := by { delta t', simp } @[simp, reassoc] lemma t'_snd_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := by { delta t', simp } @[simp, reassoc] lemma t'_snd_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.fst := by { delta t', simp, } lemma cocycle_fst_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.fst ≫ pullback.fst := by simp lemma cocycle_fst_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := by simp lemma cocycle_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.snd := by simp lemma cocycle_snd_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.fst ≫ pullback.fst = pullback.snd ≫ pullback.fst ≫ pullback.fst := by { rw ← cancel_mono (𝒰.map i), simp [pullback.condition_assoc, pullback.condition] } lemma cocycle_snd_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.fst ≫ pullback.snd := by { simp [pullback.condition_assoc, pullback.condition] } lemma cocycle_snd_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.snd = pullback.snd ≫ pullback.snd := by simp -- `by tidy` should solve it, but it times out. lemma cocycle (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j = πŸ™ _ := begin apply pullback.hom_ext; rw category.id_comp, { apply pullback.hom_ext, { apply pullback.hom_ext, { simp_rw category.assoc, exact cocycle_fst_fst_fst 𝒰 f g i j k }, { simp_rw category.assoc, exact cocycle_fst_fst_snd 𝒰 f g i j k } }, { simp_rw category.assoc, exact cocycle_fst_snd 𝒰 f g i j k } }, { apply pullback.hom_ext, { apply pullback.hom_ext, { simp_rw category.assoc, exact cocycle_snd_fst_fst 𝒰 f g i j k }, { simp_rw category.assoc, exact cocycle_snd_fst_snd 𝒰 f g i j k } }, { simp_rw category.assoc, exact cocycle_snd_snd 𝒰 f g i j k } } end /-- Given `Uα΅’ Γ—[Z] Y`, this is the glued fibered product `X Γ—[Z] Y`. -/ @[simps] def gluing : Scheme.glue_data.{u} := { J := 𝒰.J, U := Ξ» i, pullback ((𝒰.map i) ≫ f) g, V := Ξ» ⟨i, j⟩, V 𝒰 f g i j, -- `p⁻¹(Uα΅’ ∩ Uβ±Ό)` where `p : Uα΅’ Γ—[Z] Y ⟢ Uα΅’ ⟢ X`. f := Ξ» i j, pullback.fst, f_id := Ξ» i, infer_instance, f_open := infer_instance, t := Ξ» i j, t 𝒰 f g i j, t_id := Ξ» i, t_id 𝒰 f g i, t' := Ξ» i j k, t' 𝒰 f g i j k, t_fac := Ξ» i j k, begin apply pullback.hom_ext, apply pullback.hom_ext, all_goals { simp } end, cocycle := Ξ» i j k, cocycle 𝒰 f g i j k } /-- The first projection from the glued scheme into `X`. -/ def p1 : (gluing 𝒰 f g).glued ⟢ X := begin fapply multicoequalizer.desc, exact Ξ» i, pullback.fst ≫ 𝒰.map i, rintro ⟨i, j⟩, change pullback.fst ≫ _ ≫ 𝒰.map i = (_ ≫ _) ≫ _ ≫ 𝒰.map j, rw pullback.condition, rw ← category.assoc, congr' 1, rw category.assoc, exact (t_fst_fst _ _ _ _ _).symm end /-- The second projection from the glued scheme into `Y`. -/ def p2 : (gluing 𝒰 f g).glued ⟢ Y := begin fapply multicoequalizer.desc, exact Ξ» i, pullback.snd, rintro ⟨i, j⟩, change pullback.fst ≫ _ = (_ ≫ _) ≫ _, rw category.assoc, exact (t_fst_snd _ _ _ _ _).symm end lemma p_comm : p1 𝒰 f g ≫ f = p2 𝒰 f g ≫ g := begin apply multicoequalizer.hom_ext, intro i, erw [multicoequalizer.Ο€_desc_assoc, multicoequalizer.Ο€_desc_assoc], rw [category.assoc, pullback.condition] end variable (s : pullback_cone f g) /-- (Implementation) The canonical map `(s.X Γ—[X] Uα΅’) Γ—[s.X] (s.X Γ—[X] Uβ±Ό) ⟢ (Uα΅’ Γ—[Z] Y) Γ—[X] Uβ±Ό` This is used in `glued_lift`. -/ def glued_lift_pullback_map (i j : 𝒰.J) : pullback ((𝒰.pullback_cover s.fst).map i) ((𝒰.pullback_cover s.fst).map j) ⟢ (gluing 𝒰 f g).V ⟨i, j⟩ := begin change pullback pullback.fst pullback.fst ⟢ pullback _ _, refine (pullback_right_pullback_fst_iso _ _ _).hom ≫ _, refine pullback.map _ _ _ _ _ (πŸ™ _) (πŸ™ _) _ _, { exact (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (πŸ™ _) s.snd f (category.id_comp _).symm s.condition }, { simpa using pullback.condition }, { simp } end @[reassoc] lemma glued_lift_pullback_map_fst (i j : 𝒰.J) : glued_lift_pullback_map 𝒰 f g s i j ≫ pullback.fst = pullback.fst ≫ (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (πŸ™ _) s.snd f (category.id_comp _).symm s.condition := by { delta glued_lift_pullback_map, simp } @[reassoc] lemma glued_lift_pullback_map_snd (i j : 𝒰.J) : glued_lift_pullback_map 𝒰 f g s i j ≫ pullback.snd = pullback.snd ≫ pullback.snd := by { delta glued_lift_pullback_map, simp } /-- The lifted map `s.X ⟢ (gluing 𝒰 f g).glued` in order to show that `(gluing 𝒰 f g).glued` is indeed the pullback. Given a pullback cone `s`, we have the maps `s.fst ⁻¹' Uα΅’ ⟢ Uα΅’` and `s.fst ⁻¹' Uα΅’ ⟢ s.X ⟢ Y` that we may lift to a map `s.fst ⁻¹' Uα΅’ ⟢ Uα΅’ Γ—[Z] Y`. to glue these into a map `s.X ⟢ Uα΅’ Γ—[Z] Y`, we need to show that the maps agree on `(s.fst ⁻¹' Uα΅’) Γ—[s.X] (s.fst ⁻¹' Uβ±Ό) ⟢ Uα΅’ Γ—[Z] Y`. This is achieved by showing that both of these maps factors through `glued_lift_pullback_map`. -/ def glued_lift : s.X ⟢ (gluing 𝒰 f g).glued := begin fapply (𝒰.pullback_cover s.fst).glue_morphisms, { exact Ξ» i, (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (πŸ™ _) s.snd f (category.id_comp _).symm s.condition ≫ (gluing 𝒰 f g).ΞΉ i }, intros i j, rw ← glued_lift_pullback_map_fst_assoc, have : _ = pullback.fst ≫ _ := (gluing 𝒰 f g).glue_condition i j, rw [← this, gluing_to_glue_data_t, gluing_to_glue_data_f], simp_rw ← category.assoc, congr' 1, apply pullback.hom_ext; simp_rw category.assoc, { rw [t_fst_fst, glued_lift_pullback_map_snd], congr' 1, rw [← iso.inv_comp_eq, pullback_symmetry_inv_comp_snd], erw pullback.lift_fst, rw category.comp_id }, { rw [t_fst_snd, glued_lift_pullback_map_fst_assoc], erw [pullback.lift_snd, pullback.lift_snd], rw [pullback_symmetry_hom_comp_snd_assoc, pullback_symmetry_hom_comp_snd_assoc], exact pullback.condition_assoc _ } end lemma glued_lift_p1 : glued_lift 𝒰 f g s ≫ p1 𝒰 f g = s.fst := begin rw ← cancel_epi (𝒰.pullback_cover s.fst).from_glued, apply multicoequalizer.hom_ext, intro b, erw [multicoequalizer.Ο€_desc_assoc, multicoequalizer.Ο€_desc_assoc], delta glued_lift, simp_rw ← category.assoc, rw (𝒰.pullback_cover s.fst).ΞΉ_glue_morphisms, simp_rw category.assoc, erw [multicoequalizer.Ο€_desc, pullback.lift_fst_assoc, pullback.condition, category.comp_id], rw pullback_symmetry_hom_comp_fst_assoc, end lemma glued_lift_p2 : glued_lift 𝒰 f g s ≫ p2 𝒰 f g = s.snd := begin rw ← cancel_epi (𝒰.pullback_cover s.fst).from_glued, apply multicoequalizer.hom_ext, intro b, erw [multicoequalizer.Ο€_desc_assoc, multicoequalizer.Ο€_desc_assoc], delta glued_lift, simp_rw ← category.assoc, rw (𝒰.pullback_cover s.fst).ΞΉ_glue_morphisms, simp_rw category.assoc, erw [multicoequalizer.Ο€_desc, pullback.lift_snd], rw pullback_symmetry_hom_comp_snd_assoc, refl end /-- (Implementation) The canonical map `(W Γ—[X] Uα΅’) Γ—[W] (Uβ±Ό Γ—[Z] Y) ⟢ (Uβ±Ό Γ—[Z] Y) Γ—[X] Uα΅’ = V j i` where `W` is the glued fibred product. This is used in `lift_comp_ΞΉ`. -/ def pullback_fst_ΞΉ_to_V (i j : 𝒰.J) : pullback (pullback.fst : pullback (p1 𝒰 f g) (𝒰.map i) ⟢ _) ((gluing 𝒰 f g).ΞΉ j) ⟢ V 𝒰 f g j i := (pullback_symmetry _ _ β‰ͺ≫ (pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) _)).hom ≫ (pullback.congr_hom (multicoequalizer.Ο€_desc _ _ _ _ _) rfl).hom @[simp, reassoc] lemma pullback_fst_ΞΉ_to_V_fst (i j : 𝒰.J) : pullback_fst_ΞΉ_to_V 𝒰 f g i j ≫ pullback.fst = pullback.snd := by { delta pullback_fst_ΞΉ_to_V, simp } @[simp, reassoc] lemma pullback_fst_ΞΉ_to_V_snd (i j : 𝒰.J) : pullback_fst_ΞΉ_to_V 𝒰 f g i j ≫ pullback.snd = pullback.fst ≫ pullback.snd := by { delta pullback_fst_ΞΉ_to_V, simp } /-- We show that the map `W Γ—[X] Uα΅’ ⟢ Uα΅’ Γ—[Z] Y ⟢ W` is the first projection, where the first map is given by the lift of `W Γ—[X] Uα΅’ ⟢ Uα΅’` and `W Γ—[X] Uα΅’ ⟢ W ⟢ Y`. It suffices to show that the two map agrees when restricted onto `Uβ±Ό Γ—[Z] Y`. In this case, both maps factor through `V j i` via `pullback_fst_ΞΉ_to_V` -/ lemma lift_comp_ΞΉ (i : 𝒰.J) : pullback.lift pullback.snd (pullback.fst ≫ p2 𝒰 f g) (by rw [← pullback.condition_assoc, category.assoc, p_comm]) ≫ (gluing 𝒰 f g).ΞΉ i = (pullback.fst : pullback (p1 𝒰 f g) (𝒰.map i) ⟢ _) := begin apply ((gluing 𝒰 f g).open_cover.pullback_cover pullback.fst).hom_ext, intro j, dsimp only [open_cover.pullback_cover], transitivity pullback_fst_ΞΉ_to_V 𝒰 f g i j ≫ fV 𝒰 f g j i ≫ (gluing 𝒰 f g).ΞΉ _, { rw ← (show _ = fV 𝒰 f g j i ≫ _, from (gluing 𝒰 f g).glue_condition j i), simp_rw ← category.assoc, congr' 1, rw [gluing_to_glue_data_f, gluing_to_glue_data_t], apply pullback.hom_ext; simp_rw category.assoc, { rw [t_fst_fst, pullback.lift_fst, pullback_fst_ΞΉ_to_V_snd] }, { rw [t_fst_snd, pullback.lift_snd, pullback_fst_ΞΉ_to_V_fst_assoc, pullback.condition_assoc], erw multicoequalizer.Ο€_desc } }, { rw [pullback.condition, ← category.assoc], congr' 1, apply pullback.hom_ext, { simp }, { simp } } end /-- The canonical isomorphism between `W Γ—[X] Uα΅’` and `Uα΅’ Γ—[X] Y`. That is, the preimage of `Uα΅’` in `W` along `p1` is indeed `Uα΅’ Γ—[X] Y`. -/ def pullback_p1_iso (i : 𝒰.J) : pullback (p1 𝒰 f g) (𝒰.map i) β‰… pullback (𝒰.map i ≫ f) g := begin fsplit, exact pullback.lift pullback.snd (pullback.fst ≫ p2 𝒰 f g) (by rw [← pullback.condition_assoc, category.assoc, p_comm]), refine pullback.lift ((gluing 𝒰 f g).ΞΉ i) pullback.fst (by erw multicoequalizer.Ο€_desc), { apply pullback.hom_ext, { simpa using lift_comp_ΞΉ 𝒰 f g i }, { simp } }, { apply pullback.hom_ext, { simp }, { simp, erw multicoequalizer.Ο€_desc } }, end @[simp, reassoc] lemma pullback_p1_iso_hom_fst (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ pullback.fst = pullback.snd := by { delta pullback_p1_iso, simp } @[simp, reassoc] lemma pullback_p1_iso_hom_snd (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ pullback.snd = pullback.fst ≫ p2 𝒰 f g := by { delta pullback_p1_iso, simp } @[simp, reassoc] lemma pullback_p1_iso_inv_fst (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).inv ≫ pullback.fst = (gluing 𝒰 f g).ΞΉ i := by { delta pullback_p1_iso, simp } @[simp, reassoc] lemma pullback_p1_iso_inv_snd (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).inv ≫ pullback.snd = pullback.fst := by { delta pullback_p1_iso, simp } @[simp, reassoc] lemma pullback_p1_iso_hom_ΞΉ (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ (gluing 𝒰 f g).ΞΉ i = pullback.fst := by rw [← pullback_p1_iso_inv_fst, iso.hom_inv_id_assoc] /-- The glued scheme (`(gluing 𝒰 f g).glued`) is indeed the pullback of `f` and `g`. -/ def glued_is_limit : is_limit (pullback_cone.mk _ _ (p_comm 𝒰 f g)) := begin apply pullback_cone.is_limit_aux', intro s, refine ⟨glued_lift 𝒰 f g s, glued_lift_p1 𝒰 f g s, glued_lift_p2 𝒰 f g s, _⟩, intros m h₁ hβ‚‚, change m ≫ p1 𝒰 f g = _ at h₁, change m ≫ p2 𝒰 f g = _ at hβ‚‚, apply (𝒰.pullback_cover s.fst).hom_ext, intro i, rw open_cover.pullback_cover_map, have := pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) m β‰ͺ≫ pullback.congr_hom h₁ rfl, erw (𝒰.pullback_cover s.fst).ΞΉ_glue_morphisms, rw [← cancel_epi (pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) m β‰ͺ≫ pullback.congr_hom h₁ rfl).hom, iso.trans_hom, category.assoc, pullback.congr_hom_hom, pullback.lift_fst_assoc, category.comp_id, pullback_right_pullback_fst_iso_hom_fst_assoc, pullback.condition], transitivity pullback.snd ≫ (pullback_p1_iso 𝒰 f g _).hom ≫ (gluing 𝒰 f g).ΞΉ _, { congr' 1, rw ← pullback_p1_iso_hom_ΞΉ }, simp_rw ← category.assoc, congr' 1, apply pullback.hom_ext, { simp only [category.comp_id, pullback_right_pullback_fst_iso_hom_snd, category.assoc, pullback_p1_iso_hom_fst, pullback.lift_snd, pullback.lift_fst, pullback_symmetry_hom_comp_fst] }, { simp only [category.comp_id, pullback_right_pullback_fst_iso_hom_fst_assoc, pullback_p1_iso_hom_snd, category.assoc, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_snd_assoc, pullback.lift_snd], rw [← pullback.condition_assoc, hβ‚‚] } end lemma has_pullback_of_cover : has_pullback f g := ⟨⟨⟨_, glued_is_limit 𝒰 f g⟩⟩⟩ instance : has_limits CommRingα΅’α΅– := has_limits_op_of_has_colimits instance affine_has_pullback {A B C : CommRing} (f : Spec.obj (opposite.op A) ⟢ Spec.obj (opposite.op C)) (g : Spec.obj (opposite.op B) ⟢ Spec.obj (opposite.op C)) : has_pullback f g := begin rw [← Spec.image_preimage f, ← Spec.image_preimage g], exact ⟨⟨⟨_,is_limit_of_has_pullback_of_preserves_limit Spec (Spec.preimage f) (Spec.preimage g)⟩⟩⟩ end lemma affine_affine_has_pullback {B C : CommRing} {X : Scheme} (f : X ⟢ Spec.obj (opposite.op C)) (g : Spec.obj (opposite.op B) ⟢ Spec.obj (opposite.op C)) : has_pullback f g := has_pullback_of_cover X.affine_cover f g instance base_affine_has_pullback {C : CommRing} {X Y : Scheme} (f : X ⟢ Spec.obj (opposite.op C)) (g : Y ⟢ Spec.obj (opposite.op C)) : has_pullback f g := @@has_pullback_symmetry _ _ _ (@@has_pullback_of_cover Y.affine_cover g f (Ξ» i, @@has_pullback_symmetry _ _ _ $ affine_affine_has_pullback _ _)) instance left_affine_comp_pullback_has_pullback {X Y Z : Scheme} (f : X ⟢ Z) (g : Y ⟢ Z) (i : Z.affine_cover.J) : has_pullback ((Z.affine_cover.pullback_cover f).map i ≫ f) g := begin let Xα΅’ := pullback f (Z.affine_cover.map i), let Yα΅’ := pullback g (Z.affine_cover.map i), let W := pullback (pullback.snd : Yα΅’ ⟢ _) (pullback.snd : Xα΅’ ⟢ _), have := big_square_is_pullback (pullback.fst : W ⟢ _) (pullback.fst : Yα΅’ ⟢ _) (pullback.snd : Xα΅’ ⟢ _) (Z.affine_cover.map i) pullback.snd pullback.snd g pullback.condition.symm pullback.condition.symm (pullback_cone.flip_is_limit $ pullback_is_pullback _ _) (pullback_cone.flip_is_limit $ pullback_is_pullback _ _), have : has_pullback (pullback.snd ≫ Z.affine_cover.map i : Xα΅’ ⟢ _) g := ⟨⟨⟨_,this⟩⟩⟩, rw ← pullback.condition at this, exact this, end instance {X Y Z : Scheme} (f : X ⟢ Z) (g : Y ⟢ Z) : has_pullback f g := has_pullback_of_cover (Z.affine_cover.pullback_cover f) f g instance : has_pullbacks Scheme := has_pullbacks_of_has_limit_cospan _ /-- Given an open cover `{ Xα΅’ }` of `X`, then `X Γ—[Z] Y` is covered by `Xα΅’ Γ—[Z] Y`. -/ @[simps J obj map] def open_cover_of_left (𝒰 : open_cover X) (f : X ⟢ Z) (g : Y ⟢ Z) : open_cover (pullback f g) := begin fapply ((gluing 𝒰 f g).open_cover.pushforward_iso (limit.iso_limit_cone ⟨_, glued_is_limit 𝒰 f g⟩).inv).copy 𝒰.J (Ξ» i, pullback (𝒰.map i ≫ f) g) (Ξ» i, pullback.map _ _ _ _ (𝒰.map i) (πŸ™ _) (πŸ™ _) (category.comp_id _) (by simp)) (equiv.refl 𝒰.J) (Ξ» _, iso.refl _), rintro (i : 𝒰.J), change pullback.map _ _ _ _ _ _ _ _ _ = πŸ™ _ ≫ (gluing 𝒰 f g).ΞΉ i ≫ _, refine eq.trans _ (category.id_comp _).symm, apply pullback.hom_ext, all_goals { dsimp, simp only [limit.iso_limit_cone_inv_Ο€, pullback_cone.mk_Ο€_app_left, category.comp_id, pullback_cone.mk_Ο€_app_right, category.assoc, pullback.lift_fst, pullback.lift_snd], symmetry, exact multicoequalizer.Ο€_desc _ _ _ _ _ }, end /-- Given an open cover `{ Yα΅’ }` of `Y`, then `X Γ—[Z] Y` is covered by `X Γ—[Z] Yα΅’`. -/ @[simps J obj map] def open_cover_of_right (𝒰 : open_cover Y) (f : X ⟢ Z) (g : Y ⟢ Z) : open_cover (pullback f g) := begin fapply ((open_cover_of_left 𝒰 g f).pushforward_iso (pullback_symmetry _ _).hom).copy 𝒰.J (Ξ» i, pullback f (𝒰.map i ≫ g)) (Ξ» i, pullback.map _ _ _ _ (πŸ™ _) (𝒰.map i) (πŸ™ _) (by simp) (category.comp_id _)) (equiv.refl _) (Ξ» i, pullback_symmetry _ _), intro i, dsimp [open_cover.bind], apply pullback.hom_ext; simp, end /-- (Implementation). Use `open_cover_of_base` instead. -/ def open_cover_of_base' (𝒰 : open_cover Z) (f : X ⟢ Z) (g : Y ⟢ Z) : open_cover (pullback f g) := begin apply (open_cover_of_left (𝒰.pullback_cover f) f g).bind, intro i, let Xα΅’ := pullback f (𝒰.map i), let Yα΅’ := pullback g (𝒰.map i), let W := pullback (pullback.snd : Yα΅’ ⟢ _) (pullback.snd : Xα΅’ ⟢ _), have := big_square_is_pullback (pullback.fst : W ⟢ _) (pullback.fst : Yα΅’ ⟢ _) (pullback.snd : Xα΅’ ⟢ _) (𝒰.map i) pullback.snd pullback.snd g pullback.condition.symm pullback.condition.symm (pullback_cone.flip_is_limit $ pullback_is_pullback _ _) (pullback_cone.flip_is_limit $ pullback_is_pullback _ _), refine open_cover_of_is_iso ((pullback_symmetry _ _).hom ≫ (limit.iso_limit_cone ⟨_, this⟩).inv ≫ pullback.map _ _ _ _ (πŸ™ _) (πŸ™ _) (πŸ™ _) _ _), { simpa only [category.comp_id, category.id_comp, ← pullback.condition] }, { simp only [category.comp_id, category.id_comp] }, apply_instance end /-- Given an open cover `{ Zα΅’ }` of `Z`, then `X Γ—[Z] Y` is covered by `Xα΅’ Γ—[Zα΅’] Yα΅’`, where `Xα΅’ = X Γ—[Z] Zα΅’` and `Yα΅’ = Y Γ—[Z] Zα΅’` is the preimage of `Zα΅’` in `X` and `Y`. -/ @[simps J obj map] def open_cover_of_base (𝒰 : open_cover Z) (f : X ⟢ Z) (g : Y ⟢ Z) : open_cover (pullback f g) := begin apply (open_cover_of_base' 𝒰 f g).copy 𝒰.J (Ξ» i, pullback (pullback.snd : pullback f (𝒰.map i) ⟢ _) (pullback.snd : pullback g (𝒰.map i) ⟢ _)) (Ξ» i, pullback.map _ _ _ _ pullback.fst pullback.fst (𝒰.map i) pullback.condition.symm pullback.condition.symm) ((equiv.prod_punit 𝒰.J).symm.trans (equiv.sigma_equiv_prod 𝒰.J punit).symm) (Ξ» _, iso.refl _), intro i, change _ = _ ≫ _ ≫ _, refine eq.trans _ (category.id_comp _).symm, apply pullback.hom_ext; simp only [category.comp_id, open_cover_of_left_map, open_cover.pullback_cover_map, pullback_cone.mk_Ο€_app_left, open_cover_of_is_iso_map, limit.iso_limit_cone_inv_Ο€_assoc, category.assoc, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_snd_assoc, pullback.lift_fst, limit.iso_limit_cone_inv_Ο€, pullback_cone.mk_Ο€_app_right, pullback_symmetry_hom_comp_fst_assoc, pullback.lift_snd], end end pullback end algebraic_geometry.Scheme
95a86459abd8ff33d6039574ef693e9c72016967
4727251e0cd73359b15b664c3170e5d754078599
/src/data/fin/interval.lean
9c9a3976f0ef6f65a1b45838e89624fa782c4c13
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,592
lean
/- Copyright (c) 2021 YaΓ«l Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: YaΓ«l Dillies -/ import data.nat.interval /-! # Finite intervals in `fin n` This file proves that `fin n` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. -/ open finset fin open_locale big_operators variables (n : β„•) instance : locally_finite_order (fin n) := subtype.locally_finite_order _ namespace fin section bounded variables {n} (a b : fin n) lemma Icc_eq_finset_subtype : Icc a b = (Icc (a : β„•) b).subtype (Ξ» x, x < n) := rfl lemma Ico_eq_finset_subtype : Ico a b = (Ico (a : β„•) b).subtype (Ξ» x, x < n) := rfl lemma Ioc_eq_finset_subtype : Ioc a b = (Ioc (a : β„•) b).subtype (Ξ» x, x < n) := rfl lemma Ioo_eq_finset_subtype : Ioo a b = (Ioo (a : β„•) b).subtype (Ξ» x, x < n) := rfl @[simp] lemma map_subtype_embedding_Icc : (Icc a b).map (function.embedding.subtype _) = Icc (a : β„•) b := map_subtype_embedding_Icc _ _ _ (Ξ» _ c x _ hx _, hx.trans_lt) @[simp] lemma map_subtype_embedding_Ico : (Ico a b).map (function.embedding.subtype _) = Ico (a : β„•) b := map_subtype_embedding_Ico _ _ _ (Ξ» _ c x _ hx _, hx.trans_lt) @[simp] lemma map_subtype_embedding_Ioc : (Ioc a b).map (function.embedding.subtype _) = Ioc (a : β„•) b := map_subtype_embedding_Ioc _ _ _ (Ξ» _ c x _ hx _, hx.trans_lt) @[simp] lemma map_subtype_embedding_Ioo : (Ioo a b).map (function.embedding.subtype _) = Ioo (a : β„•) b := map_subtype_embedding_Ioo _ _ _ (Ξ» _ c x _ hx _, hx.trans_lt) @[simp] lemma card_Icc : (Icc a b).card = b + 1 - a := by rw [←nat.card_Icc, ←map_subtype_embedding_Icc, card_map] @[simp] lemma card_Ico : (Ico a b).card = b - a := by rw [←nat.card_Ico, ←map_subtype_embedding_Ico, card_map] @[simp] lemma card_Ioc : (Ioc a b).card = b - a := by rw [←nat.card_Ioc, ←map_subtype_embedding_Ioc, card_map] @[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 := by rw [←nat.card_Ioo, ←map_subtype_embedding_Ioo, card_map] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a := by rw [←card_Icc, fintype.card_of_finset] @[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = b - a := by rw [←card_Ico, fintype.card_of_finset] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a := by rw [←card_Ioc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 := by rw [←card_Ioo, fintype.card_of_finset] end bounded section unbounded variables {n} (a b : fin (n + 1)) lemma Ici_eq_finset_subtype : Ici a = (Icc (a : β„•) (n + 1)).subtype (Ξ» x, x < n + 1) := begin ext x, simp only [mem_subtype, mem_Ici, mem_Icc, coe_fin_le, iff_self_and], exact Ξ» _, x.2.le, end lemma Ioi_eq_finset_subtype : Ioi a = (Ioc (a : β„•) (n + 1)).subtype (Ξ» x, x < n + 1) := begin ext x, simp only [mem_subtype, mem_Ioi, mem_Ioc, coe_fin_lt, iff_self_and], exact Ξ» _, x.2.le, end lemma Iic_eq_finset_subtype : Iic b = (Iic (b : β„•)).subtype (Ξ» x, x < n + 1) := rfl lemma Iio_eq_finset_subtype : Iio b = (Iio (b : β„•)).subtype (Ξ» x, x < n + 1) := rfl @[simp] lemma map_subtype_embedding_Ici : (Ici a).map (function.embedding.subtype _) = Icc a n := begin ext x, simp only [exists_prop, function.embedding.coe_subtype, mem_Ici, mem_map, mem_Icc], split, { rintro ⟨x, hx, rfl⟩, exact ⟨hx, nat.lt_succ_iff.1 x.2⟩ }, { rintro hx, exact ⟨⟨x, nat.lt_succ_iff.2 hx.2⟩, hx.1, rfl⟩ } end @[simp] lemma map_subtype_embedding_Ioi : (Ioi a).map (function.embedding.subtype _) = Ioc a n := begin ext x, simp only [exists_prop, function.embedding.coe_subtype, mem_Ioi, mem_map, mem_Ioc], refine ⟨_, Ξ» hx, ⟨⟨x, nat.lt_succ_iff.2 hx.2⟩, hx.1, rfl⟩⟩, rintro ⟨x, hx, rfl⟩, exact ⟨hx, nat.lt_succ_iff.1 x.2⟩, end @[simp] lemma map_subtype_embedding_Iic : (Iic b).map (function.embedding.subtype _) = Iic b := begin ext x, simp only [exists_prop, function.embedding.coe_subtype, mem_Iic, mem_map], refine ⟨_, Ξ» hx, ⟨⟨x, hx.trans_lt b.2⟩, hx, rfl⟩⟩, rintro ⟨x, hx, rfl⟩, exact hx, end @[simp] lemma map_subtype_embedding_Iio : (Iio b).map (function.embedding.subtype _) = Iio b := begin ext x, simp only [exists_prop, function.embedding.coe_subtype, mem_Iio, mem_map], refine ⟨_, Ξ» hx, ⟨⟨x, hx.trans b.2⟩, hx, rfl⟩⟩, rintro ⟨x, hx, rfl⟩, exact hx, end @[simp] lemma card_Ici : (Ici a).card = n + 1 - a := by rw [←nat.card_Icc, ←map_subtype_embedding_Ici, card_map] @[simp] lemma card_Ioi : (Ioi a).card = n - a := by rw [←nat.card_Ioc, ←map_subtype_embedding_Ioi, card_map] @[simp] lemma card_Iic : (Iic b).card = b + 1 := by rw [←nat.card_Iic b, ←map_subtype_embedding_Iic, card_map] @[simp] lemma card_Iio : (Iio b).card = b := by rw [←nat.card_Iio b, ←map_subtype_embedding_Iio, card_map] @[simp] lemma card_fintype_Ici : fintype.card (set.Ici a) = n + 1 - a := by rw [fintype.card_of_finset, card_Ici] @[simp] lemma card_fintype_Ioi : fintype.card (set.Ioi a) = n - a := by rw [fintype.card_of_finset, card_Ioi] @[simp] lemma card_fintype_Iic : fintype.card (set.Iic b) = b + 1 := by rw [fintype.card_of_finset, card_Iic] @[simp] lemma card_fintype_Iio : fintype.card (set.Iio b) = b := by rw [fintype.card_of_finset, card_Iio] end unbounded section filter variables {n} (a b : fin n) @[simp] lemma card_filter_lt : (finset.univ.filter (Ξ» j, a < j)).card = n - a - 1 := begin cases n, { simp }, { rw [filter_lt_eq_Ioi, card_Ioi, tsub_tsub], exact (add_tsub_add_eq_tsub_right _ 1 _).symm } end @[simp] lemma card_filter_le : (univ.filter (Ξ» j, a ≀ j)).card = n - a := begin cases n, { simp }, { rw [filter_le_eq_Ici, card_Ici] } end @[simp] lemma card_filter_gt : (finset.univ.filter (Ξ» j, j < a)).card = a := begin cases n, { exact fin.elim0 a }, { rw [filter_gt_eq_Iio, card_Iio] } end @[simp] lemma card_filter_ge : (finset.univ.filter (Ξ» j, j ≀ a)).card = a + 1 := begin cases n, { exact fin.elim0 a }, { rw [filter_ge_eq_Iic, card_Iic] } end @[simp] lemma card_filter_lt_lt : (finset.univ.filter (Ξ» j, a < j ∧ j < b)).card = b - a - 1 := begin cases n, { exact fin.elim0 a }, { rw [filter_lt_lt_eq_Ioo, card_Ioo] } end @[simp] lemma card_filter_lt_le : (finset.univ.filter (Ξ» j, a < j ∧ j ≀ b)).card = b - a := begin cases n, { exact fin.elim0 a }, { rw [filter_lt_le_eq_Ioc, card_Ioc] } end @[simp] lemma card_filter_le_lt : (finset.univ.filter (Ξ» j, a ≀ j ∧ j < b)).card = b - a := begin cases n, { exact fin.elim0 a }, { rw [filter_le_lt_eq_Ico, card_Ico] } end @[simp] lemma card_filter_le_le : (finset.univ.filter (Ξ» j, a ≀ j ∧ j ≀ b)).card = b + 1 - a := begin cases n, { exact fin.elim0 a }, { rw [filter_le_le_eq_Icc, card_Icc] } end lemma prod_filter_lt_mul_neg_eq_prod_off_diag {R : Type*} [comm_monoid R] {n : β„•} {f : fin n β†’ fin n β†’ R} : ∏ i, (∏ j in univ.filter (Ξ» j, i < j), (f j i) * (f i j)) = ∏ i, (∏ j in univ.filter (Ξ» j, i β‰  j), (f j i)) := begin simp_rw [ne_iff_lt_or_gt, or.comm, filter_or, prod_mul_distrib], have : βˆ€ i : fin n, disjoint (filter (gt i) univ) (filter (has_lt.lt i) univ), { simp_rw disjoint_filter, intros i x y, apply lt_asymm }, simp only [prod_union, this, prod_mul_distrib], rw mul_comm, congr' 1, rw [prod_sigma', prod_sigma'], refine prod_bij' (Ξ» i hi, ⟨i.2, i.1⟩) _ _ (Ξ» i hi, ⟨i.2, i.1⟩) _ _ _; simp end end filter end fin
26fcb1a6e0b702a494d174511f6ab0794db99efc
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world10/level16.lean
8dc53f3648ff8627471f9334dd13814273037560
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
662
lean
import game.world10.level15 -- hide namespace mynat -- hide /- # Inequality world. ## Level 16: equivalence of two definitions of `<` Now let's go the other way. -/ /- Lemma : For all naturals $a$ and $b$, $$ \operatorname{succ}(a)\le b \implies a\le b\land\lnot(b\le a).$$ -/ lemma lt_aux_two (a b : mynat) : succ a ≀ b β†’ a ≀ b ∧ Β¬ (b ≀ a) := begin [nat_num_game] intro h, split, { apply le_trans a (succ a) b, exact le_succ_self a, exact h, }, intro nh, apply ne_succ_self a, apply le_antisymm a (succ a), exact le_succ_self a, exact le_trans (succ a) b a h nh, end /- Now for the payoff. -/ end mynat -- hide
c152ec15e1423a672cc86f02d0ddaf1aa5cfecb9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/tprod.lean
2d2c304179f969d05ae4f6d824a426e34f1738a7
[]
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,707
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.nodup import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Finite products of types This file defines the product of types over a list. For `l : list ΞΉ` and `Ξ± : ΞΉ β†’ Type*` we define `list.tprod Ξ± l = l.foldr (Ξ» i Ξ², Ξ± i Γ— Ξ²) punit`. This type should not be used if `Ξ  i, Ξ± i` or `Ξ  i ∈ l, Ξ± i` can be used instead (in the last expression, we could also replace the list `l` by a set or a finset). This type is used as an intermediary between binary products and finitary products. The application of this type is finitary product measures, but it could be used in any construction/theorem that is easier to define/prove on binary products than on finitary products. * Once we have the construction on binary products (like binary product measures in `measure_theory.prod`), we can easily define a finitary version on the type `tprod l Ξ±` by iterating. Properties can also be easily extended from the binary case to the finitary case by iterating. * Then we can use the equivalence `list.tprod.pi_equiv_tprod` below (or enhanced versions of it, like a `measurable_equiv` for product measures) to get the construction on `Ξ  i : ΞΉ, Ξ± i`, at least when assuming `[fintype ΞΉ] [encodable ΞΉ]` (using `encodable.sorted_univ`). Using `local attribute [instance] fintype.encodable` we can get rid of the argument `[encodable ΞΉ]`. ## Main definitions * We have the equivalence `tprod.pi_equiv_tprod : (Ξ  i, Ξ± i) ≃ tprod Ξ± l` if `l` contains every element of `ΞΉ` exactly once. * The product of sets is `set.tprod : (Ξ  i, set (Ξ± i)) β†’ set (tprod Ξ± l)`. -/ namespace list /-- The product of a family of types over a list. -/ def tprod {ΞΉ : Type u_1} (Ξ± : ΞΉ β†’ Type u_2) (l : List ΞΉ) := foldr (fun (i : ΞΉ) (Ξ² : Type (max u_2 u_3)) => Ξ± i Γ— Ξ²) PUnit l namespace tprod /-- Turning a function `f : Ξ  i, Ξ± i` into an element of the iterated product `tprod Ξ± l`. -/ protected def mk {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} (l : List ΞΉ) (f : (i : ΞΉ) β†’ Ξ± i) : tprod Ξ± l := sorry protected instance inhabited {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} {l : List ΞΉ} [(i : ΞΉ) β†’ Inhabited (Ξ± i)] : Inhabited (tprod Ξ± l) := { default := tprod.mk l fun (i : ΞΉ) => Inhabited.default } @[simp] theorem fst_mk {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} (i : ΞΉ) (l : List ΞΉ) (f : (i : ΞΉ) β†’ Ξ± i) : prod.fst (tprod.mk (i :: l) f) = f i := rfl @[simp] theorem snd_mk {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} (i : ΞΉ) (l : List ΞΉ) (f : (i : ΞΉ) β†’ Ξ± i) : prod.snd (tprod.mk (i :: l) f) = tprod.mk l f := rfl /-- Given an element of the iterated product `l.prod Ξ±`, take a projection into direction `i`. If `i` appears multiple times in `l`, this chooses the first component in direction `i`. -/ protected def elim {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} [DecidableEq ΞΉ] {l : List ΞΉ} (v : tprod Ξ± l) {i : ΞΉ} (hi : i ∈ l) : Ξ± i := sorry @[simp] theorem elim_self {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} {i : ΞΉ} {l : List ΞΉ} [DecidableEq ΞΉ] (v : tprod Ξ± (i :: l)) : tprod.elim v (mem_cons_self i l) = prod.fst v := sorry @[simp] theorem elim_of_ne {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} {i : ΞΉ} {j : ΞΉ} {l : List ΞΉ} [DecidableEq ΞΉ] (hj : j ∈ i :: l) (hji : j β‰  i) (v : tprod Ξ± (i :: l)) : tprod.elim v hj = tprod.elim (prod.snd v) (or.resolve_left hj hji) := sorry @[simp] theorem elim_of_mem {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} {i : ΞΉ} {j : ΞΉ} {l : List ΞΉ} [DecidableEq ΞΉ] (hl : nodup (i :: l)) (hj : j ∈ l) (v : tprod Ξ± (i :: l)) : tprod.elim v (mem_cons_of_mem i hj) = tprod.elim (prod.snd v) hj := sorry theorem elim_mk {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} [DecidableEq ΞΉ] (l : List ΞΉ) (f : (i : ΞΉ) β†’ Ξ± i) {i : ΞΉ} (hi : i ∈ l) : tprod.elim (tprod.mk l f) hi = f i := sorry theorem ext {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} [DecidableEq ΞΉ] {l : List ΞΉ} (hl : nodup l) {v : tprod Ξ± l} {w : tprod Ξ± l} (hvw : βˆ€ (i : ΞΉ) (hi : i ∈ l), tprod.elim v hi = tprod.elim w hi) : v = w := sorry /-- A version of `tprod.elim` when `l` contains all elements. In this case we get a function into `Ξ  i, Ξ± i`. -/ @[simp] protected def elim' {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} {l : List ΞΉ} [DecidableEq ΞΉ] (h : βˆ€ (i : ΞΉ), i ∈ l) (v : tprod Ξ± l) (i : ΞΉ) : Ξ± i := tprod.elim v (h i) theorem mk_elim {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} {l : List ΞΉ} [DecidableEq ΞΉ] (hnd : nodup l) (h : βˆ€ (i : ΞΉ), i ∈ l) (v : tprod Ξ± l) : tprod.mk l (tprod.elim' h v) = v := sorry /-- Pi-types are equivalent to iterated products. -/ def pi_equiv_tprod {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} {l : List ΞΉ} [DecidableEq ΞΉ] (hnd : nodup l) (h : βˆ€ (i : ΞΉ), i ∈ l) : ((i : ΞΉ) β†’ Ξ± i) ≃ tprod Ξ± l := equiv.mk (tprod.mk l) (tprod.elim' h) sorry sorry end tprod end list namespace set /-- A product of sets in `tprod Ξ± l`. -/ @[simp] protected def tprod {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} (l : List ΞΉ) (t : (i : ΞΉ) β†’ set (Ξ± i)) : set (list.tprod Ξ± l) := sorry theorem mk_preimage_tprod {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} (l : List ΞΉ) (t : (i : ΞΉ) β†’ set (Ξ± i)) : list.tprod.mk l ⁻¹' set.tprod l t = pi (set_of fun (i : ΞΉ) => i ∈ l) t := sorry theorem elim_preimage_pi {ΞΉ : Type u_1} {Ξ± : ΞΉ β†’ Type u_2} [DecidableEq ΞΉ] {l : List ΞΉ} (hnd : list.nodup l) (h : βˆ€ (i : ΞΉ), i ∈ l) (t : (i : ΞΉ) β†’ set (Ξ± i)) : list.tprod.elim' h ⁻¹' pi univ t = set.tprod l t := sorry
c9a94d5dc0219febd0cd2dfc3db770a142b4fa3b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/ofNatNormNum.lean
0ffbf530506579f0655b7d2236c809ff22212cda
[ "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,881
lean
class OfNatSound (Ξ± : Type u) [Add Ξ±] [(n : Nat) β†’ OfNat Ξ± n] : Prop where ofNat_add (n m : Nat) : (OfNat.ofNat n : Ξ±) + OfNat.ofNat m = OfNat.ofNat (n+m) export OfNatSound (ofNat_add) theorem ex1 {Ξ± : Type u} [Add Ξ±] [(n : Nat) β†’ OfNat Ξ± n] [OfNatSound Ξ±] : (10000000 : Ξ±) + 10000000 = 20000000 := ofNat_add .. class Zero (Ξ± : Type u) where zero : Ξ± class One (Ξ± : Type u) where one : Ξ± instance [Zero Ξ±] : OfNat Ξ± (nat_lit 0) where ofNat := Zero.zero instance [One Ξ±] : OfNat Ξ± (nat_lit 1) where ofNat := One.one -- Some example structure class S (Ξ± : Type u) extends Add Ξ±, Mul Ξ±, Zero Ξ±, One Ξ± where add_assoc (a b c : Ξ±) : a + b + c = a + (b + c) add_zero (a : Ξ±) : a + 0 = a zero_add (a : Ξ±) : 0 + a = a mul_zero (a : Ξ±) : a * 0 = 0 mul_one (a : Ξ±) : a * 1 = a left_distrib (a b c : Ξ±) : a * (b + c) = a * b + a * c -- Very simply default `ofNat` for `S` protected def S.ofNat (Ξ± : Type u) [S Ξ±] : Nat β†’ Ξ± | 0 => 0 | n+1 => S.ofNat Ξ± n + 1 instance [S Ξ±] : OfNat Ξ± n where ofNat := S.ofNat Ξ± n instance [S Ξ±] : OfNatSound Ξ± where ofNat_add n m := by induction m with | zero => simp [S.ofNat]; erw [S.add_zero]; done | succ m ih => simp [OfNat.ofNat, S.ofNat] at *; erw [← ih]; rw [S.add_assoc] theorem S.ofNat_mul [S Ξ±] (n m : Nat) : (OfNat.ofNat n : Ξ±) * OfNat.ofNat m = OfNat.ofNat (n * m) := by induction m with | zero => rw [S.mul_zero, Nat.mul_zero] | succ m ih => show OfNat.ofNat (Ξ± := Ξ±) n * OfNat.ofNat (m + 1) = OfNat.ofNat (n * m.succ) rw [Nat.mul_succ, ← ofNat_add, ← ofNat_add, ← ih, left_distrib] simp [OfNat.ofNat, S.ofNat] erw [S.zero_add, S.mul_one] theorem ex2 [S Ξ±] : (100000000000000000 : Ξ±) * 20000000000000000 = 2000000000000000000000000000000000 := S.ofNat_mul .. #print ex2
a42441d777368c55ef3cbf64a50e557ec7c84c57
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/sheaves/limits.lean
5190ac2bbca21bc9ae01fb2f8b262f998fc121d5
[ "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
672
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.presheaf import category_theory.limits.functor_category /-! # Presheaves in `C` have limits and colimits when `C` does. -/ noncomputable theory universes v u open category_theory open category_theory.limits variables {C : Type u} [category.{v} C] namespace Top instance [has_limits C] (X : Top) : has_limits (presheaf C X) := by { dsimp [presheaf], apply_instance, } instance [has_colimits C] (X : Top) : has_colimits (presheaf C X) := by { dsimp [presheaf], apply_instance, } end Top
c669a52ebf245cd43e887dca742c630ed8a1afbb
aa2345b30d710f7e75f13157a35845ee6d48c017
/data/set/lattice.lean
4f3fda648b726f71c370ccecbfa8a2658e35ba08
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
27,267
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, Johannes HΓΆlzl, Mario Carneiro -- QUESTION: can make the first argument in βˆ€ x ∈ a, ... implicit? -/ import logic.basic data.set.basic data.equiv.basic tactic import order.complete_boolean_algebra category.basic import tactic.finish data.sigma.basic order.galois_connection open function tactic set lattice auto universes u v w x variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {ΞΉ : Sort x} namespace set instance lattice_set : complete_lattice (set Ξ±) := { lattice.complete_lattice . le := (βŠ†), le_refl := subset.refl, le_trans := assume a b c, subset.trans, le_antisymm := assume a b, subset.antisymm, lt := Ξ» x y, x βŠ† y ∧ Β¬ y βŠ† x, lt_iff_le_not_le := Ξ» x y, iff.refl _, sup := (βˆͺ), le_sup_left := subset_union_left, le_sup_right := subset_union_right, sup_le := assume a b c, union_subset, inf := (∩), inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, le_inf := assume a b c, subset_inter, top := {a | true }, le_top := assume s a h, trivial, bot := βˆ…, bot_le := assume s a, false.elim, Sup := Ξ»s, {a | βˆƒ t ∈ s, a ∈ t }, le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, Inf := Ξ»s, {a | βˆ€ t ∈ s, a ∈ t }, le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := assume s t t_in a h, h _ t_in } instance : distrib_lattice (set Ξ±) := { le_sup_inf := Ξ» s t u x, or_and_distrib_left.2, ..set.lattice_set } lemma monotone_image {f : Ξ± β†’ Ξ²} : monotone (image f) := assume s t, assume h : s βŠ† t, image_subset _ h section galois_connection variables {f : Ξ± β†’ Ξ²} protected lemma image_preimage : galois_connection (image f) (preimage f) := assume a b, image_subset_iff def kern_image (f : Ξ± β†’ Ξ²) (s : set Ξ±) : set Ξ² := {y | βˆ€x, f x = y β†’ x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := assume a b, ⟨ assume h x hx y hy, have f y ∈ a, from hy.symm β–Έ hx, h this, assume h x (hx : f x ∈ a), h hx x rfl⟩ end galois_connection /- union and intersection over a family of sets indexed by a type -/ /-- Indexed union of a family of sets -/ @[reducible] def Union (s : ΞΉ β†’ set Ξ²) : set Ξ² := supr s /-- Indexed intersection of a family of sets -/ @[reducible] def Inter (s : ΞΉ β†’ set Ξ²) : set Ξ² := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `β‹‚` binders `, ` r:(scoped f, Inter f) := r @[simp] theorem mem_Union {x : Ξ²} {s : ΞΉ β†’ set Ξ²} : x ∈ Union s ↔ βˆƒ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : t = s a)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq β–Έ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate βˆƒi, ... ∧ i = t ∧ ... @[simp] theorem mem_Inter {x : Ξ²} {s : ΞΉ β†’ set Ξ²} : x ∈ Inter s ↔ βˆ€ i, x ∈ s i := ⟨assume (h : βˆ€a ∈ {a : set Ξ² | βˆƒi, a = s i}, x ∈ a) a, h (s a) ⟨a, rfl⟩, assume h t ⟨a, (eq : t = s a)⟩, eq.symm β–Έ h a⟩ theorem Union_subset {s : ΞΉ β†’ set Ξ²} {t : set Ξ²} (h : βˆ€ i, s i βŠ† t) : (⋃ i, s i) βŠ† t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set Ξ²) _ set.lattice_set _ _ h theorem Union_subset_iff {Ξ± : Sort u} {s : Ξ± β†’ set Ξ²} {t : set Ξ²} : (⋃ i, s i) βŠ† t ↔ (βˆ€ i, s i βŠ† t):= ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {Ξ± : Sort u} {x : Ξ²} {s : Ξ± β†’ set Ξ²} : (βˆ€ i, x ∈ s i) β†’ (x ∈ β‹‚ i, s i) := assume h t ⟨a, (eq : t = s a)⟩, eq.symm β–Έ h a theorem subset_Inter {t : set Ξ²} {s : Ξ± β†’ set Ξ²} (h : βˆ€ i, t βŠ† s i) : t βŠ† β‹‚ i, s i := -- TODO: should be simpler when sets' order is based on lattices @le_infi (set Ξ²) _ set.lattice_set _ _ h theorem subset_Union : βˆ€ (s : ΞΉ β†’ set Ξ²) (i : ΞΉ), s i βŠ† (⋃ i, s i) := le_supr theorem Inter_subset : βˆ€ (s : ΞΉ β†’ set Ξ²) (i : ΞΉ), (β‹‚ i, s i) βŠ† s i := infi_le theorem Union_const [inhabited ΞΉ] (s : set Ξ²) : (⋃ i:ΞΉ, s) = s := ext $ by simp theorem Inter_const [inhabited ΞΉ] (s : set Ξ²) : (β‹‚ i:ΞΉ, s) = s := ext $ by simp @[simp] -- complete_boolean_algebra theorem compl_Union (s : ΞΉ β†’ set Ξ²) : - (⋃ i, s i) = (β‹‚ i, - s i) := ext (by simp) -- classical -- complete_boolean_algebra theorem compl_Inter (s : ΞΉ β†’ set Ξ²) : -(β‹‚ i, s i) = (⋃ i, - s i) := ext (Ξ» x, by simp [classical.not_forall]) -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ΞΉ β†’ set Ξ²) : (⋃ i, s i) = - (β‹‚ i, - s i) := by simp [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ΞΉ β†’ set Ξ²) : (β‹‚ i, s i) = - (⋃ i, -s i) := by simp [compl_compl] theorem inter_Union_left (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem inter_Union_right (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ΞΉ β†’ set Ξ²) (t : ΞΉ β†’ set Ξ²) : (⋃ i, s i βˆͺ t i) = (⋃ i, s i) βˆͺ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem Inter_inter_distrib (s : ΞΉ β†’ set Ξ²) (t : ΞΉ β†’ set Ξ²) : (β‹‚ i, s i ∩ t i) = (β‹‚ i, s i) ∩ (β‹‚ i, t i) := ext $ by simp [forall_and_distrib] theorem union_Union_left [inhabited ΞΉ] (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : s βˆͺ (⋃ i, t i) = ⋃ i, s βˆͺ t i := by rw [Union_union_distrib, Union_const] theorem union_Union_right [inhabited ΞΉ] (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : (⋃ i, t i) βˆͺ s = ⋃ i, t i βˆͺ s := by rw [Union_union_distrib, Union_const] theorem inter_Inter_left [inhabited ΞΉ] (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : s ∩ (β‹‚ i, t i) = β‹‚ i, s ∩ t i := by rw [Inter_inter_distrib, Inter_const] theorem inter_Inter_right [inhabited ΞΉ] (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : (β‹‚ i, t i) ∩ s = β‹‚ i, t i ∩ s := by rw [Inter_inter_distrib, Inter_const] -- classical theorem union_Inter_left (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : s βˆͺ (β‹‚ i, t i) = β‹‚ i, s βˆͺ t i := ext $ assume x, by simp [classical.forall_or_distrib_left] theorem diff_Union_right (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : (⋃ i, t i) \ s = ⋃ i, t i \ s := inter_Union_right _ _ theorem diff_Union_left [inhabited ΞΉ] (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : s \ (⋃ i, t i) = β‹‚ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter_left]; refl theorem diff_Inter_left (s : set Ξ²) (t : ΞΉ β†’ set Ξ²) : s \ (β‹‚ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union_left]; refl /- bounded unions and intersections -/ theorem mem_bUnion_iff {s : set Ξ±} {t : Ξ± β†’ set Ξ²} {y : Ξ²} : y ∈ (⋃ x ∈ s, t x) ↔ βˆƒ x, x ∈ s ∧ y ∈ t x := by simp theorem mem_bInter_iff {s : set Ξ±} {t : Ξ± β†’ set Ξ²} {y : Ξ²} : y ∈ (β‹‚ x ∈ s, t x) ↔ βˆ€ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set Ξ±} {t : Ξ± β†’ set Ξ²} {x : Ξ±} {y : Ξ²} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := by simp; exact ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set Ξ±} {t : Ξ± β†’ set Ξ²} {y : Ξ²} (h : βˆ€ x ∈ s, y ∈ t x) : y ∈ β‹‚ x ∈ s, t x := by simp; assumption theorem bUnion_subset {s : set Ξ±} {t : set Ξ²} {u : Ξ± β†’ set Ξ²} (h : βˆ€ x ∈ s, u x βŠ† t) : (⋃ x ∈ s, u x) βŠ† t := show (⨆ x ∈ s, u x) ≀ t, -- TODO: should not be necessary when sets' order is based on lattices from supr_le $ assume x, supr_le (h x) theorem subset_bInter {s : set Ξ±} {t : set Ξ²} {u : Ξ± β†’ set Ξ²} (h : βˆ€ x ∈ s, t βŠ† u x) : t βŠ† (β‹‚ x ∈ s, u x) := show t ≀ (β¨… x ∈ s, u x), -- TODO: should not be necessary when sets' order is based on lattices from le_infi $ assume x, le_infi (h x) theorem subset_bUnion_of_mem {s : set Ξ±} {u : Ξ± β†’ set Ξ²} {x : Ξ±} (xs : x ∈ s) : u x βŠ† (⋃ x ∈ s, u x) := show u x ≀ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set Ξ±} {t : Ξ± β†’ set Ξ²} {x : Ξ±} (xs : x ∈ s) : (β‹‚ x ∈ s, t x) βŠ† t x := show (β¨…x ∈ s, t x) ≀ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set Ξ±} {t : Ξ± β†’ set Ξ²} (h : s βŠ† s') : (⋃ x ∈ s, t x) βŠ† (⋃ x ∈ s', t x) := bUnion_subset (Ξ» x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set Ξ±} {t : Ξ± β†’ set Ξ²} (h : s' βŠ† s) : (β‹‚ x ∈ s, t x) βŠ† (β‹‚ x ∈ s', t x) := subset_bInter (Ξ» x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set Ξ±} {t1 t2 : Ξ± β†’ set Ξ²} (h : βˆ€ x ∈ s, t1 x βŠ† t2 x) : (⋃ x ∈ s, t1 x) βŠ† (⋃ x ∈ s, t2 x) := bUnion_subset (Ξ» x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set Ξ±} {t1 t2 : Ξ± β†’ set Ξ²} (h : βˆ€ x ∈ s, t1 x βŠ† t2 x) : (β‹‚ x ∈ s, t1 x) βŠ† (β‹‚ x ∈ s, t2 x) := subset_bInter (Ξ» x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_eq_Union (s : set Ξ±) (t : Ξ± β†’ set Ξ²) : (⋃ x ∈ s, t x) = (⋃ x : s, t x.1) := set.ext $ by simp theorem bInter_eq_Inter (s : set Ξ±) (t : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ s, t x) = (β‹‚ x : s, t x.1) := set.ext $ by simp @[simp] theorem bInter_empty (u : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ (βˆ… : set Ξ±), u x) = univ := show (β¨…x ∈ (βˆ… : set Ξ±), u x) = ⊀, -- simplifier should be able to rewrite x ∈ βˆ… to false. from infi_emptyset @[simp] theorem bInter_univ (u : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ @univ Ξ±, u x) = β‹‚ x, u x := infi_univ -- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. @[simp] theorem bInter_singleton (a : Ξ±) (s : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ ({a} : set Ξ±), s x) = s a := show (β¨… x ∈ ({a} : set Ξ±), s x) = s a, by simp theorem bInter_union (s t : set Ξ±) (u : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ s βˆͺ t, u x) = (β‹‚ x ∈ s, u x) ∩ (β‹‚ x ∈ t, u x) := show (β¨… x ∈ s βˆͺ t, u x) = (β¨… x ∈ s, u x) βŠ“ (β¨… x ∈ t, u x), from infi_union -- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work @[simp] theorem bInter_insert (a : Ξ±) (s : set Ξ±) (t : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ insert a s, t x) = t a ∩ (β‹‚ x ∈ s, t x) := begin rw insert_eq, simp [bInter_union] end -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : Ξ±) (s : Ξ± β†’ set Ξ²) : (β‹‚ x ∈ ({a, b} : set Ξ±), s x) = s a ∩ s b := by rw insert_of_has_insert; simp [inter_comm] @[simp] theorem bUnion_empty (s : Ξ± β†’ set Ξ²) : (⋃ x ∈ (βˆ… : set Ξ±), s x) = βˆ… := supr_emptyset @[simp] theorem bUnion_univ (s : Ξ± β†’ set Ξ²) : (⋃ x ∈ @univ Ξ±, s x) = ⋃ x, s x := supr_univ @[simp] theorem bUnion_singleton (a : Ξ±) (s : Ξ± β†’ set Ξ²) : (⋃ x ∈ ({a} : set Ξ±), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set Ξ±) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set Ξ±) (u : Ξ± β†’ set Ξ²) : (⋃ x ∈ s βˆͺ t, u x) = (⋃ x ∈ s, u x) βˆͺ (⋃ x ∈ t, u x) := supr_union -- TODO(Jeremy): once again, simp doesn't do it alone. @[simp] theorem bUnion_insert (a : Ξ±) (s : set Ξ±) (t : Ξ± β†’ set Ξ²) : (⋃ x ∈ insert a s, t x) = t a βˆͺ (⋃ x ∈ s, t x) := begin rw [insert_eq], simp [bUnion_union] end theorem bUnion_pair (a b : Ξ±) (s : Ξ± β†’ set Ξ²) : (⋃ x ∈ ({a, b} : set Ξ±), s x) = s a βˆͺ s b := by rw insert_of_has_insert; simp [union_comm] @[simp] -- complete_boolean_algebra theorem compl_bUnion (s : set Ξ±) (t : Ξ± β†’ set Ξ²) : - (⋃ i ∈ s, t i) = (β‹‚ i ∈ s, - t i) := ext (Ξ» x, by simp) -- classical -- complete_boolean_algebra theorem compl_bInter (s : set Ξ±) (t : Ξ± β†’ set Ξ²) : -(β‹‚ i ∈ s, t i) = (⋃ i ∈ s, - t i) := ext (Ξ» x, by simp [classical.not_forall]) /-- Intersection of a set of sets. -/ @[reducible] def sInter (S : set (set Ξ±)) : set Ξ± := Inf S prefix `β‹‚β‚€`:110 := sInter theorem mem_sUnion_of_mem {x : Ξ±} {t : set Ξ±} {S : set (set Ξ±)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ⟨ht, hx⟩⟩ @[simp] theorem mem_sUnion {x : Ξ±} {S : set (set Ξ±)} : x ∈ ⋃₀ S ↔ βˆƒt ∈ S, x ∈ t := iff.rfl -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : Ξ±} {t : set Ξ±} {S : set (set Ξ±)} (hx : x βˆ‰ ⋃₀ S) (ht : t ∈ S) : x βˆ‰ t := Ξ» h, hx ⟨t, ht, h⟩ @[simp] theorem mem_sInter {x : Ξ±} {S : set (set Ξ±)} : x ∈ β‹‚β‚€ S ↔ βˆ€ t ∈ S, x ∈ t := iff.rfl theorem sInter_subset_of_mem {S : set (set Ξ±)} {t : set Ξ±} (tS : t ∈ S) : β‹‚β‚€ S βŠ† t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set Ξ±)} {t : set Ξ±} (tS : t ∈ S) : t βŠ† ⋃₀ S := le_Sup tS theorem sUnion_subset {S : set (set Ξ±)} {t : set Ξ±} (h : βˆ€t' ∈ S, t' βŠ† t) : (⋃₀ S) βŠ† t := Sup_le h theorem sUnion_subset_iff {s : set (set Ξ±)} {t : set Ξ±} : ⋃₀ s βŠ† t ↔ βˆ€t' ∈ s, t' βŠ† t := ⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set Ξ±)} {t : set Ξ±} (h : βˆ€t' ∈ S, t βŠ† t') : t βŠ† (β‹‚β‚€ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set Ξ±)} (h : S βŠ† T) : ⋃₀ S βŠ† ⋃₀ T := sUnion_subset $ Ξ» s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set Ξ±)} (h : S βŠ† T) : β‹‚β‚€ T βŠ† β‹‚β‚€ S := subset_sInter $ Ξ» s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ βˆ… = (βˆ… : set Ξ±) := Sup_empty @[simp] theorem sInter_empty : β‹‚β‚€ βˆ… = (univ : set Ξ±) := Inf_empty @[simp] theorem sUnion_singleton (s : set Ξ±) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set Ξ±) : β‹‚β‚€ {s} = s := Inf_singleton theorem sUnion_union (S T : set (set Ξ±)) : ⋃₀ (S βˆͺ T) = ⋃₀ S βˆͺ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set Ξ±)) : β‹‚β‚€ (S βˆͺ T) = β‹‚β‚€ S ∩ β‹‚β‚€ T := Inf_union @[simp] theorem sUnion_insert (s : set Ξ±) (T : set (set Ξ±)) : ⋃₀ (insert s T) = s βˆͺ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set Ξ±) (T : set (set Ξ±)) : β‹‚β‚€ (insert s T) = s ∩ β‹‚β‚€ T := Inf_insert theorem sUnion_pair (s t : set Ξ±) : ⋃₀ {s, t} = s βˆͺ t := (sUnion_insert _ _).trans $ by rw [union_comm, sUnion_singleton] theorem sInter_pair (s t : set Ξ±) : β‹‚β‚€ {s, t} = s ∩ t := (sInter_insert _ _).trans $ by rw [inter_comm, sInter_singleton] @[simp] theorem sUnion_image (f : Ξ± β†’ set Ξ²) (s : set Ξ±) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : Ξ± β†’ set Ξ²) (s : set Ξ±) : β‹‚β‚€ (f '' s) = β‹‚ x ∈ s, f x := Inf_image theorem compl_sUnion (S : set (set Ξ±)) : - ⋃₀ S = β‹‚β‚€ (compl '' S) := set.ext $ assume x, ⟨assume : Β¬ (βˆƒs∈S, x ∈ s), assume s h, match s, h with ._, ⟨t, hs, rfl⟩ := assume h, this ⟨t, hs, h⟩ end, assume : βˆ€s, s ∈ compl '' S β†’ x ∈ s, assume ⟨t, tS, xt⟩, this (compl t) (mem_image_of_mem _ tS) xt⟩ -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set Ξ±)) : ⋃₀ S = - β‹‚β‚€ (compl '' S) := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set Ξ±)) : - β‹‚β‚€ S = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_comp_sUnion_compl (S : set (set Ξ±)) : β‹‚β‚€ S = -(⋃₀ (compl '' S)) := by rw [←compl_compl (β‹‚β‚€ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set Ξ±} {S : set (set Ξ±)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = βˆ…) : s ∩ t = βˆ… := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem Union_eq_sUnion_range (s : Ξ± β†’ set Ξ²) : (⋃ i, s i) = ⋃₀ (range s) := by rw [← image_univ, sUnion_image]; simp theorem Inter_eq_sInter_range {Ξ± I : Type} (s : I β†’ set Ξ±) : (β‹‚ i, s i) = β‹‚β‚€ (range s) := by rw [← image_univ, sInter_image]; simp theorem range_sigma_eq_Union_range {Ξ³ : Ξ± β†’ Type*} (f : sigma Ξ³ β†’ Ξ²) : range f = ⋃ a, range (Ξ» b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : Ξ± β†’ set Ξ²) : (⋃ i, s i) = range (Ξ» a : Ξ£ i, s i, a.2) := by simp [set.ext_iff] lemma sUnion_mono {s t : set (set Ξ±)} (h : s βŠ† t) : (⋃₀ s) βŠ† (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ΞΉ β†’ set Ξ±} (h : βˆ€i, s i βŠ† t i) : (⋃i, s i) βŠ† (⋃i, t i) := @supr_le_supr (set Ξ±) ΞΉ _ s t h lemma Union_subset_Union2 {ΞΉβ‚‚ : Sort*} {s : ΞΉ β†’ set Ξ±} {t : ΞΉβ‚‚ β†’ set Ξ±} (h : βˆ€i, βˆƒj, s i βŠ† t j) : (⋃i, s i) βŠ† (⋃i, t i) := @supr_le_supr2 (set Ξ±) ΞΉ ΞΉβ‚‚ _ s t h lemma Union_subset_Union_const {ΞΉβ‚‚ : Sort x} {s : set Ξ±} (h : ΞΉ β†’ ΞΉβ‚‚) : (⋃ i:ΞΉ, s) βŠ† (⋃ j:ΞΉβ‚‚, s) := @supr_le_supr_const (set Ξ±) ΞΉ ΞΉβ‚‚ _ s h theorem bUnion_subset_Union (s : set Ξ±) (t : Ξ± β†’ set Ξ²) : (⋃ x ∈ s, t x) βŠ† (⋃ x, t x) := Union_subset_Union $ Ξ» i, Union_subset $ Ξ» h, by refl lemma sUnion_eq_bUnion {s : set (set Ξ±)} : (⋃₀ s) = (⋃ (i : set Ξ±) (h : i ∈ s), i) := set.ext $ by simp lemma sInter_eq_bInter {s : set (set Ξ±)} : (β‹‚β‚€ s) = (β‹‚ (i : set Ξ±) (h : i ∈ s), i) := set.ext $ by simp lemma sUnion_eq_Union {s : set (set Ξ±)} : (⋃₀ s) = (⋃ (i : s), i.1) := set.ext $ Ξ» x, by simp lemma sInter_eq_Inter {s : set (set Ξ±)} : (β‹‚β‚€ s) = (β‹‚ (i : s), i.1) := set.ext $ Ξ» x, by simp lemma union_eq_Union {s₁ sβ‚‚ : set Ξ±} : s₁ βˆͺ sβ‚‚ = ⋃ b : bool, cond b s₁ sβ‚‚ := set.ext $ Ξ» x, by simp [bool.exists_bool, or_comm] lemma inter_eq_Inter {s₁ sβ‚‚ : set Ξ±} : s₁ ∩ sβ‚‚ = β‹‚ b : bool, cond b s₁ sβ‚‚ := set.ext $ Ξ» x, by simp [bool.forall_bool, and_comm] instance : complete_boolean_algebra (set Ξ±) := { neg := compl, sub := (\), inf_neg_eq_bot := assume s, ext $ assume x, ⟨assume ⟨h, nh⟩, nh h, false.elim⟩, sup_neg_eq_top := assume s, ext $ assume x, ⟨assume h, trivial, assume _, classical.em $ x ∈ s⟩, le_sup_inf := distrib_lattice.le_sup_inf, sub_eq := assume x y, rfl, infi_sup_le_sup_Inf := assume s t x, show x ∈ (β‹‚ b ∈ t, s βˆͺ b) β†’ x ∈ s βˆͺ (β‹‚β‚€ t), by simp; exact assume h, or.imp_right (assume hn : x βˆ‰ s, assume i hi, or.resolve_left (h i hi) hn) (classical.em $ x ∈ s), inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) β†’ x ∈ (⋃ b ∈ t, s ∩ b), by simp [-and_imp, and.left_comm], ..set.lattice_set } @[simp] theorem sub_eq_diff (s t : set Ξ±) : s - t = s \ t := rfl section variables {p : Prop} {ΞΌ : p β†’ set Ξ±} @[simp] lemma Inter_pos (hp : p) : (β‹‚h:p, ΞΌ h) = ΞΌ hp := infi_pos hp @[simp] lemma Inter_neg (hp : Β¬ p) : (β‹‚h:p, ΞΌ h) = univ := infi_neg hp @[simp] lemma Union_pos (hp : p) : (⋃h:p, ΞΌ h) = ΞΌ hp := supr_pos hp @[simp] lemma Union_neg (hp : Β¬ p) : (⋃h:p, ΞΌ h) = βˆ… := supr_neg hp @[simp] lemma Union_empty {ΞΉ : Sort*} : (⋃i:ΞΉ, βˆ…:set Ξ±) = βˆ… := supr_bot @[simp] lemma Inter_univ {ΞΉ : Sort*} : (β‹‚i:ΞΉ, univ:set Ξ±) = univ := infi_top end section image lemma image_Union {f : Ξ± β†’ Ξ²} {s : ΞΉ β†’ set Ξ±} : f '' (⋃ i, s i) = (⋃i, f '' s i) := begin apply set.ext, intro x, simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right], exact exists_swap end lemma univ_subtype {p : Ξ± β†’ Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) := set.ext $ assume ⟨x, h⟩, by simp [h] end image section preimage theorem monotone_preimage {f : Ξ± β†’ Ξ²} : monotone (preimage f) := assume a b h, preimage_mono h @[simp] theorem preimage_Union {ΞΉ : Sort w} {f : Ξ± β†’ Ξ²} {s : ΞΉ β†’ set Ξ²} : preimage f (⋃i, s i) = (⋃i, preimage f (s i)) := set.ext $ by simp [preimage] theorem preimage_bUnion {ΞΉ} {f : Ξ± β†’ Ξ²} {s : set ΞΉ} {t : ΞΉ β†’ set Ξ²} : preimage f (⋃i ∈ s, t i) = (⋃i ∈ s, preimage f (t i)) := by simp @[simp] theorem preimage_sUnion {f : Ξ± β†’ Ξ²} {s : set (set Ξ²)} : preimage f (⋃₀ s) = (⋃t ∈ s, preimage f t) := set.ext $ by simp [preimage] lemma preimage_Inter {ΞΉ : Sort*} {s : ΞΉ β†’ set Ξ²} {f : Ξ± β†’ Ξ²} : f ⁻¹' (β‹‚ i, s i) = (β‹‚ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : Ξ³ β†’ set Ξ²} {t : set Ξ³} {f : Ξ± β†’ Ξ²} : f ⁻¹' (β‹‚ i∈t, s i) = (β‹‚ i∈t, f ⁻¹' s i) := by ext; simp end preimage section seq def seq (s : set (Ξ± β†’ Ξ²)) (t : set Ξ±) : set Ξ² := {b | βˆƒf∈s, βˆƒa∈t, (f : Ξ± β†’ Ξ²) a = b} lemma seq_def {s : set (Ξ± β†’ Ξ²)} {t : set Ξ±} : seq s t = ⋃f∈s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (Ξ± β†’ Ξ²)} {t : set Ξ±} {b : Ξ²} : b ∈ seq s t ↔ βˆƒ (f ∈ s) (a ∈ t), (f : Ξ± β†’ Ξ²) a = b := iff.refl _ lemma seq_subset {s : set (Ξ± β†’ Ξ²)} {t : set Ξ±} {u : set Ξ²} : seq s t βŠ† u ↔ (βˆ€f∈s, βˆ€a∈t, (f : Ξ± β†’ Ξ²) a ∈ u) := iff.intro (assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (assume h b ⟨f, hf, a, ha, eq⟩, eq β–Έ h f hf a ha) lemma seq_mono {sβ‚€ s₁ : set (Ξ± β†’ Ξ²)} {tβ‚€ t₁ : set Ξ±} (hs : sβ‚€ βŠ† s₁) (ht : tβ‚€ βŠ† t₁) : seq sβ‚€ tβ‚€ βŠ† seq s₁ t₁ := assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : Ξ± β†’ Ξ²} {t : set Ξ±} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (Ξ± β†’ Ξ²)} {a : Ξ±} : set.seq s {a} = (Ξ»f:Ξ±β†’Ξ², f a) '' s := set.ext $ by simp lemma seq_seq {s : set (Ξ² β†’ Ξ³)} {t : set (Ξ± β†’ Ξ²)} {u : set Ξ±} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (assume c, iff.intro _ _), { rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : Ξ² β†’ Ξ³} {s : set (Ξ± β†’ Ξ²)} {t : set Ξ±} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set Ξ±} {t : set Ξ²} : set.prod s t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set Ξ±) (t : set Ξ²) : (prod.mk '' s).seq t = seq ((Ξ»b a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp] end seq theorem monotone_prod [preorder Ξ±] {f : Ξ± β†’ set Ξ²} {g : Ξ± β†’ set Ξ³} (hf : monotone f) (hg : monotone g) : monotone (Ξ»x, set.prod (f x) (g x)) := assume a b h, prod_mono (hf h) (hg h) instance : monad set := { pure := Ξ»(Ξ± : Type u) a, {a}, bind := Ξ»(Ξ± Ξ² : Type u) s f, ⋃i∈s, f i, seq := Ξ»(Ξ± Ξ² : Type u), set.seq, map := Ξ»(Ξ± Ξ² : Type u), set.image } instance : is_lawful_monad set := { pure_bind := assume Ξ± Ξ² x f, by simp, bind_assoc := assume Ξ± Ξ² Ξ³ s f g, set.ext $ assume a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := assume Ξ±, id_map, bind_pure_comp_eq_map := assume Ξ± Ξ² f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := assume Ξ± Ξ² s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u β†’ Type u) := ⟨ assume Ξ± Ξ² s t, prod_image_seq_comm s t ⟩ section monad variables {Ξ±' Ξ²' : Type u} {s : set Ξ±'} {f : Ξ±' β†’ set Ξ²'} {g : set (Ξ±' β†’ Ξ²')} @[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl @[simp] lemma fmap_eq_image (f : Ξ±' β†’ Ξ²') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {Ξ± Ξ² : Type*} (s : set (Ξ± β†’ Ξ²)) (t : set Ξ±) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : Ξ±) : (pure a : set Ξ±) = {a} := rfl end monad section pi lemma pi_def {Ξ± : Type*} {Ο€ : Ξ± β†’ Type*} (i : set Ξ±) (s : Ξ a, set (Ο€ a)) : pi i s = (β‹‚ a∈i, ((Ξ»f:(Ξ a, Ο€ a), f a) ⁻¹' (s a))) := by ext; simp [pi] end pi end set /- disjoint sets -/ section disjoint variable [semilattice_inf_bot Ξ±] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : Ξ±) : Prop := a βŠ“ b ≀ βŠ₯ theorem disjoint.eq_bot {a b : Ξ±} (h : disjoint a b) : a βŠ“ b = βŠ₯ := eq_bot_iff.2 h theorem disjoint_iff {a b : Ξ±} : disjoint a b ↔ a βŠ“ b = βŠ₯ := eq_bot_iff.symm theorem disjoint.comm {a b : Ξ±} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] theorem disjoint.symm {a b : Ξ±} : disjoint a b β†’ disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : Ξ±} : disjoint βŠ₯ a := disjoint_iff.2 bot_inf_eq @[simp] theorem disjoint_bot_right {a : Ξ±} : disjoint a βŠ₯ := disjoint_iff.2 inf_bot_eq theorem disjoint_mono {a b c d : Ξ±} (h₁ : a ≀ b) (hβ‚‚ : c ≀ d) : disjoint b d β†’ disjoint a c := le_trans (inf_le_inf h₁ hβ‚‚) theorem disjoint_mono_left {a b c : Ξ±} (h : a ≀ b) : disjoint b c β†’ disjoint a c := disjoint_mono h (le_refl _) theorem disjoint_mono_right {a b c : Ξ±} (h : b ≀ c) : disjoint a c β†’ disjoint a b := disjoint_mono (le_refl _) h end disjoint theorem set.disjoint_diff {a b : set Ξ±} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) section open set set_option eqn_compiler.zeta true noncomputable def set.bUnion_eq_sigma_of_disjoint {Ξ± Ξ²} {s : set Ξ±} {t : Ξ± β†’ set Ξ²} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Ξ£i:s, t i.val) := let f : (Ξ£i:s, t i.val) β†’ (⋃i∈s, t i) := λ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, ⟨b, mem_bUnion ha hb⟩ in have injective f, from assume ⟨⟨a₁, haβ‚βŸ©, ⟨b₁, hbβ‚βŸ©βŸ© ⟨⟨aβ‚‚, haβ‚‚βŸ©, ⟨bβ‚‚, hbβ‚‚βŸ©βŸ© eq, have b_eq : b₁ = bβ‚‚, from congr_arg subtype.val eq, have a_eq : a₁ = aβ‚‚, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t aβ‚‚, from ⟨hb₁, b_eq.symm β–Έ hbβ‚‚βŸ©, h _ ha₁ _ haβ‚‚ ne this, sigma.eq (subtype.eq a_eq) (subtype.eq $ by subst b_eq; subst a_eq), have surjective f, from assume ⟨b, hb⟩, have βˆƒa∈s, b ∈ t a, by simpa using hb, let ⟨a, ha, hb⟩ := this in ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩, (equiv.of_bijective βŸ¨β€Ήinjective fβ€Ί, β€Ήsurjective fβ€ΊβŸ©).symm end
51a82442cfa164f00a6a0bc29d57e627c9e74983
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Parser/Basic.lean
8ba1bef32d72b096be26a7b45e3e0b6ad08b7c40
[ "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
66,342
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Types /-! # Basic Lean parser infrastructure The Lean parser was developed with the following primary goals in mind: * flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach. * extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens. * losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token" information for the use in tooling. * performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be necessary for this. Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar with a new parser. However, because all the results the combinators produce are of the homogeneous `Syntax` type, the basic parser type is not actually a monad but a monomorphic linear function `ParserState β†’ ParserState`, avoiding constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we usually use the macro `leading_parser p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the declaration being defined. The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser` for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace. The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information: `collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST" token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel. If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator. This is the only case where standard parsers might execute arbitrary backtracking. Repeated invocations of the same category or concrete parser at the same position are cached where possible; see `withCache`. Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly. Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips tokens until the next command keyword on error. -/ namespace Lean.Parser def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn := fun c s => let sz := s.stxStack.size let s' := p c s dbg_trace "{label} pos: {s'.pos} err: {s'.errorMsg} out: {s'.stxStack.extract sz s'.stxStack.size}" s' def dbgTraceState (label : String) : Parser β†’ Parser := withFn (dbgTraceStateFn label) @[noinline]def epsilonInfo : ParserInfo := { firstTokens := FirstTokens.epsilon } def checkStackTopFn (p : Syntax β†’ Bool) (msg : String) : ParserFn := fun _ s => if p s.stxStack.back then s else s.mkUnexpectedError msg def checkStackTop (p : Syntax β†’ Bool) (msg : String) : Parser := { info := epsilonInfo, fn := checkStackTopFn p msg } def andthenFn (p q : ParserFn) : ParserFn := fun c s => let s := p c s if s.hasError then s else q c s @[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.seq q.firstTokens } def andthen (p q : Parser) : Parser := { info := andthenInfo p.info q.info, fn := andthenFn p.fn q.fn } instance : AndThen Parser where andThen a b := andthen a (b ()) def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkNode n iniSz def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkTrailingNode n iniSz @[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := fun s => (p.collectKinds s).insert n, firstTokens := p.firstTokens } def node (n : SyntaxNodeKind) (p : Parser) : Parser := { info := nodeInfo n p.info, fn := nodeFn n p.fn } def errorFn (msg : String) : ParserFn := fun _ s => s.mkUnexpectedError msg def error (msg : String) : Parser := { info := epsilonInfo, fn := errorFn msg } def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s => match c.savedPos? with | none => s | some pos => let pos := if delta then c.input.next pos else pos match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ /-- Generate an error at the position saved with the `withPosition` combinator. If `delta == true`, then it reports at saved position+1. This useful to make sure a parser consumed at least one character. -/ def errorAtSavedPos (msg : String) (delta : Bool) : Parser := { fn := errorAtSavedPosFn msg delta } /-- Succeeds if `c.prec <= prec` -/ def checkPrecFn (prec : Nat) : ParserFn := fun c s => if c.prec <= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" def checkPrec (prec : Nat) : Parser := { info := epsilonInfo fn := checkPrecFn prec } /-- Succeeds if `c.lhsPrec >= prec` -/ def checkLhsPrecFn (prec : Nat) : ParserFn := fun _ s => if s.lhsPrec >= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" def checkLhsPrec (prec : Nat) : Parser := { info := epsilonInfo fn := checkLhsPrecFn prec } def setLhsPrecFn (prec : Nat) : ParserFn := fun _ s => if s.hasError then s else { s with lhsPrec := prec } def setLhsPrec (prec : Nat) : Parser := { info := epsilonInfo fn := setLhsPrecFn prec } private def addQuotDepth (i : Int) (p : Parser) : Parser := adaptCacheableContext (fun c => { c with quotDepth := c.quotDepth + i |>.toNat }) p def incQuotDepth (p : Parser) : Parser := addQuotDepth 1 p def decQuotDepth (p : Parser) : Parser := addQuotDepth (-1) p def suppressInsideQuot : Parser β†’ Parser := adaptCacheableContext fun c => -- if we are already within a quotation, don't change anything if c.quotDepth == 0 then { c with suppressInsideQuot := true } else c def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser := checkPrec prec >> node n p >> setLhsPrec prec def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := { info := nodeInfo n p.info fn := trailingNodeFn n p.fn } def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser := checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : String.Pos) (mergeErrors : Bool) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some error2⟩ => if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩ else s | other => other -- When `p` in `p <|> q` parses exactly one antiquotation, ... inductive OrElseOnAntiquotBehavior where | acceptLhs -- return it | takeLongest -- return result of `q` instead if it made more progress | merge -- ... and create choice node if both made the same progress deriving BEq def orelseFnCore (p q : ParserFn) (antiquotBehavior := OrElseOnAntiquotBehavior.merge) : ParserFn := fun c s => Id.run do let iniSz := s.stackSize let iniPos := s.pos let mut s := p c s match s.errorMsg with | some errorMsg => if s.pos == iniPos then mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos true else s | none => let pBack := s.stxStack.back if antiquotBehavior == .acceptLhs || s.stackSize != iniSz + 1 || !pBack.isAntiquots then return s let pPos := s.pos s := s.restore iniSz iniPos s := q c s if s.hasError then return s.restore iniSz pPos |>.pushSyntax pBack -- If `q` made more progress than `p`, we prefer its result. -- Thus `(structInstField| $id := $val) is interpreted as -- `(structInstField| $id:ident := $val:term), not -- `(structInstField| $id:structInstField <ERROR: expected ')'>. if s.pos > pPos then return s if s.pos < pPos || antiquotBehavior != .merge || s.stackSize != iniSz + 1 || !s.stxStack.back.isAntiquots then return s.restore iniSz pPos |>.pushSyntax pBack -- Pop off result of `q`, push result(s) of `p` and `q` in that order, turn them into a choice node let qBack := s.stxStack.back s := s.popSyntax let pushAntiquots stx s := if stx.isOfKind choiceKind then -- Flatten existing choice node { s with stxStack := s.stxStack ++ stx.getArgs } else s.pushSyntax stx s := pushAntiquots pBack s s := pushAntiquots qBack s s.mkNode choiceKind iniSz def orelseFn (p q : ParserFn) : ParserFn := orelseFnCore p q @[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens collectKinds := p.collectKinds ∘ q.collectKinds firstTokens := p.firstTokens.merge q.firstTokens } /-- Run `p`, falling back to `q` if `p` failed without consuming any input. NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...` is fine as well. -/ def orelse (p q : Parser) : Parser := { info := orelseInfo p.info q.info fn := orelseFn p.fn q.fn } instance : OrElse Parser where orElse a b := orelse a (b ()) @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { collectTokens := info.collectTokens collectKinds := info.collectKinds } def atomicFn (p : ParserFn) : ParserFn := fun c s => let iniPos := s.pos match p c s with | ⟨stack, lhsPrec, _, cache, some msg⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg⟩ | other => other def atomic : Parser β†’ Parser := withFn atomicFn def optionalFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s s.mkNode nullKind iniSz @[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens collectKinds := p.collectKinds firstTokens := p.firstTokens.toOptional } def optionalNoAntiquot (p : Parser) : Parser := { info := optionaInfo p.info fn := optionalFn p.fn } def lookaheadFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s else s.restore iniSz iniPos def lookahead : Parser β†’ Parser := withFn lookaheadFn def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s.restore iniSz iniPos else let s := s.restore iniSz iniPos s.mkUnexpectedError s!"unexpected {msg}" def notFollowedBy (p : Parser) (msg : String) : Parser := { fn := notFollowedByFn p.fn msg } partial def manyAux (p : ParserFn) : ParserFn := fun c s => Id.run do let iniSz := s.stackSize let iniPos := s.pos let mut s := p c s if s.hasError then return if iniPos == s.pos then s.restore iniSz iniPos else s if iniPos == s.pos then return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything" if s.stackSize > iniSz + 1 then s := s.mkNode nullKind iniSz manyAux p c s def manyFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := manyAux p c s s.mkNode nullKind iniSz def manyNoAntiquot (p : Parser) : Parser := { info := noFirstTokenInfo p.info fn := manyFn p.fn } def many1Fn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := andthenFn p (manyAux p) c s s.mkNode nullKind iniSz def many1NoAntiquot : Parser β†’ Parser := withFn many1Fn private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn := let rec parse (pOpt : Bool) (c s) := Id.run do let sz := s.stackSize let pos := s.pos let mut s := p c s if s.hasError then if s.pos > pos then return s.mkNode nullKind iniSz else if pOpt then s := s.restore sz pos return s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete s := s.pushSyntax Syntax.missing return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz let sz := s.stackSize let pos := s.pos s := sep c s if s.hasError then s := s.restore sz pos return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz parse allowTrailingSep c s parse pOpt def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz true c s def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz false c s @[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens collectKinds := p.collectKinds ∘ sep.collectKinds } @[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens collectKinds := p.collectKinds ∘ sep.collectKinds firstTokens := p.firstTokens } def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepByInfo p.info sep.info fn := sepByFn allowTrailingSep p.fn sep.fn } def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepBy1Info p.info sep.info fn := sepBy1Fn allowTrailingSep p.fn sep.fn } /-- Apply `f` to the syntax object produced by `p` -/ def withResultOfFn (p : ParserFn) (f : Syntax β†’ Syntax) : ParserFn := fun c s => let s := p c s if s.hasError then s else let stx := s.stxStack.back s.popSyntax.pushSyntax (f stx) @[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens collectKinds := p.collectKinds } def withResultOf (p : Parser) (f : Syntax β†’ Syntax) : Parser := { info := withResultOfInfo p.info fn := withResultOfFn p.fn f } def many1Unbox (p : Parser) : Parser := withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx partial def satisfyFn (p : Char β†’ Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s => let i := s.pos if h : c.input.atEnd i then s.mkEOIError else if p (c.input.get' i h) then s.next' c.input i h else s.mkUnexpectedError errorMsg partial def takeUntilFn (p : Char β†’ Bool) : ParserFn := fun c s => let i := s.pos if h : c.input.atEnd i then s else if p (c.input.get' i h) then s else takeUntilFn p c (s.next' c.input i h) def takeWhileFn (p : Char β†’ Bool) : ParserFn := takeUntilFn (fun c => !p c) def takeWhile1Fn (p : Char β†’ Bool) (errorMsg : String) : ParserFn := andthenFn (satisfyFn p errorMsg) (takeWhileFn p) variable (pushMissingOnError : Bool) in partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if h : input.atEnd i then eoi s else let curr := input.get' i h let i := input.next' i h if curr == '-' then if h : input.atEnd i then eoi s else let curr := input.get' i h if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next' input i h else finishCommentBlock (nesting-1) c (s.next' input i h) else finishCommentBlock nesting c (s.setPos i) else if curr == '/' then if h : input.atEnd i then eoi s else let curr := input.get' i h if curr == '-' then finishCommentBlock (nesting+1) c (s.next' input i h) else finishCommentBlock nesting c (s.setPos i) else finishCommentBlock nesting c (s.setPos i) where eoi s := s.mkUnexpectedError (pushMissing := pushMissingOnError) "unterminated comment" /-- Consume whitespace and comments -/ partial def whitespace : ParserFn := fun c s => let input := c.input let i := s.pos if h : input.atEnd i then s else let curr := input.get' i h if curr == '\t' then s.mkUnexpectedError (pushMissing := false) "tabs are not allowed; please configure your editor to expand them" else if curr.isWhitespace then whitespace c (s.next' input i h) else if curr == '-' then let i := input.next' i h let curr := input.get i if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i) else s else if curr == '/' then let i := input.next' i h let curr := input.get i if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' || curr == '!' then s -- "/--" and "/-!" doc comment are actual tokens else andthenFn (finishCommentBlock (pushMissingOnError := false) 1) whitespace c (s.next input i) else s else s def mkEmptySubstringAt (s : String) (p : String.Pos) : Substring := { str := s, startPos := p, stopPos := p } private def rawAux (startPos : String.Pos) (trailingWs : Bool) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos if trailingWs then let s := whitespace c s let stopPos' := s.pos let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val)) val s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val)) val s.pushSyntax atom /-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/ def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s => let startPos := s.pos let s := p c s if s.hasError then s else rawAux startPos trailingWs c s def chFn (c : Char) (trailingWs := false) : ParserFn := rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs def rawCh (c : Char) (trailingWs := false) : Parser := { fn := chFn c trailingWs } def hexDigitFn : ParserFn := fun c s => let input := c.input let i := s.pos if h : input.atEnd i then s.mkEOIError else let curr := input.get' i h let i := input.next' i h if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i else s.mkUnexpectedError "invalid hexadecimal numeral" def quotedCharCoreFn (isQuotable : Char β†’ Bool) : ParserFn := fun c s => let input := c.input let i := s.pos if h : input.atEnd i then s.mkEOIError else let curr := input.get' i h if isQuotable curr then s.next' input i h else if curr == 'x' then andthenFn hexDigitFn hexDigitFn c (s.next' input i h) else if curr == 'u' then andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next' input i h) else s.mkUnexpectedError "invalid escape sequence" def isQuotableCharDefault (c : Char) : Bool := c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't' def quotedCharFn : ParserFn := quotedCharCoreFn isQuotableCharDefault /-- Push `(Syntax.node tk <new-atom>)` onto syntax stack if parse was successful. -/ def mkNodeToken (n : SyntaxNodeKind) (startPos : String.Pos) : ParserFn := fun c s => Id.run do if s.hasError then return s let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let info := SourceInfo.original leading startPos trailing stopPos s.pushSyntax (Syntax.mkLit n val info) def charLitFnAux (startPos : String.Pos) : ParserFn := fun c s => let input := c.input let i := s.pos if h : input.atEnd i then s.mkEOIError else let curr := input.get' i h let s := s.setPos (input.next' i h) let s := if curr == '\\' then quotedCharFn c s else s if s.hasError then s else let i := s.pos let curr := input.get i let s := s.setPos (input.next i) if curr == '\'' then mkNodeToken charLitKind startPos c s else s.mkUnexpectedError "missing end of character literal" partial def strLitFnAux (startPos : String.Pos) : ParserFn := fun c s => let input := c.input let i := s.pos if h : input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos else let curr := input.get' i h let s := s.setPos (input.next' i h) if curr == '\"' then mkNodeToken strLitKind startPos c s else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s else strLitFnAux startPos c s def decimalNumberFn (startPos : String.Pos) (c : ParserContext) : ParserState β†’ ParserState := fun s => let s := takeWhileFn (fun c => c.isDigit) c s let input := c.input let i := s.pos let curr := input.get i if curr == '.' || curr == 'e' || curr == 'E' then let s := parseOptDot s let s := parseOptExp s mkNodeToken scientificLitKind startPos c s else mkNodeToken numLitKind startPos c s where parseOptDot s := let input := c.input let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s parseOptExp s := let input := c.input let i := s.pos let curr := input.get i if curr == 'e' || curr == 'E' then let i := input.next i let i := if input.get i == '-' || input.get i == '+' then input.next i else i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.mkUnexpectedError "missing exponent digits in scientific literal" else s def binNumberFn (startPos : String.Pos) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s mkNodeToken numLitKind startPos c s def octalNumberFn (startPos : String.Pos) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => '0' ≀ c && c ≀ '7') "octal number" c s mkNodeToken numLitKind startPos c s def hexNumberFn (startPos : String.Pos) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => ('0' ≀ c && c ≀ '9') || ('a' ≀ c && c ≀ 'f') || ('A' ≀ c && c ≀ 'F')) "hexadecimal number" c s mkNodeToken numLitKind startPos c s def numberFnAux : ParserFn := fun c s => let input := c.input let startPos := s.pos if h : input.atEnd startPos then s.mkEOIError else let curr := input.get' startPos h if curr == '0' then let i := input.next' startPos h let curr := input.get i if curr == 'b' || curr == 'B' then binNumberFn startPos c (s.next input i) else if curr == 'o' || curr == 'O' then octalNumberFn startPos c (s.next input i) else if curr == 'x' || curr == 'X' then hexNumberFn startPos c (s.next input i) else decimalNumberFn startPos c (s.setPos i) else if curr.isDigit then decimalNumberFn startPos c (s.next input startPos) else s.mkError "numeral" def isIdCont : String β†’ ParserState β†’ Bool := fun input s => let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i if input.atEnd i then false else let curr := input.get i isIdFirst curr || isIdBeginEscape curr else false private def isToken (idStartPos idStopPos : String.Pos) (tk : Option Token) : Bool := match tk with | none => false | some tk => -- if a token is both a symbol and a valid identifier (i.e. a keyword), -- we want it to be recognized as a symbol tk.endPos β‰₯ idStopPos - idStartPos def mkTokenAndFixPos (startPos : String.Pos) (tk : Option Token) : ParserFn := fun c s => match tk with | none => s.mkErrorAt "token" startPos | some tk => if c.forbiddenTk? == some tk then s.mkErrorAt "forbidden token" startPos else let input := c.input let leading := mkEmptySubstringAt input startPos let stopPos := startPos + tk let s := s.setPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing stopPos) tk s.pushSyntax atom def mkIdResult (startPos : String.Pos) (tk : Option Token) (val : Name) : ParserFn := fun c s => let stopPos := s.pos if isToken startPos stopPos tk then mkTokenAndFixPos startPos tk c s else let input := c.input let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring } let s := whitespace c s let trailingStopPos := s.pos let leading := mkEmptySubstringAt input startPos let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring } let info := SourceInfo.original leading startPos trailing stopPos let atom := mkIdent info rawVal val s.pushSyntax atom partial def identFnAux (startPos : String.Pos) (tk : Option Token) (r : Name) : ParserFn := let rec parse (r : Name) (c s) := let input := c.input let i := s.pos if h : input.atEnd i then s.mkEOIError else let curr := input.get' i h if isIdBeginEscape curr then let startPart := input.next' i h let s := takeUntilFn isIdEndEscape c (s.setPos startPart) if h : input.atEnd s.pos then s.mkUnexpectedErrorAt "unterminated identifier escape" startPart else let stopPart := s.pos let s := s.next' c.input s.pos h let r := .str r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else if isIdFirst curr then let startPart := i let s := takeWhileFn isIdRest c (s.next input i) let stopPart := s.pos let r := .str r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else mkTokenAndFixPos startPos tk c s parse r private def isIdFirstOrBeginEscape (c : Char) : Bool := isIdFirst c || isIdBeginEscape c private def nameLitAux (startPos : String.Pos) : ParserFn := fun c s => let input := c.input let s := identFnAux startPos none .anonymous c (s.next input startPos) if s.hasError then s else let stx := s.stxStack.back match stx with | .ident info rawStr _ _ => let s := s.popSyntax s.pushSyntax (Syntax.mkNameLit rawStr.toString info) | _ => s.mkError "invalid Name literal" private def tokenFnAux : ParserFn := fun c s => let input := c.input let i := s.pos let curr := input.get i if curr == '\"' then strLitFnAux i c (s.next input i) else if curr == '\'' && getNext input i != '\'' then charLitFnAux i c (s.next input i) else if curr.isDigit then numberFnAux c s else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then nameLitAux i c s else let (_, tk) := c.tokens.matchPrefix input i identFnAux i tk .anonymous c s private def updateTokenCache (startPos : String.Pos) (s : ParserState) : ParserState := -- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache` match s with | ⟨stack, lhsPrec, pos, ⟨_, catCache⟩, none⟩ => if stack.size == 0 then s else let tk := stack.back ⟨stack, lhsPrec, pos, ⟨{ startPos := startPos, stopPos := pos, token := tk }, catCache⟩, none⟩ | other => other def tokenFn (expected : List String := []) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError expected else let tkc := s.cache.tokenCache if tkc.startPos == i then let s := s.pushSyntax tkc.token s.setPos tkc.stopPos else let s := tokenFnAux c s updateTokenCache i s def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState Γ— Except ParserState Syntax := let iniSz := s.stackSize let iniPos := s.pos let s := tokenFn [] c s if let some _ := s.errorMsg then (s.restore iniSz iniPos, .error s) else let stx := s.stxStack.back (s.restore iniSz iniPos, .ok stx) def peekToken (c : ParserContext) (s : ParserState) : ParserState Γ— Except ParserState Syntax := let tkc := s.cache.tokenCache if tkc.startPos == s.pos then (s, .ok tkc.token) else peekTokenAux c s /-- Treat keywords as identifiers. -/ def rawIdentFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else identFnAux i none .anonymous c s def satisfySymbolFn (p : String β†’ Bool) (expected : List String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn expected c s if s.hasError then s else match s.stxStack.back with | .atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz | _ => s.mkErrorsAt expected startPos initStackSz def symbolFnAux (sym : String) (errorMsg : String) : ParserFn := satisfySymbolFn (fun s => s == sym) [errorMsg] def symbolInfo (sym : String) : ParserInfo := { collectTokens := fun tks => sym :: tks firstTokens := FirstTokens.tokens [ sym ] } def symbolFn (sym : String) : ParserFn := symbolFnAux sym ("'" ++ sym ++ "'") def symbolNoAntiquot (sym : String) : Parser := let sym := sym.trim { info := symbolInfo sym fn := symbolFn sym } def checkTailNoWs (prev : Syntax) : Bool := match prev.getTailInfo with | .original _ _ trailing _ => trailing.stopPos == trailing.startPos | _ => false /-- Check if the following token is the symbol _or_ identifier `sym`. Useful for parsing local tokens that have not been added to the token table (but may have been so by some unrelated code). For example, the universe `max` Function is parsed using this combinator so that it can still be used as an identifier outside of universe (but registering it as a token in a Term Syntax would not break the universe Parser). -/ def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn [errorMsg] c s if s.hasError then s else match s.stxStack.back with | .atom _ sym' => if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz | .ident info rawVal _ _ => if sym == rawVal.toString then let s := s.popSyntax s.pushSyntax (Syntax.atom info sym) else s.mkErrorAt errorMsg startPos initStackSz | _ => s.mkErrorAt errorMsg startPos initStackSz def nonReservedSymbolFn (sym : String) : ParserFn := nonReservedSymbolFnAux sym ("'" ++ sym ++ "'") def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := { firstTokens := if includeIdent then .tokens [ sym, "ident" ] else .tokens [ sym ] } def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser := let sym := sym.trim { info := nonReservedSymbolInfo sym includeIdent, fn := nonReservedSymbolFn sym } partial def strAux (sym : String) (errorMsg : String) (j : String.Pos) :ParserFn := let rec parse (j c s) := if h₁ : sym.atEnd j then s else let i := s.pos let input := c.input if hβ‚‚ : input.atEnd i then s.mkError errorMsg else if sym.get' j h₁ != input.get' i hβ‚‚ then s.mkError errorMsg else parse (sym.next' j h₁) c (s.next' input i hβ‚‚) parse j def checkTailWs (prev : Syntax) : Bool := match prev.getTailInfo with | .original _ _ trailing _ => trailing.stopPos > trailing.startPos | _ => false def checkWsBeforeFn (errorMsg : String) : ParserFn := fun _ s => let prev := s.stxStack.back if checkTailWs prev then s else s.mkError errorMsg def checkWsBefore (errorMsg : String := "space before") : Parser := { info := epsilonInfo fn := checkWsBeforeFn errorMsg } def checkTailLinebreak (prev : Syntax) : Bool := match prev.getTailInfo with | .original _ _ trailing _ => trailing.contains '\n' | _ => false def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun _ s => let prev := s.stxStack.back if checkTailLinebreak prev then s else s.mkError errorMsg def checkLinebreakBefore (errorMsg : String := "line break") : Parser := { info := epsilonInfo fn := checkLinebreakBeforeFn errorMsg } private def pickNonNone (stack : SyntaxStack) : Syntax := match stack.toSubarray.findRev? fun stx => !stx.isNone with | none => Syntax.missing | some stx => stx def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun _ s => let prev := pickNonNone s.stxStack if checkTailNoWs prev then s else s.mkError errorMsg def checkNoWsBefore (errorMsg : String := "no space before") : Parser := { info := epsilonInfo fn := checkNoWsBeforeFn errorMsg } def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn := satisfySymbolFn (fun s => s == sym || s == asciiSym) expected def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := { collectTokens := fun tks => sym :: asciiSym :: tks firstTokens := FirstTokens.tokens [ sym, asciiSym ] } def unicodeSymbolFn (sym asciiSym : String) : ParserFn := unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser := let sym := sym.trim let asciiSym := asciiSym.trim { info := unicodeSymbolInfo sym asciiSym fn := unicodeSymbolFn sym asciiSym } def mkAtomicInfo (k : String) : ParserInfo := { firstTokens := FirstTokens.tokens [ k ] } def numLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["numeral"] c s if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s def numLitNoAntiquot : Parser := { fn := numLitFn info := mkAtomicInfo "num" } def scientificLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["scientific number"] c s if !s.hasError && !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos initStackSz else s def scientificLitNoAntiquot : Parser := { fn := scientificLitFn info := mkAtomicInfo "scientific" } def strLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["string literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos initStackSz else s def strLitNoAntiquot : Parser := { fn := strLitFn info := mkAtomicInfo "str" } def charLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["char literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos initStackSz else s def charLitNoAntiquot : Parser := { fn := charLitFn info := mkAtomicInfo "char" } def nameLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["Name literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos initStackSz else s def nameLitNoAntiquot : Parser := { fn := nameLitFn info := mkAtomicInfo "name" } def identFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if !s.hasError && !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos initStackSz else s def identNoAntiquot : Parser := { fn := identFn info := mkAtomicInfo "ident" } def rawIdentNoAntiquot : Parser := { fn := rawIdentFn } def identEqFn (id : Name) : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if s.hasError then s else match s.stxStack.back with | .ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos initStackSz else s | _ => s.mkErrorAt "identifier" iniPos initStackSz def identEq (id : Name) : Parser := { fn := identEqFn id info := mkAtomicInfo "ident" } def hygieneInfoFn : ParserFn := fun c s => Id.run do let input := c.input let finish pos str trailing s := -- Builds an actual hygieneInfo node from empty string `str` and trailing whitespace `trailing`. let info := SourceInfo.original str pos trailing pos let ident := mkIdent info str .anonymous let stx := mkNode hygieneInfoKind #[ident] s.pushSyntax stx -- If we are at the whitespace after a token, the last item on the stack -- will have trailing whitespace. We want to position this hygieneInfo -- item immediately after the last token, and reattribute the trailing whitespace -- to the hygieneInfo node itself. This allows combinators like `ws` to -- be unaffected by `hygieneInfo` parsers before or after, see `2262.lean`. if !s.stxStack.isEmpty then let prev := s.stxStack.back if let .original leading pos trailing endPos := prev.getTailInfo then let str := mkEmptySubstringAt input endPos -- steal the trailing whitespace from the last node and use it for this node let s := s.popSyntax.pushSyntax <| prev.setTailInfo (.original leading pos str endPos) return finish endPos str trailing s -- The stack can be empty if this is either the first token, or if we are in a fresh cache. -- In that case we just put the hygieneInfo at the current location. let str := mkEmptySubstringAt input s.pos finish s.pos str str s def hygieneInfoNoAntiquot : Parser := { fn := hygieneInfoFn info := nodeInfo hygieneInfoKind epsilonInfo } namespace ParserState def keepTop (s : SyntaxStack) (startStackSize : Nat) : SyntaxStack := let node := s.back s.shrink startStackSize |>.push node def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => ⟨keepTop stack oldStackSize, lhsPrec, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) (oldLhsPrec : Nat) : ParserState := match s with | ⟨stack, _, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldLhsPrec, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some err⟩ => ⟨stack.shrink oldStackSize, lhsPrec, pos, cache, if oldError == err then some err else some (oldError.merge err)⟩ | other => other def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨keepTop stack startStackSize, lhsPrec, pos, cache, none⟩ def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState := s.keepLatest startStackSize end ParserState def invalidLongestMatchParser (s : ParserState) : ParserState := s.mkError "longestMatch parsers must generate exactly one Syntax node" /-- Auxiliary function used to execute parsers provided to `longestMatchFn`. Push `left?` into the stack if it is not `none`, and execute `p`. Remark: `p` must produce exactly one syntax node. Remark: the `left?` is not none when we are processing trailing parsers. -/ def runLongestMatchParser (left? : Option Syntax) (startLhsPrec : Nat) (p : ParserFn) : ParserFn := fun c s => Id.run do /- We assume any registered parser `p` has one of two forms: * a direct call to `leadingParser` or `trailingParser` * a direct call to a (leading) token parser In the first case, we can extract the precedence of the parser by having `leadingParser/trailingParser` set `ParserState.lhsPrec` to it in the very end so that no nested parser can interfere. In the second case, the precedence is effectively `max` (there is a `checkPrec` merely for the convenience of the pretty printer) and there are no nested `leadingParser/trailingParser` calls, so the value of `lhsPrec` will not be changed by the parser (nor will it be read by any leading parser). Thus we initialize the field to `maxPrec` in the leading case. -/ let mut s := { s with lhsPrec := if left?.isSome then startLhsPrec else maxPrec } let startSize := s.stackSize if let some left := left? then s := s.pushSyntax left s := p c s -- stack contains `[..., result ]` if s.stackSize == startSize + 1 then s -- success or error with the expected number of nodes else if s.hasError then -- error with an unexpected number of nodes. s.shrinkStack startSize |>.pushSyntax Syntax.missing else -- parser succeded with incorrect number of nodes invalidLongestMatchParser s def longestMatchStep (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn) : ParserContext β†’ ParserState β†’ ParserState Γ— Nat := fun c s => let score (s : ParserState) (prio : Nat) := (s.pos.byteIdx, if s.errorMsg.isSome then (0 : Nat) else 1, prio) let previousScore := score s prevPrio let prevErrorMsg := s.errorMsg let prevStopPos := s.pos let prevSize := s.stackSize let prevLhsPrec := s.lhsPrec let s := s.restore prevSize startPos let s := runLongestMatchParser left? startLhsPrec p c s match (let _ := @lexOrd; compare previousScore (score s prio)) with | .lt => (s.keepNewError startSize, prio) | .gt => (s.keepPrevError prevSize prevStopPos prevErrorMsg prevLhsPrec, prevPrio) | .eq => match prevErrorMsg with | none => -- it is not clear what the precedence of a choice node should be, so we conservatively take the minimum ({s with lhsPrec := s.lhsPrec.min prevLhsPrec }, prio) | some oldError => (s.mergeErrors prevSize oldError, prio) def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState := if s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s def longestMatchFnAux (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser Γ— Nat)) : ParserFn := let rec parse (prevPrio : Nat) (ps : List (Parser Γ— Nat)) := match ps with | [] => fun _ s => longestMatchMkResult startSize s | p::ps => fun c s => let (s, prevPrio) := longestMatchStep left? startSize startLhsPrec startPos prevPrio p.2 p.1.fn c s parse prevPrio ps c s parse prevPrio ps def longestMatchFn (left? : Option Syntax) : List (Parser Γ— Nat) β†’ ParserFn | [] => fun _ s => s.mkError "longestMatch: empty list" | [p] => fun c s => runLongestMatchParser left? s.lhsPrec p.1.fn c s | p::ps => fun c s => let startSize := s.stackSize let startLhsPrec := s.lhsPrec let startPos := s.pos let s := runLongestMatchParser left? s.lhsPrec p.1.fn c s longestMatchFnAux left? startSize startLhsPrec startPos p.2 ps c s def anyOfFn : List Parser β†’ ParserFn | [], _, s => s.mkError "anyOf: empty list" | [p], c, s => p.fn c s | p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s def checkColEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column = savedPos.column then s else s.mkError errorMsg def checkColEq (errorMsg : String := "checkColEq") : Parser := { fn := checkColEqFn errorMsg } def checkColGeFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column β‰₯ savedPos.column then s else s.mkError errorMsg def checkColGe (errorMsg : String := "checkColGe") : Parser := { fn := checkColGeFn errorMsg } def checkColGtFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column > savedPos.column then s else s.mkError errorMsg def checkColGt (errorMsg : String := "checkColGt") : Parser := { fn := checkColGtFn errorMsg } def checkLineEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.line == savedPos.line then s else s.mkError errorMsg def checkLineEq (errorMsg : String := "checkLineEq") : Parser := { fn := checkLineEqFn errorMsg } def withPosition : Parser β†’ Parser := withFn fun f c s => adaptCacheableContextFn ({ Β· with savedPos? := s.pos }) f c s def withPositionAfterLinebreak : Parser β†’ Parser := withFn fun f c s => let prev := s.stxStack.back adaptCacheableContextFn (fun c => if checkTailLinebreak prev then { c with savedPos? := s.pos } else c) f c s def withoutPosition (p : Parser) : Parser := adaptCacheableContext ({ Β· with savedPos? := none }) p def withForbidden (tk : Token) (p : Parser) : Parser := adaptCacheableContext ({ Β· with forbiddenTk? := tk }) p def withoutForbidden (p : Parser) : Parser := adaptCacheableContext ({ Β· with forbiddenTk? := none }) p def eoiFn : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else s.mkError "expected end of file" def eoi : Parser := { fn := eoiFn } /-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/ def TokenMap (Ξ± : Type) := RBMap Name (List Ξ±) Name.quickCmp namespace TokenMap def insert (map : TokenMap Ξ±) (k : Name) (v : Ξ±) : TokenMap Ξ± := match map.find? k with | none => .insert map k [v] | some vs => .insert map k (v::vs) instance : Inhabited (TokenMap Ξ±) where default := RBMap.empty instance : EmptyCollection (TokenMap Ξ±) := ⟨RBMap.empty⟩ instance : ForIn m (TokenMap Ξ±) (Name Γ— List Ξ±) := inferInstanceAs (ForIn _ (RBMap ..) _) end TokenMap structure PrattParsingTables where leadingTable : TokenMap (Parser Γ— Nat) := {} leadingParsers : List (Parser Γ— Nat) := [] -- for supporting parsers we cannot obtain first token trailingTable : TokenMap (Parser Γ— Nat) := {} trailingParsers : List (Parser Γ— Nat) := [] -- for supporting parsers such as function application instance : Inhabited PrattParsingTables where default := {} /-- The type `LeadingIdentBehavior` specifies how the parsing table lookup function behaves for identifiers. The function `prattParser` uses two tables `leadingTable` and `trailingTable`. They map tokens to parsers. We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both` and `nonReservedSymbol` parser to implement the `tactic` parsers. The idea is to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users may still use these symbols as identifiers (e.g., naming a function). -/ inductive LeadingIdentBehavior where /-- `LeadingIdentBehavior.default`: if the leading token is an identifier, then `prattParser` just executes the parsers associated with the auxiliary token "ident". -/ | default /-- `LeadingIdentBehavior.symbol`: if the leading token is an identifier `<foo>`, and there are parsers `P` associated with the token `<foo>`, then it executes `P`. Otherwise, it executes only the parsers associated with the auxiliary token "ident". -/ | symbol /-- `LeadingIdentBehavior.both`: if the leading token an identifier `<foo>`, the it executes the parsers associated with token `<foo>` and parsers associated with the auxiliary token "ident". -/ | both deriving Inhabited, BEq, Repr /-- Each parser category is implemented using a Pratt's parser. The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`. Users and plugins may define extra categories. The method ``` categoryParser `term prec ``` executes the Pratt's parser for category `term` with precedence `prec`. That is, only parsers with precedence at least `prec` are considered. The method `termParser prec` is equivalent to the method above. -/ structure ParserCategory where /-- The name of a declaration which will be used as the target of go-to-definition queries and from which doc strings will be extracted. This is a dummy declaration of type `Lean.Parser.Category` created by `declare_syntax_cat`, but for builtin categories the declaration is made manually and passed to `registerBuiltinParserAttribute`. -/ declName : Name /-- The list of syntax nodes that can parse into this category. This can be used to list all syntaxes in the category. -/ kinds : SyntaxNodeKindSet := {} /-- The parsing tables, which consist of a dynamic set of parser functions based on the syntaxes that have been declared so far. -/ tables : PrattParsingTables := {} /-- The `LeadingIdentBehavior`, which specifies how the parsing table lookup function behaves for the first identifier to be parsed. This is used by the `tactic` parser to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). -/ behavior : LeadingIdentBehavior deriving Inhabited abbrev ParserCategories := PersistentHashMap Name ParserCategory def indexed {Ξ± : Type} (map : TokenMap Ξ±) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState Γ— List Ξ± := let (s, stx) := peekToken c s let find (n : Name) : ParserState Γ— List Ξ± := match map.find? n with | some as => (s, as) | _ => (s, []) match stx with | .ok (.atom _ sym) => find (.mkSimple sym) | .ok (.ident _ _ val _) => match behavior with | .default => find identKind | .symbol => match map.find? val with | some as => (s, as) | none => find identKind | .both => match map.find? val with | some as => if val == identKind then (s, as) -- avoid running the same parsers twice else match map.find? identKind with | some as' => (s, as ++ as') | _ => (s, as) | none => find identKind | .ok (.node _ k _) => find k | .ok _ => (s, []) | .error s' => (s', []) abbrev CategoryParserFn := Name β†’ ParserFn builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun (_ : Name) => whitespace builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get def categoryParserFn (catName : Name) : ParserFn := fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s def categoryParser (catName : Name) (prec : Nat) : Parser where fn := adaptCacheableContextFn ({ Β· with prec }) (withCacheFn catName (categoryParserFn catName)) -- Define `termParser` here because we need it for antiquotations def termParser (prec : Nat := 0) : Parser := categoryParser `term prec -- ================== /-! # Antiquotations -/ -- ================== /-- Fail if previous token is immediately followed by ':'. -/ def checkNoImmediateColon : Parser := { fn := fun c s => let prev := s.stxStack.back if checkTailNoWs prev then let input := c.input let i := s.pos if h : input.atEnd i then s else let curr := input.get' i h if curr == ':' then s.mkUnexpectedError "unexpected ':'" else s else s } def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s => match p c s with | s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected } } | s' => s' def setExpected (expected : List String) : Parser β†’ Parser := withFn (setExpectedFn expected) def pushNone : Parser := { fn := fun _ s => s.pushSyntax mkNullNode } -- We support three kinds of antiquotations: `$id`, `$_`, and `$(t)`, where `id` is a term identifier and `t` is a term. def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> decQuotDepth termParser >> symbolNoAntiquot ")") def antiquotExpr : Parser := identNoAntiquot <|> symbolNoAntiquot "_" <|> antiquotNestedExpr def tokenAntiquotFn : ParserFn := fun c s => Id.run do if s.hasError then return s let iniSz := s.stackSize let iniPos := s.pos let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s if s.hasError then return s.restore iniSz iniPos s.mkNode (`token_antiquot) (iniSz - 1) def tokenWithAntiquot : Parser β†’ Parser := withFn fun f c s => let s := f c s -- fast check that is false in most cases if c.input.get s.pos == '%' then tokenAntiquotFn c s else s def symbol (sym : String) : Parser := tokenWithAntiquot (symbolNoAntiquot sym) instance : Coe String Parser where coe := symbol def nonReservedSymbol (sym : String) (includeIdent := false) : Parser := tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent) def unicodeSymbol (sym asciiSym : String) : Parser := tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym) /-- Define parser for `$e` (if `anonymous == true`) and `$e:name`. `kind` is embedded in the antiquotation's kind, and checked at syntax `match` unless `isPseudoKind` is true. Antiquotations can be escaped as in `$$e`, which produces the syntax tree for `$e`. -/ def mkAntiquot (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := false) : Parser := let kind := kind ++ (if isPseudoKind then `pseudo else .anonymous) ++ `antiquot let nameP := node `antiquotName <| checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name -- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different -- antiquotation kind via `noImmediateColon` let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP -- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error leadingNode kind maxPrec <| atomic <| setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> antiquotExpr >> nameP def withAntiquotFn (antiquotP p : ParserFn) (isCatAntiquot := false) : ParserFn := fun c s => -- fast check that is false in most cases if c.input.get s.pos == '$' then -- Do not allow antiquotation choice nodes here as `antiquotP` is the strictly more general -- antiquotation than any in `p`. -- If it is a category antiquotation, do not backtrack into the category at all as that would -- run *all* parsers of the category, and trailing parsers will later be applied anyway. orelseFnCore (antiquotBehavior := if isCatAntiquot then .acceptLhs else .takeLongest) antiquotP p c s else p c s /-- Optimized version of `mkAntiquot ... <|> p`. -/ def withAntiquot (antiquotP p : Parser) : Parser := { fn := withAntiquotFn antiquotP.fn p.fn info := orelseInfo antiquotP.info p.info } def withoutInfo (p : Parser) : Parser := { fn := p.fn } /-- Parse `$[p]suffix`, e.g. `$[p],*`. -/ def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := let kind := kind ++ `antiquot_scope leadingNode kind maxPrec <| atomic <| setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >> suffix private def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (suffix : ParserFn) : ParserFn := fun c s => Id.run do let iniSz := s.stackSize let iniPos := s.pos let s := suffix c s if s.hasError then return s.restore iniSz iniPos s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2) /-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/ def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser where info := andthenInfo p.info suffix.info fn c s := let s := p.fn c s -- fast check that is false in most cases if !s.hasError && s.stxStack.back.isAntiquots then withAntiquotSuffixSpliceFn kind suffix.fn c s else s def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) := -- prevent `p`'s info from being collected twice withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix) def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser := withAntiquot (mkAntiquot name kind anonymous) $ node kind p -- ========================= /-! # End of Antiquotations -/ -- ========================= def sepByElemParser (p : Parser) (sep : String) : Parser := withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*")) def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep private def mkResult (s : ParserState) (iniSz : Nat) : ParserState := if s.stackSize == iniSz + 1 then s else s.mkNode nullKind iniSz -- throw error instead? def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => Id.run do let iniSz := s.stackSize let (s, ps) := indexed tables.leadingTable c s behavior if s.hasError then return s let ps := tables.leadingParsers ++ ps if ps.isEmpty then return s.mkError (toString kind) let s := longestMatchFn none ps c s mkResult s iniSz def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := withAntiquotFn (isCatAntiquot := true) antiquotParser (leadingParserAux kind tables behavior) def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser Γ— Nat)) : ParserFn := fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := Id.run do let iniSz := s.stackSize let iniPos := s.pos let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default if s.hasError then -- Discard token parse errors and break the trailing loop instead. -- The error will be flagged when the next leading position is parsed, unless the token -- is in fact valid there (e.g. EOI at command level, no-longer forbidden token) return s.restore iniSz iniPos if ps.isEmpty && tables.trailingParsers.isEmpty then return s -- no available trailing parser let left := s.stxStack.back let s := s.popSyntax let s := trailingLoopStep tables left ps c s if s.hasError then -- Discard non-consuming parse errors and break the trailing loop instead, restoring `left`. -- This is necessary for fallback parsers like `app` that pretend to be always applicable. return if s.pos == iniPos then s.restore (iniSz - 1) iniPos |>.pushSyntax left else s trailingLoop tables c s /-- Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power. In our implementation, parsers have precedence instead. This method selects a parser (or more, via `longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example: ``` syntax term:51 "≀" ident "<" term "|" term : index ``` Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`. After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`. Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible, modular and easier to understand. `antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers. It should not be added to the regular leading parsers because it would heavily overlap with antiquotation parsers nested inside them. -/ def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s => let s := leadingParser kind tables behavior antiquotParser c s if s.hasError then s else trailingLoop tables c s def fieldIdxFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let curr := c.input.get iniPos if curr.isDigit && curr != '0' then let s := takeWhileFn (fun c => c.isDigit) c s mkNodeToken fieldIdxKind iniPos c s else s.mkErrorAt "field index" iniPos initStackSz def fieldIdx : Parser := withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) { fn := fieldIdxFn info := mkAtomicInfo "fieldIdx" } def skip : Parser := { fn := fun _ s => s info := epsilonInfo } end Parser namespace Syntax section variable [Monad m] def foldArgsM (s : Syntax) (f : Syntax β†’ Ξ² β†’ m Ξ²) (b : Ξ²) : m Ξ² := s.getArgs.foldlM (flip f) b def foldArgs (s : Syntax) (f : Syntax β†’ Ξ² β†’ Ξ²) (b : Ξ²) : Ξ² := Id.run (s.foldArgsM f b) def forArgsM (s : Syntax) (f : Syntax β†’ m Unit) : m Unit := s.foldArgsM (fun s _ => f s) () end end Syntax end Lean
dec1113f8ba99c44d52b28bc1484c3d1664825d7
b2e508d02500f1512e1618150413e6be69d9db10
/src/measure_theory/outer_measure.lean
b169d5e90568f50b0425b707ad9eaedbddcdf94d
[ "Apache-2.0" ]
permissive
callum-sutton/mathlib
c3788f90216e9cd43eeffcb9f8c9f959b3b01771
afd623825a3ac6bfbcc675a9b023edad3f069e89
refs/heads/master
1,591,371,888,053
1,560,990,690,000
1,560,990,690,000
192,476,045
0
0
Apache-2.0
1,568,941,843,000
1,560,837,965,000
Lean
UTF-8
Lean
false
false
19,618
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 Outer measures -- overapproximations of measures -/ import algebra.big_operators algebra.module topology.instances.ennreal analysis.specific_limits measure_theory.measurable_space noncomputable theory open set lattice finset function filter encodable local attribute [instance] classical.prop_decidable namespace measure_theory structure outer_measure (Ξ± : Type*) := (measure_of : set Ξ± β†’ ennreal) (empty : measure_of βˆ… = 0) (mono : βˆ€{s₁ sβ‚‚}, s₁ βŠ† sβ‚‚ β†’ measure_of s₁ ≀ measure_of sβ‚‚) (Union_nat : βˆ€(s:β„• β†’ set Ξ±), measure_of (⋃i, s i) ≀ (βˆ‘i, measure_of (s i))) namespace outer_measure instance {Ξ±} : has_coe_to_fun (outer_measure Ξ±) := ⟨_, Ξ» m, m.measure_of⟩ section basic variables {Ξ± : Type*} {ms : set (outer_measure Ξ±)} {m : outer_measure Ξ±} @[simp] theorem empty' (m : outer_measure Ξ±) : m βˆ… = 0 := m.empty theorem mono' (m : outer_measure Ξ±) {s₁ sβ‚‚} (h : s₁ βŠ† sβ‚‚) : m s₁ ≀ m sβ‚‚ := m.mono h theorem Union_aux (m : set Ξ± β†’ ennreal) (m0 : m βˆ… = 0) {Ξ²} [encodable Ξ²] (s : Ξ² β†’ set Ξ±) : (βˆ‘ b, m (s b)) = βˆ‘ i, m (⋃ b ∈ decode2 Ξ² i, s b) := begin have H : βˆ€ n, m (⋃ b ∈ decode2 Ξ² n, s b) β‰  0 β†’ (decode2 Ξ² n).is_some, { intros n h, cases decode2 Ξ² n with b, { exact (h (by simp [m0])).elim }, { exact rfl } }, refine tsum_eq_tsum_of_ne_zero_bij (Ξ» n h, option.get (H n h)) _ _ _, { intros m n hm hn e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨encode b, _, _⟩, { convert h, simp [ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { intros n h, transitivity, swap, rw [show decode2 Ξ² n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end protected theorem Union (m : outer_measure Ξ±) {Ξ²} [encodable Ξ²] (s : Ξ² β†’ set Ξ±) : m (⋃i, s i) ≀ (βˆ‘i, m (s i)) := by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _ lemma Union_null (m : outer_measure Ξ±) {Ξ²} [encodable Ξ²] {s : Ξ² β†’ set Ξ±} (h : βˆ€ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma union (m : outer_measure Ξ±) (s₁ sβ‚‚ : set Ξ±) : m (s₁ βˆͺ sβ‚‚) ≀ m s₁ + m sβ‚‚ := begin convert m.Union (Ξ» b, cond b s₁ sβ‚‚), { simp [union_eq_Union] }, { rw tsum_fintype, change _ = _ + _, simp } end lemma union_null (m : outer_measure Ξ±) {s₁ sβ‚‚ : set Ξ±} (h₁ : m s₁ = 0) (hβ‚‚ : m sβ‚‚ = 0) : m (s₁ βˆͺ sβ‚‚) = 0 := by simpa [h₁, hβ‚‚] using m.union s₁ sβ‚‚ @[extensionality] lemma ext : βˆ€{μ₁ ΞΌβ‚‚ : outer_measure Ξ±}, (βˆ€s, μ₁ s = ΞΌβ‚‚ s) β†’ μ₁ = ΞΌβ‚‚ | ⟨m₁, e₁, _, uβ‚βŸ© ⟨mβ‚‚, eβ‚‚, _, uβ‚‚βŸ© h := by congr; exact funext h instance : has_zero (outer_measure Ξ±) := ⟨{ measure_of := Ξ»_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem zero_apply (s : set Ξ±) : (0 : outer_measure Ξ±) s = 0 := rfl instance : inhabited (outer_measure Ξ±) := ⟨0⟩ instance : has_add (outer_measure Ξ±) := ⟨λm₁ mβ‚‚, { measure_of := Ξ»s, m₁ s + mβ‚‚ s, empty := show m₁ βˆ… + mβ‚‚ βˆ… = 0, by simp [outer_measure.empty], mono := assume s₁ sβ‚‚ h, add_le_add' (m₁.mono h) (mβ‚‚.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + mβ‚‚ (⋃i, s i) ≀ (βˆ‘i, m₁ (s i)) + (βˆ‘i, mβ‚‚ (s i)) : add_le_add' (m₁.Union_nat s) (mβ‚‚.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem add_apply (m₁ mβ‚‚ : outer_measure Ξ±) (s : set Ξ±) : (m₁ + mβ‚‚) s = m₁ s + mβ‚‚ s := rfl instance : add_comm_monoid (outer_measure Ξ±) := { zero := 0, add := (+), add_comm := assume a b, ext $ assume s, add_comm _ _, add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _, add_zero := assume a, ext $ assume s, add_zero _, zero_add := assume a, ext $ assume s, zero_add _ } instance : has_bot (outer_measure Ξ±) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure Ξ±) := { le := Ξ»m₁ mβ‚‚, βˆ€s, m₁ s ≀ mβ‚‚ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure Ξ±) := ⟨λms, { measure_of := Ξ»s, ⨆m:ms, m.val s, empty := le_zero_iff_eq.1 $ supr_le $ Ξ» ⟨m, h⟩, le_of_eq m.empty, mono := assume s₁ sβ‚‚ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs, Union_nat := assume f, supr_le $ assume m, calc m.val (⋃i, f i) ≀ (βˆ‘ (i : β„•), m.val (f i)) : m.val.Union_nat _ ... ≀ (βˆ‘i, ⨆m:ms, m.val (f i)) : ennreal.tsum_le_tsum $ assume i, le_supr (Ξ»m:ms, m.val (f i)) m }⟩ private lemma le_Sup (hm : m ∈ ms) : m ≀ Sup ms := Ξ» s, le_supr (Ξ»m:ms, m.val s) ⟨m, hm⟩ private lemma Sup_le (hm : βˆ€m' ∈ ms, m' ≀ m) : Sup ms ≀ m := Ξ» s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) instance : has_Inf (outer_measure Ξ±) := ⟨λs, Sup {m | βˆ€m'∈s, m ≀ m'}⟩ private lemma Inf_le (hm : m ∈ ms) : Inf ms ≀ m := Sup_le $ assume m' h', h' _ hm private lemma le_Inf (hm : βˆ€m' ∈ ms, m ≀ m') : m ≀ Inf ms := le_Sup hm instance : complete_lattice (outer_measure Ξ±) := { top := Sup univ, le_top := assume a, le_Sup (mem_univ a), Sup := Sup, Sup_le := assume s m, Sup_le, le_Sup := assume s m, le_Sup, Inf := Inf, Inf_le := assume s m, Inf_le, le_Inf := assume s m, le_Inf, sup := Ξ»a b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, inf := Ξ»a b, Inf {a, b}, inf_le_left := assume a b, Inf_le $ by simp, inf_le_right := assume a b, Inf_le $ by simp, le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, .. outer_measure.order_bot } @[simp] theorem Sup_apply (ms : set (outer_measure Ξ±)) (s : set Ξ±) : (Sup ms) s = ⨆ m : ms, m s := rfl @[simp] theorem supr_apply {ΞΉ} (f : ΞΉ β†’ outer_measure Ξ±) (s : set Ξ±) : (⨆ i : ΞΉ, f i) s = ⨆ i, f i s := le_antisymm (supr_le $ Ξ» ⟨_, i, rfl⟩, le_supr _ i) (supr_le $ Ξ» i, le_supr (Ξ» (m : {a : outer_measure Ξ± // βˆƒ i, f i = a}), m.1 s) ⟨f i, i, rfl⟩) @[simp] theorem sup_apply (m₁ mβ‚‚ : outer_measure Ξ±) (s : set Ξ±) : (m₁ βŠ” mβ‚‚) s = m₁ s βŠ” mβ‚‚ s := by have := supr_apply (Ξ» b, cond b m₁ mβ‚‚) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum def map {Ξ²} (f : Ξ± β†’ Ξ²) (m : outer_measure Ξ±) : outer_measure Ξ² := { measure_of := Ξ»s, m (f ⁻¹' s), empty := m.empty, mono := Ξ» s t h, m.mono (preimage_mono h), Union_nat := Ξ» s, by rw [preimage_Union]; exact m.Union_nat (Ξ» i, f ⁻¹' s i) } @[simp] theorem map_apply {Ξ²} (f : Ξ± β†’ Ξ²) (m : outer_measure Ξ±) (s : set Ξ²) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure Ξ±) : map id m = m := ext $ Ξ» s, rfl @[simp] theorem map_map {Ξ² Ξ³} (f : Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) (m : outer_measure Ξ±) : map g (map f m) = map (g ∘ f) m := ext $ Ξ» s, rfl instance : functor outer_measure := {map := Ξ» Ξ± Ξ², map} instance : is_lawful_functor outer_measure := { id_map := Ξ» Ξ±, map_id, comp_map := Ξ» Ξ± Ξ² Ξ³ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : Ξ±) : outer_measure Ξ± := { measure_of := Ξ»s, ⨆ h : a ∈ s, 1, empty := by simp, mono := Ξ» s t h, supr_le_supr2 (Ξ» h', ⟨h h', le_refl _⟩), Union_nat := Ξ» s, supr_le $ Ξ» h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : Ξ±) (s : set Ξ±) : dirac a s = ⨆ h : a ∈ s, 1 := rfl def sum {ΞΉ} (f : ΞΉ β†’ outer_measure Ξ±) : outer_measure Ξ± := { measure_of := Ξ»s, βˆ‘ i, f i s, empty := by simp, mono := Ξ» s t h, ennreal.tsum_le_tsum (Ξ» i, (f i).mono' h), Union_nat := Ξ» s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (Ξ» i, (f i).Union_nat _) } @[simp] theorem sum_apply {ΞΉ} (f : ΞΉ β†’ outer_measure Ξ±) (s : set Ξ±) : sum f s = βˆ‘ i, f i s := rfl instance : has_scalar ennreal (outer_measure Ξ±) := ⟨λ a m, { measure_of := Ξ»s, a * m s, empty := by simp, mono := Ξ» s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h), Union_nat := Ξ» s, by rw ennreal.mul_tsum; exact canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩ @[simp] theorem smul_apply (a : ennreal) (m : outer_measure Ξ±) (s : set Ξ±) : (a β€’ m) s = a * m s := rfl instance : semimodule ennreal (outer_measure Ξ±) := { smul_add := Ξ» a m₁ mβ‚‚, ext $ Ξ» s, mul_add _ _ _, add_smul := Ξ» a b m, ext $ Ξ» s, add_mul _ _ _, mul_smul := Ξ» a b m, ext $ Ξ» s, mul_assoc _ _ _, one_smul := Ξ» m, ext $ Ξ» s, one_mul _, zero_smul := Ξ» m, ext $ Ξ» s, zero_mul _, smul_zero := Ξ» a, ext $ Ξ» s, mul_zero _, ..outer_measure.has_scalar } theorem smul_dirac_apply (a : ennreal) (b : Ξ±) (s : set Ξ±) : (a β€’ dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] theorem top_apply {s : set Ξ±} (h : s β‰  βˆ…) : (⊀ : outer_measure Ξ±) s = ⊀ := let ⟨a, as⟩ := set.exists_mem_of_ne_empty h in top_unique $ le_supr_of_le ⟨(⊀ : ennreal) β€’ dirac a, trivial⟩ $ by simp [smul_dirac_apply, as] end basic section of_function set_option eqn_compiler.zeta true /-- Given any function `m` assigning measures to sets satisying `m βˆ… = 0`, there is a unique maximal outer measure `ΞΌ` satisfying `ΞΌ s ≀ m s` for all `s : set Ξ±`. -/ protected def of_function {Ξ± : Type*} (m : set Ξ± β†’ ennreal) (m_empty : m βˆ… = 0) : outer_measure Ξ± := let ΞΌ := Ξ»s, β¨…{f : β„• β†’ set Ξ±} (h : s βŠ† ⋃i, f i), βˆ‘i, m (f i) in { measure_of := ΞΌ, empty := le_antisymm (infi_le_of_le (Ξ»_, βˆ…) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ sβ‚‚ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume Ξ΅ hΞ΅ (hb : (βˆ‘i, ΞΌ (s i)) < ⊀), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hΞ΅) β„• with ⟨Ρ', hΞ΅', hl⟩, refine le_trans _ (add_le_add_left' (le_of_lt hl)), rw ← ennreal.tsum_add, choose f hf using show βˆ€i, βˆƒf:β„• β†’ set Ξ±, s i βŠ† (⋃i, f i) ∧ (βˆ‘i, m (f i)) < ΞΌ (s i) + Ξ΅' i, { intro, have : ΞΌ (s i) < ΞΌ (s i) + Ξ΅' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hΞ΅' i), simpa [ΞΌ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ Ξ» i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (Ξ» i, subset.trans (hf i).1 $ Union_subset $ Ξ» j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } theorem of_function_le {Ξ± : Type*} (m : set Ξ± β†’ ennreal) (m_empty s) : outer_measure.of_function m m_empty s ≀ m s := let f : β„• β†’ set Ξ± := Ξ»i, nat.rec_on i s (Ξ»n s, βˆ…) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (βˆ‘i, m (f i)) = ({0} : finset β„•).sum (Ξ»i, m (f i)) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem le_of_function {Ξ± : Type*} {m m_empty} {ΞΌ : outer_measure Ξ±} : ΞΌ ≀ outer_measure.of_function m m_empty ↔ βˆ€ s, ΞΌ s ≀ m s := ⟨λ H s, le_trans (H _) (of_function_le _ _ _), Ξ» H s, le_infi $ Ξ» f, le_infi $ Ξ» hs, le_trans (ΞΌ.mono hs) $ le_trans (ΞΌ.Union f) $ ennreal.tsum_le_tsum $ Ξ» i, H _⟩ end of_function section caratheodory_measurable universe u parameters {Ξ± : Type u} (m : outer_measure Ξ±) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ sβ‚‚ : set Ξ±} private def C (s : set Ξ±) := βˆ€t, m t = m (t ∩ s) + m (t \ s) private lemma C_iff_le {s : set Ξ±} : C s ↔ βˆ€t, m (t ∩ s) + m (t \ s) ≀ m t := forall_congr $ Ξ» t, le_antisymm_iff.trans $ and_iff_right $ by convert m.union _ _; rw inter_union_diff t s @[simp] private lemma C_empty : C βˆ… := by simp [C, m.empty, diff_empty] private lemma C_compl : C s₁ β†’ C (- s₁) := by simp [C, diff_eq] @[simp] private lemma C_compl_iff : C (- s) ↔ C s := ⟨λ h, by simpa using C_compl m h, C_compl⟩ private lemma C_union (h₁ : C s₁) (hβ‚‚ : C sβ‚‚) : C (s₁ βˆͺ sβ‚‚) := Ξ» t, begin rw [h₁ t, hβ‚‚ (t ∩ s₁), hβ‚‚ (t \ s₁), h₁ (t ∩ (s₁ βˆͺ sβ‚‚)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, hβ‚‚ (t ∩ s₁)], simp [diff_eq] end private lemma measure_inter_union (h : s₁ ∩ sβ‚‚ βŠ† βˆ…) (h₁ : C s₁) {t : set Ξ±} : m (t ∩ (s₁ βˆͺ sβ‚‚)) = m (t ∩ s₁) + m (t ∩ sβ‚‚) := by rw [h₁, set.inter_assoc, union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] private lemma C_Union_lt {s : β„• β†’ set Ξ±} : βˆ€{n:β„•}, (βˆ€i<n, C (s i)) β†’ C (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact C_union m (h n (le_refl (n + 1))) (C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) private lemma C_inter (h₁ : C s₁) (hβ‚‚ : C sβ‚‚) : C (s₁ ∩ sβ‚‚) := by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ hβ‚‚) private lemma C_sum {s : β„• β†’ set Ξ±} (h : βˆ€i, C (s i)) (hd : pairwise (disjoint on s)) {t : set Ξ±} : βˆ€ {n}, (finset.range n).sum (Ξ»i, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), C_sum], intro a, simpa [range_succ] using Ξ» h₁ i hi hβ‚‚, hd _ _ (ne_of_gt hi) ⟨h₁, hβ‚‚βŸ© end private lemma C_Union_nat {s : β„• β†’ set Ξ±} (h : βˆ€i, C (s i)) (hd : pairwise (disjoint on s)) : C (⋃i, s i) := C_iff_le.2 $ Ξ» t, begin have hp : m (t ∩ ⋃i, s i) ≀ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (Ξ» i, t ∩ s i), { rw inter_Union_left }, { simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } }, refine le_trans (add_le_add_right' hp) _, rw ennreal.supr_add, refine supr_le (Ξ» n, le_trans (add_le_add_left' _) (ge_of_eq (C_Union_lt m (Ξ» i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (Ξ» i _, subset_Union _ i), end private lemma f_Union {s : β„• β†’ set Ξ±} (h : βˆ€i, C (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = βˆ‘i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (Ξ» n, _), have := @C_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (Ξ» i _, subset_Union _ i)), end private def caratheodory_dynkin : measurable_space.dynkin_system Ξ± := { has := C, has_empty := C_empty, has_compl := assume s, C_compl, has_Union_nat := assume f hf hn, C_Union_nat hn hf } /-- Given an outer measure `ΞΌ`, the Caratheodory measurable space is defined such that `s` is measurable if `βˆ€t, ΞΌ t = ΞΌ (t ∩ s) + ΞΌ (t \ s)`. -/ protected def caratheodory : measurable_space Ξ± := caratheodory_dynkin.to_measurable_space $ assume s₁ sβ‚‚, C_inter lemma is_caratheodory {s : set Ξ±} : caratheodory.is_measurable s ↔ βˆ€t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_le {s : set Ξ±} : caratheodory.is_measurable s ↔ βˆ€t, m (t ∩ s) + m (t \ s) ≀ m t := C_iff_le protected lemma Union_eq_of_caratheodory {s : β„• β†’ set Ξ±} (h : βˆ€i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = βˆ‘i, m (s i) := f_Union h hd end caratheodory_measurable variables {Ξ± : Type*} lemma caratheodory_is_measurable {m : set Ξ± β†’ ennreal} {s : set Ξ±} {hβ‚€ : m βˆ… = 0} (hs : βˆ€t, m (t ∩ s) + m (t \ s) ≀ m t) : (outer_measure.of_function m hβ‚€).caratheodory.is_measurable s := let o := (outer_measure.of_function m hβ‚€) in (is_caratheodory_le o).2 $ Ξ» t, le_infi $ Ξ» f, le_infi $ Ξ» hf, begin refine le_trans (add_le_add' (infi_le_of_le (Ξ»i, f i ∩ s) $ infi_le _ _) (infi_le_of_le (Ξ»i, f i \ s) $ infi_le _ _)) _, { rw ← inter_Union_right, exact inter_subset_inter_left _ hf }, { rw ← diff_Union_right, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (Ξ» i, hs _) } end @[simp] theorem zero_caratheodory : (0 : outer_measure Ξ±).caratheodory = ⊀ := top_unique $ Ξ» s _ t, (add_zero _).symm theorem top_caratheodory : (⊀ : outer_measure Ξ±).caratheodory = ⊀ := top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t, by by_cases ht : t = βˆ…; simp [ht, top_apply] theorem le_add_caratheodory (m₁ mβ‚‚ : outer_measure Ξ±) : m₁.caratheodory βŠ“ mβ‚‚.caratheodory ≀ (m₁ + mβ‚‚ : outer_measure Ξ±).caratheodory := Ξ» s ⟨hs₁, hsβ‚‚βŸ© t, by simp [hs₁ t, hsβ‚‚ t] theorem le_sum_caratheodory {ΞΉ} (m : ΞΉ β†’ outer_measure Ξ±) : (β¨… i, (m i).caratheodory) ≀ (sum m).caratheodory := Ξ» s h t, by simp [Ξ» i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure Ξ±) : m.caratheodory ≀ (a β€’ m).caratheodory := Ξ» s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : Ξ±) : (dirac a).caratheodory = ⊀ := top_unique $ Ξ» s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end section Inf_gen def Inf_gen (m : set (outer_measure Ξ±)) (s : set Ξ±) : ennreal := ⨆(h : s β‰  βˆ…), β¨… (ΞΌ : outer_measure Ξ±) (h : ΞΌ ∈ m), ΞΌ s @[simp] lemma Inf_gen_empty (m : set (outer_measure Ξ±)) : Inf_gen m βˆ… = 0 := by simp [Inf_gen] lemma Inf_gen_nonempty1 (m : set (outer_measure Ξ±)) (t : set Ξ±) (h : t β‰  βˆ…) : Inf_gen m t = (β¨… (ΞΌ : outer_measure Ξ±) (h : ΞΌ ∈ m), ΞΌ t) := by rw [Inf_gen, supr_pos h] lemma Inf_gen_nonempty2 (m : set (outer_measure Ξ±)) (ΞΌ) (h : ΞΌ ∈ m) (t) : Inf_gen m t = (β¨… (ΞΌ : outer_measure Ξ±) (h : ΞΌ ∈ m), ΞΌ t) := begin by_cases ht : t = βˆ…, { simp [ht], refine (bot_unique $ infi_le_of_le ΞΌ $ _).symm, refine infi_le_of_le h (le_refl βŠ₯) }, { exact Inf_gen_nonempty1 m t ht } end lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure Ξ±)) : Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) := begin refine le_antisymm (assume t', le_of_function.2 (assume t, _) _) (lattice.le_Inf $ assume ΞΌ hΞΌ t, le_trans (outer_measure.of_function_le _ _ _) _); by_cases ht : t = βˆ…; simp [ht, Inf_gen_nonempty1], { assume ΞΌ hΞΌ, exact (show Inf m ≀ ΞΌ, from lattice.Inf_le hΞΌ) t }, { exact infi_le_of_le ΞΌ (infi_le _ hΞΌ) } end end Inf_gen end outer_measure end measure_theory
5b70adb09d6c95818eb2797006d0fe872f226cc9
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/group_theory/submonoid/operations.lean
e0d307a9f5b8934cd287ce6f189a67d37bf9b3bd
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
44,901
lean
/- Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes HΓΆlzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import group_theory.group_action.defs import group_theory.submonoid.basic import group_theory.subsemigroup.operations /-! # Operations on `submonoid`s In this file we define various operations on `submonoid`s and `monoid_hom`s. ## Main definitions ### Conversion between multiplicative and additive definitions * `submonoid.to_add_submonoid`, `submonoid.to_add_submonoid'`, `add_submonoid.to_submonoid`, `add_submonoid.to_submonoid'`: convert between multiplicative and additive submonoids of `M`, `multiplicative M`, and `additive M`. These are stated as `order_iso`s. ### (Commutative) monoid structure on a submonoid * `submonoid.to_monoid`, `submonoid.to_comm_monoid`: a submonoid inherits a (commutative) monoid structure. ### Group actions by submonoids * `submonoid.mul_action`, `submonoid.distrib_mul_action`: a submonoid inherits (distributive) multiplicative actions. ### Operations on submonoids * `submonoid.comap`: preimage of a submonoid under a monoid homomorphism as a submonoid of the domain; * `submonoid.map`: image of a submonoid under a monoid homomorphism as a submonoid of the codomain; * `submonoid.prod`: product of two submonoids `s : submonoid M` and `t : submonoid N` as a submonoid of `M Γ— N`; ### Monoid homomorphisms between submonoid * `submonoid.subtype`: embedding of a submonoid into the ambient monoid. * `submonoid.inclusion`: given two submonoids `S`, `T` such that `S ≀ T`, `S.inclusion T` is the inclusion of `S` into `T` as a monoid homomorphism; * `mul_equiv.submonoid_congr`: converts a proof of `S = T` into a monoid isomorphism between `S` and `T`. * `submonoid.prod_equiv`: monoid isomorphism between `s.prod t` and `s Γ— t`; ### Operations on `monoid_hom`s * `monoid_hom.mrange`: range of a monoid homomorphism as a submonoid of the codomain; * `monoid_hom.mker`: kernel of a monoid homomorphism as a submonoid of the domain; * `monoid_hom.restrict`: restrict a monoid homomorphism to a submonoid; * `monoid_hom.cod_restrict`: restrict the codomain of a monoid homomorphism to a submonoid; * `monoid_hom.mrange_restrict`: restrict a monoid homomorphism to its range; ## Tags submonoid, range, product, map, comap -/ variables {M N P : Type*} [mul_one_class M] [mul_one_class N] [mul_one_class P] (S : submonoid M) /-! ### Conversion to/from `additive`/`multiplicative` -/ section /-- Submonoids of monoid `M` are isomorphic to additive submonoids of `additive M`. -/ @[simps] def submonoid.to_add_submonoid : submonoid M ≃o add_submonoid (additive M) := { to_fun := Ξ» S, { carrier := additive.to_mul ⁻¹' S, zero_mem' := S.one_mem', add_mem' := S.mul_mem' }, inv_fun := Ξ» S, { carrier := additive.of_mul ⁻¹' S, one_mem' := S.zero_mem', mul_mem' := S.add_mem' }, left_inv := Ξ» x, by cases x; refl, right_inv := Ξ» x, by cases x; refl, map_rel_iff' := Ξ» a b, iff.rfl, } /-- Additive submonoids of an additive monoid `additive M` are isomorphic to submonoids of `M`. -/ abbreviation add_submonoid.to_submonoid' : add_submonoid (additive M) ≃o submonoid M := submonoid.to_add_submonoid.symm lemma submonoid.to_add_submonoid_closure (S : set M) : (submonoid.closure S).to_add_submonoid = add_submonoid.closure (additive.to_mul ⁻¹' S) := le_antisymm (submonoid.to_add_submonoid.le_symm_apply.1 $ submonoid.closure_le.2 add_submonoid.subset_closure) (add_submonoid.closure_le.2 submonoid.subset_closure) lemma add_submonoid.to_submonoid'_closure (S : set (additive M)) : (add_submonoid.closure S).to_submonoid' = submonoid.closure (multiplicative.of_add ⁻¹' S) := le_antisymm (add_submonoid.to_submonoid'.le_symm_apply.1 $ add_submonoid.closure_le.2 submonoid.subset_closure) (submonoid.closure_le.2 add_submonoid.subset_closure) end section variables {A : Type*} [add_zero_class A] /-- Additive submonoids of an additive monoid `A` are isomorphic to multiplicative submonoids of `multiplicative A`. -/ @[simps] def add_submonoid.to_submonoid : add_submonoid A ≃o submonoid (multiplicative A) := { to_fun := Ξ» S, { carrier := multiplicative.to_add ⁻¹' S, one_mem' := S.zero_mem', mul_mem' := S.add_mem' }, inv_fun := Ξ» S, { carrier := multiplicative.of_add ⁻¹' S, zero_mem' := S.one_mem', add_mem' := S.mul_mem' }, left_inv := Ξ» x, by cases x; refl, right_inv := Ξ» x, by cases x; refl, map_rel_iff' := Ξ» a b, iff.rfl, } /-- Submonoids of a monoid `multiplicative A` are isomorphic to additive submonoids of `A`. -/ abbreviation submonoid.to_add_submonoid' : submonoid (multiplicative A) ≃o add_submonoid A := add_submonoid.to_submonoid.symm lemma add_submonoid.to_submonoid_closure (S : set A) : (add_submonoid.closure S).to_submonoid = submonoid.closure (multiplicative.to_add ⁻¹' S) := le_antisymm (add_submonoid.to_submonoid.to_galois_connection.l_le $ add_submonoid.closure_le.2 submonoid.subset_closure) (submonoid.closure_le.2 add_submonoid.subset_closure) lemma submonoid.to_add_submonoid'_closure (S : set (multiplicative A)) : (submonoid.closure S).to_add_submonoid' = add_submonoid.closure (additive.of_mul ⁻¹' S) := le_antisymm (submonoid.to_add_submonoid'.to_galois_connection.l_le $ submonoid.closure_le.2 add_submonoid.subset_closure) (add_submonoid.closure_le.2 submonoid.subset_closure) end namespace submonoid variables {F : Type*} [mc : monoid_hom_class F M N] open set /-! ### `comap` and `map` -/ include mc /-- The preimage of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The preimage of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def comap (f : F) (S : submonoid N) : submonoid M := { carrier := (f ⁻¹' S), one_mem' := show f 1 ∈ S, by rw map_one; exact S.one_mem, mul_mem' := Ξ» a b ha hb, show f (a * b) ∈ S, by rw map_mul; exact S.mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : submonoid N) (f : F) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : submonoid N} {f : F} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl omit mc @[to_additive] lemma comap_comap (S : submonoid P) (g : N β†’* P) (f : M β†’* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl @[simp, to_additive] lemma comap_id (S : submonoid P) : S.comap (monoid_hom.id P) = S := ext (by simp) include mc /-- The image of a submonoid along a monoid homomorphism is a submonoid. -/ @[to_additive "The image of an `add_submonoid` along an `add_monoid` homomorphism is an `add_submonoid`."] def map (f : F) (S : submonoid M) : submonoid N := { carrier := (f '' S), one_mem' := ⟨1, S.one_mem, map_one f⟩, mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, S.mul_mem hx hy, by rw map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : F) (S : submonoid M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : F} {S : submonoid M} {y : N} : y ∈ S.map f ↔ βˆƒ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma mem_map_of_mem (f : F) {S : submonoid M} {x : M} (hx : x ∈ S) : f x ∈ S.map f := mem_image_of_mem f hx @[to_additive] lemma apply_coe_mem_map (f : F) (S : submonoid M) (x : S) : f x ∈ S.map f := mem_map_of_mem f x.prop omit mc @[to_additive] lemma map_map (g : N β†’* P) (f : M β†’* N) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ include mc @[to_additive] lemma mem_map_iff_mem {f : F} (hf : function.injective f) {S : submonoid M} {x : M} : f x ∈ S.map f ↔ x ∈ S := hf.mem_set_image @[to_additive] lemma map_le_iff_le_comap {f : F} {S : submonoid M} {T : submonoid N} : S.map f ≀ T ↔ S ≀ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : F) : galois_connection (map f) (comap f) := Ξ» S T, map_le_iff_le_comap @[to_additive] lemma map_le_of_le_comap {T : submonoid N} {f : F} : S ≀ T.comap f β†’ S.map f ≀ T := (gc_map_comap f).l_le @[to_additive] lemma le_comap_of_map_le {T : submonoid N} {f : F} : S.map f ≀ T β†’ S ≀ T.comap f := (gc_map_comap f).le_u @[to_additive] lemma le_comap_map {f : F} : S ≀ (S.map f).comap f := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_le {S : submonoid N} {f : F} : (S.comap f).map f ≀ S := (gc_map_comap f).l_u_le _ @[to_additive] lemma monotone_map {f : F} : monotone (map f) := (gc_map_comap f).monotone_l @[to_additive] lemma monotone_comap {f : F} : monotone (comap f) := (gc_map_comap f).monotone_u @[simp, to_additive] lemma map_comap_map {f : F} : ((S.map f).comap f).map f = S.map f := (gc_map_comap f).l_u_l_eq_l _ @[simp, to_additive] lemma comap_map_comap {S : submonoid N} {f : F} : ((S.comap f).map f).comap f = S.comap f := (gc_map_comap f).u_l_u_eq_u _ @[to_additive] lemma map_sup (S T : submonoid M) (f : F) : (S βŠ” T).map f = S.map f βŠ” T.map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_sup @[to_additive] lemma map_supr {ΞΉ : Sort*} (f : F) (s : ΞΉ β†’ submonoid M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_supr @[to_additive] lemma comap_inf (S T : submonoid N) (f : F) : (S βŠ“ T).comap f = S.comap f βŠ“ T.comap f := (gc_map_comap f : galois_connection (map f) (comap f)).u_inf @[to_additive] lemma comap_infi {ΞΉ : Sort*} (f : F) (s : ΞΉ β†’ submonoid N) : (infi s).comap f = β¨… i, (s i).comap f := (gc_map_comap f : galois_connection (map f) (comap f)).u_infi @[simp, to_additive] lemma map_bot (f : F) : (βŠ₯ : submonoid M).map f = βŠ₯ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : F) : (⊀ : submonoid N).comap f = ⊀ := (gc_map_comap f).u_top omit mc @[simp, to_additive] lemma map_id (S : submonoid M) : S.map (monoid_hom.id M) = S := ext (Ξ» x, ⟨λ ⟨_, h, rfl⟩, h, Ξ» h, ⟨_, h, rfl⟩⟩) section galois_coinsertion variables {ΞΉ : Type*} {f : F} (hf : function.injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. "-/] def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (Ξ» S x, by simp [mem_comap, mem_map, hf.eq_iff]) @[to_additive] lemma comap_map_eq_of_injective (S : submonoid M) : (S.map f).comap f = S := (gci_map_comap hf).u_l_eq _ @[to_additive] lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective @[to_additive] lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective @[to_additive] lemma comap_inf_map_of_injective (S T : submonoid M) : (S.map f βŠ“ T.map f).comap f = S βŠ“ T := (gci_map_comap hf).u_inf_l _ _ @[to_additive] lemma comap_infi_map_of_injective (S : ΞΉ β†’ submonoid M) : (β¨… i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ @[to_additive] lemma comap_sup_map_of_injective (S T : submonoid M) : (S.map f βŠ” T.map f).comap f = S βŠ” T := (gci_map_comap hf).u_sup_l _ _ @[to_additive] lemma comap_supr_map_of_injective (S : ΞΉ β†’ submonoid M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ @[to_additive] lemma map_le_map_iff_of_injective {S T : submonoid M} : S.map f ≀ T.map f ↔ S ≀ T := (gci_map_comap hf).l_le_l_iff @[to_additive] lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion section galois_insertion variables {ΞΉ : Type*} {f : F} (hf : function.surjective f) include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_insertion` when `f` is surjective. "-/] def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (Ξ» S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩) @[to_additive] lemma map_comap_eq_of_surjective (S : submonoid N) : (S.comap f).map f = S := (gi_map_comap hf).l_u_eq _ @[to_additive] lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective @[to_additive] lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective @[to_additive] lemma map_inf_comap_of_surjective (S T : submonoid N) : (S.comap f βŠ“ T.comap f).map f = S βŠ“ T := (gi_map_comap hf).l_inf_u _ _ @[to_additive] lemma map_infi_comap_of_surjective (S : ΞΉ β†’ submonoid N) : (β¨… i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ @[to_additive] lemma map_sup_comap_of_surjective (S T : submonoid N) : (S.comap f βŠ” T.comap f).map f = S βŠ” T := (gi_map_comap hf).l_sup_u _ _ @[to_additive] lemma map_supr_comap_of_surjective (S : ΞΉ β†’ submonoid N) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ @[to_additive] lemma comap_le_comap_iff_of_surjective {S T : submonoid N} : S.comap f ≀ T.comap f ↔ S ≀ T := (gi_map_comap hf).u_le_u_iff @[to_additive] lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion end submonoid namespace submonoid_class variables {A : Type*} [set_like A M] [hA : submonoid_class A M] (S' : A) include hA /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S' := ⟨⟨_, one_mem S'⟩⟩ @[simp, norm_cast, to_additive] lemma coe_one : ((1 : S') : M) = 1 := rfl variables {S'} @[simp, norm_cast, to_additive] lemma coe_eq_one {x : S'} : (↑x : M) = 1 ↔ x = 1 := (subtype.ext_iff.symm : (x : M) = (1 : S') ↔ x = 1) variables (S') @[to_additive] lemma one_def : (1 : S') = ⟨1, one_mem S'⟩ := rfl omit hA /-- An `add_submonoid` of an `add_monoid` inherits a scalar multiplication. -/ instance _root_.add_submonoid_class.has_nsmul {M} [add_monoid M] {A : Type*} [set_like A M] [add_submonoid_class A M] (S : A) : has_smul β„• S := ⟨λ n a, ⟨n β€’ a.1, nsmul_mem a.2 n⟩⟩ /-- A submonoid of a monoid inherits a power operator. -/ instance has_pow {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : has_pow S β„• := ⟨λ a n, ⟨a.1 ^ n, pow_mem a.2 n⟩⟩ attribute [to_additive] submonoid_class.has_pow @[simp, norm_cast, to_additive] lemma coe_pow {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] {S : A} (x : S) (n : β„•) : (↑(x ^ n) : M) = ↑x ^ n := rfl @[simp, to_additive] lemma mk_pow {M} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] {S : A} (x : M) (hx : x ∈ S) (n : β„•) : (⟨x, hx⟩ : S) ^ n = ⟨x ^ n, pow_mem hx n⟩ := rfl /-- A submonoid of a unital magma inherits a unital magma structure. -/ @[to_additive "An `add_submonoid` of an unital additive magma inherits an unital additive magma structure.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_mul_one_class {M : Type*} [mul_one_class M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : mul_one_class S := subtype.coe_injective.mul_one_class _ rfl (Ξ» _ _, rfl) /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_monoid {M : Type*} [monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : monoid S := subtype.coe_injective.monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_comm_monoid {M} [comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : comm_monoid S := subtype.coe_injective.comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of an `ordered_comm_monoid` is an `ordered_comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_ordered_comm_monoid {M} [ordered_comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : ordered_comm_monoid S := subtype.coe_injective.ordered_comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of a `linear_ordered_comm_monoid` is a `linear_ordered_comm_monoid`. -/ @[to_additive "An `add_submonoid` of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_linear_ordered_comm_monoid {M} [linear_ordered_comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : linear_ordered_comm_monoid S := subtype.coe_injective.linear_ordered_comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of an `ordered_cancel_comm_monoid` is an `ordered_cancel_comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_ordered_cancel_comm_monoid {M} [ordered_cancel_comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : ordered_cancel_comm_monoid S := subtype.coe_injective.ordered_cancel_comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of a `linear_ordered_cancel_comm_monoid` is a `linear_ordered_cancel_comm_monoid`. -/ @[to_additive "An `add_submonoid` of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`.", priority 75] -- Prefer subclasses of `monoid` over subclasses of `submonoid_class`. instance to_linear_ordered_cancel_comm_monoid {M} [linear_ordered_cancel_comm_monoid M] {A : Type*} [set_like A M] [submonoid_class A M] (S : A) : linear_ordered_cancel_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) include hA /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S' β†’* M := ⟨coe, rfl, Ξ» _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : (submonoid_class.subtype S' : S' β†’ M) = coe := rfl end submonoid_class namespace submonoid /-- A submonoid of a monoid inherits a multiplication. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an addition."] instance has_mul : has_mul S := ⟨λ a b, ⟨a.1 * b.1, S.mul_mem a.2 b.2⟩⟩ /-- A submonoid of a monoid inherits a 1. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits a zero."] instance has_one : has_one S := ⟨⟨_, S.one_mem⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : S) : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : S) : M) = 1 := rfl @[simp, to_additive] lemma mk_mul_mk (x y : M) (hx : x ∈ S) (hy : y ∈ S) : (⟨x, hx⟩ : S) * ⟨y, hy⟩ = ⟨x * y, S.mul_mem hx hy⟩ := rfl @[to_additive] lemma mul_def (x y : S) : x * y = ⟨x * y, S.mul_mem x.2 y.2⟩ := rfl @[to_additive] lemma one_def : (1 : S) = ⟨1, S.one_mem⟩ := rfl /-- A submonoid of a unital magma inherits a unital magma structure. -/ @[to_additive "An `add_submonoid` of an unital additive magma inherits an unital additive magma structure."] instance to_mul_one_class {M : Type*} [mul_one_class M] (S : submonoid M) : mul_one_class S := subtype.coe_injective.mul_one_class coe rfl (Ξ» _ _, rfl) @[to_additive] protected lemma pow_mem {M : Type*} [monoid M] (S : submonoid M) {x : M} (hx : x ∈ S) (n : β„•) : x ^ n ∈ S := pow_mem hx n @[simp, norm_cast, to_additive] theorem coe_pow {M : Type*} [monoid M] {S : submonoid M} (x : S) (n : β„•) : ↑(x ^ n) = (x ^ n : M) := rfl /-- A submonoid of a monoid inherits a monoid structure. -/ @[to_additive "An `add_submonoid` of an `add_monoid` inherits an `add_monoid` structure."] instance to_monoid {M : Type*} [monoid M] (S : submonoid M) : monoid S := subtype.coe_injective.monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of a `comm_monoid` is a `comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `add_comm_monoid` is an `add_comm_monoid`."] instance to_comm_monoid {M} [comm_monoid M] (S : submonoid M) : comm_monoid S := subtype.coe_injective.comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of an `ordered_comm_monoid` is an `ordered_comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`."] instance to_ordered_comm_monoid {M} [ordered_comm_monoid M] (S : submonoid M) : ordered_comm_monoid S := subtype.coe_injective.ordered_comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of a `linear_ordered_comm_monoid` is a `linear_ordered_comm_monoid`. -/ @[to_additive "An `add_submonoid` of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`."] instance to_linear_ordered_comm_monoid {M} [linear_ordered_comm_monoid M] (S : submonoid M) : linear_ordered_comm_monoid S := subtype.coe_injective.linear_ordered_comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of an `ordered_cancel_comm_monoid` is an `ordered_cancel_comm_monoid`. -/ @[to_additive "An `add_submonoid` of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`."] instance to_ordered_cancel_comm_monoid {M} [ordered_cancel_comm_monoid M] (S : submonoid M) : ordered_cancel_comm_monoid S := subtype.coe_injective.ordered_cancel_comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- A submonoid of a `linear_ordered_cancel_comm_monoid` is a `linear_ordered_cancel_comm_monoid`. -/ @[to_additive "An `add_submonoid` of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`."] instance to_linear_ordered_cancel_comm_monoid {M} [linear_ordered_cancel_comm_monoid M] (S : submonoid M) : linear_ordered_cancel_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_comm_monoid coe rfl (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) (Ξ» _ _, rfl) /-- The natural monoid hom from a submonoid of monoid `M` to `M`. -/ @[to_additive "The natural monoid hom from an `add_submonoid` of `add_monoid` `M` to `M`."] def subtype : S β†’* M := ⟨coe, rfl, Ξ» _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑S.subtype = coe := rfl /-- The top submonoid is isomorphic to the monoid. -/ @[to_additive "The top additive submonoid is isomorphic to the additive monoid.", simps] def top_equiv : (⊀ : submonoid M) ≃* M := { to_fun := Ξ» x, x, inv_fun := Ξ» x, ⟨x, mem_top x⟩, left_inv := Ξ» x, x.eta _, right_inv := Ξ» _, rfl, map_mul' := Ξ» _ _, rfl } @[simp, to_additive] lemma top_equiv_to_monoid_hom : (top_equiv : _ ≃* M).to_monoid_hom = (⊀ : submonoid M).subtype := rfl /-- A submonoid is isomorphic to its image under an injective function -/ @[to_additive "An additive submonoid is isomorphic to its image under an injective function"] noncomputable def equiv_map_of_injective (f : M β†’* N) (hf : function.injective f) : S ≃* S.map f := { map_mul' := Ξ» _ _, subtype.ext (f.map_mul _ _), ..equiv.set.image f S hf } @[simp, to_additive] lemma coe_equiv_map_of_injective_apply (f : M β†’* N) (hf : function.injective f) (x : S) : (equiv_map_of_injective S f hf x : N) = f x := rfl @[simp, to_additive] lemma closure_closure_coe_preimage {s : set M} : closure ((coe : closure s β†’ M) ⁻¹' s) = ⊀ := eq_top_iff.2 $ Ξ» x, subtype.rec_on x $ Ξ» x hx _, begin refine closure_induction' _ (Ξ» g hg, _) _ (Ξ» g₁ gβ‚‚ hg₁ hgβ‚‚, _) hx, { exact subset_closure hg }, { exact submonoid.one_mem _ }, { exact submonoid.mul_mem _ }, end /-- Given `submonoid`s `s`, `t` of monoids `M`, `N` respectively, `s Γ— t` as a submonoid of `M Γ— N`. -/ @[to_additive prod "Given `add_submonoid`s `s`, `t` of `add_monoid`s `A`, `B` respectively, `s Γ— t` as an `add_submonoid` of `A Γ— B`."] def prod (s : submonoid M) (t : submonoid N) : submonoid (M Γ— N) := { carrier := s Γ—Λ’ t, one_mem' := ⟨s.one_mem, t.one_mem⟩, mul_mem' := Ξ» p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : submonoid M) (t : submonoid N) : (s.prod t : set (M Γ— N)) = s Γ—Λ’ t := rfl @[to_additive mem_prod] lemma mem_prod {s : submonoid M} {t : submonoid N} {p : M Γ— N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono {s₁ sβ‚‚ : submonoid M} {t₁ tβ‚‚ : submonoid N} (hs : s₁ ≀ sβ‚‚) (ht : t₁ ≀ tβ‚‚) : s₁.prod t₁ ≀ sβ‚‚.prod tβ‚‚ := set.prod_mono hs ht @[to_additive prod_top] lemma prod_top (s : submonoid M) : s.prod (⊀ : submonoid N) = s.comap (monoid_hom.fst M N) := ext $ Ξ» x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : submonoid N) : (⊀ : submonoid M).prod s = s.comap (monoid_hom.snd M N) := ext $ Ξ» x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊀ : submonoid M).prod (⊀ : submonoid N) = ⊀ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (βŠ₯ : submonoid M).prod (βŠ₯ : submonoid N) = βŠ₯ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] /-- The product of submonoids is isomorphic to their product as monoids. -/ @[to_additive prod_equiv "The product of additive submonoids is isomorphic to their product as additive monoids"] def prod_equiv (s : submonoid M) (t : submonoid N) : s.prod t ≃* s Γ— t := { map_mul' := Ξ» x y, rfl, .. equiv.set.prod ↑s ↑t } open monoid_hom @[to_additive] lemma map_inl (s : submonoid M) : s.map (inl M N) = s.prod βŠ₯ := ext $ Ξ» p, ⟨λ ⟨x, hx, hp⟩, hp β–Έ ⟨hx, set.mem_singleton 1⟩, Ξ» ⟨hps, hp1⟩, ⟨p.1, hps, prod.ext rfl $ (set.eq_of_mem_singleton hp1).symm⟩⟩ @[to_additive] lemma map_inr (s : submonoid N) : s.map (inr M N) = prod βŠ₯ s := ext $ Ξ» p, ⟨λ ⟨x, hx, hp⟩, hp β–Έ ⟨set.mem_singleton 1, hx⟩, Ξ» ⟨hp1, hps⟩, ⟨p.2, hps, prod.ext (set.eq_of_mem_singleton hp1).symm rfl⟩⟩ @[simp, to_additive prod_bot_sup_bot_prod] lemma prod_bot_sup_bot_prod (s : submonoid M) (t : submonoid N) : (s.prod βŠ₯) βŠ” (prod βŠ₯ t) = s.prod t := le_antisymm (sup_le (prod_mono (le_refl s) bot_le) (prod_mono bot_le (le_refl t))) $ assume p hp, prod.fst_mul_snd p β–Έ mul_mem ((le_sup_left : s.prod βŠ₯ ≀ s.prod βŠ₯ βŠ” prod βŠ₯ t) ⟨hp.1, set.mem_singleton 1⟩) ((le_sup_right : prod βŠ₯ t ≀ s.prod βŠ₯ βŠ” prod βŠ₯ t) ⟨set.mem_singleton 1, hp.2⟩) @[to_additive] lemma mem_map_equiv {f : M ≃* N} {K : submonoid M} {x : N} : x ∈ K.map f.to_monoid_hom ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x @[to_additive] lemma map_equiv_eq_comap_symm (f : M ≃* N) (K : submonoid M) : K.map f.to_monoid_hom = K.comap f.symm.to_monoid_hom := set_like.coe_injective (f.to_equiv.image_eq_preimage K) @[to_additive] lemma comap_equiv_eq_map_symm (f : N ≃* M) (K : submonoid M) : K.comap f.to_monoid_hom = K.map f.symm.to_monoid_hom := (map_equiv_eq_comap_symm f.symm K).symm @[simp, to_additive] lemma map_equiv_top (f : M ≃* N) : (⊀ : submonoid M).map f.to_monoid_hom = ⊀ := set_like.coe_injective $ set.image_univ.trans f.surjective.range_eq @[to_additive le_prod_iff] lemma le_prod_iff {s : submonoid M} {t : submonoid N} {u : submonoid (M Γ— N)} : u ≀ s.prod t ↔ u.map (fst M N) ≀ s ∧ u.map (snd M N) ≀ t := begin split, { intros h, split, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 }, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, } end @[to_additive prod_le_iff] lemma prod_le_iff {s : submonoid M} {t : submonoid N} {u : submonoid (M Γ— N)} : s.prod t ≀ u ↔ s.map (inl M N) ≀ u ∧ t.map (inr M N) ≀ u := begin split, { intros h, split, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨hx, (submonoid.one_mem _)⟩, }, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨submonoid.one_mem _, hx⟩, }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ ⟨h1, h2⟩, have h1' : inl M N x1 ∈ u, { apply hH, simpa using h1, }, have h2' : inr M N x2 ∈ u, { apply hK, simpa using h2, }, simpa using submonoid.mul_mem _ h1' h2', } end end submonoid namespace monoid_hom variables {F : Type*} [mc : monoid_hom_class F M N] open submonoid /-- For many categories (monoids, modules, rings, ...) the set-theoretic image of a morphism `f` is a subobject of the codomain. When this is the case, it is useful to define the range of a morphism in such a way that the underlying carrier set of the range subobject is definitionally `set.range f`. In particular this means that the types `β†₯(set.range f)` and `β†₯f.range` are interchangeable without proof obligations. A convenient candidate definition for range which is mathematically correct is `map ⊀ f`, just as `set.range` could have been defined as `f '' set.univ`. However, this lacks the desired definitional convenience, in that it both does not match `set.range`, and that it introduces a redudant `x ∈ ⊀` term which clutters proofs. In such a case one may resort to the `copy` pattern. A `copy` function converts the definitional problem for the carrier set of a subobject into a one-off propositional proof obligation which one discharges while writing the definition of the definitionally convenient range (the parameter `hs` in the example below). A good example is the case of a morphism of monoids. A convenient definition for `monoid_hom.mrange` would be `(⊀ : submonoid M).map f`. However since this lacks the required definitional convenience, we first define `submonoid.copy` as follows: ```lean protected def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M := { carrier := s, one_mem' := hs.symm β–Έ S.one_mem', mul_mem' := hs.symm β–Έ S.mul_mem' } ``` and then finally define: ```lean def mrange (f : M β†’* N) : submonoid N := ((⊀ : submonoid M).map f).copy (set.range f) set.image_univ.symm ``` -/ library_note "range copy pattern" include mc /-- The range of a monoid homomorphism is a submonoid. See Note [range copy pattern]. -/ @[to_additive "The range of an `add_monoid_hom` is an `add_submonoid`."] def mrange (f : F) : submonoid N := ((⊀ : submonoid M).map f).copy (set.range f) set.image_univ.symm @[simp, to_additive] lemma coe_mrange (f : F) : (mrange f : set N) = set.range f := rfl @[simp, to_additive] lemma mem_mrange {f : F} {y : N} : y ∈ mrange f ↔ βˆƒ x, f x = y := iff.rfl @[to_additive] lemma mrange_eq_map (f : F) : mrange f = (⊀ : submonoid M).map f := copy_eq _ omit mc @[to_additive] lemma map_mrange (g : N β†’* P) (f : M β†’* N) : f.mrange.map g = (g.comp f).mrange := by simpa only [mrange_eq_map] using (⊀ : submonoid M).map_map g f include mc @[to_additive] lemma mrange_top_iff_surjective {f : F} : mrange f = (⊀ : submonoid N) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_mrange, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` hom is the whole of the codomain."] lemma mrange_top_of_surjective (f : F) (hf : function.surjective f) : mrange f = (⊀ : submonoid N) := mrange_top_iff_surjective.2 hf @[to_additive] lemma mclosure_preimage_le (f : F) (s : set N) : closure (f ⁻¹' s) ≀ (closure s).comap f := closure_le.2 $ Ξ» x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a monoid hom of the submonoid generated by a set equals the submonoid generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_submonoid` generated by a set equals the `add_submonoid` generated by the image of the set."] lemma map_mclosure (f : F) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (mclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) omit mc /-- Restriction of a monoid hom to a submonoid of the domain. -/ @[to_additive "Restriction of an add_monoid hom to an `add_submonoid` of the domain."] def restrict {N S : Type*} [mul_one_class N] [set_like S M] [submonoid_class S M] (f : M β†’* N) (s : S) : s β†’* N := f.comp (submonoid_class.subtype _) @[simp, to_additive] lemma restrict_apply {N S : Type*} [mul_one_class N] [set_like S M] [submonoid_class S M] (f : M β†’* N) (s : S) (x : s) : f.restrict s x = f x := rfl /-- Restriction of a monoid hom to a submonoid of the codomain. -/ @[to_additive "Restriction of an `add_monoid` hom to an `add_submonoid` of the codomain.", simps apply] def cod_restrict {S} [set_like S N] [submonoid_class S N] (f : M β†’* N) (s : S) (h : βˆ€ x, f x ∈ s) : M β†’* s := { to_fun := Ξ» n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := Ξ» x y, subtype.eq (f.map_mul x y) } /-- Restriction of a monoid hom to its range interpreted as a submonoid. -/ @[to_additive "Restriction of an `add_monoid` hom to its range interpreted as a submonoid."] def mrange_restrict {N} [mul_one_class N] (f : M β†’* N) : M β†’* f.mrange := f.cod_restrict f.mrange $ Ξ» x, ⟨x, rfl⟩ @[simp, to_additive] lemma coe_mrange_restrict {N} [mul_one_class N] (f : M β†’* N) (x : M) : (f.mrange_restrict x : N) = f x := rfl @[to_additive] lemma mrange_restrict_surjective (f : M β†’* N) : function.surjective f.mrange_restrict := Ξ» ⟨_, ⟨x, rfl⟩⟩, ⟨x, rfl⟩ include mc /-- The multiplicative kernel of a monoid homomorphism is the submonoid of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_submonoid` of elements such that `f x = 0`"] def mker (f : F) : submonoid M := (βŠ₯ : submonoid N).comap f @[to_additive] lemma mem_mker (f : F) {x : M} : x ∈ mker f ↔ f x = 1 := iff.rfl @[to_additive] lemma coe_mker (f : F) : (mker f : set M) = (f : M β†’ N) ⁻¹' {1} := rfl @[to_additive] instance decidable_mem_mker [decidable_eq N] (f : F) : decidable_pred (∈ mker f) := Ξ» x, decidable_of_iff (f x = 1) (mem_mker f) omit mc @[to_additive] lemma comap_mker (g : N β†’* P) (f : M β†’* N) : g.mker.comap f = (g.comp f).mker := rfl include mc @[simp, to_additive] lemma comap_bot' (f : F) : (βŠ₯ : submonoid N).comap f = mker f := rfl omit mc @[to_additive] lemma range_restrict_mker (f : M β†’* N) : mker (mrange_restrict f) = mker f := begin ext, change (⟨f x, _⟩ : mrange f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end @[simp, to_additive] lemma mker_one : (1 : M β†’* N).mker = ⊀ := by { ext, simp [mem_mker] } @[to_additive] lemma prod_map_comap_prod' {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] (f : M β†’* N) (g : M' β†’* N') (S : submonoid N) (S' : submonoid N') : (S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ @[to_additive] lemma mker_prod_map {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] (f : M β†’* N) (g : M' β†’* N') : (prod_map f g).mker = f.mker.prod g.mker := by rw [←comap_bot', ←comap_bot', ←comap_bot', ←prod_map_comap_prod', bot_prod_bot] @[simp, to_additive] lemma mker_inl : (inl M N).mker = βŠ₯ := by { ext x, simp [mem_mker] } @[simp, to_additive] lemma mker_inr : (inr M N).mker = βŠ₯ := by { ext x, simp [mem_mker] } /-- The `monoid_hom` from the preimage of a submonoid to itself. -/ @[to_additive "the `add_monoid_hom` from the preimage of an additive submonoid to itself.", simps] def submonoid_comap (f : M β†’* N) (N' : submonoid N) : N'.comap f β†’* N' := { to_fun := Ξ» x, ⟨f x, x.prop⟩, map_one' := subtype.eq f.map_one, map_mul' := Ξ» x y, subtype.eq (f.map_mul x y) } /-- The `monoid_hom` from a submonoid to its image. See `mul_equiv.submonoid_map` for a variant for `mul_equiv`s. -/ @[to_additive "the `add_monoid_hom` from an additive submonoid to its image. See `add_equiv.add_submonoid_map` for a variant for `add_equiv`s.", simps] def submonoid_map (f : M β†’* N) (M' : submonoid M) : M' β†’* M'.map f := { to_fun := Ξ» x, ⟨f x, ⟨x, x.prop, rfl⟩⟩, map_one' := subtype.eq $ f.map_one, map_mul' := Ξ» x y, subtype.eq $ f.map_mul x y } @[to_additive] lemma submonoid_map_surjective (f : M β†’* N) (M' : submonoid M) : function.surjective (f.submonoid_map M') := by { rintro ⟨_, x, hx, rfl⟩, exact ⟨⟨x, hx⟩, rfl⟩ } end monoid_hom namespace submonoid open monoid_hom @[to_additive] lemma mrange_inl : (inl M N).mrange = prod ⊀ βŠ₯ := by simpa only [mrange_eq_map] using map_inl ⊀ @[to_additive] lemma mrange_inr : (inr M N).mrange = prod βŠ₯ ⊀ := by simpa only [mrange_eq_map] using map_inr ⊀ @[to_additive] lemma mrange_inl' : (inl M N).mrange = comap (snd M N) βŠ₯ := mrange_inl.trans (top_prod _) @[to_additive] lemma mrange_inr' : (inr M N).mrange = comap (fst M N) βŠ₯ := mrange_inr.trans (prod_top _) @[simp, to_additive] lemma mrange_fst : (fst M N).mrange = ⊀ := mrange_top_of_surjective (fst M N) $ @prod.fst_surjective _ _ ⟨1⟩ @[simp, to_additive] lemma mrange_snd : (snd M N).mrange = ⊀ := mrange_top_of_surjective (snd M N) $ @prod.snd_surjective _ _ ⟨1⟩ @[to_additive] lemma prod_eq_bot_iff {s : submonoid M} {t : submonoid N} : s.prod t = βŠ₯ ↔ s = βŠ₯ ∧ t = βŠ₯ := by simp only [eq_bot_iff, prod_le_iff, (gc_map_comap _).le_iff_le, comap_bot', mker_inl, mker_inr] @[to_additive] lemma prod_eq_top_iff {s : submonoid M} {t : submonoid N} : s.prod t = ⊀ ↔ s = ⊀ ∧ t = ⊀ := by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, ← mrange_eq_map, mrange_fst, mrange_snd] @[simp, to_additive] lemma mrange_inl_sup_mrange_inr : (inl M N).mrange βŠ” (inr M N).mrange = ⊀ := by simp only [mrange_inl, mrange_inr, prod_bot_sup_bot_prod, top_prod_top] /-- The monoid hom associated to an inclusion of submonoids. -/ @[to_additive "The `add_monoid` hom associated to an inclusion of submonoids."] def inclusion {S T : submonoid M} (h : S ≀ T) : S β†’* T := S.subtype.cod_restrict _ (Ξ» x, h x.2) @[simp, to_additive] lemma range_subtype (s : submonoid M) : s.subtype.mrange = s := set_like.coe_injective $ (coe_mrange _).trans $ subtype.range_coe @[to_additive] lemma eq_top_iff' : S = ⊀ ↔ βˆ€ x : M, x ∈ S := eq_top_iff.trans ⟨λ h m, h $ mem_top m, Ξ» h m _, h m⟩ @[to_additive] lemma eq_bot_iff_forall : S = βŠ₯ ↔ βˆ€ x ∈ S, x = (1 : M) := set_like.ext_iff.trans $ by simp [iff_def, S.one_mem] { contextual := tt } @[to_additive] lemma nontrivial_iff_exists_ne_one (S : submonoid M) : nontrivial S ↔ βˆƒ x ∈ S, x β‰  (1:M) := calc nontrivial S ↔ βˆƒ x : S, x β‰  1 : nontrivial_iff_exists_ne 1 ... ↔ βˆƒ x (hx : x ∈ S), (⟨x, hx⟩ : S) β‰  ⟨1, S.one_mem⟩ : subtype.exists ... ↔ βˆƒ x ∈ S, x β‰  (1 : M) : by simp only [ne.def] /-- A submonoid is either the trivial submonoid or nontrivial. -/ @[to_additive "An additive submonoid is either the trivial additive submonoid or nontrivial."] lemma bot_or_nontrivial (S : submonoid M) : S = βŠ₯ ∨ nontrivial S := by simp only [eq_bot_iff_forall, nontrivial_iff_exists_ne_one, ← not_forall, classical.em] /-- A submonoid is either the trivial submonoid or contains a nonzero element. -/ @[to_additive "An additive submonoid is either the trivial additive submonoid or contains a nonzero element."] lemma bot_or_exists_ne_one (S : submonoid M) : S = βŠ₯ ∨ βˆƒ x ∈ S, x β‰  (1:M) := S.bot_or_nontrivial.imp_right S.nontrivial_iff_exists_ne_one.mp end submonoid namespace mul_equiv variables {S} {T : submonoid M} /-- Makes the identity isomorphism from a proof that two submonoids of a multiplicative monoid are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two submonoids of an additive monoid are equal."] def submonoid_congr (h : S = T) : S ≃* T := { map_mul' := Ξ» _ _, rfl, ..equiv.set_congr $ congr_arg _ h } -- this name is primed so that the version to `f.range` instead of `f.mrange` can be unprimed. /-- A monoid homomorphism `f : M β†’* N` with a left-inverse `g : N β†’ M` defines a multiplicative equivalence between `M` and `f.mrange`. This is a bidirectional version of `monoid_hom.mrange_restrict`. -/ @[to_additive /-" An additive monoid homomorphism `f : M β†’+ N` with a left-inverse `g : N β†’ M` defines an additive equivalence between `M` and `f.mrange`. This is a bidirectional version of `add_monoid_hom.mrange_restrict`. "-/, simps {simp_rhs := tt}] def of_left_inverse' (f : M β†’* N) {g : N β†’ M} (h : function.left_inverse g f) : M ≃* f.mrange := { to_fun := f.mrange_restrict, inv_fun := g ∘ f.mrange.subtype, left_inv := h, right_inv := Ξ» x, subtype.ext $ let ⟨x', hx'⟩ := monoid_hom.mem_mrange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.mrange_restrict } /-- A `mul_equiv` `Ο†` between two monoids `M` and `N` induces a `mul_equiv` between a submonoid `S ≀ M` and the submonoid `Ο†(S) ≀ N`. See `monoid_hom.submonoid_map` for a variant for `monoid_hom`s. -/ @[to_additive "An `add_equiv` `Ο†` between two additive monoids `M` and `N` induces an `add_equiv` between a submonoid `S ≀ M` and the submonoid `Ο†(S) ≀ N`. See `add_monoid_hom.add_submonoid_map` for a variant for `add_monoid_hom`s.", simps] def submonoid_map (e : M ≃* N) (S : submonoid M) : S ≃* S.map e.to_monoid_hom := { to_fun := Ξ» x, ⟨e x, _⟩, inv_fun := Ξ» x, ⟨e.symm x, _⟩, -- we restate this for `simps` to avoid `⇑e.symm.to_equiv x` ..e.to_monoid_hom.submonoid_map S, ..e.to_equiv.image S } end mul_equiv section actions /-! ### Actions by `submonoid`s These instances tranfer the action by an element `m : M` of a monoid `M` written as `m β€’ a` onto the action by an element `s : S` of a submonoid `S : submonoid M` such that `s β€’ a = (s : M) β€’ a`. These instances work particularly well in conjunction with `monoid.to_mul_action`, enabling `s β€’ m` as an alias for `↑s * m`. -/ namespace submonoid variables {M' : Type*} {Ξ± Ξ² : Type*} section mul_one_class variables [mul_one_class M'] @[to_additive] instance [has_smul M' Ξ±] (S : submonoid M') : has_smul S Ξ± := has_smul.comp _ S.subtype @[to_additive] instance smul_comm_class_left [has_smul M' Ξ²] [has_smul Ξ± Ξ²] [smul_comm_class M' Ξ± Ξ²] (S : submonoid M') : smul_comm_class S Ξ± Ξ² := ⟨λ a, (smul_comm (a : M') : _)⟩ @[to_additive] instance smul_comm_class_right [has_smul Ξ± Ξ²] [has_smul M' Ξ²] [smul_comm_class Ξ± M' Ξ²] (S : submonoid M') : smul_comm_class Ξ± S Ξ² := ⟨λ a s, (smul_comm a (s : M') : _)⟩ /-- Note that this provides `is_scalar_tower S M' M'` which is needed by `smul_mul_assoc`. -/ instance [has_smul Ξ± Ξ²] [has_smul M' Ξ±] [has_smul M' Ξ²] [is_scalar_tower M' Ξ± Ξ²] (S : submonoid M') : is_scalar_tower S Ξ± Ξ² := ⟨λ a, (smul_assoc (a : M') : _)⟩ @[to_additive] lemma smul_def [has_smul M' Ξ±] {S : submonoid M'} (g : S) (m : Ξ±) : g β€’ m = (g : M') β€’ m := rfl instance [has_smul M' Ξ±] [has_faithful_smul M' Ξ±] (S : submonoid M') : has_faithful_smul S Ξ± := ⟨λ x y h, subtype.ext $ eq_of_smul_eq_smul h⟩ end mul_one_class variables [monoid M'] /-- The action by a submonoid is the action by the underlying monoid. -/ @[to_additive /-"The additive action by an add_submonoid is the action by the underlying add_monoid. "-/] instance [mul_action M' Ξ±] (S : submonoid M') : mul_action S Ξ± := mul_action.comp_hom _ S.subtype /-- The action by a submonoid is the action by the underlying monoid. -/ instance [add_monoid Ξ±] [distrib_mul_action M' Ξ±] (S : submonoid M') : distrib_mul_action S Ξ± := distrib_mul_action.comp_hom _ S.subtype /-- The action by a submonoid is the action by the underlying monoid. -/ instance [monoid Ξ±] [mul_distrib_mul_action M' Ξ±] (S : submonoid M') : mul_distrib_mul_action S Ξ± := mul_distrib_mul_action.comp_hom _ S.subtype example {S : submonoid M'} : is_scalar_tower S M' M' := by apply_instance end submonoid end actions
1d9681b1e32ae67a273fb2535e6998180f7e755c
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/linear_algebra/finite_dimensional.lean
685557a179bc72ae912002400a3c42a97485cb4b
[ "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
6,347
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition and basic properties of finite dimensional vector spaces. The class `finite_dimensional` is defined to be `is_noetherian`, for ease of transfer of proofs. However an additional constructor `finite_dimensional.of_fg` is provided to prove finite dimensionality in a conventional manner. Also defined is `findim`, the dimension of a finite dimensional space, returning a `nat`, as opposed to `dim`, which returns a `cardinal`, -/ import ring_theory.noetherian linear_algebra.dimension import ring_theory.principal_ideal_domain universes u v w open vector_space cardinal submodule module function variables {K : Type u} {V : Type v} [discrete_field K] [add_comm_group V] [vector_space K V] /-- `finite_dimensional` vector spaces are defined to be noetherian modules. Use `finite_dimensional.of_fg` to prove finite dimensional from a conventional definition. -/ @[reducible] def finite_dimensional (K V : Type*) [discrete_field K] [add_comm_group V] [vector_space K V] := is_noetherian K V namespace finite_dimensional open is_noetherian lemma finite_dimensional_iff_dim_lt_omega : finite_dimensional K V ↔ dim K V < omega.{v} := begin cases exists_is_basis K V with b hb, have := is_basis.mk_eq_dim hb, simp only [lift_id] at this, rw [← this, lt_omega_iff_fintype, ← @set.set_of_mem_eq _ b, ← subtype.val_range], split, { intro, resetI, convert finite_of_linear_independent hb.1, simp }, { assume hbfinite, refine @is_noetherian_of_linear_equiv K (⊀ : submodule K V) V _ _ _ _ _ (linear_equiv.of_top _ rfl) (id _), refine is_noetherian_of_fg_of_noetherian _ ⟨set.finite.to_finset hbfinite, _⟩, rw [set.finite.coe_to_finset, ← hb.2], refl } end lemma dim_lt_omega (K V : Type*) [discrete_field K] [add_comm_group V] [vector_space K V] : βˆ€ [finite_dimensional K V], dim K V < omega.{v} := finite_dimensional_iff_dim_lt_omega.1 set_option pp.universes true lemma of_fg (hfg : (⊀ : submodule K V).fg) : finite_dimensional K V := let ⟨s, hs⟩ := hfg in begin rw [finite_dimensional_iff_dim_lt_omega, ← dim_top, ← hs], exact lt_of_le_of_lt (dim_span_le _) (lt_omega_iff_finite.2 (set.finite_mem_finset s)) end lemma exists_is_basis_finite (K V : Type*) [discrete_field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] : βˆƒ s : set V, (is_basis K (subtype.val : s β†’ V)) ∧ s.finite := begin cases exists_is_basis K V with s hs, exact ⟨s, hs, finite_of_linear_independent hs.1⟩ end instance [finite_dimensional K V] (S : submodule K V) : finite_dimensional K S := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_omega K V)) noncomputable def findim (K V : Type*) [discrete_field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] : β„• := classical.some (lt_omega.1 (dim_lt_omega K V)) lemma findim_eq_dim (K : Type u) (V : Type v) [discrete_field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] : (findim K V : cardinal.{v}) = dim K V := (classical.some_spec (lt_omega.1 (dim_lt_omega K V))).symm lemma card_eq_findim [finite_dimensional K V] {s : set V} {hfs : fintype s} (hs : is_basis K (Ξ» x : s, x.val)) : fintype.card s = findim K V := by rw [← nat_cast_inj.{v}, findim_eq_dim, ← fintype_card, ← lift_inj, ← hs.mk_eq_dim] lemma eq_top_of_findim_eq [finite_dimensional K V] {S : submodule K V} (h : findim K S = findim K V) : S = ⊀ := begin cases exists_is_basis K S with bS hbS, have : linear_independent K (subtype.val : (subtype.val '' bS : set V) β†’ V), from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ (submodule.subtype S) hbS.1 (by simp), cases exists_subset_is_basis this with b hb, letI : fintype b := classical.choice (finite_of_linear_independent hb.2.1), letI : fintype (subtype.val '' bS) := classical.choice (finite_of_linear_independent this), letI : fintype bS := classical.choice (finite_of_linear_independent hbS.1), have : subtype.val '' bS = b, from set.eq_of_subset_of_card_le hb.1 (by rw [set.card_image_of_injective _ subtype.val_injective, card_eq_findim hbS, card_eq_findim hb.2, h]; apply_instance), erw [← hb.2.2, subtype.val_range, ← this, set.set_of_mem_eq, ← subtype_eq_val, span_image], have := hbS.2, erw [subtype.val_range, set.set_of_mem_eq] at this, rw [this, map_top (submodule.subtype S), range_subtype], end end finite_dimensional namespace linear_map open finite_dimensional lemma surjective_of_injective [finite_dimensional K V] {f : V β†’β‚—[K] V} (hinj : injective f) : surjective f := begin have h := dim_eq_injective _ hinj, rw [← findim_eq_dim, ← findim_eq_dim, nat_cast_inj] at h, exact range_eq_top.1 (eq_top_of_findim_eq h.symm) end lemma injective_iff_surjective [finite_dimensional K V] {f : V β†’β‚—[K] V} : injective f ↔ surjective f := by classical; exact ⟨surjective_of_injective, Ξ» hsurj, let ⟨g, hg⟩ := exists_right_inverse_linear_map_of_surjective (range_eq_top.2 hsurj) in have function.right_inverse g f, from Ξ» x, show (linear_map.comp f g) x = (@linear_map.id K V _ _ _ : V β†’ V) x, by rw hg, injective_of_has_left_inverse ⟨g, left_inverse_of_surjective_of_right_inverse (surjective_of_injective (injective_of_has_left_inverse ⟨_, this⟩)) this⟩⟩ lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V β†’β‚—[K] V} : f.ker = βŠ₯ ↔ f.range = ⊀ := by rw [range_eq_top, ker_eq_bot, injective_iff_surjective] lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V β†’β‚—[K] V} (hfg : f * g = 1) : g * f = 1 := by classical; exact have ginj : injective g, from injective_of_has_left_inverse ⟨f, Ξ» x, show (f * g) x = (1 : V β†’β‚—[K] V) x, by rw hfg; refl⟩, let ⟨i, hi⟩ := exists_right_inverse_linear_map_of_surjective (range_eq_top.2 (injective_iff_surjective.1 ginj)) in have f * (g * i) = f * 1, from congr_arg _ hi, by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this lemma mul_eq_one_comm [finite_dimensional K V] {f g : V β†’β‚—[K] V} : f * g = 1 ↔ g * f = 1 := ⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩ end linear_map
30e1116d143b5aaf3b139dd8ad2f243c785bafb5
b87641ffb6358d6508ccbfa54e67c87070cb28d8
/ap_cat/src/function.lean
e7be07bca01a945b3b4112fc4b2b104a1ab40519
[]
no_license
Nolrai/LeanGiggle
a4b628745ae3f5a36ae79b673ee8543e18ed4899
8326b2a6685b60a3529ee0fe26bd86f5d849b071
refs/heads/master
1,545,396,766,168
1,538,238,458,000
1,538,238,458,000
105,524,473
0
0
null
null
null
null
UTF-8
Lean
false
false
33
lean
section pointwise end pointwise
fb682153d36ea3ba005a915fb4df2adfd0df5e7d
5d76f062116fa5bd22eda20d6fd74da58dba65bb
/src/snarks/plonk/knowledge_soundness.lean
3cf92f1049524c0999d93e16e000b25aac9b90d0
[]
no_license
brando90/formal_baby_snark
59e4732dfb43f97776a3643f2731262f58d2bb81
4732da237784bd461ff949729cc011db83917907
refs/heads/master
1,682,650,246,414
1,621,103,975,000
1,621,103,975,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
115
lean
/-! # Knowledge Soundness This file proves (TODO) the knowledge-soundness property of the PLONK snark scheme -/
a88e67367779fc620e9f21ff78755c102139a49d
f9a7d3a53167ab6bc77459dc7157a73c60f8aa5c
/utils.lean
60417abe454da00a6e90c4079784f127b31754e2
[]
no_license
Leangrids/grids
4ab67d0eaade70992ecf8eeea497ccaecfef881e
7ccc15b3051465c9cceedfbc57a3e06ddb1c8209
refs/heads/master
1,585,185,592,980
1,533,970,440,000
1,533,970,440,000
144,362,506
0
0
null
null
null
null
UTF-8
Lean
false
false
34,052
lean
import data.int.basic namespace utils open int nat list lemma gt_both_of_mult {m n : β„•} (h : m * n > 0) : m > 0 ∧ n > 0 := and.intro begin cases m, {rw zero_mul at h, cases h}, {apply nat.zero_lt_succ} end begin cases n, {cases h}, {apply nat.zero_lt_succ} end lemma gt_mult_of_both {m n : β„•} (h : m > 0) (h₁ : n > 0) : m * n > 0 := begin suffices hβ‚‚ : 0 * n < m * n, rw zero_mul at hβ‚‚, exact hβ‚‚, apply mul_lt_mul_of_pos_right; assumption end lemma lt_of_coe_lt_gt_zero {x : β„€} {y : β„•} (h : y > 0) : x < x + ↑y := begin apply lt_add_of_pos_right, simp [(>)] at *, exact h end lemma lt_of_add {m n k : β„•} (h : m + n < k) : m < k := begin induction n with n ih, {exact h}, { apply ih, rw [add_comm, nat.succ_add] at h, have h : n + m < k, from nat.lt_of_succ_lt h, rw add_comm, exact h } end lemma nat_le_dest : βˆ€ {n m : β„•}, n < m β†’ βˆƒ k, nat.succ n + k = m | n ._ (less_than_or_equal.refl ._) := ⟨0, rfl⟩ | n ._ (@less_than_or_equal.step ._ m h) := match le.dest h with | ⟨w, hw⟩ := ⟨succ w, hw β–Έ rfl⟩ end lemma zip_nil_right {Ξ± Ξ² : Type} {l : list Ξ±} : zip l ([] : list Ξ²) = [] := by cases l; refl lemma zip_nil_iff {Ξ± Ξ² : Type} (l₁ : list Ξ±) (lβ‚‚ : list Ξ²) : list.zip l₁ lβ‚‚ = [] ↔ l₁ = [] ∨ lβ‚‚ = [] := iff.intro (Ξ»h, by cases l₁; cases lβ‚‚; finish) (Ξ»h, begin cases h with h₁ h₁; rw h₁; unfold zip zip_with, exact zip_nil_right end) lemma zip_with_len_l {Ξ± Ξ² Ξ³ : Type*} {l₁ : list Ξ±} {lβ‚‚ : list Ξ²} {f : Ξ± β†’ Ξ² β†’ Ξ³} (h : length l₁ = length lβ‚‚) : length (zip_with f l₁ lβ‚‚) = length l₁ := begin induction l₁ with x xs ih generalizing lβ‚‚, {simp [zip_with]}, { cases lβ‚‚ with y ys, {injection h}, { simp only [zip_with, length], rw ih, injection h } } end lemma zip_with_len_r {Ξ± Ξ² Ξ³ : Type*} {l₁ : list Ξ±} {lβ‚‚ : list Ξ²} {f : Ξ± β†’ Ξ² β†’ Ξ³} (h : length l₁ = length lβ‚‚) : length (zip_with f l₁ lβ‚‚) = length lβ‚‚ := begin induction l₁ with x xs ih generalizing lβ‚‚, {rw ← h, simp [zip_with]}, { cases lβ‚‚ with y ys, {injection h}, { simp only [zip_with, length], rw ih, injection h } } end lemma repeat_nil {Ξ± : Type} (x : Ξ±) (n : β„•) : list.repeat x n = [] ↔ n = 0 := iff.intro (Ξ»h, begin cases n, refl, unfold list.repeat at h, cases h end) (Ξ»h, by rw h; refl) lemma nat_abs_zero_iff (a b : β„€) : nat_abs (a - b) = 0 ↔ a = b := iff.intro begin generalize h : a - b = c, intros, cases c; dsimp at a_1, rw a_1 at h, apply eq_of_sub_eq_zero, rw of_nat_zero at h, exact h, cases a_1 end begin generalize h : a - b = c, intros, rw a_1 at h, rw sub_self at h, rw ← h, refl end lemma join_empty_of_all_empty {Ξ± : Type*} (xs : list (list Ξ±)) (h : (βˆ€x, x ∈ xs β†’ x = [])) : join xs = [] := begin induction xs with x xs ih, {refl}, { unfold join, have h₁ : x = [], from h _ (by left; refl), rw h₁, rw nil_append, apply ih, intros x₁, specialize h x₁, intros hβ‚‚, apply h, right, exact hβ‚‚ } end lemma repeat_more {Ξ± : Type} (x : Ξ±) (n : β„•) (h : n β‰₯ 1) : repeat x n = x :: repeat x (n - 1) := begin cases n, cases h, dsimp, apply congr_arg, rw sub_one, refl end lemma one_le_succ (a : β„•) : 1 ≀ nat.succ a := begin induction a, exact le_refl _, constructor, exact a_ih end lemma nat_abs_of_lt {a b : β„€} (h : a < b) : nat_abs (b - a) β‰₯ 1 := have h₁ : b - a > 0, from sub_pos_of_lt h, begin simp only [(β‰₯)], rw [← coe_nat_le, nat_abs_of_nonneg (int.le_of_lt h₁), int.coe_nat_one], conv { to_lhs, rw ← zero_add (1 : β„€) }, apply add_one_le_of_lt, exact h₁ end lemma neg_lt_of_succ (n : β„•) (a : β„€) (h : a β‰₯ 0) : -↑n < a + (1 : β„€) := have h₁ : -↑n ≀ (0 : β„€), {rw neg_le, rw neg_zero, trivial}, have hβ‚‚ : 0 < a + 1, {rw lt_add_one_iff, exact h}, lt_of_le_of_lt h₁ hβ‚‚ section bounded variables {Ξ± : Type} [decidable_linear_order Ξ±] def bounded (a b : Ξ±) := {x : Ξ± // a ≀ x ∧ x < b} def is_bounded (a b : Ξ±) (y : Ξ±) := a ≀ y ∧ y < b lemma is_bounded_of_bounds {a b y : Ξ±} (h : a ≀ y) (h₁ : y < b) : is_bounded a b y := and.intro h h₁ instance is_bounded_dec (a b y : Ξ±) : decidable (is_bounded a b y) := by simp [is_bounded]; apply_instance def make_bounded {a b : Ξ±} {x : Ξ±} (h : is_bounded a b x) : bounded a b := ⟨x, h⟩ def z_of_bounded {a b : Ξ±} (b : bounded a b) := match b with ⟨z, _⟩ := z end def bounded_to_str [Ο† : has_to_string Ξ±] {a b : Ξ±} : bounded a b β†’ string := to_string ∘ z_of_bounded instance bounded_repr {a b : Ξ±} [has_to_string Ξ±] : has_repr (bounded a b) := ⟨bounded_to_str⟩ instance bounded_str (a b : Ξ±) [has_to_string Ξ±] : has_to_string (bounded a b) := ⟨bounded_to_str⟩ instance bounded_to_carrier_coe (a b : Ξ±) : has_coe (bounded a b) Ξ± := ⟨z_of_bounded⟩ instance zbound_dec_eq {a b : Ξ±} : decidable_eq (bounded a b) | ⟨x, _⟩ ⟨y, _⟩ := by apply_instance instance coe_bounded {Ξ± : Type} {a b : Ξ±} [decidable_linear_order Ξ±] : has_coe (@bounded Ξ± _ a b) Ξ± := ⟨z_of_bounded⟩ lemma coe_is_z_of_bounded {Ξ± : Type} {a b : Ξ±} [decidable_linear_order Ξ±] (x : bounded a b) : z_of_bounded x = ↑x := rfl lemma positive_bounded {x : β„•} (a : bounded 0 x) : ↑a β‰₯ 0 := let ⟨a, ⟨l, r⟩⟩ := a in by rw ← coe_is_z_of_bounded; simpa [z_of_bounded] lemma bounded_lt {x : β„•} (a : bounded 0 x) : ↑a < x := let ⟨a, ⟨l, r⟩⟩ := a in by rw ← coe_is_z_of_bounded; simpa [z_of_bounded] end bounded structure point := (x : β„€) (y : β„€) private def point_rep : point β†’ string | ⟨x, y⟩ := "[" ++ to_string x ++ ", " ++ to_string y ++ "]" def point_eq (p₁ pβ‚‚ : point) := p₁.x = pβ‚‚.x ∧ p₁.y = pβ‚‚.y instance dec_eq_p {p₁ pβ‚‚} : decidable (point_eq p₁ pβ‚‚) := by simp [point_eq]; apply_instance instance dec_eq_point : decidable_eq point := λ⟨x₁, yβ‚βŸ© ⟨xβ‚‚, yβ‚‚βŸ©, begin by_cases h₁ : x₁ = xβ‚‚; by_cases hβ‚‚ : y₁ = yβ‚‚, { apply is_true, rw h₁, rw hβ‚‚ }, { apply is_false, rw h₁, intros contra, injection contra, contradiction }, { apply is_false, rw hβ‚‚, intros contra, injection contra, contradiction }, { apply is_false, intros contra, injection contra, contradiction } end instance : has_to_string point := ⟨point_rep⟩ instance : has_repr point := ⟨point_rep⟩ def grid_sorted : point β†’ point β†’ Prop | ⟨x, y⟩ ⟨x₁, yβ‚βŸ© := x < x₁ ∧ y₁ < y infix `β†—` : 50 := grid_sorted instance {a b : point} : decidable (a β†— b) := let ⟨x, y⟩ := a in let ⟨x₁, yβ‚βŸ© := b in by simp [(β†—)]; apply_instance instance {a b : point} : is_irrefl point grid_sorted := { irrefl := λ⟨x, y⟩, begin simp [(β†—)], intros contra, refl end } instance {a b : point} : is_trans point grid_sorted := { trans := λ⟨x, y⟩ ⟨x₁, yβ‚βŸ© ⟨xβ‚‚, yβ‚‚βŸ© ⟨h, hβ‚βŸ© ⟨hβ‚‚, hβ‚ƒβŸ©, begin simp [(β†—)] at *, exact and.intro (lt_trans h hβ‚‚) (lt_trans h₃ h₁) end } instance {a b : point} [c : is_irrefl point grid_sorted] [c₁ : is_trans point grid_sorted] : is_strict_order point grid_sorted := by constructor; assumption def le_of_add_le_left (a b c : β„€) (h₁ : 0 ≀ b) (hβ‚‚ : a + b ≀ c) : a ≀ c := begin apply (@le_of_add_le_add_right _ _ a b c), apply le_add_of_le_of_nonneg; assumption end lemma grid_bounded_iff {p₁ pβ‚‚ : point} : p₁↗pβ‚‚ ↔ (p₁.x < pβ‚‚.x ∧ pβ‚‚.y < p₁.y) := by cases p₁; cases pβ‚‚; simp [(β†—)] lemma length_zip_left {Ξ± Ξ² : Type*} {l₁ : list Ξ±} {lβ‚‚ : list Ξ²} (h : length l₁ = length lβ‚‚) : length (zip l₁ lβ‚‚) = length l₁ := begin induction l₁ generalizing lβ‚‚; cases lβ‚‚, refl, cases h, cases h, unfold zip zip_with, dsimp, repeat {rw add_one}, apply congr_arg, apply l₁_ih, dsimp at h, injection h end lemma not_grid_bounded_iff {p₁ pβ‚‚ : point} : Β¬p₁↗pβ‚‚ ↔ (pβ‚‚.x ≀ p₁.x ∨ p₁.y ≀ pβ‚‚.y) := begin cases p₁; cases pβ‚‚, unfold point.x point.y, simp [(β†—)], split; intros h, { by_cases h₁ : p₁_x < pβ‚‚_x, have h := h h₁, right, exact h, rw not_lt_iff_eq_or_lt at h₁, cases h₁, rw h₁, left, refl, left, apply int.le_of_lt, assumption }, { intros h₁, cases h, have contra : p₁_x < p₁_x, from lt_of_lt_of_le h₁ h, have contra₁ : Β¬p₁_x < p₁_x, from lt_irrefl _, contradiction, exact h } end lemma abs_nat_lt : βˆ€n m : β„€, (0 ≀ n) β†’ n < m β†’ nat_abs n < nat_abs m | (of_nat n₁) (of_nat nβ‚‚) zlen nltm := begin dsimp, revert n₁, induction nβ‚‚; intros; cases n₁, {cases nltm}, {cases nltm}, {apply zero_lt_succ}, {apply succ_lt_succ, apply nβ‚‚_ih, {cases n₁, apply le_refl, rewrite of_nat_succ, rewrite add_comm, unfold has_le.le}, {rewrite of_nat_succ at nltm, rewrite of_nat_succ at nltm, apply lt_of_add_lt_add_right nltm} } end def range_weaken_lower_any {a b c : β„€} (h : c ≀ a) : bounded a b β†’ bounded c b | ⟨i, ⟨lbound, rbound⟩⟩ := ⟨i, and.intro (le_trans h lbound) rbound⟩ def range_weaken_upper_any {a b c : β„€} (h : b ≀ c) : bounded a b β†’ bounded a c | ⟨i, ⟨lbound, rbound⟩⟩ := ⟨i, and.intro lbound (have h : b < c ∨ b = c, from lt_or_eq_of_le h, or.elim h (assume h, lt_trans rbound h) (by cc))⟩ def range_weaken {a b : β„€} (h : bounded (a + 1) b) : bounded a b := range_weaken_lower_any (le_of_add_le_left _ 1 _ dec_trivial (le_refl _)) h def range : βˆ€(a b : β„€), list (bounded a b) | fro to := if h : fro < to then ⟨fro, and.intro (le_refl _) h⟩ :: list.map range_weaken (range (fro + 1) to) else [] using_well_founded { rel_tac := Ξ»f args, `[exact ⟨ measure (λ⟨fro, to⟩, nat_abs (to - fro)), measure_wf _ ⟩], dec_tac := `[apply abs_nat_lt, {rewrite ← sub_sub, have h₁ : 0 < to - fro, apply sub_pos_of_lt, exact h, have hβ‚‚ : 0 + 1 < (to - fro) + 1, apply add_lt_add_of_lt_of_le, exact h₁, reflexivity, have h₃ : (0 + 1 : β„€) = 1, exact dec_trivial, rw h₃ at hβ‚‚, have hβ‚„ : (0 + 1 ≀ to - fro - 1 + 1) β†’ 0 ≀ to - fro - 1, exact le_of_add_le_add_right, apply hβ‚„, rw h₃, rewrite sub_eq_add_neg, rewrite sub_eq_add_neg, rewrite add_assoc, have hβ‚… : (-1 + 1 : β„€) = 0, exact dec_trivial, rewrite hβ‚…, rewrite add_assoc, rewrite add_comm, rewrite add_zero, rewrite add_comm, have h₆ : to + -fro = to - fro, refl, rewrite h₆, unfold has_lt.lt int.lt at h₁, rewrite h₃ at h₁, exact h₁}, {rewrite ← sub_sub, apply lt_of_le_sub_one, reflexivity}] } def range_pure : β„€ β†’ β„€ β†’ list β„€ | fro to := if h : fro < to then fro :: range_pure (fro + 1) to else [] using_well_founded { rel_tac := Ξ»f args, `[exact ⟨ measure (λ⟨a, b⟩, nat_abs (b - a)), measure_wf _ ⟩], dec_tac := `[ apply abs_nat_lt, { rewrite ← sub_sub, have h₁ : 0 < to - fro, apply sub_pos_of_lt, exact h, have hβ‚‚ : 0 + 1 < (to - fro) + 1, apply add_lt_add_of_lt_of_le, exact h₁, reflexivity, have h₃ : (0 + 1 : β„€) = 1, exact dec_trivial, rw h₃ at hβ‚‚, have hβ‚„ : (0 + 1 ≀ to - fro - 1 + 1) β†’ 0 ≀ to - fro - 1, exact le_of_add_le_add_right, apply hβ‚„, rw h₃, rewrite sub_eq_add_neg, rewrite sub_eq_add_neg, rewrite add_assoc, have hβ‚… : (-1 + 1 : β„€) = 0, exact dec_trivial, rewrite hβ‚…, rewrite add_assoc, rewrite add_comm, rewrite add_zero, rewrite add_comm, have h₆ : to + -fro = to - fro, refl, rewrite h₆, unfold has_lt.lt int.lt at h₁, rewrite h₃ at h₁, exact h₁ }, { rewrite ← sub_sub, apply lt_of_le_sub_one, reflexivity } ] } lemma range_pure_cons {a b} {x xs} (h : range_pure a b = x :: xs) : range_pure (a + 1) b = xs := begin have h₁ : a < b, { by_cases hβ‚‚ : a < b, {exact hβ‚‚}, { unfold1 range_pure at h, rw if_neg hβ‚‚ at h, cases h }, }, unfold1 range_pure at h, rw if_pos h₁ at h, injection h end lemma range_pure_bounded {a b : β„€} : βˆ€{c}, c ∈ range_pure a b β†’ is_bounded a b c := assume c, begin generalize h : range_pure a b = l, induction l with x xs ih generalizing a b; intros h₁, { cases h₁ }, { rw mem_cons_iff at h₁, cases h₁ with h₁, { subst h₁, unfold1 range_pure at h, by_cases hβ‚‚ : a < b; simp [hβ‚‚] at h, { cases h with hl hr, subst hl, split, refl, exact hβ‚‚ }, { cases h } }, { have hβ‚‚ : a < b, { by_cases eq : a < b, {exact eq}, { unfold1 range_pure at h, rw if_neg eq at h, cases h }, }, unfold1 range_pure at h, rw if_pos hβ‚‚ at h, injection h with hl hr, have ih₁ := @ih (a + 1) b hr h₁, cases ih₁ with lb ub, split, { have lb := lt_of_add_one_le lb, exact int.le_of_lt lb }, { exact ub } } } end def range_pure_m (a b : β„€) : list β„€ := map z_of_bounded (range a b) lemma range_empty_iff (a b : β„€) : range a b = [] ↔ (b ≀ a) := begin split; intros h, { unfold1 range at h, by_cases h₁ : a < b; simp [h₁] at h, {contradiction}, {finish}, }, { unfold1 range, by_cases h₁ : a < b; simp [h₁], have contra : Β¬b ≀ a, from not_le_of_gt h₁, contradiction } end lemma range_length_same (a : β„€) : length (range a a) = 0 := begin unfold1 range, have h : Β¬a < a, from lt_irrefl _, simp [h] end lemma range_length_one (a : β„€) : length (range a (a + 1)) = 1 := begin unfold1 range, have h : a < a + 1, from lt_add_succ _ _, simp [h], rw range_length_same end lemma range_pure_length_same (a : β„€) : length (range_pure a a) = 0 := begin unfold1 range_pure, have h : Β¬a < a, from lt_irrefl _, simp [h] end lemma range_pure_length_one (a : β„€) : length (range_pure a (a + 1)) = 1 := begin unfold1 range_pure, have h : a < a + 1, from lt_add_succ _ _, simp [h], rw range_pure_length_same end lemma range_length {a b : β„€} (h : a ≀ b) : length (range a b) = nat_abs (b - a) := begin generalize h₁ : nat_abs (b - a) = n, induction n with n ih generalizing a b, { rw nat_abs_zero_iff at h₁, rw h₁, exact range_length_same _ }, { have hβ‚‚ : a < b, begin rw le_iff_eq_or_lt at h, cases h, { have h : b = a, by cc, rw ← nat_abs_zero_iff at h, rw h at h₁, cases h₁ }, {exact h} end, clear h, have h₃ : a + 1 ≀ b, from add_one_le_of_lt hβ‚‚, have hβ‚„ : nat_abs (b - (a + 1)) = n, begin rw ← sub_sub, rw ← int.coe_nat_eq_coe_nat_iff, have hβ‚… : b - a - 1 β‰₯ (0 : β„€), { simp [(β‰₯)], rw ← add_le_add_iff_right (1 : β„€), rw zero_add, rw ← sub_eq_add_neg, rw add_sub, rw ← sub_eq_add_neg, rw sub_add_cancel, rw ← add_le_add_iff_right a, rw sub_add_cancel, rw add_comm, exact h₃ }, rw nat_abs_of_nonneg hβ‚…, rw ← add_right_cancel_iff, any_goals {exact (1 : β„€)}, rw sub_add_cancel, have h₆ : b - a β‰₯ (0 : β„€), { simp [(β‰₯)], rw ← sub_lt_sub_iff_right a at hβ‚‚, rw sub_self at hβ‚‚, apply int.le_of_lt, exact hβ‚‚ }, rw ← int.coe_nat_eq_coe_nat_iff at h₁, rw nat_abs_of_nonneg h₆ at h₁, exact h₁ end, have ih := ih h₃ hβ‚„, unfold1 range at ih, rw le_iff_eq_or_lt at h₃, cases h₃, { have h₇ : Β¬a + 1 < b, rw ← h₃, intros contra, have hβ‚ˆ : Β¬a + 1 < a + 1, from lt_irrefl _, contradiction, simp [h₇] at ih, rw ← ih, rw ← h₃, rw range_length_one }, { simp [h₃] at ih, unfold1 range, simp [hβ‚‚], unfold1 range, simp [h₃], rw ← ih, rw ← one_add } } end lemma range_length_pure {a b : β„€} (h : a ≀ b) : length (range_pure a b) = nat_abs (b - a) := begin generalize h₁ : nat_abs (b - a) = n, induction n with n ih generalizing a b, { rw nat_abs_zero_iff at h₁, rw h₁, exact range_pure_length_same _ }, { have hβ‚‚ : a < b, begin rw le_iff_eq_or_lt at h, cases h, { have h : b = a, by cc, rw ← nat_abs_zero_iff at h, rw h at h₁, cases h₁ }, {exact h} end, clear h, have h₃ : a + 1 ≀ b, from add_one_le_of_lt hβ‚‚, have hβ‚„ : nat_abs (b - (a + 1)) = n, begin rw ← sub_sub, rw ← int.coe_nat_eq_coe_nat_iff, have hβ‚… : b - a - 1 β‰₯ (0 : β„€), { simp [(β‰₯)], rw ← add_le_add_iff_right (1 : β„€), rw zero_add, rw ← sub_eq_add_neg, rw add_sub, rw ← sub_eq_add_neg, rw sub_add_cancel, rw ← add_le_add_iff_right a, rw sub_add_cancel, rw add_comm, exact h₃ }, rw nat_abs_of_nonneg hβ‚…, rw ← add_right_cancel_iff, any_goals {exact (1 : β„€)}, rw sub_add_cancel, have h₆ : b - a β‰₯ (0 : β„€), { simp [(β‰₯)], rw ← sub_lt_sub_iff_right a at hβ‚‚, rw sub_self at hβ‚‚, apply int.le_of_lt, exact hβ‚‚ }, rw ← int.coe_nat_eq_coe_nat_iff at h₁, rw nat_abs_of_nonneg h₆ at h₁, exact h₁ end, have ih := ih h₃ hβ‚„, unfold1 range_pure at ih, rw le_iff_eq_or_lt at h₃, cases h₃, { have h₇ : Β¬a + 1 < b, rw ← h₃, intros contra, have hβ‚ˆ : Β¬a + 1 < a + 1, from lt_irrefl _, contradiction, simp [h₇] at ih, rw ← ih, rw ← h₃, rw range_pure_length_one }, { simp [h₃] at ih, unfold1 range_pure, simp [hβ‚‚], unfold1 range_pure, simp [h₃], rw ← ih, rw ← one_add } } end open list function def empty_list {Ξ± : Type} (l : list Ξ±) := [] = l lemma not_empty_of_len {Ξ± : Type} {l : list Ξ±} (h : length l > 0) : Β¬empty_list l := begin simp [empty_list], cases l, { cases h }, { trivial } end lemma empty_list_eq_ex {Ξ± : Type} {l : list Ξ±} (h : Β¬empty_list l) : βˆƒ(x : Ξ±) (xs : list Ξ±), l = x :: xs := begin cases l, unfold empty_list at h, contradiction, existsi l_hd, existsi l_tl, refl end instance decidable_empty_list {Ξ± : Type} : βˆ€l : list Ξ±, decidable (empty_list l) | [] := is_true rfl | (x :: _) := is_false (by simp [empty_list]) theorem unempty_nil_eq_false {Ξ± : Type} : Β¬(empty_list (@nil Ξ±)) ↔ false := begin simp [empty_list] end def head1 {Ξ± : Type} (l : list Ξ±) (h : Β¬empty_list l) := match l, h with | [], p := by rw unempty_nil_eq_false at p; contradiction | (x :: _), _ := x end def foldr1 {Ξ± : Type} (f : Ξ± β†’ Ξ± β†’ Ξ±) (l : list Ξ±) (h : Β¬empty_list l) : Ξ± := match l, h with | [], p := by rw unempty_nil_eq_false at p; contradiction | (x :: xs), _ := foldr f x xs end lemma foldr1_unempty_eq_foldr {Ξ± : Type} (f : Ξ± β†’ Ξ± β†’ Ξ±) (l : list Ξ±) (h : Β¬empty_list l) : foldr1 f l h = list.foldr f (head1 l h) (tail l) := begin cases l, rw unempty_nil_eq_false at h, contradiction, unfold foldr1 head1 tail end def min_element {Ξ± : Type} [decidable_linear_order Ξ±] (l : list Ξ±) (h : Β¬empty_list l) := foldr1 min l h def max_element {Ξ± : Type} [decidable_linear_order Ξ±] (l : list Ξ±) (h : Β¬empty_list l) := foldr1 max l h lemma foldr_swap {Ξ± : Type*} (f : Ξ± β†’ Ξ± β†’ Ξ±) (h : is_commutative _ f) (h₁ : is_associative _ f) {x y : Ξ±} {xs : list Ξ±} : foldr f x (y :: xs) = foldr f y (x :: xs) := have comm : βˆ€a b, f a b = f b a, by finish, have assoc : βˆ€a b c, f a (f b c) = f (f a b) c, by finish, list.rec_on xs (comm _ _) (assume x₁ xs₁ ih, by dsimp at *; rw [assoc, comm y, ← assoc, ih, assoc, comm x₁, ← assoc]) lemma le_min_elem_all {Ξ± : Type*} [decidable_linear_order Ξ±] (l : list Ξ±) (b : Ξ±) (h : Β¬empty_list l) : (βˆ€x, x ∈ l β†’ b ≀ x) β†’ b ≀ min_element l h := assume h₁, begin induction l with y ys ih, { unfold empty_list at h, contradiction }, { unfold min_element foldr1, cases ys, { dsimp, apply h₁, left, refl }, { have ih := ih _ _, unfold min_element foldr1 at ih, rw foldr_swap min ⟨min_comm⟩ ⟨min_assoc⟩, dsimp at *, rw le_min_iff, split, { apply h₁, left, refl }, { exact ih_1 }, unfold empty_list, intros ok, cases ok, intros, apply h₁, right, simp [(∈)] at a, exact a } } end lemma max_le_elem_all {Ξ± : Type*} [decidable_linear_order Ξ±] (l : list Ξ±) (b : Ξ±) (h : Β¬empty_list l) : (βˆ€x, x ∈ l β†’ x ≀ b) β†’ max_element l h ≀ b := assume h₁, begin induction l with y ys ih, { unfold empty_list at h, contradiction }, { unfold max_element foldr1, cases ys, { dsimp, apply h₁, left, refl }, { have ih := ih _ _, unfold max_element foldr1 at ih, rw foldr_swap max ⟨max_comm⟩ ⟨max_assoc⟩, dsimp at *, rw max_le_iff, split, { apply h₁, left, refl }, { exact ih_1 }, unfold empty_list, intros ok, cases ok, intros, apply h₁, right, simp [(∈)] at a, exact a } } end lemma min_le_max {Ξ± : Type*} [decidable_linear_order Ξ±] (a : Ξ±) {b c : Ξ±} (H : b ≀ c) : min a b ≀ max a c := begin unfold min max, by_cases h : a ≀ b; simp [h]; by_cases h₁ : a ≀ c; simp [h₁], exact H, rw not_le at h, exact le_of_lt h end lemma min_elem_le_max_elem {Ξ± : Type*} [decidable_linear_order Ξ±] (l : list Ξ±) (h : Β¬empty_list l) : min_element l h ≀ max_element l h := begin unfold min_element max_element, cases l with x xs, unfold empty_list at h, contradiction, unfold foldr1, induction xs with y ys, {dsimp, refl}, { dsimp, have h₁ : Β¬empty_list (x :: ys), by unfold empty_list; intros; contradiction, have ih := xs_ih h₁, exact min_le_max y ih } end lemma map_empty_iff_l_empty {Ξ± Ξ² : Type} (f : Ξ± β†’ Ξ²) (l : list Ξ±) : empty_list (map f l) ↔ empty_list l := begin split; intros h; cases l; try {finish <|> simp [empty_list]} end lemma unzip_one {Ξ± Ξ² : Type} (l : Ξ±) (r : Ξ²) (xs : list (Ξ± Γ— Ξ²)) : unzip ((l, r) :: xs) = ((l :: (unzip xs).fst), r :: (unzip xs).snd) := begin simp [unzip], cases (unzip xs), simp [unzip] end lemma unzip_fst_empty_iff_l_empty {Ξ± Ξ² : Type} (l : list (Ξ± Γ— Ξ²)) : empty_list ((unzip l).fst) ↔ empty_list l := begin split; intros h; cases l; try {finish}; simp [empty_list, unzip] at *, cases l_hd, rw unzip_one at h, contradiction end lemma unzip_snd_empty_iff_l_empty {Ξ± Ξ² : Type} (l : list (Ξ± Γ— Ξ²)) : empty_list ((unzip l).snd) ↔ empty_list l := begin split; intros h; cases l; try {finish}; simp [empty_list, unzip] at *, cases l_hd, rw unzip_one at h, contradiction end lemma pair_in_zip_l {Ξ± Ξ²} {a b} {l₁ : list Ξ±} {lβ‚‚ : list Ξ²} (h : (a, b) ∈ zip l₁ lβ‚‚) : a ∈ l₁ := begin induction l₁ with x xs ih generalizing lβ‚‚, { simp [zip, zip_with] at h, contradiction }, { cases lβ‚‚ with y ys, { simp [zip, zip_with] at h, contradiction }, { unfold1 zip at h, unfold1 zip_with at h, rw mem_cons_iff at h, cases h, injection h with hl hr, subst hl, subst hr, left, refl, rw mem_cons_eq, right, apply ih, unfold zip, exact h } } end lemma pair_in_zip_r {Ξ± Ξ²} {a b} {l₁ : list Ξ±} {lβ‚‚ : list Ξ²} (h : (a, b) ∈ zip l₁ lβ‚‚) : b ∈ lβ‚‚ := begin induction l₁ with x xs ih generalizing lβ‚‚, { simp [zip, zip_with] at h, contradiction }, { cases lβ‚‚ with y ys, { simp [zip, zip_with] at h, contradiction }, { unfold1 zip at h, unfold1 zip_with at h, rw mem_cons_iff at h, cases h, injection h with hl hr, subst hl, subst hr, left, refl, rw mem_cons_eq, right, apply ih, unfold zip, exact h } } end def decidable_uncurry {Ξ± Ξ² : Type*} {f : Ξ± β†’ Ξ² β†’ Prop} {x : Ξ± Γ— Ξ²} (h : decidable (f x.fst x.snd)) : decidable (uncurry f x) := begin resetI, cases x, unfold_projs at *, simp [uncurry], exact h end lemma filter_forall {Ξ± : Type*} {P : Ξ± β†’ Prop} [decidable_pred P] (xs : list Ξ±) (x : Ξ±) (h₁ : x ∈ filter P xs) : P x := begin induction xs with x₁ xs₁ ih; simp [filter] at h₁, { contradiction }, { by_cases hβ‚‚ : (P x₁); simp [hβ‚‚] at h₁, {cases h₁, {cc}, {exact ih h₁}}, {exact ih h₁} } end lemma unempty_filter_ex {Ξ± : Type*} {xs : list Ξ±} {p : Ξ± β†’ Prop} [decidable_pred p] (h : Β¬empty_list (filter p xs)) : βˆƒx, x ∈ xs ∧ p x := begin induction xs with x₁ xs₁ ih, { dsimp at h, unfold empty_list at h, contradiction }, { by_cases h₁ : p x₁, { existsi x₁, finish }, { unfold empty_list at *, unfold filter at h, simp [h₁] at h, have ih := ih h, cases ih with xβ‚‚ pxβ‚‚, existsi xβ‚‚, simp [(∈), list.mem] at *, split, right, exact pxβ‚‚.left, exact pxβ‚‚.right } } end def conv {Ξ± : Type*} (f : Ξ± β†’ Type*) {a b : Ξ±} : a = b β†’ f a β†’ f b := assume h₁ hβ‚‚, by rw ← h₁; exact hβ‚‚ def list_iso {Ξ± : Type*} [decidable_eq Ξ±] : list Ξ± β†’ list Ξ± β†’ bool | [] [] := tt | (x :: xs) (y :: ys) := band (x = y) (list_iso xs ys) | _ _ := ff lemma list_iso_refl {Ξ± : Type*} [decidable_eq Ξ±] (l : list Ξ±) : list_iso l l := begin induction l; simp [list_iso], assumption end lemma list_iso_nil_l {Ξ± : Type*} [decidable_eq Ξ±] (l : list Ξ±) : list_iso nil l ↔ l = nil := iff.intro (Ξ»h, begin cases l with x xs, refl, simp [list_iso] at h, contradiction end) (Ξ»h, begin cases l with x xs, exact list_iso_refl _, cases h end) lemma list_iso_nil_r {Ξ± : Type*} [decidable_eq Ξ±] (l : list Ξ±) : list_iso l nil ↔ l = nil := iff.intro (Ξ»h, begin cases l with x xs, refl, simp [list_iso] at h, contradiction end) (Ξ»h, begin cases l with x xs, exact list_iso_refl _, cases h end) lemma list_iso_symm {Ξ± : Type*} [decidable_eq Ξ±] {l₁ lβ‚‚ : list Ξ±} (h : list_iso l₁ lβ‚‚) : list_iso lβ‚‚ l₁ := begin induction l₁ with x xs generalizing lβ‚‚; cases lβ‚‚ with y ys; try {assumption}, simp [list_iso], simp [list_iso] at h, cases h with h₁ hβ‚‚, rw and_iff_left, exact eq.symm h₁, apply l₁_ih, exact hβ‚‚ end lemma list_iso_trans {Ξ± : Type*} [decidable_eq Ξ±] {l₁ lβ‚‚ l₃ : list Ξ±} (h : list_iso l₁ lβ‚‚) (h₁ : list_iso lβ‚‚ l₃) : list_iso l₁ l₃ := begin induction l₁ with x xs ih generalizing lβ‚‚ l₃; cases l₃ with y ys, {exact list_iso_refl _}, { rw list_iso_nil_l at h, rw h at h₁, rw list_iso_nil_l at h₁, cases h₁ }, { rw list_iso_nil_r at h₁, rw h₁ at h, exact h }, { simp [list_iso], cases lβ‚‚ with z zs, { rw list_iso_nil_r at h, cases h }, { simp [list_iso] at h h₁, cases h₁, cases h, split, cc, apply ih, exact h_right, exact h₁_right } } end lemma list_iso_hd {Ξ± : Type*} [decidable_eq Ξ±] {x} {y} {xs ys : list Ξ±} (h : list_iso (x :: xs) (y :: ys)) : x = y := begin simp [list_iso] at h, exact h.left end lemma list_iso_tl {Ξ± : Type*} [decidable_eq Ξ±] {x} {y} {xs ys : list Ξ±} (h : list_iso (x :: xs) (y :: ys)) : list_iso xs ys := begin simp [list_iso] at h, exact h.right end lemma list_iso_iff {Ξ± : Type*} [decidable_eq Ξ±] {l₁ lβ‚‚ : list Ξ±} : list_iso l₁ lβ‚‚ ↔ l₁ = lβ‚‚ := begin split; intros h, { induction l₁ with x xs ih generalizing lβ‚‚, { cases lβ‚‚ with y ys, {refl}, {rw list_iso_nil_l at h, cases h} }, { cases lβ‚‚ with y ys, {rw list_iso_nil_r at h, cases h}, { have h₁ : x = y, from list_iso_hd h, congr, exact h₁, apply ih, apply list_iso_tl h } } }, { rw h, exact list_iso_refl _ } end def mod_self {n : β„•} : n % n = 0 := begin induction n with n ih, refl, rw nat.mod_def, rw if_pos, rw nat.sub_self, rw nat.zero_mod, split, rw succ_eq_add_one, rw add_comm, exact zero_lt_one_add _, refl end lemma repeat_bounded {Ξ± : Type*} {a : Ξ±} {b} : βˆ€{x}, x ∈ list.repeat a b β†’ x = a := assume x h, begin induction b with b ih, { cases h }, { simp at h, cases h, assumption, exact ih h } end end utils
61a81f9c6f0413ccea978b795ed97ec8338fceb5
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/real/nnreal.lean
7da97de35727aacff83b5692a4f892d7c0882898
[ "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
26,429
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import algebra.linear_ordered_comm_group_with_zero import algebra.big_operators.ring import data.real.basic import data.indicator_function noncomputable theory open_locale classical big_operators /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≀ r} localized "notation ` ℝβ‰₯0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝβ‰₯0 ℝ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : nnreal) : n.val = n := rfl instance : can_lift ℝ nnreal := { coe := coe, cond := Ξ» r, 0 ≀ r, prf := Ξ» x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝβ‰₯0} : (n : ℝ) = (m : ℝ) β†’ n = m := subtype.eq protected lemma eq_iff {n m : ℝβ‰₯0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) lemma ne_iff {x y : ℝβ‰₯0} : (x : ℝ) β‰  (y : ℝ) ↔ x β‰  y := not_iff_not_of_iff $ nnreal.eq_iff protected def of_real (r : ℝ) : ℝβ‰₯0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≀ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr lemma le_coe_of_real (r : ℝ) : r ≀ nnreal.of_real r := le_max_left r 0 lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≀ r := r.2 @[norm_cast] theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝβ‰₯0) : ℝ) = a := rfl instance : has_zero ℝβ‰₯0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝβ‰₯0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝβ‰₯0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝβ‰₯0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝβ‰₯0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝβ‰₯0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_le ℝβ‰₯0 := ⟨λ r s, (r:ℝ) ≀ s⟩ instance : has_bot ℝβ‰₯0 := ⟨0⟩ instance : inhabited ℝβ‰₯0 := ⟨0⟩ @[simp, norm_cast] protected lemma coe_eq {r₁ rβ‚‚ : ℝβ‰₯0} : (r₁ : ℝ) = rβ‚‚ ↔ r₁ = rβ‚‚ := subtype.ext_iff_val.symm @[simp, norm_cast] protected lemma coe_zero : ((0 : ℝβ‰₯0) : ℝ) = 0 := rfl @[simp, norm_cast] protected lemma coe_one : ((1 : ℝβ‰₯0) : ℝ) = 1 := rfl @[simp, norm_cast] protected lemma coe_add (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ + rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ + rβ‚‚ := rfl @[simp, norm_cast] protected lemma coe_mul (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ * rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ * rβ‚‚ := rfl @[simp, norm_cast] protected lemma coe_inv (r : ℝβ‰₯0) : ((r⁻¹ : ℝβ‰₯0) : ℝ) = r⁻¹ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℝβ‰₯0) : ((bit0 r : ℝβ‰₯0) : ℝ) = bit0 r := rfl @[simp, norm_cast] protected lemma coe_bit1 (r : ℝβ‰₯0) : ((bit1 r : ℝβ‰₯0) : ℝ) = bit1 r := rfl @[simp, norm_cast] protected lemma coe_sub {r₁ rβ‚‚ : ℝβ‰₯0} (h : rβ‚‚ ≀ r₁) : ((r₁ - rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ - rβ‚‚ := max_eq_left $ le_sub.2 $ by simp [show (rβ‚‚ : ℝ) ≀ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma coe_eq_zero (r : ℝβ‰₯0) : ↑r = (0 : ℝ) ↔ r = 0 := by norm_cast lemma coe_ne_zero {r : ℝβ‰₯0} : (r : ℝ) β‰  0 ↔ r β‰  0 := by norm_cast instance : comm_semiring ℝβ‰₯0 := begin refine { zero := 0, add := (+), one := 1, mul := (*), ..}; { intros; apply nnreal.eq; simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib, add_comm_monoid.zero, add_comm, add_left_comm] } end /-- Coercion `ℝβ‰₯0 β†’ ℝ` as a `ring_hom`. -/ def to_real_hom : ℝβ‰₯0 β†’+* ℝ := ⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩ @[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl instance : comm_group_with_zero ℝβ‰₯0 := { exists_pair_ne := ⟨0, 1, assume h, zero_ne_one $ nnreal.eq_iff.2 h⟩, inv_zero := nnreal.eq $ show (0⁻¹ : ℝ) = 0, from inv_zero, mul_inv_cancel := assume x h, nnreal.eq $ mul_inv_cancel $ ne_iff.2 h, .. (by apply_instance : has_inv ℝβ‰₯0), .. (_ : comm_semiring ℝβ‰₯0), .. (_ : semiring ℝβ‰₯0) } @[simp, norm_cast] lemma coe_indicator {Ξ±} (s : set Ξ±) (f : Ξ± β†’ ℝβ‰₯0) (a : Ξ±) : ((s.indicator f a : ℝβ‰₯0) : ℝ) = s.indicator (Ξ» x, f x) a := (to_real_hom : ℝβ‰₯0 β†’+ ℝ).map_indicator _ _ _ @[simp, norm_cast] protected lemma coe_div (r₁ rβ‚‚ : ℝβ‰₯0) : ((r₁ / rβ‚‚ : ℝβ‰₯0) : ℝ) = r₁ / rβ‚‚ := rfl @[norm_cast] lemma coe_pow (r : ℝβ‰₯0) (n : β„•) : ((r^n : ℝβ‰₯0) : ℝ) = r^n := to_real_hom.map_pow r n @[norm_cast] lemma coe_list_sum (l : list ℝβ‰₯0) : ((l.sum : ℝβ‰₯0) : ℝ) = (l.map coe).sum := to_real_hom.map_list_sum l @[norm_cast] lemma coe_list_prod (l : list ℝβ‰₯0) : ((l.prod : ℝβ‰₯0) : ℝ) = (l.map coe).prod := to_real_hom.map_list_prod l @[norm_cast] lemma coe_multiset_sum (s : multiset ℝβ‰₯0) : ((s.sum : ℝβ‰₯0) : ℝ) = (s.map coe).sum := to_real_hom.map_multiset_sum s @[norm_cast] lemma coe_multiset_prod (s : multiset ℝβ‰₯0) : ((s.prod : ℝβ‰₯0) : ℝ) = (s.map coe).prod := to_real_hom.map_multiset_prod s @[norm_cast] lemma coe_sum {Ξ±} {s : finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(βˆ‘ a in s, f a) = βˆ‘ a in s, (f a : ℝ) := to_real_hom.map_sum _ _ @[norm_cast] lemma coe_prod {Ξ±} {s : finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(∏ a in s, f a) = ∏ a in s, (f a : ℝ) := to_real_hom.map_prod _ _ @[norm_cast] lemma nsmul_coe (r : ℝβ‰₯0) (n : β„•) : ↑(n β€’β„• r) = n β€’β„• (r:ℝ) := to_real_hom.to_add_monoid_hom.map_nsmul _ _ @[simp, norm_cast] protected lemma coe_nat_cast (n : β„•) : (↑(↑n : ℝβ‰₯0) : ℝ) = n := to_real_hom.map_nat_cast n instance : decidable_linear_order ℝβ‰₯0 := decidable_linear_order.lift (coe : ℝβ‰₯0 β†’ ℝ) subtype.val_injective @[norm_cast] protected lemma coe_le_coe {r₁ rβ‚‚ : ℝβ‰₯0} : (r₁ : ℝ) ≀ rβ‚‚ ↔ r₁ ≀ rβ‚‚ := iff.rfl @[norm_cast] protected lemma coe_lt_coe {r₁ rβ‚‚ : ℝβ‰₯0} : (r₁ : ℝ) < rβ‚‚ ↔ r₁ < rβ‚‚ := iff.rfl protected lemma coe_pos {r : ℝβ‰₯0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℝβ‰₯0 β†’ ℝ) := Ξ» _ _, nnreal.coe_le_coe.2 protected lemma of_real_mono : monotone nnreal.of_real := Ξ» x y h, max_le_max h (le_refl 0) @[simp] lemma of_real_coe {r : ℝβ‰₯0} : nnreal.of_real r = r := nnreal.eq $ max_eq_left r.2 /-- `nnreal.of_real` and `coe : ℝβ‰₯0 β†’ ℝ` form a Galois insertion. -/ protected def gi : galois_insertion nnreal.of_real coe := galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono le_coe_of_real (Ξ» _, of_real_coe) instance : order_bot ℝβ‰₯0 := { bot := βŠ₯, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order } instance : canonically_ordered_add_monoid ℝβ‰₯0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≀ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm β–Έ show a ≀ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.order_bot, ..nnreal.decidable_linear_order } instance : distrib_lattice ℝβ‰₯0 := by apply_instance instance : semilattice_inf_bot ℝβ‰₯0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : semilattice_sup_bot ℝβ‰₯0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : linear_ordered_semiring ℝβ‰₯0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_lt_one := @zero_lt_one ℝ _, .. nnreal.decidable_linear_order, .. nnreal.canonically_ordered_add_monoid, .. nnreal.comm_semiring } instance : linear_ordered_comm_group_with_zero ℝβ‰₯0 := { mul_le_mul_left := assume a b h c, mul_le_mul (le_refl c) h (zero_le a) (zero_le c), zero_le_one := zero_le 1, .. nnreal.linear_ordered_semiring, .. nnreal.comm_group_with_zero } instance : canonically_ordered_comm_semiring ℝβ‰₯0 := { .. nnreal.canonically_ordered_add_monoid, .. nnreal.comm_semiring, .. (show no_zero_divisors ℝβ‰₯0, by apply_instance), .. nnreal.comm_group_with_zero } instance : densely_ordered ℝβ‰₯0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝβ‰₯0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝβ‰₯0} : bdd_above ((coe : nnreal β†’ ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≀ max b 0, from le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq β–Έ hb hx⟩) lemma bdd_below_coe (s : set ℝβ‰₯0) : bdd_below ((coe : nnreal β†’ ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq β–Έ q.2⟩ instance : has_Sup ℝβ‰₯0 := ⟨λs, ⟨Sup ((coe : nnreal β†’ ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Sup_empty] }, rcases h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝβ‰₯0 := ⟨λs, ⟨Inf ((coe : nnreal β†’ ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq β–Έ q.2) end⟩⟩ lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal β†’ ℝ) '' s) := rfl lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal β†’ ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝβ‰₯0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : nnreal β†’ ℝ) '' s) ≀ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq β–Έ h hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≀ Inf ((coe : nnreal β†’ ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq β–Έ h hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order, .. nnreal.order_bot } instance : archimedean nnreal := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≀ (n β€’β„• y : nnreal), by simp [*, -nsmul_eq_mul, nsmul_coe]⟩ ⟩ lemma le_of_forall_epsilon_le {a b : nnreal} (h : βˆ€Ξ΅, 0 < Ξ΅ β†’ a ≀ b + Ξ΅) : a ≀ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨Ρ, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end lemma lt_iff_exists_rat_btwn (a b : nnreal) : a < b ↔ (βˆƒq:β„š, 0 ≀ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≀ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (βŠ₯ : nnreal) = 0 := rfl lemma mul_sup (a b c : ℝβ‰₯0) : a * (b βŠ” c) = (a * b) βŠ” (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {Ξ±} {f : Ξ± β†’ ℝβ‰₯0} {s : finset Ξ±} (r : ℝβ‰₯0) : r * s.sup f = s.sup (Ξ»a, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end @[simp, norm_cast] lemma coe_max (x y : nnreal) : ((max x y : nnreal) : ℝ) = max (x : ℝ) (y : ℝ) := by { delta max, split_ifs; refl } @[simp, norm_cast] lemma coe_min (x y : nnreal) : ((min x y : nnreal) : ℝ) = min (x : ℝ) (y : ℝ) := by { delta min, split_ifs; refl } section of_real @[simp] lemma zero_le_coe {q : nnreal} : 0 ≀ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma of_real_one : nnreal.of_real 1 = 1 := by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≀ 1)]; refl @[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≀ 0 := by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r)) lemma of_real_of_nonpos {r : ℝ} : r ≀ 0 β†’ nnreal.of_real r = 0 := of_real_eq_zero.2 @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≀ p) : nnreal.of_real r ≀ nnreal.of_real p ↔ r ≀ p := by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp] @[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} : nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl] lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans (and_iff_left h) lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≀ r) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans ⟨and.left, Ξ» h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≀ r) (hp : 0 ≀ p) : nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p := nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≀ r) (hp : 0 ≀ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := (of_real_add hr hp).symm lemma of_real_le_of_real {r p : ℝ} (h : r ≀ p) : nnreal.of_real r ≀ nnreal.of_real p := nnreal.of_real_mono h lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≀ nnreal.of_real r + nnreal.of_real p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≀ p ↔ r ≀ ↑p := nnreal.gi.gc r p lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : 0 ≀ p) : r ≀ nnreal.of_real p ↔ ↑r ≀ p := by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp] lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : 0 ≀ r) : nnreal.of_real r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha] lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] }, { rw [of_real_eq_zero.2 h], split, intro, have := not_lt_of_le (zero_le r), contradiction, intro rp, have : Β¬(p ≀ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction } end end of_real section mul lemma mul_eq_mul_left {a b c : nnreal} (h : a β‰  0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact mul_left_cancel' (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma of_real_mul {p q : ℝ} (hp : 0 ≀ p) : nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, have := max_eq_left (mul_nonneg hp hq), simpa [nnreal.of_real, hp, hq, max_eq_left] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] } end @[field_simps] theorem mul_ne_zero' {a b : nnreal} (h₁ : a β‰  0) (hβ‚‚ : b β‰  0) : a * b β‰  0 := mul_ne_zero h₁ hβ‚‚ end mul section sub lemma sub_def {r p : ℝβ‰₯0} : r - p = nnreal.of_real (r - p) := rfl lemma sub_eq_zero {r p : ℝβ‰₯0} (h : r ≀ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h @[simp] lemma sub_self {r : ℝβ‰₯0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝβ‰₯0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe] lemma sub_pos {r p : ℝβ‰₯0} : 0 < r - p ↔ p < r := of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe protected lemma sub_lt_self {r p : nnreal} : 0 < r β†’ 0 < p β†’ r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≀ q ↔ r ≀ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≀ p + q, from le_add_right h, by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝβ‰₯0} : r - p ≀ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] @[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≀ a) : (a - b) + b = a := nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel] lemma sub_sub_cancel_of_le {r p : ℝβ‰₯0} (h : r ≀ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h, sub_sub_cancel, nnreal.of_real_coe] lemma lt_sub_iff_add_lt {p q r : nnreal} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : nnreal) : ℝ) = (q : ℝ) - (r : ℝ) := nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H }, { assume H, have : r ≀ q := le_trans (le_add_left (le_refl _)) (le_of_lt H), rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] } end lemma sub_lt_iff_lt_add {a b c : nnreal} (h : b ≀ a) : a - b < c ↔ a < b + c := by simp only [←nnreal.coe_lt_coe, nnreal.coe_sub h, nnreal.coe_add, sub_lt_iff_lt_add'] lemma sub_eq_iff_eq_add {a b c : nnreal} (h : b ≀ a) : a - b = c ↔ a = c + b := by rw [←nnreal.eq_iff, nnreal.coe_sub h, ←nnreal.eq_iff, nnreal.coe_add, sub_eq_iff_eq_add] end sub section inv lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl lemma sum_div {ΞΉ} (s : finset ΞΉ) (f : ΞΉ β†’ ℝβ‰₯0) (b : ℝβ‰₯0) : (βˆ‘ i in s, f i) / b = βˆ‘ i in s, (f i / b) := by simp only [nnreal.div_def, finset.sum_mul] @[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero @[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 := inv_eq_zero @[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r := by simp [zero_lt_iff_ne_zero] lemma div_pos {r p : ℝβ‰₯0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := mul_pos hr (inv_pos.2 hp) @[simp] lemma inv_one : (1:ℝβ‰₯0)⁻¹ = 1 := nnreal.eq $ inv_one @[simp] lemma div_one {r : ℝβ‰₯0} : r / 1 = r := by rw [div_def, inv_one, mul_one] protected lemma mul_inv {r p : ℝβ‰₯0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv_rev' _ _ protected lemma inv_pow {r : ℝβ‰₯0} {n : β„•} : (r^n)⁻¹ = (r⁻¹)^n := nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm } @[simp] lemma inv_mul_cancel {r : ℝβ‰₯0} (h : r β‰  0) : r⁻¹ * r = 1 := nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h @[simp] lemma mul_inv_cancel {r : ℝβ‰₯0} (h : r β‰  0) : r * r⁻¹ = 1 := by rw [mul_comm, inv_mul_cancel h] @[simp] lemma div_self {r : ℝβ‰₯0} (h : r β‰  0) : r / r = 1 := mul_inv_cancel h lemma div_self_le (r : ℝβ‰₯0) : r / r ≀ 1 := if h : r = 0 then by simp [h] else by rw [div_self h] @[simp] lemma mul_div_cancel {r p : ℝβ‰₯0} (h : p β‰  0) : r * p / p = r := by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one] @[simp] lemma mul_div_cancel' {r p : ℝβ‰₯0} (h : r β‰  0) : r * (p / r) = p := by rw [mul_comm, div_mul_cancel _ h] @[simp] lemma inv_inv {r : ℝβ‰₯0} : r⁻¹⁻¹ = r := nnreal.eq (inv_inv' _) @[simp] lemma inv_le {r p : ℝβ‰₯0} (h : r β‰  0) : r⁻¹ ≀ p ↔ 1 ≀ r * p := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝβ‰₯0} (h : 1 ≀ r * p) : r⁻¹ ≀ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝβ‰₯0} (h : p β‰  0) : (r ≀ p⁻¹ ↔ r * p ≀ 1) := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝβ‰₯0} (h : p β‰  0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝβ‰₯0} (hr : r β‰  0) : r * a ≀ b ↔ a ≀ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝβ‰₯0} (hr : r β‰  0) : a ≀ b / r ↔ a * r ≀ b := by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm] lemma div_le_iff {a b r : ℝβ‰₯0} (hr : r β‰  0) : a / r ≀ b ↔ a ≀ b * r := @div_le_iff ℝ _ a r b $ zero_lt_iff_ne_zero.2 hr lemma le_of_forall_lt_one_mul_lt {x y : ℝβ‰₯0} (h : βˆ€a<1, a * x ≀ y) : x ≀ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x β‰  0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ β‰  0, by rwa [(β‰ ), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≀ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝβ‰₯0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝβ‰₯0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝβ‰₯0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝβ‰₯0} (h : a β‰  0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝβ‰₯0) < 1 := by simpa [div_def] using half_lt_self zero_ne_one.symm lemma div_lt_iff {a b c : ℝβ‰₯0} (hc : c β‰  0) : b / c < a ↔ b < a * c := begin rw [← nnreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_div, nnreal.coe_mul], exact div_lt_iff (zero_lt_iff_ne_zero.mpr hc) end lemma div_lt_one_of_lt {a b : ℝβ‰₯0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] theorem div_pow {a b : ℝβ‰₯0} (n : β„•) : (a / b) ^ n = a ^ n / b ^ n := div_pow _ _ _ @[field_simps] lemma mul_div_assoc' (a b c : ℝβ‰₯0) : a * (b / c) = (a * b) / c := by rw [div_def, div_def, mul_assoc] @[field_simps] lemma div_add_div (a : ℝβ‰₯0) {b : ℝβ‰₯0} (c : ℝβ‰₯0) {d : ℝβ‰₯0} (hb : b β‰  0) (hd : d β‰  0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma inv_eq_one_div (a : ℝβ‰₯0) : a⁻¹ = 1/a := by rw [div_def, one_mul] @[field_simps] lemma div_mul_eq_mul_div (a b c : ℝβ‰₯0) : (a / b) * c = (a * c) / b := by { rw [div_def, div_def], ac_refl } @[field_simps] lemma add_div' (a b c : ℝβ‰₯0) (hc : c β‰  0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝβ‰₯0) (hc : c β‰  0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma one_div (a : ℝβ‰₯0) : 1 / a = a⁻¹ := one_mul a⁻¹ lemma one_div_div (a b : ℝβ‰₯0) : 1 / (a / b) = b / a := by { rw ← nnreal.eq_iff, simp [one_div_div] } lemma div_eq_mul_one_div (a b : ℝβ‰₯0) : a / b = a * (1 / b) := by rw [div_def, div_def, one_mul] @[field_simps] lemma div_div_eq_mul_div (a b c : ℝβ‰₯0) : a / (b / c) = (a * c) / b := by { rw ← nnreal.eq_iff, simp [div_div_eq_mul_div] } @[field_simps] lemma div_div_eq_div_mul (a b c : ℝβ‰₯0) : (a / b) / c = a / (b * c) := by { rw ← nnreal.eq_iff, simp [div_div_eq_div_mul] } @[field_simps] lemma div_eq_div_iff {a b c d : ℝβ‰₯0} (hb : b β‰  0) (hd : d β‰  0) : a / b = c / d ↔ a * d = c * b := div_eq_div_iff hb hd @[field_simps] lemma div_eq_iff {a b c : ℝβ‰₯0} (hb : b β‰  0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff a b c 1 hb one_ne_zero @[field_simps] lemma eq_div_iff {a b c : ℝβ‰₯0} (hb : b β‰  0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff c 1 a b one_ne_zero hb end inv section pow theorem pow_eq_zero {a : ℝβ‰₯0} {n : β„•} (h : a^n = 0) : a = 0 := begin rw ← nnreal.eq_iff, rw [← nnreal.eq_iff, coe_pow] at h, exact pow_eq_zero h end @[field_simps] theorem pow_ne_zero {a : ℝβ‰₯0} (n : β„•) (h : a β‰  0) : a ^ n β‰  0 := mt pow_eq_zero h end pow @[simp] lemma abs_eq (x : ℝβ‰₯0) : abs (x : ℝ) = x := abs_of_nonneg x.property end nnreal /-- The absolute value on `ℝ` as a map to `ℝβ‰₯0`. -/ @[pp_nodot] def real.nnabs (x : ℝ) : ℝβ‰₯0 := ⟨abs x, abs_nonneg x⟩ @[norm_cast, simp] lemma nnreal.coe_nnabs (x : ℝ) : (real.nnabs x : ℝ) = abs x := by simp [real.nnabs]
eafe8149e5e777bfca3aeff98cfc6c4d762529dc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/DSL/Targets.lean
5eb98a4364995decc86c79f95913c94f81b33358
[ "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
8,410
lean
/- Copyright (c) 2022 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.DSL.DeclUtil import Lake.Build.Index /-! # DSL for Targets & Facets Macros for declaring Lake targets and facets. -/ namespace Lake.DSL open Lean Parser Command syntax buildDeclSig := ident (ppSpace simpleBinder)? Term.typeSpec declValSimple -------------------------------------------------------------------------------- /-! ## Facet Declarations -/ -------------------------------------------------------------------------------- /-- Define a new module facet. Has one form: ```lean module_facet Β«facet-nameΒ» (mod : Module) : Ξ± := /- build term of type `IndexBuildM (BuildJob Ξ±)` -/ ``` The `mod` parameter (and its type specifier) is optional. -/ scoped macro (name := moduleFacetDecl) doc?:optional(docComment) attrs?:optional(Term.attributes) kw:"module_facet " sig:buildDeclSig : command => do match sig with | `(buildDeclSig| $id:ident $[$mod?]? : $ty := $defn $[$wds?]?) => let attr ← withRef kw `(Term.attrInstance| module_facet) let attrs := #[attr] ++ expandAttrs attrs? let name := Name.quoteFrom id id.getId let facetId := mkIdentFrom id <| id.getId.modifyBase (.str Β· "_modFacet") let mod ← expandOptSimpleBinder mod? `(module_data $id : BuildJob $ty $[$doc?:docComment]? @[$attrs,*] abbrev $facetId : ModuleFacetDecl := { name := $name config := Lake.mkFacetJobConfig fun $mod => ($defn : IndexBuildM (BuildJob $ty)) } $[$wds?]?) | stx => Macro.throwErrorAt stx "ill-formed module facet declaration" /-- Define a new package facet. Has one form: ```lean package_facet Β«facet-nameΒ» (pkg : Package) : Ξ± := /- build term of type `IndexBuildM (BuildJob Ξ±)` -/ ``` The `pkg` parameter (and its type specifier) is optional. -/ scoped macro (name := packageFacetDecl) doc?:optional(docComment) attrs?:optional(Term.attributes) kw:"package_facet " sig:buildDeclSig : command => do match sig with | `(buildDeclSig| $id:ident $[$pkg?]? : $ty := $defn $[$wds?]?) => let attr ← withRef kw `(Term.attrInstance| package_facet) let attrs := #[attr] ++ expandAttrs attrs? let name := Name.quoteFrom id id.getId let facetId := mkIdentFrom id <| id.getId.modifyBase (.str Β· "_pkgFacet") let pkg ← expandOptSimpleBinder pkg? `(package_data $id : BuildJob $ty $[$doc?]? @[$attrs,*] abbrev $facetId : PackageFacetDecl := { name := $name config := Lake.mkFacetJobConfig fun $pkg => ($defn : IndexBuildM (BuildJob $ty)) } $[$wds?]?) | stx => Macro.throwErrorAt stx "ill-formed package facet declaration" /-- Define a new library facet. Has one form: ```lean library_facet Β«facet-nameΒ» (lib : LeanLib) : Ξ± := /- build term of type `IndexBuildM (BuildJob Ξ±)` -/ ``` The `lib` parameter (and its type specifier) is optional. -/ scoped macro (name := libraryFacetDecl) doc?:optional(docComment) attrs?:optional(Term.attributes) kw:"library_facet " sig:buildDeclSig : command => do match sig with | `(buildDeclSig| $id:ident $[$lib?]? : $ty := $defn $[$wds?]?) => let attr ← withRef kw `(Term.attrInstance| library_facet) let attrs := #[attr] ++ expandAttrs attrs? let name := Name.quoteFrom id id.getId let facetId := mkIdentFrom id <| id.getId.modifyBase (.str Β· "_libFacet") let lib ← expandOptSimpleBinder lib? `(library_data $id : BuildJob $ty $[$doc?]? @[$attrs,*] abbrev $facetId : LibraryFacetDecl := { name := $name config := Lake.mkFacetJobConfig fun $lib => ($defn : IndexBuildM (BuildJob $ty)) } $[$wds?]?) | stx => Macro.throwErrorAt stx "ill-formed library facet declaration" -------------------------------------------------------------------------------- /-! ## Custom Target Declaration -/ -------------------------------------------------------------------------------- /-- Define a new custom target for the package. Has one form: ```lean target Β«target-nameΒ» (pkg : NPackage _package.name) : Ξ± := /- build term of type `IndexBuildM (BuildJob Ξ±)` -/ ``` The `pkg` parameter (and its type specifier) is optional. It is of type `NPackage _package.name` to provably demonstrate the package provided is the package in which the target is defined. -/ scoped macro (name := targetDecl) doc?:optional(docComment) attrs?:optional(Term.attributes) kw:"target " sig:buildDeclSig : command => do match sig with | `(buildDeclSig| $id:ident $[$pkg?]? : $ty := $defn $[$wds?]?) => let attr ← withRef kw `(Term.attrInstance| target) let attrs := #[attr] ++ expandAttrs attrs? let name := Name.quoteFrom id id.getId let pkgName := mkIdentFrom id `_package.name let pkg ← expandOptSimpleBinder pkg? `(family_def $id : CustomData ($pkgName, $name) := BuildJob $ty $[$doc?]? @[$attrs,*] abbrev $id : TargetDecl := { pkg := $pkgName name := $name config := Lake.mkTargetJobConfig fun $pkg => ($defn : IndexBuildM (BuildJob $ty)) } $[$wds?]?) | stx => Macro.throwErrorAt stx "ill-formed target declaration" -------------------------------------------------------------------------------- /-! ## Lean Library & Executable Target Declarations -/ -------------------------------------------------------------------------------- /-- Define a new Lean library target for the package. Can optionally be provided with a configuration of type `LeanLibConfig`. Has many forms: ```lean lean_lib Β«target-nameΒ» lean_lib Β«target-nameΒ» { /- config opts -/ } lean_lib Β«target-nameΒ» where /- config opts -/ lean_lib Β«target-nameΒ» := /- config -/ ``` -/ scoped macro (name := leanLibDecl) doc?:optional(docComment) attrs?:optional(Term.attributes) "lean_lib " sig:structDeclSig : command => do let attr ← `(Term.attrInstance| lean_lib) let ty := mkCIdentFrom (← getRef) ``LeanLibConfig let attrs := #[attr] ++ expandAttrs attrs? mkConfigStructDecl none doc? attrs ty sig /-- Define a new Lean binary executable target for the package. Can optionally be provided with a configuration of type `LeanExeConfig`. Has many forms: ```lean lean_exe Β«target-nameΒ» lean_exe Β«target-nameΒ» { /- config opts -/ } lean_exe Β«target-nameΒ» where /- config opts -/ lean_exe Β«target-nameΒ» := /- config -/ ``` -/ scoped macro (name := leanExeDecl) doc?:optional(docComment) attrs?:optional(Term.attributes) "lean_exe " sig:structDeclSig : command => do let attr ← `(Term.attrInstance| lean_exe) let ty := mkCIdentFrom (← getRef) ``LeanExeConfig let attrs := #[attr] ++ expandAttrs attrs? mkConfigStructDecl none doc? attrs ty sig -------------------------------------------------------------------------------- /-! ## External Library Target Declaration -/ -------------------------------------------------------------------------------- syntax externLibDeclSpec := ident (ppSpace simpleBinder)? declValSimple /-- Define a new external library target for the package. Has one form: ```lean extern_lib Β«target-nameΒ» (pkg : NPackage _package.name) := /- build term of type `IndexBuildM (BuildJob FilePath)` -/ ``` The `pkg` parameter (and its type specifier) is optional. It is of type `NPackage _package.name` to provably demonstrate the package provided is the package in which the target is defined. The term should build the external library's **static** library. -/ scoped macro (name := externLibDecl) doc?:optional(docComment) attrs?:optional(Term.attributes) "extern_lib " spec:externLibDeclSpec : command => do match spec with | `(externLibDeclSpec| $id:ident $[$pkg?]? := $defn $[$wds?]?) => let attr ← `(Term.attrInstance| extern_lib) let attrs := #[attr] ++ expandAttrs attrs? let pkgName := mkIdentFrom id `_package.name let targetId := mkIdentFrom id <| id.getId.modifyBase (Β· ++ `static) let name := Name.quoteFrom id id.getId `(target $targetId $[$pkg?]? : FilePath := $defn $[$wds?]? $[$doc?:docComment]? @[$attrs,*] def $id : ExternLibDecl := { pkg := $pkgName name := $name config := {getJob := ofFamily} }) | stx => Macro.throwErrorAt stx "ill-formed external library declaration"
2f3264476dcb9a1d1baf69ba48397c50d81e59d5
680b0d1592ce164979dab866b232f6fa743f2cc8
/library/data/real/division.lean
0766ccf659bf6888de4ad1b5c69f37a628caf96e
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
24,105
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). At this point, we no longer proceed constructively: this file makes heavy use of decidability and excluded middle. -/ import data.real.basic data.real.order data.rat data.nat open rat open nat open eq.ops pnat classical namespace rat_seq local postfix ⁻¹ := pnat.inv ----------------------------- -- Facts about absolute values of sequences, to define inverse definition s_abs (s : seq) : seq := Ξ» n, abs (s n) theorem abs_reg_of_reg {s : seq} (Hs : regular s) : regular (s_abs s) := begin intros, apply le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Hs end theorem abs_pos_of_nonzero {s : seq} (Hs : regular s) (Hnz : sep s zero) : βˆƒ N : β„•+, βˆ€ m : β„•+, m β‰₯ N β†’ abs (s m) β‰₯ N⁻¹ := begin rewrite [↑sep at Hnz, ↑s_lt at Hnz], apply or.elim Hnz, intro Hnz1, have H' : pos (sneg s), begin apply pos_of_pos_equiv, rotate 2, apply Hnz1, rotate 1, apply s_zero_add, repeat (assumption | apply reg_add_reg | apply reg_neg_reg | apply zero_is_reg) end, cases bdd_away_of_pos (reg_neg_reg Hs) H' with [N, HN], existsi N, intro m Hm, apply le.trans, apply HN m Hm, rewrite ↑sneg, apply neg_le_abs_self, intro Hnz2, let H' := pos_of_pos_equiv (reg_add_reg Hs (reg_neg_reg zero_is_reg)) (s_add_zero s Hs) Hnz2, let H'' := bdd_away_of_pos Hs H', cases H'' with [N, HN], existsi N, intro m Hm, apply le.trans, apply HN m Hm, apply le_abs_self end theorem abs_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≑ t) : s_abs s ≑ s_abs t := begin rewrite [↑equiv at *], intro n, rewrite ↑s_abs, apply le.trans, apply abs_abs_sub_abs_le_abs_sub, apply Heq end theorem sep_zero_of_pos {s : seq} (Hs : regular s) (Hpos : pos s) : sep s zero := begin apply or.inr, apply pos_of_pos_equiv, rotate 2, apply Hpos, apply Hs, apply equiv.symm, apply s_sub_zero Hs end ------------------------ -- This section could be cleaned up. private noncomputable definition pb {s : seq} (Hs : regular s) (Hpos : pos s) := some (abs_pos_of_nonzero Hs (sep_zero_of_pos Hs Hpos)) private noncomputable definition ps {s : seq} (Hs : regular s) (Hsep : sep s zero) := some (abs_pos_of_nonzero Hs Hsep) private theorem pb_spec {s : seq} (Hs : regular s) (Hpos : pos s) : βˆ€ m : β„•+, m β‰₯ (pb Hs Hpos) β†’ abs (s m) β‰₯ (pb Hs Hpos)⁻¹ := some_spec (abs_pos_of_nonzero Hs (sep_zero_of_pos Hs Hpos)) private theorem ps_spec {s : seq} (Hs : regular s) (Hsep : sep s zero) : βˆ€ m : β„•+, m β‰₯ (ps Hs Hsep) β†’ abs (s m) β‰₯ (ps Hs Hsep)⁻¹ := some_spec (abs_pos_of_nonzero Hs Hsep) noncomputable definition s_inv {s : seq} (Hs : regular s) (n : β„•+) : β„š := if H : sep s zero then (if n < (ps Hs H) then 1 / (s ((ps Hs H) * (ps Hs H) * (ps Hs H))) else 1 / (s ((ps Hs H) * (ps Hs H) * n))) else 0 private theorem peq {s : seq} (Hsep : sep s zero) (Hpos : pos s) (Hs : regular s) : pb Hs Hpos = ps Hs Hsep := rfl private theorem s_inv_of_sep_lt_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : β„•+} (Hn : n < (ps Hs Hsep)) : s_inv Hs n = 1 / s ((ps Hs Hsep) * (ps Hs Hsep) * (ps Hs Hsep)) := begin apply eq.trans, apply dif_pos Hsep, apply dif_pos Hn end private theorem s_inv_of_sep_gt_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : β„•+} (Hn : n β‰₯ (ps Hs Hsep)) : s_inv Hs n = 1 / s ((ps Hs Hsep) * (ps Hs Hsep) * n) := begin apply eq.trans, apply dif_pos Hsep, apply dif_neg (pnat.not_lt_of_ge Hn) end private theorem s_inv_of_pos_lt_p {s : seq} (Hs : regular s) (Hpos : pos s) {n : β„•+} (Hn : n < (pb Hs Hpos)) : s_inv Hs n = 1 / s ((pb Hs Hpos) * (pb Hs Hpos) * (pb Hs Hpos)) := s_inv_of_sep_lt_p Hs (sep_zero_of_pos Hs Hpos) Hn private theorem s_inv_of_pos_gt_p {s : seq} (Hs : regular s) (Hpos : pos s) {n : β„•+} (Hn : n β‰₯ (pb Hs Hpos)) : s_inv Hs n = 1 / s ((pb Hs Hpos) * (pb Hs Hpos) * n) := s_inv_of_sep_gt_p Hs (sep_zero_of_pos Hs Hpos) Hn private theorem le_ps {s : seq} (Hs : regular s) (Hsep : sep s zero) (n : β„•+) : abs (s_inv Hs n) ≀ (rat_of_pnat (ps Hs Hsep)) := if Hn : n < ps Hs Hsep then (begin rewrite [(s_inv_of_sep_lt_p Hs Hsep Hn), abs_one_div], apply div_le_pnat, apply ps_spec, apply pnat.mul_le_mul_left end) else (begin rewrite [(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hn)), abs_one_div], apply div_le_pnat, apply ps_spec, rewrite pnat.mul_assoc, apply pnat.mul_le_mul_right end) theorem s_inv_zero : s_inv zero_is_reg = zero := funext (Ξ» n, dif_neg (!not_sep_self)) private theorem s_inv_of_zero' {s : seq} (Hs : regular s) (Hz : Β¬ sep s zero) (n : β„•+) : s_inv Hs n = 0 := dif_neg Hz theorem s_inv_of_zero {s : seq} (Hs : regular s) (Hz : Β¬ sep s zero) : s_inv Hs = zero := begin apply funext, intro n, apply s_inv_of_zero' Hs Hz n end private theorem s_ne_zero_of_ge_p {s : seq} (Hs : regular s) (Hsep : sep s zero) {n : β„•+} (Hn : n β‰₯ (ps Hs Hsep)) : s n β‰  0 := begin let Hps := ps_spec Hs Hsep, apply ne_zero_of_abs_ne_zero, apply ne_of_gt, apply gt_of_ge_of_gt, apply Hps, apply Hn, apply pnat.inv_pos end theorem reg_inv_reg {s : seq} (Hs : regular s) (Hsep : sep s zero) : regular (s_inv Hs) := begin rewrite ↑regular, intros, have Hsp : s ((ps Hs Hsep) * (ps Hs Hsep) * (ps Hs Hsep)) β‰  0, from s_ne_zero_of_ge_p Hs Hsep !pnat.mul_le_mul_left, have Hspn : s ((ps Hs Hsep) * (ps Hs Hsep) * n) β‰  0, from s_ne_zero_of_ge_p Hs Hsep (show (ps Hs Hsep) * (ps Hs Hsep) * n β‰₯ ps Hs Hsep, by rewrite pnat.mul_assoc; apply pnat.mul_le_mul_right), have Hspm : s ((ps Hs Hsep) * (ps Hs Hsep) * m) β‰  0, from s_ne_zero_of_ge_p Hs Hsep (show (ps Hs Hsep) * (ps Hs Hsep) * m β‰₯ ps Hs Hsep, by rewrite pnat.mul_assoc; apply pnat.mul_le_mul_right), cases em (m < ps Hs Hsep) with [Hmlt, Hmlt], cases em (n < ps Hs Hsep) with [Hnlt, Hnlt], rewrite [(s_inv_of_sep_lt_p Hs Hsep Hmlt), (s_inv_of_sep_lt_p Hs Hsep Hnlt)], rewrite [sub_self, abs_zero], apply add_invs_nonneg, rewrite [(s_inv_of_sep_lt_p Hs Hsep Hmlt), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt))], rewrite [(!div_sub_div Hsp Hspn), div_eq_mul_one_div, *abs_mul, *mul_one, *one_mul], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hsp Hspn), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_lt_p Hs Hsep Hmlt), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply add_le_add_right, apply inv_ge_of_le, apply pnat.le_of_lt, apply Hmlt, cases em (n < ps Hs Hsep) with [Hnlt, Hnlt], rewrite [(s_inv_of_sep_lt_p Hs Hsep Hnlt), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt))], rewrite [(!div_sub_div Hspm Hsp), div_eq_mul_one_div, *abs_mul, *mul_one, *one_mul], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hspm Hsp), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt)), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_lt_p Hs Hsep Hnlt), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply rat.add_le_add_left, apply inv_ge_of_le, apply pnat.le_of_lt, apply Hnlt, rewrite [(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), (s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt))], rewrite [(!div_sub_div Hspm Hspn), div_eq_mul_one_div, abs_mul, *one_mul, *mul_one], apply le.trans, apply mul_le_mul, apply Hs, rewrite [-(mul_one 1), -(!field.div_mul_div Hspm Hspn), abs_mul], apply mul_le_mul, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hmlt)), apply le_ps Hs Hsep, rewrite -(s_inv_of_sep_gt_p Hs Hsep (pnat.le_of_not_gt Hnlt)), apply le_ps Hs Hsep, apply abs_nonneg, apply le_of_lt !rat_of_pnat_is_pos, apply abs_nonneg, apply add_invs_nonneg, rewrite [right_distrib, *pnat_cancel', add.comm], apply le.refl end theorem s_inv_ne_zero {s : seq} (Hs : regular s) (Hsep : sep s zero) (n : β„•+) : s_inv Hs n β‰  0 := if H : n β‰₯ ps Hs Hsep then (begin rewrite (s_inv_of_sep_gt_p Hs Hsep H), apply one_div_ne_zero, apply s_ne_zero_of_ge_p, apply pnat.le_trans, apply H, apply pnat.mul_le_mul_left end) else (begin rewrite (s_inv_of_sep_lt_p Hs Hsep (pnat.lt_of_not_le H)), apply one_div_ne_zero, apply s_ne_zero_of_ge_p, apply pnat.mul_le_mul_left end) protected theorem mul_inv {s : seq} (Hs : regular s) (Hsep : sep s zero) : smul s (s_inv Hs) ≑ one := begin let Rsi := reg_inv_reg Hs Hsep, let Rssi := reg_mul_reg Hs Rsi, apply eq_of_bdd Rssi one_is_reg, intros, existsi max (ps Hs Hsep) j, intro n Hn, have Hnz : s_inv Hs ((Kβ‚‚ s (s_inv Hs)) * 2 * n) β‰  0, from s_inv_ne_zero Hs Hsep _, rewrite [↑smul, ↑one, mul.comm, -(mul_one_div_cancel Hnz), -mul_sub_left_distrib, abs_mul], apply le.trans, apply mul_le_mul_of_nonneg_right, apply canon_2_bound_right s, apply Rsi, apply abs_nonneg, have Hp : (Kβ‚‚ s (s_inv Hs)) * 2 * n β‰₯ ps Hs Hsep, begin apply pnat.le_trans, apply pnat.max_left, rotate 1, apply pnat.le_trans, apply Hn, apply pnat.mul_le_mul_left end, have Hnz' : s (((ps Hs Hsep) * (ps Hs Hsep)) * ((Kβ‚‚ s (s_inv Hs)) * 2 * n)) β‰  0, from s_ne_zero_of_ge_p Hs Hsep (show ps Hs Hsep ≀ ((ps Hs Hsep) * (ps Hs Hsep)) * ((Kβ‚‚ s (s_inv Hs)) * 2 * n), by rewrite *pnat.mul_assoc; apply pnat.mul_le_mul_right), rewrite [(s_inv_of_sep_gt_p Hs Hsep Hp), (division_ring.one_div_one_div Hnz')], apply rat.le_trans, apply mul_le_mul_of_nonneg_left, apply Hs, apply le_of_lt, apply rat_of_pnat_is_pos, rewrite [left_distrib, pnat.mul_comm ((ps Hs Hsep) * (ps Hs Hsep)), *pnat.mul_assoc, *(@pnat.inv_mul_eq_mul_inv (Kβ‚‚ s (s_inv Hs))), -*mul.assoc, *pnat.inv_cancel_left, *one_mul, -(pnat.add_halves j)], apply add_le_add, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply pnat.max_right, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le_trans, apply pnat.max_right, rotate 1, apply pnat.le_trans, apply Hn, apply pnat.mul_le_mul_right end protected theorem inv_mul {s : seq} (Hs : regular s) (Hsep : sep s zero) : smul (s_inv Hs) s ≑ one := begin apply equiv.trans, rotate 3, apply s_mul_comm, apply rat_seq.mul_inv, repeat (assumption | apply reg_mul_reg | apply reg_inv_reg | apply zero_is_reg) end theorem sep_of_equiv_sep {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≑ t) (Hsep : sep s zero) : sep t zero := begin apply or.elim Hsep, intro Hslt, apply or.inl, rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 2, apply Hslt, rotate_right 1, apply add_well_defined, rotate 4, apply equiv.refl, apply neg_well_defined, apply Heq, intro Hslt, apply or.inr, rewrite ↑s_lt at *, apply pos_of_pos_equiv, rotate 2, apply Hslt, rotate_right 1, apply add_well_defined, rotate 5, apply equiv.refl, repeat (assumption | apply reg_neg_reg | apply reg_add_reg | apply zero_is_reg) end theorem inv_unique {s t : seq} (Hs : regular s) (Ht : regular t) (Hsep : sep s zero) (Heq : smul s t ≑ one) : s_inv Hs ≑ t := begin apply equiv.trans, rotate 3, apply equiv.symm, apply s_mul_one, rotate 1, apply equiv.trans, rotate 3, apply mul_well_defined, rotate 4, apply equiv.refl, apply equiv.symm, apply Heq, apply equiv.trans, rotate 3, apply equiv.symm, apply s_mul_assoc, rotate 3, apply equiv.trans, rotate 3, apply mul_well_defined, rotate 4, apply rat_seq.inv_mul, rotate 1, apply equiv.refl, apply s_one_mul, repeat (assumption | apply reg_inv_reg | apply reg_mul_reg | apply one_is_reg) end theorem inv_well_defined {s t : seq} (Hs : regular s) (Ht : regular t) (Heq : s ≑ t) : s_inv Hs ≑ s_inv Ht := if Hsep : sep s zero then (begin note Hsept := sep_of_equiv_sep Hs Ht Heq Hsep, have Hm : smul t (s_inv Hs) ≑ smul s (s_inv Hs), begin apply mul_well_defined, repeat (assumption | apply reg_inv_reg), apply equiv.symm s t Heq, apply equiv.refl end, apply equiv.symm, apply inv_unique, rotate 2, apply equiv.trans, rotate 3, apply Hm, apply rat_seq.mul_inv, repeat (assumption | apply reg_inv_reg | apply reg_mul_reg), apply one_is_reg end) else (assert H : s_inv Hs = zero, from funext (Ξ» n, dif_neg Hsep), have Hsept : Β¬ sep t zero, from assume H', Hsep (sep_of_equiv_sep Ht Hs (equiv.symm _ _ Heq) H'), assert H' : s_inv Ht = zero, from funext (Ξ» n, dif_neg Hsept), by rewrite [H', H]; apply equiv.refl) theorem s_neg_neg {s : seq} : sneg (sneg s) ≑ s := begin rewrite [↑equiv, ↑sneg], intro n, rewrite [neg_neg, sub_self, abs_zero], apply add_invs_nonneg end theorem s_neg_sub {s t : seq} (Hs : regular s) (Ht : regular t) : sneg (sadd s (sneg t)) ≑ sadd t (sneg s) := begin apply equiv.trans, rotate 3, apply s_neg_add_eq_s_add_neg, apply equiv.trans, rotate 3, apply add_well_defined, rotate 4, apply equiv.refl, apply s_neg_neg, apply s_add_comm, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_total {s t : seq} (Hs : regular s) (Ht : regular t) : s_le s t ∨ s_le t s := if H : s_le s t then or.inl H else or.inr begin rewrite [↑s_le at *], have H' : βˆƒ n : β„•+, -n⁻¹ > sadd t (sneg s) n, begin apply by_contradiction, intro Hex, have Hex' : βˆ€ n : β„•+, -n⁻¹ ≀ sadd t (sneg s) n, begin intro m, apply by_contradiction, intro Hm, note Hm' := lt_of_not_ge Hm, note Hex'' := exists.intro m Hm', apply Hex Hex'' end, apply H Hex' end, eapply exists.elim H', intro m Hm, note Hm' := neg_lt_neg Hm, rewrite neg_neg at Hm', apply s_nonneg_of_pos, rotate 1, apply pos_of_pos_equiv, rotate 1, apply s_neg_sub, rotate 2, rewrite [↑pos, ↑sneg], existsi m, apply Hm', repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_of_not_lt {s t : seq} (Hle : Β¬ s_lt s t) : s_le t s := begin rewrite [↑s_le, ↑nonneg, ↑s_lt at Hle, ↑pos at Hle], let Hle' := iff.mp forall_iff_not_exists Hle, intro n, let Hn := neg_le_neg (le_of_not_gt (Hle' n)), rewrite [↑sadd, ↑sneg, add_neg_eq_neg_add_rev], apply Hn end theorem sep_of_nequiv {s t : seq} (Hs : regular s) (Ht : regular t) (Hneq : Β¬ equiv s t) : sep s t := begin rewrite ↑sep, apply by_contradiction, intro Hnor, let Hand := iff.mp !not_or_iff_not_and_not Hnor, let Hle1 := s_le_of_not_lt (and.left Hand), let Hle2 := s_le_of_not_lt (and.right Hand), apply Hneq (equiv_of_le_of_ge Hs Ht Hle2 Hle1) end theorem s_zero_inv_equiv_zero : s_inv zero_is_reg ≑ zero := by rewrite s_inv_zero; apply equiv.refl theorem lt_or_equiv_of_le {s t : seq} (Hs : regular s) (Ht : regular t) (Hle : s_le s t) : s_lt s t ∨ s ≑ t := if H : s ≑ t then or.inr H else or.inl (lt_of_le_and_sep Hs Ht (and.intro Hle (sep_of_nequiv Hs Ht H))) theorem s_le_of_equiv_le_left {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Heq : s ≑ t) (Hle : s_le s u) : s_le t u := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply equiv.refl, apply neg_well_defined, apply Heq, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end theorem s_le_of_equiv_le_right {s t u : seq} (Hs : regular s) (Ht : regular t) (Hu : regular u) (Heq : t ≑ u) (Hle : s_le s t) : s_le s u := begin rewrite ↑s_le at *, apply nonneg_of_nonneg_equiv, rotate 2, apply add_well_defined, rotate 4, apply Heq, apply equiv.refl, repeat (assumption | apply reg_add_reg | apply reg_neg_reg) end ----------------------------- noncomputable definition r_inv (s : reg_seq) : reg_seq := reg_seq.mk (s_inv (reg_seq.is_reg s)) (if H : sep (reg_seq.sq s) zero then reg_inv_reg (reg_seq.is_reg s) H else assert Hz : s_inv (reg_seq.is_reg s) = zero, from funext (Ξ» n, dif_neg H), by rewrite Hz; apply zero_is_reg) theorem r_inv_zero : requiv (r_inv r_zero) r_zero := s_zero_inv_equiv_zero theorem r_inv_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_inv s) (r_inv t) := inv_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H theorem r_le_total (s t : reg_seq) : r_le s t ∨ r_le t s := s_le_total (reg_seq.is_reg s) (reg_seq.is_reg t) theorem r_mul_inv (s : reg_seq) (Hsep : r_sep s r_zero) : requiv (s * (r_inv s)) r_one := rat_seq.mul_inv (reg_seq.is_reg s) Hsep theorem r_sep_of_nequiv (s t : reg_seq) (Hneq : Β¬ requiv s t) : r_sep s t := sep_of_nequiv (reg_seq.is_reg s) (reg_seq.is_reg t) Hneq theorem r_lt_or_equiv_of_le (s t : reg_seq) (Hle : r_le s t) : r_lt s t ∨ requiv s t := lt_or_equiv_of_le (reg_seq.is_reg s) (reg_seq.is_reg t) Hle theorem r_le_of_equiv_le_left {s t u : reg_seq} (Heq : requiv s t) (Hle : r_le s u) : r_le t u := s_le_of_equiv_le_left (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Heq Hle theorem r_le_of_equiv_le_right {s t u : reg_seq} (Heq : requiv t u) (Hle : r_le s t) : r_le s u := s_le_of_equiv_le_right (reg_seq.is_reg s) (reg_seq.is_reg t) (reg_seq.is_reg u) Heq Hle definition r_abs (s : reg_seq) : reg_seq := reg_seq.mk (s_abs (reg_seq.sq s)) (abs_reg_of_reg (reg_seq.is_reg s)) theorem r_abs_well_defined {s t : reg_seq} (H : requiv s t) : requiv (r_abs s) (r_abs t) := abs_well_defined (reg_seq.is_reg s) (reg_seq.is_reg t) H end rat_seq namespace real open [class] rat_seq noncomputable protected definition inv (x : ℝ) : ℝ := quot.lift_on x (Ξ» a, quot.mk (rat_seq.r_inv a)) (Ξ» a b H, quot.sound (rat_seq.r_inv_well_defined H)) noncomputable definition real_has_inv [instance] [reducible] [priority real.prio] : has_inv real := has_inv.mk real.inv noncomputable protected definition div (x y : ℝ) : ℝ := x * y⁻¹ noncomputable definition real_has_div [instance] [reducible] [priority real.prio] : has_div real := has_div.mk real.div protected theorem le_total (x y : ℝ) : x ≀ y ∨ y ≀ x := quot.induction_onβ‚‚ x y (Ξ» s t, rat_seq.r_le_total s t) protected theorem mul_inv_cancel' (x : ℝ) : x β‰’ 0 β†’ x * x⁻¹ = 1 := quot.induction_on x (Ξ» s H, quot.sound (rat_seq.r_mul_inv s H)) protected theorem inv_mul_cancel' (x : ℝ) : x β‰’ 0 β†’ x⁻¹ * x = 1 := by rewrite real.mul_comm; apply real.mul_inv_cancel' theorem neq_of_sep {x y : ℝ} (H : x β‰’ y) : Β¬ x = y := assume Heq, !not_sep_self (Heq β–Έ H) theorem sep_of_neq {x y : ℝ} : Β¬ x = y β†’ x β‰’ y := quot.induction_onβ‚‚ x y (Ξ» s t H, rat_seq.r_sep_of_nequiv s t (assume Heq, H (quot.sound Heq))) theorem sep_is_neq (x y : ℝ) : (x β‰’ y) = (Β¬ x = y) := propext (iff.intro neq_of_sep sep_of_neq) protected theorem mul_inv_cancel (x : ℝ) : x β‰  0 β†’ x * x⁻¹ = 1 := !sep_is_neq β–Έ !real.mul_inv_cancel' protected theorem inv_mul_cancel (x : ℝ) : x β‰  0 β†’ x⁻¹ * x = 1 := !sep_is_neq β–Έ !real.inv_mul_cancel' protected theorem inv_zero : (0 : ℝ)⁻¹ = 0 := quot.sound (rat_seq.r_inv_zero) protected theorem lt_or_eq_of_le (x y : ℝ) : x ≀ y β†’ x < y ∨ x = y := quot.induction_onβ‚‚ x y (Ξ» s t H, or.elim (rat_seq.r_lt_or_equiv_of_le s t H) (assume H1, or.inl H1) (assume H2, or.inr (quot.sound H2))) protected theorem le_iff_lt_or_eq (x y : ℝ) : x ≀ y ↔ x < y ∨ x = y := iff.intro (real.lt_or_eq_of_le x y) (real.le_of_lt_or_eq x y) noncomputable definition dec_lt : decidable_rel real.lt := begin rewrite ↑decidable_rel, intros, apply prop_decidable end protected noncomputable definition discrete_linear_ordered_field [reducible] [trans_instance]: discrete_linear_ordered_field ℝ := ⦃ discrete_linear_ordered_field, real.comm_ring, real.ordered_ring, le_total := real.le_total, mul_inv_cancel := real.mul_inv_cancel, inv_mul_cancel := real.inv_mul_cancel, zero_lt_one := real.zero_lt_one, inv_zero := real.inv_zero, le_iff_lt_or_eq := real.le_iff_lt_or_eq, decidable_lt := dec_lt ⦄ theorem of_rat_zero : of_rat (0:rat) = (0:real) := rfl theorem of_rat_one : of_rat (1:rat) = (1:real) := rfl theorem of_rat_divide (x y : β„š) : of_rat (x / y) = of_rat x / of_rat y := by_cases (assume yz : y = 0, by krewrite [yz, div_zero, +of_rat_zero, div_zero]) (assume ynz : y β‰  0, have ynz' : of_rat y β‰  0, from assume yz', ynz (of_rat.inj yz'), !eq_div_of_mul_eq ynz' (by krewrite [-of_rat_mul, !div_mul_cancel ynz])) open int theorem of_int_div (x y : β„€) (H : y ∣ x) : of_int (x / y) = of_int x / of_int y := by rewrite [of_int_eq, rat.of_int_div H, of_rat_divide] theorem of_nat_div (x y : β„•) (H : y ∣ x) : of_nat (x / y) = of_nat x / of_nat y := by rewrite [of_nat_eq, rat.of_nat_div H, of_rat_divide] /- useful for proving equalities -/ theorem eq_zero_of_nonneg_of_forall_lt {x : ℝ} (xnonneg : x β‰₯ 0) (H : βˆ€ Ξ΅ : ℝ, Ξ΅ > 0 β†’ x < Ξ΅) : x = 0 := decidable.by_contradiction (suppose x β‰  0, have x > 0, from lt_of_le_of_ne xnonneg (ne.symm this), have x < x, from H x this, show false, from !lt.irrefl this) theorem eq_zero_of_nonneg_of_forall_le {x : ℝ} (xnonneg : x β‰₯ 0) (H : βˆ€ Ξ΅ : ℝ, Ξ΅ > 0 β†’ x ≀ Ξ΅) : x = 0 := have βˆ€ Ξ΅ : ℝ, Ξ΅ > 0 β†’ x < Ξ΅, from take Ξ΅, suppose Ξ΅ > 0, assert e2pos : Ξ΅ / 2 > 0, from div_pos_of_pos_of_pos `Ξ΅ > 0` two_pos, assert Ξ΅ / 2 < Ξ΅, from div_two_lt_of_pos `Ξ΅ > 0`, begin apply lt_of_le_of_lt, apply H _ e2pos, apply this end, eq_zero_of_nonneg_of_forall_lt xnonneg this theorem eq_zero_of_forall_abs_le {x : ℝ} (H : βˆ€ Ξ΅ : ℝ, Ξ΅ > 0 β†’ abs x ≀ Ξ΅) : x = 0 := by_contradiction (suppose x β‰  0, have abs x = 0, from eq_zero_of_nonneg_of_forall_le !abs_nonneg H, show false, from `x β‰  0` (eq_zero_of_abs_eq_zero this)) theorem eq_of_forall_abs_sub_le {x y : ℝ} (H : βˆ€ Ξ΅ : ℝ, Ξ΅ > 0 β†’ abs (x - y) ≀ Ξ΅) : x = y := have x - y = 0, from eq_zero_of_forall_abs_le H, eq_of_sub_eq_zero this end real
3a91fe0f8c6ec157805da7f31ec385bc5d300ec5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/ellipsisProjIssue.lean
6312eefd60dd928aee48b44bb76e58f08e670182
[ "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
23
lean
#check Nat.add ...succ
d767e61041422ecb4442a9f1192783246b48b23b
9028d228ac200bbefe3a711342514dd4e4458bff
/src/field_theory/separable.lean
cdd941f1ff4ada4b92ba7c915d6fef887d8ba35c
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,605
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau. -/ import algebra.polynomial.big_operators import field_theory.minimal_polynomial import field_theory.splitting_field import field_theory.tower /-! # Separable polynomials We define a polynomial to be separable if it is coprime with its derivative. We prove basic properties about separable polynomials here. ## Main definitions * `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative. * `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a commutative semiring `R` by a factor of p, so `expand R p (βˆ‘ aβ‚™ xⁿ)` is `βˆ‘ aβ‚™ xⁿᡖ`. * `polynomial.contract p f`: the opposite of `expand`, so it sends `βˆ‘ aβ‚™ xⁿᡖ` to `βˆ‘ aβ‚™ xⁿ`. -/ universes u v w open_locale classical big_operators open finset namespace polynomial section comm_semiring variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] /-- A polynomial is separable iff it is coprime with its derivative. -/ def separable (f : polynomial R) : Prop := is_coprime f f.derivative lemma separable_def (f : polynomial R) : f.separable ↔ is_coprime f f.derivative := iff.rfl lemma separable_def' (f : polynomial R) : f.separable ↔ βˆƒ a b : polynomial R, a * f + b * f.derivative = 1 := iff.rfl lemma separable_one : (1 : polynomial R).separable := is_coprime_one_left lemma separable_X_add_C (a : R) : (X + C a).separable := by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero], exact is_coprime_one_right } lemma separable_X : (X : polynomial R).separable := by { rw [separable_def, derivative_X], exact is_coprime_one_right } lemma separable_C (r : R) : (C r).separable ↔ is_unit r := by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C] lemma separable.of_mul_left {f g : polynomial R} (h : (f * g).separable) : f.separable := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this) end lemma separable.of_mul_right {f g : polynomial R} (h : (f * g).separable) : g.separable := by { rw mul_comm at h, exact h.of_mul_left } lemma separable.of_dvd {f g : polynomial R} (hf : f.separable) (hfg : g ∣ f) : g.separable := by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf } lemma separable_gcd_left {F : Type*} [field F] {f : polynomial F} (hf : f.separable) (g : polynomial F) : (euclidean_domain.gcd f g).separable := separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g) lemma separable_gcd_right {F : Type*} [field F] {g : polynomial F} (f : polynomial F) (hg : g.separable) : (euclidean_domain.gcd f g).separable := separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g) lemma separable.is_coprime {f g : polynomial R} (h : (f * g).separable) : is_coprime f g := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this) end theorem separable.of_pow' {f : polynomial R} : βˆ€ {n : β„•} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0 | 0 := Ξ» h, or.inr $ or.inr rfl | 1 := Ξ» h, or.inr $ or.inl ⟨pow_one f β–Έ h, rfl⟩ | (n+2) := Ξ» h, or.inl $ is_coprime_self.1 h.is_coprime.of_mul_right_left theorem separable.of_pow {f : polynomial R} (hf : Β¬is_unit f) {n : β„•} (hn : n β‰  0) (hfs : (f ^ n).separable) : f.separable ∧ n = 1 := (hfs.of_pow'.resolve_left hf).resolve_right hn theorem separable.map {p : polynomial R} (h : p.separable) {f : R β†’+* S} : (p.map f).separable := let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f, by rw [derivative_map, ← map_mul, ← map_mul, ← map_add, H, map_one]⟩ variables (R) (p q : β„•) /-- Expand the polynomial by a factor of p, so `βˆ‘ aβ‚™ xⁿ` becomes `βˆ‘ aβ‚™ xⁿᡖ`. -/ noncomputable def expand : polynomial R →ₐ[R] polynomial R := { commutes' := Ξ» r, evalβ‚‚_C _ _, .. (evalβ‚‚_ring_hom C (X ^ p) : polynomial R β†’+* polynomial R) } lemma coe_expand : (expand R p : polynomial R β†’ polynomial R) = evalβ‚‚ C (X ^ p) := rfl variables {R} lemma expand_eq_sum {f : polynomial R} : expand R p f = f.sum (Ξ» e a, C a * (X ^ p) ^ e) := by { dsimp [expand, evalβ‚‚], refl, } @[simp] lemma expand_C (r : R) : expand R p (C r) = C r := evalβ‚‚_C _ _ @[simp] lemma expand_X : expand R p X = X ^ p := evalβ‚‚_X _ _ @[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r := by simp_rw [monomial_eq_smul_X, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul] theorem expand_expand (f : polynomial R) : expand R p (expand R q f) = expand R (p * q) f := polynomial.induction_on f (Ξ» r, by simp_rw expand_C) (Ξ» f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg]) (Ξ» n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, alg_hom.map_pow, expand_X, pow_mul]) theorem expand_mul (f : polynomial R) : expand R (p * q) f = expand R p (expand R q f) := (expand_expand p q f).symm @[simp] theorem expand_one (f : polynomial R) : expand R 1 f = f := polynomial.induction_on f (Ξ» r, by rw expand_C) (Ξ» f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg]) (Ξ» n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one]) theorem expand_pow (f : polynomial R) : expand R (p ^ q) f = (expand R p ^[q] f) := nat.rec_on q (by rw [pow_zero, expand_one, function.iterate_zero, id]) $ Ξ» n ih, by rw [function.iterate_succ_apply', pow_succ, expand_mul, ih] theorem derivative_expand (f : polynomial R) : (expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) := by rw [coe_expand, derivative_evalβ‚‚_C, derivative_pow, derivative_X, mul_one] theorem coeff_expand {p : β„•} (hp : 0 < p) (f : polynomial R) (n : β„•) : (expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 := begin simp only [expand_eq_sum], change (show β„• β†’β‚€ R, from (f.sum (Ξ» e a, C a * (X ^ p) ^ e) : polynomial R)) n = _, simp_rw [finsupp.sum_apply, finsupp.sum, ← pow_mul, C_mul', ← monomial_eq_smul_X, monomial, finsupp.single_apply], split_ifs with h, { rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl], refl, { intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] }, { intro hn, rw finsupp.not_mem_support_iff.1 hn, split_ifs; refl } }, { rw finset.sum_eq_zero, intros k hk, rw if_neg, exact Ξ» hkn, h ⟨k, hkn.symm⟩, }, end @[simp] theorem coeff_expand_mul {p : β„•} (hp : 0 < p) (f : polynomial R) (n : β„•) : (expand R p f).coeff (n * p) = f.coeff n := by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp] @[simp] theorem coeff_expand_mul' {p : β„•} (hp : 0 < p) (f : polynomial R) (n : β„•) : (expand R p f).coeff (p * n) = f.coeff n := by rw [mul_comm, coeff_expand_mul hp] theorem expand_eq_map_domain (p : β„•) (f : polynomial R) : expand R p f = f.map_domain (*p) := finsupp.induction f (by { simp only [expand_eq_sum], refl }) $ Ξ» n r f hf hr ih, by rw [finsupp.map_domain_add, finsupp.map_domain_single, alg_hom.map_add, ← monomial, expand_monomial, ← monomial, ih] theorem expand_inj {p : β„•} (hp : 0 < p) {f g : polynomial R} : expand R p f = expand R p g ↔ f = g := ⟨λ H, ext $ Ξ» n, by rw [← coeff_expand_mul hp, H, coeff_expand_mul hp], congr_arg _⟩ theorem expand_eq_zero {p : β„•} (hp : 0 < p) {f : polynomial R} : expand R p f = 0 ↔ f = 0 := by rw [← (expand R p).map_zero, expand_inj hp, alg_hom.map_zero] theorem expand_eq_C {p : β„•} (hp : 0 < p) {f : polynomial R} {r : R} : expand R p f = C r ↔ f = C r := by rw [← expand_C, expand_inj hp, expand_C] theorem nat_degree_expand (p : β„•) (f : polynomial R) : (expand R p f).nat_degree = f.nat_degree * p := begin cases p.eq_zero_or_pos with hp hp, { rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, evalβ‚‚_hom, nat_degree_C] }, by_cases hf : f = 0, { rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] }, have hf1 : expand R p f β‰  0 := mt (expand_eq_zero hp).1 hf, rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1], refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ Ξ» n hn, _) _, { rw coeff_expand hp, split_ifs with hpn, { rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn, rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn }, { refl } }, { refine le_degree_of_ne_zero _, rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf } end theorem map_expand {p : β„•} (hp : 0 < p) {f : R β†’+* S} {q : polynomial R} : map f (expand R p q) = expand S p (map f q) := by { ext, rw [coeff_map, coeff_expand hp, coeff_expand hp], split_ifs; simp, } end comm_semiring section comm_ring variables {R : Type u} [comm_ring R] lemma separable_X_sub_C {x : R} : separable (X - C x) := by simpa only [C_neg] using separable_X_add_C (-x) lemma separable.mul {f g : polynomial R} (hf : f.separable) (hg : g.separable) (h : is_coprime f g) : (f * g).separable := by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left ((h.symm.mul_right hg).mul_add_right_right _) } lemma separable_prod' {ΞΉ : Sort*} {f : ΞΉ β†’ polynomial R} {s : finset ΞΉ} : (βˆ€x∈s, βˆ€y∈s, x β‰  y β†’ is_coprime (f x) (f y)) β†’ (βˆ€x∈s, (f x).separable) β†’ (∏ x in s, f x).separable := finset.induction_on s (Ξ» _ _, separable_one) $ Ξ» a s has ih h1 h2, begin simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has, exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ Ξ» i his, h1.1.2 i his $ ne.symm $ ne_of_mem_of_not_mem his has) end lemma separable_prod {ΞΉ : Sort*} [fintype ΞΉ] {f : ΞΉ β†’ polynomial R} (h1 : pairwise (is_coprime on f)) (h2 : βˆ€ x, (f x).separable) : (∏ x, f x).separable := separable_prod' (Ξ» x hx y hy hxy, h1 x y hxy) (Ξ» x hx, h2 x) lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ΞΉ : Sort*} {f : ΞΉ β†’ R} {s : finset ΞΉ} (hfs : (∏ i in s, (X - C (f i))).separable) {x y : ΞΉ} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y := begin by_contra hxy, rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy), prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← pow_two] at hfs, cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C) two_ne_zero).2 end lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ΞΉ : Sort*} [fintype ΞΉ] {f : ΞΉ β†’ R} (hfs : (∏ i, (X - C (f i))).separable) : function.injective f := Ξ» x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy lemma is_unit_of_self_mul_dvd_separable {p q : polynomial R} (hp : p.separable) (hq : q * q ∣ p) : is_unit q := begin obtain ⟨p, rfl⟩ := hq, apply is_coprime_self.mp, have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)), { simp only [← mul_assoc, mul_add], convert hp, rw [derivative_mul, derivative_mul], ring }, exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this) end end comm_ring section integral_domain variables (R : Type u) [integral_domain R] theorem is_local_ring_hom_expand {p : β„•} (hp : 0 < p) : is_local_ring_hom (↑(expand R p) : polynomial R β†’+* polynomial R) := begin refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1, have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1), rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2, rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C] end end integral_domain section field variables {F : Type u} [field F] {K : Type v} [field K] theorem separable_iff_derivative_ne_zero {f : polynomial F} (hf : irreducible f) : f.separable ↔ f.derivative β‰  0 := ⟨λ h1 h2, hf.1 $ is_coprime_zero_right.1 $ h2 β–Έ h1, Ξ» h, is_coprime_of_dvd (mt and.right h) $ Ξ» g hg1 hg2 ⟨p, hg3⟩ hg4, let ⟨u, hu⟩ := (hf.2 _ _ hg3).resolve_left hg1 in have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd }, not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt h⟩ theorem separable_map (f : F β†’+* K) {p : polynomial F} : (p.map f).separable ↔ p.separable := by simp_rw [separable_def, derivative_map, is_coprime_map] section char_p variables (p : β„•) [hp : fact p.prime] include hp /-- The opposite of `expand`: sends `βˆ‘ aβ‚™ xⁿᡖ` to `βˆ‘ aβ‚™ xⁿ`. -/ noncomputable def contract (f : polynomial F) : polynomial F := ⟨f.support.preimage (*p) $ Ξ» _ _ _ _, (nat.mul_left_inj hp.pos).1, Ξ» n, f.coeff (n * p), Ξ» n, by { rw [finset.mem_preimage, finsupp.mem_support_iff], refl }⟩ theorem coeff_contract (f : polynomial F) (n : β„•) : (contract p f).coeff n = f.coeff (n * p) := rfl theorem of_irreducible_expand {f : polynomial F} (hf : irreducible (expand F p f)) : irreducible f := @@of_irreducible_map _ _ _ (is_local_ring_hom_expand F hp.pos) hf theorem of_irreducible_expand_pow {f : polynomial F} {n : β„•} : irreducible (expand F (p ^ n) f) β†’ irreducible f := nat.rec_on n (Ξ» hf, by rwa [pow_zero, expand_one] at hf) $ Ξ» n ih hf, ih $ of_irreducible_expand p $ by rwa [expand_expand] variables [HF : char_p F p] include HF theorem expand_char (f : polynomial F) : map (frobenius F p) (expand F p f) = f ^ p := begin refine f.induction_on' (Ξ» a b ha hb, _) (Ξ» n a, _), { rw [alg_hom.map_add, map_add, ha, hb, add_pow_char], }, { rw [expand_monomial, map_monomial, single_eq_C_mul_X, single_eq_C_mul_X, mul_pow, ← C.map_pow, frobenius_def], ring_exp } end theorem map_expand_pow_char (f : polynomial F) (n : β„•) : map ((frobenius F p) ^ n) (expand F (p ^ n) f) = f ^ (p ^ n) := begin induction n, {simp [ring_hom.one_def]}, symmetry, rw [pow_succ', pow_mul, ← n_ih, ← expand_char, pow_succ, ring_hom.mul_def, ← map_map, mul_comm, expand_mul, ← map_expand (nat.prime.pos hp)], end theorem expand_contract {f : polynomial F} (hf : f.derivative = 0) : expand F p (contract p f) = f := begin ext n, rw [coeff_expand hp.pos, coeff_contract], split_ifs with h, { rw nat.div_mul_cancel h }, { cases n, { exact absurd (dvd_zero p) h }, have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this }, rw [← nat.cast_succ, char_p.cast_eq_zero_iff F p] at this, exact absurd this h } end theorem separable_or {f : polynomial F} (hf : irreducible f) : f.separable ∨ Β¬f.separable ∧ βˆƒ g : polynomial F, irreducible g ∧ expand F p g = f := if H : f.derivative = 0 then or.inr ⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H], contract p f, by haveI := is_local_ring_hom_expand F hp.pos; exact of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H at hf), expand_contract p H⟩ else or.inl $ (separable_iff_derivative_ne_zero hf).2 H theorem exists_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f β‰  0) : βˆƒ (n : β„•) (g : polynomial F), g.separable ∧ expand F (p ^ n) g = f := begin generalize hn : f.nat_degree = N, unfreezingI { revert f }, apply nat.strong_induction_on N, intros N ih f hf hf0 hn, rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩, { refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] }, { cases N with N, { rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn, rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1, rw [h1, C_0] at hn, exact absurd hn hf0 }, have hg1 : g.nat_degree * p = N.succ, { rwa [← nat_degree_expand, hgf] }, have hg2 : g.nat_degree β‰  0, { intro this, rw [this, zero_mul] at hg1, cases hg1 }, have hg3 : g.nat_degree < N.succ, { rw [← mul_one g.nat_degree, ← hg1], exact nat.mul_lt_mul_of_pos_left hp.one_lt (nat.pos_of_ne_zero hg2) }, have hg4 : g β‰  0, { rintro rfl, exact hg2 nat_degree_zero }, rcases ih _ hg3 hg hg4 rfl with ⟨n, g, hg5, rfl⟩, refine ⟨n+1, g, hg5, _⟩, rw [← hgf, expand_expand, pow_succ] } end theorem is_unit_or_eq_zero_of_separable_expand {f : polynomial F} (n : β„•) (hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 := begin rw or_iff_not_imp_right, intro hn, have hf2 : (expand F (p ^ n) f).derivative = 0, { by rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero, zero_pow (nat.pos_of_ne_zero hn), zero_mul, mul_zero] }, rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩, rw [eq_comm, expand_eq_C (pow_pos hp.pos _)] at hrf, rwa [hrf, is_unit_C] end theorem unique_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f β‰  0) (n₁ : β„•) (g₁ : polynomial F) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f) (nβ‚‚ : β„•) (gβ‚‚ : polynomial F) (hgβ‚‚ : gβ‚‚.separable) (hgfβ‚‚ : expand F (p ^ nβ‚‚) gβ‚‚ = f) : n₁ = nβ‚‚ ∧ g₁ = gβ‚‚ := begin revert g₁ gβ‚‚, wlog hn : n₁ ≀ nβ‚‚ := le_total n₁ nβ‚‚ using [n₁ nβ‚‚, nβ‚‚ n₁] tactic.skip, unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩, rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp.pos n₁)] at hgfβ‚‚, subst hgfβ‚‚, subst hgf₁, rcases is_unit_or_eq_zero_of_separable_expand p k hg₁ with h | rfl, { rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩, simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 }, { rw [add_zero, pow_zero, expand_one], split; refl } }, exact Ξ» g₁ gβ‚‚ hg₁ hgf₁ hgβ‚‚ hgfβ‚‚, let ⟨hn, hg⟩ := this gβ‚‚ g₁ hgβ‚‚ hgfβ‚‚ hg₁ hgf₁ in ⟨hn.symm, hg.symm⟩ end end char_p lemma separable_prod_X_sub_C_iff' {ΞΉ : Sort*} {f : ΞΉ β†’ F} {s : finset ΞΉ} : (∏ i in s, (X - C (f i))).separable ↔ (βˆ€ (x ∈ s) (y ∈ s), f x = f y β†’ x = y) := ⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy, Ξ» H, by { rw ← prod_attach, exact separable_prod' (Ξ» x hx y hy hxy, @pairwise_coprime_X_sub _ _ { x // x ∈ s } (Ξ» x, f x) (Ξ» x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy) (Ξ» _ _, separable_X_sub_C) }⟩ lemma separable_prod_X_sub_C_iff {ΞΉ : Sort*} [fintype ΞΉ] {f : ΞΉ β†’ F} : (∏ i, (X - C (f i))).separable ↔ function.injective f := separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff] section splits open_locale big_operators variables {i : F β†’+* K} lemma not_unit_X_sub_C (a : F) : Β¬ is_unit (X - C a) := Ξ» h, have one_eq_zero : (1 : with_bot β„•) = 0, by simpa using degree_eq_zero_of_is_unit h, one_ne_zero (option.some_injective _ one_eq_zero) lemma nodup_of_separable_prod {s : multiset F} (hs : separable (multiset.map (Ξ» a, X - C a) s).prod) : s.nodup := begin rw multiset.nodup_iff_ne_cons_cons, rintros a t rfl, refine not_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _), simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _) end lemma multiplicity_le_one_of_seperable {p q : polynomial F} (hq : Β¬ is_unit q) (hsep : separable p) : multiplicity q p ≀ 1 := begin contrapose! hq, apply is_unit_of_self_mul_dvd_separable hsep, rw ← pow_two, apply multiplicity.pow_dvd_of_le_multiplicity, exact_mod_cast (enat.add_one_le_of_lt hq) end lemma root_multiplicity_le_one_of_seperable {p : polynomial F} (hp : p β‰  0) (hsep : separable p) (x : F) : root_multiplicity x p ≀ 1 := begin rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_le_coe, enat.coe_get], exact multiplicity_le_one_of_seperable (not_unit_X_sub_C _) hsep end lemma count_roots_le_one {p : polynomial F} (hsep : separable p) (x : F) : p.roots.count x ≀ 1 := begin by_cases hp : p = 0, { simp [hp] }, rw count_roots hp, exact root_multiplicity_le_one_of_seperable hp hsep x end lemma nodup_roots {p : polynomial F} (hsep : separable p) : p.roots.nodup := multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep) lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : polynomial F} (h_ne_zero : h β‰  0) (h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h) (h_roots : βˆ€ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits, apply finset.mk.inj, { change _ = {i x}, rw finset.eq_singleton_iff_unique_mem, split, { apply finset.mem_mk.mpr, rw mem_roots (show h.map i β‰  0, by exact map_ne_zero h_ne_zero), rw [is_root.def,←evalβ‚‚_eq_eval_map,evalβ‚‚_hom,h_root], exact ring_hom.map_zero i }, { exact h_roots } }, { exact nodup_roots (separable.map h_sep) }, end end splits end field end polynomial open polynomial theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F} (hf : irreducible f) (hf0 : f β‰  0) : f.separable := begin rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], rintro ⟨⟩, rw [nat.pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff], refine Ξ» hf1, hf.1 _, rw [hf1, is_unit_C, is_unit_iff_ne_zero], intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf0 end /-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff the minimal polynomial of every `x : K` is separable. -/ @[class] def is_separable (F K : Sort*) [field F] [field K] [algebra F K] : Prop := βˆ€ x : K, βˆƒ H : is_integral F x, (minimal_polynomial H).separable section is_separable_tower variables {F E : Type*} (K : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_separable_tower_top_of_is_separable (h : is_separable F E) : is_separable K E := Ξ» x, Exists.cases_on (h x) (Ξ» hx hs, ⟨is_integral_of_is_scalar_tower x hx, hs.map.of_dvd (minimal_polynomial.dvd_map_of_is_scalar_tower K hx)⟩) lemma is_separable_tower_bot_of_is_separable (h : is_separable F E) : is_separable F K := begin intro x, obtain ⟨hx, hs⟩ := h (algebra_map K E x), have hx' : is_integral F x := is_integral_tower_bot_of_is_integral_field hx, obtain ⟨q, hq⟩ := minimal_polynomial.dvd hx' (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero_field (minimal_polynomial.aeval hx)), use hx', apply polynomial.separable.of_mul_left, rw ← hq, exact hs, end end is_separable_tower
ae9ea62836144449692c7c63194f9d141668755a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/finsupp/lattice.lean
6e628836798986e0c3a3373afaa4d05b961e9d97
[]
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,536
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.finsupp.basic import Mathlib.algebra.ordered_group import Mathlib.PostPort universes u_1 u_3 u_2 u_4 namespace Mathlib /-! # Lattice structure on finsupps This file provides instances of ordered structures on finsupps. -/ namespace finsupp protected instance order_bot {Ξ± : Type u_1} {ΞΌ : Type u_3} [canonically_ordered_add_monoid ΞΌ] : order_bot (Ξ± β†’β‚€ ΞΌ) := order_bot.mk 0 partial_order.le partial_order.lt sorry sorry sorry sorry protected instance semilattice_inf {Ξ± : Type u_1} {Ξ² : Type u_2} [HasZero Ξ²] [semilattice_inf Ξ²] : semilattice_inf (Ξ± β†’β‚€ Ξ²) := semilattice_inf.mk (zip_with has_inf.inf sorry) partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry @[simp] theorem inf_apply {Ξ± : Type u_1} {Ξ² : Type u_2} [HasZero Ξ²] [semilattice_inf Ξ²] {a : Ξ±} {f : Ξ± β†’β‚€ Ξ²} {g : Ξ± β†’β‚€ Ξ²} : coe_fn (f βŠ“ g) a = coe_fn f a βŠ“ coe_fn g a := rfl @[simp] theorem support_inf {Ξ± : Type u_1} {Ξ³ : Type u_4} [canonically_linear_ordered_add_monoid Ξ³] {f : Ξ± β†’β‚€ Ξ³} {g : Ξ± β†’β‚€ Ξ³} : support (f βŠ“ g) = support f ∩ support g := sorry protected instance semilattice_sup {Ξ± : Type u_1} {Ξ² : Type u_2} [HasZero Ξ²] [semilattice_sup Ξ²] : semilattice_sup (Ξ± β†’β‚€ Ξ²) := semilattice_sup.mk (zip_with has_sup.sup sorry) partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry @[simp] theorem sup_apply {Ξ± : Type u_1} {Ξ² : Type u_2} [HasZero Ξ²] [semilattice_sup Ξ²] {a : Ξ±} {f : Ξ± β†’β‚€ Ξ²} {g : Ξ± β†’β‚€ Ξ²} : coe_fn (f βŠ” g) a = coe_fn f a βŠ” coe_fn g a := rfl @[simp] theorem support_sup {Ξ± : Type u_1} {Ξ³ : Type u_4} [canonically_linear_ordered_add_monoid Ξ³] {f : Ξ± β†’β‚€ Ξ³} {g : Ξ± β†’β‚€ Ξ³} : support (f βŠ” g) = support f βˆͺ support g := sorry protected instance lattice {Ξ± : Type u_1} {Ξ² : Type u_2} [HasZero Ξ²] [lattice Ξ²] : lattice (Ξ± β†’β‚€ Ξ²) := lattice.mk semilattice_sup.sup semilattice_inf.le semilattice_inf.lt sorry sorry sorry sorry sorry sorry semilattice_inf.inf sorry sorry sorry protected instance semilattice_inf_bot {Ξ± : Type u_1} {Ξ³ : Type u_4} [canonically_linear_ordered_add_monoid Ξ³] : semilattice_inf_bot (Ξ± β†’β‚€ Ξ³) := semilattice_inf_bot.mk order_bot.bot order_bot.le order_bot.lt sorry sorry sorry sorry lattice.inf sorry sorry sorry theorem bot_eq_zero {Ξ± : Type u_1} {Ξ³ : Type u_4} [canonically_linear_ordered_add_monoid Ξ³] : βŠ₯ = 0 := rfl theorem disjoint_iff {Ξ± : Type u_1} {Ξ³ : Type u_4} [canonically_linear_ordered_add_monoid Ξ³] {x : Ξ± β†’β‚€ Ξ³} {y : Ξ± β†’β‚€ Ξ³} : disjoint x y ↔ disjoint (support x) (support y) := sorry /-- The order on `finsupp`s over a partial order embeds into the order on functions -/ def order_embedding_to_fun {Ξ± : Type u_1} {Ξ² : Type u_2} [HasZero Ξ²] [partial_order Ξ²] : (Ξ± β†’β‚€ Ξ²) β†ͺo (Ξ± β†’ Ξ²) := rel_embedding.mk (function.embedding.mk (fun (f : Ξ± β†’β‚€ Ξ²) (a : Ξ±) => coe_fn f a) sorry) sorry @[simp] theorem order_embedding_to_fun_apply {Ξ± : Type u_1} {Ξ² : Type u_2} [HasZero Ξ²] [partial_order Ξ²] {f : Ξ± β†’β‚€ Ξ²} {a : Ξ±} : coe_fn order_embedding_to_fun f a = coe_fn f a := rfl theorem monotone_to_fun {Ξ± : Type u_1} {Ξ² : Type u_2} [HasZero Ξ²] [partial_order Ξ²] : monotone to_fun := fun (f g : Ξ± β†’β‚€ Ξ²) (h : f ≀ g) (a : Ξ±) => iff.mp le_def h a
fbb871eaa8ee0393ea8e627ab26d57f3f7b41028
aa2345b30d710f7e75f13157a35845ee6d48c017
/analysis/metric_space.lean
628f8a3c2ebfac666eae943f0cbc5cc1867a4942
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
31,968
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes HΓΆlzl, Mario Carneiro, SΓ©bastien GouΓ«zel Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import data.real.nnreal analysis.topology.topological_structures open lattice set filter classical topological_space noncomputable theory universes u v w variables {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} /-- Construct a metric space from a distance function and metric space axioms -/ def metric_space.uniform_space_of_dist (dist : Ξ± β†’ Ξ± β†’ ℝ) (dist_self : βˆ€ x : Ξ±, dist x x = 0) (dist_comm : βˆ€ x y : Ξ±, dist x y = dist y x) (dist_triangle : βˆ€ x y z : Ξ±, dist x z ≀ dist x y + dist y z) : uniform_space Ξ± := uniform_space.of_core { uniformity := (β¨… Ξ΅>0, principal {p:Ξ±Γ—Ξ± | dist p.1 p.2 < Ξ΅}), refl := le_infi $ assume Ξ΅, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume Ξ΅, le_infi $ assume h, lift'_le (mem_infi_sets (Ξ΅ / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have βˆ€ (a b c : Ξ±), dist a c < Ξ΅ / 2 β†’ dist c b < Ξ΅ / 2 β†’ dist a b < Ξ΅, from assume a b c hac hcb, calc dist a b ≀ dist a c + dist c b : dist_triangle _ _ _ ... < Ξ΅ / 2 + Ξ΅ / 2 : add_lt_add hac hcb ... = Ξ΅ : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume Ξ΅, tendsto_infi.2 $ assume h, tendsto_infi' Ξ΅ $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- The distance function (given an ambient metric space on `Ξ±`), which returns a nonnegative real number `dist x y` given `x y : Ξ±`. -/ class has_dist (Ξ± : Type*) := (dist : Ξ± β†’ Ξ± β†’ ℝ) export has_dist (dist) /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. -/ class metric_space (Ξ± : Type u) extends has_dist Ξ± : Type u := (dist_self : βˆ€ x : Ξ±, dist x x = 0) (eq_of_dist_eq_zero : βˆ€ {x y : Ξ±}, dist x y = 0 β†’ x = y) (dist_comm : βˆ€ x y : Ξ±, dist x y = dist y x) (dist_triangle : βˆ€ x y z : Ξ±, dist x z ≀ dist x y + dist y z) (to_uniform_space : uniform_space Ξ± := metric_space.uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : uniformity = β¨… Ξ΅>0, principal {p:Ξ±Γ—Ξ± | dist p.1 p.2 < Ξ΅} . control_laws_tac) theorem uniformity_dist_of_mem_uniformity {U : filter (Ξ± Γ— Ξ±)} (D : Ξ± β†’ Ξ± β†’ ℝ) (H : βˆ€ s, s ∈ U.sets ↔ βˆƒΞ΅>0, βˆ€{a b:Ξ±}, D a b < Ξ΅ β†’ (a, b) ∈ s) : U = β¨… Ξ΅>0, principal {p:Ξ±Γ—Ξ± | D p.1 p.2 < Ξ΅} := le_antisymm (le_infi $ Ξ» Ξ΅, le_infi $ Ξ» Ξ΅0, le_principal_iff.2 $ (H _).2 ⟨Ρ, Ξ΅0, Ξ» a b, id⟩) (Ξ» r ur, let ⟨Ρ, Ξ΅0, h⟩ := (H _).1 ur in mem_infi_sets Ξ΅ $ mem_infi_sets Ξ΅0 $ mem_principal_sets.2 $ Ξ» ⟨a, b⟩, h) variables [metric_space Ξ±] instance metric_space.to_uniform_space' : uniform_space Ξ± := metric_space.to_uniform_space Ξ± @[simp] theorem dist_self (x : Ξ±) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : Ξ±} : dist x y = 0 β†’ x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : Ξ±) : dist x y = dist y x := metric_space.dist_comm x y @[simp] theorem dist_eq_zero {x y : Ξ±} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this β–Έ dist_self _) @[simp] theorem zero_eq_dist {x y : Ξ±} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : Ξ±) : dist x z ≀ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : Ξ±) : dist x y ≀ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : Ξ±) : dist x y ≀ dist x z + dist y z := by rw dist_comm y; apply dist_triangle theorem swap_dist : function.swap (@dist Ξ± _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : Ξ±) : abs (dist x z - dist y z) ≀ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : Ξ±} : 0 ≀ dist x y := have 2 * dist x y β‰₯ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... β‰₯ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : Ξ±} : dist x y ≀ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : Ξ±} : 0 < dist x y ↔ x β‰  y := by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y) section variables [metric_space Ξ±] def nndist (a b : Ξ±) : nnreal := ⟨dist a b, dist_nonneg⟩ @[simp] lemma nndist_self (a : Ξ±) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) @[simp] lemma coe_dist (a b : Ξ±) : (nndist a b : ℝ) = dist a b := rfl theorem eq_of_nndist_eq_zero {x y : Ξ±} : nndist x y = 0 β†’ x = y := by simp [nnreal.eq_iff.symm] theorem nndist_comm (x y : Ξ±) : nndist x y = nndist y x := by simpa [nnreal.eq_iff.symm] using dist_comm x y @[simp] theorem nndist_eq_zero {x y : Ξ±} : nndist x y = 0 ↔ x = y := by simp [nnreal.eq_iff.symm] @[simp] theorem zero_eq_nndist {x y : Ξ±} : 0 = nndist x y ↔ x = y := by simp [nnreal.eq_iff.symm] theorem nndist_triangle (x y z : Ξ±) : nndist x z ≀ nndist x y + nndist y z := by simpa [nnreal.coe_le] using dist_triangle x y z theorem nndist_triangle_left (x y z : Ξ±) : nndist x y ≀ nndist z x + nndist z y := by simpa [nnreal.coe_le] using dist_triangle_left x y z theorem nndist_triangle_right (x y z : Ξ±) : nndist x y ≀ nndist x z + nndist y z := by simpa [nnreal.coe_le] using dist_triangle_right x y z end /- instantiate metric space as a topology -/ variables {x y z : Ξ±} {Ξ΅ Ρ₁ Ξ΅β‚‚ : ℝ} {s : set Ξ±} /-- `ball x Ξ΅` is the set of all points `y` with `dist y x < Ξ΅` -/ def ball (x : Ξ±) (Ξ΅ : ℝ) : set Ξ± := {y | dist y x < Ξ΅} @[simp] theorem mem_ball : y ∈ ball x Ξ΅ ↔ dist y x < Ξ΅ := iff.rfl theorem mem_ball' : y ∈ ball x Ξ΅ ↔ dist x y < Ξ΅ := by rw dist_comm; refl /-- `closed_ball x Ξ΅` is the set of all points `y` with `dist y x ≀ Ξ΅` -/ def closed_ball (x : Ξ±) (Ξ΅ : ℝ) := {y | dist y x ≀ Ξ΅} @[simp] theorem mem_closed_ball : y ∈ closed_ball x Ξ΅ ↔ dist y x ≀ Ξ΅ := iff.rfl theorem ball_subset_closed_ball : ball x Ξ΅ βŠ† closed_ball x Ξ΅ := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x Ξ΅) : Ξ΅ > 0 := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : Ξ΅ > 0) : x ∈ ball x Ξ΅ := show dist x x < Ξ΅, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y Ξ΅ ↔ y ∈ ball x Ξ΅ := by simp [dist_comm] theorem ball_subset_ball (h : Ρ₁ ≀ Ξ΅β‚‚) : ball x Ρ₁ βŠ† ball x Ξ΅β‚‚ := Ξ» y (yx : _ < Ρ₁), lt_of_lt_of_le yx h theorem ball_disjoint (h : Ρ₁ + Ξ΅β‚‚ ≀ dist x y) : ball x Ρ₁ ∩ ball y Ξ΅β‚‚ = βˆ… := eq_empty_iff_forall_not_mem.2 $ Ξ» z ⟨h₁, hβ‚‚βŸ©, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ hβ‚‚) h) theorem ball_disjoint_same (h : Ξ΅ ≀ dist x y / 2) : ball x Ξ΅ ∩ ball y Ξ΅ = βˆ… := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos] theorem ball_subset (h : dist x y ≀ Ξ΅β‚‚ - Ρ₁) : ball x Ρ₁ βŠ† ball y Ξ΅β‚‚ := Ξ» z zx, by rw ← add_sub_cancel'_right Ρ₁ Ξ΅β‚‚; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (Ξ΅ / 2)) : ball y (Ξ΅ / 2) βŠ† ball x Ξ΅ := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x Ξ΅) : βˆƒ Ξ΅' > 0, ball y Ξ΅' βŠ† ball x Ξ΅ := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem ball_eq_empty_iff_nonpos : Ξ΅ ≀ 0 ↔ ball x Ξ΅ = βˆ… := (eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ Ξ» Ξ΅0, h _ $ mem_ball_self Ξ΅0, Ξ» Ξ΅0 y h, not_lt_of_le Ξ΅0 $ pos_of_mem_ball h⟩).symm theorem uniformity_dist : uniformity = (β¨… Ξ΅>0, principal {p:Ξ±Γ—Ξ± | dist p.1 p.2 < Ξ΅}) := metric_space.uniformity_dist _ theorem uniformity_dist' : uniformity = (β¨…Ξ΅:{Ξ΅:ℝ // Ξ΅>0}, principal {p:Ξ±Γ—Ξ± | dist p.1 p.2 < Ξ΅.val}) := by simp [infi_subtype]; exact uniformity_dist theorem mem_uniformity_dist {s : set (Ξ±Γ—Ξ±)} : s ∈ (@uniformity Ξ± _).sets ↔ (βˆƒΞ΅>0, βˆ€{a b:Ξ±}, dist a b < Ξ΅ β†’ (a, b) ∈ s) := begin rw [uniformity_dist', infi_sets_eq], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (β‰₯)] {contextual := tt}⟩, exact ⟨⟨1, zero_lt_one⟩⟩ end theorem dist_mem_uniformity {Ξ΅:ℝ} (Ξ΅0 : 0 < Ξ΅) : {p:Ξ±Γ—Ξ± | dist p.1 p.2 < Ξ΅} ∈ (@uniformity Ξ± _).sets := mem_uniformity_dist.2 ⟨Ρ, Ξ΅0, Ξ» a b, id⟩ theorem uniform_continuous_of_metric [metric_space Ξ²] {f : Ξ± β†’ Ξ²} : uniform_continuous f ↔ βˆ€ Ξ΅ > 0, βˆƒ Ξ΄ > 0, βˆ€{a b:Ξ±}, dist a b < Ξ΄ β†’ dist (f a) (f b) < Ξ΅ := uniform_continuous_def.trans ⟨λ H Ξ΅ Ξ΅0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity Ξ΅0, Ξ» H r ru, let ⟨Ρ, Ξ΅0, hΡ⟩ := mem_uniformity_dist.1 ru, ⟨δ, Ξ΄0, hδ⟩ := H _ Ξ΅0 in mem_uniformity_dist.2 ⟨δ, Ξ΄0, Ξ» a b h, hΞ΅ (hΞ΄ h)⟩⟩ theorem uniform_embedding_of_metric [metric_space Ξ²] {f : Ξ± β†’ Ξ²} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ βˆ€ Ξ΄ > 0, βˆƒ Ξ΅ > 0, βˆ€ {a b : Ξ±}, dist (f a) (f b) < Ξ΅ β†’ dist a b < Ξ΄ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H Ξ΄ Ξ΄0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity Ξ΄0), ⟨Ρ, Ξ΅0, hΡ⟩ := mem_uniformity_dist.1 tu in ⟨Ρ, Ξ΅0, Ξ» a b h, ht _ _ (hΞ΅ h)⟩, Ξ» H s su, let ⟨δ, Ξ΄0, hδ⟩ := mem_uniformity_dist.1 su, ⟨Ρ, Ξ΅0, hΡ⟩ := H _ Ξ΄0 in ⟨_, dist_mem_uniformity Ξ΅0, Ξ» a b h, hΞ΄ (hΞ΅ h)⟩⟩ theorem totally_bounded_of_metric {s : set Ξ±} : totally_bounded s ↔ βˆ€ Ξ΅ > 0, βˆƒt : set Ξ±, finite t ∧ s βŠ† ⋃y∈t, ball y Ξ΅ := ⟨λ H Ξ΅ Ξ΅0, H _ (dist_mem_uniformity Ξ΅0), Ξ» H r ru, let ⟨Ρ, Ξ΅0, hΡ⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H Ξ΅ Ξ΅0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ Ξ» y, Union_subset_Union $ Ξ» yt z, hΡ⟩⟩ lemma cauchy_of_metric {f : filter Ξ±} : cauchy f ↔ f β‰  βŠ₯ ∧ βˆ€ Ξ΅ > 0, βˆƒ t ∈ f.sets, βˆ€ x y ∈ t, dist x y < Ξ΅ := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H Ξ΅ Ξ΅0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity Ξ΅0) in ⟨t, tf, Ξ» x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, Ξ» H r ru, let ⟨Ρ, Ξ΅0, hΡ⟩ := mem_uniformity_dist.1 ru, ⟨t, tf, h⟩ := H Ξ΅ Ξ΅0 in ⟨t, tf, Ξ» ⟨x, y⟩ ⟨hx, hy⟩, hΞ΅ (h x y hx hy)⟩⟩ theorem nhds_eq_metric : nhds x = (β¨…Ξ΅:{Ξ΅:ℝ // Ξ΅>0}, principal (ball x Ξ΅.val)) := begin rw [nhds_eq_uniformity, uniformity_dist', lift'_infi], { apply congr_arg, funext Ξ΅, rw [lift'_principal], { simp [ball, dist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff_metric : s ∈ (nhds x).sets ↔ βˆƒΞ΅>0, ball x Ξ΅ βŠ† s := begin rw [nhds_eq_metric, infi_sets_eq], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right, (β‰₯)] }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end theorem is_open_metric : is_open s ↔ βˆ€x∈s, βˆƒΞ΅>0, ball x Ξ΅ βŠ† s := by simp [is_open_iff_nhds, mem_nhds_iff_metric] theorem is_open_ball : is_open (ball x Ξ΅) := is_open_metric.2 $ Ξ» y, exists_ball_subset_ball theorem ball_mem_nhds (x : Ξ±) {Ξ΅ : ℝ} (Ξ΅0 : 0 < Ξ΅) : ball x Ξ΅ ∈ (nhds x).sets := mem_nhds_sets is_open_ball (mem_ball_self Ξ΅0) theorem tendsto_nhds_of_metric [metric_space Ξ²] {f : Ξ± β†’ Ξ²} {a b} : tendsto f (nhds a) (nhds b) ↔ βˆ€ Ξ΅ > 0, βˆƒ Ξ΄ > 0, βˆ€{x:Ξ±}, dist x a < Ξ΄ β†’ dist (f x) b < Ξ΅ := ⟨λ H Ξ΅ Ξ΅0, mem_nhds_iff_metric.1 (H (ball_mem_nhds _ Ξ΅0)), Ξ» H s hs, let ⟨Ρ, Ξ΅0, hΡ⟩ := mem_nhds_iff_metric.1 hs, ⟨δ, Ξ΄0, hδ⟩ := H _ Ξ΅0 in mem_nhds_iff_metric.2 ⟨δ, Ξ΄0, Ξ» x h, hΞ΅ (hΞ΄ h)⟩⟩ theorem continuous_of_metric [metric_space Ξ²] {f : Ξ± β†’ Ξ²} : continuous f ↔ βˆ€b (Ξ΅ > 0), βˆƒ Ξ΄ > 0, βˆ€a, dist a b < Ξ΄ β†’ dist (f a) (f b) < Ξ΅ := continuous_iff_tendsto.trans $ forall_congr $ Ξ» b, tendsto_nhds_of_metric theorem exists_delta_of_continuous [metric_space Ξ²] {f : Ξ± β†’ Ξ²} {Ξ΅:ℝ} (hf : continuous f) (hΞ΅ : Ξ΅ > 0) (b : Ξ±) : βˆƒ Ξ΄ > 0, βˆ€a, dist a b ≀ Ξ΄ β†’ dist (f a) (f b) < Ξ΅ := let ⟨δ, Ξ΄_pos, hδ⟩ := continuous_of_metric.1 hf b Ξ΅ hΞ΅ in ⟨δ / 2, half_pos Ξ΄_pos, assume a ha, hΞ΄ a $ lt_of_le_of_lt ha $ div_two_lt_of_pos Ξ΄_pos⟩ theorem eq_of_forall_dist_le {x y : Ξ±} (h : βˆ€Ξ΅, Ξ΅ > 0 β†’ dist x y ≀ Ξ΅) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) instance metric_space.to_separated : separated Ξ± := separated_def.2 $ Ξ» x y h, eq_of_forall_dist_le $ Ξ» Ξ΅ Ξ΅0, le_of_lt (h _ (dist_mem_uniformity Ξ΅0)) /-- Instantiate the reals as a metric space. -/ instance : metric_space ℝ := { dist := Ξ»x y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, abs_sub _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] @[simp] theorem abs_dist {a b : Ξ±} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg instance : orderable_topology ℝ := orderable_topology_of_nhds_abs $ Ξ» x, begin simp only [show βˆ€ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact Ξ» Ξ΅ Ξ΅0, mem_nhds_sets (is_open_ball) (mem_ball_self Ξ΅0) }, { intros s h, rcases mem_nhds_iff_metric.1 h with ⟨Ρ, Ξ΅0, ss⟩, exact mem_infi_sets _ (mem_infi_sets Ξ΅0 (mem_principal_sets.2 ss)) }, end def metric_space.replace_uniformity {Ξ±} [U : uniform_space Ξ±] (m : metric_space Ξ±) (H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space Ξ±)) : metric_space Ξ± := { dist := @dist _ m.to_has_dist, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := U, uniformity_dist := H.trans (@uniformity_dist Ξ± _) } def metric_space.induced {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (hf : function.injective f) (m : metric_space Ξ²) : metric_space Ξ± := { dist := Ξ» x y, dist (f x) (f y), dist_self := Ξ» x, dist_self _, eq_of_dist_eq_zero := Ξ» x y h, hf (dist_eq_zero.1 h), dist_comm := Ξ» x y, dist_comm _ _, dist_triangle := Ξ» x y z, dist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ (Ξ» x y, dist (f x) (f y)), refine Ξ» s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨Ρ, Ξ΅0, hΡ⟩, refine ⟨Ρ, Ξ΅0, Ξ» a b h, rs (hΞ΅ _)⟩, exact h }, { rcases H with ⟨Ρ, Ξ΅0, hΡ⟩, exact ⟨_, dist_mem_uniformity Ξ΅0, Ξ» ⟨a, b⟩, hΡ⟩ } end } theorem metric_space.induced_uniform_embedding {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (hf : function.injective f) (m : metric_space Ξ²) : by haveI := metric_space.induced f hf m; exact uniform_embedding f := by let := metric_space.induced f hf m; exactI uniform_embedding_of_metric.2 ⟨hf, uniform_continuous_comap, Ξ» Ξ΅ Ξ΅0, ⟨Ρ, Ξ΅0, Ξ» a b, id⟩⟩ instance {p : Ξ± β†’ Prop} [t : metric_space Ξ±] : metric_space (subtype p) := metric_space.induced subtype.val (Ξ» x y, subtype.eq) t theorem subtype.dist_eq {p : Ξ± β†’ Prop} [t : metric_space Ξ±] (x y : subtype p) : dist x y = dist x.1 y.1 := rfl instance prod.metric_space_max [metric_space Ξ²] : metric_space (Ξ± Γ— Ξ²) := { dist := Ξ» x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := Ξ» x, by simp, eq_of_dist_eq_zero := Ξ» x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ hβ‚‚, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 hβ‚‚βŸ© end, dist_comm := Ξ» x y, by simp [dist_comm], dist_triangle := Ξ» x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_dist := begin refine uniformity_prod.trans _, simp [uniformity_dist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } theorem uniform_continuous_dist' : uniform_continuous (Ξ»p:Ξ±Γ—Ξ±, dist p.1 p.2) := uniform_continuous_of_metric.2 (Ξ» Ξ΅ Ξ΅0, ⟨Ρ/2, half_pos Ξ΅0, begin suffices, { intros p q h, cases p with p₁ pβ‚‚, cases q with q₁ qβ‚‚, cases max_lt_iff.1 h with h₁ hβ‚‚, clear h, dsimp at h₁ hβ‚‚ ⊒, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ pβ‚‚ q₁ qβ‚‚ h₁ hβ‚‚, exact this }, { apply this; rwa dist_comm } }, intros p₁ pβ‚‚ q₁ qβ‚‚ h₁ hβ‚‚, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ pβ‚‚) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le pβ‚‚ qβ‚‚ q₁) hβ‚‚)).1, rwa [add_halves, dist_comm pβ‚‚, sub_add_sub_cancel, dist_comm qβ‚‚] at this end⟩) theorem uniform_continuous_dist [uniform_space Ξ²] {f g : Ξ² β†’ Ξ±} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (Ξ»b, dist (f b) (g b)) := (hf.prod_mk hg).comp uniform_continuous_dist' theorem continuous_dist' : continuous (Ξ»p:Ξ±Γ—Ξ±, dist p.1 p.2) := uniform_continuous_dist'.continuous theorem continuous_dist [topological_space Ξ²] {f g : Ξ² β†’ Ξ±} (hf : continuous f) (hg : continuous g) : continuous (Ξ»b, dist (f b) (g b)) := (hf.prod_mk hg).comp continuous_dist' theorem tendsto_dist {f g : Ξ² β†’ Ξ±} {x : filter Ξ²} {a b : Ξ±} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (Ξ»x, dist (f x) (g x)) x (nhds (dist a b)) := have tendsto (Ξ»p:Ξ±Γ—Ξ±, dist p.1 p.2) (nhds (a, b)) (nhds (dist a b)), from continuous_iff_tendsto.mp continuous_dist' (a, b), (hf.prod_mk hg).comp (by rw [nhds_prod_eq] at this; exact this) lemma nhds_comap_dist (a : Ξ±) : (nhds (0 : ℝ)).comap (Ξ»a', dist a' a) = nhds a := have h₁ : βˆ€Ξ΅, (Ξ»a', dist a' a) ⁻¹' ball 0 Ξ΅ βŠ† ball a Ξ΅, by simp [subset_def, real.dist_0_eq_abs], have hβ‚‚ : tendsto (Ξ»a', dist a' a) (nhds a) (nhds (dist a a)), from tendsto_dist tendsto_id tendsto_const_nhds, le_antisymm (by simp [h₁, nhds_eq_metric, infi_le_infi, principal_mono, -le_principal_iff, -le_infi_iff]) (by simpa [map_le_iff_le_comap.symm, tendsto] using hβ‚‚) lemma tendsto_iff_dist_tendsto_zero {f : Ξ² β†’ Ξ±} {x : filter Ξ²} {a : Ξ±} : (tendsto f x (nhds a)) ↔ (tendsto (Ξ»b, dist (f b) a) x (nhds 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] theorem is_closed_ball : is_closed (closed_ball x Ξ΅) := is_closed_le (continuous_dist continuous_id continuous_const) continuous_const /-- Ξ΅-characterization of the closure in metric spaces-/ theorem mem_closure_iff' {Ξ± : Type u} [metric_space Ξ±] {s : set Ξ±} {a : Ξ±} : a ∈ closure s ↔ βˆ€Ξ΅>0, βˆƒb ∈ s, dist a b < Ξ΅ := ⟨begin intros ha Ξ΅ hΞ΅, have A : ball a Ξ΅ ∩ s β‰  βˆ… := mem_closure_iff.1 ha _ is_open_ball (mem_ball_self hΞ΅), cases ne_empty_iff_exists_mem.1 A with b hb, simp, exact ⟨b, ⟨hb.2, by have B := hb.1; simpa [mem_ball'] using B⟩⟩ end, begin intros H, apply mem_closure_iff.2, intros o ho ao, rcases is_open_metric.1 ho a ao with ⟨Ρ, ⟨Ρpos, hΡ⟩⟩, rcases H Ξ΅ Ξ΅pos with ⟨b, ⟨bs, bdist⟩⟩, have B : b ∈ o ∩ s := ⟨hΞ΅ (by simpa [dist_comm]), bs⟩, apply ne_empty_of_mem B end⟩ section pi open finset lattice variables {Ο€ : Ξ² β†’ Type*} [fintype Ξ²] [βˆ€b, metric_space (Ο€ b)] instance has_dist_pi : has_dist (Ξ b, Ο€ b) := ⟨λf g, ((finset.sup univ (Ξ»b, nndist (f b) (g b)) : nnreal) : ℝ)⟩ lemma dist_pi_def (f g : Ξ b, Ο€ b) : dist f g = (finset.sup univ (Ξ»b, nndist (f b) (g b)) : nnreal) := rfl instance metric_space_pi : metric_space (Ξ b, Ο€ b) := { dist := dist, dist_self := assume f, (nnreal.coe_eq_zero _).2 $ bot_unique $ finset.sup_le $ by simp, dist_comm := assume f g, nnreal.eq_iff.2 $ by congr; ext a; exact nndist_comm _ _, dist_triangle := assume f g h, show dist f h ≀ (dist f g) + (dist g h), from begin simp only [dist_pi_def, (nnreal.coe_add _ _).symm, (nnreal.coe_le _ _).symm, finset.sup_le_iff], assume b hb, exact le_trans (nndist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, eq_of_dist_eq_zero := assume f g eq0, begin simp only [dist_pi_def, nnreal.coe_eq_zero, nnreal.bot_eq_zero.symm, eq_bot_iff, finset.sup_le_iff] at eq0, exact (funext $ assume b, eq_of_nndist_eq_zero $ bot_unique $ eq0 b $ mem_univ b), end } end pi section second_countable /-- A separable metric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops.-/ lemma second_countable_of_separable_metric_space (Ξ± : Type u) [metric_space Ξ±] [separable_space Ξ±] : second_countable_topology Ξ± := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ Ξ± in βŸ¨βŸ¨β‹ƒx ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, begin apply countable_bUnion S_countable, intros a aS, apply countable_Union, simp end, show uniform_space.to_topological_space Ξ± = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), begin have A : βˆ€ (u : set Ξ±), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ℝ)⁻¹)} : set (set Ξ±))) β†’ is_open u := begin simp, intros u x hx i u_ball, rw [u_ball], apply is_open_ball end, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set Ξ±))) := begin apply is_topological_basis_of_open_of_nhds A, intros a u au open_u, rcases is_open_metric.1 open_u a au with ⟨Ρ, Ξ΅pos, Ξ΅ball⟩, have : Ξ΅ / 2 > 0 := half_pos Ξ΅pos, /- The ball `ball a Ξ΅` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a Ξ΅`. For this, we take `n` larger than `2/Ξ΅`, and then `x` in `S` at distance at most `n⁻¹` of `a`-/ rcases exists_nat_gt (Ξ΅/2)⁻¹ with ⟨n, Ξ΅n⟩, have : (n : ℝ) > 0 := lt_trans (inv_pos β€ΉΞ΅/2 > 0β€Ί) Ξ΅n, have : 0 < (n : ℝ)⁻¹ := inv_pos this, have : (n : ℝ)⁻¹ < Ξ΅/2 := (inv_lt β€ΉΞ΅/2 > 0β€Ί β€Ή(n : ℝ) > 0β€Ί).1 Ξ΅n, have : (a : Ξ±) ∈ closure (S : set Ξ±) := by rw [S_dense]; simp, rcases mem_closure_iff'.1 this _ β€Ή0 < (n : ℝ)⁻¹› with ⟨x, xS, xdist⟩, have : a ∈ ball x (n⁻¹) := by simpa, have : ball x (n⁻¹) βŠ† ball a Ξ΅ := begin intros y, simp, intros ydist, calc dist y a = dist a y : dist_comm _ _ ... ≀ dist a x + dist y x : dist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : add_lt_add xdist ydist ... < Ξ΅/2 + Ξ΅/2 : add_lt_add β€Ή(n : ℝ)⁻¹ < Ξ΅/2β€Ί β€Ή(n : ℝ)⁻¹ < Ξ΅/2β€Ί ... = Ξ΅ : add_halves _, end, have : ball x (n⁻¹) βŠ† u := subset.trans this Ξ΅ball, existsi ball x (↑n)⁻¹, simp, exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by assumption, by assumption⟩⟩, end, exact B.2.2, end⟩⟩⟩ end second_countable section compact /--Any compact set in a metric space can be covered by finitely many balls of a given positive radius-/ lemma finite_cover_balls_of_compact {Ξ± : Type u} [metric_space Ξ±] {s : set Ξ±} (hs : compact s) {e : ℝ} (he : e > 0) : βˆƒt βŠ† s, (finite t ∧ s βŠ† (⋃x∈t, ball x e)) := begin apply compact_elim_finite_subcover_image hs, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end /--A compact set in a metric space is separable, i.e., it is the closure of a countable set-/ lemma countable_closure_of_compact {Ξ± : Type u} [metric_space Ξ±] {s : set Ξ±} (hs : compact s) : βˆƒ t βŠ† s, (countable t ∧ s = closure t) := begin have A : βˆ€ (e:ℝ), e > 0 β†’ βˆƒ t βŠ† s, (finite t ∧ s βŠ† (⋃x∈t, ball x e)) := assume e, finite_cover_balls_of_compact hs, have B : βˆ€ (e:ℝ), βˆƒ t βŠ† s, finite t ∧ (e > 0 β†’ s βŠ† (⋃x∈t, ball x e)) := begin intro e, cases le_or_gt e 0 with h, { exact βŸ¨βˆ…, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish } end, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`.-/ choose T T_in_s finite_T using B, let t := ⋃n, T (n : β„•)⁻¹, have T₁ : t βŠ† s := begin apply Union_subset, assume n, apply T_in_s end, have Tβ‚‚ : countable t := by finish [countable_Union, countable_finite], have T₃ : s βŠ† closure t := begin intros x x_in_s, apply mem_closure_iff'.2, intros Ξ΅ Ξ΅pos, rcases exists_nat_gt Ρ⁻¹ with ⟨n, Ξ΅n⟩, have : (n : ℝ) > 0 := lt_trans (inv_pos Ξ΅pos) Ξ΅n, have inv_n_pos : 0 < (n : ℝ)⁻¹ := inv_pos this, have C : x ∈ (⋃y∈ T (↑n)⁻¹, ball y (↑n)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (↑n)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, x_w⟩, simp at x_w, have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (Ξ» (n:β„•), T (n : ℝ)⁻¹)), have : dist x y < Ξ΅ := lt_trans x_w ((inv_lt Ξ΅pos β€Ή(n : ℝ) > 0β€Ί).1 Ξ΅n), exact ⟨y, β€Ήy ∈ tβ€Ί, β€Ήdist x y < Ξ΅β€ΊβŸ© end, have Tβ‚„ : closure t βŠ† s := calc closure t βŠ† closure s : closure_mono T₁ ... = s : closure_eq_of_is_closed (closed_of_compact _ hs), exact ⟨t, ⟨T₁, Tβ‚‚, subset.antisymm T₃ Tβ‚„βŸ©βŸ© end end compact section proper_space /--A metric space is proper if all closed balls are compact.-/ class proper_space (Ξ± : Type u) [metric_space Ξ±] : Prop := (compact_ball : βˆ€x:Ξ±, βˆ€r, compact (closed_ball x r)) /-A compact metric space is proper-/ instance proper_of_compact_metric_space [metric_space Ξ±] [compact_space Ξ±] : proper_space Ξ± := ⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩ /--A proper space is locally compact-/ instance locally_compact_of_proper_metric_space [metric_space Ξ±] [proper_space Ξ±] : locally_compact_space Ξ± := begin apply locally_compact_of_compact_nhds, intros x, existsi closed_ball x 1, split, { apply mem_nhds_iff_metric.2, existsi (1 : ℝ), simp, exact ⟨zero_lt_one, ball_subset_closed_ball⟩ }, { apply proper_space.compact_ball } end /--A proper space is complete-/ instance complete_of_proper {Ξ± : Type u} [metric_space Ξ±] [proper_space Ξ±] : complete_space Ξ± := ⟨begin intros f hf, /-We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial.-/ have A : βˆƒ t ∈ f.sets, βˆ€ x y ∈ t, dist x y < 1 := (cauchy_of_metric.1 hf).2 1 (by norm_num), rcases A with ⟨t, ⟨t_fset, ht⟩⟩, rcases inhabited_of_mem_sets hf.1 t_fset with ⟨x, xt⟩, have : t βŠ† closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt), have : closed_ball x 1 ∈ f.sets := f.sets_of_superset t_fset this, exact complete_of_compact_set hf this (proper_space.compact_ball _ _), end⟩ /--A proper metric space is separable, and therefore second countable. Indeed, any ball is compact, and therefore admits a countable dense subset. Taking a countable union over the balls centered at a fixed point and with integer radius, one obtains a countable set which is dense in the whole space.-/ instance second_countable_of_proper_metric_space [metric_space Ξ±] [proper_space Ξ±] : second_countable_topology Ξ± := begin /-We show that the space admits a countable dense subset. The case where the space is empty is special, and trivial.-/ have A : (univ : set Ξ±) = βˆ… β†’ βˆƒ(s : set Ξ±), countable s ∧ closure s = (univ : set Ξ±) := assume H, βŸ¨βˆ…, ⟨by simp, by simp; exact H.symm⟩⟩, have B : (univ : set Ξ±) β‰  βˆ… β†’ βˆƒ(s : set Ξ±), countable s ∧ closure s = (univ : set Ξ±) := begin /-When the space is not empty, we take a point `x` in the space, and then a countable set `T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set `t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union of countable sets, and dense in the space by construction.-/ assume non_empty, rcases ne_empty_iff_exists_mem.1 non_empty with ⟨x, x_univ⟩, choose T a using show βˆ€ (r:ℝ), βˆƒ t βŠ† closed_ball x r, (countable (t : set Ξ±) ∧ closed_ball x r = closure t), from assume r, countable_closure_of_compact (proper_space.compact_ball _ _), let t := (⋃n:β„•, T (n : ℝ)), have T₁ : countable t := by finish [countable_Union], have Tβ‚‚ : closure t βŠ† univ := by simp, have T₃ : univ βŠ† closure t := begin intros y y_univ, rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩, have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large, have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish, have : y ∈ closure (T (n : ℝ)) := by rwa h' at h, show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (Ξ»(n:β„•), T (n:ℝ))), end, exact ⟨t, ⟨T₁, subset.antisymm Tβ‚‚ Tβ‚ƒβŸ©βŸ© end, haveI : separable_space Ξ± := ⟨by_cases A B⟩, apply second_countable_of_separable_metric_space, end end proper_space lemma lebesgue_number_lemma_of_metric {s : set Ξ±} {ΞΉ} {c : ΞΉ β†’ set Ξ±} (hs : compact s) (hc₁ : βˆ€ i, is_open (c i)) (hcβ‚‚ : s βŠ† ⋃ i, c i) : βˆƒ Ξ΄ > 0, βˆ€ x ∈ s, βˆƒ i, ball x Ξ΄ βŠ† c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hcβ‚‚, ⟨δ, Ξ΄0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, Ξ΄0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hΞ΄ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set Ξ±} {c : set (set Ξ±)} (hs : compact s) (hc₁ : βˆ€ t ∈ c, is_open t) (hcβ‚‚ : s βŠ† ⋃₀ c) : βˆƒ Ξ΄ > 0, βˆ€ x ∈ s, βˆƒ t ∈ c, ball x Ξ΄ βŠ† t := by rw sUnion_eq_Union at hcβ‚‚; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hcβ‚‚
a20e442d242c4ee97a44d75253393fb827789604
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Std/Control.lean
c6ef78cc4da32806040223ad12485bdde09be2a9
[ "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
190
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Control.Nondet
9dbae8e501b63f514069ad8fc0222eace91d342a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Util/InstantiateLevelParams.lean
17b775321d109778245cacd6e4e73e3b1364c993
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,310
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ReplaceExpr namespace Lean.Expr /-- Instantiate level parameters -/ @[specialize] def instantiateLevelParamsCore (s : Name β†’ Option Level) (e : Expr) : Expr := e.replace replaceFn where @[specialize] replaceFn (e : Expr) : Option Expr := if !e.hasLevelParam then e else match e with | const _ us => e.updateConst! (us.map fun u => u.substParams s) | sort u => e.updateSort! (u.substParams s) | _ => none private def getParamSubst : List Name β†’ List Level β†’ Name β†’ Option Level | p::ps, u::us, p' => if p == p' then some u else getParamSubst ps us p' | _, _, _ => none /-- Instantiate universe level parameters names `paramNames` with `lvls` in `e`. If the two lists have different length, the smallest one is used. -/ def instantiateLevelParams (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr := if paramNames.isEmpty || lvls.isEmpty then e else instantiateLevelParamsCore (getParamSubst paramNames lvls) e /-- Instantiate universe level parameters names `paramNames` with `lvls` in `e`. If the two lists have different length, the smallest one is used. (Does not preserve expression sharing.) -/ def instantiateLevelParamsNoCache (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr := if paramNames.isEmpty || lvls.isEmpty then e else e.replaceNoCache (instantiateLevelParamsCore.replaceFn (getParamSubst paramNames lvls)) private partial def getParamSubstArray (ps : Array Name) (us : Array Level) (p' : Name) (i : Nat) : Option Level := if h : i < ps.size then let p := ps.get ⟨i, h⟩ if h : i < us.size then let u := us.get ⟨i, h⟩ if p == p' then some u else getParamSubstArray ps us p' (i+1) else none else none /-- Instantiate universe level parameters names `paramNames` with `lvls` in `e`. If the two arrays have different length, the smallest one is used. -/ def instantiateLevelParamsArray (e : Expr) (paramNames : Array Name) (lvls : Array Level) : Expr := if paramNames.isEmpty || lvls.isEmpty then e else e.instantiateLevelParamsCore fun p => getParamSubstArray paramNames lvls p 0
6bd1caf4ef6bd8a8e6178d23f8d27e83cd1ba611
843cffbd2a25fd01677509247a92e9e8b33bec48
/complex.lean
da4e495813f63fcb236a1401bd6e4f30105067bb
[]
no_license
AlexandruBosinta/MyLeanPlayground
9a78eba4a5c7a2b82edf84e1794a966f53f06c4f
5dc50a590d784bfc27e7fb37b6361a6dcc1b2790
refs/heads/master
1,586,230,010,351
1,542,487,422,000
1,542,487,422,000
158,016,626
0
0
null
null
null
null
UTF-8
Lean
false
false
1,179
lean
import data.real.basic import tactic.ring structure complex : Type := (re : ℝ) (im : ℝ) notation `β„‚` := complex def z : β„‚ := ⟨5,6⟩ namespace complex theorem ext (z w : β„‚) : z.re = w.re ∧ z.im = w.im β†’ z = w := begin cases z, cases w, intros, simp * at * end instance : has_coe ℝ β„‚ := ⟨λ x, {re := x, im := 0}⟩ def I : β„‚ := ⟨0, 1⟩ def add : β„‚ β†’ β„‚ β†’ β„‚ := Ξ» z w, {re := z.re + w.re, im := z.im + w.im} instance : has_add β„‚ := ⟨complex.add⟩ @[simp] theorem add_re : βˆ€ z w : β„‚, (z + w).re = z.re + w.re := Ξ» z w, rfl @[simp] theorem add_im : βˆ€ z w : β„‚, (z + w).im = z.im + w.im := Ξ» z w, rfl theorem add_comm : βˆ€ z w : β„‚, z + w = w + z := begin intros, apply ext, split; simp end theorem add_assoc : βˆ€ a b c : β„‚, a + (b + c) = (a + b) + c := begin intros, apply ext, split; simp end def neg : β„‚ β†’ β„‚ := Ξ» z, ⟨-z.re,z.im⟩ instance : has_neg β„‚ := ⟨complex.neg⟩ @[simp] theorem neg_re (z : β„‚) : (-z).re = -z.re := _ @[simp] theorem neg_im (z : β„‚) : (-z).im = -z.im := rfl end complex
3d3c698aea87c3b7e00fb29e31d1091a4fa3a186
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/ideal/basic.lean
e4083a18aa8a1953e5c66fd60a48d36c04aadf57
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
22,388
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.zorn import order.atoms import order.compactly_generated import tactic.abel import data.nat.choose.sum import linear_algebra.finsupp /-! # Ideals over a ring This file defines `ideal R`, the type of ideals over a commutative ring `R`. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `β€’` is interpreted as `*`. ## TODO Support one-sided ideals, and ideals over non-commutative rings. -/ universes u v w variables {Ξ± : Type u} {Ξ² : Type v} open set function open_locale classical big_operators pointwise /-- A (left) ideal in a semiring `R` is an additive submonoid `s` such that `a * b ∈ s` whenever `b ∈ s`. If `R` is a ring, then `s` is an additive subgroup. -/ @[reducible] def ideal (R : Type u) [semiring R] := submodule R R section semiring namespace ideal variables [semiring Ξ±] (I : ideal Ξ±) {a b : Ξ±} protected lemma zero_mem : (0 : Ξ±) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I β†’ b ∈ I β†’ a + b ∈ I := I.add_mem variables (a) lemma mul_mem_left : b ∈ I β†’ a * b ∈ I := I.smul_mem a variables {a} @[ext] lemma ext {I J : ideal Ξ±} (h : βˆ€ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : Ξ±) (hx : x ∈ I) (h : y * x = 1) : I = ⊀ := eq_top_iff.2 $ Ξ» z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left _ hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊀ := let ⟨y, hy⟩ := h.exists_left_inv in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊀ ↔ (1:Ξ±) ∈ I := ⟨by rintro rfl; trivial, Ξ» h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I β‰  ⊀ ↔ (1:Ξ±) βˆ‰ I := not_congr I.eq_top_iff_one @[simp] theorem unit_mul_mem_iff_mem {x y : Ξ±} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, Ξ» h, I.mul_mem_left y h⟩, obtain ⟨y', hy'⟩ := hy.exists_left_inv, have := I.mul_mem_left y' h, rwa [← mul_assoc, hy', one_mul] at this, end /-- The ideal generated by a subset of a ring -/ def span (s : set Ξ±) : ideal Ξ± := submodule.span Ξ± s @[simp] lemma submodule_span_eq {s : set Ξ±} : submodule.span Ξ± s = ideal.span s := rfl lemma subset_span {s : set Ξ±} : s βŠ† span s := submodule.subset_span lemma span_le {s : set Ξ±} {I} : span s ≀ I ↔ s βŠ† I := submodule.span_le lemma span_mono {s t : set Ξ±} : s βŠ† t β†’ span s ≀ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set Ξ±) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span ({1} : set Ξ±) = ⊀ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set Ξ±} {x y} : x ∈ span (insert y s) ↔ βˆƒ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_singleton' {x y : Ξ±} : x ∈ span ({y} : set Ξ±) ↔ βˆƒ a, a * y = x := submodule.mem_span_singleton lemma span_insert (x) (s : set Ξ±) : span (insert x s) = span ({x} : set Ξ±) βŠ” span s := submodule.span_insert x s lemma span_eq_bot {s : set Ξ±} : span s = βŠ₯ ↔ βˆ€ x ∈ s, (x:Ξ±) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set Ξ±) = βŠ₯ ↔ x = 0 := submodule.span_singleton_eq_bot @[simp] lemma span_zero : span (0 : set Ξ±) = βŠ₯ := by rw [←set.singleton_zero, span_singleton_eq_bot] @[simp] lemma span_one : span (1 : set Ξ±) = ⊀ := by rw [←set.singleton_one, span_singleton_one] lemma span_eq_top_iff_finite (s : set Ξ±) : span s = ⊀ ↔ βˆƒ s' : finset Ξ±, ↑s' βŠ† s ∧ span (s' : set Ξ±) = ⊀ := begin simp_rw eq_top_iff_one, exact ⟨submodule.mem_span_finite_of_mem_span, Ξ» ⟨s', h₁, hβ‚‚βŸ©, span_mono h₁ hβ‚‚βŸ© end /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : Ξ± β†’ Ξ± β†’ Prop) : ideal Ξ± := submodule.span Ξ± { x | βˆƒ (a b) (h : r a b), x + b = a } /-- An ideal `P` of a ring `R` is prime if `P β‰  R` and `xy ∈ P β†’ x ∈ P ∨ y ∈ P` -/ class is_prime (I : ideal Ξ±) : Prop := (ne_top' : I β‰  ⊀) (mem_or_mem' : βˆ€ {x y : Ξ±}, x * y ∈ I β†’ x ∈ I ∨ y ∈ I) theorem is_prime_iff {I : ideal Ξ±} : is_prime I ↔ I β‰  ⊀ ∧ βˆ€ {x y : Ξ±}, x * y ∈ I β†’ x ∈ I ∨ y ∈ I := ⟨λ h, ⟨h.1, h.2⟩, Ξ» h, ⟨h.1, h.2⟩⟩ theorem is_prime.ne_top {I : ideal Ξ±} (hI : I.is_prime) : I β‰  ⊀ := hI.1 theorem is_prime.mem_or_mem {I : ideal Ξ±} (hI : I.is_prime) : βˆ€ {x y : Ξ±}, x * y ∈ I β†’ x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal Ξ±} (hI : I.is_prime) {x y : Ξ±} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.mem_or_mem (h.symm β–Έ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal Ξ±} (hI : I.is_prime) {r : Ξ±} (n : β„•) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { rw pow_zero at H, exact (mt (eq_top_iff_one _).2 hI.1).elim H }, { rw pow_succ at H, exact or.cases_on (hI.mem_or_mem H) id ih } end lemma not_is_prime_iff {I : ideal Ξ±} : Β¬ I.is_prime ↔ I = ⊀ ∨ βˆƒ (x βˆ‰ I) (y βˆ‰ I), x * y ∈ I := begin simp_rw [ideal.is_prime_iff, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, Ξ» ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal Ξ±} (h : I β‰  ⊀) : (0:Ξ±) β‰  1 := Ξ» hz, I.ne_top_iff_one.1 h $ hz β–Έ I.zero_mem lemma bot_prime {R : Type*} [ring R] [is_domain R] : (βŠ₯ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), Ξ» x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ class is_maximal (I : ideal Ξ±) : Prop := (out : is_coatom I) theorem is_maximal_def {I : ideal Ξ±} : I.is_maximal ↔ is_coatom I := ⟨λ h, h.1, Ξ» h, ⟨h⟩⟩ theorem is_maximal.ne_top {I : ideal Ξ±} (h : I.is_maximal) : I β‰  ⊀ := (is_maximal_def.1 h).1 theorem is_maximal_iff {I : ideal Ξ±} : I.is_maximal ↔ (1:Ξ±) βˆ‰ I ∧ βˆ€ (J : ideal Ξ±) x, I ≀ J β†’ x βˆ‰ I β†’ x ∈ J β†’ (1:Ξ±) ∈ J := is_maximal_def.trans $ and_congr I.ne_top_iff_one $ forall_congr $ Ξ» J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hxβ‚‚, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hxβ‚‚, hxβ‚βŸ©βŸ©, Ξ» H ⟨h₁, hβ‚‚βŸ©, let ⟨x, xJ, xI⟩ := not_subset.1 hβ‚‚ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal Ξ±} (hI : I.is_maximal) (hJ : J β‰  ⊀) (IJ : I ≀ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, Ξ» h, hJ (hI.1.2 _ h)⟩ instance : is_coatomic (ideal Ξ±) := begin apply complete_lattice.coatomic_of_top_compact, rw ←span_singleton_one, exact submodule.singleton_span_is_compact_element 1, end /-- **Krull's theorem**: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal Ξ±) (hI : I β‰  ⊀) : βˆƒ M : ideal Ξ±, M.is_maximal ∧ I ≀ M := let ⟨m, hm⟩ := (eq_top_or_exists_le_coatom I).resolve_left hI in ⟨m, ⟨⟨hm.1⟩, hm.2⟩⟩ variables (Ξ±) /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial Ξ±] : βˆƒ M : ideal Ξ±, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (βŠ₯ : ideal Ξ±) bot_ne_top in ⟨I, hI⟩ variables {Ξ±} instance [nontrivial Ξ±] : nontrivial (ideal Ξ±) := begin rcases @exists_maximal Ξ± _ _ with ⟨M, hM, _⟩, exact nontrivial_of_ne M ⊀ hM end /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [comm_semiring R] {P : ideal R} (hmax : βˆ€ m : ideal R, P < m β†’ Β¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊀ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end theorem mem_span_pair {x y z : Ξ±} : z ∈ span ({x, y} : set Ξ±) ↔ βˆƒ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] theorem is_maximal.exists_inv {I : ideal Ξ±} (hI : I.is_maximal) {x} (hx : x βˆ‰ I) : βˆƒ y, βˆƒ i ∈ I, y * x + i = 1 := begin cases is_maximal_iff.1 hI with H₁ Hβ‚‚, rcases mem_span_insert.1 (Hβ‚‚ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, z, hz, hy⟩, refine ⟨y, z, _, hy.symm⟩, rwa ← span_eq I, end section lattice variables {R : Type u} [semiring R] lemma mem_sup_left {S T : ideal R} : βˆ€ {x : R}, x ∈ S β†’ x ∈ S βŠ” T := show S ≀ S βŠ” T, from le_sup_left lemma mem_sup_right {S T : ideal R} : βˆ€ {x : R}, x ∈ T β†’ x ∈ S βŠ” T := show T ≀ S βŠ” T, from le_sup_right lemma mem_supr_of_mem {ΞΉ : Sort*} {S : ΞΉ β†’ ideal R} (i : ΞΉ) : βˆ€ {x : R}, x ∈ S i β†’ x ∈ supr S := show S i ≀ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : βˆ€ {x : R}, x ∈ s β†’ x ∈ Sup S := show s ≀ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ βˆ€ ⦃I⦄, I ∈ s β†’ x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, Ξ» H I ⟨J, hij⟩, hij β–Έ Ξ» S ⟨hj, hS⟩, hS β–Έ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I βŠ“ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ΞΉ : Sort*} {I : ΞΉ β†’ ideal R} {x : R} : x ∈ infi I ↔ βˆ€ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (βŠ₯ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice section pi variables (ΞΉ : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ΞΉ β†’ Ξ±) := { carrier := { x | βˆ€ i, x i ∈ I }, zero_mem' := Ξ» i, I.zero_mem, add_mem' := Ξ» a b ha hb i, I.add_mem (ha i) (hb i), smul_mem' := Ξ» a b hb i, I.mul_mem_left (a i) (hb i) } lemma mem_pi (x : ΞΉ β†’ Ξ±) : x ∈ I.pi ΞΉ ↔ βˆ€ i, x i ∈ I := iff.rfl end pi end ideal end semiring section comm_semiring variables {a b : Ξ±} -- A separate namespace definition is needed because the variables were historically in a different -- order. namespace ideal variables [comm_semiring Ξ±] (I : ideal Ξ±) @[simp] theorem mul_unit_mem_iff_mem {x y : Ξ±} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x β–Έ unit_mul_mem_iff_mem I hy lemma mem_span_singleton {x y : Ξ±} : x ∈ span ({y} : set Ξ±) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ Ξ» _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : Ξ±} : span ({x} : set Ξ±) ≀ span ({y} : set Ξ±) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {Ξ± : Type u} [comm_ring Ξ±] [is_domain Ξ±] {x y : Ξ±} : span ({x} : set Ξ±) = span ({y} : set Ξ±) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_singleton_mul_right_unit {a : Ξ±} (h2 : is_unit a) (x : Ξ±) : span ({x * a} : set Ξ±) = span {x} := begin apply le_antisymm, { rw span_singleton_le_span_singleton, use a}, { rw span_singleton_le_span_singleton, rw is_unit.mul_right_dvd h2} end lemma span_singleton_mul_left_unit {a : Ξ±} (h2 : is_unit a) (x : Ξ±) : span ({a * x} : set Ξ±) = span {x} := by rw [mul_comm, span_singleton_mul_right_unit h2] lemma span_singleton_eq_top {x} : span ({x} : set Ξ±) = ⊀ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff] theorem span_singleton_prime {p : Ξ±} (hp : p β‰  0) : is_prime (span ({p} : set Ξ±)) ↔ prime p := by simp [is_prime_iff, prime, span_singleton_eq_top, hp, mem_span_singleton] theorem is_maximal.is_prime {I : ideal Ξ±} (H : I.is_maximal) : I.is_prime := ⟨H.1.1, Ξ» x y hxy, or_iff_not_imp_left.2 $ Ξ» hx, begin let J : ideal Ξ± := submodule.span Ξ± (insert x ↑I), have IJ : I ≀ J := (set.subset.trans (subset_insert _ _) subset_span), have xJ : x ∈ J := ideal.subset_span (set.mem_insert x I), cases is_maximal_iff.1 H with _ oJ, specialize oJ J x IJ hx xJ, rcases submodule.mem_span_insert.mp oJ with ⟨a, b, h, oe⟩, obtain (F : y * 1 = y * (a β€’ x + b)) := congr_arg (Ξ» g : Ξ±, y * g) oe, rw [← mul_one y, F, mul_add, mul_comm, smul_eq_mul, mul_assoc], refine submodule.add_mem I (I.mul_mem_left a hxy) (submodule.smul_mem I y _), rwa submodule.span_eq at h, end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal Ξ±) : βˆ€ [H : I.is_maximal], I.is_prime := is_maximal.is_prime lemma span_singleton_lt_span_singleton [comm_ring Ξ²] [is_domain Ξ²] {x y : Ξ²} : span ({x} : set Ξ²) < span ({y} : set Ξ²) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [comm_ring Ξ²] [is_domain Ξ²] (b₁ bβ‚‚ : Ξ²) (h₁ : b₁ β‰  0) (hβ‚‚ : Β¬ is_unit bβ‚‚) : span ({b₁ * bβ‚‚} : set Ξ²) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨bβ‚‚, rfl⟩) $ Ξ» h, hβ‚‚ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] variables (b) lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a β–Έ I.mul_mem_left b h variables {b} lemma pow_mem_of_mem (ha : a ∈ I) (n : β„•) (hn : 0 < n) : a ^ n ∈ I := nat.cases_on n (not.elim dec_trivial) (Ξ» m hm, (pow_succ a m).symm β–Έ I.mul_mem_right (a^m) ha) hn theorem is_prime.mul_mem_iff_mem_or_mem {I : ideal Ξ±} (hI : I.is_prime) : βˆ€ {x y : Ξ±}, x * y ∈ I ↔ x ∈ I ∨ y ∈ I := Ξ» x y, ⟨hI.mem_or_mem, by { rintro (h | h), exacts [I.mul_mem_right y h, I.mul_mem_left x h] }⟩ theorem is_prime.pow_mem_iff_mem {I : ideal Ξ±} (hI : I.is_prime) {r : Ξ±} (n : β„•) (hn : 0 < n) : r ^ n ∈ I ↔ r ∈ I := ⟨hI.mem_of_pow_mem n, (Ξ» hr, I.pow_mem_of_mem hr n hn)⟩ theorem pow_multiset_sum_mem_span_pow (s : multiset Ξ±) (n : β„•) : s.sum ^ (s.card * n + 1) ∈ span ((s.map (Ξ» x, x ^ (n + 1))).to_finset : set Ξ±) := begin induction s using multiset.induction_on with a s hs, { simp }, simp only [finset.coe_insert, multiset.map_cons, multiset.to_finset_cons, multiset.sum_cons, multiset.card_cons, add_pow], refine submodule.sum_mem _ _, intros c hc, rw mem_span_insert, by_cases h : n+1 ≀ c, { refine ⟨a ^ (c - (n + 1)) * s.sum ^ ((s.card + 1) * n + 1 - c) * (((s.card + 1) * n + 1).choose c), 0, submodule.zero_mem _, _⟩, rw mul_comm _ (a ^ (n + 1)), simp_rw ← mul_assoc, rw [← pow_add, add_zero, add_tsub_cancel_of_le h], }, { use 0, simp_rw [zero_mul, zero_add], refine ⟨_,_,rfl⟩, replace h : c ≀ n := nat.lt_succ_iff.mp (not_le.mp h), have : (s.card + 1) * n + 1 - c = s.card * n + 1 + (n - c), { rw [add_mul, one_mul, add_assoc, add_comm n 1, ← add_assoc, add_tsub_assoc_of_le h] }, rw [this, pow_add], simp_rw [mul_assoc, mul_comm (s.sum ^ (s.card * n + 1)), ← mul_assoc], exact mul_mem_left _ _ hs } end theorem sum_pow_mem_span_pow {ΞΉ} (s : finset ΞΉ) (f : ΞΉ β†’ Ξ±) (n : β„•) : (βˆ‘ i in s, f i) ^ (s.card * n + 1) ∈ span ((Ξ» i, f i ^ (n + 1)) '' s) := begin convert pow_multiset_sum_mem_span_pow (s.1.map f) n, { rw multiset.card_map, refl }, rw [multiset.map_map, multiset.to_finset_map, finset.val_to_finset, finset.coe_image] end theorem span_pow_eq_top (s : set Ξ±) (hs : span s = ⊀) (n : β„•) : span ((Ξ» x, x ^ n) '' s) = ⊀ := begin rw eq_top_iff_one, cases n, { obtain rfl | ⟨x, hx⟩ := eq_empty_or_nonempty s, { rw [set.image_empty, hs], trivial }, { exact subset_span ⟨_, hx, pow_zero _⟩ } }, rw [eq_top_iff_one, span, finsupp.mem_span_iff_total] at hs, rcases hs with ⟨f, hf⟩, change f.support.sum (Ξ» a, f a * a) = 1 at hf, have := sum_pow_mem_span_pow f.support (Ξ» a, f a * a) n, rw [hf, one_pow] at this, refine (span_le).mpr _ this, rintros _ hx, simp_rw [finset.mem_coe, set.mem_image] at hx, rcases hx with ⟨x, hx, rfl⟩, have : span ({x ^ (n + 1)} : set Ξ±) ≀ span ((Ξ» (x : Ξ±), x ^ (n + 1)) '' s), { rw [span_le, set.singleton_subset_iff], exact subset_span ⟨x, x.prop, rfl⟩ }, refine this _, rw [mul_pow, mem_span_singleton], exact ⟨f x ^ (n + 1), mul_comm _ _⟩ end end ideal end comm_semiring section ring namespace ideal variables [ring Ξ±] (I : ideal Ξ±) {a b : Ξ±} lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I β†’ (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I β†’ (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I β†’ b ∈ I β†’ a - b ∈ I := I.sub_mem lemma mem_span_insert' {s : set Ξ±} {x y} : x ∈ span (insert y s) ↔ βˆƒa, x + a * y ∈ span s := submodule.mem_span_insert' end ideal end ring section division_ring variables {K : Type u} [division_ring K] (I : ideal K) namespace ideal /-- All ideals in a division ring are trivial. -/ lemma eq_bot_or_top : I = βŠ₯ ∨ I = ⊀ := begin rw or_iff_not_imp_right, change _ β‰  _ β†’ _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using I.mul_mem_left r⁻¹ hr, end lemma eq_bot_of_prime [h : I.is_prime] : I = βŠ₯ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal : is_maximal (βŠ₯ : ideal K) := ⟨⟨λ h, absurd ((eq_top_iff_one (⊀ : ideal K)).mp rfl) (by rw ← h; simp), Ξ» I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩⟩ end ideal end division_ring section comm_ring namespace ideal theorem mul_sub_mul_mem {R : Type*} [comm_ring R] (I : ideal R) {a b c d : R} (h1 : a - b ∈ I) (h2 : c - d ∈ I) : a * c - b * d ∈ I := begin rw (show a * c - b * d = (a - b) * c + b * (c - d), by {rw [sub_mul, mul_sub], abel}), exact I.add_mem (I.mul_mem_right _ h1) (I.mul_mem_left _ h2), end end ideal end comm_ring namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : Β¬ is_field R := Ξ» ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : Β¬ is_field R) : βˆƒ x β‰  (0 : R), Β¬ is_unit x := begin have : Β¬ _ := Ξ» h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊒ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : Β¬ is_field R ↔ βˆƒ I : ideal R, βŠ₯ < I ∧ I < ⊀ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := set_like.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (I.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : Β¬ is_field R ↔ βˆƒ p : ideal R, p β‰  βŠ₯ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, Ξ» ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ /-- When a ring is not a field, the maximal ideals are nontrivial. -/ lemma ne_bot_of_is_maximal_of_not_is_field [nontrivial R] {M : ideal R} (max : M.is_maximal) (not_field : Β¬ is_field R) : M β‰  βŠ₯ := begin rintros h, rw h at max, rcases max with ⟨⟨h1, h2⟩⟩, obtain ⟨I, hIbot, hItop⟩ := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.mp not_field, exact ne_of_lt hItop (h2 I hIbot), end end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : Β¬ is_field R) : βŠ₯ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, { simp }, intro mle, apply @irrefl _ (<) _ (⊀ : ideal R), have : M = βŠ₯ := eq_bot_iff.mpr mle, rw this at *, rwa hm.1.2 I Ibot at Itop, end end ideal variables {a b : Ξ±} /-- The set of non-invertible elements of a monoid. -/ def nonunits (Ξ± : Type u) [monoid Ξ±] : set Ξ± := { a | Β¬is_unit a } @[simp] theorem mem_nonunits_iff [monoid Ξ±] : a ∈ nonunits Ξ± ↔ Β¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid Ξ±] : b ∈ nonunits Ξ± β†’ a * b ∈ nonunits Ξ± := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid Ξ±] : a ∈ nonunits Ξ± β†’ a * b ∈ nonunits Ξ± := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring Ξ±] : 0 ∈ nonunits Ξ± ↔ (0:Ξ±) β‰  1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid Ξ±] : (1:Ξ±) βˆ‰ nonunits Ξ± := not_not_intro is_unit_one theorem coe_subset_nonunits [semiring Ξ±] {I : ideal Ξ±} (h : I β‰  ⊀) : (I : set Ξ±) βŠ† nonunits Ξ± := Ξ» x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_semiring Ξ±] (h : a ∈ nonunits Ξ±) : βˆƒ I : ideal Ξ±, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set Ξ±) β‰  ⊀, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end
3d0f32bba7474058a2444e9f2ce53a0d7da96504
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/quotient_group.lean
9946637bc541546be0cb8982964e2f576d911845
[ "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
18,170
lean
/- Copyright (c) 2018 Kevin Buzzard, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot This file is to a certain extent based on `quotient_module.lean` by Johannes HΓΆlzl. -/ import group_theory.coset import data.setoid.basic /-! # Quotients of groups by normal subgroups This files develops the basic theory of quotients of groups by normal subgroups. In particular it proves Noether's first and second isomorphism theorems. ## Main definitions * `mk'`: the canonical group homomorphism `G β†’* G/N` given a normal subgroup `N` of `G`. * `lift Ο†`: the group homomorphism `G/N β†’* H` given a group homomorphism `Ο† : G β†’* H` such that `N βŠ† ker Ο†`. * `map f`: the group homomorphism `G/N β†’* H/M` given a group homomorphism `f : G β†’* H` such that `N βŠ† f⁻¹(M)`. ## Main statements * `quotient_ker_equiv_range`: Noether's first isomorphism theorem, an explicit isomorphism `G/ker Ο† β†’ range Ο†` for every group homomorphism `Ο† : G β†’* H`. * `quotient_inf_equiv_prod_normal_quotient`: Noether's second isomorphism theorem, an explicit isomorphism between `H/(H ∩ N)` and `(HN)/N` given a subgroup `H` and a normal subgroup `N` of a group `G`. * `quotient_group.quotient_quotient_equiv_quotient`: Noether's third isomorphism theorem, the canonical isomorphism between `(G / M) / (M / N)` and `G / N`, where `N ≀ M`. ## Tags isomorphism theorems, quotient groups -/ universes u v namespace quotient_group variables {G : Type u} [group G] (N : subgroup G) [nN : N.normal] {H : Type v} [group H] include nN -- Define the `div_inv_monoid` before the `group` structure, -- to make sure we have `inv` fully defined before we show `mul_left_inv`. -- TODO: is there a non-invasive way of defining this in one declaration? @[to_additive quotient_add_group.div_inv_monoid] instance : div_inv_monoid (quotient N) := { one := (1 : G), mul := quotient.mapβ‚‚' (*) (Ξ» a₁ b₁ hab₁ aβ‚‚ bβ‚‚ habβ‚‚, ((N.mul_mem_cancel_right (N.inv_mem habβ‚‚)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ bβ‚‚, ← mul_assoc bβ‚‚, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact nN.conj_mem _ hab₁ _))), mul_assoc := Ξ» a b c, quotient.induction_on₃' a b c (Ξ» a b c, congr_arg mk (mul_assoc a b c)), one_mul := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (one_mul a)), mul_one := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (mul_one a)), inv := Ξ» a, quotient.lift_on' a (Ξ» a, ((a⁻¹ : G) : quotient N)) (Ξ» a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact N.inv_mem (nN.mem_comm hab) end) } @[to_additive quotient_add_group.add_group] instance : group (quotient N) := { mul_left_inv := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (mul_left_inv a)), .. quotient.div_inv_monoid _ } /-- The group homomorphism from `G` to `G/N`. -/ @[to_additive quotient_add_group.mk' "The additive group homomorphism from `G` to `G/N`."] def mk' : G β†’* quotient N := monoid_hom.mk' (quotient_group.mk) (Ξ» _ _, rfl) @[simp, to_additive] lemma coe_mk' : (mk' N : G β†’ quotient N) = coe := rfl @[simp, to_additive] lemma mk'_apply (x : G) : mk' N x = x := rfl /-- Two `monoid_hom`s from a quotient group are equal if their compositions with `quotient_group.mk'` are equal. See note [partially-applied ext lemmas]. -/ @[ext, to_additive /-" Two `add_monoid_hom`s from an additive quotient group are equal if their compositions with `add_quotient_group.mk'` are equal. See note [partially-applied ext lemmas]. "-/] lemma monoid_hom_ext ⦃f g : quotient N β†’* H⦄ (h : f.comp (mk' N) = g.comp (mk' N)) : f = g := monoid_hom.ext $ Ξ» x, quotient_group.induction_on x $ (monoid_hom.congr_fun h : _) @[simp, to_additive quotient_add_group.eq_zero_iff] lemma eq_one_iff {N : subgroup G} [nN : N.normal] (x : G) : (x : quotient N) = 1 ↔ x ∈ N := begin refine quotient_group.eq.trans _, rw [mul_one, subgroup.inv_mem_iff], end @[simp, to_additive quotient_add_group.ker_mk] lemma ker_mk : monoid_hom.ker (quotient_group.mk' N : G β†’* quotient_group.quotient N) = N := subgroup.ext eq_one_iff @[to_additive quotient_add_group.eq_iff_sub_mem] lemma eq_iff_div_mem {N : subgroup G} [nN : N.normal] {x y : G} : (x : quotient N) = y ↔ x / y ∈ N := begin refine eq_comm.trans (quotient_group.eq.trans _), rw [nN.mem_comm_iff, div_eq_mul_inv] end -- for commutative groups we don't need normality assumption omit nN @[to_additive quotient_add_group.add_comm_group] instance {G : Type*} [comm_group G] (N : subgroup G) : comm_group (quotient N) := { mul_comm := Ξ» a b, quotient.induction_onβ‚‚' a b (Ξ» a b, congr_arg mk (mul_comm a b)), .. @quotient_group.quotient.group _ _ N N.normal_of_comm } include nN local notation ` Q ` := quotient N @[simp, to_additive quotient_add_group.coe_zero] lemma coe_one : ((1 : G) : Q) = 1 := rfl @[simp, to_additive quotient_add_group.coe_add] lemma coe_mul (a b : G) : ((a * b : G) : Q) = a * b := rfl @[simp, to_additive quotient_add_group.coe_neg] lemma coe_inv (a : G) : ((a⁻¹ : G) : Q) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : β„•) : ((a ^ n : G) : Q) = a ^ n := (mk' N).map_pow a n @[simp] lemma coe_zpow (a : G) (n : β„€) : ((a ^ n : G) : Q) = a ^ n := (mk' N).map_zpow a n /-- A group homomorphism `Ο† : G β†’* H` with `N βŠ† ker(Ο†)` descends (i.e. `lift`s) to a group homomorphism `G/N β†’* H`. -/ @[to_additive quotient_add_group.lift "An `add_group` homomorphism `Ο† : G β†’+ H` with `N βŠ† ker(Ο†)` descends (i.e. `lift`s) to a group homomorphism `G/N β†’* H`."] def lift (Ο† : G β†’* H) (HN : βˆ€x∈N, Ο† x = 1) : Q β†’* H := monoid_hom.mk' (Ξ» q : Q, q.lift_on' Ο† $ assume a b (hab : a⁻¹ * b ∈ N), (calc Ο† a = Ο† a * 1 : (mul_one _).symm ... = Ο† a * Ο† (a⁻¹ * b) : HN (a⁻¹ * b) hab β–Έ rfl ... = Ο† (a * (a⁻¹ * b)) : (Ο†.map_mul a (a⁻¹ * b)).symm ... = Ο† b : by rw mul_inv_cancel_left)) (Ξ» q r, quotient.induction_onβ‚‚' q r $ Ο†.map_mul) @[simp, to_additive quotient_add_group.lift_mk] lemma lift_mk {Ο† : G β†’* H} (HN : βˆ€x∈N, Ο† x = 1) (g : G) : lift N Ο† HN (g : Q) = Ο† g := rfl @[simp, to_additive quotient_add_group.lift_mk'] lemma lift_mk' {Ο† : G β†’* H} (HN : βˆ€x∈N, Ο† x = 1) (g : G) : lift N Ο† HN (mk g : Q) = Ο† g := rfl @[simp, to_additive quotient_add_group.lift_quot_mk] lemma lift_quot_mk {Ο† : G β†’* H} (HN : βˆ€x∈N, Ο† x = 1) (g : G) : lift N Ο† HN (quot.mk _ g : Q) = Ο† g := rfl /-- A group homomorphism `f : G β†’* H` induces a map `G/N β†’* H/M` if `N βŠ† f⁻¹(M)`. -/ @[to_additive quotient_add_group.map "An `add_group` homomorphism `f : G β†’+ H` induces a map `G/N β†’+ H/M` if `N βŠ† f⁻¹(M)`."] def map (M : subgroup H) [M.normal] (f : G β†’* H) (h : N ≀ M.comap f) : quotient N β†’* quotient M := begin refine quotient_group.lift N ((mk' M).comp f) _, assume x hx, refine quotient_group.eq.2 _, rw [mul_one, subgroup.inv_mem_iff], exact h hx, end @[simp, to_additive quotient_add_group.map_coe] lemma map_coe (M : subgroup H) [M.normal] (f : G β†’* H) (h : N ≀ M.comap f) (x : G) : map N M f h ↑x = ↑(f x) := lift_mk' _ _ x @[to_additive quotient_add_group.map_mk'] lemma map_mk' (M : subgroup H) [M.normal] (f : G β†’* H) (h : N ≀ M.comap f) (x : G) : map N M f h (mk' _ x) = ↑(f x) := quotient_group.lift_mk' _ _ x omit nN variables (Ο† : G β†’* H) open function monoid_hom /-- The induced map from the quotient by the kernel to the codomain. -/ @[to_additive quotient_add_group.ker_lift "The induced map from the quotient by the kernel to the codomain."] def ker_lift : quotient (ker Ο†) β†’* H := lift _ Ο† $ Ξ» g, Ο†.mem_ker.mp @[simp, to_additive quotient_add_group.ker_lift_mk] lemma ker_lift_mk (g : G) : (ker_lift Ο†) g = Ο† g := lift_mk _ _ _ @[simp, to_additive quotient_add_group.ker_lift_mk'] lemma ker_lift_mk' (g : G) : (ker_lift Ο†) (mk g) = Ο† g := lift_mk' _ _ _ @[to_additive quotient_add_group.injective_ker_lift] lemma ker_lift_injective : injective (ker_lift Ο†) := assume a b, quotient.induction_onβ‚‚' a b $ assume a b (h : Ο† a = Ο† b), quotient.sound' $ show a⁻¹ * b ∈ ker Ο†, by rw [mem_ker, Ο†.map_mul, ← h, Ο†.map_inv, inv_mul_self] -- Note that `ker Ο†` isn't definitionally `ker (Ο†.range_restrict)` -- so there is a bit of annoying code duplication here /-- The induced map from the quotient by the kernel to the range. -/ @[to_additive quotient_add_group.range_ker_lift "The induced map from the quotient by the kernel to the range."] def range_ker_lift : quotient (ker Ο†) β†’* Ο†.range := lift _ Ο†.range_restrict $ Ξ» g hg, (mem_ker _).mp $ by rwa range_restrict_ker @[to_additive quotient_add_group.range_ker_lift_injective] lemma range_ker_lift_injective : injective (range_ker_lift Ο†) := assume a b, quotient.induction_onβ‚‚' a b $ assume a b (h : Ο†.range_restrict a = Ο†.range_restrict b), quotient.sound' $ show a⁻¹ * b ∈ ker Ο†, by rw [←range_restrict_ker, mem_ker, Ο†.range_restrict.map_mul, ← h, Ο†.range_restrict.map_inv, inv_mul_self] @[to_additive quotient_add_group.range_ker_lift_surjective] lemma range_ker_lift_surjective : surjective (range_ker_lift Ο†) := begin rintro ⟨_, g, rfl⟩, use mk g, refl, end /-- **Noether's first isomorphism theorem** (a definition): the canonical isomorphism between `G/(ker Ο†)` to `range Ο†`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_range "The first isomorphism theorem (a definition): the canonical isomorphism between `G/(ker Ο†)` to `range Ο†`."] noncomputable def quotient_ker_equiv_range : (quotient (ker Ο†)) ≃* range Ο† := mul_equiv.of_bijective (range_ker_lift Ο†) ⟨range_ker_lift_injective Ο†, range_ker_lift_surjective Ο†βŸ© /-- The canonical isomorphism `G/(ker Ο†) ≃* H` induced by a homomorphism `Ο† : G β†’* H` with a right inverse `ψ : H β†’ G`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_right_inverse "The canonical isomorphism `G/(ker Ο†) ≃+ H` induced by a homomorphism `Ο† : G β†’+ H` with a right inverse `ψ : H β†’ G`.", simps] def quotient_ker_equiv_of_right_inverse (ψ : H β†’ G) (hΟ† : function.right_inverse ψ Ο†) : quotient (ker Ο†) ≃* H := { to_fun := ker_lift Ο†, inv_fun := mk ∘ ψ, left_inv := Ξ» x, ker_lift_injective Ο† (by rw [function.comp_app, ker_lift_mk', hΟ†]), right_inv := hΟ†, .. ker_lift Ο† } /-- The canonical isomorphism `G/βŠ₯ ≃* G`. -/ @[to_additive quotient_add_group.quotient_bot "The canonical isomorphism `G/βŠ₯ ≃+ G`.", simps] def quotient_bot : quotient (βŠ₯ : subgroup G) ≃* G := quotient_ker_equiv_of_right_inverse (monoid_hom.id G) id (Ξ» x, rfl) /-- The canonical isomorphism `G/(ker Ο†) ≃* H` induced by a surjection `Ο† : G β†’* H`. For a `computable` version, see `quotient_group.quotient_ker_equiv_of_right_inverse`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_surjective "The canonical isomorphism `G/(ker Ο†) ≃+ H` induced by a surjection `Ο† : G β†’+ H`. For a `computable` version, see `quotient_add_group.quotient_ker_equiv_of_right_inverse`."] noncomputable def quotient_ker_equiv_of_surjective (hΟ† : function.surjective Ο†) : quotient (ker Ο†) ≃* H := quotient_ker_equiv_of_right_inverse Ο† _ hΟ†.has_right_inverse.some_spec /-- If two normal subgroups `M` and `N` of `G` are the same, their quotient groups are isomorphic. -/ @[to_additive "If two normal subgroups `M` and `N` of `G` are the same, their quotient groups are isomorphic."] def equiv_quotient_of_eq {M N : subgroup G} [M.normal] [N.normal] (h : M = N) : quotient M ≃* quotient N := { to_fun := (lift M (mk' N) (Ξ» m hm, quotient_group.eq.mpr (by simpa [← h] using M.inv_mem hm))), inv_fun := (lift N (mk' M) (Ξ» n hn, quotient_group.eq.mpr (by simpa [← h] using N.inv_mem hn))), left_inv := Ξ» x, x.induction_on' $ by { intro, refl }, right_inv := Ξ» x, x.induction_on' $ by { intro, refl }, map_mul' := Ξ» x y, by rw map_mul } @[simp, to_additive] lemma equiv_quotient_of_eq_mk {M N : subgroup G} [M.normal] [N.normal] (h : M = N) (x : G) : quotient_group.equiv_quotient_of_eq h (quotient_group.mk x) = (quotient_group.mk x) := rfl /-- Let `A', A, B', B` be subgroups of `G`. If `A' ≀ B'` and `A ≀ B`, then there is a map `A / (A' βŠ“ A) β†’* B / (B' βŠ“ B)` induced by the inclusions. -/ @[to_additive "Let `A', A, B', B` be subgroups of `G`. If `A' ≀ B'` and `A ≀ B`, then there is a map `A / (A' βŠ“ A) β†’+ B / (B' βŠ“ B)` induced by the inclusions."] def quotient_map_subgroup_of_of_le {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' ≀ B') (h : A ≀ B) : quotient (A'.subgroup_of A) β†’* quotient (B'.subgroup_of B) := map _ _ (subgroup.inclusion h) $ by simp [subgroup.subgroup_of, subgroup.comap_comap]; exact subgroup.comap_mono h' @[simp, to_additive] lemma quotient_map_subgroup_of_of_le_coe {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' ≀ B') (h : A ≀ B) (x : A) : quotient_map_subgroup_of_of_le h' h x = ↑(subgroup.inclusion h x : B) := rfl /-- Let `A', A, B', B` be subgroups of `G`. If `A' = B'` and `A = B`, then the quotients `A / (A' βŠ“ A)` and `B / (B' βŠ“ B)` are isomorphic. Applying this equiv is nicer than rewriting along the equalities, since the type of `(A'.subgroup_of A : subgroup A)` depends on on `A`. -/ @[to_additive "Let `A', A, B', B` be subgroups of `G`. If `A' = B'` and `A = B`, then the quotients `A / (A' βŠ“ A)` and `B / (B' βŠ“ B)` are isomorphic. Applying this equiv is nicer than rewriting along the equalities, since the type of `(A'.add_subgroup_of A : add_subgroup A)` depends on on `A`. "] def equiv_quotient_subgroup_of_of_eq {A' A B' B : subgroup G} [hAN : (A'.subgroup_of A).normal] [hBN : (B'.subgroup_of B).normal] (h' : A' = B') (h : A = B) : quotient (A'.subgroup_of A) ≃* quotient (B'.subgroup_of B) := monoid_hom.to_mul_equiv (quotient_map_subgroup_of_of_le h'.le h.le) (quotient_map_subgroup_of_of_le h'.ge h.ge) (by { ext ⟨x, hx⟩, refl }) (by { ext ⟨x, hx⟩, refl }) section snd_isomorphism_thm open subgroup /-- **Noether's second isomorphism theorem**: given two subgroups `H` and `N` of a group `G`, where `N` is normal, defines an isomorphism between `H/(H ∩ N)` and `(HN)/N`. -/ @[to_additive "The second isomorphism theorem: given two subgroups `H` and `N` of a group `G`, where `N` is normal, defines an isomorphism between `H/(H ∩ N)` and `(H + N)/N`"] noncomputable def quotient_inf_equiv_prod_normal_quotient (H N : subgroup G) [N.normal] : quotient ((H βŠ“ N).comap H.subtype) ≃* quotient (N.comap (H βŠ” N).subtype) := /- Ο† is the natural homomorphism H β†’* (HN)/N. -/ let Ο† : H β†’* quotient (N.comap (H βŠ” N).subtype) := (mk' $ N.comap (H βŠ” N).subtype).comp (inclusion le_sup_left) in have Ο†_surjective : function.surjective Ο† := Ξ» x, x.induction_on' $ begin rintro ⟨y, (hy : y ∈ ↑(H βŠ” N))⟩, rw mul_normal H N at hy, rcases hy with ⟨h, n, hh, hn, rfl⟩, use [h, hh], apply quotient.eq.mpr, change h⁻¹ * (h * n) ∈ N, rwa [←mul_assoc, inv_mul_self, one_mul], end, (equiv_quotient_of_eq (by simp [comap_comap, ←comap_ker])).trans (quotient_ker_equiv_of_surjective Ο† Ο†_surjective) end snd_isomorphism_thm section third_iso_thm variables (M : subgroup G) [nM : M.normal] include nM nN @[to_additive quotient_add_group.map_normal] instance map_normal : (M.map (quotient_group.mk' N)).normal := { conj_mem := begin rintro _ ⟨x, hx, rfl⟩ y, refine induction_on' y (Ξ» y, ⟨y * x * y⁻¹, subgroup.normal.conj_mem nM x hx y, _⟩), simp only [mk'_apply, coe_mul, coe_inv] end } variables (h : N ≀ M) /-- The map from the third isomorphism theorem for groups: `(G / N) / (M / N) β†’ G / M`. -/ @[to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux "The map from the third isomorphism theorem for additive groups: `(A / N) / (M / N) β†’ A / M`."] def quotient_quotient_equiv_quotient_aux : quotient (M.map (mk' N)) β†’* quotient M := lift (M.map (mk' N)) (map N M (monoid_hom.id G) h) (by { rintro _ ⟨x, hx, rfl⟩, rw map_mk' N M _ _ x, exact (quotient_group.eq_one_iff _).mpr hx }) @[simp, to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux_coe] lemma quotient_quotient_equiv_quotient_aux_coe (x : quotient_group.quotient N) : quotient_quotient_equiv_quotient_aux N M h x = quotient_group.map N M (monoid_hom.id G) h x := quotient_group.lift_mk' _ _ x @[to_additive quotient_add_group.quotient_quotient_equiv_quotient_aux_coe_coe] lemma quotient_quotient_equiv_quotient_aux_coe_coe (x : G) : quotient_quotient_equiv_quotient_aux N M h (x : quotient_group.quotient N) = x := quotient_group.lift_mk' _ _ x /-- **Noether's third isomorphism theorem** for groups: `(G / N) / (M / N) ≃ G / M`. -/ @[to_additive quotient_add_group.quotient_quotient_equiv_quotient "**Noether's third isomorphism theorem** for additive groups: `(A / N) / (M / N) ≃ A / M`."] def quotient_quotient_equiv_quotient : quotient_group.quotient (M.map (quotient_group.mk' N)) ≃* quotient_group.quotient M := monoid_hom.to_mul_equiv (quotient_quotient_equiv_quotient_aux N M h) (quotient_group.map _ _ (quotient_group.mk' N) (subgroup.le_comap_map _ _)) (by { ext, simp }) (by { ext, simp }) end third_iso_thm section trivial @[to_additive] lemma subsingleton_quotient_top : subsingleton (quotient_group.quotient (⊀ : subgroup G)) := trunc.subsingleton /-- If the quotient by a subgroup gives a singleton then the subgroup is the whole group. -/ @[to_additive] lemma subgroup_eq_top_of_subsingleton (H : subgroup G) (h : subsingleton (quotient_group.quotient H)) : H = ⊀ := top_unique $ Ξ» x _, have this : 1⁻¹ * x ∈ H := quotient_group.eq.1 (subsingleton.elim _ _), by rwa [one_inv, one_mul] at this end trivial end quotient_group
760802a920364f4683196e992ec197bf48444057
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/limits/shapes/pullbacks.lean
5a7a481915bb3d812d82bde89093f4f671c05c2c
[ "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
29,167
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel, Bhavik Mehta -/ import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. ## References * [Stacks: Fibre products](https://stacks.math.columbia.edu/tag/001U) * [Stacks: Pushouts](https://stacks.math.columbia.edu/tag/0025) -/ noncomputable theory open category_theory namespace category_theory.limits universes v u uβ‚‚ local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback, defined as a special case of `wide_pullback_shape`. -/ abbreviation walking_cospan : Type v := wide_pullback_shape walking_pair /-- The left point of the walking cospan. -/ abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ abbreviation walking_cospan.one : walking_cospan := none /-- The type of objects for the diagram indexing a pushout, defined as a special case of `wide_pushout_shape`. -/ abbreviation walking_span : Type v := wide_pushout_shape walking_pair /-- The left point of the walking span. -/ abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ abbreviation walking_span.zero : walking_span := none namespace walking_cospan /-- The type of arrows for the diagram indexing a pullback. -/ abbreviation hom : walking_cospan β†’ walking_cospan β†’ Type v := wide_pullback_shape.hom /-- The left arrow of the walking cospan. -/ abbreviation hom.inl : left ⟢ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ abbreviation hom.inr : right ⟢ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ abbreviation hom.id (X : walking_cospan) : X ⟢ X := wide_pullback_shape.hom.id X instance (X Y : walking_cospan) : subsingleton (X ⟢ Y) := by tidy end walking_cospan namespace walking_span /-- The type of arrows for the diagram indexing a pushout. -/ abbreviation hom : walking_span β†’ walking_span β†’ Type v := wide_pushout_shape.hom /-- The left arrow of the walking span. -/ abbreviation hom.fst : zero ⟢ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ abbreviation hom.snd : zero ⟢ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ abbreviation hom.id (X : walking_span) : X ⟢ X := wide_pushout_shape.hom.id X instance (X Y : walking_span) : subsingleton (X ⟢ Y) := by tidy end walking_span open walking_span.hom walking_cospan.hom wide_pullback_shape.hom wide_pushout_shape.hom variables {C : Type u} [category.{v} C] /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) : walking_cospan β₯€ C := wide_pullback_shape.wide_cospan Z (Ξ» j, walking_pair.cases_on j X Y) (Ξ» j, walking_pair.cases_on j f g) /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) : walking_span β₯€ C := wide_pushout_shape.wide_span X (Ξ» j, walking_pair.cases_on j Y Z) (Ξ» j, walking_pair.cases_on j f g) @[simp] lemma cospan_left {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = πŸ™ _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = πŸ™ _ := rfl /-- Every diagram indexing an pullback is naturally isomorphic (actually, equal) to a `cospan` -/ @[simps {rhs_md := semireducible}] def diagram_iso_cospan (F : walking_cospan β₯€ C) : F β‰… cospan (F.map inl) (F.map inr) := nat_iso.of_components (Ξ» j, eq_to_iso (by tidy)) (by tidy) /-- Every diagram indexing a pushout is naturally isomorphic (actually, equal) to a `span` -/ @[simps {rhs_md := semireducible}] def diagram_iso_span (F : walking_span β₯€ C) : F β‰… span (F.map fst) (F.map snd) := nat_iso.of_components (Ξ» j, eq_to_iso (by tidy)) (by tidy) variables {X Y Z : C} /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟢ Z` and `g : Y ⟢ Z`.-/ abbreviation pullback_cone (f : X ⟢ Z) (g : Y ⟢ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟢ Z} {g : Y ⟢ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟢ X := t.Ο€.app walking_cospan.left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟢ Y := t.Ο€.app walking_cospan.right /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : pullback_cone f g) (lift : Ξ  (s : cone (cospan f g)), s.X ⟢ t.X) (fac_left : βˆ€ (s : pullback_cone f g), lift s ≫ t.fst = s.fst) (fac_right : βˆ€ (s : pullback_cone f g), lift s ≫ t.snd = s.snd) (uniq : βˆ€ (s : pullback_cone f g) (m : s.X ⟢ t.X) (w : βˆ€ j : walking_cospan, m ≫ t.Ο€.app j = s.Ο€.app j), m = lift s) : is_limit t := { lift := lift, fac' := Ξ» s j, option.cases_on j (by { rw [← s.w inl, ← t.w inl, ←category.assoc], congr, exact fac_left s, } ) (Ξ» j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_limit_aux' (t : pullback_cone f g) (create : Ξ  (s : pullback_cone f g), {l // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ βˆ€ {m}, m ≫ t.fst = s.fst β†’ m ≫ t.snd = s.snd β†’ m = l}) : limits.is_limit t := pullback_cone.is_limit_aux t (Ξ» s, (create s).1) (Ξ» s, (create s).2.1) (Ξ» s, (create s).2.2.1) (Ξ» s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟢ X` and `snd : W ⟢ Y` such that `fst ≫ f = snd ≫ g`. -/ @[simps] def mk {W : C} (fst : W ⟢ X) (snd : W ⟢ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, Ο€ := { app := Ξ» j, option.cases_on j (fst ≫ f) (Ξ» j', walking_pair.cases_on j' fst snd) } } @[simp] lemma mk_Ο€_app_left {W : C} (fst : W ⟢ X) (snd : W ⟢ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).Ο€.app walking_cospan.left = fst := rfl @[simp] lemma mk_Ο€_app_right {W : C} (fst : W ⟢ X) (snd : W ⟢ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).Ο€.app walking_cospan.right = snd := rfl @[simp] lemma mk_Ο€_app_one {W : C} (fst : W ⟢ X) (snd : W ⟢ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).Ο€.app walking_cospan.one = fst ≫ f := rfl @[simp] lemma mk_fst {W : C} (fst : W ⟢ X) (snd : W ⟢ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).fst = fst := rfl @[simp] lemma mk_snd {W : C} (fst : W ⟢ X) (snd : W ⟢ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).snd = snd := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := (t.w inl).trans (t.w inr).symm /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟢ t.X} (hβ‚€ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : βˆ€ (j : walking_cospan), k ≫ t.Ο€.app j = l ≫ t.Ο€.app j | (some walking_pair.left) := hβ‚€ | (some walking_pair.right) := h₁ | none := by rw [← t.w inl, reassoc_of hβ‚€] lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟢ t.X} (hβ‚€ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ hβ‚€ h₁ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟢ X` and `k : W ⟢ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟢ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟢ X) (k : W ⟢ Y) (w : h ≫ f = k ≫ g) : {l : W ⟢ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pullback_cone` constructed using `pullback_cone.mk` is a limit cone. -/ def is_limit.mk {W : C} {fst : W ⟢ X} {snd : W ⟢ Y} (eq : fst ≫ f = snd ≫ g) (lift : Ξ  (s : pullback_cone f g), s.X ⟢ W) (fac_left : βˆ€ (s : pullback_cone f g), lift s ≫ fst = s.fst) (fac_right : βˆ€ (s : pullback_cone f g), lift s ≫ snd = s.snd) (uniq : βˆ€ (s : pullback_cone f g) (m : s.X ⟢ W) (w_fst : m ≫ fst = s.fst) (w_snd : m ≫ snd = s.snd), m = lift s) : is_limit (mk fst snd eq) := is_limit_aux _ lift fac_left fac_right (Ξ» s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pullback square is a pullback square. -/ def flip_is_limit {W : C} {h : W ⟢ X} {k : W ⟢ Y} {comm : h ≫ f = k ≫ g} (t : is_limit (mk _ _ comm.symm)) : is_limit (mk _ _ comm) := is_limit_aux' _ $ Ξ» s, begin refine ⟨(is_limit.lift' t _ _ s.condition.symm).1, (is_limit.lift' t _ _ _).2.2, (is_limit.lift' t _ _ _).2.1, Ξ» m m₁ mβ‚‚, t.hom_ext _⟩, apply (mk k h _).equalizer_ext, { rwa (is_limit.lift' t _ _ _).2.1 }, { rwa (is_limit.lift' t _ _ _).2.2 }, end /-- The pullback cone `(πŸ™ X, πŸ™ X)` for the pair `(f, f)` is a limit if `f` is a mono. The converse is shown in `mono_of_pullback_is_id`. -/ def is_limit_mk_id_id (f : X ⟢ Y) [mono f] : is_limit (mk (πŸ™ X) (πŸ™ X) rfl : pullback_cone f f) := is_limit.mk _ (Ξ» s, s.fst) (Ξ» s, category.comp_id _) (Ξ» s, by rw [←cancel_mono f, category.comp_id, s.condition]) (Ξ» s m m₁ mβ‚‚, by simpa using m₁) /-- `f` is a mono if the pullback cone `(πŸ™ X, πŸ™ X)` is a limit for the pair `(f, f)`. The converse is given in `pullback_cone.is_id_of_mono`. -/ lemma mono_of_is_limit_mk_id_id (f : X ⟢ Y) (t : is_limit (mk (πŸ™ X) (πŸ™ X) rfl : pullback_cone f f)) : mono f := ⟨λ Z g h eq, by { rcases pullback_cone.is_limit.lift' t _ _ eq with ⟨_, rfl, rfl⟩, refl } ⟩ end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟢ Y` and `g : X ⟢ Z`.-/ abbreviation pushout_cocone (f : X ⟢ Y) (g : X ⟢ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟢ Y} {g : X ⟢ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟢ t.X := t.ΞΉ.app walking_span.left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟢ t.X := t.ΞΉ.app walking_span.right /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : pushout_cocone f g) (desc : Ξ  (s : pushout_cocone f g), t.X ⟢ s.X) (fac_left : βˆ€ (s : pushout_cocone f g), t.inl ≫ desc s = s.inl) (fac_right : βˆ€ (s : pushout_cocone f g), t.inr ≫ desc s = s.inr) (uniq : βˆ€ (s : pushout_cocone f g) (m : t.X ⟢ s.X) (w : βˆ€ j : walking_span, t.ΞΉ.app j ≫ m = s.ΞΉ.app j), m = desc s) : is_colimit t := { desc := desc, fac' := Ξ» s j, option.cases_on j (by { simp [← s.w fst, ← t.w fst, fac_left s] } ) (Ξ» j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_colimit_aux' (t : pushout_cocone f g) (create : Ξ  (s : pushout_cocone f g), {l // t.inl ≫ l = s.inl ∧ t.inr ≫ l = s.inr ∧ βˆ€ {m}, t.inl ≫ m = s.inl β†’ t.inr ≫ m = s.inr β†’ m = l}) : is_colimit t := is_colimit_aux t (Ξ» s, (create s).1) (Ξ» s, (create s).2.1) (Ξ» s, (create s).2.2.1) (Ξ» s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟢ W` and `inr : Z ⟢ W` such that `f ≫ inl = g β†  inr`. -/ @[simps] def mk {W : C} (inl : Y ⟢ W) (inr : Z ⟢ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ΞΉ := { app := Ξ» j, option.cases_on j (f ≫ inl) (Ξ» j', walking_pair.cases_on j' inl inr) } } @[simp] lemma mk_ΞΉ_app_left {W : C} (inl : Y ⟢ W) (inr : Z ⟢ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ΞΉ.app walking_span.left = inl := rfl @[simp] lemma mk_ΞΉ_app_right {W : C} (inl : Y ⟢ W) (inr : Z ⟢ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ΞΉ.app walking_span.right = inr := rfl @[simp] lemma mk_ΞΉ_app_zero {W : C} (inl : Y ⟢ W) (inr : Z ⟢ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ΞΉ.app walking_span.zero = f ≫ inl := rfl @[simp] lemma mk_inl {W : C} (inl : Y ⟢ W) (inr : Z ⟢ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inl = inl := rfl @[simp] lemma mk_inr {W : C} (inl : Y ⟢ W) (inr : Z ⟢ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inr = inr := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := (t.w fst).trans (t.w snd).symm /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟢ W} (hβ‚€ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : βˆ€ (j : walking_span), t.ΞΉ.app j ≫ k = t.ΞΉ.app j ≫ l | (some walking_pair.left) := hβ‚€ | (some walking_pair.right) := h₁ | none := by rw [← t.w fst, category.assoc, category.assoc, hβ‚€] lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟢ W} (hβ‚€ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ hβ‚€ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟢ W` and `k : Z ⟢ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟢ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟢ W) (k : Z ⟢ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟢ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pushout_cocone` constructed using `pushout_cocone.mk` is a colimit cocone. -/ def is_colimit.mk {W : C} {inl : Y ⟢ W} {inr : Z ⟢ W} (eq : f ≫ inl = g ≫ inr) (desc : Ξ  (s : pushout_cocone f g), W ⟢ s.X) (fac_left : βˆ€ (s : pushout_cocone f g), inl ≫ desc s = s.inl) (fac_right : βˆ€ (s : pushout_cocone f g), inr ≫ desc s = s.inr) (uniq : βˆ€ (s : pushout_cocone f g) (m : W ⟢ s.X) (w_inl : inl ≫ m = s.inl) (w_inr : inr ≫ m = s.inr), m = desc s) : is_colimit (mk inl inr eq) := is_colimit_aux _ desc fac_left fac_right (Ξ» s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pushout square is a pushout square. -/ def flip_is_colimit {W : C} {h : Y ⟢ W} {k : Z ⟢ W} {comm : f ≫ h = g ≫ k} (t : is_colimit (mk _ _ comm.symm)) : is_colimit (mk _ _ comm) := is_colimit_aux' _ $ Ξ» s, begin refine ⟨(is_colimit.desc' t _ _ s.condition.symm).1, (is_colimit.desc' t _ _ _).2.2, (is_colimit.desc' t _ _ _).2.1, Ξ» m m₁ mβ‚‚, t.hom_ext _⟩, apply (mk k h _).coequalizer_ext, { rwa (is_colimit.desc' t _ _ _).2.1 }, { rwa (is_colimit.desc' t _ _ _).2.2 }, end end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan β₯€ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ @[simps] def cone.of_pullback_cone {F : walking_cospan β₯€ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, Ο€ := t.Ο€ ≫ (diagram_iso_cospan F).inv } /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span β₯€ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ @[simps] def cocone.of_pushout_cocone {F : walking_span β₯€ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ΞΉ := (diagram_iso_span F).hom ≫ t.ΞΉ } /-- Given `F : walking_cospan β₯€ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ @[simps] def pullback_cone.of_cone {F : walking_cospan β₯€ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, Ο€ := t.Ο€ ≫ (diagram_iso_cospan F).hom } /-- Given `F : walking_span β₯€ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ @[simps] def pushout_cocone.of_cocone {F : walking_span β₯€ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ΞΉ := (diagram_iso_span F).inv ≫ t.ΞΉ } /-- `has_pullback f g` represents a particular choice of limiting cone for the pair of morphisms `f : X ⟢ Z` and `g : Y ⟢ Z`. -/ abbreviation has_pullback {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) := has_limit (cospan f g) /-- `has_pushout f g` represents a particular choice of colimiting cocone for the pair of morphisms `f : X ⟢ Y` and `g : X ⟢ Z`. -/ abbreviation has_pushout {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) := has_colimit (span f g) /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟢ Y) (g : X ⟢ Z) [has_pushout f g] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] : pullback f g ⟢ X := limit.Ο€ (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] : pullback f g ⟢ Y := limit.Ο€ (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] : Y ⟢ pushout f g := colimit.ΞΉ (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] : Z ⟢ pushout f g := colimit.ΞΉ (span f g) walking_span.right /-- A pair of morphisms `h : W ⟢ X` and `k : W ⟢ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟢ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] (h : W ⟢ X) (k : W ⟢ Y) (w : h ≫ f = k ≫ g) : W ⟢ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟢ W` and `k : Z ⟢ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟢ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] (h : Y ⟢ W) (k : Z ⟢ W) (w : f ≫ h = g ≫ k) : pushout f g ⟢ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] (h : W ⟢ X) (k : W ⟢ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_Ο€ _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] (h : W ⟢ X) (k : W ⟢ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_Ο€ _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] (h : Y ⟢ W) (k : Z ⟢ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ΞΉ_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] (h : Y ⟢ W) (k : Z ⟢ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ΞΉ_desc _ _ /-- A pair of morphisms `h : W ⟢ X` and `k : W ⟢ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟢ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] (h : W ⟢ X) (k : W ⟢ Y) (w : h ≫ f = k ≫ g) : {l : W ⟢ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟢ W` and `k : Z ⟢ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟢ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] (h : Y ⟢ W) (k : Z ⟢ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟢ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ @[reassoc] lemma pullback.condition {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] : (pullback.fst : pullback f g ⟢ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ @[reassoc] lemma pushout.condition {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] : f ≫ (pushout.inl : Y ⟢ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] {W : C} {k l : W ⟢ pullback f g} (hβ‚€ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ hβ‚€ h₁ /-- The pullback cone built from the pullback projections is a pullback. -/ def pullback_is_pullback {X Y Z : C} (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] : is_limit (pullback_cone.mk (pullback.fst : pullback f g ⟢ _) pullback.snd pullback.condition) := pullback_cone.is_limit.mk _ (Ξ» s, pullback.lift s.fst s.snd s.condition) (by simp) (by simp) (by tidy) /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] [mono g] : mono (pullback.fst : pullback f g ⟢ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ by simp [← pullback.condition, reassoc_of h]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z} [has_pullback f g] [mono f] : mono (pullback.snd : pullback f g ⟢ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ by simp [pullback.condition, reassoc_of h]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] {W : C} {k l : pushout f g ⟢ W} (hβ‚€ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ hβ‚€ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] [epi g] : epi (pushout.inl : Y ⟢ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ by simp [← pushout.condition_assoc, h] ⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z} [has_pushout f g] [epi f] : epi (pushout.inr : Z ⟢ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ by simp [pushout.condition_assoc, h]) h⟩ section variables {D : Type uβ‚‚} [category.{v} D] (G : C β₯€ D) /-- The comparison morphism for the pullback of `f,g`. This is an isomorphism iff `G` preserves the pullback of `f,g`; see `category_theory/limits/preserves/shapes/pullbacks.lean` -/ def pullback_comparison (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : G.obj (pullback f g) ⟢ pullback (G.map f) (G.map g) := pullback.lift (G.map pullback.fst) (G.map pullback.snd) (by simp only [←G.map_comp, pullback.condition]) @[simp, reassoc] lemma pullback_comparison_comp_fst (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : pullback_comparison G f g ≫ pullback.fst = G.map pullback.fst := pullback.lift_fst _ _ _ @[simp, reassoc] lemma pullback_comparison_comp_snd (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : pullback_comparison G f g ≫ pullback.snd = G.map pullback.snd := pullback.lift_snd _ _ _ @[simp, reassoc] lemma map_lift_pullback_comparison (f : X ⟢ Z) (g : Y ⟢ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] {W : C} {h : W ⟢ X} {k : W ⟢ Y} (w : h ≫ f = k ≫ g) : G.map (pullback.lift _ _ w) ≫ pullback_comparison G f g = pullback.lift (G.map h) (G.map k) (by simp only [←G.map_comp, w]) := by { ext; simp [← G.map_comp] } end variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms See https://stacks.math.columbia.edu/tag/001W. -/ abbreviation has_pullbacks := has_limits_of_shape walking_cospan C /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ abbreviation has_pushouts := has_colimits_of_shape walking_span C /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ lemma has_pullbacks_of_has_limit_cospan [Ξ  {X Y Z : C} {f : X ⟢ Z} {g : Y ⟢ Z}, has_limit (cospan f g)] : has_pullbacks C := { has_limit := Ξ» F, has_limit_of_iso (diagram_iso_cospan F).symm } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ lemma has_pushouts_of_has_colimit_span [Ξ  {X Y Z : C} {f : X ⟢ Y} {g : X ⟢ Z}, has_colimit (span f g)] : has_pushouts C := { has_colimit := Ξ» F, has_colimit_of_iso (diagram_iso_span F) } end category_theory.limits
54ee4c27aa957dafa170ba3020c6fda7df619995
75bd9c50a345718d735a7533c007cf45f9da9a83
/src/ring_theory/algebra.lean
1392cc09b4947b4474b1211a24eb3c72b3fd766b
[ "Apache-2.0" ]
permissive
jtbarker/mathlib
a1a3b1ddc16179826260578410746756ef18032c
392d3e376b44265ef2dedbd92231d3177acc1fd0
refs/heads/master
1,671,246,411,096
1,600,801,712,000
1,600,801,712,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,494
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import data.matrix.basic import linear_algebra.tensor_product import ring_theory.subring import deprecated.subring /-! # Algebra over Commutative Semiring (under category) In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`, algebra equivalences `alg_equiv`, and `subalgebra`s. We also define usual operations on `alg_hom`s (`id`, `comp`) and subalgebras (`map`, `comap`). If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replcaed with `is_scalar_tower`. ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ noncomputable theory universes u v w u₁ v₁ open_locale tensor_product big_operators section prio -- We set this priority to 0 later in this file set_option extends_priority 200 /- control priority of `instance [algebra R A] : has_scalar R A` -/ /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg β₯€ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R β†’+* A := (commutes' : βˆ€ r x, to_fun r * x = x * to_fun r) (smul_def' : βˆ€ r x, r β€’ x = to_fun r * x) end prio /-- Embedding `R β†’+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R β†’+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R β†’+* S) (h : βˆ€ c x, i c * x = x * i c) : algebra R S := { smul := Ξ» c x, i c * x, commutes' := h, smul_def' := Ξ» c x, rfl, .. i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R β†’+* S) : algebra R S := i.to_algebra' $ Ξ» _, mul_comm _ namespace algebra variables {R : Type u} {S : Type v} {A : Type w} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r β€’ 1) * x = x * (r β€’ 1) = r β€’ x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A] (h₁ : βˆ€ (r : R) (x : A), (r β€’ 1) * x = r β€’ x) (hβ‚‚ : βˆ€ (r : R) (x : A), x * (r β€’ 1) = r β€’ x) : algebra R A := { to_fun := Ξ» r, r β€’ 1, map_one' := one_smul _ _, map_mul' := Ξ» r₁ rβ‚‚, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := Ξ» r₁ rβ‚‚, add_smul r₁ rβ‚‚ 1, commutes' := Ξ» r x, by simp only [h₁, hβ‚‚], smul_def' := Ξ» r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r β€’ x) * y = x * (r β€’ y) = r β€’ (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule [comm_semiring R] [semiring A] [semimodule R A] (h₁ : βˆ€ (r : R) (x y : A), (r β€’ x) * y = r β€’ (x * y)) (hβ‚‚ : βˆ€ (r : R) (x y : A), x * (r β€’ y) = r β€’ (x * y)) : algebra R A := of_semimodule' (Ξ» r x, by rw [h₁, one_mul]) (Ξ» r x, by rw [hβ‚‚, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A] lemma smul_def'' (r : R) (x : A) : r β€’ x = algebra_map R A r * x := algebra.smul_def' r x /-- To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree, it suffices to check the `algebra_map`s agree. -/ -- We'll later use this to show `algebra β„€ M` is a subsingleton. @[ext] lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A) (w : βˆ€ (r : R), by { haveI := P, exact algebra_map R A r } = by { haveI := Q, exact algebra_map R A r }) : P = Q := begin unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ }, congr, { funext r a, replace w := congr_arg (Ξ» s, s * a) (w r), simp only [←algebra.smul_def''] at w, apply w, }, { ext r, exact w r, }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, }, end @[priority 200] -- see Note [lower instance priority] instance to_semimodule : semimodule R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- from now on, we don't want to use the following instance anymore attribute [instance, priority 0] algebra.to_has_scalar lemma smul_def (r : R) (x : A) : r β€’ x = algebra_map R A r * x := algebra.smul_def' r x lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r β€’ 1 := calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm ... = r β€’ 1 : (algebra.smul_def r 1).symm theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s β€’ y) = s β€’ (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r β€’ x) * y = r β€’ (x * y) := by rw [smul_def, smul_def, mul_assoc] variables (R A) /-- The canonical ring homomorphism `algebra_map R A : R β†’* A` for any `R`-algebra `A`, packaged as an `R`-linear map. -/ protected def linear_map : R β†’β‚—[R] A := { map_smul' := Ξ» x y, begin dsimp, simp [algebra.smul_def], end, ..algebra_map R A } @[simp] lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl instance id : algebra R R := (ring_hom.id R).to_algebra variables {R A} namespace id @[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x β€’ y = x * y := rfl end id /-- Algebra over a subsemiring. -/ instance of_subsemiring (S : subsemiring R) : algebra S A := { smul := Ξ» s x, (s : R) β€’ x, commutes' := Ξ» r x, algebra.commutes r x, smul_def' := Ξ» r x, algebra.smul_def r x, .. (algebra_map R A).comp (subsemiring.subtype S) } /-- Algebra over a subring. -/ instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : subring R) : algebra S A := { smul := Ξ» s x, (s : R) β€’ x, commutes' := Ξ» r x, algebra.commutes r x, smul_def' := Ξ» r x, algebra.smul_def r x, .. (algebra_map R A).comp (subring.subtype S) } lemma algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S β†’+* R) = subring.subtype S := rfl lemma coe_algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) : (algebra_map S R : S β†’ R) = subtype.val := rfl lemma algebra_map_of_subring_apply {R : Type*} [comm_ring R] (S : subring R) (x : S) : algebra_map S R x = x := rfl /-- Algebra over a set that is closed under the ring operations. -/ instance of_is_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : set R) [is_subring S] : algebra S A := algebra.of_subring S.to_subring lemma is_subring_coe_algebra_map_hom {R : Type*} [comm_ring R] (S : set R) [is_subring S] : (algebra_map S R : S β†’+* R) = is_subring.subtype S := rfl lemma is_subring_coe_algebra_map {R : Type*} [comm_ring R] (S : set R) [is_subring S] : (algebra_map S R : S β†’ R) = subtype.val := rfl lemma is_subring_algebra_map_apply {R : Type*} [comm_ring R] (S : set R) [is_subring S] (x : S) : algebra_map S R x = x := rfl lemma set_range_subset {R : Type*} [comm_ring R] {T₁ Tβ‚‚ : set R} [is_subring T₁] (hyp : T₁ βŠ† Tβ‚‚) : set.range (algebra_map T₁ R) βŠ† Tβ‚‚ := begin rintros x ⟨⟨t, ht⟩, rfl⟩, exact hyp ht, end variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A β†’β‚— A β†’β‚— A := linear_map.mkβ‚‚ R (*) (Ξ» x y z, add_mul x y z) (Ξ» c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (Ξ» x y z, mul_add x y z) (Ξ» c x y, by rw [smul_def, smul_def, left_comm]) /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A β†’β‚— A := lmul R A r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A β†’β‚— A := (lmul R A).flip r /-- Simultaneous multiplication on the left and right is a linear map. -/ def lmul_left_right (vw: A Γ— A) : A β†’β‚—[R] A := (lmul_right R A vw.2).comp (lmul_left R A vw.1) /-- The multiplication map on an algebra, as an `R`-linear map from `A βŠ—[R] A` to `A`. -/ def lmul' : A βŠ—[R] A β†’β‚—[R] A := tensor_product.lift (algebra.lmul R A) variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl @[simp] lemma lmul_left_right_apply (vw : A Γ— A) (p : A) : lmul_left_right R A vw p = vw.1 * p * vw.2 := rfl @[simp] lemma lmul'_apply {x y} : algebra.lmul' R A (x βŠ—β‚œ y) = x * y := begin dsimp [algebra.lmul'], simp, end /-- Explicit characterization of the submonoid map in the case of an algebra. `S` is made explicit to help with type inference -/ def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S] (M : submonoid R) : (submonoid S) := submonoid.map (algebra_map R S : R β†’* S) M lemma mem_algebra_map_submonoid_of_mem [algebra R S] {M : submonoid R} (x : M) : (algebra_map R S x) ∈ algebra_map_submonoid S M := set.mem_image_of_mem (algebra_map R S) x.2 instance linear_map.semimodule' (R : Type u) [comm_semiring R] (M : Type v) [add_comm_monoid M] [semimodule R M] (S : Type w) [comm_semiring S] [algebra R S] : semimodule S (M β†’β‚—[R] S) := { smul := Ξ» s f, linear_map.llcomp _ _ _ _ (algebra.lmul R S s) f, one_smul := Ξ» f, linear_map.ext $ Ξ» x, one_mul _, mul_smul := Ξ» s₁ sβ‚‚ f, linear_map.ext $ Ξ» x, mul_assoc _ _ _, smul_add := Ξ» s f g, linear_map.map_add _ _ _, smul_zero := Ξ» s, linear_map.map_zero _, add_smul := Ξ» s₁ sβ‚‚ f, linear_map.ext $ Ξ» x, add_mul _ _ _, zero_smul := Ξ» f, linear_map.ext $ Ξ» x, zero_mul _ } end semiring end algebra namespace module instance endomorphism_algebra (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : algebra R (M β†’β‚—[R] M) := { to_fun := Ξ» r, r β€’ linear_map.id, map_one' := one_smul _ _, map_zero' := zero_smul _ _, map_add' := Ξ» r₁ rβ‚‚, add_smul _ _ _, map_mul' := Ξ» r₁ rβ‚‚, by { ext x, simp [mul_smul] }, commutes' := by { intros, ext, simp }, smul_def' := by { intros, ext, simp } } lemma algebra_map_End_eq_smul_id (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] (a : R) : (algebra_map R (End R M)) a = a β€’ linear_map.id := rfl lemma algebra_map_End_apply (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] (a : R) (m : M) : (algebra_map R (End R M)) a m = a β€’ m := rfl lemma ker_algebra_map_End (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] (a : K) (ha : a β‰  0) : ((algebra_map K (End K V)) a).ker = βŠ₯ := linear_map.ker_smul _ _ ha end module instance matrix_algebra (n : Type u) (R : Type v) [decidable_eq n] [fintype n] [comm_semiring R] : algebra R (matrix n n R) := { commutes' := by { intros, simp [matrix.scalar], }, smul_def' := by { intros, simp [matrix.scalar], }, ..(matrix.scalar n) } set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : βˆ€ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, Ξ» f, f.to_fun⟩ instance coe_ring_hom : has_coe (A →ₐ[R] B) (A β†’+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A β†’* B) := ⟨λ f, ↑(f : A β†’+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A β†’+ B) := ⟨λ f, ↑(f : A β†’+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A β†’ B} (h₁ hβ‚‚ h₃ hβ‚„ hβ‚…) : ⇑(⟨f, h₁, hβ‚‚, h₃, hβ‚„, hβ‚…βŸ© : A →ₐ[R] B) = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A β†’+* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A β†’* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A β†’+ B) = f := rfl variables (Ο† : A →ₐ[R] B) theorem coe_fn_inj ⦃φ₁ Ο†β‚‚ : A →ₐ[R] B⦄ (H : ⇑φ₁ = Ο†β‚‚) : φ₁ = Ο†β‚‚ := by { cases φ₁, cases Ο†β‚‚, congr, exact H } theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) β†’ (A β†’+* B)) := Ξ» φ₁ Ο†β‚‚ H, coe_fn_inj $ show ((φ₁ : (A β†’+* B)) : A β†’ B) = ((Ο†β‚‚ : (A β†’+* B)) : A β†’ B), from congr_arg _ H theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) β†’ (A β†’* B)) := ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) β†’ (A β†’+ B)) := ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective @[ext] theorem ext {φ₁ Ο†β‚‚ : A →ₐ[R] B} (H : βˆ€ x, φ₁ x = Ο†β‚‚ x) : φ₁ = Ο†β‚‚ := coe_fn_inj $ funext H theorem ext_iff {φ₁ Ο†β‚‚ : A →ₐ[R] B} : φ₁ = Ο†β‚‚ ↔ βˆ€ x, φ₁ x = Ο†β‚‚ x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] theorem commutes (r : R) : Ο† (algebra_map R A r) = algebra_map R B r := Ο†.commutes' r theorem comp_algebra_map : (Ο† : A β†’+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ Ο†.commutes @[simp] lemma map_add (r s : A) : Ο† (r + s) = Ο† r + Ο† s := Ο†.to_ring_hom.map_add r s @[simp] lemma map_zero : Ο† 0 = 0 := Ο†.to_ring_hom.map_zero @[simp] lemma map_mul (x y) : Ο† (x * y) = Ο† x * Ο† y := Ο†.to_ring_hom.map_mul x y @[simp] lemma map_one : Ο† 1 = 1 := Ο†.to_ring_hom.map_one @[simp] lemma map_smul (r : R) (x : A) : Ο† (r β€’ x) = r β€’ Ο† x := by simp only [algebra.smul_def, map_mul, commutes] @[simp] lemma map_pow (x : A) (n : β„•) : Ο† (x ^ n) = (Ο† x) ^ n := Ο†.to_ring_hom.map_pow x n lemma map_sum {ΞΉ : Type*} (f : ΞΉ β†’ A) (s : finset ΞΉ) : Ο† (βˆ‘ x in s, f x) = βˆ‘ x in s, Ο† (f x) := Ο†.to_ring_hom.map_sum f s @[simp] lemma map_nat_cast (n : β„•) : Ο† n = n := Ο†.to_ring_hom.map_nat_cast n section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := Ξ» _, rfl, ..ring_hom.id A } end @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (Ο†β‚‚ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := Ξ» r : R, by rw [← φ₁.commutes, ← Ο†β‚‚.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (Ο†β‚‚ : A →ₐ[R] B) (p : A) : φ₁.comp Ο†β‚‚ p = φ₁ (Ο†β‚‚ p) := rfl @[simp] theorem comp_id : Ο†.comp (alg_hom.id R A) = Ο† := ext $ Ξ» x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp Ο† = Ο† := ext $ Ξ» x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (Ο†β‚‚ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp Ο†β‚‚).comp φ₃ = φ₁.comp (Ο†β‚‚.comp φ₃) := ext $ Ξ» x, rfl /-- R-Alg β₯€ R-Mod -/ def to_linear_map : A β†’β‚— B := { to_fun := Ο†, map_add' := Ο†.map_add, map_smul' := Ο†.map_smul } @[simp] lemma to_linear_map_apply (p : A) : Ο†.to_linear_map p = Ο† p := rfl theorem to_linear_map_inj {φ₁ Ο†β‚‚ : A →ₐ[R] B} (H : φ₁.to_linear_map = Ο†β‚‚.to_linear_map) : φ₁ = Ο†β‚‚ := ext $ Ξ» x, show φ₁.to_linear_map x = Ο†β‚‚.to_linear_map x, by rw H @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] variables (Ο† : A →ₐ[R] B) lemma map_prod {ΞΉ : Type*} (f : ΞΉ β†’ A) (s : finset ΞΉ) : Ο† (∏ x in s, f x) = ∏ x in s, Ο† (f x) := Ο†.to_ring_hom.map_prod f s end comm_semiring section ring variables [comm_ring R] [ring A] [ring B] [ring C] variables [algebra R A] [algebra R B] [algebra R C] (Ο† : A →ₐ[R] B) @[simp] lemma map_neg (x) : Ο† (-x) = -Ο† x := Ο†.to_ring_hom.map_neg x @[simp] lemma map_sub (x y) : Ο† (x - y) = Ο† x - Ο† y := Ο†.to_ring_hom.map_sub x y end ring section division_ring variables [comm_ring R] [division_ring A] [division_ring B] variables [algebra R A] [algebra R B] (Ο† : A →ₐ[R] B) @[simp] lemma map_inv (x) : Ο† (x⁻¹) = (Ο† x)⁻¹ := Ο†.to_ring_hom.map_inv x @[simp] lemma map_div (x y) : Ο† (x / y) = Ο† x / Ο† y := Ο†.to_ring_hom.map_div x y end division_ring theorem injective_iff {R A B : Type*} [comm_semiring R] [ring A] [semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : function.injective f ↔ (βˆ€ x, f x = 0 β†’ x = 0) := ring_hom.injective_iff (f : A β†’+* B) end alg_hom set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : βˆ€ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' namespace alg_equiv variables {R : Type u} {A₁ : Type v} {Aβ‚‚ : Type w} {A₃ : Type u₁} variables [comm_semiring R] [semiring A₁] [semiring Aβ‚‚] [semiring A₃] variables [algebra R A₁] [algebra R Aβ‚‚] [algebra R A₃] variables (e : A₁ ≃ₐ[R] Aβ‚‚) instance : has_coe_to_fun (A₁ ≃ₐ[R] Aβ‚‚) := ⟨_, alg_equiv.to_fun⟩ @[ext] lemma ext {f g : A₁ ≃ₐ[R] Aβ‚‚} (h : βˆ€ a, f a = g a) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] Aβ‚‚) (A₁ β†’ Aβ‚‚) (Ξ» e, (e : A₁ β†’ Aβ‚‚)) := begin intros f g w, ext, exact congr_fun w a, end instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] Aβ‚‚) (A₁ ≃+* Aβ‚‚) := ⟨alg_equiv.to_ring_equiv⟩ @[simp] lemma mk_apply {to_fun inv_fun left_inv right_inv map_mul map_add commutes a} : (⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] Aβ‚‚) a = to_fun a := rfl @[simp] lemma to_fun_apply {e : A₁ ≃ₐ[R] Aβ‚‚} {a : A₁} : e.to_fun a = e a := rfl @[simp, norm_cast] lemma coe_ring_equiv : ((e : A₁ ≃+* Aβ‚‚) : A₁ β†’ Aβ‚‚) = e := rfl lemma coe_ring_equiv_injective : function.injective (Ξ» e : A₁ ≃ₐ[R] Aβ‚‚, (e : A₁ ≃+* Aβ‚‚)) := begin intros f g w, ext, replace w : ((f : A₁ ≃+* Aβ‚‚) : A₁ β†’ Aβ‚‚) = ((g : A₁ ≃+* Aβ‚‚) : A₁ β†’ Aβ‚‚) := congr_arg (Ξ» e : A₁ ≃+* Aβ‚‚, (e : A₁ β†’ Aβ‚‚)) w, exact congr_fun w a, end @[simp] lemma map_add : βˆ€ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add @[simp] lemma map_zero : e 0 = 0 := e.to_add_equiv.map_zero @[simp] lemma map_mul : βˆ€ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul @[simp] lemma map_one : e 1 = 1 := e.to_mul_equiv.map_one @[simp] lemma commutes : βˆ€ (r : R), e (algebra_map R A₁ r) = algebra_map R Aβ‚‚ r := e.commutes' @[simp] lemma map_neg {A₁ : Type v} {Aβ‚‚ : Type w} [ring A₁] [ring Aβ‚‚] [algebra R A₁] [algebra R Aβ‚‚] (e : A₁ ≃ₐ[R] Aβ‚‚) : βˆ€ x, e (-x) = -(e x) := e.to_add_equiv.map_neg @[simp] lemma map_sub {A₁ : Type v} {Aβ‚‚ : Type w} [ring A₁] [ring Aβ‚‚] [algebra R A₁] [algebra R Aβ‚‚] (e : A₁ ≃ₐ[R] Aβ‚‚) : βˆ€ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub lemma map_sum {ΞΉ : Type*} (f : ΞΉ β†’ A₁) (s : finset ΞΉ) : e (βˆ‘ x in s, f x) = βˆ‘ x in s, e (f x) := e.to_add_equiv.map_sum f s /-- Interpret an algebra equivalence as an algebra homomorphism. This definition is included for symmetry with the other `to_*_hom` projections. The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/ def to_alg_hom : A₁ →ₐ[R] Aβ‚‚ := { map_one' := e.map_one, map_zero' := e.map_zero, ..e } instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] Aβ‚‚) (A₁ →ₐ[R] Aβ‚‚) := ⟨to_alg_hom⟩ @[simp] lemma to_alg_hom_eq_coe : e.to_alg_hom = e := rfl @[simp, norm_cast] lemma coe_alg_hom : ((e : A₁ →ₐ[R] Aβ‚‚) : A₁ β†’ Aβ‚‚) = e := rfl lemma injective : function.injective e := e.to_equiv.injective lemma surjective : function.surjective e := e.to_equiv.surjective lemma bijective : function.bijective e := e.to_equiv.bijective instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := Ξ» r, rfl, ..(1 : A₁ ≃+* A₁)}⟩ instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩ /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := 1 @[simp] lemma coe_refl : (@refl R A₁ _ _ _ : A₁ →ₐ[R] A₁) = alg_hom.id R A₁ := alg_hom.ext (Ξ» x, rfl) /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] Aβ‚‚) : Aβ‚‚ ≃ₐ[R] A₁ := { commutes' := Ξ» r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } @[simp] lemma inv_fun_apply {e : A₁ ≃ₐ[R] Aβ‚‚} {a : Aβ‚‚} : e.inv_fun a = e.symm a := rfl @[simp] lemma symm_symm {e : A₁ ≃ₐ[R] Aβ‚‚} : e.symm.symm = e := by { ext, refl, } /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] Aβ‚‚) (eβ‚‚ : Aβ‚‚ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := Ξ» r, show eβ‚‚.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', eβ‚‚.commutes'], ..(e₁.to_ring_equiv.trans eβ‚‚.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] Aβ‚‚) : βˆ€ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] Aβ‚‚) : βˆ€ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp] lemma trans_apply (e₁ : A₁ ≃ₐ[R] Aβ‚‚) (eβ‚‚ : Aβ‚‚ ≃ₐ[R] A₃) (x : A₁) : (e₁.trans eβ‚‚) x = eβ‚‚ (e₁ x) := rfl @[simp] lemma comp_symm (e : A₁ ≃ₐ[R] Aβ‚‚) : alg_hom.comp (e : A₁ →ₐ[R] Aβ‚‚) ↑e.symm = alg_hom.id R Aβ‚‚ := by { ext, simp } @[simp] lemma symm_comp (e : A₁ ≃ₐ[R] Aβ‚‚) : alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] Aβ‚‚) = alg_hom.id R A₁ := by { ext, simp } /-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/ def of_alg_hom (f : A₁ →ₐ[R] Aβ‚‚) (g : Aβ‚‚ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R Aβ‚‚) (hβ‚‚ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] Aβ‚‚ := { inv_fun := g, left_inv := alg_hom.ext_iff.1 hβ‚‚, right_inv := alg_hom.ext_iff.1 h₁, ..f } /-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/ def of_bijective (f : A₁ →ₐ[R] Aβ‚‚) (hf : function.bijective f) : A₁ ≃ₐ[R] Aβ‚‚ := { .. ring_equiv.of_bijective (f : A₁ β†’+* Aβ‚‚) hf, .. f } /-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/ def to_linear_equiv (e : A₁ ≃ₐ[R] Aβ‚‚) : A₁ ≃ₗ[R] Aβ‚‚ := { to_fun := e.to_fun, map_add' := Ξ» x y, by simp, map_smul' := Ξ» r x, by simp [algebra.smul_def''], inv_fun := e.symm.to_fun, left_inv := e.left_inv, right_inv := e.right_inv, } @[simp] lemma to_linear_equiv_apply (e : A₁ ≃ₐ[R] Aβ‚‚) (x : A₁) : e.to_linear_equiv x = e x := rfl theorem to_linear_equiv_inj {e₁ eβ‚‚ : A₁ ≃ₐ[R] Aβ‚‚} (H : e₁.to_linear_equiv = eβ‚‚.to_linear_equiv) : e₁ = eβ‚‚ := ext $ Ξ» x, show e₁.to_linear_equiv x = eβ‚‚.to_linear_equiv x, by rw H /-- Interpret an algebra equivalence as a linear map. -/ def to_linear_map : A₁ β†’β‚—[R] Aβ‚‚ := e.to_alg_hom.to_linear_map @[simp] lemma to_alg_hom_to_linear_map : (e : A₁ →ₐ[R] Aβ‚‚).to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_equiv_to_linear_map : e.to_linear_equiv.to_linear_map = e.to_linear_map := rfl @[simp] lemma to_linear_map_apply (x : A₁) : e.to_linear_map x = e x := rfl theorem to_linear_map_inj {e₁ eβ‚‚ : A₁ ≃ₐ[R] Aβ‚‚} (H : e₁.to_linear_map = eβ‚‚.to_linear_map) : e₁ = eβ‚‚ := ext $ Ξ» x, show e₁.to_linear_map x = eβ‚‚.to_linear_map x, by rw H @[simp] lemma trans_to_linear_map (f : A₁ ≃ₐ[R] Aβ‚‚) (g : Aβ‚‚ ≃ₐ[R] A₃) : (f.trans g).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl end alg_equiv namespace algebra variables (R : Type u) (S : Type v) (A : Type w) include R S A /-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it when `algebra R S` and `algebra S A`. If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replaced with `is_scalar_tower`. -/ /- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and `algebra ?m_1 A -/ /- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the appropriate type classes -/ @[nolint unused_arguments] def comap : Type w := A instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h instance comap.semiring [h : semiring A] : semiring (comap R S A) := h instance comap.ring [h : ring A] : ring (comap R S A) := h instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] : algebra S (comap R S A) := h /-- Identity homomorphism `A →ₐ[S] comap R S A`. -/ def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] : A →ₐ[S] comap R S A := alg_hom.id S A /-- Identity homomorphism `comap R S A →ₐ[S] A`. -/ def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] : comap R S A →ₐ[S] A := alg_hom.id S A variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] /-- `R ⟢ S` induces `S-Alg β₯€ R-Alg` -/ instance comap.algebra : algebra R (comap R S A) := { smul := Ξ» r x, (algebra_map R S r β€’ x : A), commutes' := Ξ» r x, algebra.commutes _ _, smul_def' := Ξ» _ _, algebra.smul_def _ _, .. (algebra_map S A).comp (algebra_map R S) } /-- Embedding of `S` into `comap R S A`. -/ def to_comap : S →ₐ[R] comap R S A := { commutes' := Ξ» r, rfl, .. algebra_map S A } theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] (Ο† : A →ₐ[S] B) include R /-- R ⟢ S induces S-Alg β₯€ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { commutes' := Ξ» r, Ο†.commutes (algebra_map R S r) ..Ο† } end alg_hom namespace rat instance algebra_rat {Ξ±} [division_ring Ξ±] [char_zero Ξ±] : algebra β„š Ξ± := (rat.cast_hom Ξ±).to_algebra' $ Ξ» r x, r.cast_commute x end rat /-- A subalgebra is a sub(semi)ring that includes the range of `algebra_map`. -/ structure subalgebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] extends subsemiring A : Type v := (algebra_map_mem' : βˆ€ r, algebra_map R A r ∈ carrier) /-- Reinterpret a `subalgebra` as a `subsemiring`. -/ add_decl_doc subalgebra.to_subsemiring namespace subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] include R instance : has_coe (subalgebra R A) (subsemiring A) := ⟨λ S, { ..S }⟩ instance : has_mem A (subalgebra R A) := ⟨λ x S, x ∈ (S : set A)⟩ variables {A} theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s := iff.rfl @[ext] theorem ext {S T : subalgebra R A} (h : βˆ€ x : A, x ∈ S ↔ x ∈ T) : S = T := by cases S; cases T; congr; ext x; exact h x theorem ext_iff {S T : subalgebra R A} : S = T ↔ βˆ€ x : A, x ∈ S ↔ x ∈ T := ⟨λ h x, by rw h, ext⟩ variables (S : subalgebra R A) theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S := S.algebra_map_mem' r theorem srange_le : (algebra_map R A).srange ≀ S := Ξ» x ⟨r, _, hr⟩, hr β–Έ S.algebra_map_mem r theorem range_subset : set.range (algebra_map R A) βŠ† S := Ξ» x ⟨r, hr⟩, hr β–Έ S.algebra_map_mem r theorem range_le : set.range (algebra_map R A) ≀ S := S.range_subset theorem one_mem : (1 : A) ∈ S := subsemiring.one_mem S theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S := subsemiring.mul_mem S hx hy theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r β€’ x ∈ S := (algebra.smul_def r x).symm β–Έ S.mul_mem (S.algebra_map_mem r) hx theorem pow_mem {x : A} (hx : x ∈ S) (n : β„•) : x ^ n ∈ S := subsemiring.pow_mem S hx n theorem zero_mem : (0 : A) ∈ S := subsemiring.zero_mem S theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S := subsemiring.add_mem S hx hy theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S := neg_one_smul R x β–Έ S.smul_mem hx _ theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S := S.add_mem hx $ S.neg_mem hy theorem nsmul_mem {x : A} (hx : x ∈ S) (n : β„•) : n β€’β„• x ∈ S := subsemiring.nsmul_mem S hx n theorem gsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) (n : β„€) : n β€’β„€ x ∈ S := int.cases_on n (Ξ» i, S.nsmul_mem hx i) (Ξ» i, S.neg_mem $ S.nsmul_mem hx _) theorem coe_nat_mem (n : β„•) : (n : A) ∈ S := subsemiring.coe_nat_mem S n theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) (n : β„€) : (n : A) ∈ S := int.cases_on n (Ξ» i, S.coe_nat_mem i) (Ξ» i, S.neg_mem $ S.coe_nat_mem $ i + 1) theorem list_prod_mem {L : list A} (h : βˆ€ x ∈ L, x ∈ S) : L.prod ∈ S := subsemiring.list_prod_mem S h theorem list_sum_mem {L : list A} (h : βˆ€ x ∈ L, x ∈ S) : L.sum ∈ S := subsemiring.list_sum_mem S h theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) {m : multiset A} (h : βˆ€ x ∈ m, x ∈ S) : m.prod ∈ S := subsemiring.multiset_prod_mem S m h theorem multiset_sum_mem {m : multiset A} (h : βˆ€ x ∈ m, x ∈ S) : m.sum ∈ S := subsemiring.multiset_sum_mem S m h theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) {ΞΉ : Type w} {t : finset ΞΉ} {f : ΞΉ β†’ A} (h : βˆ€ x ∈ t, f x ∈ S) : ∏ x in t, f x ∈ S := subsemiring.prod_mem S h theorem sum_mem {ΞΉ : Type w} {t : finset ΞΉ} {f : ΞΉ β†’ A} (h : βˆ€ x ∈ t, f x ∈ S) : βˆ‘ x in t, f x ∈ S := subsemiring.sum_mem S h instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : is_add_submonoid (S : set A) := { zero_mem := S.zero_mem, add_mem := Ξ» _ _, S.add_mem } instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : is_submonoid (S : set A) := { one_mem := S.one_mem, mul_mem := Ξ» _ _, S.mul_mem } /-- A subalgebra over a ring is also a `subring`. -/ def to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : subring A := { neg_mem' := Ξ» _, S.neg_mem, .. S.to_subsemiring } instance {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : is_subring (S : set A) := { neg_mem := Ξ» _, S.neg_mem } instance : inhabited S := ⟨0⟩ instance (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : semiring S := subsemiring.to_semiring S instance (R : Type u) (A : Type v) [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) : comm_semiring S := subsemiring.to_comm_semiring S instance (R : Type u) (A : Type v) [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : ring S := @@subtype.ring _ S.is_subring instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring instance algebra : algebra R S := { smul := Ξ» (c:R) x, ⟨c β€’ x.1, S.smul_mem x.2 c⟩, commutes' := Ξ» c x, subtype.eq $ algebra.commutes _ _, smul_def' := Ξ» c x, subtype.eq $ algebra.smul_def _ _, .. (algebra_map R A).cod_srestrict S $ Ξ» x, S.range_le ⟨x, rfl⟩ } instance to_algebra {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) : algebra S A := algebra.of_subsemiring _ instance nontrivial [nontrivial A] : nontrivial S := subsemiring.nontrivial S -- todo: standardize on the names these morphisms -- compare with submodule.subtype /-- Embedding of a subalgebra into the algebra. -/ def val : S →ₐ[R] A := by refine_struct { to_fun := (coe : S β†’ A) }; intros; refl @[simp] lemma val_apply (x : S) : S.val x = (x : A) := rfl /-- Convert a `subalgebra` to `submodule` -/ def to_submodule : submodule R A := { carrier := S, zero_mem' := (0:S).2, add_mem' := Ξ» x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul_mem' := Ξ» c x hx, (algebra.smul_def c x).symm β–Έ (⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) := ⟨to_submodule⟩ instance to_submodule.is_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : is_subring ((S : submodule R A) : set A) := S.is_subring @[simp] lemma mem_to_submodule {x} : x ∈ (S : submodule R A) ↔ x ∈ S := iff.rfl theorem to_submodule_injective {S U : subalgebra R A} (h : (S : submodule R A) = U) : S = U := ext $ Ξ» x, by rw [← mem_to_submodule, ← mem_to_submodule, h] theorem to_submodule_inj {S U : subalgebra R A} : (S : submodule R A) = U ↔ S = U := ⟨to_submodule_injective, congr_arg _⟩ instance : partial_order (subalgebra R A) := { le := Ξ» S T, (S : set A) βŠ† (T : set A), le_refl := Ξ» S, set.subset.refl S, le_trans := Ξ» _ _ _, set.subset.trans, le_antisymm := Ξ» S T hst hts, ext $ Ξ» x, ⟨@hst x, @hts x⟩ } /-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/ def comap {R : Type u} {S : Type v} {A : Type w} [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] (iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) := { algebra_map_mem' := Ξ» r, iSB.algebra_map_mem (algebra_map R S r), .. iSB } /-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`, then `T` is an `R`-subalgebra of `A`. -/ def under {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] {i : algebra R A} (S : subalgebra R A) (T : subalgebra S A) : subalgebra R A := { algebra_map_mem' := Ξ» r, T.algebra_map_mem ⟨algebra_map R A r, S.algebra_map_mem r⟩, .. T } /-- Transport a subalgebra via an algebra homomorphism. -/ def map (S : subalgebra R A) (f : A →ₐ[R] B) : subalgebra R B := { algebra_map_mem' := Ξ» r, f.commutes r β–Έ set.mem_image_of_mem _ (S.algebra_map_mem r), .. subsemiring.map (f : A β†’+* B) S,} /-- Preimage of a subalgebra under an algebra homomorphism. -/ def comap' (S : subalgebra R B) (f : A →ₐ[R] B) : subalgebra R A := { algebra_map_mem' := Ξ» r, show f (algebra_map R A r) ∈ S, from (f.commutes r).symm β–Έ S.algebra_map_mem r, .. subsemiring.comap (f : A β†’+* B) S,} theorem map_le {S : subalgebra R A} {f : A →ₐ[R] B} {U : subalgebra R B} : map S f ≀ U ↔ S ≀ comap' U f := set.image_subset_iff lemma mem_map {S : subalgebra R A} {f : A →ₐ[R] B} {y : B} : y ∈ map S f ↔ βˆƒ x ∈ S, f x = y := subsemiring.mem_map instance integral_domain {R A : Type*} [comm_ring R] [integral_domain A] [algebra R A] (S : subalgebra R A) : integral_domain S := @subring.domain A _ S _ end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] variables (Ο† : A →ₐ[R] B) /-- Range of an `alg_hom` as a subalgebra. -/ protected def range (Ο† : A →ₐ[R] B) : subalgebra R B := { algebra_map_mem' := Ξ» r, ⟨algebra_map R A r, set.mem_univ _, Ο†.commutes r⟩, .. Ο†.to_ring_hom.srange } @[simp] lemma mem_range (Ο† : A →ₐ[R] B) {y : B} : y ∈ Ο†.range ↔ βˆƒ x, Ο† x = y := ring_hom.mem_srange @[simp] lemma coe_range (Ο† : A →ₐ[R] B) : (Ο†.range : set B) = set.range Ο† := by { ext, rw [subalgebra.mem_coe, mem_range], refl } /-- Restrict the codomain of an algebra homomorphism. -/ def cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : βˆ€ x, f x ∈ S) : A →ₐ[R] S := { commutes' := Ξ» r, subtype.eq $ f.commutes r, .. ring_hom.cod_srestrict (f : A β†’+* B) S hf } theorem injective_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : βˆ€ x, f x ∈ S) : function.injective (f.cod_restrict S hf) ↔ function.injective f := ⟨λ H x y hxy, H $ subtype.eq hxy, Ξ» H x y hxy, H (congr_arg subtype.val hxy : _)⟩ end alg_hom namespace algebra variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := Ξ» _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra namespace algebra variables (R : Type u) {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] /-- The minimal subalgebra that includes `s`. -/ def adjoin (s : set A) : subalgebra R A := { algebra_map_mem' := Ξ» r, subsemiring.subset_closure $ or.inl ⟨r, rfl⟩, .. subsemiring.closure (set.range (algebra_map R A) βˆͺ s) } variables {R} protected lemma gc : galois_connection (adjoin R : set A β†’ subalgebra R A) coe := Ξ» s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H, Ξ» H, subsemiring.closure_le.2 $ set.union_subset S.range_subset H⟩ /-- Galois insertion between `adjoin` and `coe`. -/ protected def gi : galois_insertion (adjoin R : set A β†’ subalgebra R A) coe := { choice := Ξ» s hs, adjoin R s, gc := algebra.gc, le_l_u := Ξ» S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := Ξ» _ _, rfl } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi instance : inhabited (subalgebra R A) := ⟨βŠ₯⟩ theorem mem_bot {x : A} : x ∈ (βŠ₯ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) := suffices (of_id R A).range = (βŠ₯ : subalgebra R A), by { rw [← this, ← subalgebra.mem_coe, alg_hom.coe_range], refl }, le_bot_iff.mp (Ξ» x hx, subalgebra.range_le _ ((of_id R A).coe_range β–Έ hx)) theorem mem_top {x : A} : x ∈ (⊀ : subalgebra R A) := subsemiring.subset_closure $ or.inr trivial @[simp] theorem coe_top : ((⊀ : subalgebra R A) : submodule R A) = ⊀ := submodule.ext $ Ξ» x, iff_of_true mem_top trivial theorem eq_top_iff {S : subalgebra R A} : S = ⊀ ↔ βˆ€ x : A, x ∈ S := ⟨λ h x, by rw h; exact mem_top, Ξ» h, by ext x; exact ⟨λ _, mem_top, Ξ» _, h x⟩⟩ @[simp] theorem map_top (f : A →ₐ[R] B) : subalgebra.map (⊀ : subalgebra R A) f = f.range := subalgebra.ext $ Ξ» x, ⟨λ ⟨y, _, hy⟩, ⟨y, set.mem_univ _, hy⟩, Ξ» ⟨y, mem, hy⟩, ⟨y, algebra.mem_top, hy⟩⟩ @[simp] theorem map_bot (f : A →ₐ[R] B) : subalgebra.map (βŠ₯ : subalgebra R A) f = βŠ₯ := eq_bot_iff.2 $ Ξ» x ⟨y, hy, hfy⟩, let ⟨r, hr⟩ := mem_bot.1 hy in subalgebra.range_le _ ⟨r, by rwa [← f.commutes, hr]⟩ @[simp] theorem comap_top (f : A →ₐ[R] B) : subalgebra.comap' (⊀ : subalgebra R B) f = ⊀ := eq_top_iff.2 $ Ξ» x, mem_top /-- `alg_hom` to `⊀ : subalgebra R A`. -/ def to_top : A →ₐ[R] (⊀ : subalgebra R A) := by refine_struct { to_fun := Ξ» x, (⟨x, mem_top⟩ : (⊀ : subalgebra R A)) }; intros; refl theorem surjective_algbera_map_iff : function.surjective (algebra_map R A) ↔ (⊀ : subalgebra R A) = βŠ₯ := ⟨λ h, eq_bot_iff.2 $ Ξ» y _, let ⟨x, hx⟩ := h y in hx β–Έ subalgebra.algebra_map_mem _ _, Ξ» h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y ∈ _)⟩ theorem bijective_algbera_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A] [algebra R A] : function.bijective (algebra_map R A) ↔ (⊀ : subalgebra R A) = βŠ₯ := ⟨λ h, surjective_algbera_map_iff.1 h.2, Ξ» h, ⟨(algebra_map R A).injective, surjective_algbera_map_iff.2 h⟩⟩ /-- The bottom subalgebra is isomorphic to the base ring. -/ def bot_equiv_of_injective (h : function.injective (algebra_map R A)) : (βŠ₯ : subalgebra R A) ≃ₐ[R] R := alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _) ⟨λ x y hxy, h (congr_arg subtype.val hxy : _), Ξ» ⟨y, hy⟩, let ⟨x, hx⟩ := algebra.mem_bot.1 hy in ⟨x, subtype.eq hx⟩⟩ /-- The bottom subalgebra is isomorphic to the field. -/ def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] : (βŠ₯ : subalgebra F R) ≃ₐ[F] F := bot_equiv_of_injective (ring_hom.injective _) end algebra section nat variables (R : Type*) [semiring R] /-- Reinterpret a `ring_hom` as an `β„•`-algebra homomorphism. -/ def alg_hom_nat {R : Type u} [semiring R] [algebra β„• R] {S : Type v} [semiring S] [algebra β„• S] (f : R β†’+* S) : R →ₐ[β„•] S := { commutes' := Ξ» i, show f _ = _, by simp, .. f } /-- Semiring β₯€ β„•-Alg -/ instance algebra_nat : algebra β„• R := { commutes' := nat.cast_commute, smul_def' := Ξ» _ _, nsmul_eq_mul _ _, .. nat.cast_ring_hom R } variables {R} /-- A subsemiring is a `β„•`-subalgebra. -/ def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra β„• R := { algebra_map_mem' := Ξ» i, S.coe_nat_mem i, .. S } @[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} : x ∈ subalgebra_of_subsemiring S ↔ x ∈ S := iff.rfl section span_nat open submodule lemma span_nat_eq_add_group_closure (s : set R) : (span β„• s).to_add_submonoid = add_submonoid.closure s := eq.symm $ add_submonoid.closure_eq_of_le subset_span $ Ξ» x hx, span_induction hx (Ξ» x hx, add_submonoid.subset_closure hx) (add_submonoid.zero_mem _) (Ξ» _ _, add_submonoid.add_mem _) (Ξ» _ _ _, add_submonoid.nsmul_mem _ β€Ή_β€Ί _) @[simp] lemma span_nat_eq (s : add_submonoid R) : (span β„• (s : set R)).to_add_submonoid = s := by rw [span_nat_eq_add_group_closure, s.closure_eq] end span_nat end nat section int variables (R : Type*) [ring R] /-- Reinterpret a `ring_hom` as a `β„€`-algebra homomorphism. -/ def alg_hom_int {R : Type u} [comm_ring R] [algebra β„€ R] {S : Type v} [comm_ring S] [algebra β„€ S] (f : R β†’+* S) : R →ₐ[β„€] S := { commutes' := Ξ» i, show f _ = _, by simp, .. f } /-- Ring β₯€ β„€-Alg -/ instance algebra_int : algebra β„€ R := { commutes' := int.cast_commute, smul_def' := Ξ» _ _, gsmul_eq_mul _ _, .. int.cast_ring_hom R } /-- Promote a ring homomorphisms to a `β„€`-algebra homomorphism. -/ def ring_hom.to_int_alg_hom {R S : Type*} [ring R] [ring S] (f : R β†’+* S) : R →ₐ[β„€] S := { commutes' := Ξ» n, by simp, .. f } variables {R} /-- A subring is a `β„€`-subalgebra. -/ def subalgebra_of_subring (S : subring R) : subalgebra β„€ R := { algebra_map_mem' := Ξ» i, int.induction_on i S.zero_mem (Ξ» i ih, S.add_mem ih S.one_mem) (Ξ» i ih, show ((-i - 1 : β„€) : R) ∈ S, by { rw [int.cast_sub, int.cast_one], exact S.sub_mem ih S.one_mem }), .. S } /-- A subset closed under the ring operations is a `β„€`-subalgebra. -/ def subalgebra_of_is_subring (S : set R) [is_subring S] : subalgebra β„€ R := subalgebra_of_subring S.to_subring section variables {S : Type*} [ring S] instance int_algebra_subsingleton : subsingleton (algebra β„€ S) := ⟨λ P Q, by { ext, simp, }⟩ end section variables {S : Type*} [semiring S] instance nat_algebra_subsingleton : subsingleton (algebra β„• S) := ⟨λ P Q, by { ext, simp, }⟩ end @[simp] lemma mem_subalgebra_of_subring {x : R} {S : subring R} : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl @[simp] lemma mem_subalgebra_of_is_subring {x : R} {S : set R} [is_subring S] : x ∈ subalgebra_of_is_subring S ↔ x ∈ S := iff.rfl section span_int open submodule lemma span_int_eq_add_group_closure (s : set R) : (span β„€ s).to_add_subgroup = add_subgroup.closure s := eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ Ξ» x hx, span_induction hx (Ξ» x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _) (Ξ» _ _, add_subgroup.add_mem _) (Ξ» _ _ _, add_subgroup.gsmul_mem _ β€Ή_β€Ί _) @[simp] lemma span_int_eq (s : add_subgroup R) : (span β„€ (s : set R)).to_add_subgroup = s := by rw [span_int_eq_add_group_closure, s.closure_eq] end span_int end int /-! The R-algebra structure on `Ξ  i : I, A i` when each `A i` is an R-algebra. We couldn't set this up back in `algebra.pi_instances` because this file imports it. -/ namespace pi variable {I : Type u} -- The indexing type variable {f : I β†’ Type v} -- The family of types already equipped with instances variables (x y : Ξ  i, f i) (i : I) variables (I f) instance algebra (Ξ±) {r : comm_semiring Ξ±} [s : βˆ€ i, semiring (f i)] [βˆ€ i, algebra Ξ± (f i)] : algebra Ξ± (Ξ  i : I, f i) := { commutes' := Ξ» a f, begin ext, simp [algebra.commutes], end, smul_def' := Ξ» a f, begin ext, simp [algebra.smul_def''], end, ..pi.ring_hom (Ξ» i, algebra_map Ξ± (f i)) } @[simp] lemma algebra_map_apply (Ξ±) {r : comm_semiring Ξ±} [s : βˆ€ i, semiring (f i)] [βˆ€ i, algebra Ξ± (f i)] (a : Ξ±) (i : I) : algebra_map Ξ± (Ξ  i, f i) a i = algebra_map Ξ± (f i) a := rfl -- One could also build a `Ξ  i, R i`-algebra structure on `Ξ  i, A i`, -- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful. end pi section is_scalar_tower variables {R : Type*} [comm_semiring R] variables (A : Type*) [semiring A] [algebra R A] variables {M : Type*} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] variables {N : Type*} [add_comm_monoid N] [semimodule A N] [semimodule R N] [is_scalar_tower R A N] lemma algebra_compatible_smul (r : R) (m : M) : r β€’ m = ((algebra_map R A) r) β€’ m := by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul] variable {A} lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a β€’ r β€’ m = r β€’ a β€’ m := by rw [algebra_compatible_smul A r (a β€’ m), smul_smul, algebra.commutes, mul_smul, ←algebra_compatible_smul] @[simp] lemma map_smul_eq_smul_map (f : M β†’β‚—[A] N) (r : R) (m : M) : f (r β€’ m) = r β€’ f m := by rw [algebra_compatible_smul A r m, linear_map.map_smul, ←algebra_compatible_smul A r (f m)] instance : has_coe (M β†’β‚—[A] N) (M β†’β‚—[R] N) := ⟨λ f, ⟨f.to_fun, Ξ» x y, f.map_add' x y, Ξ» r n, map_smul_eq_smul_map _ _ _⟩⟩ end is_scalar_tower section restrict_scalars /- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then `S`-modules are also `R`-modules. -/ section semimodule variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] variables (E : Type*) [add_comm_monoid E] [semimodule S E] variables {F : Type*} [add_comm_monoid F] [semimodule S F] /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, called `module.restrict_scalars' R S E`. We do not register this as an instance as `S` can not be inferred. -/ def semimodule.restrict_scalars' : semimodule R E := { smul := Ξ» c x, (algebra_map R S c) β€’ x, one_smul := by simp, mul_smul := by simp [mul_smul], smul_add := by simp [smul_add], smul_zero := by simp [smul_zero], add_smul := by simp [add_smul], zero_smul := by simp [zero_smul] } /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, provided as a type synonym `module.restrict_scalars R S E := E`. When the `R`-module structure on `E` is registered directly (using `module.restrict_scalars'` for instance, or for `S = β„‚` and `R = ℝ`), theorems on `module.restrict_scalars R S E` can be directly applied to `E` as these types are the same for the kernel. -/ @[nolint unused_arguments] def semimodule.restrict_scalars (R : Type*) (S : Type*) (E : Type*) : Type* := E instance (R : Type*) (S : Type*) (E : Type*) [I : inhabited E] : inhabited (semimodule.restrict_scalars R S E) := I instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_monoid E] : add_comm_monoid (semimodule.restrict_scalars R S E) := I instance semimodule.restrict_scalars.module_orig (R : Type*) (S : Type*) [semiring S] (E : Type*) [add_comm_monoid E] [I : semimodule S E] : semimodule S (semimodule.restrict_scalars R S E) := I instance : semimodule R (semimodule.restrict_scalars R S E) := (semimodule.restrict_scalars' R S E : semimodule R E) lemma semimodule.restrict_scalars_smul_def (c : R) (x : semimodule.restrict_scalars R S E) : c β€’ x = ((algebra_map R S c) β€’ x : E) := rfl /-- `module.restrict_scalars R S S` is `R`-linearly equivalent to the original algebra `S`. Unfortunately these structures are not generally definitionally equal: the `R`-module structure on `S` is part of the data of `S`, while the `R`-module structure on `module.restrict_scalars R S S` comes from the ring homomorphism `R β†’+* S`, which is a separate part of the data of `S`. The field `algebra.smul_def'` gives the equation we need here. -/ def algebra.restrict_scalars_equiv : (semimodule.restrict_scalars R S S) ≃ₗ[R] S := { to_fun := Ξ» s, s, inv_fun := Ξ» s, s, left_inv := Ξ» s, rfl, right_inv := Ξ» s, rfl, map_add' := Ξ» x y, rfl, map_smul' := Ξ» c x, (algebra.smul_def' _ _).symm, } @[simp] lemma algebra.restrict_scalars_equiv_apply (s : S) : algebra.restrict_scalars_equiv R S s = s := rfl @[simp] lemma algebra.restrict_scalars_equiv_symm_apply (s : S) : (algebra.restrict_scalars_equiv R S).symm s = s := rfl variables {S E} open semimodule instance : is_scalar_tower R S (restrict_scalars R S E) := ⟨λ r s e, by { rw [algebra.smul_def, mul_smul], refl }⟩ /-- `V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars, corresponding to `V`, an `S`-submodule of the original `S`-module. -/ @[simps] def submodule.restrict_scalars (V : submodule S E) : submodule R (restrict_scalars R S E) := { carrier := V.carrier, zero_mem' := V.zero_mem, smul_mem' := Ξ» c e h, V.smul_mem _ h, add_mem' := Ξ» x y hx hy, V.add_mem hx hy, } @[simp] lemma submodule.restrict_scalars_mem (V : submodule S E) (e : E) : e ∈ V.restrict_scalars R ↔ e ∈ V := iff.refl _ @[simp] lemma submodule.restrict_scalars_bot : submodule.restrict_scalars R (βŠ₯ : submodule S E) = βŠ₯ := rfl @[simp] lemma submodule.restrict_scalars_top : submodule.restrict_scalars R (⊀ : submodule S E) = ⊀ := rfl /-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/ def linear_map.restrict_scalars (f : E β†’β‚—[S] F) : (restrict_scalars R S E) β†’β‚—[R] (restrict_scalars R S F) := { to_fun := f.to_fun, map_add' := Ξ»x y, f.map_add x y, map_smul' := Ξ»c x, f.map_smul (algebra_map R S c) x } @[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E β†’β‚—[S] F) : (f.restrict_scalars R : E β†’ F) = f := rfl @[simp] lemma restrict_scalars_ker (f : E β†’β‚—[S] F) : (f.restrict_scalars R).ker = submodule.restrict_scalars R f.ker := rfl /-- `A`-linearly coerce a `R`-linear map from `M` to `R` to a function, given an algebra `A` over a commutative semiring `R` and `M` a semimodule over `R`. -/ def linear_map.lto_fun (R : Type u) (M : Type v) (A : Type w) [comm_semiring R] [add_comm_monoid M] [semimodule R M] [comm_ring A] [algebra R A] : (M β†’β‚—[R] A) β†’β‚—[A] (M β†’ A) := { to_fun := linear_map.to_fun, map_add' := Ξ» f g, rfl, map_smul' := Ξ» c f, rfl } end semimodule section module instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_group E] : add_comm_group (semimodule.restrict_scalars R S E) := I end module variables (π•œ : Type*) [field π•œ] (π•œ' : Type*) [field π•œ'] [algebra π•œ π•œ'] variables (W : Type*) [add_comm_group W] [vector_space π•œ' W] /-- `V.restrict_scalars π•œ` is the `π•œ`-subspace of the `π•œ`-vector space given by restriction of scalars, corresponding to `V`, a `π•œ'`-subspace of the original `π•œ'`-vector space. -/ def subspace.restrict_scalars (V : subspace π•œ' W) : subspace π•œ (semimodule.restrict_scalars π•œ π•œ' W) := { ..submodule.restrict_scalars π•œ (V : submodule π•œ' W) } end restrict_scalars section extend_scalars /-! When `V` is an `R`-module and `W` is an `S`-module, where `S` is an algebra over `R`, then the collection of `R`-linear maps from `V` to `W` admits an `S`-module structure, given by multiplication in the target -/ variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] (V : Type*) [add_comm_monoid V] [semimodule R V] (W : Type*) [add_comm_monoid W] [semimodule S W] /-- The set of `R`-linear maps admits an `S`-action by left multiplication -/ instance linear_map.has_scalar_extend_scalars : has_scalar S (V β†’β‚—[R] (semimodule.restrict_scalars R S W)) := { smul := Ξ» r f, { to_fun := Ξ» v, r β€’ f v, map_add' := by simp [smul_add], map_smul' := Ξ» c x, by rw [linear_map.map_smul, smul_algebra_smul_comm] }} /-- The set of `R`-linear maps is an `S`-module-/ instance linear_map.module_extend_scalars : semimodule S (V β†’β‚—[R] (semimodule.restrict_scalars R S W)) := { one_smul := Ξ» f, by { ext v, simp [(β€’)] }, mul_smul := Ξ» r r' f, by { ext v, simp [(β€’), smul_smul] }, smul_add := Ξ» r f g, by { ext v, simp [(β€’), smul_add] }, smul_zero := Ξ» r, by { ext v, simp [(β€’)] }, add_smul := Ξ» r r' f, by { ext v, simp [(β€’), add_smul] }, zero_smul := Ξ» f, by { ext v, simp [(β€’)] } } variables {R S V W} /-- When `f` is a linear map taking values in `S`, then `Ξ»b, f b β€’ x` is a linear map. -/ def smul_algebra_right (f : V β†’β‚—[R] S) (x : semimodule.restrict_scalars R S W) : V β†’β‚—[R] (semimodule.restrict_scalars R S W) := { to_fun := Ξ»b, f b β€’ x, map_add' := by simp [add_smul], map_smul' := Ξ» b y, by { simp [algebra.smul_def, ← smul_smul], refl } } @[simp] theorem smul_algebra_right_apply (f : V β†’β‚—[R] S) (x : semimodule.restrict_scalars R S W) (c : V) : smul_algebra_right f x c = f c β€’ x := rfl end extend_scalars /-! When `V` and `W` are `S`-modules, for some `R`-algebra `S`, the collection of `S`-linear maps from `V` to `W` forms an `R`-module. (But not generally an `S`-module, because `S` may be non-commutative.) -/ section module_of_linear_maps variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] (V : Type*) [add_comm_monoid V] [semimodule S V] (W : Type*) [add_comm_monoid W] [semimodule S W] /-- For `r : R`, and `f : V β†’β‚—[S] W` (where `S` is an `R`-algebra) we define `(r β€’ f) v = f (r β€’ v)`. -/ def linear_map_algebra_has_scalar : has_scalar R (V β†’β‚—[S] W) := { smul := Ξ» r f, { to_fun := Ξ» v, f ((algebra_map R S r) β€’ v), map_add' := Ξ» x y, by simp [smul_add], map_smul' := Ξ» s v, by simp [smul_smul, algebra.commutes], } } local attribute [instance] linear_map_algebra_has_scalar /-- The `R`-module structure on `S`-linear maps, for `S` an `R`-algebra. -/ def linear_map_algebra_module : semimodule R (V β†’β‚—[S] W) := { one_smul := Ξ» f, begin ext v, dsimp [(β€’)], simp, end, mul_smul := Ξ» r r' f, begin ext v, dsimp [(β€’)], rw [linear_map.map_smul, linear_map.map_smul, linear_map.map_smul, ring_hom.map_mul, smul_smul, algebra.commutes], end, smul_zero := Ξ» r, by { ext v, dsimp [(β€’)], refl, }, smul_add := Ξ» r f g, by { ext v, dsimp [(β€’)], simp [linear_map.map_add], }, zero_smul := Ξ» f, by { ext v, dsimp [(β€’)], simp, }, add_smul := Ξ» r r' f, by { ext v, dsimp [(β€’)], simp [add_smul], }, } local attribute [instance] linear_map_algebra_module variables {R S V W} @[simp] lemma linear_map_algebra_module.smul_apply (c : R) (f : V β†’β‚—[S] W) (v : V) : (c β€’ f) v = (c β€’ (f v) : semimodule.restrict_scalars R S W) := begin erw [linear_map.map_smul], refl, end end module_of_linear_maps
41608b2c2a522b97a574ffd8c9d5da1e3608eb7a
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/convex/specific_functions.lean
e5a8a96e9f7ea1323f548507e7b7879a121a5ab3
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
6,632
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, SΓ©bastien GouΓ«zel -/ import analysis.calculus.mean_value import data.nat.parity import analysis.special_functions.pow /-! # Collection of convex functions In this file we prove that the following functions are convex: * `convex_on_exp` : the exponential function is convex on $(-∞, +∞)$; * `convex_on_pow_of_even` : given an even natural number $n$, the function $f(x)=x^n$ is convex on $(-∞, +∞)$; * `convex_on_pow` : for a natural $n$, the function $f(x)=x^n$ is convex on $[0, +∞)$; * `convex_on_fpow` : for an integer $m$, the function $f(x)=x^m$ is convex on $(0, +∞)$. * `convex_on_rpow : βˆ€ p : ℝ, 1 ≀ p β†’ convex_on (Ici 0) (Ξ» x, x ^ p)` * `concave_on_log_Ioi` and `concave_on_log_Iio`: log is concave on `Ioi 0` and `Iio 0` respectively. -/ open real set open_locale big_operators /-- `exp` is convex on the whole real line -/ lemma convex_on_exp : convex_on univ exp := convex_on_univ_of_deriv2_nonneg differentiable_exp (by simp) (assume x, (iter_deriv_exp 2).symm β–Έ le_of_lt (exp_pos x)) /-- `x^n`, `n : β„•` is convex on the whole real line whenever `n` is even -/ lemma convex_on_pow_of_even {n : β„•} (hn : even n) : convex_on set.univ (Ξ» x : ℝ, x^n) := begin apply convex_on_univ_of_deriv2_nonneg differentiable_pow, { simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] }, { intro x, rcases nat.even.sub_even hn (nat.even_bit0 1) with ⟨k, hk⟩, simp only [iter_deriv_pow, finset.prod_range_succ, finset.prod_range_zero, nat.sub_zero, mul_one, hk, pow_mul', sq], exact mul_nonneg (nat.cast_nonneg _) (mul_self_nonneg _) } end /-- `x^n`, `n : β„•` is convex on `[0, +∞)` for all `n` -/ lemma convex_on_pow (n : β„•) : convex_on (Ici 0) (Ξ» x : ℝ, x^n) := begin apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on; simp only [interior_Ici, differentiable_on_pow, deriv_pow', differentiable_on_const, differentiable_on.mul, iter_deriv_pow], intros x hx, exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (le_of_lt hx) _) end lemma finset.prod_nonneg_of_card_nonpos_even {Ξ± Ξ² : Type*} [linear_ordered_comm_ring Ξ²] {f : Ξ± β†’ Ξ²} [decidable_pred (Ξ» x, f x ≀ 0)] {s : finset Ξ±} (h0 : even (s.filter (Ξ» x, f x ≀ 0)).card) : 0 ≀ ∏ x in s, f x := calc 0 ≀ (∏ x in s, ((if f x ≀ 0 then (-1:Ξ²) else 1) * f x)) : finset.prod_nonneg (Ξ» x _, by { split_ifs with hx hx, by simp [hx], simp at hx ⊒, exact le_of_lt hx }) ... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one, mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul] lemma int_prod_range_nonneg (m : β„€) (n : β„•) (hn : even n) : 0 ≀ ∏ k in finset.range n, (m - k) := begin cases (le_or_lt ↑n m) with hnm hmn, { exact finset.prod_nonneg (Ξ» k hk, sub_nonneg.2 (le_trans (int.coe_nat_le.2 $ le_of_lt $ finset.mem_range.1 hk) hnm)) }, cases le_or_lt 0 m with hm hm, { lift m to β„• using hm, exact le_of_eq (eq.symm $ finset.prod_eq_zero (finset.mem_range.2 $ int.coe_nat_lt.1 hmn) (sub_self _)) }, clear hmn, apply finset.prod_nonneg_of_card_nonpos_even, convert hn, convert finset.card_range n, ext k, simp only [finset.mem_filter, finset.mem_range], refine ⟨and.left, Ξ» hk, ⟨hk, sub_nonpos.2 $ le_trans (le_of_lt hm) _⟩⟩, exact int.coe_nat_nonneg k end /-- `x^m`, `m : β„€` is convex on `(0, +∞)` for all `m` -/ lemma convex_on_fpow (m : β„€) : convex_on (Ioi 0) (Ξ» x : ℝ, x^m) := begin apply convex_on_of_deriv2_nonneg (convex_Ioi 0); try { rw [interior_Ioi] }, { exact (differentiable_on_fpow $ lt_irrefl _).continuous_on }, { exact differentiable_on_fpow (lt_irrefl _) }, { have : eq_on (deriv (Ξ»x:ℝ, x^m)) (Ξ»x, ↑m * x^(m-1)) (Ioi 0), from Ξ» x hx, deriv_fpow (ne_of_gt hx), refine (differentiable_on_congr this).2 _, exact (differentiable_on_fpow (lt_irrefl _)).const_mul _ }, { intros x hx, simp only [iter_deriv_fpow (ne_of_gt hx)], refine mul_nonneg (int.cast_nonneg.2 _) (fpow_nonneg (le_of_lt hx) _), exact int_prod_range_nonneg _ _ (nat.even_bit0 1) } end lemma convex_on_rpow {p : ℝ} (hp : 1 ≀ p) : convex_on (Ici 0) (Ξ» x : ℝ, x^p) := begin have A : deriv (Ξ» (x : ℝ), x ^ p) = Ξ» x, p * x^(p-1), by { ext x, simp [hp] }, apply convex_on_of_deriv2_nonneg (convex_Ici 0), { apply (continuous_rpow_of_pos (Ξ» _, lt_of_lt_of_le zero_lt_one hp) continuous_id continuous_const).continuous_on }, { apply differentiable.differentiable_on, simp [hp] }, { rw A, assume x hx, replace hx : x β‰  0, by { simp at hx, exact ne_of_gt hx }, simp [differentiable_at.differentiable_within_at, hx] }, { assume x hx, replace hx : 0 < x, by simpa using hx, suffices : 0 ≀ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], apply mul_nonneg (le_trans zero_le_one hp), exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg (le_of_lt hx) _) } end lemma concave_on_log_Ioi : concave_on (Ioi 0) log := begin have h₁ : Ioi 0 βŠ† ({0} : set ℝ)ᢜ, { intros x hx hx', rw [mem_singleton_iff] at hx', rw [hx'] at hx, exact lt_irrefl 0 hx }, refine concave_on_open_of_deriv2_nonpos (convex_Ioi 0) is_open_Ioi _ _ _, { exact differentiable_on_log.mono h₁ }, { refine ((times_cont_diff_on_log.deriv_of_open _ le_top).differentiable_on le_top).mono h₁, exact is_open_compl_singleton }, { intros x hx, rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x ≀ 0, rw [deriv_log', deriv_inv (show x β‰  0, by {rintro rfl, exact lt_irrefl 0 hx})], exact neg_nonpos.mpr (inv_nonneg.mpr (sq_nonneg x)) } end lemma concave_on_log_Iio : concave_on (Iio 0) log := begin have h₁ : Iio 0 βŠ† ({0} : set ℝ)ᢜ, { intros x hx hx', rw [mem_singleton_iff] at hx', rw [hx'] at hx, exact lt_irrefl 0 hx }, refine concave_on_open_of_deriv2_nonpos (convex_Iio 0) is_open_Iio _ _ _, { exact differentiable_on_log.mono h₁ }, { refine ((times_cont_diff_on_log.deriv_of_open _ le_top).differentiable_on le_top).mono h₁, exact is_open_compl_singleton }, { intros x hx, rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x ≀ 0, rw [deriv_log', deriv_inv (show x β‰  0, by {rintro rfl, exact lt_irrefl 0 hx})], exact neg_nonpos.mpr (inv_nonneg.mpr (sq_nonneg x)) } end
07003735d70cabcc0ba413c0e39a4c7ee799b2f9
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/group_theory/quotient_group.lean
2d8162e821ef6a5d3ff794f44ecbdbc849013593
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
9,875
lean
/- Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot. This file is to a certain extent based on `quotient_module.lean` by Johannes HΓΆlzl. -/ import group_theory.coset universes u v namespace quotient_group variables {G : Type u} [group G] (N : set G) [normal_subgroup N] {H : Type v} [group H] instance : group (quotient N) := { one := (1 : G), mul := Ξ» a b, quotient.lift_onβ‚‚' a b (Ξ» a b, ((a * b : G) : quotient N)) (Ξ» a₁ aβ‚‚ b₁ bβ‚‚ hab₁ habβ‚‚, quot.sound ((is_subgroup.mul_mem_cancel_left N (is_subgroup.inv_mem habβ‚‚)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ bβ‚‚, ← mul_assoc bβ‚‚, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact normal_subgroup.normal _ hab₁ _))), mul_assoc := Ξ» a b c, quotient.induction_on₃' a b c (Ξ» a b c, congr_arg mk (mul_assoc a b c)), one_mul := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (one_mul a)), mul_one := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (mul_one a)), inv := Ξ» a, quotient.lift_on' a (Ξ» a, ((a⁻¹ : G) : quotient N)) (Ξ» a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact is_subgroup.inv_mem (is_subgroup.mem_norm_comm hab) end), mul_left_inv := Ξ» a, quotient.induction_on' a (Ξ» a, congr_arg mk (mul_left_inv a)) } attribute [to_additive quotient_add_group.add_group._proof_6] quotient_group.group._proof_6 attribute [to_additive quotient_add_group.add_group._proof_5] quotient_group.group._proof_5 attribute [to_additive quotient_add_group.add_group._proof_4] quotient_group.group._proof_4 attribute [to_additive quotient_add_group.add_group._proof_3] quotient_group.group._proof_3 attribute [to_additive quotient_add_group.add_group._proof_2] quotient_group.group._proof_2 attribute [to_additive quotient_add_group.add_group._proof_1] quotient_group.group._proof_1 attribute [to_additive quotient_add_group.add_group] quotient_group.group attribute [to_additive quotient_add_group.quotient.equations._eqn_1] quotient_group.quotient.equations._eqn_1 attribute [to_additive quotient_add_group.add_group.equations._eqn_1] quotient_group.group.equations._eqn_1 instance : is_group_hom (mk : G β†’ quotient N) := ⟨λ _ _, rfl⟩ attribute [to_additive quotient_add_group.is_add_group_hom] quotient_group.is_group_hom attribute [to_additive quotient_add_group.is_add_group_hom.equations._eqn_1] quotient_group.is_group_hom.equations._eqn_1 @[simp] lemma ker_mk : is_group_hom.ker (quotient_group.mk : G β†’ quotient_group.quotient N) = N := begin ext g, rw [is_group_hom.mem_ker, eq_comm], show (((1 : G) : quotient_group.quotient N)) = g ↔ _, rw [quotient_group.eq, one_inv, one_mul], end attribute [to_additive quotient_add_group.ker_mk] quotient_group.ker_mk instance {G : Type*} [comm_group G] (s : set G) [is_subgroup s] : comm_group (quotient s) := { mul_comm := Ξ» a b, quotient.induction_onβ‚‚' a b (Ξ» a b, congr_arg mk (mul_comm a b)), ..@quotient_group.group _ _ s (normal_subgroup_of_comm_group s) } attribute [to_additive quotient_add_group.add_comm_group._proof_6] quotient_group.comm_group._proof_6 attribute [to_additive quotient_add_group.add_comm_group._proof_5] quotient_group.comm_group._proof_5 attribute [to_additive quotient_add_group.add_comm_group._proof_4] quotient_group.comm_group._proof_4 attribute [to_additive quotient_add_group.add_comm_group._proof_3] quotient_group.comm_group._proof_3 attribute [to_additive quotient_add_group.add_comm_group._proof_2] quotient_group.comm_group._proof_2 attribute [to_additive quotient_add_group.add_comm_group._proof_1] quotient_group.comm_group._proof_1 attribute [to_additive quotient_add_group.add_comm_group] quotient_group.comm_group attribute [to_additive quotient_add_group.add_comm_group.equations._eqn_1] quotient_group.comm_group.equations._eqn_1 @[simp] lemma coe_one : ((1 : G) : quotient N) = 1 := rfl @[simp] lemma coe_mul (a b : G) : ((a * b : G) : quotient N) = a * b := rfl @[simp] lemma coe_inv (a : G) : ((a⁻¹ : G) : quotient N) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : β„•) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.pow _ _ _ _ mk _ a n attribute [to_additive quotient_add_group.coe_zero] coe_one attribute [to_additive quotient_add_group.coe_add] coe_mul attribute [to_additive quotient_add_group.coe_neg] coe_inv @[simp] lemma coe_gpow (a : G) (n : β„€) : ((a ^ n : G) : quotient N) = a ^ n := @is_group_hom.gpow _ _ _ _ mk _ a n local notation ` Q ` := quotient N def lift (Ο† : G β†’ H) [is_group_hom Ο†] (HN : βˆ€x∈N, Ο† x = 1) (q : Q) : H := q.lift_on' Ο† $ assume a b (hab : a⁻¹ * b ∈ N), (calc Ο† a = Ο† a * 1 : by simp ... = Ο† a * Ο† (a⁻¹ * b) : by rw HN (a⁻¹ * b) hab ... = Ο† (a * (a⁻¹ * b)) : by rw is_group_hom.mul Ο† a (a⁻¹ * b) ... = Ο† b : by simp) attribute [to_additive quotient_add_group.lift._proof_1] lift._proof_1 attribute [to_additive quotient_add_group.lift] lift attribute [to_additive quotient_add_group.lift.equations._eqn_1] lift.equations._eqn_1 @[simp] lemma lift_mk {Ο† : G β†’ H} [is_group_hom Ο†] (HN : βˆ€x∈N, Ο† x = 1) (g : G) : lift N Ο† HN (g : Q) = Ο† g := rfl attribute [to_additive quotient_add_group.lift_mk] lift_mk @[simp] lemma lift_mk' {Ο† : G β†’ H} [is_group_hom Ο†] (HN : βˆ€x∈N, Ο† x = 1) (g : G) : lift N Ο† HN (mk g : Q) = Ο† g := rfl attribute [to_additive quotient_add_group.lift_mk'] lift_mk' def map (M : set H) [normal_subgroup M] (f : G β†’ H) [is_group_hom f] (h : N βŠ† f ⁻¹' M) : quotient N β†’ quotient M := begin haveI : is_group_hom ((mk : H β†’ quotient M) ∘ f) := is_group_hom.comp _ _, refine quotient_group.lift N (mk ∘ f) _, assume x hx, refine quotient_group.eq.2 _, rw [mul_one, is_subgroup.inv_mem_iff], exact h hx, end attribute [to_additive quotient_add_group.map._proof_1] map._proof_1 attribute [to_additive quotient_add_group.map._proof_2] map._proof_2 attribute [to_additive quotient_add_group.map] map variables (Ο† : G β†’ H) [is_group_hom Ο†] (HN : βˆ€x∈N, Ο† x = 1) instance is_group_hom_quotient_lift : is_group_hom (lift N Ο† HN) := ⟨λ q r, quotient.induction_onβ‚‚' q r $ Ξ» a b, show Ο† (a * b) = Ο† a * Ο† b, from is_group_hom.mul Ο† a b⟩ attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift] quotient_group.is_group_hom_quotient_lift attribute [to_additive quotient_add_group.is_add_group_hom_quotient_lift.equations._eqn_1] quotient_group.is_group_hom_quotient_lift.equations._eqn_1 @[to_additive quotient_add_group.map_is_add_group_hom] instance map_is_group_hom (M : set H) [normal_subgroup M] (f : G β†’ H) [is_group_hom f] (h : N βŠ† f ⁻¹' M) : is_group_hom (map N M f h) := quotient_group.is_group_hom_quotient_lift _ _ _ open function is_group_hom /-- The induced map from the quotient by the kernel to the codomain. -/ def ker_lift : quotient (ker Ο†) β†’ H := lift _ Ο† $ Ξ» g, (mem_ker Ο†).mp attribute [to_additive quotient_add_group.ker_lift._proof_1] quotient_group.ker_lift._proof_1 attribute [to_additive quotient_add_group.ker_lift._proof_2] quotient_group.ker_lift._proof_2 attribute [to_additive quotient_add_group.ker_lift] quotient_group.ker_lift attribute [to_additive quotient_add_group.ker_lift.equations._eqn_1] quotient_group.ker_lift.equations._eqn_1 @[simp, to_additive quotient_add_group.ker_lift_mk] lemma ker_lift_mk (g : G) : (ker_lift Ο†) g = Ο† g := lift_mk _ _ _ @[simp, to_additive quotient_add_group.ker_lift_mk'] lemma ker_lift_mk' (g : G) : (ker_lift Ο†) (mk g) = Ο† g := lift_mk' _ _ _ @[to_additive quotient_add_group.ker_lift_is_add_group_hom] instance ker_lift_is_group_hom : is_group_hom (ker_lift Ο†) := quotient_group.is_group_hom_quotient_lift _ _ _ @[to_additive quotient_add_group.injective_ker_lift] lemma injective_ker_lift : injective (ker_lift Ο†) := assume a b, quotient.induction_onβ‚‚' a b $ assume a b (h : Ο† a = Ο† b), quotient.sound' $ show a⁻¹ * b ∈ ker Ο†, by rw [mem_ker Ο†, is_group_hom.mul Ο†, ← h, is_group_hom.inv Ο†, inv_mul_self] --@[to_additive quotient_add_group.quotient_ker_equiv_range] noncomputable def quotient_ker_equiv_range : (quotient (ker Ο†)) ≃ set.range Ο† := @equiv.of_bijective _ (set.range Ο†) (Ξ» x, ⟨lift (ker Ο†) Ο† (by simp [mem_ker]) x, by exact quotient.induction_on' x (Ξ» x, ⟨x, rfl⟩)⟩) ⟨λ a b h, injective_ker_lift _ (subtype.mk.inj h), Ξ» ⟨x, y, hy⟩, ⟨mk y, subtype.eq hy⟩⟩ noncomputable def quotient_ker_equiv_of_surjective (hΟ† : function.surjective Ο†) : (quotient (ker Ο†)) ≃ H := calc (quotient_group.quotient (is_group_hom.ker Ο†)) ≃ set.range Ο† : quotient_ker_equiv_range _ ... ≃ H : ⟨λ a, a.1, Ξ» b, ⟨b, hΟ† b⟩, Ξ» ⟨_, _⟩, rfl, Ξ» _, rfl⟩ end quotient_group namespace quotient_add_group open is_add_group_hom variables {G : Type u} [_root_.add_group G] (N : set G) [normal_add_subgroup N] {H : Type v} [_root_.add_group H] variables (Ο† : G β†’ H) [_root_.is_add_group_hom Ο†] noncomputable def quotient_ker_equiv_range : (quotient (ker Ο†)) ≃ set.range Ο† := @quotient_group.quotient_ker_equiv_range (multiplicative G) _ (multiplicative H) _ Ο† _ noncomputable def quotient_ker_equiv_of_surjective (hΟ† : function.surjective Ο†) : (quotient (ker Ο†)) ≃ H := @quotient_group.quotient_ker_equiv_of_surjective (multiplicative G) _ (multiplicative H) _ Ο† _ hΟ† attribute [to_additive quotient_add_group.quotient_ker_equiv_range] quotient_group.quotient_ker_equiv_range attribute [to_additive quotient_add_group.quotient_ker_equiv_of_surjective] quotient_group.quotient_ker_equiv_of_surjective end quotient_add_group
46aec6d565954dd543c24fa1c1b97bff05a65b07
7b02c598aa57070b4cf4fbfe2416d0479220187f
/algebra/serre.hlean
fceeb3984e64dd68b981a56546e0fa33ce01eb00
[ "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
245
hlean
/- The serre spectral sequence -/ -- Author: Floris van Doorn import .module_exact_couple namespace left_module /- The Atiyah-Hirzebruch spectral sequence (with local coefficents) -/ /- The Serre Spectral Sequence -/ end left_module
bcf55e055f36c87f95570ee5d6f15f06635394ce
e953c38599905267210b87fb5d82dcc3e52a4214
/tests/lean/slow/nat_wo_hints.lean
801ac3fec654160617b7e69d99158e41fc539cd9
[ "Apache-2.0" ]
permissive
c-cube/lean
563c1020bff98441c4f8ba60111fef6f6b46e31b
0fb52a9a139f720be418dafac35104468e293b66
refs/heads/master
1,610,753,294,113
1,440,451,356,000
1,440,499,588,000
41,748,334
0
0
null
1,441,122,656,000
1,441,122,656,000
null
UTF-8
Lean
false
false
49,745
lean
---------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 Floris van Doorn. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Floris van Doorn ---------------------------------------------------------------------------------------------------- import logic algebra.binary open binary eq.ops eq open decidable namespace experiment inductive nat : Type := | zero : nat | succ : nat β†’ nat namespace nat notation `β„•`:max := nat definition plus (x y : β„•) : β„• := nat.rec x (Ξ» n r, succ r) y definition to_nat [coercion] (n : num) : β„• := num.rec zero (Ξ» n, pos_num.rec (succ zero) (Ξ» n r, plus r (plus r (succ zero))) (Ξ» n r, plus r r) n) n namespace helper_tactics definition apply_refl := tactic.apply @eq.refl tactic_hint apply_refl end helper_tactics open helper_tactics theorem nat_rec_zero {P : β„• β†’ Type} (x : P 0) (f : βˆ€m, P m β†’ P (succ m)) : nat.rec x f 0 = x theorem nat_rec_succ {P : β„• β†’ Type} (x : P 0) (f : βˆ€m, P m β†’ P (succ m)) (n : β„•) : nat.rec x f (succ n) = f n (nat.rec x f n) theorem succ_ne_zero (n : β„•) : succ n β‰  0 := assume H : succ n = 0, have H2 : true = false, from let f := (nat.rec false (fun a b, true)) in calc true = f (succ n) : rfl ... = f 0 : {H} ... = false : rfl, absurd H2 true_ne_false definition pred (n : β„•) := nat.rec 0 (fun m x, m) n theorem pred_zero : pred 0 = 0 theorem pred_succ (n : β„•) : pred (succ n) = n theorem zero_or_succ (n : β„•) : n = 0 ∨ n = succ (pred n) := nat.induction_on n (or.intro_left _ (eq.refl 0)) (take m IH, or.intro_right _ (show succ m = succ (pred (succ m)), from congr_arg succ ((pred_succ m)⁻¹))) theorem zero_or_succ2 (n : β„•) : n = 0 ∨ βˆƒk, n = succ k := or_of_or_of_imp_of_imp (zero_or_succ n) (assume H, H) (assume H : n = succ (pred n), exists.intro (pred n) H) theorem case {P : β„• β†’ Prop} (n : β„•) (H1: P 0) (H2 : βˆ€m, P (succ m)) : P n := nat.induction_on n H1 (take m IH, H2 m) theorem discriminate {B : Prop} {n : β„•} (H1: n = 0 β†’ B) (H2 : βˆ€m, n = succ m β†’ B) : B := or.elim (zero_or_succ n) (take H3 : n = 0, H1 H3) (take H3 : n = succ (pred n), H2 (pred n) H3) theorem succ.inj {n m : β„•} (H : succ n = succ m) : n = m := calc n = pred (succ n) : (pred_succ n)⁻¹ ... = pred (succ m) : {H} ... = m : pred_succ m theorem succ_ne_self (n : β„•) : succ n β‰  n := nat.induction_on n (take H : 1 = 0, have ne : 1 β‰  0, from succ_ne_zero 0, absurd H ne) (take k IH H, IH (succ.inj H)) theorem decidable_eq [instance] (n m : β„•) : decidable (n = m) := have general : βˆ€n, decidable (n = m), from nat.rec_on m (take n, nat.rec_on n (inl (eq.refl 0)) (Ξ» m iH, inr (succ_ne_zero m))) (Ξ» (m' : β„•) (iH1 : βˆ€n, decidable (n = m')), take n, nat.rec_on n (inr (ne.symm (succ_ne_zero m'))) (Ξ» (n' : β„•) (iH2 : decidable (n' = succ m')), have d1 : decidable (n' = m'), from iH1 n', decidable.rec_on d1 (assume Heq : n' = m', inl (congr_arg succ Heq)) (assume Hne : n' β‰  m', have H1 : succ n' β‰  succ m', from assume Heq, absurd (succ.inj Heq) Hne, inr H1))), general n theorem two_step_induction_on {P : β„• β†’ Prop} (a : β„•) (H1 : P 0) (H2 : P 1) (H3 : βˆ€ (n : β„•) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a := have stronger : P a ∧ P (succ a), from nat.induction_on a (and.intro H1 H2) (take k IH, have IH1 : P k, from and.elim_left IH, have IH2 : P (succ k), from and.elim_right IH, and.intro IH2 (H3 k IH1 IH2)), and.elim_left stronger theorem sub_induction {P : β„• β†’ β„• β†’ Prop} (n m : β„•) (H1 : βˆ€m, P 0 m) (H2 : βˆ€n, P (succ n) 0) (H3 : βˆ€n m, P n m β†’ P (succ n) (succ m)) : P n m := have general : βˆ€m, P n m, from nat.induction_on n (take m : β„•, H1 m) (take k : β„•, assume IH : βˆ€m, P k m, take m : β„•, discriminate (assume Hm : m = 0, Hm⁻¹ β–Έ (H2 k)) (take l : β„•, assume Hm : m = succ l, Hm⁻¹ β–Έ (H3 k l (IH l)))), general m -------------------------------------------------- add definition add (x y : β„•) : β„• := plus x y infixl `+` := add theorem add_zero (n : β„•) : n + 0 = n theorem add_succ (n m : β„•) : n + succ m = succ (n + m) ---------- comm, assoc theorem zero_add (n : β„•) : 0 + n = n := nat.induction_on n (add_zero 0) (take m IH, show 0 + succ m = succ m, from calc 0 + succ m = succ (0 + m) : add_succ _ _ ... = succ m : {IH}) theorem succ_add (n m : β„•) : (succ n) + m = succ (n + m) := nat.induction_on m (calc succ n + 0 = succ n : add_zero (succ n) ... = succ (n + 0) : {symm (add_zero n)}) (take k IH, calc succ n + succ k = succ (succ n + k) : add_succ _ _ ... = succ (succ (n + k)) : {IH} ... = succ (n + succ k) : {symm (add_succ _ _)}) theorem add_comm (n m : β„•) : n + m = m + n := nat.induction_on m (trans (add_zero _) (symm (zero_add _))) (take k IH, calc n + succ k = succ (n+k) : add_succ _ _ ... = succ (k + n) : {IH} ... = succ k + n : symm (succ_add _ _)) theorem succ_add_eq_add_succ (n m : β„•) : succ n + m = n + succ m := calc succ n + m = succ (n + m) : succ_add n m ... = n +succ m : symm (add_succ n m) theorem add_comm_succ (n m : β„•) : n + succ m = m + succ n := calc n + succ m = succ n + m : symm (succ_add_eq_add_succ n m) ... = m + succ n : add_comm (succ n) m theorem add_assoc (n m k : β„•) : (n + m) + k = n + (m + k) := nat.induction_on k (calc (n + m) + 0 = n + m : add_zero _ ... = n + (m + 0) : {symm (add_zero m)}) (take l IH, calc (n + m) + succ l = succ ((n + m) + l) : add_succ _ _ ... = succ (n + (m + l)) : {IH} ... = n + succ (m + l) : symm (add_succ _ _) ... = n + (m + succ l) : {symm (add_succ _ _)}) theorem add_left_comm (n m k : β„•) : n + (m + k) = m + (n + k) := left_comm add_comm add_assoc n m k theorem add_right_comm (n m k : β„•) : n + m + k = n + k + m := right_comm add_comm add_assoc n m k ---------- inversion theorem add_cancel_left {n m k : β„•} : n + m = n + k β†’ m = k := nat.induction_on n (take H : 0 + m = 0 + k, calc m = 0 + m : symm (zero_add m) ... = 0 + k : H ... = k : zero_add k) (take (n : β„•) (IH : n + m = n + k β†’ m = k) (H : succ n + m = succ n + k), have H2 : succ (n + m) = succ (n + k), from calc succ (n + m) = succ n + m : symm (succ_add n m) ... = succ n + k : H ... = succ (n + k) : succ_add n k, have H3 : n + m = n + k, from succ.inj H2, IH H3) --rename to and_cancel_right theorem add_cancel_right {n m k : β„•} (H : n + m = k + m) : n = k := have H2 : m + n = m + k, from calc m + n = n + m : add_comm m n ... = k + m : H ... = m + k : add_comm k m, add_cancel_left H2 theorem eq_zero_of_add_eq_zero_right {n m : β„•} : n + m = 0 β†’ n = 0 := nat.induction_on n (take (H : 0 + m = 0), eq.refl 0) (take k IH, assume (H : succ k + m = 0), absurd (show succ (k + m) = 0, from calc succ (k + m) = succ k + m : symm (succ_add k m) ... = 0 : H) (succ_ne_zero (k + m))) theorem add_eq_zero_right {n m : β„•} (H : n + m = 0) : m = 0 := eq_zero_of_add_eq_zero_right (trans (add_comm m n) H) theorem add_eq_zero {n m : β„•} (H : n + m = 0) : n = 0 ∧ m = 0 := and.intro (eq_zero_of_add_eq_zero_right H) (add_eq_zero_right H) -- add_eq_self below ---------- misc theorem add_one (n:β„•) : n + 1 = succ n := calc n + 1 = succ (n + 0) : add_succ _ _ ... = succ n : {add_zero _} theorem add_one_left (n:β„•) : 1 + n = succ n := calc 1 + n = succ (0 + n) : succ_add _ _ ... = succ n : {zero_add _} --the following theorem has a terrible name, but since the name is not a substring or superstring of another name, it is at least easy to globally replace it theorem induction_plus_one {P : β„• β†’ Prop} (a : β„•) (H1 : P 0) (H2 : βˆ€ (n : β„•) (IH : P n), P (n + 1)) : P a := nat.rec H1 (take n IH, (add_one n) β–Έ (H2 n IH)) a -------------------------------------------------- mul definition mul (n m : β„•) := nat.rec 0 (fun m x, x + n) m infixl `*` := mul theorem mul_zero_right (n:β„•) : n * 0 = 0 theorem mul_succ_right (n m:β„•) : n * succ m = n * m + n set_option unifier.max_steps 100000 ---------- comm, distr, assoc, identity theorem mul_zero_left (n:β„•) : 0 * n = 0 := nat.induction_on n (mul_zero_right 0) (take m IH, calc 0 * succ m = 0 * m + 0 : mul_succ_right _ _ ... = 0 * m : add_zero _ ... = 0 : IH) theorem mul_succ_left (n m:β„•) : (succ n) * m = (n * m) + m := nat.induction_on m (calc succ n * 0 = 0 : mul_zero_right _ ... = n * 0 : symm (mul_zero_right _) ... = n * 0 + 0 : symm (add_zero _)) (take k IH, calc succ n * succ k = (succ n * k) + succ n : mul_succ_right _ _ ... = (n * k) + k + succ n : { IH } ... = (n * k) + (k + succ n) : add_assoc _ _ _ ... = (n * k) + (n + succ k) : {add_comm_succ _ _} ... = (n * k) + n + succ k : symm (add_assoc _ _ _) ... = (n * succ k) + succ k : {symm (mul_succ_right n k)}) theorem mul_comm (n m:β„•) : n * m = m * n := nat.induction_on m (trans (mul_zero_right _) (symm (mul_zero_left _))) (take k IH, calc n * succ k = n * k + n : mul_succ_right _ _ ... = k * n + n : {IH} ... = (succ k) * n : symm (mul_succ_left _ _)) theorem mul_add_distr_left (n m k : β„•) : (n + m) * k = n * k + m * k := nat.induction_on k (calc (n + m) * 0 = 0 : mul_zero_right _ ... = 0 + 0 : symm (add_zero _) ... = n * 0 + 0 : eq.refl _ ... = n * 0 + m * 0 : eq.refl _) (take l IH, calc (n + m) * succ l = (n + m) * l + (n + m) : mul_succ_right _ _ ... = n * l + m * l + (n + m) : {IH} ... = n * l + m * l + n + m : symm (add_assoc _ _ _) ... = n * l + n + m * l + m : {add_right_comm _ _ _} ... = n * l + n + (m * l + m) : add_assoc _ _ _ ... = n * succ l + (m * l + m) : {symm (mul_succ_right _ _)} ... = n * succ l + m * succ l : {symm (mul_succ_right _ _)}) theorem mul_add_distr_right (n m k : β„•) : n * (m + k) = n * m + n * k := calc n * (m + k) = (m + k) * n : mul_comm _ _ ... = m * n + k * n : mul_add_distr_left _ _ _ ... = n * m + k * n : {mul_comm _ _} ... = n * m + n * k : {mul_comm _ _} theorem mul_assoc (n m k:β„•) : (n * m) * k = n * (m * k) := nat.induction_on k (calc (n * m) * 0 = 0 : mul_zero_right _ ... = n * 0 : symm (mul_zero_right _) ... = n * (m * 0) : {symm (mul_zero_right _)}) (take l IH, calc (n * m) * succ l = (n * m) * l + n * m : mul_succ_right _ _ ... = n * (m * l) + n * m : {IH} ... = n * (m * l + m) : symm (mul_add_distr_right _ _ _) ... = n * (m * succ l) : {symm (mul_succ_right _ _)}) theorem mul_comm_left (n m k : β„•) : n * (m * k) = m * (n * k) := left_comm mul_comm mul_assoc n m k theorem mul_comm_right (n m k : β„•) : n * m * k = n * k * m := right_comm mul_comm mul_assoc n m k theorem mul_one_right (n : β„•) : n * 1 = n := calc n * 1 = n * 0 + n : mul_succ_right n 0 ... = 0 + n : {mul_zero_right n} ... = n : zero_add n theorem mul_one_left (n : β„•) : 1 * n = n := calc 1 * n = n * 1 : mul_comm _ _ ... = n : mul_one_right n ---------- inversion theorem mul_eq_zero {n m : β„•} (H : n * m = 0) : n = 0 ∨ m = 0 := discriminate (take Hn : n = 0, or.intro_left _ Hn) (take (k : β„•), assume (Hk : n = succ k), discriminate (take (Hm : m = 0), or.intro_right _ Hm) (take (l : β„•), assume (Hl : m = succ l), have Heq : succ (k * succ l + l) = n * m, from symm (calc n * m = n * succ l : { Hl } ... = succ k * succ l : { Hk } ... = k * succ l + succ l : mul_succ_left _ _ ... = succ (k * succ l + l) : add_succ _ _), absurd (trans Heq H) (succ_ne_zero _))) -- see more under "positivity" below -------------------------------------------------- le definition le (n m:β„•) : Prop := βˆƒk, n + k = m infix `<=` := le infix `≀` := le theorem le_intro {n m k : β„•} (H : n + k = m) : n ≀ m := exists.intro k H theorem le_elim {n m : β„•} (H : n ≀ m) : βˆƒ k, n + k = m := H ---------- partial order (totality is part of lt) theorem le_intro2 (n m : β„•) : n ≀ n + m := le_intro (eq.refl (n + m)) theorem le_refl (n : β„•) : n ≀ n := le_intro (add_zero n) theorem zero_le (n : β„•) : 0 ≀ n := le_intro (zero_add n) theorem le_zero {n : β„•} (H : n ≀ 0) : n = 0 := obtain (k : β„•) (Hk : n + k = 0), from le_elim H, eq_zero_of_add_eq_zero_right Hk theorem not_succ_zero_le (n : β„•) : Β¬ succ n ≀ 0 := assume H : succ n ≀ 0, have H2 : succ n = 0, from le_zero H, absurd H2 (succ_ne_zero n) theorem le_zero_inv {n : β„•} (H : n ≀ 0) : n = 0 := obtain (k : β„•) (Hk : n + k = 0), from le_elim H, eq_zero_of_add_eq_zero_right Hk theorem le_trans {n m k : β„•} (H1 : n ≀ m) (H2 : m ≀ k) : n ≀ k := obtain (l1 : β„•) (Hl1 : n + l1 = m), from le_elim H1, obtain (l2 : β„•) (Hl2 : m + l2 = k), from le_elim H2, le_intro (calc n + (l1 + l2) = n + l1 + l2 : symm (add_assoc n l1 l2) ... = m + l2 : { Hl1 } ... = k : Hl2) theorem le_antisym {n m : β„•} (H1 : n ≀ m) (H2 : m ≀ n) : n = m := obtain (k : β„•) (Hk : n + k = m), from (le_elim H1), obtain (l : β„•) (Hl : m + l = n), from (le_elim H2), have L1 : k + l = 0, from add_cancel_left (calc n + (k + l) = n + k + l : { symm (add_assoc n k l) } ... = m + l : { Hk } ... = n : Hl ... = n + 0 : symm (add_zero n)), have L2 : k = 0, from eq_zero_of_add_eq_zero_right L1, calc n = n + 0 : symm (add_zero n) ... = n + k : { symm L2 } ... = m : Hk ---------- interaction with add theorem add_le_left {n m : β„•} (H : n ≀ m) (k : β„•) : k + n ≀ k + m := obtain (l : β„•) (Hl : n + l = m), from (le_elim H), le_intro (calc k + n + l = k + (n + l) : add_assoc k n l ... = k + m : { Hl }) theorem add_le_right {n m : β„•} (H : n ≀ m) (k : β„•) : n + k ≀ m + k := (add_comm k m) β–Έ (add_comm k n) β–Έ (add_le_left H k) theorem add_le {n m k l : β„•} (H1 : n ≀ k) (H2 : m ≀ l) : n + m ≀ k + l := le_trans (add_le_right H1 m) (add_le_left H2 k) theorem add_le_left_inv {n m k : β„•} (H : k + n ≀ k + m) : n ≀ m := obtain (l : β„•) (Hl : k + n + l = k + m), from (le_elim H), le_intro (add_cancel_left (calc k + (n + l) = k + n + l : symm (add_assoc k n l) ... = k + m : Hl)) theorem add_le_right_inv {n m k : β„•} (H : n + k ≀ m + k) : n ≀ m := add_le_left_inv (add_comm m k β–Έ add_comm n k β–Έ H) ---------- interaction with succ and pred theorem succ_le {n m : β„•} (H : n ≀ m) : succ n ≀ succ m := add_one m β–Έ add_one n β–Έ add_le_right H 1 theorem succ_le_cancel {n m : β„•} (H : succ n ≀ succ m) : n ≀ m := add_le_right_inv ((add_one m)⁻¹ β–Έ (add_one n)⁻¹ β–Έ H) theorem self_le_succ (n : β„•) : n ≀ succ n := le_intro (add_one n) theorem le_imp_le_succ {n m : β„•} (H : n ≀ m) : n ≀ succ m := le_trans H (self_le_succ m) theorem succ_le_left_or {n m : β„•} (H : n ≀ m) : succ n ≀ m ∨ n = m := obtain (k : β„•) (Hk : n + k = m), from (le_elim H), discriminate (assume H3 : k = 0, have Heq : n = m, from calc n = n + 0 : (add_zero n)⁻¹ ... = n + k : {H3⁻¹} ... = m : Hk, or.intro_right _ Heq) (take l:β„•, assume H3 : k = succ l, have Hlt : succ n ≀ m, from (le_intro (calc succ n + l = n + succ l : succ_add_eq_add_succ n l ... = n + k : {H3⁻¹} ... = m : Hk)), or.intro_left _ Hlt) theorem succ_le_left {n m : β„•} (H1 : n ≀ m) (H2 : n β‰  m) : succ n ≀ m := or_resolve_left (succ_le_left_or H1) H2 theorem succ_le_right_inv {n m : β„•} (H : n ≀ succ m) : n ≀ m ∨ n = succ m := or_of_or_of_imp_of_imp (succ_le_left_or H) (take H2 : succ n ≀ succ m, show n ≀ m, from succ_le_cancel H2) (take H2 : n = succ m, H2) theorem succ_le_left_inv {n m : β„•} (H : succ n ≀ m) : n ≀ m ∧ n β‰  m := obtain (k : β„•) (H2 : succ n + k = m), from (le_elim H), and.intro (have H3 : n + succ k = m, from calc n + succ k = succ n + k : symm (succ_add_eq_add_succ n k) ... = m : H2, show n ≀ m, from le_intro H3) (assume H3 : n = m, have H4 : succ n ≀ n, from subst (symm H3) H, have H5 : succ n = n, from le_antisym H4 (self_le_succ n), show false, from absurd H5 (succ_ne_self n)) theorem le_pred_self (n : β„•) : pred n ≀ n := case n (subst (symm pred_zero) (le_refl 0)) (take k : β„•, subst (symm (pred_succ k)) (self_le_succ k)) theorem pred_le {n m : β„•} (H : n ≀ m) : pred n ≀ pred m := discriminate (take Hn : n = 0, have H2 : pred n = 0, from calc pred n = pred 0 : {Hn} ... = 0 : pred_zero, subst (symm H2) (zero_le (pred m))) (take k : β„•, assume Hn : n = succ k, obtain (l : β„•) (Hl : n + l = m), from le_elim H, have H2 : pred n + l = pred m, from calc pred n + l = pred (succ k) + l : {Hn} ... = k + l : {pred_succ k} ... = pred (succ (k + l)) : symm (pred_succ (k + l)) ... = pred (succ k + l) : {symm (succ_add k l)} ... = pred (n + l) : {symm Hn} ... = pred m : {Hl}, le_intro H2) theorem pred_le_left_inv {n m : β„•} (H : pred n ≀ m) : n ≀ m ∨ n = succ m := discriminate (take Hn : n = 0, or.intro_left _ (subst (symm Hn) (zero_le m))) (take k : β„•, assume Hn : n = succ k, have H2 : pred n = k, from calc pred n = pred (succ k) : {Hn} ... = k : pred_succ k, have H3 : k ≀ m, from subst H2 H, have H4 : succ k ≀ m ∨ k = m, from succ_le_left_or H3, show n ≀ m ∨ n = succ m, from or_of_or_of_imp_of_imp H4 (take H5 : succ k ≀ m, show n ≀ m, from subst (symm Hn) H5) (take H5 : k = m, show n = succ m, from subst H5 Hn)) -- ### interaction with successor and predecessor theorem le_imp_succ_le_or_eq {n m : β„•} (H : n ≀ m) : succ n ≀ m ∨ n = m := obtain (k : β„•) (Hk : n + k = m), from (le_elim H), discriminate (assume H3 : k = 0, have Heq : n = m, from calc n = n + 0 : symm (add_zero n) ... = n + k : {symm H3} ... = m : Hk, or.intro_right _ Heq) (take l : nat, assume H3 : k = succ l, have Hlt : succ n ≀ m, from (le_intro (calc succ n + l = n + succ l : succ_add_eq_add_succ n l ... = n + k : {symm H3} ... = m : Hk)), or.intro_left _ Hlt) theorem le_ne_imp_succ_le {n m : β„•} (H1 : n ≀ m) (H2 : n β‰  m) : succ n ≀ m := or_resolve_left (le_imp_succ_le_or_eq H1) H2 theorem le_succ_imp_le_or_eq {n m : β„•} (H : n ≀ succ m) : n ≀ m ∨ n = succ m := or_of_or_of_imp_left (le_imp_succ_le_or_eq H) (take H2 : succ n ≀ succ m, show n ≀ m, from succ_le_cancel H2) theorem succ_le_imp_le_and_ne {n m : β„•} (H : succ n ≀ m) : n ≀ m ∧ n β‰  m := and.intro (le_trans (self_le_succ n) H) (assume H2 : n = m, have H3 : succ n ≀ n, from subst (symm H2) H, have H4 : succ n = n, from le_antisym H3 (self_le_succ n), show false, from absurd H4 (succ_ne_self n)) theorem pred_le_self (n : β„•) : pred n ≀ n := case n (subst (symm pred_zero) (le_refl 0)) (take k : nat, subst (symm (pred_succ k)) (self_le_succ k)) theorem pred_le_imp_le_or_eq {n m : β„•} (H : pred n ≀ m) : n ≀ m ∨ n = succ m := discriminate (take Hn : n = 0, or.intro_left _ (subst (symm Hn) (zero_le m))) (take k : nat, assume Hn : n = succ k, have H2 : pred n = k, from calc pred n = pred (succ k) : {Hn} ... = k : pred_succ k, have H3 : k ≀ m, from subst H2 H, have H4 : succ k ≀ m ∨ k = m, from le_imp_succ_le_or_eq H3, show n ≀ m ∨ n = succ m, from or_of_or_of_imp_of_imp H4 (take H5 : succ k ≀ m, show n ≀ m, from subst (symm Hn) H5) (take H5 : k = m, show n = succ m, from subst H5 Hn)) ---------- interaction with mul theorem mul_le_left {n m : β„•} (H : n ≀ m) (k : β„•) : k * n ≀ k * m := obtain (l : β„•) (Hl : n + l = m), from (le_elim H), nat.induction_on k (have H2 : 0 * n = 0 * m, from calc 0 * n = 0 : mul_zero_left n ... = 0 * m : symm (mul_zero_left m), show 0 * n ≀ 0 * m, from subst H2 (le_refl (0 * n))) (take (l : β„•), assume IH : l * n ≀ l * m, have H2 : l * n + n ≀ l * m + m, from add_le IH H, have H3 : succ l * n ≀ l * m + m, from subst (symm (mul_succ_left l n)) H2, show succ l * n ≀ succ l * m, from subst (symm (mul_succ_left l m)) H3) theorem mul_le_right {n m : β„•} (H : n ≀ m) (k : β„•) : n * k ≀ m * k := mul_comm k m β–Έ mul_comm k n β–Έ (mul_le_left H k) theorem mul_le {n m k l : β„•} (H1 : n ≀ k) (H2 : m ≀ l) : n * m ≀ k * l := le_trans (mul_le_right H1 m) (mul_le_left H2 k) -- mul_le_[left|right]_inv below -------------------------------------------------- lt definition lt (n m : β„•) := succ n ≀ m infix `<` := lt theorem lt_intro {n m k : β„•} (H : succ n + k = m) : n < m := le_intro H theorem lt_elim {n m : β„•} (H : n < m) : βˆƒ k, succ n + k = m := le_elim H theorem lt_intro2 (n m : β„•) : n < n + succ m := lt_intro (succ_add_eq_add_succ n m) -------------------------------------------------- ge, gt definition ge (n m : β„•) := m ≀ n infix `>=` := ge infix `β‰₯` := ge definition gt (n m : β„•) := m < n infix `>` := gt ---------- basic facts theorem lt_ne {n m : β„•} (H : n < m) : n β‰  m := and.elim_right (succ_le_left_inv H) theorem lt_irrefl (n : β„•) : Β¬ n < n := assume H : n < n, absurd (eq.refl n) (lt_ne H) theorem lt_zero (n : β„•) : 0 < succ n := succ_le (zero_le n) theorem lt_zero_inv (n : β„•) : Β¬ n < 0 := assume H : n < 0, have H2 : succ n = 0, from le_zero_inv H, absurd H2 (succ_ne_zero n) theorem lt_positive {n m : β„•} (H : n < m) : βˆƒk, m = succ k := discriminate (take (Hm : m = 0), absurd (subst Hm H) (lt_zero_inv n)) (take (l : β„•) (Hm : m = succ l), exists.intro l Hm) ---------- interaction with le theorem lt_imp_le_succ {n m : β„•} (H : n < m) : succ n ≀ m := H theorem le_succ_imp_lt {n m : β„•} (H : succ n ≀ m) : n < m := H theorem self_lt_succ (n : β„•) : n < succ n := le_refl (succ n) theorem lt_imp_le {n m : β„•} (H : n < m) : n ≀ m := and.elim_left (succ_le_imp_le_and_ne H) theorem le_imp_lt_or_eq {n m : β„•} (H : n ≀ m) : n < m ∨ n = m := le_imp_succ_le_or_eq H theorem le_ne_imp_lt {n m : β„•} (H1 : n ≀ m) (H2 : n β‰  m) : n < m := le_ne_imp_succ_le H1 H2 theorem le_imp_lt_succ {n m : β„•} (H : n ≀ m) : n < succ m := succ_le H theorem lt_succ_imp_le {n m : β„•} (H : n < succ m) : n ≀ m := succ_le_cancel H ---------- trans, antisym theorem lt_le_trans {n m k : β„•} (H1 : n < m) (H2 : m ≀ k) : n < k := le_trans H1 H2 theorem le_lt_trans {n m k : β„•} (H1 : n ≀ m) (H2 : m < k) : n < k := le_trans (succ_le H1) H2 theorem lt_trans {n m k : β„•} (H1 : n < m) (H2 : m < k) : n < k := lt_le_trans H1 (lt_imp_le H2) theorem le_imp_not_gt {n m : β„•} (H : n ≀ m) : Β¬ n > m := assume H2 : m < n, absurd (le_lt_trans H H2) (lt_irrefl n) theorem lt_imp_not_ge {n m : β„•} (H : n < m) : Β¬ n β‰₯ m := assume H2 : m ≀ n, absurd (lt_le_trans H H2) (lt_irrefl n) theorem lt_antisym {n m : β„•} (H : n < m) : Β¬ m < n := le_imp_not_gt (lt_imp_le H) ---------- interaction with add theorem add_lt_left {n m : β„•} (H : n < m) (k : β„•) : k + n < k + m := add_succ k n β–Έ add_le_left H k theorem add_lt_right {n m : β„•} (H : n < m) (k : β„•) : n + k < m + k := add_comm k m β–Έ add_comm k n β–Έ add_lt_left H k theorem add_le_lt {n m k l : β„•} (H1 : n ≀ k) (H2 : m < l) : n + m < k + l := le_lt_trans (add_le_right H1 m) (add_lt_left H2 k) theorem add_lt_le {n m k l : β„•} (H1 : n < k) (H2 : m ≀ l) : n + m < k + l := lt_le_trans (add_lt_right H1 m) (add_le_left H2 k) theorem add_lt {n m k l : β„•} (H1 : n < k) (H2 : m < l) : n + m < k + l := add_lt_le H1 (lt_imp_le H2) theorem add_lt_left_inv {n m k : β„•} (H : k + n < k + m) : n < m := add_le_left_inv ((add_succ k n)⁻¹ β–Έ H) theorem add_lt_right_inv {n m k : β„•} (H : n + k < m + k) : n < m := add_lt_left_inv (add_comm m k β–Έ add_comm n k β–Έ H) ---------- interaction with succ (see also the interaction with le) theorem succ_lt {n m : β„•} (H : n < m) : succ n < succ m := add_one m β–Έ add_one n β–Έ add_lt_right H 1 theorem succ_lt_inv {n m : β„•} (H : succ n < succ m) : n < m := add_lt_right_inv ((add_one m)⁻¹ β–Έ (add_one n)⁻¹ β–Έ H) theorem lt_self_succ (n : β„•) : n < succ n := le_refl (succ n) theorem succ_lt_right {n m : β„•} (H : n < m) : n < succ m := lt_trans H (lt_self_succ m) ---------- totality of lt and le theorem le_or_lt (n m : β„•) : n ≀ m ∨ m < n := nat.induction_on n (or.intro_left _ (zero_le m)) (take (k : β„•), assume IH : k ≀ m ∨ m < k, or.elim IH (assume H : k ≀ m, obtain (l : β„•) (Hl : k + l = m), from le_elim H, discriminate (assume H2 : l = 0, have H3 : m = k, from calc m = k + l : symm Hl ... = k + 0 : {H2} ... = k : add_zero k, have H4 : m < succ k, from subst H3 (lt_self_succ m), or.intro_right _ H4) (take l2 : β„•, assume H2 : l = succ l2, have H3 : succ k + l2 = m, from calc succ k + l2 = k + succ l2 : succ_add_eq_add_succ k l2 ... = k + l : {symm H2} ... = m : Hl, or.intro_left _ (le_intro H3))) (assume H : m < k, or.intro_right _ (succ_lt_right H))) theorem trichotomy_alt (n m : β„•) : (n < m ∨ n = m) ∨ m < n := or_of_or_of_imp_of_imp (le_or_lt n m) (assume H : n ≀ m, le_imp_lt_or_eq H) (assume H : m < n, H) theorem trichotomy (n m : β„•) : n < m ∨ n = m ∨ m < n := iff.elim_left or.assoc (trichotomy_alt n m) theorem le_total (n m : β„•) : n ≀ m ∨ m ≀ n := or_of_or_of_imp_of_imp (le_or_lt n m) (assume H : n ≀ m, H) (assume H : m < n, lt_imp_le H) -- interaction with mul under "positivity" theorem strong_induction_on {P : β„• β†’ Prop} (n : β„•) (IH : βˆ€n, (βˆ€m, m < n β†’ P m) β†’ P n) : P n := have stronger : βˆ€k, k ≀ n β†’ P k, from nat.induction_on n (take (k : β„•), assume H : k ≀ 0, have H2 : k = 0, from le_zero_inv H, have H3 : βˆ€m, m < k β†’ P m, from (take m : β„•, assume H4 : m < k, have H5 : m < 0, from subst H2 H4, absurd H5 (lt_zero_inv m)), show P k, from IH k H3) (take l : β„•, assume IHl : βˆ€k, k ≀ l β†’ P k, take k : β„•, assume H : k ≀ succ l, or.elim (succ_le_right_inv H) (assume H2 : k ≀ l, show P k, from IHl k H2) (assume H2 : k = succ l, have H3 : βˆ€m, m < k β†’ P m, from (take m : β„•, assume H4 : m < k, have H5 : m ≀ l, from lt_succ_imp_le (subst H2 H4), show P m, from IHl m H5), show P k, from IH k H3)), stronger n (le_refl n) theorem case_strong_induction_on {P : β„• β†’ Prop} (a : β„•) (H0 : P 0) (Hind : βˆ€(n : β„•), (βˆ€m, m ≀ n β†’ P m) β†’ P (succ n)) : P a := strong_induction_on a (take n, case n (assume H : (βˆ€m, m < 0 β†’ P m), H0) (take n, assume H : (βˆ€m, m < succ n β†’ P m), Hind n (take m, assume H1 : m ≀ n, H m (le_imp_lt_succ H1)))) theorem add_eq_self {n m : β„•} (H : n + m = n) : m = 0 := discriminate (take Hm : m = 0, Hm) (take k : β„•, assume Hm : m = succ k, have H2 : succ n + k = n, from calc succ n + k = n + succ k : succ_add_eq_add_succ n k ... = n + m : {symm Hm} ... = n : H, have H3 : n < n, from lt_intro H2, have H4 : n β‰  n, from lt_ne H3, absurd (eq.refl n) H4) -------------------------------------------------- positivity -- we use " _ > 0" as canonical way of denoting that a number is positive ---------- basic theorem zero_or_positive (n : β„•) : n = 0 ∨ n > 0 := or_of_or_of_imp_of_imp (or.swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H) (take H : n > 0, H) theorem succ_positive {n m : β„•} (H : n = succ m) : n > 0 := subst (symm H) (lt_zero m) theorem ne_zero_positive {n : β„•} (H : n β‰  0) : n > 0 := or.elim (zero_or_positive n) (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2) theorem pos_imp_eq_succ {n : β„•} (H : n > 0) : βˆƒl, n = succ l := discriminate (take H2, absurd (subst H2 H) (lt_irrefl 0)) (take l Hl, exists.intro l Hl) theorem add_positive_right (n : β„•) {k : β„•} (H : k > 0) : n + k > n := obtain (l : β„•) (Hl : k = succ l), from pos_imp_eq_succ H, subst (symm Hl) (lt_intro2 n l) theorem add_positive_left (n : β„•) {k : β„•} (H : k > 0) : k + n > n := subst (add_comm n k) (add_positive_right n H) -- Positivity -- --------- -- -- Writing "t > 0" is the preferred way to assert that a natural number is positive. -- ### basic -- See also succ_pos. theorem succ_pos (n : β„•) : 0 < succ n := succ_le (zero_le n) theorem case_zero_pos {P : β„• β†’ Prop} (y : β„•) (H0 : P 0) (H1 : βˆ€y, y > 0 β†’ P y) : P y := case y H0 (take y', H1 _ (succ_pos _)) theorem zero_or_pos (n : β„•) : n = 0 ∨ n > 0 := or_of_or_of_imp_left (or.swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H) theorem succ_imp_pos {n m : β„•} (H : n = succ m) : n > 0 := subst (symm H) (succ_pos m) theorem ne_zero_pos {n : β„•} (H : n β‰  0) : n > 0 := or.elim (zero_or_pos n) (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2) theorem add_pos_right (n : β„•) {k : β„•} (H : k > 0) : n + k > n := subst (add_zero n) (add_lt_left H n) theorem add_pos_left (n : β„•) {k : β„•} (H : k > 0) : k + n > n := subst (add_comm n k) (add_pos_right n H) ---------- mul theorem mul_positive {n m : β„•} (Hn : n > 0) (Hm : m > 0) : n * m > 0 := obtain (k : β„•) (Hk : n = succ k), from pos_imp_eq_succ Hn, obtain (l : β„•) (Hl : m = succ l), from pos_imp_eq_succ Hm, succ_positive (calc n * m = succ k * m : {Hk} ... = succ k * succ l : {Hl} ... = succ k * l + succ k : mul_succ_right (succ k) l ... = succ (succ k * l + k) : add_succ _ _) theorem mul_positive_inv_left {n m : β„•} (H : n * m > 0) : n > 0 := discriminate (assume H2 : n = 0, have H3 : n * m = 0, from calc n * m = 0 * m : {H2} ... = 0 : mul_zero_left m, have H4 : 0 > 0, from subst H3 H, absurd H4 (lt_irrefl 0)) (take l : β„•, assume Hl : n = succ l, subst (symm Hl) (lt_zero l)) theorem mul_positive_inv_right {n m : β„•} (H : n * m > 0) : m > 0 := mul_positive_inv_left (subst (mul_comm n m) H) theorem mul_left_inj {n m k : β„•} (Hn : n > 0) (H : n * m = n * k) : m = k := have general : βˆ€m, n * m = n * k β†’ m = k, from nat.induction_on k (take m:β„•, assume H : n * m = n * 0, have H2 : n * m = 0, from calc n * m = n * 0 : H ... = 0 : mul_zero_right n, have H3 : n = 0 ∨ m = 0, from mul_eq_zero H2, or_resolve_right H3 (ne.symm (lt_ne Hn))) (take (l : β„•), assume (IH : βˆ€ m, n * m = n * l β†’ m = l), take (m : β„•), assume (H : n * m = n * succ l), have H2 : n * succ l > 0, from mul_positive Hn (lt_zero l), have H3 : m > 0, from mul_positive_inv_right (subst (symm H) H2), obtain (l2:β„•) (Hm : m = succ l2), from pos_imp_eq_succ H3, have H4 : n * l2 + n = n * l + n, from calc n * l2 + n = n * succ l2 : symm (mul_succ_right n l2) ... = n * m : {symm Hm} ... = n * succ l : H ... = n * l + n : mul_succ_right n l, have H5 : n * l2 = n * l, from add_cancel_right H4, calc m = succ l2 : Hm ... = succ l : {IH l2 H5}), general m H theorem mul_right_inj {n m k : β„•} (Hm : m > 0) (H : n * m = k * m) : n = k := mul_left_inj Hm (subst (mul_comm k m) (subst (mul_comm n m) H)) -- mul_eq_one below ---------- interaction of mul with le and lt theorem mul_lt_left {n m k : β„•} (Hk : k > 0) (H : n < m) : k * n < k * m := have H2 : k * n < k * n + k, from add_positive_right (k * n) Hk, have H3 : k * n + k ≀ k * m, from subst (mul_succ_right k n) (mul_le_left H k), lt_le_trans H2 H3 theorem mul_lt_right {n m k : β„•} (Hk : k > 0) (H : n < m) : n * k < m * k := subst (mul_comm k m) (subst (mul_comm k n) (mul_lt_left Hk H)) theorem mul_le_lt {n m k l : β„•} (Hk : k > 0) (H1 : n ≀ k) (H2 : m < l) : n * m < k * l := le_lt_trans (mul_le_right H1 m) (mul_lt_left Hk H2) theorem mul_lt_le {n m k l : β„•} (Hl : l > 0) (H1 : n < k) (H2 : m ≀ l) : n * m < k * l := le_lt_trans (mul_le_left H2 n) (mul_lt_right Hl H1) theorem mul_lt {n m k l : β„•} (H1 : n < k) (H2 : m < l) : n * m < k * l := have H3 : n * m ≀ k * m, from mul_le_right (lt_imp_le H1) m, have H4 : k * m < k * l, from mul_lt_left (le_lt_trans (zero_le n) H1) H2, le_lt_trans H3 H4 theorem mul_lt_left_inv {n m k : β„•} (H : k * n < k * m) : n < m := have general : βˆ€ m, k * n < k * m β†’ n < m, from nat.induction_on n (take m : β„•, assume H2 : k * 0 < k * m, have H3 : 0 < k * m, from mul_zero_right k β–Έ H2, show 0 < m, from mul_positive_inv_right H3) (take l : β„•, assume IH : βˆ€ m, k * l < k * m β†’ l < m, take m : β„•, assume H2 : k * succ l < k * m, have H3 : 0 < k * m, from le_lt_trans (zero_le _) H2, have H4 : 0 < m, from mul_positive_inv_right H3, obtain (l2 : β„•) (Hl2 : m = succ l2), from pos_imp_eq_succ H4, have H5 : k * l + k < k * m, from mul_succ_right k l β–Έ H2, have H6 : k * l + k < k * succ l2, from Hl2 β–Έ H5, have H7 : k * l + k < k * l2 + k, from mul_succ_right k l2 β–Έ H6, have H8 : k * l < k * l2, from add_lt_right_inv H7, have H9 : l < l2, from IH l2 H8, have H10 : succ l < succ l2, from succ_lt H9, show succ l < m, from Hl2⁻¹ β–Έ H10), general m H theorem mul_lt_right_inv {n m k : β„•} (H : n * k < m * k) : n < m := mul_lt_left_inv (mul_comm m k β–Έ mul_comm n k β–Έ H) theorem mul_le_left_inv {n m k : β„•} (H : succ k * n ≀ succ k * m) : n ≀ m := have H2 : succ k * n < succ k * m + succ k, from le_lt_trans H (lt_intro2 _ _), have H3 : succ k * n < succ k * succ m, from subst (symm (mul_succ_right (succ k) m)) H2, have H4 : n < succ m, from mul_lt_left_inv H3, show n ≀ m, from lt_succ_imp_le H4 theorem mul_le_right_inv {n m k : β„•} (H : n * succ m ≀ k * succ m) : n ≀ k := mul_le_left_inv (subst (mul_comm k (succ m)) (subst (mul_comm n (succ m)) H)) theorem mul_eq_one_left {n m : β„•} (H : n * m = 1) : n = 1 := have H2 : n * m > 0, from subst (symm H) (lt_zero 0), have H3 : n > 0, from mul_positive_inv_left H2, have H4 : m > 0, from mul_positive_inv_right H2, or.elim (le_or_lt n 1) (assume H5 : n ≀ 1, show n = 1, from le_antisym H5 H3) (assume H5 : n > 1, have H6 : n * m β‰₯ 2 * 1, from mul_le H5 H4, have H7 : 1 β‰₯ 2, from subst (mul_one_right 2) (subst H H6), absurd (self_lt_succ 1) (le_imp_not_gt H7)) theorem mul_eq_one_right {n m : β„•} (H : n * m = 1) : m = 1 := mul_eq_one_left (subst (mul_comm n m) H) theorem mul_eq_one {n m : β„•} (H : n * m = 1) : n = 1 ∧ m = 1 := and.intro (mul_eq_one_left H) (mul_eq_one_right H) -------------------------------------------------- sub definition sub (n m : β„•) : β„• := nat.rec n (fun m x, pred x) m infixl `-` := sub theorem sub_zero_right (n : β„•) : n - 0 = n theorem sub_succ_right (n m : β„•) : n - succ m = pred (n - m) theorem sub_zero_left (n : β„•) : 0 - n = 0 := nat.induction_on n (sub_zero_right 0) (take k : β„•, assume IH : 0 - k = 0, calc 0 - succ k = pred (0 - k) : sub_succ_right 0 k ... = pred 0 : {IH} ... = 0 : pred_zero) theorem sub_succ_succ (n m : β„•) : succ n - succ m = n - m := nat.induction_on m (calc succ n - 1 = pred (succ n - 0) : sub_succ_right (succ n) 0 ... = pred (succ n) : {sub_zero_right (succ n)} ... = n : pred_succ n ... = n - 0 : symm (sub_zero_right n)) (take k : β„•, assume IH : succ n - succ k = n - k, calc succ n - succ (succ k) = pred (succ n - succ k) : sub_succ_right (succ n) (succ k) ... = pred (n - k) : {IH} ... = n - succ k : symm (sub_succ_right n k)) theorem sub_one (n : β„•) : n - 1 = pred n := calc n - 1 = pred (n - 0) : sub_succ_right n 0 ... = pred n : {sub_zero_right n} theorem sub_self (n : β„•) : n - n = 0 := nat.induction_on n (sub_zero_right 0) (take k IH, trans (sub_succ_succ k k) IH) theorem sub_add_add_right (n m k : β„•) : (n + k) - (m + k) = n - m := nat.induction_on k (calc (n + 0) - (m + 0) = n - (m + 0) : {add_zero _} ... = n - m : {add_zero _}) (take l : β„•, assume IH : (n + l) - (m + l) = n - m, calc (n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {add_succ _ _} ... = succ (n + l) - succ (m + l) : {add_succ _ _} ... = (n + l) - (m + l) : sub_succ_succ _ _ ... = n - m : IH) theorem sub_add_add_left (n m k : β„•) : (k + n) - (k + m) = n - m := subst (add_comm m k) (subst (add_comm n k) (sub_add_add_right n m k)) theorem sub_add_left (n m : β„•) : n + m - m = n := nat.induction_on m (subst (symm (add_zero n)) (sub_zero_right n)) (take k : β„•, assume IH : n + k - k = n, calc n + succ k - succ k = succ (n + k) - succ k : {add_succ n k} ... = n + k - k : sub_succ_succ _ _ ... = n : IH) theorem sub_sub (n m k : β„•) : n - m - k = n - (m + k) := nat.induction_on k (calc n - m - 0 = n - m : sub_zero_right _ ... = n - (m + 0) : {symm (add_zero m)}) (take l : β„•, assume IH : n - m - l = n - (m + l), calc n - m - succ l = pred (n - m - l) : sub_succ_right (n - m) l ... = pred (n - (m + l)) : {IH} ... = n - succ (m + l) : symm (sub_succ_right n (m + l)) ... = n - (m + succ l) : {symm (add_succ m l)}) theorem succ_sub_sub (n m k : β„•) : succ n - m - succ k = n - m - k := calc succ n - m - succ k = succ n - (m + succ k) : sub_sub _ _ _ ... = succ n - succ (m + k) : {add_succ m k} ... = n - (m + k) : sub_succ_succ _ _ ... = n - m - k : symm (sub_sub n m k) theorem sub_add_right_eq_zero (n m : β„•) : n - (n + m) = 0 := calc n - (n + m) = n - n - m : symm (sub_sub n n m) ... = 0 - m : {sub_self n} ... = 0 : sub_zero_left m theorem sub_comm (m n k : β„•) : m - n - k = m - k - n := calc m - n - k = m - (n + k) : sub_sub m n k ... = m - (k + n) : {add_comm n k} ... = m - k - n : symm (sub_sub m k n) theorem succ_sub_one (n : β„•) : succ n - 1 = n := sub_succ_succ n 0 ⬝ sub_zero_right n ---------- mul theorem mul_pred_left (n m : β„•) : pred n * m = n * m - m := nat.induction_on n (calc pred 0 * m = 0 * m : {pred_zero} ... = 0 : mul_zero_left _ ... = 0 - m : symm (sub_zero_left m) ... = 0 * m - m : {symm (mul_zero_left m)}) (take k : β„•, assume IH : pred k * m = k * m - m, calc pred (succ k) * m = k * m : {pred_succ k} ... = k * m + m - m : symm (sub_add_left _ _) ... = succ k * m - m : {symm (mul_succ_left k m)}) theorem mul_pred_right (n m : β„•) : n * pred m = n * m - n := calc n * pred m = pred m * n : mul_comm _ _ ... = m * n - n : mul_pred_left m n ... = n * m - n : {mul_comm m n} theorem mul_sub_distr_left (n m k : β„•) : (n - m) * k = n * k - m * k := nat.induction_on m (calc (n - 0) * k = n * k : {sub_zero_right n} ... = n * k - 0 : symm (sub_zero_right _) ... = n * k - 0 * k : {symm (mul_zero_left _)}) (take l : β„•, assume IH : (n - l) * k = n * k - l * k, calc (n - succ l) * k = pred (n - l) * k : {sub_succ_right n l} ... = (n - l) * k - k : mul_pred_left _ _ ... = n * k - l * k - k : {IH} ... = n * k - (l * k + k) : sub_sub _ _ _ ... = n * k - (succ l * k) : {symm (mul_succ_left l k)}) theorem mul_sub_distr_right (n m k : β„•) : n * (m - k) = n * m - n * k := calc n * (m - k) = (m - k) * n : mul_comm _ _ ... = m * n - k * n : mul_sub_distr_left _ _ _ ... = n * m - k * n : {mul_comm _ _} ... = n * m - n * k : {mul_comm _ _} -------------------------------------------------- max, min, iteration, maybe: sub, div theorem succ_sub {m n : β„•} : m β‰₯ n β†’ succ m - n = succ (m - n) := sub_induction n m (take k, assume H : 0 ≀ k, calc succ k - 0 = succ k : sub_zero_right (succ k) ... = succ (k - 0) : {symm (sub_zero_right k)}) (take k, assume H : succ k ≀ 0, absurd H (not_succ_zero_le k)) (take k l, assume IH : k ≀ l β†’ succ l - k = succ (l - k), take H : succ k ≀ succ l, calc succ (succ l) - succ k = succ l - k : sub_succ_succ (succ l) k ... = succ (l - k) : IH (succ_le_cancel H) ... = succ (succ l - succ k) : {symm (sub_succ_succ l k)}) theorem le_imp_sub_eq_zero {n m : β„•} (H : n ≀ m) : n - m = 0 := obtain (k : β„•) (Hk : n + k = m), from le_elim H, subst Hk (sub_add_right_eq_zero n k) theorem add_sub_le {n m : β„•} : n ≀ m β†’ n + (m - n) = m := sub_induction n m (take k, assume H : 0 ≀ k, calc 0 + (k - 0) = k - 0 : zero_add (k - 0) ... = k : sub_zero_right k) (take k, assume H : succ k ≀ 0, absurd H (not_succ_zero_le k)) (take k l, assume IH : k ≀ l β†’ k + (l - k) = l, take H : succ k ≀ succ l, calc succ k + (succ l - succ k) = succ k + (l - k) : {sub_succ_succ l k} ... = succ (k + (l - k)) : succ_add k (l - k) ... = succ l : {IH (succ_le_cancel H)}) theorem add_sub_ge_left {n m : β„•} : n β‰₯ m β†’ n - m + m = n := subst (add_comm m (n - m)) add_sub_le theorem add_sub_ge {n m : β„•} (H : n β‰₯ m) : n + (m - n) = n := calc n + (m - n) = n + 0 : {le_imp_sub_eq_zero H} ... = n : add_zero n theorem add_sub_le_left {n m : β„•} : n ≀ m β†’ n - m + m = m := subst (add_comm m (n - m)) add_sub_ge theorem le_add_sub_left (n m : β„•) : n ≀ n + (m - n) := or.elim (le_total n m) (assume H : n ≀ m, subst (symm (add_sub_le H)) H) (assume H : m ≀ n, subst (symm (add_sub_ge H)) (le_refl n)) theorem le_add_sub_right (n m : β„•) : m ≀ n + (m - n) := or.elim (le_total n m) (assume H : n ≀ m, subst (symm (add_sub_le H)) (le_refl m)) (assume H : m ≀ n, subst (symm (add_sub_ge H)) H) theorem sub_split {P : β„• β†’ Prop} {n m : β„•} (H1 : n ≀ m β†’ P 0) (H2 : βˆ€k, m + k = n -> P k) : P (n - m) := or.elim (le_total n m) (assume H3 : n ≀ m, subst (symm (le_imp_sub_eq_zero H3)) (H1 H3)) (assume H3 : m ≀ n, H2 (n - m) (add_sub_le H3)) theorem sub_le_self (n m : β„•) : n - m ≀ n := sub_split (assume H : n ≀ m, zero_le n) (take k : β„•, assume H : m + k = n, le_intro (subst (add_comm m k) H)) theorem le_elim_sub (n m : β„•) (H : n ≀ m) : βˆƒk, m - k = n := obtain (k : β„•) (Hk : n + k = m), from le_elim H, exists.intro k (calc m - k = n + k - k : {symm Hk} ... = n : sub_add_left n k) theorem add_sub_assoc {m k : β„•} (H : k ≀ m) (n : β„•) : n + m - k = n + (m - k) := have l1 : k ≀ m β†’ n + m - k = n + (m - k), from sub_induction k m (take m : β„•, assume H : 0 ≀ m, calc n + m - 0 = n + m : sub_zero_right (n + m) ... = n + (m - 0) : {symm (sub_zero_right m)}) (take k : β„•, assume H : succ k ≀ 0, absurd H (not_succ_zero_le k)) (take k m, assume IH : k ≀ m β†’ n + m - k = n + (m - k), take H : succ k ≀ succ m, calc n + succ m - succ k = succ (n + m) - succ k : {add_succ n m} ... = n + m - k : sub_succ_succ (n + m) k ... = n + (m - k) : IH (succ_le_cancel H) ... = n + (succ m - succ k) : {symm (sub_succ_succ m k)}), l1 H theorem sub_eq_zero_imp_le {n m : β„•} : n - m = 0 β†’ n ≀ m := sub_split (assume H1 : n ≀ m, assume H2 : 0 = 0, H1) (take k : β„•, assume H1 : m + k = n, assume H2 : k = 0, have H3 : n = m, from subst (add_zero m) (subst H2 (symm H1)), subst H3 (le_refl n)) theorem sub_sub_split {P : β„• β†’ β„• β†’ Prop} {n m : β„•} (H1 : βˆ€k, n = m + k -> P k 0) (H2 : βˆ€k, m = n + k β†’ P 0 k) : P (n - m) (m - n) := or.elim (le_total n m) (assume H3 : n ≀ m, (le_imp_sub_eq_zero H3)⁻¹ β–Έ (H2 (m - n) ((add_sub_le H3)⁻¹))) (assume H3 : m ≀ n, (le_imp_sub_eq_zero H3)⁻¹ β–Έ (H1 (n - m) ((add_sub_le H3)⁻¹))) theorem sub_intro {n m k : β„•} (H : n + m = k) : k - n = m := have H2 : k - n + n = m + n, from calc k - n + n = k : add_sub_ge_left (le_intro H) ... = n + m : symm H ... = m + n : add_comm n m, add_cancel_right H2 theorem sub_lt {x y : β„•} (xpos : x > 0) (ypos : y > 0) : x - y < x := obtain (x' : β„•) (xeq : x = succ x'), from pos_imp_eq_succ xpos, obtain (y' : β„•) (yeq : y = succ y'), from pos_imp_eq_succ ypos, have xsuby_eq : x - y = x' - y', from calc x - y = succ x' - y : {xeq} ... = succ x' - succ y' : {yeq} ... = x' - y' : sub_succ_succ _ _, have H1 : x' - y' ≀ x', from sub_le_self _ _, have H2 : x' < succ x', from self_lt_succ _, show x - y < x, from xeq⁻¹ β–Έ xsuby_eq⁻¹ β–Έ le_lt_trans H1 H2 -- Max, min, iteration, and absolute difference -- -------------------------------------------- definition max (n m : β„•) : β„• := n + (m - n) definition min (n m : β„•) : β„• := m - (m - n) theorem max_le {n m : β„•} (H : n ≀ m) : n + (m - n) = m := add_sub_le H theorem max_ge {n m : β„•} (H : n β‰₯ m) : n + (m - n) = n := add_sub_ge H theorem left_le_max (n m : β„•) : n ≀ n + (m - n) := le_add_sub_left n m theorem right_le_max (n m : β„•) : m ≀ max n m := le_add_sub_right n m -- ### absolute difference -- This section is still incomplete definition dist (n m : β„•) := (n - m) + (m - n) theorem dist_comm (n m : β„•) : dist n m = dist m n := add_comm (n - m) (m - n) theorem dist_eq_zero {n m : β„•} (H : dist n m = 0) : n = m := have H2 : n - m = 0, from eq_zero_of_add_eq_zero_right H, have H3 : n ≀ m, from sub_eq_zero_imp_le H2, have H4 : m - n = 0, from add_eq_zero_right H, have H5 : m ≀ n, from sub_eq_zero_imp_le H4, le_antisym H3 H5 theorem dist_le {n m : β„•} (H : n ≀ m) : dist n m = m - n := calc dist n m = (n - m) + (m - n) : eq.refl _ ... = 0 + (m - n) : {le_imp_sub_eq_zero H} ... = m - n : zero_add (m - n) theorem dist_ge {n m : β„•} (H : n β‰₯ m) : dist n m = n - m := subst (dist_comm m n) (dist_le H) theorem dist_zero_right (n : β„•) : dist n 0 = n := trans (dist_ge (zero_le n)) (sub_zero_right n) theorem dist_zero_left (n : β„•) : dist 0 n = n := trans (dist_le (zero_le n)) (sub_zero_right n) theorem dist_intro {n m k : β„•} (H : n + m = k) : dist k n = m := calc dist k n = k - n : dist_ge (le_intro H) ... = m : sub_intro H theorem dist_add_right (n k m : β„•) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : eq.refl _ ... = (n - m) + ((m + k) - (n + k)) : {sub_add_add_right _ _ _} ... = (n - m) + (m - n) : {sub_add_add_right _ _ _} theorem dist_add_left (k n m : β„•) : dist (k + n) (k + m) = dist n m := subst (add_comm m k) (subst (add_comm n k) (dist_add_right n k m)) theorem dist_ge_add_right {n m : β„•} (H : n β‰₯ m) : dist n m + m = n := calc dist n m + m = n - m + m : {dist_ge H} ... = n : add_sub_ge_left H theorem dist_eq_intro {n m k l : β„•} (H : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : symm (dist_add_right n m k) ... = dist (k + l) (k + m) : {H} ... = dist l m : dist_add_left k l m end nat end experiment