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
f287518aa062e628eee541279906bb10214d646a
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/IR/TypeRef.lean
388f597901bb6b31148ad0939f503f39168188ce
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,696
lean
import Papyrus.FFI import Papyrus.Context import Papyrus.IR.TypeID namespace Papyrus /-- An opaque type representing and external LLVM [Type](https://llvm.org/doxygen/classllvm_1_1Type.html). -/ constant Llvm.Type : Type := Unit /-- A reference to an external LLVM [Type](https://llvm.org/doxygen/classllvm_1_1Type.html). -/ structure TypeRef where ptr : LinkedLoosePtr ContextRef Llvm.Type namespace TypeRef /-- The `TypeID` of this type. -/ @[extern "papyrus_type_id"] constant typeID (self : TypeRef) : TypeID /-- Get the owning LLVM context of this type. -/ @[extern "papyrus_type_get_context"] constant getContext (self : TypeRef) : IO ContextRef /-- Print this type (without a newline) to LLVM's standard output (which may not correspond to Lean's). If `noDetails`, print just the name of identified struct types. -/ @[extern "papyrus_type_print"] constant print (self : @& TypeRef) (isForDebug := false) (noDetails := false) : IO PUnit /-- Print this type (without a newline) to LLVM's standard error (which may not correspond to Lean's). If `noDetails`, print just the name of identified struct types. -/ @[extern "papyrus_type_eprint"] constant eprint (self : @& TypeRef) (isForDebug := false) (noDetails := false) : IO PUnit /-- Print this type to a string (without a newline). If `noDetails`, print just the name of identified struct types. -/ @[extern "papyrus_type_sprint"] constant sprint (self : @& TypeRef) (isForDebug := false) (noDetails := false) : IO String /-- Print this type to Lean's standard output for debugging (with a newline). -/ def dump (self : @& TypeRef) : IO PUnit := do IO.println (← self.sprint (isForDebug := true))
ca3bbbdd64fd88ccf5b088abe9377ba197caf342
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/omega/eq_elim.lean
5909b8a64262af8cce7459dd2d1f8f9ae3809717
[]
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,936
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.omega.clause import Mathlib.PostPort universes l namespace Mathlib /- Correctness lemmas for equality elimination. See 5.5 of <http://www.decision-procedures.org/> for details. -/ namespace omega def symdiv (i : ℤ) (j : ℤ) : ℤ := ite (bit0 1 * (i % j) < j) (i / j) (i / j + 1) def symmod (i : ℤ) (j : ℤ) : ℤ := ite (bit0 1 * (i % j) < j) (i % j) (i % j - j) theorem symmod_add_one_self {i : ℤ} : 0 < i → symmod i (i + 1) = -1 := sorry theorem mul_symdiv_eq {i : ℤ} {j : ℤ} : j * symdiv i j = i - symmod i j := sorry theorem symmod_eq {i : ℤ} {j : ℤ} : symmod i j = i - j * symdiv i j := eq.mpr (id (Eq._oldrec (Eq.refl (symmod i j = i - j * symdiv i j)) mul_symdiv_eq)) (eq.mpr (id (Eq._oldrec (Eq.refl (symmod i j = i - (i - symmod i j))) (sub_sub_cancel i (symmod i j)))) (Eq.refl (symmod i j))) /-- (sgm v b as n) is the new value assigned to the nth variable after a single step of equality elimination using valuation v, term ⟨b, as⟩, and variable index n. If v satisfies the initial constraint set, then (v ⟨n ↦ sgm v b as n⟩) satisfies the new constraint set after equality elimination. -/ def sgm (v : ℕ → ℤ) (b : ℤ) (as : List ℤ) (n : ℕ) : ℤ := let a_n : ℤ := list.func.get n as; let m : ℤ := a_n + 1; (symmod b m + coeffs.val v (list.map (fun (x : ℤ) => symmod x m) as)) / m def rhs : ℕ → ℤ → List ℤ → term := sorry theorem rhs_correct_aux {v : ℕ → ℤ} {m : ℤ} {as : List ℤ} {k : ℕ} : ∃ (d : ℤ), m * d + coeffs.val_between v (list.map (fun (x : ℤ) => symmod x m) as) 0 k = coeffs.val_between v as 0 k := sorry theorem rhs_correct {v : ℕ → ℤ} {b : ℤ} {as : List ℤ} (n : ℕ) : 0 < list.func.get n as → 0 = term.val v (b, as) → v n = term.val (update n (sgm v b as n) v) (rhs n b as) := sorry def sym_sym (m : ℤ) (b : ℤ) : ℤ := symdiv b m + symmod b m def coeffs_reduce : ℕ → ℤ → List ℤ → term := sorry theorem coeffs_reduce_correct {v : ℕ → ℤ} {b : ℤ} {as : List ℤ} {n : ℕ} : 0 < list.func.get n as → 0 = term.val v (b, as) → 0 = term.val (update n (sgm v b as n) v) (coeffs_reduce n b as) := sorry -- Requires : t1.coeffs[m] = 1 def cancel (m : ℕ) (t1 : term) (t2 : term) : term := term.add (term.mul (-list.func.get m (prod.snd t2)) t1) t2 def subst (n : ℕ) (t1 : term) (t2 : term) : term := term.add (term.mul (list.func.get n (prod.snd t2)) t1) (prod.fst t2, list.func.set 0 (prod.snd t2) n) theorem subst_correct {v : ℕ → ℤ} {b : ℤ} {as : List ℤ} {t : term} {n : ℕ} : 0 < list.func.get n as → 0 = term.val v (b, as) → term.val v t = term.val (update n (sgm v b as n) v) (subst n (rhs n b as) t) := sorry /-- The type of equality elimination rules. -/ inductive ee where | drop : ee | nondiv : ℤ → ee | factor : ℤ → ee | neg : ee | reduce : ℕ → ee | cancel : ℕ → ee namespace ee def repr : ee → string := sorry protected instance has_repr : has_repr ee := has_repr.mk repr end ee /-- Apply a given sequence of equality elimination steps to a clause. -/ def eq_elim : List ee → clause → clause := sorry theorem sat_empty : clause.sat ([], []) := Exists.intro (fun (_x : ℕ) => 0) { left := of_as_true trivial, right := of_as_true trivial } theorem sat_eq_elim {es : List ee} {c : clause} : clause.sat c → clause.sat (eq_elim es c) := sorry /-- If the result of equality elimination is unsatisfiable, the original clause is unsatisfiable. -/ theorem unsat_of_unsat_eq_elim (ee : List ee) (c : clause) : clause.unsat (eq_elim ee c) → clause.unsat c := fun (h1 : clause.unsat (eq_elim ee c)) => id fun (h2 : clause.sat c) => h1 (sat_eq_elim h2)
fec7c3dbdb23d074672dd98f376298b12545c848
ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f
/qp/p1_categories/c5_leancat/s2_depprod.lean
2c200e0941da8a1b97103ddc27eafb81762b8262
[]
no_license
intoverflow/qvr
34b9ef23604738381ca20b7d622fd0399d88f2dd
0cfcd33fe4bf8d93851a00cec5bfd21e77105d74
refs/heads/master
1,616,591,570,371
1,492,575,772,000
1,492,575,772,000
80,061,627
0
0
null
null
null
null
UTF-8
Lean
false
false
12,997
lean
/- ----------------------------------------------------------------------- Dependent products in LeanCat. ----------------------------------------------------------------------- -/ import ..c1_basic import ..c2_limits import ..c3_wtypes import .s1_basic namespace qp open stdaux universe variables ℓ ℓobjx ℓhomx /- ----------------------------------------------------------------------- The dependent product functor. ----------------------------------------------------------------------- -/ /-! #brief The dependent product functor on objects. -/ definition LeanCat.DepProdFun.obj {B A : LeanCat.{ℓ}^.obj} (disp : LeanCat.{ℓ}^.hom B A) (S : OverObj LeanCat.{ℓ} B) : OverObj LeanCat.{ℓ} A := { obj := @coproduct LeanCat A (λ a, @product LeanCat {b : B // disp b = a} (λ b, { x : S^.obj // S^.hom x = b^.val}) (LeanCat.HasProduct.{ℓ ℓ} _)) (LeanCat.HasCoProduct.{ℓ ℓ} _) , hom := sigma.fst } -- /-! #brief Function induced toward the dependent product of a monic. -- -/ -- definition LeanCat.DepProdFun.obj.monic_to {B A : LeanCat.{ℓ}^.obj} -- (disp : LeanCat.{ℓ}^.hom B A) -- [disp_Monic : @Monic LeanCat.{ℓ} B A disp] -- (S : OverObj LeanCat.{ℓ} B) -- (s : S^.obj) -- : (LeanCat.DepProdFun.obj disp S)^.obj -- := { fst := disp (S^.hom s) -- , snd := λ b -- , { val := s -- , property := eq.symm (LeanCat.Monic.inj disp_Monic b^.property) -- } -- } -- /-! #brief Function induced from the dependent product of a (strong) epic. -- -/ -- definition LeanCat.DepProdFun.obj.epic_from.upon {B A : LeanCat.{ℓ}^.obj} -- (disp : LeanCat.{ℓ}^.hom B A) -- (undisp : LeanCat.{ℓ}^.hom A B) -- {ωdisp_undisp : LeanCat.{ℓ}^.circ disp undisp = LeanCat.{ℓ}^.id A} -- (S : OverObj LeanCat.{ℓ} B) -- (af : (LeanCat.DepProdFun.obj disp S)^.obj) -- : {b // disp b = af^.fst} -- := { val := undisp af^.fst -- , property := congr_fun ωdisp_undisp af^.fst -- } -- /-! #brief Function induced from the dependent product of a (strong) epic. -- -/ -- definition LeanCat.DepProdFun.obj.epic_from {B A : LeanCat.{ℓ}^.obj} -- (disp : LeanCat.{ℓ}^.hom B A) -- (undisp : LeanCat.{ℓ}^.hom A B) -- (ωdisp_undisp : LeanCat.{ℓ}^.circ disp undisp = LeanCat.{ℓ}^.id A) -- (S : OverObj LeanCat.{ℓ} B) -- (af : (LeanCat.DepProdFun.obj disp S)^.obj) -- : S^.obj -- := (af^.snd (@LeanCat.DepProdFun.obj.epic_from.upon B A disp undisp ωdisp_undisp S af))^.val -- /-! #brief The dependent product functor is trivial on isos. -- -/ -- definition LeanCat.DepProdFun.obj.Iso {B A : LeanCat.{ℓ}^.obj} -- (disp : LeanCat.{ℓ}^.hom B A) -- [disp_Monic : @Monic LeanCat.{ℓ} B A disp] -- (undisp : LeanCat.{ℓ}^.hom A B) -- (ωdisp_undisp : LeanCat.{ℓ}^.circ disp undisp = LeanCat.{ℓ}^.id A) -- (S : OverObj LeanCat.{ℓ} B) -- : @Iso LeanCat.{ℓ} _ _ -- (LeanCat.DepProdFun.obj.monic_to disp S) -- (LeanCat.DepProdFun.obj.epic_from disp undisp ωdisp_undisp S) -- := { id₁ := rfl -- , id₂ := begin -- apply funext, -- intro a, -- cases a with a f, -- unfold LeanCat SortCat, -- dsimp, -- unfold LeanCat.DepProdFun.obj.monic_to, -- unfold LeanCat.DepProdFun.obj.epic_from, -- exact sorry -- end -- } /-! #brief The dependent product functor on functions. -/ definition LeanCat.DepProdFun.hom {B A : LeanCat.{ℓ}^.obj} (disp : LeanCat.{ℓ}^.hom B A) {S₀ S₁ : OverObj LeanCat.{ℓ} B} (f : OverHom LeanCat.{ℓ} B S₀ S₁) : OverHom LeanCat.{ℓ} A (@LeanCat.DepProdFun.obj B A disp S₀) (@LeanCat.DepProdFun.obj B A disp S₁) := let a : (LeanCat.DepProdFun.obj disp S₀)^.obj → A := λ σ , σ^.fst in let s₁ : ∀ (σ : (LeanCat.DepProdFun.obj disp S₀)^.obj) (b : {b // disp b = a σ}) , S₁^.obj := λ σ b , f^.hom (σ^.snd b)^.val in let ωs₁ : ∀ (σ : (LeanCat.DepProdFun.obj disp S₀)^.obj) (b : {b // disp b = a σ}) , S₁^.hom (s₁ σ b) = b^.val := λ σ b , begin apply eq.trans (congr_fun (eq.symm f^.triangle) (σ^.snd b)), apply (σ^.snd b)^.property end in { hom := λ σ, { fst := a σ , snd := λ b, { val := s₁ σ b, property := ωs₁ σ b } } , triangle := rfl } /-! #brief The dependent product functor preserves identity functions. -/ definition LeanCat.DepProdFun.hom_id {B A : LeanCat.{ℓ}^.obj} (disp : LeanCat.{ℓ}^.hom B A) (S : OverObj LeanCat.{ℓ} B) : LeanCat.DepProdFun.hom disp (OverHom.id LeanCat.{ℓ} B S) = OverHom.id LeanCat.{ℓ} A (LeanCat.DepProdFun.obj disp S) := begin apply OverHom.eq, apply funext, intro σ, cases σ with a f, apply congr_arg (sigma.mk a), apply funext, intro b, apply subtype.eq, trivial end /-! #brief The dependent product functor distributes over composition. -/ definition LeanCat.DepProdFun.hom_comp {B A : LeanCat.{ℓ}^.obj} (disp : LeanCat.{ℓ}^.hom B A) (S₁ S₂ S₃ : OverObj LeanCat.{ℓ} B) (g : OverHom LeanCat.{ℓ} B S₂ S₃) (f : OverHom LeanCat.{ℓ} B S₁ S₂) : LeanCat.DepProdFun.hom disp (OverHom.comp LeanCat.{ℓ} B _ _ _ g f) = OverHom.comp LeanCat.{ℓ} A _ _ _ (LeanCat.DepProdFun.hom disp g) (LeanCat.DepProdFun.hom disp f) := begin apply OverHom.eq, apply funext, intro σ, cases σ with a h, apply congr_arg (sigma.mk a), apply funext, intro b, apply subtype.eq, trivial end /-! #brief The dependent product functor. -/ definition LeanCat.DepProdFun {B A : LeanCat.{ℓ}^.obj} (disp : LeanCat.{ℓ}^.hom B A) : Fun (OverCat LeanCat.{ℓ} B) (OverCat LeanCat.{ℓ} A) := { obj := LeanCat.DepProdFun.obj disp , hom := @LeanCat.DepProdFun.hom B A disp , hom_id := LeanCat.DepProdFun.hom_id disp , hom_circ := LeanCat.DepProdFun.hom_comp disp } -- /- ----------------------------------------------------------------------- -- The dependent product functor is right adjoint to base change. -- ----------------------------------------------------------------------- -/ /-! #brief Component of the counit of the BaseChangeFun/LeanCat.DepProdFun adjunction. -/ definition LeanCat.BaseChange_DepProd.Adj.counit_com {x y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom x y) (X : OverObj LeanCat.{ℓ} x) : OverHom LeanCat.{ℓ} x (BaseChangeFun.obj f (LeanCat.DepProdFun.obj f X)) X := { hom := λ Z , let pb₀ := pullback.π LeanCat.{ℓ} (f ↗→ (LeanCat.DepProdFun.obj f X)^.hom ↗→↗) (@fin_of 1 0) Z in let pb₁ := (pullback.π LeanCat.{ℓ} (f ↗→ (LeanCat.DepProdFun.obj f X)^.hom ↗→↗) (@fin_of 0 1) Z)^.snd in (pb₁ { val := pb₀, property := sorry })^.val , triangle := sorry } /-! #brief Counit of the BaseChangeFun/LeanCat.DepProdFun adjunction. -/ definition LeanCat.BaseChange_DepProd.Adj.counit {x y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom x y) : NatTrans (@BaseChangeFun LeanCat.{ℓ} x y f (HasAllPullbacks.HasPullbacksAlong LeanCat _) □□ LeanCat.DepProdFun f) (Fun.id (OverCat LeanCat.{ℓ} x)) := { com := LeanCat.BaseChange_DepProd.Adj.counit_com f , natural := sorry } /-! #brief Cone used to define the component of the unit of the BaseChangeFun/LeanCat.DepProdFun adjunction. -/ definition LeanCat.BaseChange_DepProd.Adj.unit_com.cone {x y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom x y) (Y : OverObj LeanCat.{ℓ} y) (Yy : OverObj.dom Y) (Xx : {b // f b = Y^.hom Yy}) : PullbackCone LeanCat.{ℓ} (f ↗→ Y^.hom ↗→↗) := @PullbackCone.mk LeanCat.{ℓ} _ _ (f ↗→ Y^.hom ↗→↗) {b // f b = Y^.hom Yy} (λ Xx, f Xx^.val) (subtype.val ↗← (λ Xx, Yy) ↗←↗) begin apply dlist.eq, { trivial }, apply dlist.eq, { apply funext, intro Xx, cases Xx with Xx ωXx, exact sorry } , trivial end /-! #brief Component of the unit of the BaseChangeFun/LeanCat.DepProdFun adjunction. -/ definition LeanCat.BaseChange_DepProd.Adj.unit_com {x y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom x y) (Y : OverObj LeanCat.{ℓ} y) : OverHom LeanCat.{ℓ} y Y (LeanCat.DepProdFun.obj f (BaseChangeFun.obj f Y)) := { hom := λ Yy, { fst := Y^.hom Yy , snd := λ Xx , { val := pullback.univ LeanCat.{ℓ} (f ↗→ Y^.hom ↗→↗) (LeanCat.BaseChange_DepProd.Adj.unit_com.cone f Y Yy Xx) Xx , property := sorry } } , triangle := sorry } /-! #brief Unit of the BaseChangeFun/LeanCat.DepProdFun adjunction. -/ definition LeanCat.BaseChange_DepProd.Adj.unit {x y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom x y) : NatTrans (Fun.id (OverCat LeanCat.{ℓ} y)) (LeanCat.DepProdFun f □□ @BaseChangeFun LeanCat.{ℓ} x y f (HasAllPullbacks.HasPullbacksAlong _ _)) := { com := LeanCat.BaseChange_DepProd.Adj.unit_com f , natural := sorry } /-! #brief Left-identity of the BaseChangeFun/LeanCat.DepProdFun adjunction. -/ theorem LeanCat.BaseChange_DepProd.Adj.id_left {x y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom x y) (Y : OverObj LeanCat.{ℓ} y) : OverHom.comp LeanCat x _ _ _ (LeanCat.BaseChange_DepProd.Adj.counit_com f (BaseChangeFun.obj f Y)) (BaseChangeFun.hom f _ _ (LeanCat.BaseChange_DepProd.Adj.unit_com f Y)) = OverHom.id LeanCat x (BaseChangeFun.obj f Y) := sorry /-! #brief Right-identity of the BaseChangeFun/LeanCat.DepProdFun adjunction. -/ theorem LeanCat.BaseChange_DepProd.Adj.id_right {x y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom x y) (X : OverObj LeanCat.{ℓ} x) : OverHom.comp LeanCat y _ _ _ (LeanCat.DepProdFun.hom f (LeanCat.BaseChange_DepProd.Adj.counit_com f X)) (LeanCat.BaseChange_DepProd.Adj.unit_com f (LeanCat.DepProdFun.obj f X)) = OverHom.id LeanCat y (LeanCat.DepProdFun.obj f X) := sorry /-! #brief BaseChangeFun and LeanCat.DepProdFun are adjoint. -/ definition LeanCat.BaseChange_DepProd.Adj {x y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom x y) : Adj (LeanCat.BaseChangeFun f) (LeanCat.DepProdFun f) := { counit := LeanCat.BaseChange_DepProd.Adj.counit f , unit := LeanCat.BaseChange_DepProd.Adj.unit f , id_left := LeanCat.BaseChange_DepProd.Adj.id_left f , id_right := LeanCat.BaseChange_DepProd.Adj.id_right f } /-! #brief LeanCat has dependent product. -/ instance LeanCat.HasDepProd {X Y : LeanCat.{ℓ}^.obj} (f : LeanCat.{ℓ}^.hom X Y) : HasDepProd LeanCat.{ℓ} f := { depprod := LeanCat.DepProdFun f , adj := LeanCat.BaseChange_DepProd.Adj f } /-! #brief LeanCat has all dependent products. -/ instance LeanCat.HasAllDepProd : HasAllDepProd LeanCat.{ℓ} := { has_depprod := λ x y f, LeanCat.HasDepProd f } /- ----------------------------------------------------------------------- Existence of W-types in LeanCat. ----------------------------------------------------------------------- -/ definition LeanCat.DepProdFun.PresCoLimit.hom (P : PolyEndoFun LeanCat.{ℓ}) (ωP : ∀ (a : P^.codom), FinType { b : P^.dom // P^.hom b = a }) (L : Fun NatCat (OverCat LeanCat P^.dom)) : OverHom LeanCat P^.codom ((LeanCat.DepProdFun P^.hom)^.obj (colimit L)) (colimit (LeanCat.DepProdFun P^.hom □□ L)) := sorry definition LeanCat.DepProdFun.PresCoLimit (P : PolyEndoFun LeanCat.{ℓ}) (ωP : ∀ (a : P^.codom), FinType { b : P^.dom // P^.hom b = a }) (L : Fun NatCat (OverCat LeanCat P^.dom)) : PresCoLimit L (LeanCat.DepProdFun P^.hom) := PresCoLimit.show (λ L_HasCoLimit C hom ωhom , let ccone : CoCone (LeanCat.DepProdFun P^.hom □□ L) := CoCone.mk C hom @ωhom in (OverCat LeanCat P^.codom)^.circ ((OverCat LeanCat P^.codom)^.circ (@colimit.univ _ _ _ (LeanCat.Over.HasCoLimit _ _) ccone) (LeanCat.DepProdFun.PresCoLimit.hom P ωP L)) ((LeanCat.DepProdFun P^.hom)^.hom (colimit.iso L_HasCoLimit (LeanCat.Over.HasCoLimit P^.dom L)))) sorry sorry definition LeanCat.HasWType (P : PolyEndoFun LeanCat.{ℓ}) (ωP : ∀ (a : P^.codom), FinType { b : P^.dom // P^.hom b = a }) : HasWType LeanCat P := HasWType.Adamek LeanCat P { pres_colimit := LeanCat.DepProdFun.PresCoLimit P ωP } end qp
6e23209aa6448e734c24bfb7c7229ad067150542
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/products/basic.lean
211fa0c2a29db788410799579aeafebb8e861e80
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
5,179
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import category_theory.eq_to_hom namespace category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation section variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] /-- `prod C D` gives the cartesian product of two categories. -/ instance prod : category.{max v₁ v₂} (C × D) := { hom := λ X Y, ((X.1) ⟶ (Y.1)) × ((X.2) ⟶ (Y.2)), id := λ X, ⟨ 𝟙 (X.1), 𝟙 (X.2) ⟩, comp := λ _ _ _ f g, (f.1 ≫ g.1, f.2 ≫ g.2) } -- rfl lemmas for category.prod @[simp] lemma prod_id (X : C) (Y : D) : 𝟙 (X, Y) = (𝟙 X, 𝟙 Y) := rfl @[simp] lemma prod_comp {P Q R : C} {S T U : D} (f : (P, S) ⟶ (Q, T)) (g : (Q, T) ⟶ (R, U)) : f ≫ g = (f.1 ≫ g.1, f.2 ≫ g.2) := rfl @[simp] lemma prod_id_fst (X : prod C D) : prod.fst (𝟙 X) = 𝟙 X.fst := rfl @[simp] lemma prod_id_snd (X : prod C D) : prod.snd (𝟙 X) = 𝟙 X.snd := rfl @[simp] lemma prod_comp_fst {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).1 = f.1 ≫ g.1 := rfl @[simp] lemma prod_comp_snd {X Y Z : prod C D} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).2 = f.2 ≫ g.2 := rfl end section variables (C : Type u₁) [category.{v₁} C] (D : Type u₁) [category.{v₁} D] /-- `prod.category.uniform C D` is an additional instance specialised so both factors have the same universe levels. This helps typeclass resolution. -/ instance uniform_prod : category (C × D) := category_theory.prod C D end -- Next we define the natural functors into and out of product categories. For now this doesn't -- address the universal properties. namespace prod /-- `sectl C Z` is the functor `C ⥤ C × D` given by `X ↦ (X, Z)`. -/ @[simps] def sectl (C : Type u₁) [category.{v₁} C] {D : Type u₂} [category.{v₂} D] (Z : D) : C ⥤ C × D := { obj := λ X, (X, Z), map := λ X Y f, (f, 𝟙 Z) } /-- `sectr Z D` is the functor `D ⥤ C × D` given by `Y ↦ (Z, Y)` . -/ @[simps] def sectr {C : Type u₁} [category.{v₁} C] (Z : C) (D : Type u₂) [category.{v₂} D] : D ⥤ C × D := { obj := λ X, (Z, X), map := λ X Y f, (𝟙 Z, f) } variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] /-- `fst` is the functor `(X, Y) ↦ X`. -/ @[simps] def fst : C × D ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.1 } /-- `snd` is the functor `(X, Y) ↦ Y`. -/ @[simps] def snd : C × D ⥤ D := { obj := λ X, X.2, map := λ X Y f, f.2 } @[simps] def swap : C × D ⥤ D × C := { obj := λ X, (X.2, X.1), map := λ _ _ f, (f.2, f.1) } @[simps] def symmetry : swap C D ⋙ swap D C ≅ 𝟭 (C × D) := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } def braiding : C × D ≌ D × C := equivalence.mk (swap C D) (swap D C) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) instance swap_is_equivalence : is_equivalence (swap C D) := (by apply_instance : is_equivalence (braiding C D).functor) end prod section variables (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] @[simps] def evaluation : C ⥤ (C ⥤ D) ⥤ D := { obj := λ X, { obj := λ F, F.obj X, map := λ F G α, α.app X, }, map := λ X Y f, { app := λ F, F.map f, naturality' := λ F G α, eq.symm (α.naturality f) } } @[simps] def evaluation_uncurried : C × (C ⥤ D) ⥤ D := { obj := λ p, p.2.obj p.1, map := λ x y f, (x.2.map f.1) ≫ (f.2.app y.1), map_comp' := λ X Y Z f g, begin cases g, cases f, cases Z, cases Y, cases X, simp only [prod_comp, nat_trans.comp_app, functor.map_comp, category.assoc], rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app, category.assoc, nat_trans.naturality], end } end variables {A : Type u₁} [category.{v₁} A] {B : Type u₂} [category.{v₂} B] {C : Type u₃} [category.{v₃} C] {D : Type u₄} [category.{v₄} D] namespace functor /-- The cartesian product of two functors. -/ @[simps] def prod (F : A ⥤ B) (G : C ⥤ D) : A × C ⥤ B × D := { obj := λ X, (F.obj X.1, G.obj X.2), map := λ _ _ f, (F.map f.1, G.map f.2) } /- Because of limitations in Lean 3's handling of notations, we do not setup a notation `F × G`. You can use `F.prod G` as a "poor man's infix", or just write `functor.prod F G`. -/ end functor namespace nat_trans /-- The cartesian product of two natural transformations. -/ @[simps] def prod {F G : A ⥤ B} {H I : C ⥤ D} (α : F ⟶ G) (β : H ⟶ I) : F.prod H ⟶ G.prod I := { app := λ X, (α.app X.1, β.app X.2), naturality' := λ X Y f, begin cases X, cases Y, simp only [functor.prod_map, prod.mk.inj_iff, prod_comp], split; rw naturality end } /- Again, it is inadvisable in Lean 3 to setup a notation `α × β`; use instead `α.prod β` or `nat_trans.prod α β`. -/ end nat_trans end category_theory
af607d62a4aa986c006c1572bffbe9d36e2fdb1a
b074a51e20fdb737b2d4c635dd292fc54685e010
/src/data/list/basic.lean
121ee9293e0ca2ede3c69f73ea495635c89295b0
[ "Apache-2.0" ]
permissive
minchaowu/mathlib
2daf6ffdb5a56eeca403e894af88bcaaf65aec5e
879da1cf04c2baa9eaa7bd2472100bc0335e5c73
refs/heads/master
1,609,628,676,768
1,564,310,105,000
1,564,310,105,000
99,461,307
0
0
null
null
null
null
UTF-8
Lean
false
false
212,882
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Basic properties of lists. -/ import tactic.interactive tactic.mk_iff_of_inductive_prop logic.basic logic.function logic.relator algebra.group order.basic data.list.defs data.nat.basic data.option.basic data.bool data.prod data.fin open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ @[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe @[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /- mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] /- bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [mem_cons_iff, forall_mem_cons'] theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) @[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /- list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ /- append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t := by {induction s with b s H generalizing a, refl, simp only [foldl, cons_append], rw H _} theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s := by {induction s with b s H generalizing a, refl, simp only [foldr, cons_append], rw H _} @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_left h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_right' h rfl theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /- join -/ attribute [simp] join theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] /- repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] /- bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append {α β} (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ /- concat -/ @[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl @[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by induction l; intro h; contradiction @[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by induction l₁; simp only [*, cons_append, concat]; split; refl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl @[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by induction l₂ with b l₂ ih; simp only [concat_eq_append, nil_append, cons_append, append_assoc] /- reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl theorem reverse_injective : injective (@reverse α) := injective_of_left_inverse reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /- last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, refl} /- map -/ lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α) (h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l := by revert a; induction l; intros; [refl, simp only [*, foldl]] theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α) (h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l := by revert a; induction l; intros; [refl, simp only [*, foldr]] theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl /- map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /- sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_app_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact append_sublist_append_of_sublist_right ih [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp only [reverse_reverse] at this; assumption, reverse_sublist⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp only [reverse_append, append_sublist_append_left, reverse_sublist_iff] at this; assumption, λ h, append_sublist_append_of_sublist_right h l⟩ theorem append_sublist_append {α} {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (append_sublist_append_of_sublist_right hl _).trans ((append_sublist_append_left _).2 hr) theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (subset_of_sublist s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ subset_of_sublist s theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /- index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /- nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_ge_len (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_ge_len hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < n) : (list.repeat a n).nth_le m (by rwa list.length_repeat) = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] @[simp] lemma nth_concat_length: ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[extensionality] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])] @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) end insert_nth /- take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_ge (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_all (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by simp, by simpa [take_cons, h] using drop_take m n l theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /- foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /- mfoldl, mfoldr -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl variables [is_lawful_monad m] @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /- sum -/ attribute [to_additive list.sum] list.prod attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1 section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive list.sum_nil] theorem prod_nil : ([] : list α).prod = 1 := rfl @[simp, to_additive list.sum_cons] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive list.sum_append] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive list.sum_join] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] end monoid @[simp, to_additive list.sum_erase] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] /- lexicographic ordering -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {} {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /- all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /- map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach {α} (L : list α) : L.attach.length = L.length := length_pmap /- find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end @[simp] theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /- lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /- filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem map_sublist_map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s /- filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := subset_of_sublist $ filter_sublist l theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /- count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append @[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by rw [concat_eq_append, count_append, count_singleton] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /- prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ @[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] @[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp only [concat_eq_append, prefix_append] theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_left_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_left_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /- sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s, { simp only [sublists'_nil, mem_singleton], exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, simp only [sublists'_cons, mem_append, IH, mem_map], split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ h }, { exact cons_sublist_cons _ h }, { cases h with _ _ _ h s _ _ h, { exact or.inl h }, { exact or.inr ⟨s, h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, pow_succ, mul_succ, mul_zero, zero_add] @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc] theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih, {refl}, simp only [ih, foldr_cons] end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil] | (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := rfl | (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l] theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind], congr, funext x, apply congr_arg _, rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map, map_eq_map, map_id' (append_nil), append_nil] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l with hd tl ih; [refl, simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro, {rwa foldr}, simp only [foldr, mem_cons_iff, false_or, not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp only [map, map_append, sublists_concat]; exact ((append_sublist_append_left _).2 $ singleton_sublist.2 $ mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans ((append_sublist_append_right _).2 IH) /- sublists_len -/ def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β | 0 l f r := f [] :: r | (n+1) [] f r := r | (n+1) (a::l) f r := sublists_len_aux (n + 1) l f (sublists_len_aux n l (f ∘ list.cons a) r) def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) := sublists_len_aux n l id [] lemma sublists_len_aux_append {α β γ : Type*} : ∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ), sublists_len_aux n l (g ∘ f) (r.map g ++ s) = (sublists_len_aux n l f r).map g ++ s | 0 l f g r s := rfl | (n+1) [] f g r s := rfl | (n+1) (a::l) f g r s := begin unfold sublists_len_aux, rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl, sublists_len_aux_append, sublists_len_aux_append] end lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) : sublists_len_aux n l f r = (sublists_len n l).map f ++ r := by rw [sublists_len, ← sublists_len_aux_append]; refl lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) : sublists_len_aux 0 l f r = f [] :: r := by cases l; refl @[simp] lemma sublists_len_zero {α : Type*} (l : list α) : sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _ @[simp] lemma sublists_len_succ_nil {α : Type*} (n) : sublists_len (n+1) (@nil α) = [] := rfl @[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) : sublists_len (n + 1) (a::l) = sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) := by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq, sublists_len_aux_eq, map_id, append_nil]; refl @[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α), length (sublists_len n l) = nat.choose (length l) n | 0 l := by simp | (n+1) [] := by simp | (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α), sublists_len n l <+ sublists' l | 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _)) | (n+1) [] := nil_sublist _ | (n+1) (a::l) := begin rw [sublists_len_succ_cons, sublists'_cons], exact append_sublist_append (sublists_len_sublist_sublists' _ _) (map_sublist_map _ (sublists_len_sublist_sublists' _ _)) end lemma sublists_len_sublist_of_sublist {α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl}, { refine IH.trans _, rw sublists_len_succ_cons, apply sublist_append_left }, { simp [sublists_len_succ_cons], exact append_sublist_append IH (map_sublist_map _ (IHn s)) } end lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α}, l' ∈ sublists_len n l → length l' = n | 0 l l' (or.inl rfl) := rfl | (n+1) (a::l) l' h := begin rw [sublists_len_succ_cons, mem_append, mem_map] at h, rcases h with h | ⟨l', h, rfl⟩, { exact length_of_sublists_len h }, { exact congr_arg (+1) (length_of_sublists_len h) }, end lemma mem_sublists_len_self {α : Type*} {l l' : list α} (h : l' <+ l) : l' ∈ sublists_len (length l') l := begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH, { exact or.inl rfl }, { cases l₁ with b l₁, { exact or.inl rfl }, { rw [length, sublists_len_succ_cons], exact mem_append_left _ IH } }, { rw [length, sublists_len_succ_cons], exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) } end @[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} : l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n := ⟨λ h, ⟨mem_sublists'.1 (subset_of_sublist (sublists_len_sublist_sublists' _ _) h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩ /- forall₂ -/ section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff @[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} : forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := ⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩ theorem forall₂.imp {R S : α → β → Prop} (H : ∀ a b, R a b → S a b) {l₁ l₂} (h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ := by induction h; constructor; solve_by_elim lemma forall₂.mp {r q s : α → β → Prop} (h : ∀a b, r a b → q a b → s a b) : ∀{l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂ | [] [] forall₂.nil forall₂.nil := forall₂.nil | (a::l₁) (b::l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) := forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs) lemma forall₂.flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l | [] _ := forall₂.nil | (a::as) h := forall₂.cons (h _ (mem_cons_self _ _)) (forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha) lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l := forall₂_same $ assume a h, is_refl.refl _ _ lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) := begin funext a b, apply propext, split, { assume h, induction h, {refl}, simp only [*]; split; refl }, { assume h, subst h, exact forall₂_refl _ } end @[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ @[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_cons_right_iff {b l u} : forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} : ∀l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀a∈l, p a) ∧ forall₂ r l u | [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and] | (a::l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons, and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm] @[simp] lemma forall₂_map_left_iff {f : γ → α} : ∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u | [] _ := by simp only [map, forall₂_nil_left_iff] | (a::l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff] @[simp] lemma forall₂_map_right_iff {f : γ → β} : ∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u | _ [] := by simp only [map, forall₂_nil_right_iff] | _ (b::u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff] lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r) | a₀ nil a₁ forall₂.nil forall₂.nil := rfl | (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r) | nil a₀ a₁ forall₂.nil forall₂.nil := rfl | (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) := ⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩ theorem forall₂_length_eq {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂ | _ _ forall₂.nil := rfl | _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂) theorem forall₂_zip {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b | _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁ | _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃ theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b := ⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩, λ h, begin cases h with h₁ h₂, induction l₁ with a l₁ IH generalizing l₂, { cases length_eq_zero.1 h₁.symm, constructor }, { cases l₂ with b l₂; injection h₁ with h₁, exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) } end⟩ theorem forall₂_take {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂) | 0 _ _ _ := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n] theorem forall₂_drop {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂) | 0 _ _ h := by simp only [drop, h] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n] theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ := have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h, by rwa [take_left] at h' theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ := have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h, by rwa [drop_left] at h' lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp only [not_mem_nil] | a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂) lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map | f g h [] [] forall₂.nil := forall₂.nil | f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂) lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append | [] [] h l₁ l₂ hl := hl | (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl) lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join | [] [] forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂) lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind := assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁) lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs) lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : (r ⇒ (↔)) p q) : (forall₂ r ⇒ forall₂ r) (filter p) (filter q) | _ _ forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := begin by_cases p a, { have : q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], }, end theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { rw filter_map_cons_none _ _ eq }, { rw filter_map_cons_some _ _ _ eq }, end lemma rel_filter_map {f : α → option γ} {q : β → option δ} : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive list.rel_sum] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := assume a b, rel_foldl (assume a b, hf) h end forall₂ /- sections -/ theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L := begin refine ⟨λ h, _, λ h, _⟩, { induction L generalizing f, {cases mem_singleton.1 h, exact forall₂.nil}, simp only [sections, bind_eq_bind, mem_bind, mem_map] at h, rcases h with ⟨_, _, _, _, rfl⟩, simp only [*, forall₂_cons, true_and] }, { induction h with a l f L al fL fs, {exact or.inl rfl}, simp only [sections, bind_eq_bind, mem_bind, mem_map], exact ⟨_, fs, _, al, rfl, rfl⟩ } end theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L := forall₂_length_eq (mem_sections.1 h) lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections | _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil | _ _ (forall₂.cons h₀ h₁) := rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀) /- permutations -/ section permutations @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl end permutations /- insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) @[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /- erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := subset_of_sublist (erasep_sublist l) theorem erasep_sublist_erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /- erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := subset_of_sublist (erase_sublist a l) theorem erase_sublist_erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact erasep_sublist_erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /- diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := subset_of_sublist $ diff_sublist _ _ theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem diff_sublist_of_sublist : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, diff_sublist_of_sublist (erase_sublist_erase _ h)] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (erase_sublist_erase b h) end diff /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := (zip_nil_right _).symm | l₁ [] := by rw zip_nil_right; refl | (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := rfl | l₁ [] := by simp only [length, zip_nil_right, min_zero] | (a::l₁) (b::l₂) := by by simp only [length, zip_cons_cons, length_zip l₁ l₂, min_add_add_right] theorem zip_append : ∀ {l₁ l₂ r₁ r₂ : list α} (h : length l₁ = length l₂), zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ | [] l₂ r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl | l₁ [] r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl | (a::l₁) (b::l₂) r₁ r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ_inj h)]; split; refl theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g) | [] l₂ := rfl | l₁ [] := by simp only [map, zip_nil_right] | (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) : zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) := by rw [← zip_map, map_id] theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) : zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) := by rw [← zip_map, map_id] theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α), zip (l.map f) (l.map g) = l.map (λ a, (f a, g a)) | [] := rfl | (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ | (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩ | (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h] @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd) | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp only [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp only [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁ | [] l₂ h := rfl | l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl | (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) : (unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)] @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := unzip_zip (length_reverse l).symm @[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l := by rw [← unzip_left, unzip_revzip] @[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse := by rw [← unzip_right, unzip_revzip] theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip] theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse := by simp [revzip] /- enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : Π {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := by { simp [enum_from,mem_enum_from ys], rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply lt_of_lt_of_le (nat.lt_add_of_pos_right zero_lt_one), apply nat.add_le_add_left, apply nat.le_add_right }, { replace h := mem_enum_from _ h, simp at h, revert h, apply and_implies _ (and_implies id or.inr), intro h, transitivity j+1, apply nat.le_add_right, exact h } } /- product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /- sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /- of_fn -/ theorem length_of_fn_aux {n} (f : fin n → α) : ∀ m h l, length (of_fn_aux f m h l) = length l + m | 0 h l := rfl | (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _) @[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) theorem nth_of_fn_aux {n} (f : fin n → α) (i) : ∀ m h l, (∀ i, nth l i = of_fn_nth_val f (i + m)) → nth (of_fn_aux f m h l) i = of_fn_nth_val f i | 0 h l H := H i | (succ m) h l H := nth_of_fn_aux m _ _ begin intro j, cases j with j, { simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] }, { simp only [nth, H, succ_add] } end @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = of_fn_nth_val f i := nth_of_fn_aux f _ _ _ _ $ λ i, by simp only [of_fn_nth_val, dif_neg (not_lt.2 (le_add_left n i))]; refl @[simp] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) : nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i := option.some.inj $ by rw [← nth_le_nth]; simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.2] theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read := suffices ∀ {m h l}, d_array.rev_iterate_aux a (λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, simp only [d_array.rev_iterate_aux, of_fn_aux, IH] end theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl theorem of_fn_succ {n} (f : fin (succ n) → α) : of_fn f = f 0 :: of_fn (λ i, f i.succ) := suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l = f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, rw [of_fn_aux, IH], refl end theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l | [] := rfl | (a::l) := by rw of_fn_succ; congr; simp only [fin.succ_val]; exact of_fn_nth_le l /- disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /- union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /- inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter /- bag_inter -/ section bag_inter variable [decidable_eq α] @[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] := by cases l; refl @[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] := by cases l; refl @[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) : (a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) := by cases l₂; exact if_pos h @[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) : (a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ := begin cases l₂, {simp only [bag_inter_nil]}, simp only [erase_of_not_mem h, list.bag_inter, if_neg h] end @[simp] theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ | [] l₂ := by simp only [nil_bag_inter, not_mem_nil, false_and] | (b::l₁) l₂ := begin by_cases b ∈ l₂, { rw [cons_bag_inter_of_pos _ h, mem_cons_iff, mem_cons_iff, mem_bag_inter], by_cases ba : a = b, { simp only [ba, h, eq_self_iff_true, true_or, true_and] }, { simp only [mem_erase_of_ne ba, ba, false_or] } }, { rw [cons_bag_inter_of_neg _ h, mem_bag_inter, mem_cons_iff, or_and_distrib_right], symmetry, apply or_iff_right_of_imp, rintro ⟨rfl, h'⟩, exact h.elim h' } end @[simp] theorem count_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, count a (l₁.bag_inter l₂) = min (count a l₁) (count a l₂) | [] l₂ := by simp | l₁ [] := by simp | (h₁ :: l₁) (h₂ :: l₂) := begin simp only [list.bag_inter, list.mem_cons_iff], by_cases p₁ : h₂ = h₁; by_cases p₂ : h₁ = a, { simp only [p₁, p₂, count_bag_inter, min_succ_succ, erase_cons_head, if_true, mem_cons_iff, count_cons_self, true_or, eq_self_iff_true] }, { simp only [p₁, ne.symm p₂, count_bag_inter, count_cons, erase_cons_head, if_true, mem_cons_iff, true_or, eq_self_iff_true, if_false] }, { rw p₂ at p₁, by_cases p₃ : a ∈ l₂, { simp only [p₁, ne.symm p₁, p₂, p₃, erase_cons, count_bag_inter, eq.symm (min_succ_succ _ _), succ_pred_eq_of_pos (count_pos.2 p₃), if_true, mem_cons_iff, false_or, count_cons_self, eq_self_iff_true, if_false, ne.def, not_false_iff, count_erase_self, list.count_cons_of_ne] }, { simp [ne.symm p₁, p₂, p₃] } }, { by_cases p₄ : h₁ ∈ l₂; simp only [ne.symm p₁, ne.symm p₂, p₄, count_bag_inter, if_true, if_false, mem_cons_iff, false_or, eq_self_iff_true, ne.def, not_false_iff,count_erase_of_ne, count_cons_of_ne] } end theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁ | [] l₂ := by simp [nil_sublist] | (b::l₁) l₂ := begin by_cases b ∈ l₂; simp [h], { apply cons_sublist_cons, apply bag_inter_sublist_left }, { apply sublist_cons_of_sublist, apply bag_inter_sublist_left } end theorem bag_inter_nil_iff_inter_nil : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ = [] ↔ l₁ ∩ l₂ = [] | [] l₂ := by simp | (b::l₁) l₂ := begin by_cases h : b ∈ l₂; simp [h], exact bag_inter_nil_iff_inter_nil l₁ l₂ end end bag_inter /- pairwise relation (generalized no duplicate) -/ section pairwise run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pairwise_iff variable {R : α → α → Prop} theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp only [pairwise.nil, pairwise_cons] at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; [exact pairwise.nil, simp only [*, pairwise_cons, forall_2_true_iff, and_true]] theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i) theorem forall_of_forall_of_pairwise (H : symmetric R) {l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) : ∀ (x ∈ l) (y ∈ l), R x y := begin induction l with a l IH, { exact forall_mem_nil _ }, cases forall_mem_cons.1 H₁ with H₁₁ H₁₂, cases pairwise_cons.1 H₂ with H₂₁ H₂₂, rintro x (rfl | hx) y (rfl | hy), exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy] end lemma forall_of_pairwise (H : symmetric R) {l : list α} (hl : pairwise R l) : (∀a∈l, ∀b∈l, a ≠ b → R a b) := forall_of_forall_of_pairwise (λ a b h hne, H (h hne.symm)) (λ _ _ h, (h rfl).elim) (pairwise.imp (λ _ _ h _, h) hl) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append], simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]] theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp only [map, pairwise.nil] | (b::l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'], by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map] theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp only [option.mem_def], induction l with a l IH, { simp only [filter_map, pairwise.nil] }, cases e : f a with b, { rw [filter_map_cons_none _ _ e, IH, pairwise_cons], simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] }, rw [filter_map_cons_some _ _ _ e], simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'], end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons], simp only [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH, pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h] theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (not_lt_zero j).elim h | (a::l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (not_lt_zero _).elim h₂}, cases i with i, { exact H.1 _ (nth_le_mem l _ _) }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ pairwise.nil := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this /- pairwise reduct -/ variable [decidable_rel R] @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_map (f : β → α) : Π (l : list β), pw_filter R (map f l) = map f (pw_filter (λ x y, R (f x) (f y)) l) | [] := rfl | (x :: xs) := if h : ∀ b ∈ pw_filter R (map f xs), R (f x) b then have h' : ∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ b hb, h _ (by rw [pw_filter_map]; apply mem_map_of_mem _ hb), by rw [map,pw_filter_cons_of_pos h,pw_filter_cons_of_pos h',pw_filter_map,map] else have h' : ¬∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ hh, h $ λ a ha, by { rw [pw_filter_map,mem_map] at ha, rcases ha with ⟨b,hb₀,hb₁⟩, subst a, exact hh _ hb₀, }, by rw [map,pw_filter_cons_of_neg h,pw_filter_cons_of_neg h',pw_filter_map] theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := subset_of_sublist (pw_filter_sublist _) theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {refl}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH, { exact λ _ _, false.elim }, simp only [forall_mem_cons], by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end pairwise /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ section chain run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff variable {R : α → α → Prop} theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := by induction p with _ a b l r p IH; constructor; [exact H _ _ r, exact IH] theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp only [chain_cons, chain.nil, and_true] theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp only [map, chain.nil, chain_cons, *] theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, IH r'⟩ end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {exact pairwise_singleton _ _}, apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem {S : α → α → Prop} : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x::l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ theorem chain'_singleton (a : α) : chain' R [a] := chain.nil theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔ chain' R (l₁++[a]) ∧ chain' R (a::l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b::l₁) l₂ := chain_split theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R l := ((chain'_map f).1 p).imp H theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem chain'_of_pairwise : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a::l) h := chain_of_pairwise h theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a::l) := chain_iff_pairwise tr end chain /- no duplicates predicate -/ section nodup @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_nil : @nodup α [] := pairwise.nil @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp only [nodup, pairwise_cons, forall_mem_ne] lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp only [nodup_nil] | _ _ (forall₂.cons hab h) := by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin induction l with a l IH; intro h, {exact nodup_nil}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1 | 0 := by simp [nat.zero_le] | 1 := by simp | (n+2) := iff_of_false (λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (le_add_left 2 n))) (not_le_of_lt $ le_add_left 2 n) @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp only [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp only [nodup_append, and.left_comm, disjoint_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) := nodup_map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup_of_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm] theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH, {refl}, by_cases b = a, { subst h, rw [erase_cons_head, filter_cons_of_neg], symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl }, { rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h } end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem nodup_diff [decidable_eq α] : ∀ {l₁ l₂ : list α} (h : l₁.nodup), (l₁.diff l₂).nodup | l₁ [] h := h | l₁ (a::l₂) h := by rw diff_cons; exact nodup_diff (nodup_erase_of_nodup _ h) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp only [mem_filter, and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, forall_eq'] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂, d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := if h' : a ∈ l then by rw [insert_of_mem h']; exact h else by rw [insert_of_not_mem h', nodup_cons]; split; assumption theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] lemma nodup_sublists_len {α : Type*} (n) {l : list α} (nd : nodup l) : (sublists_len n l).nodup := nodup_of_sublist (sublists_len_sublist_sublists' _ _) (nodup_sublists'.2 nd) lemma diff_eq_filter_of_nodup [decidable_eq α] : ∀ {l₁ l₂ : list α} (hl₁ : l₁.nodup), l₁.diff l₂ = l₁.filter (∉ l₂) | l₁ [] hl₁ := by simp | l₁ (a::l₂) hl₁ := begin rw [diff_cons, diff_eq_filter_of_nodup (nodup_erase_of_nodup _ hl₁), nodup_erase_eq_filter _ hl₁, filter_filter], simp only [mem_cons_iff, not_or_distrib, and.comm], congr end lemma mem_diff_iff_of_nodup [decidable_eq α] {l₁ l₂ : list α} (hl₁ : l₁.nodup) {a : α} : a ∈ l₁.diff l₂ ↔ a ∈ l₁ ∧ a ∉ l₂ := by rw [diff_eq_filter_of_nodup hl₁, mem_filter] lemma nodup_update_nth : ∀ {l : list α} {n : ℕ} {a : α} (hl : l.nodup) (ha : a ∉ l), (l.update_nth n a).nodup | [] n a hl ha := nodup_nil | (b::l) 0 a hl ha := nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩ | (b::l) (n+1) a hl ha := nodup_cons.2 ⟨λ h, (mem_or_eq_of_mem_update_nth h).elim (nodup_cons.1 hl).1 (λ hba, ha (hba ▸ mem_cons_self _ _)), nodup_update_nth (nodup_cons.1 hl).2 (mt (mem_cons_of_mem _) ha)⟩ end nodup /- erase duplicates function -/ section erase_dup variable [decidable_eq α] @[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) : erase_dup (a::l) = erase_dup l := pw_filter_cons_of_neg $ by simpa only [forall_mem_ne] using h theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) : erase_dup (a::l) = a :: erase_dup l := pw_filter_cons_of_pos $ by simpa only [forall_mem_ne] using h @[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l := by simpa only [erase_dup, forall_mem_ne, not_not] using not_congr (@forall_mem_pw_filter α (≠) _ (λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l) @[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) : erase_dup (a::l) = erase_dup l := erase_dup_cons_of_mem' $ mem_erase_dup.2 h @[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) : erase_dup (a::l) = a :: erase_dup l := erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l := λ a, mem_erase_dup.2 theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self @[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l := pw_filter_idempotent theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ := begin induction l₁ with a l₁ IH, {refl}, rw [cons_union, ← IH], show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)), by_cases a ∈ erase_dup (l₁ ++ l₂); [ rw [erase_dup_cons_of_mem' h, insert_of_mem h], rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]] end end erase_dup /- iota and range(') -/ @[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n | s 0 := rfl | s (n+1) := congr_arg succ (length_range' _ _) @[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n | s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1 | s (succ n) := have m = s → m < s + n + 1, from λ e, e ▸ lt_succ_of_le (le_add_right _ _), have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m, by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm, (mem_cons_iff _ _ _).trans $ by simp only [mem_range', or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n | s 0 := rfl | s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n) theorem map_sub_range' (a) : ∀ (s n : ℕ) (h : a ≤ s), map (λ x, x - a) (range' s n) = range' (s - a) n | s 0 _ := rfl | s (n+1) h := begin convert congr_arg (cons (s-a)) (map_sub_range' (s+1) n (nat.le_succ_of_le h)), rw nat.succ_sub h, refl, end theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) @[simp] theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa only [length_range'] using length_le_of_sublist h, λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩ theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n := ⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $ (mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2, λ h, subset_of_sublist (range'_sublist_right.2 h)⟩ theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m) | s 0 (n+1) _ := rfl | s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] := by rw add_comm n 1; exact (range'_append s n 1).symm theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s) | 0 n := rfl | (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1) theorem range_eq_range' (n : ℕ) : range n = range' 0 n := (range_core_range' n 0).trans $ by rw zero_add theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) := by rw [range_eq_range', range_eq_range', range', add_comm, ← map_add_range']; congr; exact funext one_add theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) := by rw [range_eq_range', map_add_range']; refl @[simp] theorem length_range (n : ℕ) : length (range n) = n := by simp only [range_eq_range', length_range'] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp only [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp only [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp only [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp only [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add] @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := mt mem_range.1 $ lt_irrefl _ theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m := by simp only [range_eq_range', nth_range' _ h, zero_add] theorem range_concat (n : ℕ) : range (succ n) = range n ++ [n] := by simp only [range_eq_range', range'_concat, zero_add] theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp only [iota_eq_reverse_range', length_reverse, length_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff] theorem reverse_range' : ∀ s n : ℕ, reverse (range' s n) = map (λ i, s + n - 1 - i) (range n) | s 0 := rfl | s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map]; simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘), λ a i, show a - 1 - i = a - succ i, from pred_sub _ _, reverse_singleton, map_cons, nat.sub_zero, cons_append, nil_append, eq_self_iff_true, true_and, map_map] using reverse_range' s n def fin_range (n : ℕ) : list (fin n) := (range n).pmap fin.mk (λ _, list.mem_range.1) @[simp] lemma mem_fin_range {n : ℕ} (a : fin n) : a ∈ fin_range n := mem_pmap.2 ⟨a.1, mem_range.2 a.2, fin.eta _ _⟩ lemma nodup_fin_range (n : ℕ) : (fin_range n).nodup := nodup_pmap (λ _ _ _ _, fin.veq_of_eq) (nodup_range _) @[simp] lemma length_fin_range (n : ℕ) : (fin_range n).length = n := by rw [fin_range, length_pmap, length_range] @[to_additive list.sum_range_succ] theorem prod_range_succ {α : Type u} [monoid α] (f : ℕ → α) (n : ℕ) : ((range n.succ).map f).prod = ((range n).map f).prod * f n := by rw [range_concat, map_append, map_singleton, prod_append, prod_cons, prod_nil, mul_one] /-- `Ico n m` is the list of natural numbers `n ≤ x < m`. (Ico stands for "interval, closed-open".) See also `data/set/intervals.lean` for `set.Ico`, modelling intervals in general preorders, and `multiset.Ico` and `finset.Ico` for `n ≤ x < m` as a multiset or as a finset. @TODO (anyone): Define `Ioo` and `Icc`, state basic lemmas about them. @TODO (anyone): Prove that `finset.Ico` and `set.Ico` agree. @TODO (anyone): Also do the versions for integers? @TODO (anyone): One could generalise even further, defining 'locally finite partial orders', for which `set.Ico a b` is `[finite]`, and 'locally finite total orders', for which there is a list model. -/ def Ico (n m : ℕ) : list ℕ := range' n (m - n) namespace Ico theorem zero_bot (n : ℕ) : Ico 0 n = range n := by rw [Ico, nat.sub_zero, range_eq_range'] @[simp] theorem length (n m : ℕ) : length (Ico n m) = m - n := by dsimp [Ico]; simp only [length_range'] theorem pairwise_lt (n m : ℕ) : pairwise (<) (Ico n m) := by dsimp [Ico]; simp only [pairwise_lt_range'] theorem nodup (n m : ℕ) : nodup (Ico n m) := by dsimp [Ico]; simp only [nodup_range'] @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := suffices n ≤ l ∧ l < n + (m - n) ↔ n ≤ l ∧ l < m, by simp [Ico, this], begin cases le_total n m with hnm hmn, { rw [nat.add_sub_of_le hnm] }, { rw [nat.sub_eq_zero_of_le hmn, add_zero], exact and_congr_right (assume hnl, iff.intro (assume hln, (not_le_of_gt hln hnl).elim) (assume hlm, lt_of_lt_of_le hlm hmn)) } end theorem eq_nil_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = [] := by simp [Ico, nat.sub_eq_zero_of_le h] theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := by rw [Ico, Ico, map_add_range', nat.add_sub_add_right, add_comm n k] theorem map_sub (n m k : ℕ) (h₁ : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := begin by_cases h₂ : n < m, { rw [Ico, Ico], rw nat.sub_sub_sub_cancel_right h₁, rw [map_sub_range' _ _ _ h₁] }, { simp at h₂, rw [eq_nil_of_le h₂], rw [eq_nil_of_le (nat.sub_le_sub_right h₂ _)], refl } end @[simp] theorem self_empty {n : ℕ} : Ico n n = [] := eq_nil_of_le (le_refl n) @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = [] ↔ m ≤ n := iff.intro (assume h, nat.le_of_sub_eq_zero $ by rw [← length, h]; refl) eq_nil_of_le lemma append_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ++ Ico m l = Ico n l := begin dunfold Ico, convert range'_append _ _ _, { exact (nat.add_sub_of_le hnm).symm }, { rwa [← nat.add_sub_assoc hnm, nat.sub_add_cancel] } end @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = [] := begin apply eq_nil_iff_forall_not_mem.2, intro a, simp only [and_imp, not_and, not_lt, list.mem_inter, list.Ico.mem], intros h₁ h₂ h₃, exfalso, exact not_lt_of_ge h₃ h₂ end @[simp] lemma bag_inter_consecutive (n m l : ℕ) : list.bag_inter (Ico n m) (Ico m l) = [] := (bag_inter_nil_iff_inter_nil _ _).2 (inter_consecutive n m l) @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = [n] := by dsimp [Ico]; simp [nat.add_sub_cancel_left] theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] := by rwa [← succ_singleton, append_consecutive]; exact nat.le_succ _ theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := by rw [← append_consecutive (nat.le_succ n) h, succ_singleton]; refl @[simp] theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = [m - 1] := by dsimp [Ico]; rw nat.sub_sub_self h; simp theorem chain'_succ (n m : ℕ) : chain' (λa b, b = succ a) (Ico n m) := begin by_cases n < m, { rw [eq_cons h], exact chain_succ_range' _ _ }, { rw [eq_nil_of_le (le_of_not_gt h)], trivial } end @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := by simp; intros; refl lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := filter_eq_self.2 $ assume k hk, lt_of_lt_of_le (mem.1 hk).2 hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = [] := filter_eq_nil.2 $ assume k hk, not_lt_of_le $ le_trans hln $ (mem.1 hk).1 lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := begin cases le_total n l with hnl hln, { rw [← append_consecutive hnl hlm, filter_append, filter_lt_of_top_le (le_refl l), filter_lt_of_le_bot (le_refl l), append_nil] }, { rw [eq_nil_of_le hln, filter_lt_of_le_bot hln] } end @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := begin cases le_total m l with hml hlm, { rw [min_eq_left hml, filter_lt_of_top_le hml] }, { rw [min_eq_right hlm, filter_lt_of_ge hlm] } end lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := filter_eq_self.2 $ assume k hk, le_trans hln (mem.1 hk).1 lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = [] := filter_eq_nil.2 $ assume k hk, not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml) lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := begin cases le_total l m with hlm hml, { rw [← append_consecutive hnl hlm, filter_append, filter_ge_of_top_le (le_refl l), filter_ge_of_le_bot (le_refl l), nil_append] }, { rw [eq_nil_of_le hml, filter_ge_of_top_le hml] } end @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (_root_.max n l) m := begin cases le_total n l with hnl hln, { rw [max_eq_right hnl, filter_ge_of_ge hnl] }, { rw [max_eq_left hln, filter_ge_of_le_bot hln] } end end Ico @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp only [enum, enum_from_map_fst, range_eq_range'] theorem last'_mem {α} : ∀ a l, @last' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (last'_mem b l) @[simp] lemma nth_le_attach {α} (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val @[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) : nth_le (range n) i H = i := option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)] theorem of_fn_eq_pmap {α n} {f : fin n → α} : of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) := by rw [pmap_eq_map_attach]; from ext_le (by simp) (λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩]) theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) : nodup (of_fn f) := by rw of_fn_eq_pmap; from nodup_pmap (λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n) section tfae /- tfae: The Following (propositions) Are Equivalent -/ theorem tfae_nil : tfae [] := forall_mem_nil _ theorem tfae_singleton (p) : tfae [p] := by simp [tfae] theorem tfae_cons_of_mem {a b} {l : list Prop} (h : b ∈ l) : tfae (a::l) ↔ (a ↔ b) ∧ tfae l := ⟨λ H, ⟨H a (by simp) b (or.inr h), λ p hp q hq, H _ (or.inr hp) _ (or.inr hq)⟩, begin rintro ⟨ab, H⟩ p (rfl | hp) q (rfl | hq), { refl }, { exact ab.trans (H _ h _ hq) }, { exact (ab.trans (H _ h _ hp)).symm }, { exact H _ hp _ hq } end⟩ theorem tfae_cons_cons {a b} {l : list Prop} : tfae (a::b::l) ↔ (a ↔ b) ∧ tfae (b::l) := tfae_cons_of_mem (or.inl rfl) theorem tfae_of_forall (b : Prop) (l : list Prop) (h : ∀ a ∈ l, a ↔ b) : tfae l := λ a₁ h₁ a₂ h₂, (h _ h₁).trans (h _ h₂).symm theorem tfae_of_cycle {a b} {l : list Prop} : list.chain (→) a (b::l) → (last' b l → a) → tfae (a::b::l) := begin induction l with c l IH generalizing a b; simp [tfae_cons_cons, tfae_singleton] at *, { intros a _ b, exact iff.intro a b }, intros ab bc ch la, have := IH bc ch (ab ∘ la), exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (last'_mem _ _)).1 ∘ bc⟩, this⟩ end theorem tfae.out {l} (h : tfae l) (n₁ n₂) (h₁ : n₁ < list.length l . tactic.exact_dec_trivial) (h₂ : n₂ < list.length l . tactic.exact_dec_trivial) : list.nth_le l n₁ h₁ ↔ list.nth_le l n₂ h₂ := h _ (list.nth_le_mem _ _ _) _ (list.nth_le_mem _ _ _) end tfae lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n := by simp [rotate] @[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; refl @[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate] @[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl @[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate'] @[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length | [] n := rfl | (a::l) 0 := rfl | (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp lemma rotate'_eq_take_append_drop : ∀ {l : list α} {n : ℕ}, n ≤ l.length → l.rotate' n = l.drop n ++ l.take n | [] n h := by simp [drop_append_of_le_length h] | l 0 h := by simp [take_append_of_le_length h] | (a::l) (n+1) h := have hnl : n ≤ l.length, from le_of_succ_le_succ h, have hnl' : n ≤ (l ++ [a]).length, by rw [length_append, length_cons, list.length, zero_add]; exact (le_of_succ_le h), by rw [rotate'_cons_succ, rotate'_eq_take_append_drop hnl', drop, take, drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m) | (a::l) 0 m := by simp | [] n m := by simp | (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ] @[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l := by rw rotate'_eq_take_append_drop (le_refl _); simp @[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l | 0 := by simp | (n+1) := calc l.rotate' (l.length * (n + 1)) = (l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length : by simp [-rotate'_length, nat.mul_succ, rotate'_rotate'] ... = l : by rw [rotate'_length, rotate'_length_mul] lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n := calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul ... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div] lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n := if h : l.length = 0 then by simp [length_eq_zero, *] at * else by rw [← rotate'_mod, rotate'_eq_take_append_drop (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))]; simp [rotate] lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate n.succ = (l ++ [a]).rotate n := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ] @[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l | [] _ n := by simp | (a::l) _ 0 := by simp | (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm] @[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length := by rw [rotate_eq_rotate', length_rotate'] lemma rotate_eq_take_append_drop {l : list α} {n : ℕ} : n ≤ l.length → l.rotate n = l.drop n ++ l.take n := by rw rotate_eq_rotate'; exact rotate'_eq_take_append_drop lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate'] @[simp] lemma rotate_length (l : list α) : rotate l l.length = l := by rw [rotate_eq_rotate', rotate'_length] @[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l := by rw [rotate_eq_rotate', rotate'_length_mul] lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ), (l.rotate n).prod = 1 | [] _ _ := by simp | (a::l) hl n := have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial), by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl; rw [← rotate_mod, rotate_eq_take_append_drop this, list.prod_append, mul_eq_one_iff_inv_eq, ← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one] section choose variables (p : α → Prop) [decidable_pred p] (l : list α) lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose namespace func variables {a : α} variables {as as1 as2 as3 : list α} local notation as ` {` m ` ↦ ` a `}` := set a as m /- set -/ lemma length_set [inhabited α] : ∀ {m : ℕ} {as : list α}, (as {m ↦ a}).length = _root_.max as.length (m+1) | 0 [] := rfl | 0 (a::as) := by {rw max_eq_left, refl, simp [nat.le_add_right]} | (m+1) [] := by simp only [set, nat.zero_max, length, @length_set m] | (m+1) (a::as) := by simp only [set, nat.max_succ_succ, length, @length_set m] @[simp] lemma get_nil [inhabited α] {k : ℕ} : get k [] = default α := by {cases k; refl} lemma get_eq_default_of_le [inhabited α] : ∀ (k : ℕ) {as : list α}, as.length ≤ k → get k as = default α | 0 [] h1 := rfl | 0 (a::as) h1 := by cases h1 | (k+1) [] h1 := rfl | (k+1) (a::as) h1 := begin apply get_eq_default_of_le k, rw ← nat.succ_le_succ_iff, apply h1, end @[simp] lemma get_set [inhabited α] {a : α} : ∀ {k : ℕ} {as : list α}, get k (as {k ↦ a}) = a | 0 as := by {cases as; refl, } | (k+1) as := by {cases as; simp [get_set]} lemma eq_get_of_mem [inhabited α] {a : α} : ∀ {as : list α}, a ∈ as → ∃ n : nat, ∀ d : α, a = (get n as) | [] h := by cases h | (b::as) h := begin rw mem_cons_iff at h, cases h, { existsi 0, intro d, apply h }, { cases eq_get_of_mem h with n h2, existsi (n+1), apply h2 } end lemma mem_get_of_le [inhabited α] : ∀ {n : ℕ} {as : list α}, n < as.length → get n as ∈ as | _ [] h1 := by cases h1 | 0 (a::as) _ := or.inl rfl | (n+1) (a::as) h1 := begin apply or.inr, unfold get, apply mem_get_of_le, apply nat.lt_of_succ_lt_succ h1, end lemma mem_get_of_ne_zero [inhabited α] : ∀ {n : ℕ} {as : list α}, get n as ≠ default α → get n as ∈ as | _ [] h1 := begin exfalso, apply h1, rw get_nil end | 0 (a::as) h1 := or.inl rfl | (n+1) (a::as) h1 := begin unfold get, apply (or.inr (mem_get_of_ne_zero _)), apply h1 end lemma get_set_eq_of_ne [inhabited α] {a : α} : ∀ {as : list α} (k : ℕ) (m : ℕ), m ≠ k → get m (as {k ↦ a}) = get m as | as 0 m h1 := by { cases m, contradiction, cases as; simp only [set, get, get_nil] } | as (k+1) m h1 := begin cases as; cases m, simp only [set, get], { have h3 : get m (nil {k ↦ a}) = default α, { rw [get_set_eq_of_ne k m, get_nil], intro hc, apply h1, simp [hc] }, apply h3 }, simp only [set, get], { apply get_set_eq_of_ne k m, intro hc, apply h1, simp [hc], } end lemma get_map [inhabited α] [inhabited β] {f : α → β} : ∀ {n : ℕ} {as : list α}, n < as.length → get n (as.map f) = f (get n as) | _ [] h := by cases h | 0 (a::as) h := rfl | (n+1) (a::as) h1 := begin have h2 : n < length as, { rw [← nat.succ_le_iff, ← nat.lt_succ_iff], apply h1 }, apply get_map h2, end lemma get_map' [inhabited α] [inhabited β] {f : α → β} {n : ℕ} {as : list α} : f (default α) = (default β) → get n (as.map f) = f (get n as) := begin intro h1, by_cases h2 : n < as.length, { apply get_map h2, }, { rw not_lt at h2, rw [get_eq_default_of_le _ h2, get_eq_default_of_le, h1], rw [length_map], apply h2 } end lemma forall_val_of_forall_mem [inhabited α] {as : list α} {p : α → Prop} : p (default α) → (∀ x ∈ as, p x) → (∀ n, p (get n as)) := begin intros h1 h2 n, by_cases h3 : n < as.length, { apply h2 _ (mem_get_of_le h3) }, { rw not_lt at h3, rw get_eq_default_of_le _ h3, apply h1 } end /- equiv -/ lemma equiv_refl [inhabited α] : equiv as as := λ k, rfl lemma equiv_symm [inhabited α] : equiv as1 as2 → equiv as2 as1 := λ h1 k, (h1 k).symm lemma equiv_trans [inhabited α] : equiv as1 as2 → equiv as2 as3 → equiv as1 as3 := λ h1 h2 k, eq.trans (h1 k) (h2 k) lemma equiv_of_eq [inhabited α] : as1 = as2 → equiv as1 as2 := begin intro h1, rw h1, apply equiv_refl end lemma eq_of_equiv [inhabited α] : ∀ {as1 as2 : list α}, as1.length = as2.length → equiv as1 as2 → as1 = as2 | [] [] h1 h2 := rfl | (_::_) [] h1 h2 := by cases h1 | [] (_::_) h1 h2 := by cases h1 | (a1::as1) (a2::as2) h1 h2 := begin congr, { apply h2 0 }, have h3 : as1.length = as2.length, { simpa [add_left_inj, add_comm, length] using h1 }, apply eq_of_equiv h3, intro m, apply h2 (m+1) end /- neg -/ @[simp] lemma get_neg [inhabited α] [add_group α] {k : ℕ} {as : list α} : @get α ⟨0⟩ k (neg as) = -(@get α ⟨0⟩ k as) := by {unfold neg, rw (@get_map' α α ⟨0⟩), apply neg_zero} @[simp] lemma length_neg [inhabited α] [has_neg α] (as : list α) : (neg as).length = as.length := by simp only [neg, length_map] /- pointwise -/ lemma nil_pointwise [inhabited α] [inhabited β] {f : α → β → γ} : ∀ bs : list β, pointwise f [] bs = bs.map (f $ default α) | [] := rfl | (b::bs) := by simp only [nil_pointwise bs, pointwise, eq_self_iff_true, and_self, map] lemma pointwise_nil [inhabited α] [inhabited β] {f : α → β → γ} : ∀ as : list α, pointwise f as [] = as.map (λ a, f a $ default β) | [] := rfl | (a::as) := by simp only [pointwise_nil as, pointwise, eq_self_iff_true, and_self, list.map] lemma get_pointwise [inhabited α] [inhabited β] [inhabited γ] {f : α → β → γ} (h1 : f (default α) (default β) = default γ) : ∀ (k : nat) (as : list α) (bs : list β), get k (pointwise f as bs) = f (get k as) (get k bs) | k [] [] := by simp only [h1, get_nil, pointwise, get] | 0 [] (b::bs) := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) [] (b::bs) := by { have : get k (map (f $ default α) bs) = f (default α) (get k bs), { simpa [nil_pointwise, get_nil] using (get_pointwise k [] bs) }, simpa [get, get_nil, pointwise, map] } | 0 (a::as) [] := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) (a::as) [] := by simpa [get, get_nil, pointwise, map, pointwise_nil, get_nil] using get_pointwise k as [] | 0 (a::as) (b::bs) := by simp only [pointwise, get] | (k+1) (a::as) (b::bs) := by simp only [pointwise, get, get_pointwise k] lemma length_pointwise [inhabited α] [inhabited β] {f : α → β → γ} : ∀ {as : list α} {bs : list β}, (pointwise f as bs).length = _root_.max as.length bs.length | [] [] := rfl | [] (b::bs) := by simp only [pointwise, length, length_map, max_eq_right (nat.zero_le (length bs + 1))] | (a::as) [] := by simp only [pointwise, length, length_map, max_eq_left (nat.zero_le (length as + 1))] | (a::as) (b::bs) := by simp only [pointwise, length, nat.max_succ_succ, @length_pointwise as bs] /- add -/ @[simp] lemma get_add {α : Type u} [add_monoid α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (add xs ys) = ( @get α ⟨0⟩ k xs + @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply zero_add} @[simp] lemma length_add {α : Type u} [has_zero α] [has_add α] {xs ys : list α} : (add xs ys).length = _root_.max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_add {α : Type u} [add_monoid α] (as : list α) : add [] as = as := begin rw [add, @nil_pointwise α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, zero_add], refl end @[simp] lemma add_nil {α : Type u} [add_monoid α] (as : list α) : add as [] = as := begin rw [add, @pointwise_nil α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, add_zero], refl end lemma map_add_map {α : Type u} [add_monoid α] (f g : α → α) {as : list α} : add (as.map f) (as.map g) = as.map (λ x, f x + g x) := begin apply @eq_of_equiv _ (⟨0⟩ : inhabited α), { rw [length_map, length_add, max_eq_left, length_map], apply le_of_eq, rw [length_map, length_map] }, intros m, rw [get_add], by_cases h : m < length as, { repeat {rw [@get_map α α ⟨0⟩ ⟨0⟩ _ _ _ h]} }, rw not_lt at h, repeat {rw [get_eq_default_of_le m]}; try {rw length_map, apply h}, apply zero_add end /- sub -/ @[simp] lemma get_sub {α : Type u} [add_group α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (sub xs ys) = (@get α ⟨0⟩ k xs - @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply sub_zero} @[simp] lemma length_sub [has_zero α] [has_sub α] {xs ys : list α} : (sub xs ys).length = _root_.max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_sub {α : Type} [add_group α] (as : list α) : sub [] as = @neg α ⟨0⟩ _ as := begin rw [sub, nil_pointwise], congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, zero_sub] end @[simp] lemma sub_nil {α : Type} [add_group α] (as : list α) : sub as [] = as := begin rw [sub, pointwise_nil], apply eq.trans _ (map_id as), congr, ext, have : @default α ⟨0⟩ = 0 := rfl, rw [this, sub_zero], refl end end func namespace nat /-- The antidiagonal of a natural number `n` is the list of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : list (ℕ × ℕ) := (range (n+1)).map (λ i, (i, n - i)) /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := begin rw [antidiagonal, mem_map], split, { rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_sub_of_le hi }, { rintro rfl, refine ⟨x.fst, _, _⟩, { rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ }, { exact prod.ext rfl (nat.add_sub_cancel_left _ _) } } end /-- The length of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 := by rw [antidiagonal, length_map, length_range] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] := ext_le (length_antidiagonal 0) $ λ n h₁ h₂, begin rw [length_antidiagonal, lt_succ_iff, le_zero_iff] at h₁, subst n, simp [antidiagonal] end /-- The antidiagonal of `n` does not contain duplicate entries. -/ lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := nodup_map (@injective_of_left_inverse ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl) (nodup_range _) end nat end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x
b8a3b3183e402d22989e1fe4f04c940b0e7b74ac
9dc8cecdf3c4634764a18254e94d43da07142918
/src/combinatorics/young_diagram.lean
2d80a2b00291e8ff4769d53dfbd5d8ddbf7d674f
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
11,056
lean
/- Copyright (c) 2022 Jake Levinson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jake Levinson -/ import order.upper_lower import data.finset.preimage /-! # Young diagrams A Young diagram is a finite set of up-left justified boxes: ```text □□□□□ □□□ □□□ □ ``` This Young diagram corresponds to the [5, 3, 3, 1] partition of 12. We represent it as a lower set in `ℕ × ℕ` in the product partial order. We write `(i, j) ∈ μ` to say that `(i, j)` (in matrix coordinates) is in the Young diagram `μ`. ## Main definitions - `young_diagram` : Young diagrams - `young_diagram.card` : the number of cells in a Young diagram (its *cardinality*) - `young_diagram.distrib_lattice` : a distributive lattice instance for Young diagrams ordered by containment, with `(⊥ : young_diagram)` the empty diagram. - `young_diagram.row` and `young_diagram.row_len`: rows of a Young diagram and their lengths - `young_diagram.col` and `young_diagram.col_len`: columns of a Young diagram and their lengths ## Notation In "English notation", a Young diagram is drawn so that (i1, j1) ≤ (i2, j2) means (i1, j1) is weakly up-and-left of (i2, j2). This terminology is used below, e.g. in `young_diagram.up_left_mem`. ## Tags Young diagram ## References <https://en.wikipedia.org/wiki/Young_tableau> -/ /-- A Young diagram is a finite collection of cells on the `ℕ × ℕ` grid such that whenever a cell is present, so are all the ones above and to the left of it. Like matrices, an `(i, j)` cell is a cell in row `i` and column `j`, where rows are enumerated downward and columns rightward. Young diagrams are modeled as finite sets in `ℕ × ℕ` that are lower sets with respect to the standard order on products. -/ @[ext] structure young_diagram := (cells : finset (ℕ × ℕ)) (is_lower_set : is_lower_set (cells : set (ℕ × ℕ))) namespace young_diagram instance : set_like young_diagram (ℕ × ℕ) := { coe := coe young_diagram.cells, coe_injective' := λ μ ν h, by { rwa [young_diagram.ext_iff, ← finset.coe_inj] } } @[simp] lemma mem_cells {μ : young_diagram} (c : ℕ × ℕ) : c ∈ μ.cells ↔ c ∈ μ := iff.rfl @[simp] lemma mem_mk (c : ℕ × ℕ) (cells) (is_lower_set) : c ∈ young_diagram.mk cells is_lower_set ↔ c ∈ cells := iff.rfl instance decidable_mem (μ : young_diagram) : decidable_pred (∈ μ) := show decidable_pred (∈ μ.cells), by apply_instance /-- In "English notation", a Young diagram is drawn so that (i1, j1) ≤ (i2, j2) means (i1, j1) is weakly up-and-left of (i2, j2). -/ lemma up_left_mem (μ : young_diagram) {i1 i2 j1 j2 : ℕ} (hi : i1 ≤ i2) (hj : j1 ≤ j2) (hcell : (i2, j2) ∈ μ) : (i1, j1) ∈ μ := μ.is_lower_set (prod.mk_le_mk.mpr ⟨hi, hj⟩) hcell section distrib_lattice @[simp] lemma cells_subset_iff {μ ν : young_diagram} : μ.cells ⊆ ν.cells ↔ μ ≤ ν := iff.rfl @[simp] lemma cells_ssubset_iff {μ ν : young_diagram} : μ.cells ⊂ ν.cells ↔ μ < ν := iff.rfl instance : has_sup young_diagram := { sup := λ μ ν, { cells := μ.cells ∪ ν.cells, is_lower_set := by { rw finset.coe_union, exact μ.is_lower_set.union ν.is_lower_set } } } @[simp] lemma cells_sup (μ ν : young_diagram) : (μ ⊔ ν).cells = μ.cells ∪ ν.cells := rfl @[simp, norm_cast] lemma coe_sup (μ ν : young_diagram) : ↑(μ ⊔ ν) = (μ ∪ ν : set (ℕ × ℕ)) := finset.coe_union _ _ @[simp] lemma mem_sup {μ ν : young_diagram} {x : ℕ × ℕ} : x ∈ (μ ⊔ ν) ↔ x ∈ μ ∨ x ∈ ν := finset.mem_union instance : has_inf young_diagram := { inf := λ μ ν, { cells := μ.cells ∩ ν.cells, is_lower_set := by { rw finset.coe_inter, exact μ.is_lower_set.inter ν.is_lower_set } } } @[simp] lemma cells_inf (μ ν : young_diagram) : (μ ⊓ ν).cells = μ.cells ∩ ν.cells := rfl @[simp, norm_cast] lemma coe_inf (μ ν : young_diagram) : ↑(μ ⊓ ν) = (μ ∩ ν : set (ℕ × ℕ)) := finset.coe_inter _ _ @[simp] lemma mem_inf {μ ν : young_diagram} {x : ℕ × ℕ} : x ∈ (μ ⊓ ν) ↔ x ∈ μ ∧ x ∈ ν := finset.mem_inter /-- The empty Young diagram is (⊥ : young_diagram). -/ instance : order_bot young_diagram := { bot := { cells := ∅, is_lower_set := λ _ _ _, false.elim }, bot_le := λ _ _, false.elim } @[simp] lemma cells_bot : (⊥ : young_diagram).cells = ∅ := rfl @[simp, norm_cast] lemma coe_bot : ↑(⊥ : young_diagram) = (∅ : set (ℕ × ℕ)) := rfl @[simp] lemma not_mem_bot (x : ℕ × ℕ) : x ∉ (⊥ : young_diagram) := finset.not_mem_empty x instance : inhabited young_diagram := ⟨⊥⟩ instance : distrib_lattice young_diagram := function.injective.distrib_lattice young_diagram.cells (λ μ ν h, by rwa young_diagram.ext_iff) (λ _ _, rfl) (λ _ _, rfl) end distrib_lattice /-- Cardinality of a Young diagram -/ @[reducible] protected def card (μ : young_diagram) : ℕ := μ.cells.card section transpose /-- The `transpose` of a Young diagram is obtained by swapping i's with j's. -/ def transpose (μ : young_diagram) : young_diagram := { cells := (equiv.prod_comm _ _).finset_congr μ.cells, is_lower_set := λ _ _ h, begin simp only [finset.mem_coe, equiv.finset_congr_apply, finset.mem_map_equiv], intro hcell, apply μ.is_lower_set _ hcell, simp [h], end } @[simp] lemma mem_transpose {μ : young_diagram} {c : ℕ × ℕ} : c ∈ μ.transpose ↔ c.swap ∈ μ := by simp [transpose] @[simp] lemma transpose_transpose (μ : young_diagram) : μ.transpose.transpose = μ := by { ext, simp } lemma transpose_eq_iff_eq_transpose {μ ν : young_diagram} : μ.transpose = ν ↔ μ = ν.transpose := by { split; { rintro rfl, simp } } @[simp] lemma transpose_eq_iff {μ ν : young_diagram} : μ.transpose = ν.transpose ↔ μ = ν := by { rw transpose_eq_iff_eq_transpose, simp } -- This is effectively both directions of `transpose_le_iff` below. protected lemma le_of_transpose_le {μ ν : young_diagram} (h_le : μ.transpose ≤ ν) : μ ≤ ν.transpose := λ c hc, by { simp only [mem_transpose], apply h_le, simpa } @[simp] lemma transpose_le_iff {μ ν : young_diagram} : μ.transpose ≤ ν.transpose ↔ μ ≤ ν := ⟨ λ h, by { convert young_diagram.le_of_transpose_le h, simp }, λ h, by { convert @young_diagram.le_of_transpose_le _ _ _, simpa } ⟩ @[mono] protected lemma transpose_mono {μ ν : young_diagram} (h_le : μ ≤ ν) : μ.transpose ≤ ν.transpose := transpose_le_iff.mpr h_le /-- Transposing Young diagrams is an `order_iso`. -/ @[simps] def transpose_order_iso : young_diagram ≃o young_diagram := ⟨⟨transpose, transpose, λ _, by simp, λ _, by simp⟩, by simp⟩ end transpose section rows /-! ### Rows and row lengths of Young diagrams. This section defines `μ.row` and `μ.row_len`, with the following API: 1. `(i, j) ∈ μ ↔ j < μ.row_len i` 2. `μ.row i = {i} ×ˢ (finset.range (μ.row_len i))` 3. `μ.row_len i = (μ.row i).card` 4. `∀ {i1 i2}, i1 ≤ i2 → μ.row_len i2 ≤ μ.row_len i1` Note: #3 is not convenient for defining `μ.row_len`; instead, `μ.row_len` is defined as the smallest `j` such that `(i, j) ∉ μ`. -/ /-- The `i`-th row of a Young diagram consists of the cells whose first coordinate is `i`. -/ def row (μ : young_diagram) (i : ℕ) : finset (ℕ × ℕ) := μ.cells.filter (λ c, c.fst = i) lemma mem_row_iff {μ : young_diagram} {i : ℕ} {c : ℕ × ℕ} : c ∈ μ.row i ↔ c ∈ μ ∧ c.fst = i := by simp [row] lemma mk_mem_row_iff {μ : young_diagram} {i j : ℕ} : (i, j) ∈ μ.row i ↔ (i, j) ∈ μ := by simp [row] protected lemma exists_not_mem_row (μ : young_diagram) (i : ℕ) : ∃ j, (i, j) ∉ μ := begin obtain ⟨j, hj⟩ := infinite.exists_not_mem_finset ((μ.cells).preimage (prod.mk i) (λ _ _ _ _ h, by {cases h, refl})), rw finset.mem_preimage at hj, exact ⟨j, hj⟩, end /-- Length of a row of a Young diagram -/ def row_len (μ : young_diagram) (i : ℕ) : ℕ := nat.find $ μ.exists_not_mem_row i lemma mem_iff_lt_row_len {μ : young_diagram} {i j : ℕ} : (i, j) ∈ μ ↔ j < μ.row_len i := by { rw [row_len, nat.lt_find_iff], push_neg, exact ⟨λ h _ hmj, μ.up_left_mem (by refl) hmj h, λ h, h _ (by refl)⟩ } lemma row_eq_prod {μ : young_diagram} {i : ℕ} : μ.row i = {i} ×ˢ finset.range (μ.row_len i) := by { ext ⟨a, b⟩, simp only [finset.mem_product, finset.mem_singleton, finset.mem_range, mem_row_iff, mem_iff_lt_row_len, and_comm, and.congr_right_iff], rintro rfl, refl } lemma row_len_eq_card (μ : young_diagram) {i : ℕ} : μ.row_len i = (μ.row i).card := by simp [row_eq_prod] @[mono] lemma row_len_anti (μ : young_diagram) (i1 i2 : ℕ) (hi : i1 ≤ i2) : μ.row_len i2 ≤ μ.row_len i1 := by { by_contra' h_lt, rw ← lt_self_iff_false (μ.row_len i1), rw ← mem_iff_lt_row_len at h_lt ⊢, exact μ.up_left_mem hi (by refl) h_lt } end rows section columns /-! ### Columns and column lengths of Young diagrams. This section has an identical API to the rows section. -/ /-- The `j`-th column of a Young diagram consists of the cells whose second coordinate is `j`. -/ def col (μ : young_diagram) (j : ℕ) : finset (ℕ × ℕ) := μ.cells.filter (λ c, c.snd = j) lemma mem_col_iff {μ : young_diagram} {j : ℕ} {c : ℕ × ℕ} : c ∈ μ.col j ↔ c ∈ μ ∧ c.snd = j := by simp [col] lemma mk_mem_col_iff {μ : young_diagram} {i j : ℕ} : (i, j) ∈ μ.col j ↔ (i, j) ∈ μ := by simp [col] protected lemma exists_not_mem_col (μ : young_diagram) (j : ℕ) : ∃ i, (i, j) ∉ μ.cells := by { convert μ.transpose.exists_not_mem_row j, simp } /-- Length of a column of a Young diagram -/ def col_len (μ : young_diagram) (j : ℕ) : ℕ := nat.find $ μ.exists_not_mem_col j @[simp] lemma col_len_transpose (μ : young_diagram) (j : ℕ) : μ.transpose.col_len j = μ.row_len j := by simp [row_len, col_len] @[simp] lemma row_len_transpose (μ : young_diagram) (i : ℕ) : μ.transpose.row_len i = μ.col_len i := by simp [row_len, col_len] lemma mem_iff_lt_col_len {μ : young_diagram} {i j : ℕ} : (i, j) ∈ μ ↔ i < μ.col_len j := by { rw [← row_len_transpose, ← mem_iff_lt_row_len], simp } lemma col_eq_prod {μ : young_diagram} {j : ℕ} : μ.col j = (finset.range (μ.col_len j)) ×ˢ {j} := by { ext ⟨a, b⟩, simp only [finset.mem_product, finset.mem_singleton, finset.mem_range, mem_col_iff, mem_iff_lt_col_len, and_comm, and.congr_right_iff], rintro rfl, refl } lemma col_len_eq_card (μ : young_diagram) {j : ℕ} : μ.col_len j = (μ.col j).card := by simp [col_eq_prod] @[mono] lemma col_len_anti (μ : young_diagram) (j1 j2 : ℕ) (hj : j1 ≤ j2) : μ.col_len j2 ≤ μ.col_len j1 := by { convert μ.transpose.row_len_anti j1 j2 hj; simp } end columns end young_diagram
73ad825ce5bf02707b84ae99cfb2a9b19f413233
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/MultMeetSemilattice.lean
66f6306175cd4204114645993ed0c55be978ee4f
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,911
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section MultMeetSemilattice structure MultMeetSemilattice (A : Type) : Type := (times : (A → (A → A))) (commutative_times : (∀ {x y : A} , (times x y) = (times y x))) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) (idempotent_times : (∀ {x : A} , (times x x) = x)) open MultMeetSemilattice structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (commutative_timesP : (∀ {xP yP : (Prod A A)} , (timesP xP yP) = (timesP yP xP))) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) (idempotent_timesP : (∀ {xP : (Prod A A)} , (timesP xP xP) = xP)) structure Hom {A1 : Type} {A2 : Type} (Mu1 : (MultMeetSemilattice A1)) (Mu2 : (MultMeetSemilattice A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times Mu1) x1 x2)) = ((times Mu2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Mu1 : (MultMeetSemilattice A1)) (Mu2 : (MultMeetSemilattice A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times Mu1) x1 x2) ((times Mu2) y1 y2)))))) inductive MultMeetSemilatticeTerm : Type | timesL : (MultMeetSemilatticeTerm → (MultMeetSemilatticeTerm → MultMeetSemilatticeTerm)) open MultMeetSemilatticeTerm inductive ClMultMeetSemilatticeTerm (A : Type) : Type | sing : (A → ClMultMeetSemilatticeTerm) | timesCl : (ClMultMeetSemilatticeTerm → (ClMultMeetSemilatticeTerm → ClMultMeetSemilatticeTerm)) open ClMultMeetSemilatticeTerm inductive OpMultMeetSemilatticeTerm (n : ℕ) : Type | v : ((fin n) → OpMultMeetSemilatticeTerm) | timesOL : (OpMultMeetSemilatticeTerm → (OpMultMeetSemilatticeTerm → OpMultMeetSemilatticeTerm)) open OpMultMeetSemilatticeTerm inductive OpMultMeetSemilatticeTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpMultMeetSemilatticeTerm2) | sing2 : (A → OpMultMeetSemilatticeTerm2) | timesOL2 : (OpMultMeetSemilatticeTerm2 → (OpMultMeetSemilatticeTerm2 → OpMultMeetSemilatticeTerm2)) open OpMultMeetSemilatticeTerm2 def simplifyCl {A : Type} : ((ClMultMeetSemilatticeTerm A) → (ClMultMeetSemilatticeTerm A)) | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpMultMeetSemilatticeTerm n) → (OpMultMeetSemilatticeTerm n)) | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpMultMeetSemilatticeTerm2 n A) → (OpMultMeetSemilatticeTerm2 n A)) | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((MultMeetSemilattice A) → (MultMeetSemilatticeTerm → A)) | Mu (timesL x1 x2) := ((times Mu) (evalB Mu x1) (evalB Mu x2)) def evalCl {A : Type} : ((MultMeetSemilattice A) → ((ClMultMeetSemilatticeTerm A) → A)) | Mu (sing x1) := x1 | Mu (timesCl x1 x2) := ((times Mu) (evalCl Mu x1) (evalCl Mu x2)) def evalOpB {A : Type} {n : ℕ} : ((MultMeetSemilattice A) → ((vector A n) → ((OpMultMeetSemilatticeTerm n) → A))) | Mu vars (v x1) := (nth vars x1) | Mu vars (timesOL x1 x2) := ((times Mu) (evalOpB Mu vars x1) (evalOpB Mu vars x2)) def evalOp {A : Type} {n : ℕ} : ((MultMeetSemilattice A) → ((vector A n) → ((OpMultMeetSemilatticeTerm2 n A) → A))) | Mu vars (v2 x1) := (nth vars x1) | Mu vars (sing2 x1) := x1 | Mu vars (timesOL2 x1 x2) := ((times Mu) (evalOp Mu vars x1) (evalOp Mu vars x2)) def inductionB {P : (MultMeetSemilatticeTerm → Type)} : ((∀ (x1 x2 : MultMeetSemilatticeTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → (∀ (x : MultMeetSemilatticeTerm) , (P x))) | ptimesl (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl x1) (inductionB ptimesl x2)) def inductionCl {A : Type} {P : ((ClMultMeetSemilatticeTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClMultMeetSemilatticeTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → (∀ (x : (ClMultMeetSemilatticeTerm A)) , (P x)))) | psing ptimescl (sing x1) := (psing x1) | psing ptimescl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl x1) (inductionCl psing ptimescl x2)) def inductionOpB {n : ℕ} {P : ((OpMultMeetSemilatticeTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpMultMeetSemilatticeTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → (∀ (x : (OpMultMeetSemilatticeTerm n)) , (P x)))) | pv ptimesol (v x1) := (pv x1) | pv ptimesol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol x1) (inductionOpB pv ptimesol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpMultMeetSemilatticeTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpMultMeetSemilatticeTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → (∀ (x : (OpMultMeetSemilatticeTerm2 n A)) , (P x))))) | pv2 psing2 ptimesol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 x1) (inductionOp pv2 psing2 ptimesol2 x2)) def stageB : (MultMeetSemilatticeTerm → (Staged MultMeetSemilatticeTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClMultMeetSemilatticeTerm A) → (Staged (ClMultMeetSemilatticeTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpMultMeetSemilatticeTerm n) → (Staged (OpMultMeetSemilatticeTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpMultMeetSemilatticeTerm2 n A) → (Staged (OpMultMeetSemilatticeTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) end MultMeetSemilattice
6979378601c3e4c860fe36794938ab696746645c
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/sites/grothendieck.lean
6d9af6d6516c7a0e0d4697cfccd2ed9814c60411
[ "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
19,412
lean
/- Copyright (c) 2020 Bhavik Mehta, E. W. Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, E. W. Ayers -/ import category_theory.sites.sieves import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.multiequalizer import category_theory.category.preorder import order.copy /-! # Grothendieck topologies Definition and lemmas about Grothendieck topologies. A Grothendieck topology for a category `C` is a set of sieves on each object `X` satisfying certain closure conditions. Alternate versions of the axioms (in arrow form) are also described. Two explicit examples of Grothendieck topologies are given: * The dense topology * The atomic topology as well as the complete lattice structure on Grothendieck topologies (which gives two additional explicit topologies: the discrete and trivial topologies.) A pretopology, or a basis for a topology is defined in `pretopology.lean`. The topology associated to a topological space is defined in `spaces.lean`. ## Tags Grothendieck topology, coverage, pretopology, site ## References * [https://ncatlab.org/nlab/show/Grothendieck+topology][nlab] * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM91] ## Implementation notes We use the definition of [nlab] and [MM91](Chapter III, Section 2), where Grothendieck topologies are saturated collections of morphisms, rather than the notions of the Stacks project (00VG) and the Elephant, in which topologies are allowed to be unsaturated, and are then completed. TODO (BM): Add the definition from Stacks, as a pretopology, and complete to a topology. This is so that we can produce a bijective correspondence between Grothendieck topologies on a small category and Lawvere-Tierney topologies on its presheaf topos, as well as the equivalence between Grothendieck topoi and left exact reflective subcategories of presheaf toposes. -/ universes w v u namespace category_theory open category_theory category variables (C : Type u) [category.{v} C] /-- The definition of a Grothendieck topology: a set of sieves `J X` on each object `X` satisfying three axioms: 1. For every object `X`, the maximal sieve is in `J X`. 2. If `S ∈ J X` then its pullback along any `h : Y ⟶ X` is in `J Y`. 3. If `S ∈ J X` and `R` is a sieve on `X`, then provided that the pullback of `R` along any arrow `f : Y ⟶ X` in `S` is in `J Y`, we have that `R` itself is in `J X`. A sieve `S` on `X` is referred to as `J`-covering, (or just covering), if `S ∈ J X`. See https://stacks.math.columbia.edu/tag/00Z4, or [nlab], or [MM92] Chapter III, Section 2, Definition 1. -/ structure grothendieck_topology := (sieves : Π (X : C), set (sieve X)) (top_mem' : ∀ X, ⊤ ∈ sieves X) (pullback_stable' : ∀ ⦃X Y : C⦄ ⦃S : sieve X⦄ (f : Y ⟶ X), S ∈ sieves X → S.pullback f ∈ sieves Y) (transitive' : ∀ ⦃X⦄ ⦃S : sieve X⦄ (hS : S ∈ sieves X) (R : sieve X), (∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → R.pullback f ∈ sieves Y) → R ∈ sieves X) namespace grothendieck_topology instance : has_coe_to_fun (grothendieck_topology C) (λ _, Π X : C, set (sieve X)) := ⟨sieves⟩ variables {C} {X Y : C} {S R : sieve X} variables (J : grothendieck_topology C) /-- An extensionality lemma in terms of the coercion to a pi-type. We prove this explicitly rather than deriving it so that it is in terms of the coercion rather than the projection `.sieves`. -/ @[ext] lemma ext {J₁ J₂ : grothendieck_topology C} (h : (J₁ : Π (X : C), set (sieve X)) = J₂) : J₁ = J₂ := by { cases J₁, cases J₂, congr, apply h } @[simp] lemma mem_sieves_iff_coe : S ∈ J.sieves X ↔ S ∈ J X := iff.rfl -- Also known as the maximality axiom. @[simp] lemma top_mem (X : C) : ⊤ ∈ J X := J.top_mem' X -- Also known as the stability axiom. @[simp] lemma pullback_stable (f : Y ⟶ X) (hS : S ∈ J X) : S.pullback f ∈ J Y := J.pullback_stable' f hS lemma transitive (hS : S ∈ J X) (R : sieve X) (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → R.pullback f ∈ J Y) : R ∈ J X := J.transitive' hS R h lemma covering_of_eq_top : S = ⊤ → S ∈ J X := λ h, h.symm ▸ J.top_mem X /-- If `S` is a subset of `R`, and `S` is covering, then `R` is covering as well. See https://stacks.math.columbia.edu/tag/00Z5 (2), or discussion after [MM92] Chapter III, Section 2, Definition 1. -/ lemma superset_covering (Hss : S ≤ R) (sjx : S ∈ J X) : R ∈ J X := begin apply J.transitive sjx R (λ Y f hf, _), apply covering_of_eq_top, rw [← top_le_iff, ← S.pullback_eq_top_of_mem hf], apply sieve.pullback_monotone _ Hss, end /-- The intersection of two covering sieves is covering. See https://stacks.math.columbia.edu/tag/00Z5 (1), or [MM92] Chapter III, Section 2, Definition 1 (iv). -/ lemma intersection_covering (rj : R ∈ J X) (sj : S ∈ J X) : R ⊓ S ∈ J X := begin apply J.transitive rj _ (λ Y f Hf, _), rw [sieve.pullback_inter, R.pullback_eq_top_of_mem Hf], simp [sj], end @[simp] lemma intersection_covering_iff : R ⊓ S ∈ J X ↔ R ∈ J X ∧ S ∈ J X := ⟨λ h, ⟨J.superset_covering inf_le_left h, J.superset_covering inf_le_right h⟩, λ t, intersection_covering _ t.1 t.2⟩ lemma bind_covering {S : sieve X} {R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y} (hS : S ∈ J X) (hR : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (H : S f), R H ∈ J Y) : sieve.bind S R ∈ J X := J.transitive hS _ (λ Y f hf, superset_covering J (sieve.le_pullback_bind S R f hf) (hR hf)) /-- The sieve `S` on `X` `J`-covers an arrow `f` to `X` if `S.pullback f ∈ J Y`. This definition is an alternate way of presenting a Grothendieck topology. -/ def covers (S : sieve X) (f : Y ⟶ X) : Prop := S.pullback f ∈ J Y lemma covers_iff (S : sieve X) (f : Y ⟶ X) : J.covers S f ↔ S.pullback f ∈ J Y := iff.rfl lemma covering_iff_covers_id (S : sieve X) : S ∈ J X ↔ J.covers S (𝟙 X) := by simp [covers_iff] /-- The maximality axiom in 'arrow' form: Any arrow `f` in `S` is covered by `S`. -/ lemma arrow_max (f : Y ⟶ X) (S : sieve X) (hf : S f) : J.covers S f := begin rw [covers, (sieve.pullback_eq_top_iff_mem f).1 hf], apply J.top_mem, end /-- The stability axiom in 'arrow' form: If `S` covers `f` then `S` covers `g ≫ f` for any `g`. -/ lemma arrow_stable (f : Y ⟶ X) (S : sieve X) (h : J.covers S f) {Z : C} (g : Z ⟶ Y) : J.covers S (g ≫ f) := begin rw covers_iff at h ⊢, simp [h, sieve.pullback_comp], end /-- The transitivity axiom in 'arrow' form: If `S` covers `f` and every arrow in `S` is covered by `R`, then `R` covers `f`. -/ lemma arrow_trans (f : Y ⟶ X) (S R : sieve X) (h : J.covers S f) : (∀ {Z : C} (g : Z ⟶ X), S g → J.covers R g) → J.covers R f := begin intro k, apply J.transitive h, intros Z g hg, rw ← sieve.pullback_comp, apply k (g ≫ f) hg, end lemma arrow_intersect (f : Y ⟶ X) (S R : sieve X) (hS : J.covers S f) (hR : J.covers R f) : J.covers (S ⊓ R) f := by simpa [covers_iff] using and.intro hS hR variable (C) /-- The trivial Grothendieck topology, in which only the maximal sieve is covering. This topology is also known as the indiscrete, coarse, or chaotic topology. See [MM92] Chapter III, Section 2, example (a), or https://en.wikipedia.org/wiki/Grothendieck_topology#The_discrete_and_indiscrete_topologies -/ def trivial : grothendieck_topology C := { sieves := λ X, {⊤}, top_mem' := λ X, rfl, pullback_stable' := λ X Y S f hf, begin rw set.mem_singleton_iff at ⊢ hf, simp [hf], end, transitive' := λ X S hS R hR, begin rw [set.mem_singleton_iff, ← sieve.id_mem_iff_eq_top] at hS, simpa using hR hS, end } /-- The discrete Grothendieck topology, in which every sieve is covering. See https://en.wikipedia.org/wiki/Grothendieck_topology#The_discrete_and_indiscrete_topologies. -/ def discrete : grothendieck_topology C := { sieves := λ X, set.univ, top_mem' := by simp, pullback_stable' := λ X Y f, by simp, transitive' := by simp } variable {C} lemma trivial_covering : S ∈ trivial C X ↔ S = ⊤ := set.mem_singleton_iff /-- See https://stacks.math.columbia.edu/tag/00Z6 -/ instance : partial_order (grothendieck_topology C) := { le := λ J₁ J₂, (J₁ : Π (X : C), set (sieve X)) ≤ (J₂ : Π (X : C), set (sieve X)), le_refl := λ J₁, le_refl _, le_trans := λ J₁ J₂ J₃ h₁₂ h₂₃, le_trans h₁₂ h₂₃, le_antisymm := λ J₁ J₂ h₁₂ h₂₁, grothendieck_topology.ext (le_antisymm h₁₂ h₂₁) } /-- See https://stacks.math.columbia.edu/tag/00Z7 -/ instance : has_Inf (grothendieck_topology C) := { Inf := λ T, { sieves := Inf (sieves '' T), top_mem' := begin rintro X S ⟨⟨_, J, hJ, rfl⟩, rfl⟩, simp, end, pullback_stable' := begin rintro X Y S hS f _ ⟨⟨_, J, hJ, rfl⟩, rfl⟩, apply J.pullback_stable _ (f _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩), end, transitive' := begin rintro X S hS R h _ ⟨⟨_, J, hJ, rfl⟩, rfl⟩, apply J.transitive (hS _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩) _ (λ Y f hf, h hf _ ⟨⟨_, _, hJ, rfl⟩, rfl⟩), end } } /-- See https://stacks.math.columbia.edu/tag/00Z7 -/ lemma is_glb_Inf (s : set (grothendieck_topology C)) : is_glb s (Inf s) := begin refine @is_glb.of_image _ _ _ _ sieves _ _ _ _, { intros, refl }, { exact is_glb_Inf _ }, end /-- Construct a complete lattice from the `Inf`, but make the trivial and discrete topologies definitionally equal to the bottom and top respectively. -/ instance : complete_lattice (grothendieck_topology C) := complete_lattice.copy (complete_lattice_of_Inf _ is_glb_Inf) _ rfl (discrete C) (begin apply le_antisymm, { exact @complete_lattice.le_top _ (complete_lattice_of_Inf _ is_glb_Inf) (discrete C) }, { intros X S hS, apply set.mem_univ }, end) (trivial C) (begin apply le_antisymm, { intros X S hS, rw trivial_covering at hS, apply covering_of_eq_top _ hS }, { refine @complete_lattice.bot_le _ (complete_lattice_of_Inf _ is_glb_Inf) (trivial C) }, end) _ rfl _ rfl _ rfl Inf rfl instance : inhabited (grothendieck_topology C) := ⟨⊤⟩ @[simp] lemma trivial_eq_bot : trivial C = ⊥ := rfl @[simp] lemma discrete_eq_top : discrete C = ⊤ := rfl @[simp] lemma bot_covering : S ∈ (⊥ : grothendieck_topology C) X ↔ S = ⊤ := trivial_covering @[simp] lemma top_covering : S ∈ (⊤ : grothendieck_topology C) X := ⟨⟩ lemma bot_covers (S : sieve X) (f : Y ⟶ X) : (⊥ : grothendieck_topology C).covers S f ↔ S f := by rw [covers_iff, bot_covering, ← sieve.pullback_eq_top_iff_mem] @[simp] lemma top_covers (S : sieve X) (f : Y ⟶ X) : (⊤ : grothendieck_topology C).covers S f := by simp [covers_iff] /-- The dense Grothendieck topology. See https://ncatlab.org/nlab/show/dense+topology, or [MM92] Chapter III, Section 2, example (e). -/ def dense : grothendieck_topology C := { sieves := λ X S, ∀ {Y : C} (f : Y ⟶ X), ∃ Z (g : Z ⟶ Y), S (g ≫ f), top_mem' := λ X Y f, ⟨Y, 𝟙 Y, ⟨⟩⟩, pullback_stable' := begin intros X Y S h H Z f, rcases H (f ≫ h) with ⟨W, g, H'⟩, exact ⟨W, g, by simpa⟩, end, transitive' := begin intros X S H₁ R H₂ Y f, rcases H₁ f with ⟨Z, g, H₃⟩, rcases H₂ H₃ (𝟙 Z) with ⟨W, h, H₄⟩, exact ⟨W, (h ≫ g), by simpa using H₄⟩, end } lemma dense_covering : S ∈ dense X ↔ ∀ {Y} (f : Y ⟶ X), ∃ Z (g : Z ⟶ Y), S (g ≫ f) := iff.rfl /-- A category satisfies the right Ore condition if any span can be completed to a commutative square. NB. Any category with pullbacks obviously satisfies the right Ore condition, see `right_ore_of_pullbacks`. -/ def right_ore_condition (C : Type u) [category.{v} C] : Prop := ∀ {X Y Z : C} (yx : Y ⟶ X) (zx : Z ⟶ X), ∃ W (wy : W ⟶ Y) (wz : W ⟶ Z), wy ≫ yx = wz ≫ zx lemma right_ore_of_pullbacks [limits.has_pullbacks C] : right_ore_condition C := λ X Y Z yx zx, ⟨_, _, _, limits.pullback.condition⟩ /-- The atomic Grothendieck topology: a sieve is covering iff it is nonempty. For the pullback stability condition, we need the right Ore condition to hold. See https://ncatlab.org/nlab/show/atomic+site, or [MM92] Chapter III, Section 2, example (f). -/ def atomic (hro : right_ore_condition C) : grothendieck_topology C := { sieves := λ X S, ∃ Y (f : Y ⟶ X), S f, top_mem' := λ X, ⟨_, 𝟙 _, ⟨⟩⟩, pullback_stable' := begin rintros X Y S h ⟨Z, f, hf⟩, rcases hro h f with ⟨W, g, k, comm⟩, refine ⟨_, g, _⟩, simp [comm, hf], end, transitive' := begin rintros X S ⟨Y, f, hf⟩ R h, rcases h hf with ⟨Z, g, hg⟩, exact ⟨_, _, hg⟩, end } /-- `J.cover X` denotes the poset of covers of `X` with respect to the Grothendieck topology `J`. -/ @[derive preorder] def cover (X : C) := { S : sieve X // S ∈ J X } namespace cover variables {J} instance : has_coe (J.cover X) (sieve X) := ⟨λ S, S.1⟩ instance : has_coe_to_fun (J.cover X) (λ S, Π ⦃Y⦄ (f : Y ⟶ X), Prop) := ⟨λ S Y f, (S : sieve X) f⟩ @[simp] lemma coe_fun_coe (S : J.cover X) (f : Y ⟶ X) : (S : sieve X) f = S f := rfl lemma condition (S : J.cover X) : (S : sieve X) ∈ J X := S.2 @[ext] lemma ext (S T : J.cover X) (h : ∀ ⦃Y⦄ (f : Y ⟶ X), S f ↔ T f) : S = T := subtype.ext $ sieve.ext h instance : semilattice_inf_top (J.cover X) := { inf := λ S T, ⟨S ⊓ T, J.intersection_covering S.condition T.condition⟩, le_antisymm := λ S T h1 h2, ext _ _ $ λ Y f, ⟨h1 _, h2 _⟩, inf_le_left := λ S T Y f hf, hf.1, inf_le_right := λ S T Y f hf, hf.2, le_inf := λ S T W h1 h2 Y f h, ⟨h1 _ h, h2 _ h⟩, top := ⟨⊤, J.top_mem _⟩, le_top := λ S Y f h, by tauto, ..(infer_instance : preorder _) } instance : inhabited (J.cover X) := ⟨⊤⟩ /-- An auxiliary structure, used to define `S.index` in `plus.lean`. -/ @[nolint has_inhabited_instance, ext] structure arrow (S : J.cover X) := (Y : C) (f : Y ⟶ X) (hf : S f) /-- An auxiliary structure, used to define `S.index` in `plus.lean`. -/ @[nolint has_inhabited_instance, ext] structure relation (S : J.cover X) := (Y₁ Y₂ Z : C) (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) (f₁ : Y₁ ⟶ X) (f₂ : Y₂ ⟶ X) (h₁ : S f₁) (h₂ : S f₂) (w : g₁ ≫ f₁ = g₂ ≫ f₂) /-- Map a `arrow` along a refinement `S ⟶ T`. -/ @[simps] def arrow.map {S T : J.cover X} (I : S.arrow) (f : S ⟶ T) : T.arrow := ⟨I.Y, I.f, f.le _ I.hf⟩ /-- Map a `relation` along a refinement `S ⟶ T`. -/ @[simps] def relation.map {S T : J.cover X} (I : S.relation) (f : S ⟶ T) : T.relation := ⟨_, _, _, I.g₁, I.g₂, I.f₁, I.f₂, f.le _ I.h₁, f.le _ I.h₂, I.w⟩ /-- The first `arrow` associated to a `relation`. Used in defining `index` in `plus.lean`. -/ @[simps] def relation.fst {S : J.cover X} (I : S.relation) : S.arrow := ⟨I.Y₁, I.f₁, I.h₁⟩ /-- The second `arrow` associated to a `relation`. Used in defining `index` in `plus.lean`. -/ @[simps] def relation.snd {S : J.cover X} (I : S.relation) : S.arrow := ⟨I.Y₂, I.f₂, I.h₂⟩ @[simp] lemma relation.map_fst {S T : J.cover X} (I : S.relation) (f : S ⟶ T) : I.fst.map f = (I.map f).fst := rfl @[simp] lemma relation.map_snd {S T : J.cover X} (I : S.relation) (f : S ⟶ T) : I.snd.map f = (I.map f).snd := rfl /-- Pull back a cover along a morphism. -/ def pullback (S : J.cover X) (f : Y ⟶ X) : J.cover Y := ⟨sieve.pullback f S, J.pullback_stable _ S.condition⟩ /-- An arrow of `S.pullback f` gives rise to an arrow of `S`. -/ @[simps] def arrow.base {f : Y ⟶ X} {S : J.cover X} (I : (S.pullback f).arrow) : S.arrow := ⟨I.Y, I.f ≫ f, I.hf⟩ /-- A relation of `S.pullback f` gives rise to a relation of `S`. -/ @[simps] def relation.base {f : Y ⟶ X} {S : J.cover X} (I : (S.pullback f).relation) : S.relation := ⟨_, _, _, I.g₁, I.g₂, I.f₁ ≫ f, I.f₂≫ f, I.h₁, I.h₂, by simp [reassoc_of I.w]⟩ @[simp] lemma relation.base_fst {f : Y ⟶ X} {S : J.cover X} (I : (S.pullback f).relation) : I.fst.base = I.base.fst := rfl @[simp] lemma relation.base_snd {f : Y ⟶ X} {S : J.cover X} (I : (S.pullback f).relation) : I.snd.base = I.base.snd := rfl @[simp] lemma coe_pullback {Z : C} (f : Y ⟶ X) (g : Z ⟶ Y) (S : J.cover X) : (S.pullback f) g ↔ S (g ≫ f) := iff.rfl /-- The isomorphism between `S` and the pullback of `S` w.r.t. the identity. -/ def pullback_id (S : J.cover X) : S.pullback (𝟙 X) ≅ S := eq_to_iso $ cover.ext _ _ $ λ Y f, by simp /-- Pulling back with respect to a composition is the composition of the pullbacks. -/ def pullback_comp {X Y Z : C} (S : J.cover X) (f : Z ⟶ Y) (g : Y ⟶ X) : S.pullback (f ≫ g) ≅ (S.pullback g).pullback f := eq_to_iso $ cover.ext _ _ $ λ Y f, by simp -- This is used extensively in `plus.lean`, etc. -- We place this definition here as it will be used in `sheaf.lean` as well. /-- To every `S : J.cover X` and presheaf `P`, associate a `multicospan_index`. -/ def index {D : Type w} [category.{max v u} D] (S : J.cover X) (P : Cᵒᵖ ⥤ D) : limits.multicospan_index D := { L := S.arrow, R := S.relation, fst_to := λ I, I.fst, snd_to := λ I, I.snd, left := λ I, P.obj (opposite.op I.Y), right := λ I, P.obj (opposite.op I.Z), fst := λ I, P.map I.g₁.op, snd := λ I, P.map I.g₂.op } /-- The natural multifork associated to `S : J.cover X` for a presheaf `P`. Saying that this multifork is a limit is essentially equivalent to the sheaf condition at the given object for the given covering sieve. See `sheaf.lean` for an equivalent sheaf condition using this. -/ abbreviation multifork {D : Type w} [category.{max v u} D] (S : J.cover X) (P : Cᵒᵖ ⥤ D) : limits.multifork (S.index P) := limits.multifork.of_ι _ (P.obj (opposite.op X)) (λ I, P.map I.f.op) begin intros I, dsimp [index], simp only [← P.map_comp, ← op_comp, I.w] end /-- The canonical map from `P.obj (op X)` to the multiequalizer associated to a covering sieve, assuming such a multiequalizer exists. This will be used in `sheaf.lean` to provide an equivalent sheaf condition in terms of multiequalizers. -/ noncomputable abbreviation to_multiequalizer {D : Type w} [category.{max v u} D] (S : J.cover X) (P : Cᵒᵖ ⥤ D) [limits.has_multiequalizer (S.index P)] : P.obj (opposite.op X) ⟶ limits.multiequalizer (S.index P) := limits.multiequalizer.lift _ _ (λ I, P.map I.f.op) begin intros I, dsimp only [index, relation.fst, relation.snd], simp only [← P.map_comp, ← op_comp, I.w], end end cover /-- Pull back a cover along a morphism. -/ @[simps obj] def pullback (f : Y ⟶ X) : J.cover X ⥤ J.cover Y := { obj := λ S, S.pullback f, map := λ S T f, (sieve.pullback_monotone _ f.le).hom } /-- Pulling back along the identity is naturally isomorphic to the identity functor. -/ def pullback_id (X : C) : J.pullback (𝟙 X) ≅ 𝟭 _ := nat_iso.of_components (λ S, S.pullback_id) $ by tidy /-- Pulling back along a composition is naturally isomorphic to the composition of the pullbacks. -/ def pullback_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) : J.pullback (f ≫ g) ≅ J.pullback g ⋙ J.pullback f := nat_iso.of_components (λ S, S.pullback_comp f g) $ by tidy end grothendieck_topology end category_theory
8cca74afe480f61e0f96096f601a8905d8a78760
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_assert_nn_soundness.lean
372f2d079ccd796bdc4e240f7a76ffdfa3f62f37
[]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
3,257
lean
/- File: signature_recover_public_key_assert_nn_soundness.lean Autogenerated file. -/ import starkware.cairo.lean.semantics.soundness.hoare import .signature_recover_public_key_code import ..signature_recover_public_key_spec open tactic open starkware.cairo.common.math variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F] variable mem : F → F variable σ : register_state F /- starkware.cairo.common.math.assert_nn autogenerated soundness theorem -/ theorem auto_sound_assert_nn -- arguments (range_check_ptr a : F) -- code is in memory at σ.pc (h_mem : mem_at mem code_assert_nn σ.pc) -- input arguments on the stack (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 4)) (hin_a : a = mem (σ.fp - 3)) -- conclusion : ensures_ret mem σ (λ κ τ, τ.ap = σ.ap + 1 ∧ ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 4)) (mem $ τ.ap - 1) (spec_assert_nn mem κ range_check_ptr a (mem (τ.ap - 1)))) := begin apply ensures_of_ensuresb, intro νbound, have h_mem_rec := h_mem, unpack_memory code_assert_nn at h_mem with ⟨hpc0, hpc1, hpc2, hpc3⟩, -- assert eq step_assert_eq hpc0 with temp0, have a0: a = mem (range_check_ptr), { apply assert_eq_reduction temp0, try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, try { dsimp at a0 }, try { arith_simps at a0 }, clear temp0, -- let generalize' hl_rev_range_check_ptr₁: (range_check_ptr + 1 : F) = range_check_ptr₁, have hl_range_check_ptr₁ := hl_rev_range_check_ptr₁.symm, clear hl_rev_range_check_ptr₁, try { dsimp at hl_range_check_ptr₁ }, try { arith_simps at hl_range_check_ptr₁ }, -- return step_assert_eq hpc1 hpc2 with hret0, step_ret hpc3, -- finish step_done, use_only [rfl, rfl], split, refl, -- range check condition use_only (1+0+0), split, linarith [], split, { arith_simps, try { simp only [hret0] }, try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof -- user-provided reduction suffices auto_spec: auto_spec_assert_nn mem _ range_check_ptr a _, { apply sound_assert_nn, apply auto_spec }, -- prove the auto generated assertion dsimp [auto_spec_assert_nn], try { norm_num1 }, try { arith_simps }, use_only [a0], cases rc_h_range_check_ptr' (0) (by norm_num1) with n hn, arith_simps at hn, use_only [n], { simp only [a0, hin_range_check_ptr], arith_simps, exact hn }, have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁,try { norm_cast at rc_h_range_check_ptr₁' }, use_only [range_check_ptr₁, hl_range_check_ptr₁], try { split, linarith }, try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hl_range_check_ptr₁] }, }, try { arith_simps }, try { simp only [hret0] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, end
31d69fb9a12ac76d57a42410312f94a4ed2ce848
d5ecf6c46a2f605470a4a7724909dc4b9e7350e0
/analysis/limits.lean
8b79b285155bdc9c8cc424dba5c79d8108a22615
[ "Apache-2.0" ]
permissive
MonoidMusician/mathlib
41f79df478987a636b735c338396813d2e8e44c4
72234ef1a050eea3a2197c23aeb345fc13c08ff3
refs/heads/master
1,583,672,205,771
1,522,892,143,000
1,522,892,143,000
128,144,032
0
0
Apache-2.0
1,522,892,144,000
1,522,890,892,000
Lean
UTF-8
Lean
false
false
8,004
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 A collection of limit properties. -/ import algebra.big_operators algebra.group_power analysis.real analysis.topology.infinite_sum noncomputable theory open classical set finset function filter local attribute [instance] prop_decidable section real lemma has_sum_of_absolute_convergence {f : ℕ → ℝ} (hf : ∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (nhds r)) : has_sum f := let f' := λs:finset ℕ, s.sum (λi, abs (f i)) in suffices cauchy (map (λs:finset ℕ, s.sum f) at_top), from complete_space.complete this, cauchy_iff.mpr $ and.intro (map_ne_bot at_top_ne_bot) $ assume s hs, let ⟨ε, hε, hsε⟩ := mem_uniformity_dist.mp hs, ⟨r, hr⟩ := hf in have hε' : {p : ℝ × ℝ | dist p.1 p.2 < ε / 2} ∈ (@uniformity ℝ _).sets, from mem_uniformity_dist.mpr ⟨ε / 2, div_pos_of_pos_of_pos hε two_pos, assume a b h, h⟩, have cauchy (at_top.map $ λn, f' (range n)), from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hr, have ∃n, ∀{n'}, n ≤ n' → dist (f' (range n)) (f' (range n')) < ε / 2, by simp [cauchy_iff, mem_at_top_sets] at this; from let ⟨t, ⟨u, hu⟩, ht⟩ := this _ hε' in ⟨u, assume n' hn, ht $ prod_mk_mem_set_prod_eq.mpr ⟨hu _ (le_refl _), hu _ hn⟩⟩, let ⟨n, hn⟩ := this in have ∀{s}, range n ⊆ s → abs ((s \ range n).sum f) < ε / 2, from assume s hs, let ⟨n', hn'⟩ := @exists_nat_subset_range s in have range n ⊆ range n', from finset.subset.trans hs hn', have f'_nn : 0 ≤ f' (range n' \ range n), from zero_le_sum $ assume _ _, abs_nonneg _, calc abs ((s \ range n).sum f) ≤ f' (s \ range n) : abs_sum_le_sum_abs ... ≤ f' (range n' \ range n) : sum_le_sum_of_subset_of_nonneg (finset.sdiff_subset_sdiff hn' (finset.subset.refl _)) (assume _ _ _, abs_nonneg _) ... = abs (f' (range n' \ range n)) : (abs_of_nonneg f'_nn).symm ... = abs (f' (range n') - f' (range n)) : by simp [f', (sum_sdiff ‹range n ⊆ range n'›).symm] ... = abs (f' (range n) - f' (range n')) : abs_sub _ _ ... < ε / 2 : hn $ range_subset.mp this, have ∀{s t}, range n ⊆ s → range n ⊆ t → dist (s.sum f) (t.sum f) < ε, from assume s t hs ht, calc abs (s.sum f - t.sum f) = abs ((s \ range n).sum f + - (t \ range n).sum f) : by rw [←sum_sdiff hs, ←sum_sdiff ht]; simp ... ≤ abs ((s \ range n).sum f) + abs ((t \ range n).sum f) : le_trans (abs_add_le_abs_add_abs _ _) $ by rw [abs_neg]; exact le_refl _ ... < ε / 2 + ε / 2 : add_lt_add (this hs) (this ht) ... = ε : by rw [←add_div, add_self_div_two], ⟨(λs:finset ℕ, s.sum f) '' {s | range n ⊆ s}, image_mem_map $ mem_at_top (range n), assume ⟨a, b⟩ ⟨⟨t, ht, ha⟩, ⟨s, hs, hb⟩⟩, by simp at ha hb; exact ha ▸ hb ▸ hsε (this ht hs)⟩ lemma is_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} {r : ℝ} (hf : ∀n, 0 ≤ f n) : is_sum f r ↔ tendsto (λn, (range n).sum f) at_top (nhds r) := ⟨tendsto_sum_nat_of_is_sum, assume hr, have tendsto (λn, (range n).sum (λn, abs (f n))) at_top (nhds r), by simp [(λi, abs_of_nonneg (hf i)), hr], let ⟨p, h⟩ := has_sum_of_absolute_convergence ⟨r, this⟩ in have hp : tendsto (λn, (range n).sum f) at_top (nhds p), from tendsto_sum_nat_of_is_sum h, have p = r, from tendsto_nhds_unique at_top_ne_bot hp hr, this ▸ h⟩ end real lemma mul_add_one_le_pow {r : ℝ} (hr : 0 ≤ r) : ∀{n:ℕ}, (n:ℝ) * r + 1 ≤ (r + 1) ^ n | 0 := by simp; exact le_refl 1 | (n + 1) := let h : (n:ℝ) ≥ 0 := nat.cast_nonneg n in calc ↑(n + 1) * r + 1 ≤ ((n + 1) * r + 1) + r * r * n : le_add_of_le_of_nonneg (le_refl _) (mul_nonneg (mul_nonneg hr hr) h) ... = (r + 1) * (n * r + 1) : by simp [mul_add, add_mul, mul_comm, mul_assoc] ... ≤ (r + 1) * (r + 1) ^ n : mul_le_mul (le_refl _) mul_add_one_le_pow (add_nonneg (mul_nonneg h hr) zero_le_one) (add_nonneg hr zero_le_one) lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : r > 1) : tendsto (λn:ℕ, r ^ n) at_top at_top := tendsto_infi.2 $ assume p, tendsto_principal.2 $ let ⟨n, hn⟩ := exists_nat_gt (p / (r - 1)) in have hn_nn : (0:ℝ) ≤ n, from nat.cast_nonneg n, have r - 1 > 0, from sub_lt_iff.mp $ by simp; assumption, have p ≤ r ^ n, from calc p = (p / (r - 1)) * (r - 1) : (div_mul_cancel _ $ ne_of_gt this).symm ... ≤ n * (r - 1) : mul_le_mul (le_of_lt hn) (le_refl _) (le_of_lt this) hn_nn ... ≤ n * (r - 1) + 1 : le_add_of_le_of_nonneg (le_refl _) zero_le_one ... ≤ ((r - 1) + 1) ^ n : mul_add_one_le_pow $ le_of_lt this ... ≤ r ^ n : by simp; exact le_refl _, show {n | p ≤ r ^ n} ∈ at_top.sets, from mem_at_top_sets.mpr ⟨n, assume m hnm, le_trans this (pow_le_pow (le_of_lt h) hnm)⟩ lemma tendsto_inverse_at_top_nhds_0 : tendsto (λr:ℝ, r⁻¹) at_top (nhds 0) := tendsto_orderable_unbounded (no_top 0) (no_bot 0) $ assume l u hl hu, mem_at_top_sets.mpr ⟨u⁻¹ + 1, assume b hb, have u⁻¹ < b, from lt_of_lt_of_le (lt_add_of_pos_right _ zero_lt_one) hb, ⟨lt_trans hl $ inv_pos $ lt_trans (inv_pos hu) this, lt_of_one_div_lt_one_div hu $ begin rw [inv_eq_one_div], simp [-one_div_eq_inv, div_div_eq_mul_div, div_one], simp [this] end⟩⟩ lemma map_succ_at_top_eq : map nat.succ at_top = at_top := le_antisymm (assume s hs, let ⟨b, hb⟩ := mem_at_top_sets.mp hs in mem_at_top_sets.mpr ⟨b, assume c hc, hb (c + 1) $ le_trans hc $ nat.le_succ _⟩) (assume s hs, let ⟨b, hb⟩ := mem_at_top_sets.mp hs in mem_at_top_sets.mpr ⟨b + 1, assume c, match c with | 0 := assume h, have 0 > 0, from lt_of_lt_of_le (lt_add_of_le_of_pos (nat.zero_le _) zero_lt_one) h, (lt_irrefl 0 this).elim | (c+1) := assume h, hb _ (nat.le_of_succ_le_succ h) end⟩) lemma tendsto_comp_succ_at_top_iff {α : Type*} {f : ℕ → α} {x : filter α} : tendsto (λn, f (nat.succ n)) at_top x ↔ tendsto f at_top x := calc tendsto (f ∘ nat.succ) at_top x ↔ tendsto f (map nat.succ at_top) x : by simp [tendsto, map_map] ... ↔ _ : by rw [map_succ_at_top_eq] lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn, r^n) at_top (nhds 0) := by_cases (assume : r = 0, tendsto_comp_succ_at_top_iff.mp $ by simp [pow_succ, this, tendsto_const_nhds]) (assume : r ≠ 0, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (nhds 0), from (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂).comp tendsto_inverse_at_top_nhds_0, tendsto_cong this $ univ_mem_sets' $ by simp *) lemma sum_geometric' {r : ℝ} (h : r ≠ 0) : ∀{n}, (finset.range n).sum (λi, (r + 1) ^ i) = ((r + 1) ^ n - 1) / r | 0 := by simp [zero_div] | (n+1) := by simp [@sum_geometric' n, h, pow_succ, add_div_eq_mul_add_div, add_mul, mul_comm, mul_assoc] lemma sum_geometric {r : ℝ} {n : ℕ} (h : r ≠ 1) : (range n).sum (λi, r ^ i) = (r ^ n - 1) / (r - 1) := calc (range n).sum (λi, r ^ i) = (range n).sum (λi, ((r - 1) + 1) ^ i) : by simp ... = (((r - 1) + 1) ^ n - 1) / (r - 1) : sum_geometric' $ by simp [sub_eq_iff_eq_add, -sub_eq_add_neg, h] ... = (r ^ n - 1) / (r - 1) : by simp lemma is_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : is_sum (λn, r ^ n) (1 / (1 - r)) := have r ≠ 1, from ne_of_lt h₂, have r + -1 ≠ 0, by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (nhds ((0 - 1) * (r - 1)⁻¹)), from tendsto_mul (tendsto_sub (tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂) tendsto_const_nhds) tendsto_const_nhds, (is_sum_iff_tendsto_nat_of_nonneg $ pow_nonneg h₁).mpr $ by simp [neg_inv, sum_geometric, div_eq_mul_inv, *] at *
6420129e16b8615c99c7a626d7b793e0fae1a48c
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/homotopy/circle.hlean
9fec818dab1d954b04976cefc00d5668e1288490
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
12,943
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 Declaration of the circle -/ import .sphere import types.int.hott import algebra.homotopy_group .connectedness open eq susp bool sphere_index is_equiv equiv is_trunc is_conn pi algebra definition circle : Type₀ := sphere 1 namespace circle notation `S¹` := circle definition base1 : circle := !north definition base2 : circle := !south definition seg1 : base1 = base2 := merid !north definition seg2 : base1 = base2 := merid !south definition base : circle := base1 definition loop : base = base := seg2 ⬝ seg1⁻¹ definition rec2 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) (x : circle) : P x := begin induction x with b, { exact Pb1}, { exact Pb2}, { esimp at *, induction b with y, { exact Ps1}, { exact Ps2}, { cases y}}, end definition rec2_on [reducible] {P : circle → Type} (x : circle) (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : P x := circle.rec2 Pb1 Pb2 Ps1 Ps2 x theorem rec2_seg1 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : apd (rec2 Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := !rec_merid theorem rec2_seg2 {P : circle → Type} (Pb1 : P base1) (Pb2 : P base2) (Ps1 : Pb1 =[seg1] Pb2) (Ps2 : Pb1 =[seg2] Pb2) : apd (rec2 Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := !rec_merid definition elim2 {P : Type} (Pb1 Pb2 : P) (Ps1 Ps2 : Pb1 = Pb2) (x : circle) : P := rec2 Pb1 Pb2 (pathover_of_eq Ps1) (pathover_of_eq Ps2) x definition elim2_on [reducible] {P : Type} (x : circle) (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : P := elim2 Pb1 Pb2 Ps1 Ps2 x theorem elim2_seg1 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : ap (elim2 Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg1), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim2,rec2_seg1], end theorem elim2_seg2 {P : Type} (Pb1 Pb2 : P) (Ps1 : Pb1 = Pb2) (Ps2 : Pb1 = Pb2) : ap (elim2 Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg2), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim2,rec2_seg2], end definition elim2_type (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) (x : circle) : Type := elim2 Pb1 Pb2 (ua Ps1) (ua Ps2) x definition elim2_type_on [reducible] (x : circle) (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : Type := elim2_type Pb1 Pb2 Ps1 Ps2 x theorem elim2_type_seg1 (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : transport (elim2_type Pb1 Pb2 Ps1 Ps2) seg1 = Ps1 := by rewrite [tr_eq_cast_ap_fn,↑elim2_type,elim2_seg1];apply cast_ua_fn theorem elim2_type_seg2 (Pb1 Pb2 : Type) (Ps1 Ps2 : Pb1 ≃ Pb2) : transport (elim2_type Pb1 Pb2 Ps1 Ps2) seg2 = Ps2 := by rewrite [tr_eq_cast_ap_fn,↑elim2_type,elim2_seg2];apply cast_ua_fn protected definition rec {P : circle → Type} (Pbase : P base) (Ploop : Pbase =[loop] Pbase) (x : circle) : P x := begin fapply (rec2_on x), { exact Pbase}, { exact (transport P seg1 Pbase)}, { apply pathover_tr}, { apply pathover_tr_of_pathover, exact Ploop} end protected definition rec_on [reducible] {P : circle → Type} (x : circle) (Pbase : P base) (Ploop : Pbase =[loop] Pbase) : P x := circle.rec Pbase Ploop x theorem rec_loop_helper {A : Type} (P : A → Type) {x y z : A} {p : x = y} {p' : z = y} {u : P x} {v : P z} (q : u =[p ⬝ p'⁻¹] v) : pathover_tr_of_pathover q ⬝o !pathover_tr⁻¹ᵒ = q := by cases p'; cases q; exact idp definition con_refl {A : Type} {x y : A} (p : x = y) : p ⬝ refl _ = p := eq.rec_on p idp theorem rec_loop {P : circle → Type} (Pbase : P base) (Ploop : Pbase =[loop] Pbase) : apd (circle.rec Pbase Ploop) loop = Ploop := begin rewrite [↑loop,apd_con,↑circle.rec,↑circle.rec2_on,↑base,rec2_seg2,apd_inv,rec2_seg1], apply rec_loop_helper end protected definition elim {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) (x : circle) : P := circle.rec Pbase (pathover_of_eq Ploop) x protected definition elim_on [reducible] {P : Type} (x : circle) (Pbase : P) (Ploop : Pbase = Pbase) : P := circle.elim Pbase Ploop x theorem elim_loop {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) : ap (circle.elim Pbase Ploop) loop = Ploop := begin apply eq_of_fn_eq_fn_inv !(pathover_constant loop), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,rec_loop], end theorem elim_seg1 {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) : ap (circle.elim Pbase Ploop) seg1 = (tr_constant seg1 Pbase)⁻¹ := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg1), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,↑circle.rec], rewrite [↑circle.rec2_on,rec2_seg1], apply inverse, apply pathover_of_eq_tr_constant_inv end theorem elim_seg2 {P : Type} (Pbase : P) (Ploop : Pbase = Pbase) : ap (circle.elim Pbase Ploop) seg2 = Ploop ⬝ (tr_constant seg1 Pbase)⁻¹ := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg2), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑circle.elim,↑circle.rec], rewrite [↑circle.rec2_on,rec2_seg2], assert l : Π(A B : Type)(a a₂ a₂' : A)(b b' : B)(p : a = a₂)(p' : a₂' = a₂) (q : b = b'), pathover_tr_of_pathover (pathover_of_eq q) = pathover_of_eq (q ⬝ (tr_constant p' b')⁻¹) :> b =[p] p' ▸ b', { intros, cases q, cases p', cases p, reflexivity }, apply l end protected definition elim_type (Pbase : Type) (Ploop : Pbase ≃ Pbase) (x : circle) : Type := circle.elim Pbase (ua Ploop) x protected definition elim_type_on [reducible] (x : circle) (Pbase : Type) (Ploop : Pbase ≃ Pbase) : Type := circle.elim_type Pbase Ploop x theorem elim_type_loop (Pbase : Type) (Ploop : Pbase ≃ Pbase) : transport (circle.elim_type Pbase Ploop) loop = Ploop := by rewrite [tr_eq_cast_ap_fn,↑circle.elim_type,elim_loop];apply cast_ua_fn theorem elim_type_loop_inv (Pbase : Type) (Ploop : Pbase ≃ Pbase) : transport (circle.elim_type Pbase Ploop) loop⁻¹ = to_inv Ploop := by rewrite [tr_inv_fn]; apply inv_eq_inv; apply elim_type_loop end circle attribute circle.base1 circle.base2 circle.base [constructor] attribute circle.rec2 circle.elim2 [unfold 6] [recursor 6] attribute circle.elim2_type [unfold 5] attribute circle.rec2_on circle.elim2_on [unfold 2] attribute circle.elim2_type [unfold 1] attribute circle.rec circle.elim [unfold 4] [recursor 4] attribute circle.elim_type [unfold 3] attribute circle.rec_on circle.elim_on [unfold 2] attribute circle.elim_type_on [unfold 1] namespace circle open sigma /- universal property of the circle -/ definition circle_pi_equiv [constructor] (P : S¹ → Type) : (Π(x : S¹), P x) ≃ Σ(p : P base), p =[loop] p := begin fapply equiv.MK, { intro f, exact ⟨f base, apd f loop⟩}, { intro v x, induction v with p q, induction x, { exact p}, { exact q}}, { intro v, induction v with p q, fapply sigma_eq, { reflexivity}, { esimp, apply pathover_idp_of_eq, apply rec_loop}}, { intro f, apply eq_of_homotopy, intro x, induction x, { reflexivity}, { apply eq_pathover_dep, apply hdeg_squareover, esimp, apply rec_loop}} end definition circle_arrow_equiv [constructor] (P : Type) : (S¹ → P) ≃ Σ(p : P), p = p := begin fapply equiv.MK, { intro f, exact ⟨f base, ap f loop⟩}, { intro v x, induction v with p q, induction x, { exact p}, { exact q}}, { intro v, induction v with p q, fapply sigma_eq, { reflexivity}, { esimp, apply pathover_idp_of_eq, apply elim_loop}}, { intro f, apply eq_of_homotopy, intro x, induction x, { reflexivity}, { apply eq_pathover, apply hdeg_square, esimp, apply elim_loop}} end definition pointed_circle [instance] [constructor] : pointed S¹ := pointed.mk base definition pcircle [constructor] : Type* := pointed.mk' S¹ notation `S¹.` := pcircle definition loop_neq_idp : loop ≠ idp := assume H : loop = idp, have H2 : Π{A : Type₁} {a : A} {p : a = a}, p = idp, from λA a p, calc p = ap (circle.elim a p) loop : elim_loop ... = ap (circle.elim a p) (refl base) : by rewrite H, eq_bnot_ne_idp H2 definition nonidp (x : circle) : x = x := begin induction x, { exact loop}, { apply concato_eq, apply pathover_eq_lr, rewrite [con.left_inv,idp_con]} end definition nonidp_neq_idp : nonidp ≠ (λx, idp) := assume H : nonidp = λx, idp, have H2 : loop = idp, from apd10 H base, absurd H2 loop_neq_idp open int protected definition code [unfold 1] (x : circle) : Type₀ := circle.elim_type_on x ℤ equiv_succ definition transport_code_loop (a : ℤ) : transport circle.code loop a = succ a := ap10 !elim_type_loop a definition transport_code_loop_inv (a : ℤ) : transport circle.code loop⁻¹ a = pred a := ap10 !elim_type_loop_inv a protected definition encode [unfold 2] {x : circle} (p : base = x) : circle.code x := transport circle.code p (of_num 0) protected definition decode [unfold 1] {x : circle} : circle.code x → base = x := begin induction x, { exact power loop}, { apply arrow_pathover_left, intro b, apply concato_eq, apply pathover_eq_r, rewrite [power_con,transport_code_loop]} end definition circle_eq_equiv [constructor] (x : circle) : (base = x) ≃ circle.code x := begin fapply equiv.MK, { exact circle.encode}, { exact circle.decode}, { exact abstract [irreducible] begin induction x, { intro a, esimp, apply rec_nat_on a, { exact idp}, { intros n p, rewrite [↑circle.encode, -power_con, con_tr, transport_code_loop], exact ap succ p}, { intros n p, rewrite [↑circle.encode, nat_succ_eq_int_succ, neg_succ, -power_con_inv, @con_tr _ circle.code, transport_code_loop_inv, ↑[circle.encode] at p, p, -neg_succ] }}, { apply pathover_of_tr_eq, apply eq_of_homotopy, intro a, apply @is_set.elim, esimp, exact _} end end}, { intro p, cases p, exact idp}, end definition base_eq_base_equiv [constructor] : base = base ≃ ℤ := circle_eq_equiv base definition decode_add (a b : ℤ) : circle.decode (a +[ℤ] b) = circle.decode a ⬝ circle.decode b := !power_con_power⁻¹ definition encode_con (p q : base = base) : circle.encode (p ⬝ q) = circle.encode p +[ℤ] circle.encode q := preserve_binary_of_inv_preserve base_eq_base_equiv concat (@add ℤ _) decode_add p q --the carrier of π₁(S¹) is the set-truncation of base = base. open algebra trunc group definition fg_carrier_equiv_int : π[1](S¹.) ≃ ℤ := trunc_equiv_trunc 0 base_eq_base_equiv ⬝e @(trunc_equiv 0 ℤ) proof _ qed definition con_comm_base (p q : base = base) : p ⬝ q = q ⬝ p := eq_of_fn_eq_fn base_eq_base_equiv (by esimp;rewrite [+encode_con,add.comm]) definition fundamental_group_of_circle : π₁(S¹.) ≃g gℤ := begin apply (isomorphism_of_equiv fg_carrier_equiv_int), intros g h, induction g with g', induction h with h', apply encode_con, end open nat definition homotopy_group_of_circle (n : ℕ) : πg[n+1 +1] S¹. ≃g G0 := begin refine @trivial_homotopy_add_of_is_set_loop_space S¹. 1 n _, apply is_trunc_equiv_closed_rev, apply base_eq_base_equiv end definition eq_equiv_Z (x : S¹) : x = x ≃ ℤ := begin induction x, { apply base_eq_base_equiv}, { apply equiv_pathover, intro p p' q, apply pathover_of_eq, note H := eq_of_square (square_of_pathover q), rewrite con_comm_base at H, note H' := cancel_left _ H, induction H', reflexivity} end proposition is_trunc_circle [instance] : is_trunc 1 S¹ := begin apply is_trunc_succ_of_is_trunc_loop, { apply trunc_index.minus_one_le_succ}, { intro x, apply is_trunc_equiv_closed_rev, apply eq_equiv_Z} end proposition is_conn_circle [instance] : is_conn 0 circle := sphere.is_conn_sphere -1.+2 definition circle_turn [reducible] (x : S¹) : x = x := begin induction x, { exact loop }, { apply eq_pathover, apply square_of_eq, rewrite ap_id } end definition circle_mul [reducible] (x y : S¹) : S¹ := circle.elim y (circle_turn y) x definition circle_mul_base (x : S¹) : circle_mul x base = x := begin induction x, { reflexivity }, { apply eq_pathover, krewrite [elim_loop,ap_id], apply hrefl } end definition circle_base_mul [reducible] (x : S¹) : circle_mul base x = x := idp end circle
5c77407cc741b89791d5b73e58260e259cdb57e0
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/lie/basic.lean
f6a8c887d4e63eb2574fd6511d1bc23382a204e0
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,710
lean
/- Copyright (c) 2019 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import data.bracket import algebra.algebra.basic import tactic.noncomm_ring /-! # Lie algebras This file defines Lie rings and Lie algebras over a commutative ring together with their modules, morphisms and equivalences, as well as various lemmas to make these definitions usable. ## Main definitions * `lie_ring` * `lie_algebra` * `lie_ring_module` * `lie_module` * `lie_hom` * `lie_equiv` * `lie_module_hom` * `lie_module_equiv` ## Notation Working over a fixed commutative ring `R`, we introduce the notations: * `L →ₗ⁅R⁆ L'` for a morphism of Lie algebras, * `L ≃ₗ⁅R⁆ L'` for an equivalence of Lie algebras, * `M →ₗ⁅R,L⁆ N` for a morphism of Lie algebra modules `M`, `N` over a Lie algebra `L`, * `M ≃ₗ⁅R,L⁆ N` for an equivalence of Lie algebra modules `M`, `N` over a Lie algebra `L`. ## Implementation notes Lie algebras are defined as modules with a compatible Lie ring structure and thus, like modules, are partially unbundled. ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*](bourbaki1975) ## Tags lie bracket, jacobi identity, lie ring, lie algebra, lie module -/ universes u v w w₁ w₂ /-- A Lie ring is an additive group with compatible product, known as the bracket, satisfying the Jacobi identity. -/ @[protect_proj] class lie_ring (L : Type v) extends add_comm_group L, has_bracket L L := (add_lie : ∀ (x y z : L), ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆) (lie_add : ∀ (x y z : L), ⁅x, y + z⁆ = ⁅x, y⁆ + ⁅x, z⁆) (lie_self : ∀ (x : L), ⁅x, x⁆ = 0) (leibniz_lie : ∀ (x y z : L), ⁅x, ⁅y, z⁆⁆ = ⁅⁅x, y⁆, z⁆ + ⁅y, ⁅x, z⁆⁆) /-- A Lie algebra is a module with compatible product, known as the bracket, satisfying the Jacobi identity. Forgetting the scalar multiplication, every Lie algebra is a Lie ring. -/ @[protect_proj] class lie_algebra (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] extends module R L := (lie_smul : ∀ (t : R) (x y : L), ⁅x, t • y⁆ = t • ⁅x, y⁆) /-- A Lie ring module is an additive group, together with an additive action of a Lie ring on this group, such that the Lie bracket acts as the commutator of endomorphisms. (For representations of Lie *algebras* see `lie_module`.) -/ @[protect_proj] class lie_ring_module (L : Type v) (M : Type w) [lie_ring L] [add_comm_group M] extends has_bracket L M := (add_lie : ∀ (x y : L) (m : M), ⁅x + y, m⁆ = ⁅x, m⁆ + ⁅y, m⁆) (lie_add : ∀ (x : L) (m n : M), ⁅x, m + n⁆ = ⁅x, m⁆ + ⁅x, n⁆) (leibniz_lie : ∀ (x y : L) (m : M), ⁅x, ⁅y, m⁆⁆ = ⁅⁅x, y⁆, m⁆ + ⁅y, ⁅x, m⁆⁆) /-- A Lie module is a module over a commutative ring, together with a linear action of a Lie algebra on this module, such that the Lie bracket acts as the commutator of endomorphisms. -/ @[protect_proj] class lie_module (R : Type u) (L : Type v) (M : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] [lie_ring_module L M] := (smul_lie : ∀ (t : R) (x : L) (m : M), ⁅t • x, m⁆ = t • ⁅x, m⁆) (lie_smul : ∀ (t : R) (x : L) (m : M), ⁅x, t • m⁆ = t • ⁅x, m⁆) section basic_properties variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] variables (t : R) (x y z : L) (m n : M) @[simp] lemma add_lie : ⁅x + y, m⁆ = ⁅x, m⁆ + ⁅y, m⁆ := lie_ring_module.add_lie x y m @[simp] lemma lie_add : ⁅x, m + n⁆ = ⁅x, m⁆ + ⁅x, n⁆ := lie_ring_module.lie_add x m n @[simp] lemma smul_lie : ⁅t • x, m⁆ = t • ⁅x, m⁆ := lie_module.smul_lie t x m @[simp] lemma lie_smul : ⁅x, t • m⁆ = t • ⁅x, m⁆ := lie_module.lie_smul t x m lemma leibniz_lie : ⁅x, ⁅y, m⁆⁆ = ⁅⁅x, y⁆, m⁆ + ⁅y, ⁅x, m⁆⁆ := lie_ring_module.leibniz_lie x y m @[simp] lemma lie_zero : ⁅x, 0⁆ = (0 : M) := (add_monoid_hom.mk' _ (lie_add x)).map_zero @[simp] lemma zero_lie : ⁅(0 : L), m⁆ = 0 := (add_monoid_hom.mk' (λ (x : L), ⁅x, m⁆) (λ x y, add_lie x y m)).map_zero @[simp] lemma lie_self : ⁅x, x⁆ = 0 := lie_ring.lie_self x instance lie_ring_self_module : lie_ring_module L L := { ..(infer_instance : lie_ring L) } @[simp] lemma lie_skew : -⁅y, x⁆ = ⁅x, y⁆ := have h : ⁅x + y, x⁆ + ⁅x + y, y⁆ = 0, { rw ← lie_add, apply lie_self, }, by simpa [neg_eq_iff_add_eq_zero] using h /-- Every Lie algebra is a module over itself. -/ instance lie_algebra_self_module : lie_module R L L := { smul_lie := λ t x m, by rw [←lie_skew, ←lie_skew x m, lie_algebra.lie_smul, smul_neg], lie_smul := by apply lie_algebra.lie_smul, } @[simp] lemma neg_lie : ⁅-x, m⁆ = -⁅x, m⁆ := by { rw [←sub_eq_zero, sub_neg_eq_add, ←add_lie], simp, } @[simp] lemma lie_neg : ⁅x, -m⁆ = -⁅x, m⁆ := by { rw [←sub_eq_zero, sub_neg_eq_add, ←lie_add], simp, } @[simp] lemma sub_lie : ⁅x - y, m⁆ = ⁅x, m⁆ - ⁅y, m⁆ := by simp [sub_eq_add_neg] @[simp] lemma lie_sub : ⁅x, m - n⁆ = ⁅x, m⁆ - ⁅x, n⁆ := by simp [sub_eq_add_neg] @[simp] lemma nsmul_lie (n : ℕ) : ⁅n • x, m⁆ = n • ⁅x, m⁆ := add_monoid_hom.map_nsmul ⟨λ (x : L), ⁅x, m⁆, zero_lie m, λ _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_nsmul (n : ℕ) : ⁅x, n • m⁆ = n • ⁅x, m⁆ := add_monoid_hom.map_nsmul ⟨λ (m : M), ⁅x, m⁆, lie_zero x, λ _ _, lie_add _ _ _⟩ _ _ @[simp] lemma gsmul_lie (a : ℤ) : ⁅a • x, m⁆ = a • ⁅x, m⁆ := add_monoid_hom.map_gsmul ⟨λ (x : L), ⁅x, m⁆, zero_lie m, λ _ _, add_lie _ _ _⟩ _ _ @[simp] lemma lie_gsmul (a : ℤ) : ⁅x, a • m⁆ = a • ⁅x, m⁆ := add_monoid_hom.map_gsmul ⟨λ (m : M), ⁅x, m⁆, lie_zero x, λ _ _, lie_add _ _ _⟩ _ _ @[simp] lemma lie_lie : ⁅⁅x, y⁆, m⁆ = ⁅x, ⁅y, m⁆⁆ - ⁅y, ⁅x, m⁆⁆ := by rw [leibniz_lie, add_sub_cancel] lemma lie_jacobi : ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0 := by { rw [← neg_neg ⁅x, y⁆, lie_neg z, lie_skew y x, ← lie_skew, lie_lie], abel, } instance lie_ring.int_lie_algebra : lie_algebra ℤ L := { lie_smul := λ n x y, lie_gsmul x y n, } instance : lie_ring_module L (M →ₗ[R] N) := { bracket := λ x f, { to_fun := λ m, ⁅x, f m⁆ - f ⁅x, m⁆, map_add' := λ m n, by { simp only [lie_add, linear_map.map_add], abel, }, map_smul' := λ t m, by simp only [smul_sub, linear_map.map_smul, lie_smul], }, add_lie := λ x y f, by { ext n, simp only [add_lie, linear_map.coe_mk, linear_map.add_apply, linear_map.map_add], abel, }, lie_add := λ x f g, by { ext n, simp only [linear_map.coe_mk, lie_add, linear_map.add_apply], abel, }, leibniz_lie := λ x y f, by { ext n, simp only [lie_lie, linear_map.coe_mk, linear_map.map_sub, linear_map.add_apply, lie_sub], abel, }, } @[simp] lemma lie_hom.lie_apply (f : M →ₗ[R] N) (x : L) (m : M) : ⁅x, f⁆ m = ⁅x, f m⁆ - f ⁅x, m⁆ := rfl instance : lie_module R L (M →ₗ[R] N) := { smul_lie := λ t x f, by { ext n, simp only [smul_sub, smul_lie, linear_map.smul_apply, lie_hom.lie_apply, linear_map.map_smul], }, lie_smul := λ t x f, by { ext n, simp only [smul_sub, linear_map.smul_apply, lie_hom.lie_apply, lie_smul], }, } end basic_properties set_option old_structure_cmd true /-- A morphism of Lie algebras is a linear map respecting the bracket operations. -/ structure lie_hom (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends L →ₗ[R] L' := (map_lie' : ∀ {x y : L}, to_fun ⁅x, y⁆ = ⁅to_fun x, to_fun y⁆) attribute [nolint doc_blame] lie_hom.to_linear_map notation L ` →ₗ⁅`:25 R:25 `⁆ `:0 L':0 := lie_hom R L L' namespace lie_hom variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃] variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃] instance : has_coe (L₁ →ₗ⁅R⁆ L₂) (L₁ →ₗ[R] L₂) := ⟨lie_hom.to_linear_map⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ →ₗ⁅R⁆ L₂) := ⟨_, lie_hom.to_fun⟩ initialize_simps_projections lie_hom (to_fun → apply) @[simp, norm_cast] lemma coe_to_linear_map (f : L₁ →ₗ⁅R⁆ L₂) : ((f : L₁ →ₗ[R] L₂) : L₁ → L₂) = f := rfl @[simp] lemma to_fun_eq_coe (f : L₁ →ₗ⁅R⁆ L₂) : f.to_fun = ⇑f := rfl @[simp] lemma map_smul (f : L₁ →ₗ⁅R⁆ L₂) (c : R) (x : L₁) : f (c • x) = c • f x := linear_map.map_smul (f : L₁ →ₗ[R] L₂) c x @[simp] lemma map_add (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f (x + y) = (f x) + (f y) := linear_map.map_add (f : L₁ →ₗ[R] L₂) x y @[simp] lemma map_sub (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f (x - y) = (f x) - (f y) := linear_map.map_sub (f : L₁ →ₗ[R] L₂) x y @[simp] lemma map_neg (f : L₁ →ₗ⁅R⁆ L₂) (x : L₁) : f (-x) = -(f x) := linear_map.map_neg (f : L₁ →ₗ[R] L₂) x @[simp] lemma map_lie (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f ⁅x, y⁆ = ⁅f x, f y⁆ := lie_hom.map_lie' f @[simp] lemma map_zero (f : L₁ →ₗ⁅R⁆ L₂) : f 0 = 0 := (f : L₁ →ₗ[R] L₂).map_zero /-- The identity map is a morphism of Lie algebras. -/ def id : L₁ →ₗ⁅R⁆ L₁ := { map_lie' := λ x y, rfl, .. (linear_map.id : L₁ →ₗ[R] L₁) } @[simp] lemma coe_id : ((id : L₁ →ₗ⁅R⁆ L₁) : L₁ → L₁) = _root_.id := rfl lemma id_apply (x : L₁) : (id : L₁ →ₗ⁅R⁆ L₁) x = x := rfl /-- The constant 0 map is a Lie algebra morphism. -/ instance : has_zero (L₁ →ₗ⁅R⁆ L₂) := ⟨{ map_lie' := by simp, ..(0 : L₁ →ₗ[R] L₂)}⟩ @[norm_cast, simp] lemma coe_zero : ((0 : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = 0 := rfl lemma zero_apply (x : L₁) : (0 : L₁ →ₗ⁅R⁆ L₂) x = 0 := rfl /-- The identity map is a Lie algebra morphism. -/ instance : has_one (L₁ →ₗ⁅R⁆ L₁) := ⟨id⟩ @[simp] lemma coe_one : ((1 : (L₁ →ₗ⁅R⁆ L₁)) : L₁ → L₁) = _root_.id := rfl lemma one_apply (x : L₁) : (1 : (L₁ →ₗ⁅R⁆ L₁)) x = x := rfl instance : inhabited (L₁ →ₗ⁅R⁆ L₂) := ⟨0⟩ lemma coe_injective : @function.injective (L₁ →ₗ⁅R⁆ L₂) (L₁ → L₂) coe_fn := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] lemma ext {f g : L₁ →ₗ⁅R⁆ L₂} (h : ∀ x, f x = g x) : f = g := coe_injective $ funext h lemma ext_iff {f g : L₁ →ₗ⁅R⁆ L₂} : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ lemma congr_fun {f g : L₁ →ₗ⁅R⁆ L₂} (h : f = g) (x : L₁) : f x = g x := h ▸ rfl @[simp] lemma mk_coe (f : L₁ →ₗ⁅R⁆ L₂) (h₁ h₂ h₃) : (⟨f, h₁, h₂, h₃⟩ : L₁ →ₗ⁅R⁆ L₂) = f := by { ext, refl, } @[simp] lemma coe_mk (f : L₁ → L₂) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = f := rfl @[norm_cast, simp] lemma coe_linear_mk (f : L₁ →ₗ[R] L₂) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : L₁ →ₗ⁅R⁆ L₂) : L₁ →ₗ[R] L₂) = ⟨f, h₁, h₂⟩ := by { ext, refl, } /-- The composition of morphisms is a morphism. -/ def comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : L₁ →ₗ⁅R⁆ L₃ := { map_lie' := λ x y, by { change f (g ⁅x, y⁆) = ⁅f (g x), f (g y)⁆, rw [map_lie, map_lie], }, ..linear_map.comp f.to_linear_map g.to_linear_map } lemma comp_apply (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) (x : L₁) : f.comp g x = f (g x) := rfl @[norm_cast, simp] lemma coe_comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : (f.comp g : L₁ → L₃) = f ∘ g := rfl @[norm_cast, simp] lemma coe_linear_map_comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : (f.comp g : L₁ →ₗ[R] L₃) = (f : L₂ →ₗ[R] L₃).comp (g : L₁ →ₗ[R] L₂) := rfl @[simp] lemma comp_id (f : L₁ →ₗ⁅R⁆ L₂) : f.comp (id : L₁ →ₗ⁅R⁆ L₁) = f := by { ext, refl, } @[simp] lemma id_comp (f : L₁ →ₗ⁅R⁆ L₂) : (id : L₂ →ₗ⁅R⁆ L₂).comp f = f := by { ext, refl, } /-- The inverse of a bijective morphism is a morphism. -/ def inverse (f : L₁ →ₗ⁅R⁆ L₂) (g : L₂ → L₁) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : L₂ →ₗ⁅R⁆ L₁ := { map_lie' := λ x y, calc g ⁅x, y⁆ = g ⁅f (g x), f (g y)⁆ : by { conv_lhs { rw [←h₂ x, ←h₂ y], }, } ... = g (f ⁅g x, g y⁆) : by rw map_lie ... = ⁅g x, g y⁆ : (h₁ _), ..linear_map.inverse f.to_linear_map g h₁ h₂ } end lie_hom /-- An equivalence of Lie algebras is a morphism which is also a linear equivalence. We could instead define an equivalence to be a morphism which is also a (plain) equivalence. However it is more convenient to define via linear equivalence to get `.to_linear_equiv` for free. -/ structure lie_equiv (R : Type u) (L : Type v) (L' : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] extends L →ₗ⁅R⁆ L', L ≃ₗ[R] L' attribute [nolint doc_blame] lie_equiv.to_lie_hom attribute [nolint doc_blame] lie_equiv.to_linear_equiv notation L ` ≃ₗ⁅`:50 R `⁆ ` L' := lie_equiv R L L' namespace lie_equiv variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃] variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃] instance has_coe_to_lie_hom : has_coe (L₁ ≃ₗ⁅R⁆ L₂) (L₁ →ₗ⁅R⁆ L₂) := ⟨to_lie_hom⟩ instance has_coe_to_linear_equiv : has_coe (L₁ ≃ₗ⁅R⁆ L₂) (L₁ ≃ₗ[R] L₂) := ⟨to_linear_equiv⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (L₁ ≃ₗ⁅R⁆ L₂) := ⟨_, to_fun⟩ @[simp, norm_cast] lemma coe_to_lie_equiv (e : L₁ ≃ₗ⁅R⁆ L₂) : ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = e := rfl @[simp, norm_cast] lemma coe_to_linear_equiv (e : L₁ ≃ₗ⁅R⁆ L₂) : ((e : L₁ ≃ₗ[R] L₂) : L₁ → L₂) = e := rfl instance : has_one (L₁ ≃ₗ⁅R⁆ L₁) := ⟨{ map_lie' := λ x y, by { change ((1 : L₁→ₗ[R] L₁) ⁅x, y⁆) = ⁅(1 : L₁→ₗ[R] L₁) x, (1 : L₁→ₗ[R] L₁) y⁆, simp, }, ..(1 : L₁ ≃ₗ[R] L₁)}⟩ @[simp] lemma one_apply (x : L₁) : (1 : (L₁ ≃ₗ⁅R⁆ L₁)) x = x := rfl instance : inhabited (L₁ ≃ₗ⁅R⁆ L₁) := ⟨1⟩ /-- Lie algebra equivalences are reflexive. -/ @[refl] def refl : L₁ ≃ₗ⁅R⁆ L₁ := 1 @[simp] lemma refl_apply (x : L₁) : (refl : L₁ ≃ₗ⁅R⁆ L₁) x = x := rfl /-- Lie algebra equivalences are symmetric. -/ @[symm] def symm (e : L₁ ≃ₗ⁅R⁆ L₂) : L₂ ≃ₗ⁅R⁆ L₁ := { ..lie_hom.inverse e.to_lie_hom e.inv_fun e.left_inv e.right_inv, ..e.to_linear_equiv.symm } @[simp] lemma symm_symm (e : L₁ ≃ₗ⁅R⁆ L₂) : e.symm.symm = e := by { cases e, refl, } @[simp] lemma apply_symm_apply (e : L₁ ≃ₗ⁅R⁆ L₂) : ∀ x, e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : L₁ ≃ₗ⁅R⁆ L₂) : ∀ x, e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply /-- Lie algebra equivalences are transitive. -/ @[trans] def trans (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) : L₁ ≃ₗ⁅R⁆ L₃ := { ..lie_hom.comp e₂.to_lie_hom e₁.to_lie_hom, ..linear_equiv.trans e₁.to_linear_equiv e₂.to_linear_equiv } @[simp] lemma trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) (x : L₁) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl @[simp] lemma symm_trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) (x : L₃) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl lemma bijective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.bijective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) := e.to_linear_equiv.bijective lemma injective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.injective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) := e.to_linear_equiv.injective lemma surjective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.surjective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) := e.to_linear_equiv.surjective end lie_equiv section lie_module_morphisms variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) (P : Type w₂) variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [add_comm_group N] [add_comm_group P] variables [module R M] [module R N] [module R P] variables [lie_ring_module L M] [lie_ring_module L N] [lie_ring_module L P] variables [lie_module R L M] [lie_module R L N] [lie_module R L P] set_option old_structure_cmd true /-- A morphism of Lie algebra modules is a linear map which commutes with the action of the Lie algebra. -/ structure lie_module_hom extends M →ₗ[R] N := (map_lie' : ∀ {x : L} {m : M}, to_fun ⁅x, m⁆ = ⁅x, to_fun m⁆) attribute [nolint doc_blame] lie_module_hom.to_linear_map notation M ` →ₗ⁅`:25 R,L:25 `⁆ `:0 N:0 := lie_module_hom R L M N namespace lie_module_hom variables {R L M N P} instance : has_coe (M →ₗ⁅R,L⁆ N) (M →ₗ[R] N) := ⟨lie_module_hom.to_linear_map⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (M →ₗ⁅R,L⁆ N) := ⟨_, lie_module_hom.to_fun⟩ @[simp, norm_cast] lemma coe_to_linear_map (f : M →ₗ⁅R,L⁆ N) : ((f : M →ₗ[R] N) : M → N) = f := rfl @[simp] lemma map_smul (f : M →ₗ⁅R,L⁆ N) (c : R) (x : M) : f (c • x) = c • f x := linear_map.map_smul (f : M →ₗ[R] N) c x @[simp] lemma map_add (f : M →ₗ⁅R,L⁆ N) (x y : M) : f (x + y) = (f x) + (f y) := linear_map.map_add (f : M →ₗ[R] N) x y @[simp] lemma map_sub (f : M →ₗ⁅R,L⁆ N) (x y : M) : f (x - y) = (f x) - (f y) := linear_map.map_sub (f : M →ₗ[R] N) x y @[simp] lemma map_neg (f : M →ₗ⁅R,L⁆ N) (x : M) : f (-x) = -(f x) := linear_map.map_neg (f : M →ₗ[R] N) x @[simp] lemma map_lie (f : M →ₗ⁅R,L⁆ N) (x : L) (m : M) : f ⁅x, m⁆ = ⁅x, f m⁆ := lie_module_hom.map_lie' f lemma map_lie₂ (f : M →ₗ⁅R,L⁆ N →ₗ[R] P) (x : L) (m : M) (n : N) : ⁅x, f m n⁆ = f ⁅x, m⁆ n + f m ⁅x, n⁆ := by simp only [sub_add_cancel, map_lie, lie_hom.lie_apply] @[simp] lemma map_zero (f : M →ₗ⁅R,L⁆ N) : f 0 = 0 := linear_map.map_zero (f : M →ₗ[R] N) /-- The constant 0 map is a Lie module morphism. -/ instance : has_zero (M →ₗ⁅R,L⁆ N) := ⟨{ map_lie' := by simp, ..(0 : M →ₗ[R] N) }⟩ @[norm_cast, simp] lemma coe_zero : ((0 : M →ₗ⁅R,L⁆ N) : M → N) = 0 := rfl lemma zero_apply (m : M) : (0 : M →ₗ⁅R,L⁆ N) m = 0 := rfl /-- The identity map is a Lie module morphism. -/ instance : has_one (M →ₗ⁅R,L⁆ M) := ⟨{ map_lie' := by simp, ..(1 : M →ₗ[R] M) }⟩ instance : inhabited (M →ₗ⁅R,L⁆ N) := ⟨0⟩ lemma coe_injective : @function.injective (M →ₗ⁅R,L⁆ N) (M → N) coe_fn := by { rintros ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩, congr, } @[ext] lemma ext {f g : M →ₗ⁅R,L⁆ N} (h : ∀ m, f m = g m) : f = g := coe_injective $ funext h lemma ext_iff {f g : M →ₗ⁅R,L⁆ N} : f = g ↔ ∀ m, f m = g m := ⟨by { rintro rfl m, refl, }, ext⟩ lemma congr_fun {f g : M →ₗ⁅R,L⁆ N} (h : f = g) (x : M) : f x = g x := h ▸ rfl @[simp] lemma mk_coe (f : M →ₗ⁅R,L⁆ N) (h₁ h₂ h₃) : (⟨f, h₁, h₂, h₃⟩ : M →ₗ⁅R,L⁆ N) = f := by { ext, refl, } @[simp] lemma coe_mk (f : M → N) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : M →ₗ⁅R,L⁆ N) : M → N) = f := rfl @[norm_cast, simp] lemma coe_linear_mk (f : M →ₗ[R] N) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : M →ₗ⁅R,L⁆ N) : M →ₗ[R] N) = ⟨f, h₁, h₂⟩ := by { ext, refl, } /-- The composition of Lie module morphisms is a morphism. -/ def comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : M →ₗ⁅R,L⁆ P := { map_lie' := λ x m, by { change f (g ⁅x, m⁆) = ⁅x, f (g m)⁆, rw [map_lie, map_lie], }, ..linear_map.comp f.to_linear_map g.to_linear_map } lemma comp_apply (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) (m : M) : f.comp g m = f (g m) := rfl @[norm_cast, simp] lemma coe_comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : (f.comp g : M → P) = f ∘ g := rfl @[norm_cast, simp] lemma coe_linear_map_comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : (f.comp g : M →ₗ[R] P) = (f : N →ₗ[R] P).comp (g : M →ₗ[R] N) := rfl /-- The inverse of a bijective morphism of Lie modules is a morphism of Lie modules. -/ def inverse (f : M →ₗ⁅R,L⁆ N) (g : N → M) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : N →ₗ⁅R,L⁆ M := { map_lie' := λ x n, calc g ⁅x, n⁆ = g ⁅x, f (g n)⁆ : by rw h₂ ... = g (f ⁅x, g n⁆) : by rw map_lie ... = ⁅x, g n⁆ : (h₁ _), ..linear_map.inverse f.to_linear_map g h₁ h₂ } instance : has_add (M →ₗ⁅R,L⁆ N) := { add := λ f g, { map_lie' := by simp, ..((f : M →ₗ[R] N) + (g : M →ₗ[R] N)) }, } instance : has_sub (M →ₗ⁅R,L⁆ N) := { sub := λ f g, { map_lie' := by simp, ..((f : M →ₗ[R] N) - (g : M →ₗ[R] N)) }, } instance : has_neg (M →ₗ⁅R,L⁆ N) := { neg := λ f, { map_lie' := by simp, ..(-(f : (M →ₗ[R] N))) }, } @[norm_cast, simp] lemma coe_add (f g : M →ₗ⁅R,L⁆ N) : ⇑(f + g) = f + g := rfl lemma add_apply (f g : M →ₗ⁅R,L⁆ N) (m : M) : (f + g) m = f m + g m := rfl @[norm_cast, simp] lemma coe_sub (f g : M →ₗ⁅R,L⁆ N) : ⇑(f - g) = f - g := rfl lemma sub_apply (f g : M →ₗ⁅R,L⁆ N) (m : M) : (f - g) m = f m - g m := rfl @[norm_cast, simp] lemma coe_neg (f : M →ₗ⁅R,L⁆ N) : ⇑(-f) = -f := rfl lemma neg_apply (f : M →ₗ⁅R,L⁆ N) (m : M) : (-f) m = -(f m) := rfl instance : add_comm_group (M →ₗ⁅R,L⁆ N) := { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, nsmul := λ n f, { map_lie' := λ x m, by simp, ..(n • (f : M →ₗ[R] N)) }, nsmul_zero' := λ f, by { ext, simp, }, nsmul_succ' := λ n f, by { ext, simp [nat.succ_eq_one_add, add_nsmul], }, ..(coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub : add_comm_group (M →ₗ⁅R,L⁆ N)) } instance : has_scalar R (M →ₗ⁅R,L⁆ N) := { smul := λ t f, { map_lie' := by simp, ..(t • (f : M →ₗ[R] N)) }, } @[norm_cast, simp] lemma coe_smul (t : R) (f : M →ₗ⁅R,L⁆ N) : ⇑(t • f) = t • f := rfl lemma smul_apply (t : R) (f : M →ₗ⁅R,L⁆ N) (m : M) : (t • f) m = t • (f m) := rfl instance : module R (M →ₗ⁅R,L⁆ N) := function.injective.module R ⟨to_fun, rfl, coe_add⟩ coe_injective coe_smul end lie_module_hom /-- An equivalence of Lie algebra modules is a linear equivalence which is also a morphism of Lie algebra modules. -/ structure lie_module_equiv extends M ≃ₗ[R] N, M →ₗ⁅R,L⁆ N, M ≃ N attribute [nolint doc_blame] lie_module_equiv.to_equiv attribute [nolint doc_blame] lie_module_equiv.to_lie_module_hom attribute [nolint doc_blame] lie_module_equiv.to_linear_equiv notation M ` ≃ₗ⁅`:25 R,L:25 `⁆ `:0 N:0 := lie_module_equiv R L M N namespace lie_module_equiv variables {R L M N P} instance has_coe_to_equiv : has_coe (M ≃ₗ⁅R,L⁆ N) (M ≃ N) := ⟨to_equiv⟩ instance has_coe_to_lie_module_hom : has_coe (M ≃ₗ⁅R,L⁆ N) (M →ₗ⁅R,L⁆ N) := ⟨to_lie_module_hom⟩ instance has_coe_to_linear_equiv : has_coe (M ≃ₗ⁅R,L⁆ N) (M ≃ₗ[R] N) := ⟨to_linear_equiv⟩ /-- see Note [function coercion] -/ instance : has_coe_to_fun (M ≃ₗ⁅R,L⁆ N) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : M → N) (h₁ h₂ F h₃ h₄ h₅) : ((⟨f, h₁, h₂, F, h₃, h₄, h₅⟩ : M ≃ₗ⁅R,L⁆ N) : M → N) = f := rfl @[simp, norm_cast] lemma coe_to_lie_module_hom (e : M ≃ₗ⁅R,L⁆ N) : ((e : M →ₗ⁅R,L⁆ N) : M → N) = e := rfl @[simp, norm_cast] lemma coe_to_linear_equiv (e : M ≃ₗ⁅R,L⁆ N) : ((e : M ≃ₗ[R] N) : M → N) = e := rfl lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ⁅R,L⁆ N) → M ≃ N) := λ ⟨_, _, _, _, _, _, _⟩ ⟨_, _, _, _, _, _, _⟩ h, lie_module_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[ext] lemma ext (e₁ e₂ : M ≃ₗ⁅R,L⁆ N) (h : ∀ m, e₁ m = e₂ m) : e₁ = e₂ := to_equiv_injective (equiv.ext h) instance : has_one (M ≃ₗ⁅R,L⁆ M) := ⟨{ map_lie' := λ x m, rfl, ..(1 : M ≃ₗ[R] M) }⟩ @[simp] lemma one_apply (m : M) : (1 : (M ≃ₗ⁅R,L⁆ M)) m = m := rfl instance : inhabited (M ≃ₗ⁅R,L⁆ M) := ⟨1⟩ /-- Lie module equivalences are reflexive. -/ @[refl] def refl : M ≃ₗ⁅R,L⁆ M := 1 @[simp] lemma refl_apply (m : M) : (refl : M ≃ₗ⁅R,L⁆ M) m = m := rfl /-- Lie module equivalences are syemmtric. -/ @[symm] def symm (e : M ≃ₗ⁅R,L⁆ N) : N ≃ₗ⁅R,L⁆ M := { ..lie_module_hom.inverse e.to_lie_module_hom e.inv_fun e.left_inv e.right_inv, ..(e : M ≃ₗ[R] N).symm } @[simp] lemma symm_symm (e : M ≃ₗ⁅R,L⁆ N) : e.symm.symm = e := by { cases e, refl, } @[simp] lemma apply_symm_apply (e : M ≃ₗ⁅R,L⁆ N) : ∀ x, e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : M ≃ₗ⁅R,L⁆ N) : ∀ x, e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply /-- Lie module equivalences are transitive. -/ @[trans] def trans (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) : M ≃ₗ⁅R,L⁆ P := { ..lie_module_hom.comp e₂.to_lie_module_hom e₁.to_lie_module_hom, ..linear_equiv.trans e₁.to_linear_equiv e₂.to_linear_equiv } @[simp] lemma trans_apply (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) (m : M) : (e₁.trans e₂) m = e₂ (e₁ m) := rfl @[simp] lemma symm_trans_apply (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) (p : P) : (e₁.trans e₂).symm p = e₁.symm (e₂.symm p) := rfl end lie_module_equiv end lie_module_morphisms
226054cde855cb6a4eb235b1a9a98d674ca330b1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/extra/goal_hole.lean
d8a8a2b342858a34e512ba88d2d82ad0bc568145
[ "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
106
lean
example (a b c : nat) : a = b → b = c → a = c := begin intro h₁ h₂, exact eq.trans _ h₂ end
1bfa421ff716f2b6f6ba621e31b5b76b5623eb55
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/support.lean
808283562912b6a3432230f9d2286a4f8db8a093
[ "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
4,861
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import order.conditionally_complete_lattice import algebra.big_operators /-! # Support of a function In this file we define `function.support f = {x | f x ≠ 0}` and prove its basic properties. -/ universes u v w x y open set open_locale big_operators namespace function variables {α : Type u} {β : Type v} {ι : Sort w} {A : Type x} {B : Type y} /-- `support` of a function is the set of points `x` such that `f x ≠ 0`. -/ def support [has_zero A] (f : α → A) : set α := {x | f x ≠ 0} lemma nmem_support [has_zero A] {f : α → A} {x : α} : x ∉ support f ↔ f x = 0 := classical.not_not lemma mem_support [has_zero A] {f : α → A} {x : α} : x ∈ support f ↔ f x ≠ 0 := iff.rfl lemma support_binop_subset [has_zero A] (op : A → A → A) (op0 : op 0 0 = 0) (f g : α → A) : support (λ x, op (f x) (g x)) ⊆ support f ∪ support g := λ x hx, classical.by_cases (λ hf : f x = 0, or.inr $ λ hg, hx $ by simp only [hf, hg, op0]) or.inl lemma support_add [add_monoid A] (f g : α → A) : support (λ x, f x + g x) ⊆ support f ∪ support g := support_binop_subset (+) (zero_add _) f g @[simp] lemma support_neg [add_group A] (f : α → A) : support (λ x, -f x) = support f := set.ext $ λ x, not_congr neg_eq_zero lemma support_sub [add_group A] (f g : α → A) : support (λ x, f x - g x) ⊆ support f ∪ support g := support_binop_subset (has_sub.sub) (sub_self _) f g @[simp] lemma support_mul [mul_zero_class A] [no_zero_divisors A] (f g : α → A) : support (λ x, f x * g x) = support f ∩ support g := set.ext $ λ x, by simp only [support, ne.def, mul_eq_zero, mem_set_of_eq, mem_inter_iff, not_or_distrib] @[simp] lemma support_inv [division_ring A] (f : α → A) : support (λ x, (f x)⁻¹) = support f := set.ext $ λ x, not_congr inv_eq_zero @[simp] lemma support_div [division_ring A] (f g : α → A) : support (λ x, f x / g x) = support f ∩ support g := by simp [div_eq_mul_inv] lemma support_sup [has_zero A] [semilattice_sup A] (f g : α → A) : support (λ x, (f x) ⊔ (g x)) ⊆ support f ∪ support g := support_binop_subset (⊔) sup_idem f g lemma support_inf [has_zero A] [semilattice_inf A] (f g : α → A) : support (λ x, (f x) ⊓ (g x)) ⊆ support f ∪ support g := support_binop_subset (⊓) inf_idem f g lemma support_max [has_zero A] [decidable_linear_order A] (f g : α → A) : support (λ x, max (f x) (g x)) ⊆ support f ∪ support g := support_sup f g lemma support_min [has_zero A] [decidable_linear_order A] (f g : α → A) : support (λ x, min (f x) (g x)) ⊆ support f ∪ support g := support_inf f g lemma support_supr [has_zero A] [conditionally_complete_lattice A] [nonempty ι] (f : ι → α → A) : support (λ x, ⨆ i, f i x) ⊆ ⋃ i, support (f i) := begin intros x hx, classical, contrapose hx, simp only [mem_Union, not_exists, nmem_support] at hx ⊢, simp only [hx, csupr_const] end lemma support_infi [has_zero A] [conditionally_complete_lattice A] [nonempty ι] (f : ι → α → A) : support (λ x, ⨅ i, f i x) ⊆ ⋃ i, support (f i) := @support_supr _ _ (order_dual A) ⟨(0:A)⟩ _ _ f lemma support_sum [add_comm_monoid A] (s : finset α) (f : α → β → A) : support (λ x, ∑ i in s, f i x) ⊆ ⋃ i ∈ s, support (f i) := begin intros x hx, classical, contrapose hx, simp only [mem_Union, not_exists, nmem_support] at hx ⊢, exact finset.sum_eq_zero hx end lemma support_prod_subset [comm_monoid_with_zero A] (s : finset α) (f : α → β → A) : support (λ x, ∏ i in s, f i x) ⊆ ⋂ i ∈ s, support (f i) := λ x hx, mem_bInter_iff.2 $ λ i hi H, hx $ finset.prod_eq_zero hi H lemma support_prod [comm_monoid_with_zero A] [no_zero_divisors A] [nontrivial A] (s : finset α) (f : α → β → A) : support (λ x, ∏ i in s, f i x) = ⋂ i ∈ s, support (f i) := set.ext $ λ x, by simp only [support, ne.def, finset.prod_eq_zero_iff, mem_set_of_eq, set.mem_Inter, not_exists] lemma support_comp [has_zero A] [has_zero B] (g : A → B) (hg : g 0 = 0) (f : α → A) : support (g ∘ f) ⊆ support f := λ x, mt $ λ h, by simp [(∘), *] lemma support_comp' [has_zero A] [has_zero B] (g : A → B) (hg : g 0 = 0) (f : α → A) : support (λ x, g (f x)) ⊆ support f := support_comp g hg f lemma support_comp_eq [has_zero A] [has_zero B] (g : A → B) (hg : ∀ {x}, g x = 0 ↔ x = 0) (f : α → A) : support (g ∘ f) = support f := set.ext $ λ x, not_congr hg lemma support_comp_eq' [has_zero A] [has_zero B] (g : A → B) (hg : ∀ {x}, g x = 0 ↔ x = 0) (f : α → A) : support (λ x, g (f x)) = support f := support_comp_eq g @hg f end function
765d6c02c6719daa2315b56a58b29df1555a7b64
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/Manufacturable.lean
010239c3dd5a867c8387681396b9a0ad8419c5cb
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
695
lean
-- Manufacturable /- [Manufacturable] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Efficient]. An instance of type [SystemType] is deemed [Manufacturable] if and only if all the requirements are satisfied. -/ import SystemModel.System inductive Manufacturable (sys_type: SystemType): Prop | intro : (exists manufacturable: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, manufacturable c p s st) -> Manufacturable
fa8dd159cd36e5772929d351710dc6f78a8e7e5e
94e33a31faa76775069b071adea97e86e218a8ee
/src/tactic/doc_commands.lean
721a9e477b84bc5056940e1218c28049878d811a
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
17,319
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.fix_reflect_string /-! # Documentation commands We generate html documentation from mathlib. It is convenient to collect lists of tactics, commands, notes, etc. To facilitate this, we declare these documentation entries in the library using special commands. * `library_note` adds a note describing a certain feature or design decision. These can be referenced in doc strings with the text `note [name of note]`. * `add_tactic_doc` adds an entry documenting an interactive tactic, command, hole command, or attribute. Since these commands are used in files imported by `tactic.core`, this file has no imports. ## Implementation details `library_note note_id note_msg` creates a declaration `` `library_note.i `` for some `i`. This declaration is a pair of strings `note_id` and `note_msg`, and it gets tagged with the `library_note` attribute. Similarly, `add_tactic_doc` creates a declaration `` `tactic_doc.i `` that stores the provided information. -/ /-- A rudimentary hash function on strings. -/ def string.hash (s : string) : ℕ := s.fold 1 (λ h c, (33*h + c.val) % unsigned_sz) /-- `mk_hashed_name nspace id` hashes the string `id` to a value `i` and returns the name `nspace._i` -/ meta def string.mk_hashed_name (nspace : name) (id : string) : name := nspace <.> ("_" ++ to_string id.hash) open tactic /-- `copy_doc_string fr to` copies the docstring from the declaration named `fr` to each declaration named in the list `to`. -/ meta def tactic.copy_doc_string (fr : name) (to : list name) : tactic unit := do fr_ds ← doc_string fr, to.mmap' $ λ tgt, add_doc_string tgt fr_ds open lean lean.parser interactive /-- `copy_doc_string source → target_1 target_2 ... target_n` copies the doc string of the declaration named `source` to each of `target_1`, `target_2`, ..., `target_n`. -/ @[user_command] meta def copy_doc_string_cmd (_ : parse (tk "copy_doc_string")) : parser unit := do fr ← parser.ident, tk "->", to ← parser.many parser.ident, expr.const fr _ ← resolve_name fr, to ← parser.of_tactic (to.mmap $ λ n, expr.const_name <$> resolve_name n), tactic.copy_doc_string fr to /-! ### The `library_note` command -/ /-- A user attribute `library_note` for tagging decls of type `string × string` for use in note output. -/ @[user_attribute] meta def library_note_attr : user_attribute := { name := `library_note, descr := "Notes about library features to be included in documentation", parser := failed } /-- `mk_reflected_definition name val` constructs a definition declaration by reflection. Example: ``mk_reflected_definition `foo 17`` constructs the definition declaration corresponding to `def foo : ℕ := 17` -/ meta def mk_reflected_definition (decl_name : name) {type} [reflected _ type] (body : type) [reflected _ body] : declaration := mk_definition decl_name (reflect type).collect_univ_params (reflect type) (reflect body) /-- If `note_name` and `note` are `pexpr`s representing strings, `add_library_note note_name note` adds a declaration of type `string × string` and tags it with the `library_note` attribute. -/ meta def tactic.add_library_note (note_name note : string) : tactic unit := do let decl_name := note_name.mk_hashed_name `library_note, add_decl $ mk_reflected_definition decl_name (note_name, note), library_note_attr.set decl_name () tt none open tactic /-- A command to add library notes. Syntax: ``` /-- note message -/ library_note "note id" ``` -/ @[user_command] meta def library_note (mi : interactive.decl_meta_info) (_ : parse (tk "library_note")) : parser unit := do note_name ← parser.pexpr, note_name ← eval_pexpr string note_name, some doc_string ← pure mi.doc_string | fail "library_note requires a doc string", add_library_note note_name doc_string /-- Collects all notes in the current environment. Returns a list of pairs `(note_id, note_content)` -/ meta def tactic.get_library_notes : tactic (list (string × string)) := attribute.get_instances `library_note >>= list.mmap (λ dcl, mk_const dcl >>= eval_expr (string × string)) /-! ### The `add_tactic_doc_entry` command -/ /-- The categories of tactic doc entry. -/ @[derive [decidable_eq, has_reflect]] inductive doc_category | tactic | cmd | hole_cmd | attr /-- Format a `doc_category` -/ meta def doc_category.to_string : doc_category → string | doc_category.tactic := "tactic" | doc_category.cmd := "command" | doc_category.hole_cmd := "hole_command" | doc_category.attr := "attribute" meta instance : has_to_format doc_category := ⟨↑doc_category.to_string⟩ /-- The information used to generate a tactic doc entry -/ @[derive has_reflect] structure tactic_doc_entry := (name : string) (category : doc_category) (decl_names : list _root_.name) (tags : list string := []) (description : string := "") (inherit_description_from : option _root_.name := none) /-- Turns a `tactic_doc_entry` into a JSON representation. -/ meta def tactic_doc_entry.to_json (d : tactic_doc_entry) : json := json.object [ ("name", d.name), ("category", d.category.to_string), ("decl_names", d.decl_names.map (json.of_string ∘ to_string)), ("tags", d.tags.map json.of_string), ("description", d.description) ] meta instance : has_to_string tactic_doc_entry := ⟨json.unparse ∘ tactic_doc_entry.to_json⟩ /-- `update_description_from tde inh_id` replaces the `description` field of `tde` with the doc string of the declaration named `inh_id`. -/ meta def tactic_doc_entry.update_description_from (tde : tactic_doc_entry) (inh_id : name) : tactic tactic_doc_entry := do ds ← doc_string inh_id <|> fail (to_string inh_id ++ " has no doc string"), return { description := ds .. tde } /-- `update_description tde` replaces the `description` field of `tde` with: * the doc string of `tde.inherit_description_from`, if this field has a value * the doc string of the entry in `tde.decl_names`, if this field has length 1 If neither of these conditions are met, it returns `tde`. -/ meta def tactic_doc_entry.update_description (tde : tactic_doc_entry) : tactic tactic_doc_entry := match tde.inherit_description_from, tde.decl_names with | some inh_id, _ := tde.update_description_from inh_id | none, [inh_id] := tde.update_description_from inh_id | none, _ := return tde end /-- A user attribute `tactic_doc` for tagging decls of type `tactic_doc_entry` for use in doc output -/ @[user_attribute] meta def tactic_doc_entry_attr : user_attribute := { name := `tactic_doc, descr := "Information about a tactic to be included in documentation", parser := failed } /-- Collects everything in the environment tagged with the attribute `tactic_doc`. -/ meta def tactic.get_tactic_doc_entries : tactic (list tactic_doc_entry) := attribute.get_instances `tactic_doc >>= list.mmap (λ dcl, mk_const dcl >>= eval_expr tactic_doc_entry) /-- `add_tactic_doc tde` adds a declaration to the environment with `tde` as its body and tags it with the `tactic_doc` attribute. If `tde.decl_names` has exactly one entry `` `decl`` and if `tde.description` is the empty string, `add_tactic_doc` uses the doc string of `decl` as the description. -/ meta def tactic.add_tactic_doc (tde : tactic_doc_entry) : tactic unit := do when (tde.description = "" ∧ tde.inherit_description_from.is_none ∧ tde.decl_names.length ≠ 1) $ fail "A tactic doc entry must either: 1. have a description written as a doc-string for the `add_tactic_doc` invocation, or 2. have a single declaration in the `decl_names` field, to inherit a description from, or 3. explicitly indicate the declaration to inherit the description from using `inherit_description_from`.", tde ← if tde.description = "" then tde.update_description else return tde, let decl_name := (tde.name ++ tde.category.to_string).mk_hashed_name `tactic_doc, add_decl $ mk_definition decl_name [] `(tactic_doc_entry) (reflect tde), tactic_doc_entry_attr.set decl_name () tt none /-- A command used to add documentation for a tactic, command, hole command, or attribute. Usage: after defining an interactive tactic, command, or attribute, add its documentation as follows. ```lean /-- describe what the command does here -/ add_tactic_doc { name := "display name of the tactic", category := cat, decl_names := [`dcl_1, `dcl_2], tags := ["tag_1", "tag_2"] } ``` The argument to `add_tactic_doc` is a structure of type `tactic_doc_entry`. * `name` refers to the display name of the tactic; it is used as the header of the doc entry. * `cat` refers to the category of doc entry. Options: `doc_category.tactic`, `doc_category.cmd`, `doc_category.hole_cmd`, `doc_category.attr` * `decl_names` is a list of the declarations associated with this doc. For instance, the entry for `linarith` would set ``decl_names := [`tactic.interactive.linarith]``. Some entries may cover multiple declarations. It is only necessary to list the interactive versions of tactics. * `tags` is an optional list of strings used to categorize entries. * The doc string is the body of the entry. It can be formatted with markdown. What you are reading now is the description of `add_tactic_doc`. If only one related declaration is listed in `decl_names` and if this invocation of `add_tactic_doc` does not have a doc string, the doc string of that declaration will become the body of the tactic doc entry. If there are multiple declarations, you can select the one to be used by passing a name to the `inherit_description_from` field. If you prefer a tactic to have a doc string that is different then the doc entry, you should write the doc entry as a doc string for the `add_tactic_doc` invocation. Note that providing a badly formed `tactic_doc_entry` to the command can result in strange error messages. -/ @[user_command] meta def add_tactic_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_tactic_doc") : parser unit := do pe ← parser.pexpr, e ← eval_pexpr tactic_doc_entry pe, let e : tactic_doc_entry := match mi.doc_string with | some desc := { description := desc, ..e } | none := e end, tactic.add_tactic_doc e . /-- At various places in mathlib, we leave implementation notes that are referenced from many other files. To keep track of these notes, we use the command `library_note`. This makes it easy to retrieve a list of all notes, e.g. for documentation output. These notes can be referenced in mathlib with the syntax `Note [note id]`. Often, these references will be made in code comments (`--`) that won't be displayed in docs. If such a reference is made in a doc string or module doc, it will be linked to the corresponding note in the doc display. Syntax: ``` /-- note message -/ library_note "note id" ``` An example from `meta.expr`: ``` /-- Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ library_note "open expressions" ``` This note can be referenced near a usage of `pi_binders`: ``` -- See Note [open expressions] /-- behavior of f -/ def f := pi_binders ... ``` -/ add_tactic_doc { name := "library_note", category := doc_category.cmd, decl_names := [`library_note, `tactic.add_library_note], tags := ["documentation"], inherit_description_from := `library_note } add_tactic_doc { name := "add_tactic_doc", category := doc_category.cmd, decl_names := [`add_tactic_doc_command, `tactic.add_tactic_doc], tags := ["documentation"], inherit_description_from := `add_tactic_doc_command } add_tactic_doc { name := "copy_doc_string", category := doc_category.cmd, decl_names := [`copy_doc_string_cmd, `tactic.copy_doc_string], tags := ["documentation"], inherit_description_from := `copy_doc_string_cmd } -- add docs to core tactics /-- The congruence closure tactic `cc` tries to solve the goal by chaining equalities from context and applying congruence (i.e. if `a = b`, then `f a = f b`). It is a finishing tactic, i.e. it is meant to close the current goal, not to make some inconclusive progress. A mostly trivial example would be: ```lean example (a b c : ℕ) (f : ℕ → ℕ) (h: a = b) (h' : b = c) : f a = f c := by cc ``` As an example requiring some thinking to do by hand, consider: ```lean example (f : ℕ → ℕ) (x : ℕ) (H1 : f (f (f x)) = x) (H2 : f (f (f (f (f x)))) = x) : f x = x := by cc ``` The tactic works by building an equality matching graph. It's a graph where the vertices are terms and they are linked by edges if they are known to be equal. Once you've added all the equalities in your context, you take the transitive closure of the graph and, for each connected component (i.e. equivalence class) you can elect a term that will represent the whole class and store proofs that the other elements are equal to it. You then take the transitive closure of these equalities under the congruence lemmas. The `cc` implementation in Lean does a few more tricks: for example it derives `a=b` from `nat.succ a = nat.succ b`, and `nat.succ a != nat.zero` for any `a`. * The starting reference point is Nelson, Oppen, [Fast decision procedures based on congruence closure](http://www.cs.colorado.edu/~bec/courses/csci5535-s09/reading/nelson-oppen-congruence.pdf), Journal of the ACM (1980) * The congruence lemmas for dependent type theory as used in Lean are described in [Congruence closure in intensional type theory](https://leanprover.github.io/papers/congr.pdf) (de Moura, Selsam IJCAR 2016). -/ add_tactic_doc { name := "cc (congruence closure)", category := doc_category.tactic, decl_names := [`tactic.interactive.cc], tags := ["core", "finishing"] } /-- `conv {...}` allows the user to perform targeted rewriting on a goal or hypothesis, by focusing on particular subexpressions. See <https://leanprover-community.github.io/extras/conv.html> for more details. Inside `conv` blocks, mathlib currently additionally provides * `erw`, * `ring`, `ring2` and `ring_exp`, * `norm_num`, * `norm_cast`, * `apply_congr`, and * `conv` (within another `conv`). `apply_congr` applies congruence lemmas to step further inside expressions, and sometimes gives better results than the automatically generated congruence lemmas used by `congr`. Using `conv` inside a `conv` block allows the user to return to the previous state of the outer `conv` block after it is finished. Thus you can continue editing an expression without having to start a new `conv` block and re-scoping everything. For example: ```lean example (a b c d : ℕ) (h₁ : b = c) (h₂ : a + c = a + d) : a + b = a + d := by conv { to_lhs, conv { congr, skip, rw h₁ }, rw h₂, } ``` Without `conv`, the above example would need to be proved using two successive `conv` blocks, each beginning with `to_lhs`. Also, as a shorthand, `conv_lhs` and `conv_rhs` are provided, so that ```lean example : 0 + 0 = 0 := begin conv_lhs { simp } end ``` just means ```lean example : 0 + 0 = 0 := begin conv { to_lhs, simp } end ``` and likewise for `to_rhs`. -/ add_tactic_doc { name := "conv", category := doc_category.tactic, decl_names := [`tactic.interactive.conv], tags := ["core"] } add_tactic_doc { name := "simp", category := doc_category.tactic, decl_names := [`tactic.interactive.simp], tags := ["core", "simplification"] } /-- Accepts terms with the type `component tactic_state string` or `html empty` and renders them interactively. Requires a compatible version of the vscode extension to view the resulting widget. ### Example: ```lean /-- A simple counter that can be incremented or decremented with some buttons. -/ meta def counter_widget {π α : Type} : component π α := component.ignore_props $ component.mk_simple int int 0 (λ _ x y, (x + y, none)) (λ _ s, h "div" [] [ button "+" (1 : int), html.of_string $ to_string $ s, button "-" (-1) ] ) #html counter_widget ``` -/ add_tactic_doc { name := "#html", category := doc_category.cmd, decl_names := [`show_widget_cmd], tags := ["core", "widgets"] } /-- The `add_decl_doc` command is used to add a doc string to an existing declaration. ```lean def foo := 5 /-- Doc string for foo. -/ add_decl_doc foo ``` -/ @[user_command] meta def add_decl_doc_command (mi : interactive.decl_meta_info) (_ : parse $ tk "add_decl_doc") : parser unit := do n ← parser.ident, n ← resolve_constant n, some doc ← pure mi.doc_string | fail "add_decl_doc requires a doc string", add_doc_string n doc add_tactic_doc { name := "add_decl_doc", category := doc_category.cmd, decl_names := [``add_decl_doc_command], tags := ["documentation"] }
1f90958a93ec9d96cbb986f090de2bfacec9d9df
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/set/finite.lean
df1546892420e2a4a65078bcb59942471db68b41
[ "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
8,756
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The notion of "finiteness" for sets. This approach is not computational: for example, just because an element s : set A satsifies finite s doesn't mean that we can compute the cardinality. For a computational representation, use the finset type. -/ import data.finset.to_set .classical_inverse open nat classical variable {A : Type} namespace set definition finite [class] (s : set A) : Prop := ∃ (s' : finset A), s = finset.to_set s' theorem finite_finset [instance] (s : finset A) : finite (finset.to_set s) := exists.intro s rfl /- to finset: casts every set to a finite set -/ noncomputable definition to_finset (s : set A) : finset A := if fins : finite s then some fins else finset.empty theorem to_finset_of_not_finite {s : set A} (nfins : ¬ finite s) : to_finset s = (#finset ∅) := by rewrite [↑to_finset, dif_neg nfins] theorem to_set_to_finset (s : set A) [fins : finite s] : finset.to_set (to_finset s) = s := by rewrite [↑to_finset, dif_pos fins]; exact eq.symm (some_spec fins) theorem mem_to_finset_eq (a : A) (s : set A) [finite s] : (#finset a ∈ to_finset s) = (a ∈ s) := by rewrite [-to_set_to_finset at {2}] theorem to_set_to_finset_of_not_finite {s : set A} (nfins : ¬ finite s) : finset.to_set (to_finset s) = ∅ := by rewrite [to_finset_of_not_finite nfins] theorem to_finset_to_set (s : finset A) : to_finset (finset.to_set s) = s := by rewrite [finset.eq_eq_to_set_eq, to_set_to_finset (finset.to_set s)] theorem to_finset_eq_of_to_set_eq {s : set A} {t : finset A} (H : finset.to_set t = s) : to_finset s = t := finset.eq_of_to_set_eq_to_set (by subst [s]; rewrite to_finset_to_set) /- finiteness -/ theorem finite_of_to_set_to_finset_eq {s : set A} (H : finset.to_set (to_finset s) = s) : finite s := by rewrite -H; apply finite_finset theorem finite_empty [instance] : finite (∅ : set A) := by rewrite [-finset.to_set_empty]; apply finite_finset theorem to_finset_empty : to_finset (∅ : set A) = (#finset ∅) := to_finset_eq_of_to_set_eq !finset.to_set_empty theorem to_finset_eq_empty_of_eq_empty {s : set A} [fins : finite s] (H : s = ∅) : to_finset s = finset.empty := by rewrite [H, to_finset_empty] theorem eq_empty_of_to_finset_eq_empty {s : set A} [fins : finite s] (H : to_finset s = finset.empty) : s = ∅ := by rewrite [-finset.to_set_empty, -H, to_set_to_finset] theorem to_finset_eq_empty (s : set A) [fins : finite s] : (to_finset s = finset.empty) ↔ (s = ∅) := iff.intro eq_empty_of_to_finset_eq_empty to_finset_eq_empty_of_eq_empty theorem finite_insert [instance] (a : A) (s : set A) [finite s] : finite (insert a s) := exists.intro (finset.insert a (to_finset s)) (by rewrite [finset.to_set_insert, to_set_to_finset]) theorem to_finset_insert (a : A) (s : set A) [finite s] : to_finset (insert a s) = finset.insert a (to_finset s) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_insert, to_set_to_finset] theorem finite_union [instance] (s t : set A) [finite s] [finite t] : finite (s ∪ t) := exists.intro (#finset to_finset s ∪ to_finset t) (by rewrite [finset.to_set_union, *to_set_to_finset]) theorem to_finset_union (s t : set A) [finite s] [finite t] : to_finset (s ∪ t) = (#finset to_finset s ∪ to_finset t) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_union, *to_set_to_finset] theorem finite_inter [instance] (s t : set A) [finite s] [finite t] : finite (s ∩ t) := exists.intro (#finset to_finset s ∩ to_finset t) (by rewrite [finset.to_set_inter, *to_set_to_finset]) theorem to_finset_inter (s t : set A) [finite s] [finite t] : to_finset (s ∩ t) = (#finset to_finset s ∩ to_finset t) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_inter, *to_set_to_finset] theorem finite_sep [instance] (s : set A) (p : A → Prop) [finite s] : finite {x ∈ s | p x} := exists.intro (finset.sep p (to_finset s)) (by rewrite [finset.to_set_sep, *to_set_to_finset]) theorem to_finset_sep (s : set A) (p : A → Prop) [finite s] : to_finset {x ∈ s | p x} = (#finset {x ∈ to_finset s | p x}) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_sep, to_set_to_finset] theorem finite_image [instance] {B : Type} (f : A → B) (s : set A) [finite s] : finite (f ' s) := exists.intro (finset.image f (to_finset s)) (by rewrite [finset.to_set_image, *to_set_to_finset]) theorem to_finset_image {B : Type} (f : A → B) (s : set A) [fins : finite s] : to_finset (f ' s) = (#finset f ' (to_finset s)) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_image, to_set_to_finset] theorem finite_diff [instance] (s t : set A) [finite s] : finite (s \ t) := !finite_sep theorem to_finset_diff (s t : set A) [finite s] [finite t] : to_finset (s \ t) = (#finset to_finset s \ to_finset t) := by apply to_finset_eq_of_to_set_eq; rewrite [finset.to_set_diff, *to_set_to_finset] theorem finite_subset {s t : set A} [finite t] (ssubt : s ⊆ t) : finite s := by rewrite (eq_sep_of_subset ssubt); apply finite_sep theorem to_finset_subset_to_finset_eq (s t : set A) [finite s] [finite t] : (#finset to_finset s ⊆ to_finset t) = (s ⊆ t) := by rewrite [finset.subset_eq_to_set_subset, *to_set_to_finset] theorem finite_of_finite_insert {s : set A} {a : A} (finias : finite (insert a s)) : finite s := finite_subset (subset_insert a s) theorem finite_upto [instance] (n : ℕ) : finite {i | i < n} := by rewrite [-finset.to_set_upto n]; apply finite_finset theorem to_finset_upto (n : ℕ) : to_finset {i | i < n} = finset.upto n := by apply (to_finset_eq_of_to_set_eq !finset.to_set_upto) theorem finite_of_surj_on {B : Type} {f : A → B} {s : set A} [finite s] {t : set B} (H : surj_on f s t) : finite t := finite_subset H theorem finite_of_inj_on {B : Type} {f : A → B} {s : set A} {t : set B} [finite t] (mapsto : maps_to f s t) (injf : inj_on f s) : finite s := if H : s = ∅ then by rewrite H; apply _ else obtain (dflt : A) (xs : dflt ∈ s), from exists_mem_of_ne_empty H, let finv := inv_fun f s dflt in have surj_on finv t s, from surj_on_inv_fun_of_inj_on dflt mapsto injf, finite_of_surj_on this theorem finite_of_bij_on {B : Type} {f : A → B} {s : set A} {t : set B} [finite s] (bijf : bij_on f s t) : finite t := finite_of_surj_on (surj_on_of_bij_on bijf) theorem finite_of_bij_on' {B : Type} {f : A → B} {s : set A} {t : set B} [finite t] (bijf : bij_on f s t) : finite s := finite_of_inj_on (maps_to_of_bij_on bijf) (inj_on_of_bij_on bijf) theorem finite_iff_finite_of_bij_on {B : Type} {f : A → B} {s : set A} {t : set B} (bijf : bij_on f s t) : finite s ↔ finite t := iff.intro (assume fs, finite_of_bij_on bijf) (assume ft, finite_of_bij_on' bijf) theorem finite_powerset (s : set A) [finite s] : finite 𝒫 s := assert H : 𝒫 s = finset.to_set ' (finset.to_set (#finset 𝒫 (to_finset s))), from ext (take t, iff.intro (suppose t ∈ 𝒫 s, assert t ⊆ s, from this, assert finite t, from finite_subset this, assert (#finset to_finset t ∈ 𝒫 (to_finset s)), by rewrite [finset.mem_powerset_iff_subset, to_finset_subset_to_finset_eq]; apply `t ⊆ s`, assert to_finset t ∈ (finset.to_set (finset.powerset (to_finset s))), from this, mem_image this (by rewrite to_set_to_finset)) (assume H', obtain t' [(tmem : (#finset t' ∈ 𝒫 (to_finset s))) (teq : finset.to_set t' = t)], from H', show t ⊆ s, begin rewrite [-teq, finset.mem_powerset_iff_subset at tmem, -to_set_to_finset s], rewrite -finset.subset_eq_to_set_subset, assumption end)), by rewrite H; apply finite_image /- induction for finite sets -/ theorem induction_finite [recursor 6] {P : set A → Prop} (H1 : P ∅) (H2 : ∀ ⦃a : A⦄, ∀ {s : set A} [finite s], a ∉ s → P s → P (insert a s)) : ∀ (s : set A) [finite s], P s := begin intro s fins, rewrite [-to_set_to_finset s], generalize to_finset s, intro s', induction s' using finset.induction with a s' nains ih, {rewrite finset.to_set_empty, apply H1}, rewrite [finset.to_set_insert], apply H2, {rewrite -finset.mem_eq_mem_to_set, assumption}, exact ih end theorem induction_on_finite {P : set A → Prop} (s : set A) [finite s] (H1 : P ∅) (H2 : ∀ ⦃a : A⦄, ∀ {s : set A} [finite s], a ∉ s → P s → P (insert a s)) : P s := induction_finite H1 H2 s end set
e6b32d1ff0dba60c7d93fd4006ea1770626704eb
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/homotopy/wedge.hlean
103d9596f51871edb524710ff1699d15c2125d57
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
2,737
hlean
/- Copyright (c) 2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Ulrik Buchholtz The Wedge Sum of Two Pointed Types -/ import hit.pointed_pushout .connectedness open eq pushout pointed Pointed unit definition Wedge (A B : Type*) : Type* := Pushout (pconst Unit A) (pconst Unit B) namespace wedge -- TODO maybe find a cleaner proof protected definition unit (A : Type*) : A ≃* Wedge Unit A := begin fconstructor, { fapply pmap.mk, intro a, apply pinr a, apply respect_pt }, { fapply is_equiv.adjointify, intro x, fapply pushout.elim_on x, exact λ x, Point A, exact id, intro u, reflexivity, intro x, fapply pushout.rec_on x, intro u, cases u, esimp, apply (glue unit.star)⁻¹, intro a, reflexivity, intro u, cases u, esimp, apply eq_pathover, refine _ ⬝hp !ap_id⁻¹, fapply eq_hconcat, apply ap_compose inr, krewrite elim_glue, fapply eq_hconcat, apply ap_idp, apply square_of_eq, apply con.left_inv, intro a, reflexivity }, end end wedge open trunc is_trunc function homotopy namespace wedge_extension section -- The wedge connectivity lemma (Lemma 8.6.2) parameters {A B : Type*} (n m : trunc_index) [cA : is_conn n .+2 A] [cB : is_conn m .+2 B] (P : A → B → (m .+1 +2+ n .+1)-Type) (f : Πa : A, P a (Point B)) (g : Πb : B, P (Point A) b) (p : f (Point A) = g (Point B)) include cA cB private definition Q (a : A) : (n .+1)-Type := trunctype.mk (fiber (λs : (Πb : B, P a b), s (Point B)) (f a)) (is_conn.elim_general (P a) (f a)) private definition Q_sec : Πa : A, Q a := is_conn.elim Q (fiber.mk g p⁻¹) protected definition ext : Π(a : A)(b : B), P a b := λa, fiber.point (Q_sec a) protected definition β_left (a : A) : ext a (Point B) = f a := fiber.point_eq (Q_sec a) private definition coh_aux : Σq : ext (Point A) = g, β_left (Point A) = ap (λs : (Πb : B, P (Point A) b), s (Point B)) q ⬝ p⁻¹ := equiv.to_fun (fiber.fiber_eq_equiv (Q_sec (Point A)) (fiber.mk g p⁻¹)) (is_conn.elim_β Q (fiber.mk g p⁻¹)) protected definition β_right (b : B) : ext (Point A) b = g b := apd10 (sigma.pr1 coh_aux) b private definition lem : β_left (Point A) = β_right (Point B) ⬝ p⁻¹ := begin unfold β_right, unfold β_left, krewrite (apd10_eq_ap_eval (sigma.pr1 coh_aux) (Point B)), exact sigma.pr2 coh_aux, end protected definition coh : (β_left (Point A))⁻¹ ⬝ β_right (Point B) = p := by rewrite [lem,con_inv,inv_inv,con.assoc,con.left_inv] end end wedge_extension
ccff7eb61239f13c8a2452af8ed996f75998d99a
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/equiv/list.lean
bfb13a3c15ff8b5bd15280ea55aa473c3207ab13
[ "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
8,940
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Additional equiv and encodable instances for lists and finsets. -/ import data.equiv.denumerable data.nat.pairing order.order_iso data.vector2 data.array.lemmas data.fintype open nat list namespace encodable variables {α : Type*} section list variable [encodable α] def encode_list : list α → ℕ | [] := 0 | (a::l) := succ (mkpair (encode a) (encode_list l)) def decode_list : ℕ → option (list α) | 0 := some [] | (succ v) := match unpair v, unpair_le_right v with | (v₁, v₂), h := have v₂ < succ v, from lt_succ_of_le h, (::) <$> decode α v₁ <*> decode_list v₂ end instance list : encodable (list α) := ⟨encode_list, decode_list, λ l, by induction l with a l IH; simp [encode_list, decode_list, unpair_mkpair, encodek, *]⟩ @[simp] theorem encode_list_nil : encode (@nil α) = 0 := rfl @[simp] theorem encode_list_cons (a : α) (l : list α) : encode (a :: l) = succ (mkpair (encode a) (encode l)) := rfl @[simp] theorem decode_list_zero : decode (list α) 0 = some [] := rfl @[simp] theorem decode_list_succ (v : ℕ) : decode (list α) (succ v) = (::) <$> decode α v.unpair.1 <*> decode (list α) v.unpair.2 := show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], refl end theorem length_le_encode : ∀ (l : list α), length l ≤ encode l | [] := _root_.zero_le _ | (a :: l) := succ_le_succ $ le_trans (length_le_encode l) (le_mkpair_right _ _) end list section finset variables [encodable α] private def enle : α → α → Prop := encode ⁻¹'o (≤) private lemma enle.is_linear_order : is_linear_order α enle := (order_embedding.preimage ⟨encode, encode_injective⟩ (≤)).is_linear_order private def decidable_enle (a b : α) : decidable (enle a b) := by unfold enle order.preimage; apply_instance local attribute [instance] enle.is_linear_order decidable_enle def encode_multiset (s : multiset α) : ℕ := encode (s.sort enle) def decode_multiset (n : ℕ) : option (multiset α) := coe <$> decode (list α) n instance multiset : encodable (multiset α) := ⟨encode_multiset, decode_multiset, λ s, by simp [encode_multiset, decode_multiset, encodek]⟩ end finset def encodable_of_list [decidable_eq α] (l : list α) (H : ∀ x, x ∈ l) : encodable α := ⟨λ a, index_of a l, l.nth, λ a, index_of_nth (H _)⟩ def trunc_encodable_of_fintype (α : Type*) [decidable_eq α] [fintype α] : trunc (encodable α) := @@quot.rec_on_subsingleton _ (λ s : multiset α, (∀ x:α, x ∈ s) → trunc (encodable α)) _ finset.univ.1 (λ l H, trunc.mk $ encodable_of_list l H) finset.mem_univ instance vector [encodable α] {n} : encodable (vector α n) := encodable.subtype instance fin_arrow [encodable α] {n} : encodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance fin_pi (n) (π : fin n → Type*) [∀i, encodable (π i)] : encodable (Πi, π i) := of_equiv _ (equiv.pi_equiv_subtype_sigma (fin n) π) instance array [encodable α] {n} : encodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) instance finset [encodable α] : encodable (finset α) := by haveI := decidable_eq_of_encodable α; exact of_equiv {s : multiset α // s.nodup} ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ def fintype_arrow (α : Type*) (β : Type*) [fintype α] [decidable_eq α] [encodable β] : trunc (encodable (α → β)) := (fintype.equiv_fin α).map $ λf, encodable.of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr f (equiv.refl _) def fintype_pi (α : Type*) (π : α → Type*) [fintype α] [decidable_eq α] [∀a, encodable (π a)] : trunc (encodable (Πa, π a)) := (encodable.trunc_encodable_of_fintype α).bind $ λa, (@fintype_arrow α (Σa, π a) _ _ (@encodable.sigma _ _ a _)).bind $ λf, trunc.mk $ @encodable.of_equiv _ _ (@encodable.subtype _ _ f _) (equiv.pi_equiv_subtype_sigma α π) end encodable namespace denumerable variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable section list theorem denumerable_list_aux : ∀ n : ℕ, ∃ a ∈ @decode_list α _ n, encode_list a = n | 0 := ⟨_, rfl, rfl⟩ | (succ v) := begin cases e : unpair v with v₁ v₂, have h := unpair_le_right v, rw e at h, rcases have v₂ < succ v, from lt_succ_of_le h, denumerable_list_aux v₂ with ⟨a, h₁, h₂⟩, simp at h₁, simp [decode_list, e, h₂, h₁, encode_list, mkpair_unpair' e] end instance denumerable_list : denumerable (list α) := ⟨denumerable_list_aux⟩ @[simp] theorem list_of_nat_zero : of_nat (list α) 0 = [] := rfl @[simp] theorem list_of_nat_succ (v : ℕ) : of_nat (list α) (succ v) = of_nat α v.unpair.1 :: of_nat (list α) v.unpair.2 := of_nat_of_decode $ show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], rw [show decode_list v₂ = decode (list α) v₂, from rfl, decode_eq_of_nat]; refl end end list section multiset def lower : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower l m def raise : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise l (m + n) lemma lower_raise : ∀ l n, lower (raise l n) n = l | [] n := rfl | (m :: l) n := by simp [raise, lower, nat.add_sub_cancel, lower_raise] lemma raise_lower : ∀ {l n}, list.sorted (≤) (n :: l) → raise (lower l n) n = l | [] n h := rfl | (m :: l) n h := have n ≤ m, from list.rel_of_sorted_cons h _ (l.mem_cons_self _), by simp [raise, lower, nat.add_sub_cancel' this, raise_lower (list.sorted_of_sorted_cons h)] lemma raise_chain : ∀ l n, list.chain (≤) n (raise l n) | [] n := list.chain.nil _ _ | (m :: l) n := list.chain.cons (nat.le_add_left _ _) (raise_chain _ _) lemma raise_sorted : ∀ l n, list.sorted (≤) (raise l n) | [] n := list.sorted_nil | (m :: l) n := (list.chain_iff_pairwise (@le_trans _ _)).1 (raise_chain _ _) /- Warning: this is not the same encoding as used in `encodable` -/ instance multiset : denumerable (multiset α) := mk' ⟨ λ s : multiset α, encode $ lower ((s.map encode).sort (≤)) 0, λ n, multiset.map (of_nat α) (raise (of_nat (list ℕ) n) 0), λ s, by have := raise_lower (list.sorted_cons.2 ⟨λ n _, zero_le n, (s.map encode).sort_sorted _⟩); simp [-multiset.coe_map, this], λ n, by simp [-multiset.coe_map, list.merge_sort_eq_self _ (raise_sorted _ _), lower_raise]⟩ end multiset section finset def lower' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower' l (m + 1) def raise' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise' l (m + n + 1) lemma lower_raise' : ∀ l n, lower' (raise' l n) n = l | [] n := rfl | (m :: l) n := by simp [raise', lower', nat.add_sub_cancel, lower_raise'] lemma raise_lower' : ∀ {l n}, (∀ m ∈ l, n ≤ m) → list.sorted (<) l → raise' (lower' l n) n = l | [] n h₁ h₂ := rfl | (m :: l) n h₁ h₂ := have n ≤ m, from h₁ _ (l.mem_cons_self _), by simp [raise', lower', nat.add_sub_cancel' this, raise_lower' (list.rel_of_sorted_cons h₂ : ∀ a ∈ l, m < a) (list.sorted_of_sorted_cons h₂)] lemma raise'_chain : ∀ l {m n}, m < n → list.chain (<) m (raise' l n) | [] m n h := list.chain.nil _ _ | (a :: l) m n h := list.chain.cons (lt_of_lt_of_le h (nat.le_add_left _ _)) (raise'_chain _ (lt_succ_self _)) lemma raise'_sorted : ∀ l n, list.sorted (<) (raise' l n) | [] n := list.sorted_nil | (m :: l) n := (list.chain_iff_pairwise (@lt_trans _ _)).1 (raise'_chain _ (lt_succ_self _)) def raise'_finset (l : list ℕ) (n : ℕ) : finset ℕ := ⟨raise' l n, (raise'_sorted _ _).imp (@ne_of_lt _ _)⟩ /- Warning: this is not the same encoding as used in `encodable` -/ instance finset : denumerable (finset α) := mk' ⟨ λ s : finset α, encode $ lower' ((s.map (eqv α).to_embedding).sort (≤)) 0, λ n, finset.map (eqv α).symm.to_embedding (raise'_finset (of_nat (list ℕ) n) 0), λ s, finset.eq_of_veq $ by simp [-multiset.coe_map, raise'_finset, raise_lower' (λ n _, zero_le n) (finset.sort_sorted_lt _)], λ n, by simp [-multiset.coe_map, finset.map, raise'_finset, finset.sort, list.merge_sort_eq_self (≤) ((raise'_sorted _ _).imp (@le_of_lt _ _)), lower_raise']⟩ end finset end denumerable namespace equiv def list_nat_equiv_nat : list ℕ ≃ ℕ := denumerable.eqv _ def list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : list α ≃ α := calc list α ≃ list ℕ : list_equiv_of_equiv e ... ≃ ℕ : list_nat_equiv_nat ... ≃ α : e.symm end equiv
a65cae65b2579134b12f9d579ddf5f3309210a94
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/sommation.lean
51812dd7b9cf98cc119323cc1f3b03fe0d13acf8
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
2,021
lean
import linear_algebra.basic import data.fintype.basic import algebra.big_operators import data.finset algebra.big_operators import data.set.function import data.equiv.basic open finset open equiv function fintype finset universes u v w namespace technical notation `Σ` := finset.sum finset.univ variables {α : Type u} {β : Type v} lemma finset.prod_univ_perm [fintype α] [comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).prod f = univ.prod (λ z, f (σ z)) := eq.symm $ prod_bij (λ z _, σ z) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ H, σ.injective H) (λ b _, ⟨σ⁻¹ b, mem_univ _, by simp⟩) end technical def Sum {R : Type u}[add_comm_monoid R]{X : Type v}[fintype X](g : X → R) : R := finset.sum (finset.univ) g lemma Sum_permutation {R :Type u}[add_comm_monoid R]{X : Type v}[fintype X](g : X → R)(σ : equiv.perm X ) : finset.sum (finset.univ) g = finset.sum (finset.univ) (λ z, g (σ z)) := @technical.finset.prod_univ_perm _ (multiplicative R) _ _ g σ lemma Sum_add {R : Type} [ring R]{X : Type}[fintype X] (g : X → R)(h : X → R) : Σ (h+g) = Σ h + Σ g := begin exact multiset.sum_map_add, --- end #check multiset.sum_map_sum_map lemma Sum.left_mul {R : Type} [ring R]{X : Type}[fintype X] (g : X → R) (r : R): Σ (r • g) = r • Σ g := begin exact multiset.sum_map_mul_left, end lemma Sum.left_right {R : Type} [add_comm_monoid R]{X : Type}[fintype X] (g : X → R)(r : R) : Σ (r • g ) = (Σ g) := begin rw mul_comm, exact Sum.left_mul g r, end lemma Sum.morp {R : Type} [add_comm_monoid R] (R' : Type) [add_comm_monoid R'] {X : Type}[fintype X] (g : X → R) (φ : R →+ R') : φ ( Σ g ) = Σ (λ t, φ ( g t) ) := begin exact add_monoid_hom.map_sum φ g univ, end def Sum' (R : Type)[hyp1 : comm_ring R](X :Type)[hyp2 : fintype X] : (X → R) →ₗ[R] R := { to_fun := λ g, Σ g, add := begin intros, rw Sum_add,end, smul := begin intros, rw Sum.left_mul, exact rfl, end }
7200f52e315ba5a6fe90d2d4471547d5ff9f7f9d
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/category/category.hlean
e07f82ab02c533c27586f665e0beb428f11d391f
[ "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
4,797
hlean
/- 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 -/ import .iso open iso is_equiv equiv eq is_trunc sigma equiv.ops /- A category is a precategory extended by a witness that the function from paths to isomorphisms is an equivalence. -/ namespace category /- TODO: restructure this. Should is_univalent be a class with as argument (C : Precategory). Or is that problematic if we want to apply this to cases where e.g. a b are functors, and we need to synthesize ? : precategory (functor C D). -/ definition is_univalent [class] {ob : Type} (C : precategory ob) := Π(a b : ob), is_equiv (iso_of_eq : a = b → a ≅ b) definition is_equiv_of_is_univalent [instance] {ob : Type} [C : precategory ob] [H : is_univalent C] (a b : ob) : is_equiv (iso_of_eq : a = b → a ≅ b) := H a b structure category [class] (ob : Type) extends parent : precategory ob := mk' :: (iso_of_path_equiv : is_univalent parent) -- Remark: category and precategory are classes. So, the structure command -- does not create a coercion between them automatically. -- This coercion is needed for definitions such as category_eq_of_equiv -- without it, we would have to explicitly use category.to_precategory attribute category.to_precategory [coercion] attribute category [multiple_instances] abbreviation iso_of_path_equiv := @category.iso_of_path_equiv attribute category.iso_of_path_equiv [instance] definition category.mk [reducible] [unfold 2] {ob : Type} (C : precategory ob) (H : is_univalent C) : category ob := precategory.rec_on C category.mk' H section basic variables {ob : Type} [C : category ob] include C -- Make iso_of_path_equiv a class instance attribute iso_of_path_equiv [instance] definition eq_equiv_iso [constructor] (a b : ob) : (a = b) ≃ (a ≅ b) := equiv.mk iso_of_eq _ definition eq_of_iso [reducible] {a b : ob} : a ≅ b → a = b := iso_of_eq⁻¹ᶠ definition iso_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : iso_of_eq (eq_of_iso p) = p := right_inv iso_of_eq p definition hom_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : hom_of_eq (eq_of_iso p) = to_hom p := ap to_hom !iso_of_eq_eq_of_iso definition inv_of_eq_eq_of_iso {a b : ob} (p : a ≅ b) : inv_of_eq (eq_of_iso p) = to_inv p := ap to_inv !iso_of_eq_eq_of_iso theorem eq_of_iso_refl {a : ob} : eq_of_iso (iso.refl a) = idp := inv_eq_of_eq idp definition is_trunc_1_ob : is_trunc 1 ob := begin apply is_trunc_succ_intro, intro a b, fapply is_trunc_is_equiv_closed, exact (@eq_of_iso _ _ a b), apply is_equiv_inv, end end basic -- Bundled version of categories -- we don't use Category.carrier explicitly, but rather use Precategory.carrier (to_Precategory C) structure Category : Type := (carrier : Type) (struct : category carrier) attribute Category.struct [instance] [coercion] definition Category.to_Precategory [constructor] [coercion] [reducible] (C : Category) : Precategory := Precategory.mk (Category.carrier C) _ definition category.Mk [constructor] [reducible] := Category.mk definition category.MK [constructor] [reducible] (C : Precategory) (H : is_univalent C) : Category := Category.mk C (category.mk C H) definition Category.eta (C : Category) : Category.mk C C = C := Category.rec (λob c, idp) C protected definition category.sigma_char.{u v} [constructor] (ob : Type) : category.{u v} ob ≃ Σ(C : precategory.{u v} ob), is_univalent C := begin fapply equiv.MK, { intro x, induction x, constructor, assumption}, { intro y, induction y with y1 y2, induction y1, constructor, assumption}, { intro y, induction y with y1 y2, induction y1, reflexivity}, { intro x, induction x, reflexivity} end definition category_eq {ob : Type} {C D : category ob} (p : Π{a b}, @hom ob C a b = @hom ob D a b) (q : Πa b c g f, cast p (@comp ob C a b c g f) = @comp ob D a b c (cast p g) (cast p f)) : C = D := begin apply eq_of_fn_eq_fn !category.sigma_char, fapply sigma_eq, { induction C, induction D, esimp, exact precategory_eq @p q}, { unfold is_univalent, apply is_hprop.elimo}, end definition category_eq_of_equiv {ob : Type} {C D : category ob} (p : Π⦃a b⦄, @hom ob C a b ≃ @hom ob D a b) (q : Π{a b c} g f, p (@comp ob C a b c g f) = @comp ob D a b c (p g) (p f)) : C = D := begin fapply category_eq, { intro a b, exact ua !@p}, { intros, refine !cast_ua ⬝ !q ⬝ _, unfold [category.to_precategory], apply ap011 !@category.comp !cast_ua⁻¹ᵖ !cast_ua⁻¹ᵖ}, end -- TODO: Category_eq['] end category
7e6c81e6a60dc2e0855a4ca50d0a925afdd41535
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/algebra/continued_fractions/terminated_stable.lean
25def8a55ea4ca982142b8fbff09970cf9b18cf2
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
4,650
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.translations /-! # Stabilisation of gcf Computations Under Termination ## Summary We show that the continuants and convergents of a gcf stabilise once the gcf terminates. -/ namespace generalized_continued_fraction open generalized_continued_fraction as gcf variables {α : Type*} {g : gcf α} {n m : ℕ} /-- If a gcf terminated at position `n`, it also terminated at `m ≥ n`.-/ lemma terminated_stable (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.terminated_at m := g.s.terminated_stable n_le_m terminated_at_n variable [division_ring α] lemma continuants_aux_stable_step_of_terminated (terminated_at_n : g.terminated_at n) : g.continuants_aux (n + 2) = g.continuants_aux (n + 1) := by { rw [terminated_at_iff_s_none] at terminated_at_n, simp only [terminated_at_n, continuants_aux] } lemma continuants_aux_stable_of_terminated (succ_n_le_m : (n + 1) ≤ m) (terminated_at_n : g.terminated_at n) : g.continuants_aux m = g.continuants_aux (n + 1) := begin induction succ_n_le_m with m succ_n_le_m IH, { refl }, { have : g.continuants_aux (m + 1) = g.continuants_aux m, by { have : n ≤ m - 1, from nat.le_pred_of_lt succ_n_le_m, have : g.terminated_at (m - 1), from terminated_stable this terminated_at_n, have stable_step : g.continuants_aux (m - 1 + 2) = g.continuants_aux (m - 1 + 1), from continuants_aux_stable_step_of_terminated this, have one_le_m : 1 ≤ m, from nat.one_le_of_lt succ_n_le_m, have : m - 1 + 2 = m + 2 - 1, from (nat.sub_add_comm one_le_m).symm, have : m - 1 + 1 = m + 1 - 1, from (nat.sub_add_comm one_le_m).symm, simpa [*] using stable_step }, exact (eq.trans this IH) } end lemma convergents'_aux_stable_step_of_terminated {s : seq $ gcf.pair α} (terminated_at_n : s.terminated_at n) : convergents'_aux s (n + 1) = convergents'_aux s n := begin change s.nth n = none at terminated_at_n, induction n with n IH generalizing s, case nat.zero { simp only [convergents'_aux, terminated_at_n, seq.head] }, case nat.succ { cases s_head_eq : s.head with gp_head, case option.none { simp only [convergents'_aux, s_head_eq] }, case option.some { have : s.tail.terminated_at n, by simp only [seq.terminated_at, s.nth_tail, terminated_at_n], simp only [convergents'_aux, s_head_eq, (IH this)] }} end lemma convergents'_aux_stable_of_terminated {s : seq $ gcf.pair α} (n_le_m : n ≤ m) (terminated_at_n : s.terminated_at n) : convergents'_aux s m = convergents'_aux s n := begin induction n_le_m with m n_le_m IH generalizing s, { refl }, { cases s_head_eq : s.head with gp_head, case option.none { cases n; simp only [convergents'_aux, s_head_eq] }, case option.some { have : convergents'_aux s (n + 1) = convergents'_aux s n, from convergents'_aux_stable_step_of_terminated terminated_at_n, rw [←this], have : s.tail.terminated_at n, by simpa only [seq.terminated_at, seq.nth_tail] using (s.le_stable n.le_succ terminated_at_n), have : convergents'_aux s.tail m = convergents'_aux s.tail n, from IH this, simp only [convergents'_aux, s_head_eq, this] }} end lemma continuants_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.continuants m = g.continuants n := by simp only [nth_cont_eq_succ_nth_cont_aux, (continuants_aux_stable_of_terminated (nat.pred_le_iff.elim_left n_le_m) terminated_at_n)] lemma numerators_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.numerators m = g.numerators n := by simp only [num_eq_conts_a, (continuants_stable_of_terminated n_le_m terminated_at_n)] lemma denominators_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.denominators m = g.denominators n := by simp only [denom_eq_conts_b, (continuants_stable_of_terminated n_le_m terminated_at_n)] lemma convergents_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.convergents m = g.convergents n := by simp only [convergents, (denominators_stable_of_terminated n_le_m terminated_at_n), (numerators_stable_of_terminated n_le_m terminated_at_n)] lemma convergents'_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.convergents' m = g.convergents' n := by simp only [convergents', (convergents'_aux_stable_of_terminated n_le_m terminated_at_n)] end generalized_continued_fraction
62792f50a2d11007f06545ae7959a527abe7fa5d
2896b9fe3a438a5619c7c90fc035be5592aa6c95
/src/zero_divisors_and_nilpotents.lean
3864d7cfd09d93d6fbd4f7c9c04f9867fe7489ac
[]
no_license
anrddh/commutative-algebra-playground
29f29210083ada4ea2e04e1dc2016e8a2a028782
4f4d1701e2c21f13bba50cf1bda44ec7a125a91e
refs/heads/master
1,656,887,159,041
1,589,827,091,000
1,589,827,091,000
265,029,257
0
0
null
null
null
null
UTF-8
Lean
false
false
3,470
lean
import algebra.associated import algebra.group_power import ring_theory.ideal_operations import ring_theory.ideals universe u variables {α : Type*} open_locale classical /- An element a of a ring α is a zero divisor if there exists a b ∈ α such that b ≠ 0 and ab = 0. -/ def is_zero_divisor [comm_ring α] (a : α) := ∃ b : α, b ≠ 0 ∧ a * b = 0 /- An element a of a ring α is nilpotent if there exists a n ∈ ℕ such that a^n = 0. -/ def is_nilpotent [comm_ring α] (a : α) := ∃ n : ℕ, a ^ n = 0 /- 0 is nilpotent. -/ theorem zero_is_nilpotent [comm_ring α] : is_nilpotent (0 : α) := exists.intro 1 (by simp) theorem exists_min_pow_zero_of_nilpotent [comm_ring α] : ∀ a : α, is_nilpotent a → ∃ m : ℕ, a^m = 0 ∧ ∀ n : ℕ, n < m → a^n ≠ 0 := begin rintros a hna, use nat.find hna, split, { exact nat.find_spec hna}, { intro n, exact nat.find_min hna} end theorem eq_mul [comm_ring α] (a : α) (ha : (1 : α) = 0) : a = 0 := begin have h : (a * 1 = a * 0) := eq.subst ha rfl, simp at h, exact h end /- All nonzero nilpotents are zerodivisors. -/ theorem nz_nilpotent_is_zerodivisor [comm_ring α] : ∀ a : α, is_nilpotent a → a ≠ 0 → is_zero_divisor a := begin intros a ha ha', unfold is_zero_divisor, unfold is_nilpotent at ha, have h := exists_min_pow_zero_of_nilpotent a ha, cases h with m hm, cases m with, { rw pow_zero at hm, have haz := eq_mul a hm.left, contradiction }, { cases m with, { simp at hm, have haz := hm.left, contradiction }, { let n := m + 1, use a ^ n, rw nat.succ_eq_add_one at hm, rw nat.succ_eq_add_one at hm, simp at hm, split, { have hn : n < m + 2, simp, exact hm.right n hn }, { rw <- pow_succ, exact hm.left, }, } } end /- Zero is a zero divisor in a nonzero ring. -/ theorem zero_zero_divisor_in_nz_ring [nonzero_comm_ring α] : is_zero_divisor (0 : α) := exists.intro 1 ⟨one_ne_zero, by simp⟩ /- All nilpotents are zero divisors in a nonzero ring. -/ theorem nonzero_ring_nilpotent_is_zerodivisor [nonzero_comm_ring α] : ∀ a : α, is_nilpotent a → is_zero_divisor a := assume a : α, assume ha : is_nilpotent a, classical.by_cases (assume hz : a = 0, by simp[hz, zero_zero_divisor_in_nz_ring]) (assume hnz : a ≠ 0, nz_nilpotent_is_zerodivisor a ha hnz) open ideal /- The nilradical of a ring α is the radical of (0). -/ def nilradical [comm_ring α] := radical (span ({ 0 } : set α)) /- The elements of the nilradical are precisely the nilpotents of α -/ theorem elem_nilradical_nilpotent [comm_ring α] : ∀ a : α, a ∈ (@nilradical α).carrier ↔ is_nilpotent a := sorry /- A ring is reduced if its nilradical is the trivial ideal (0) -/ class reduced_ring (α : Type u) extends comm_ring α := (is_reduced : nilradical = span ({ 0 } : set α)) /- The zero ideal is prime in an integral domain. -/ theorem zero_is_prime_in_id [integral_domain α] : (span ({0} : set α)).is_prime := begin -- Our strategy is to show that the kernel of the identity α → α is -- (0) and then apply the ker_is_prime theorem. let id_hom := @id α, have ker_of_id_is_prime := ring_hom.ker_is_prime id_hom, end /- All integral domains are reduced. -/ theorem integral_domains_are_reduced [integral_domain α] : reduced_ring α := is_reduced = is_prime.radical zero_is_prime_in_id
e6de54bbb1159070d03930042ae7e3924f1a718c
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/computability/partrec.lean
4ce2cf46d92153df0932f35c63c2e2a7d6712716
[ "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
29,010
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import computability.primrec import data.nat.psub import data.pfun /-! # The partial recursive functions The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `part` monad, and there is an additional operation, called μ-recursion, which performs unbounded minimization. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable part local attribute [-simp] not_forall namespace nat section rfind parameter (p : ℕ →. bool) private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ff ∈ p k parameter (H : ∃ n, tt ∈ p n ∧ ∀ k < n, (p k).dom) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in begin suffices : ∀m k, n ≤ k + m → acc (lbp p) k, { from λ a, this _ _ (nat.le_add_left _ _) }, intros m k kn, induction m with m IH generalizing k; refine ⟨_, λ y r, _⟩; rcases r with ⟨rfl, a⟩, { injection mem_unique pn.1 (a _ kn) }, { exact IH _ (by rw nat.add_right_comm; exact kn) } end⟩ def rfind_x : {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m} := suffices ∀ k, (∀n < k, ff ∈ p n) → {n // tt ∈ p n ∧ ∀m < n, ff ∈ p m}, from this 0 (λ n, (nat.not_lt_zero _).elim), @well_founded.fix _ _ lbp wf_lbp begin intros m IH al, have pm : (p m).dom, { rcases H with ⟨n, h₁, h₂⟩, rcases lt_trichotomy m n with h₃|h₃|h₃, { exact h₂ _ h₃ }, { rw h₃, exact h₁.fst }, { injection mem_unique h₁ (al _ h₃) } }, cases e : (p m).get pm, { suffices, exact IH _ ⟨rfl, this⟩ (λ n h, this _ (le_of_lt_succ h)), intros n h, cases h.lt_or_eq_dec with h h, { exact al _ h }, { rw h, exact ⟨_, e⟩ } }, { exact ⟨m, ⟨_, e⟩, al⟩ } end end rfind def rfind (p : ℕ →. bool) : part ℕ := ⟨_, λ h, (rfind_x p h).1⟩ theorem rfind_spec {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : tt ∈ p n := h.snd ▸ (rfind_x p h.fst).2.1 theorem rfind_min {p : ℕ →. bool} {n : ℕ} (h : n ∈ rfind p) : ∀ {m : ℕ}, m < n → ff ∈ p m := h.snd ▸ (rfind_x p h.fst).2.2 @[simp] theorem rfind_dom {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m < n → (p m).dom := iff.rfl theorem rfind_dom' {p : ℕ →. bool} : (rfind p).dom ↔ ∃ n, tt ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → (p m).dom := exists_congr $ λ n, and_congr_right $ λ pn, ⟨λ H m h, (decidable.eq_or_lt_of_le h).elim (λ e, e.symm ▸ pn.fst) (H _), λ H m h, H (le_of_lt h)⟩ @[simp] theorem mem_rfind {p : ℕ →. bool} {n : ℕ} : n ∈ rfind p ↔ tt ∈ p n ∧ ∀ {m : ℕ}, m < n → ff ∈ p m := ⟨λ h, ⟨rfind_spec h, @rfind_min _ _ h⟩, λ ⟨h₁, h₂⟩, let ⟨m, hm⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨_, h₁, λ m mn, (h₂ mn).fst⟩ in begin rcases lt_trichotomy m n with h|h|h, { injection mem_unique (h₂ h) (rfind_spec hm) }, { rwa ← h }, { injection mem_unique h₁ (rfind_min hm h) }, end⟩ theorem rfind_min' {p : ℕ → bool} {m : ℕ} (pm : p m) : ∃ n ∈ rfind p, n ≤ m := have tt ∈ (p : ℕ →. bool) m, from ⟨trivial, pm⟩, let ⟨n, hn⟩ := dom_iff_mem.1 $ (@rfind_dom p).2 ⟨m, this, λ k h, ⟨⟩⟩ in ⟨n, hn, not_lt.1 $ λ h, by injection mem_unique this (rfind_min hn h)⟩ theorem rfind_zero_none (p : ℕ →. bool) (p0 : p 0 = none) : rfind p = none := eq_none_iff.2 $ λ a h, let ⟨n, h₁, h₂⟩ := rfind_dom'.1 h.fst in (p0 ▸ h₂ (zero_le _) : (@part.none bool).dom) def rfind_opt {α} (f : ℕ → option α) : part α := (rfind (λ n, (f n).is_some)).bind (λ n, f n) theorem rfind_opt_spec {α} {f : ℕ → option α} {a} (h : a ∈ rfind_opt f) : ∃ n, a ∈ f n := let ⟨n, h₁, h₂⟩ := mem_bind_iff.1 h in ⟨n, mem_coe.1 h₂⟩ theorem rfind_opt_dom {α} {f : ℕ → option α} : (rfind_opt f).dom ↔ ∃ n a, a ∈ f n := ⟨λ h, (rfind_opt_spec ⟨h, rfl⟩).imp (λ n h, ⟨_, h⟩), λ h, begin have h' : ∃ n, (f n).is_some := h.imp (λ n, option.is_some_iff_exists.2), have s := nat.find_spec h', have fd : (rfind (λ n, (f n).is_some)).dom := ⟨nat.find h', by simpa using s.symm, λ _ _, trivial⟩, refine ⟨fd, _⟩, have := rfind_spec (get_mem fd), simp at this ⊢, cases option.is_some_iff_exists.1 this.symm with a e, rw e, trivial end⟩ theorem rfind_opt_mono {α} {f : ℕ → option α} (H : ∀ {a m n}, m ≤ n → a ∈ f m → a ∈ f n) {a} : a ∈ rfind_opt f ↔ ∃ n, a ∈ f n := ⟨rfind_opt_spec, λ ⟨n, h⟩, begin have h' := rfind_opt_dom.2 ⟨_, _, h⟩, cases rfind_opt_spec ⟨h', rfl⟩ with k hk, have := (H (le_max_left _ _) h).symm.trans (H (le_max_right _ _) hk), simp at this, simp [this, get_mem] end⟩ inductive partrec : (ℕ →. ℕ) → Prop | zero : partrec (pure 0) | succ : partrec succ | left : partrec ↑(λ n : ℕ, n.unpair.1) | right : partrec ↑(λ n : ℕ, n.unpair.2) | pair {f g} : partrec f → partrec g → partrec (λ n, mkpair <$> f n <*> g n) | comp {f g} : partrec f → partrec g → partrec (λ n, g n >>= f) | prec {f g} : partrec f → partrec g → partrec (unpaired (λ a n, n.elim (f a) (λ y IH, do i ← IH, g (mkpair a (mkpair y i))))) | rfind {f} : partrec f → partrec (λ a, rfind (λ n, (λ m, m = 0) <$> f (mkpair a n))) namespace partrec theorem of_eq {f g : ℕ →. ℕ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : partrec g := hf.of_eq (λ n, eq_some_iff.2 (H n)) theorem of_primrec {f : ℕ → ℕ} (hf : primrec f) : partrec f := begin induction hf, case nat.primrec.zero { exact zero }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact left }, case nat.primrec.right { exact right }, case nat.primrec.pair : f g hf hg pf pg { refine (pf.pair pg).of_eq_tot (λ n, _), simp [has_seq.seq] }, case nat.primrec.comp : f g hf hg pf pg { refine (pf.comp pg).of_eq_tot (λ n, _), simp }, case nat.primrec.prec : f g hf hg pf pg { refine (pf.prec pg).of_eq_tot (λ n, _), simp, induction n.unpair.2 with m IH, {simp}, simp, exact ⟨_, IH, rfl⟩ }, end protected theorem some : partrec some := of_primrec primrec.id theorem none : partrec (λ n, none) := (of_primrec (nat.primrec.const 1)).rfind.of_eq $ λ n, eq_none_iff.2 $ λ a ⟨h, e⟩, by simpa using h theorem prec' {f g h} (hf : partrec f) (hg : partrec g) (hh : partrec h) : partrec (λ a, (f a).bind (λ n, n.elim (g a) (λ y IH, do i ← IH, h (mkpair a (mkpair y i))))) := ((prec hg hh).comp (pair partrec.some hf)).of_eq $ λ a, ext $ λ s, by simp [(<*>)]; exact ⟨λ ⟨n, h₁, h₂⟩, ⟨_, ⟨_, h₁, rfl⟩, by simpa using h₂⟩, λ ⟨_, ⟨n, h₁, rfl⟩, h₂⟩, ⟨_, h₁, by simpa using h₂⟩⟩ theorem ppred : partrec (λ n, ppred n) := have primrec₂ (λ n m, if n = nat.succ m then 0 else 1), from (primrec.ite (@@primrec_rel.comp _ _ _ _ _ _ _ primrec.eq primrec.fst (_root_.primrec.succ.comp primrec.snd)) (_root_.primrec.const 0) (_root_.primrec.const 1)).to₂, (of_primrec (primrec₂.unpaired'.2 this)).rfind.of_eq $ λ n, begin cases n; simp, { exact eq_none_iff.2 (λ a ⟨⟨m, h, _⟩, _⟩, by simpa [show 0 ≠ m.succ, by intro h; injection h] using h) }, { refine eq_some_iff.2 _, simp, intros m h, simp [ne_of_gt h] } end end partrec end nat def partrec {α σ} [primcodable α] [primcodable σ] (f : α →. σ) := nat.partrec (λ n, part.bind (decode α n) (λ a, (f a).map encode)) def partrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β →. σ) := partrec (λ p : α × β, f p.1 p.2) def computable {α σ} [primcodable α] [primcodable σ] (f : α → σ) := partrec (f : α →. σ) def computable₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := computable (λ p : α × β, f p.1 p.2) theorem primrec.to_comp {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : primrec f) : computable f := (nat.partrec.ppred.comp (nat.partrec.of_primrec hf)).of_eq $ λ n, by simp; cases decode α n; simp theorem primrec₂.to_comp {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : primrec₂ f) : computable₂ f := hf.to_comp protected theorem computable.partrec {α σ} [primcodable α] [primcodable σ] {f : α → σ} (hf : computable f) : partrec (f : α →. σ) := hf protected theorem computable₂.partrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : computable₂ f) : partrec₂ (λ a, (f a : β →. σ)) := hf namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem of_eq {f g : α → σ} (hf : computable f) (H : ∀ n, f n = g n) : computable g := (funext H : f = g) ▸ hf theorem const (s : σ) : computable (λ a : α, s) := (primrec.const _).to_comp theorem of_option {f : α → option β} (hf : computable f) : partrec (λ a, (f a : part β)) := (nat.partrec.ppred.comp hf).of_eq $ λ n, begin cases decode α n with a; simp, cases f a with b; simp end theorem to₂ {f : α × β → σ} (hf : computable f) : computable₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl protected theorem id : computable (@id α) := primrec.id.to_comp theorem fst : computable (@prod.fst α β) := primrec.fst.to_comp theorem snd : computable (@prod.snd α β) := primrec.snd.to_comp theorem pair {f : α → β} {g : α → γ} (hf : computable f) (hg : computable g) : computable (λ a, (f a, g a)) := (hf.pair hg).of_eq $ λ n, by cases decode α n; simp [(<*>)] theorem unpair : computable nat.unpair := primrec.unpair.to_comp theorem succ : computable nat.succ := primrec.succ.to_comp theorem pred : computable nat.pred := primrec.pred.to_comp theorem nat_bodd : computable nat.bodd := primrec.nat_bodd.to_comp theorem nat_div2 : computable nat.div2 := primrec.nat_div2.to_comp theorem sum_inl : computable (@sum.inl α β) := primrec.sum_inl.to_comp theorem sum_inr : computable (@sum.inr α β) := primrec.sum_inr.to_comp theorem list_cons : computable₂ (@list.cons α) := primrec.list_cons.to_comp theorem list_reverse : computable (@list.reverse α) := primrec.list_reverse.to_comp theorem list_nth : computable₂ (@list.nth α) := primrec.list_nth.to_comp theorem list_append : computable₂ ((++) : list α → list α → list α) := primrec.list_append.to_comp theorem list_concat : computable₂ (λ l (a:α), l ++ [a]) := primrec.list_concat.to_comp theorem list_length : computable (@list.length α) := primrec.list_length.to_comp theorem vector_cons {n} : computable₂ (@vector.cons α n) := primrec.vector_cons.to_comp theorem vector_to_list {n} : computable (@vector.to_list α n) := primrec.vector_to_list.to_comp theorem vector_length {n} : computable (@vector.length α n) := primrec.vector_length.to_comp theorem vector_head {n} : computable (@vector.head α n) := primrec.vector_head.to_comp theorem vector_tail {n} : computable (@vector.tail α n) := primrec.vector_tail.to_comp theorem vector_nth {n} : computable₂ (@vector.nth α n) := primrec.vector_nth.to_comp theorem vector_nth' {n} : computable (@vector.nth α n) := primrec.vector_nth'.to_comp theorem vector_of_fn' {n} : computable (@vector.of_fn α n) := primrec.vector_of_fn'.to_comp theorem fin_app {n} : computable₂ (@id (fin n → σ)) := primrec.fin_app.to_comp protected theorem encode : computable (@encode α _) := primrec.encode.to_comp protected theorem decode : computable (decode α) := primrec.decode.to_comp protected theorem of_nat (α) [denumerable α] : computable (of_nat α) := (primrec.of_nat _).to_comp theorem encode_iff {f : α → σ} : computable (λ a, encode (f a)) ↔ computable f := iff.rfl theorem option_some : computable (@option.some α) := primrec.option_some.to_comp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem of_eq {f g : α →. σ} (hf : partrec f) (H : ∀ n, f n = g n) : partrec g := (funext H : f = g) ▸ hf theorem of_eq_tot {f : α →. σ} {g : α → σ} (hf : partrec f) (H : ∀ n, g n ∈ f n) : computable g := hf.of_eq (λ a, eq_some_iff.2 (H a)) theorem none : partrec (λ a : α, @part.none σ) := nat.partrec.none.of_eq $ λ n, by cases decode α n; simp protected theorem some : partrec (@part.some α) := computable.id theorem _root_.decidable.partrec.const' (s : part σ) [decidable s.dom] : partrec (λ a : α, s) := (of_option (const (to_option s))).of_eq (λ a, of_to_option s) theorem const' (s : part σ) : partrec (λ a : α, s) := by haveI := classical.dec s.dom; exact decidable.partrec.const' s protected theorem bind {f : α →. β} {g : α → β →. σ} (hf : partrec f) (hg : partrec₂ g) : partrec (λ a, (f a).bind (g a)) := (hg.comp (nat.partrec.some.pair hf)).of_eq $ λ n, by simp [(<*>)]; cases e : decode α n with a; simp [e, encodek] theorem map {f : α →. β} {g : α → β → σ} (hf : partrec f) (hg : computable₂ g) : partrec (λ a, (f a).map (g a)) := by simpa [bind_some_eq_map] using @@partrec.bind _ _ _ (λ a b, part.some (g a b)) hf hg theorem to₂ {f : α × β →. σ} (hf : partrec f) : partrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : computable f) (hg : partrec g) (hh : partrec₂ h) : partrec (λ a, (f a).elim (g a) (λ y IH, IH.bind (λ i, h a (y, i)))) := (nat.partrec.prec' hf hg hh).of_eq $ λ n, begin cases e : decode α n with a; simp [e], induction f a with m IH; simp, rw [IH, bind_map], congr, funext s, simp [encodek] end theorem comp {f : β →. σ} {g : α → β} (hf : partrec f) (hg : computable g) : partrec (λ a, f (g a)) := (hf.comp hg).of_eq $ λ n, by simp; cases e : decode α n with a; simp [e, encodek] theorem nat_iff {f : ℕ →. ℕ} : partrec f ↔ nat.partrec f := by simp [partrec, map_id'] theorem map_encode_iff {f : α →. σ} : partrec (λ a, (f a).map encode) ↔ partrec f := iff.rfl end partrec namespace partrec₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem unpaired {f : ℕ → ℕ →. α} : partrec (nat.unpaired f) ↔ partrec₂ f := ⟨λ h, by simpa using h.comp primrec₂.mkpair.to_comp, λ h, h.comp primrec.unpair.to_comp⟩ theorem unpaired' {f : ℕ → ℕ →. ℕ} : nat.partrec (nat.unpaired f) ↔ partrec₂ f := partrec.nat_iff.symm.trans unpaired theorem comp {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : partrec₂ f) (hg : computable g) (hh : computable h) : partrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : partrec₂ f) (hg : computable₂ g) (hh : computable₂ h) : partrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end partrec₂ namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem comp {f : β → σ} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, f (g a)) := hf.comp hg theorem comp₂ {f : γ → σ} {g : α → β → γ} (hf : computable f) (hg : computable₂ g) : computable₂ (λ a b, f (g a b)) := hf.comp hg end computable namespace computable₂ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : computable₂ f) (hg : computable g) (hh : computable h) : computable (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : computable₂ f) (hg : computable₂ g) (hh : computable₂ h) : computable₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh end computable₂ namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem rfind {p : α → ℕ →. bool} (hp : partrec₂ p) : partrec (λ a, nat.rfind (p a)) := (nat.partrec.rfind $ hp.map ((primrec.dom_bool (λ b, cond b 0 1)) .comp primrec.snd).to₂.to_comp).of_eq $ λ n, begin cases e : decode α n with a; simp [e, nat.rfind_zero_none, map_id'], congr, funext n, simp [part.map_map, (∘)], apply map_id' (λ b, _), cases b; refl end theorem rfind_opt {f : α → ℕ → option σ} (hf : computable₂ f) : partrec (λ a, nat.rfind_opt (f a)) := (rfind (primrec.option_is_some.to_comp.comp hf).partrec.to₂).bind (of_option hf) theorem nat_cases_right {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : computable f) (hg : computable g) (hh : partrec₂ h) : partrec (λ a, (f a).cases (some (g a)) (h a)) := (nat_elim hf hg (hh.comp fst (pred.comp $ hf.comp fst)).to₂).of_eq $ λ a, begin simp, cases f a; simp, refine ext (λ b, ⟨λ H, _, λ H, _⟩), { rcases mem_bind_iff.1 H with ⟨c, h₁, h₂⟩, exact h₂ }, { have : ∀ m, (nat.elim (part.some (g a)) (λ y IH, IH.bind (λ _, h a n)) m).dom, { intro, induction m; simp [*, H.fst] }, exact ⟨⟨this n, H.fst⟩, H.snd⟩ } end theorem bind_decode₂_iff {f : α →. σ} : partrec f ↔ nat.partrec (λ n, part.bind (decode₂ α n) (λ a, (f a).map encode)) := ⟨λ hf, nat_iff.1 $ (of_option primrec.decode₂.to_comp).bind $ (map hf (computable.encode.comp snd).to₂).comp snd, λ h, map_encode_iff.1 $ by simpa [encodek₂] using (nat_iff.2 h).comp (@computable.encode α _)⟩ theorem vector_m_of_fn : ∀ {n} {f : fin n → α →. σ}, (∀ i, partrec (f i)) → partrec (λ (a : α), vector.m_of_fn (λ i, f i a)) | 0 f hf := const _ | (n+1) f hf := by simp [vector.m_of_fn]; exact (hf 0).bind (partrec.bind ((vector_m_of_fn (λ i, hf i.succ)).comp fst) (primrec.vector_cons.to_comp.comp (snd.comp fst) snd)) end partrec @[simp] theorem vector.m_of_fn_part_some {α n} : ∀ (f : fin n → α), vector.m_of_fn (λ i, part.some (f i)) = part.some (vector.of_fn f) := vector.m_of_fn_pure namespace computable variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem option_some_iff {f : α → σ} : computable (λ a, some (f a)) ↔ computable f := ⟨λ h, encode_iff.1 $ primrec.pred.to_comp.comp $ encode_iff.2 h, option_some.comp⟩ theorem bind_decode_iff {f : α → β → option σ} : computable₂ (λ a n, (decode β n).bind (f a)) ↔ computable₂ f := ⟨λ hf, nat.partrec.of_eq (((partrec.nat_iff.2 (nat.partrec.ppred.comp $ nat.partrec.of_primrec $ primcodable.prim β)).comp snd).bind (computable.comp hf fst).to₂.partrec₂) $ λ n, by simp; cases decode α n.unpair.1; simp; cases decode β n.unpair.2; simp, λ hf, begin have : partrec (λ a : α × ℕ, (encode (decode β a.2)).cases (some option.none) (λ n, part.map (f a.1) (decode β n))) := partrec.nat_cases_right (primrec.encdec.to_comp.comp snd) (const none) ((of_option (computable.decode.comp snd)).map (hf.comp (fst.comp $ fst.comp fst) snd).to₂), refine this.of_eq (λ a, _), simp, cases decode β a.2; simp [encodek] end⟩ theorem map_decode_iff {f : α → β → σ} : computable₂ (λ a n, (decode β n).map (f a)) ↔ computable₂ f := bind_decode_iff.trans option_some_iff theorem nat_elim {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).elim (g a) (λ y IH, h a (y, IH))) := (partrec.nat_elim hf hg hh.partrec₂).of_eq $ λ a, by simp; induction f a; simp * theorem nat_cases {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable (λ a, (f a).cases (g a) (h a)) := nat_elim hf hg (hh.comp fst $ fst.comp snd).to₂ theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : computable c) (hf : computable f) (hg : computable g) : computable (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : computable o) (hf : computable f) (hg : computable₂ g) : @computable _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := option_some_iff.1 $ (nat_cases (encode_iff.2 ho) (option_some_iff.2 hf) (map_decode_iff.2 hg)).of_eq $ λ a, by cases o a; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).bind (g a)) := (option_cases hf (const option.none) hg).of_eq $ λ a, by cases f a; refl theorem option_map {f : α → option β} {g : α → β → σ} (hf : computable f) (hg : computable₂ g) : computable (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_get_or_else {f : α → option β} {g : α → β} (hf : computable f) (hg : computable g) : computable (λ a, (f a).get_or_else (g a)) := (computable.option_cases hf hg (show computable₂ (λ a b, b), from computable.snd)).of_eq $ λ a, by cases f a; refl theorem subtype_mk {f : α → β} {p : β → Prop} [decidable_pred p] {h : ∀ a, p (f a)} (hp : primrec_pred p) (hf : computable f) : @computable _ _ _ (primcodable.subtype hp) (λ a, (⟨f a, h a⟩ : subtype p)) := hf theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : computable f) (hg : computable₂ g) (hh : computable₂ h) : @computable _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (computable.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : computable₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : computable₂ f := suffices computable₂ (λ a n, (list.range n).map (f a)), from option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a, by simp [list.nth_range (nat.lt_succ_self a.2)]; refl, option_some_iff.1 $ (nat_elim snd (const (option.some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp $ fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a, begin simp, induction a.2 with n IH, {refl}, simp [IH, H, list.range_succ] end theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, computable (f i)) → computable (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, computable (f i)) : computable (λ a, vector.of_fn (λ i, f i a)) := (partrec.vector_m_of_fn hf).of_eq $ λ a, by simp end computable namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable theorem option_some_iff {f : α →. σ} : partrec (λ a, (f a).map option.some) ↔ partrec f := ⟨λ h, (nat.partrec.ppred.comp h).of_eq $ λ n, by simp [part.bind_assoc, bind_some_eq_map], λ hf, hf.map (option_some.comp snd).to₂⟩ theorem option_cases_right {o : α → option β} {f : α → σ} {g : α → β →. σ} (ho : computable o) (hf : computable f) (hg : partrec₂ g) : @partrec _ σ _ _ (λ a, option.cases_on (o a) (some (f a)) (g a)) := have partrec (λ (a : α), nat.cases (part.some (f a)) (λ n, part.bind (decode β n) (g a)) (encode (o a))) := nat_cases_right (encode_iff.2 ho) hf.partrec $ ((@computable.decode β _).comp snd).of_option.bind (hg.comp (fst.comp fst) snd).to₂, this.of_eq $ λ a, by cases o a with b; simp [encodek] theorem sum_cases_right {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : computable f) (hg : computable₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (λ b, some (g a b)) (h a)) := have partrec (λ a, (option.cases_on (sum.cases_on (f a) (λ b, option.none) option.some : option γ) (some (sum.cases_on (f a) (λ b, some (g a b)) (λ c, option.none))) (λ c, (h a c).map option.some) : part (option σ))) := option_cases_right (sum_cases hf (const option.none).to₂ (option_some.comp snd).to₂) (sum_cases hf (option_some.comp hg) (const option.none).to₂) (option_some_iff.2 hh), option_some_iff.1 $ this.of_eq $ λ a, by cases f a; simp theorem sum_cases_left {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : computable f) (hg : partrec₂ g) (hh : computable₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (λ c, some (h a c))) := (sum_cases_right (sum_cases hf (sum_inr.comp snd).to₂ (sum_inl.comp snd).to₂) hh hg).of_eq $ λ a, by cases f a; simp lemma fix_aux {α σ} (f : α →. σ ⊕ α) (a : α) (b : σ) : let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, part.some s) f in (∃ (n : ℕ), ((∃ (b' : σ), sum.inl b' ∈ F a n) ∧ ∀ {m : ℕ}, m < n → (∃ (b : α), sum.inr b ∈ F a m)) ∧ sum.inl b ∈ F a n) ↔ b ∈ pfun.fix f a := begin intro, refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨n, ⟨_x, h₁⟩, h₂⟩, have : ∀ m a' (_: sum.inr a' ∈ F a m) (_: b ∈ pfun.fix f a'), b ∈ pfun.fix f a, { intros m a' am ba, induction m with m IH generalizing a'; simp [F] at am, { rwa ← am }, rcases am with ⟨a₂, am₂, fa₂⟩, exact IH _ am₂ (pfun.mem_fix_iff.2 (or.inr ⟨_, fa₂, ba⟩)) }, cases n; simp [F] at h₂, {cases h₂}, rcases h₂ with h₂ | ⟨a', am', fa'⟩, { cases h₁ (nat.lt_succ_self _) with a' h, injection mem_unique h h₂ }, { exact this _ _ am' (pfun.mem_fix_iff.2 (or.inl fa')) } }, { suffices : ∀ a' (_: b ∈ pfun.fix f a') k (_: sum.inr a' ∈ F a k), ∃ n, sum.inl b ∈ F a n ∧ ∀ (m < n) (_ : k ≤ m), ∃ a₂, sum.inr a₂ ∈ F a m, { rcases this _ h 0 (by simp [F]) with ⟨n, hn₁, hn₂⟩, exact ⟨_, ⟨⟨_, hn₁⟩, λ m mn, hn₂ m mn (nat.zero_le _)⟩, hn₁⟩ }, intros a₁ h₁, apply pfun.fix_induction h₁, intros a₂ h₂ IH k hk, rcases pfun.mem_fix_iff.1 h₂ with h₂ | ⟨a₃, am₃, fa₃⟩, { refine ⟨k.succ, _, λ m mk km, ⟨a₂, _⟩⟩, { simp [F], exact or.inr ⟨_, hk, h₂⟩ }, { rwa le_antisymm (nat.le_of_lt_succ mk) km } }, { rcases IH _ fa₃ am₃ k.succ _ with ⟨n, hn₁, hn₂⟩, { refine ⟨n, hn₁, λ m mn km, _⟩, cases km.lt_or_eq_dec with km km, { exact hn₂ _ mn km }, { exact km ▸ ⟨_, hk⟩ } }, { simp [F], exact ⟨_, hk, am₃⟩ } } } end theorem fix {f : α →. σ ⊕ α} (hf : partrec f) : partrec (pfun.fix f) := let F : α → ℕ →. σ ⊕ α := λ a n, n.elim (some (sum.inr a)) $ λ y IH, IH.bind $ λ s, sum.cases_on s (λ _, part.some s) f in have hF : partrec₂ F := partrec.nat_elim snd (sum_inr.comp fst).partrec (sum_cases_right (snd.comp snd) (snd.comp $ snd.comp fst).to₂ (hf.comp snd).to₂).to₂, let p := λ a n, @part.map _ bool (λ s, sum.cases_on s (λ_, tt) (λ _, ff)) (F a n) in have hp : partrec₂ p := hF.map ((sum_cases computable.id (const tt).to₂ (const ff).to₂).comp snd).to₂, (hp.rfind.bind (hF.bind (sum_cases_right snd snd.to₂ none.to₂).to₂).to₂).of_eq $ λ a, ext $ λ b, by simp; apply fix_aux f end partrec
524301384c37f765ea8be6261bbde4a24a84a568
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/ToExpr.lean
25e529d3c5fd4944844a4bfa8c55e16af0afef6d
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,686
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.Expr universe u namespace Lean class ToExpr (α : Type u) where toExpr : α → Expr toTypeExpr : Expr export ToExpr (toExpr toTypeExpr) instance : ToExpr Expr where toExpr := id toTypeExpr := mkConst `Expr instance : ToExpr Nat where toExpr := mkNatLit toTypeExpr := mkConst `Nat instance : ToExpr Bool where toExpr := fun b => if b then mkConst `Bool.true else mkConst `Bool.false toTypeExpr := mkConst `Bool instance : ToExpr Char where toExpr := fun c => mkApp (mkConst `Char.ofNat) (toExpr c.toNat) toTypeExpr := mkConst `Char instance : ToExpr String where toExpr := mkStrLit toTypeExpr := mkConst `String instance : ToExpr Unit where toExpr := fun _ => mkConst `Unit.unit toTypeExpr := mkConst `Unit def Name.toExprAux : Name → Expr | Name.anonymous => mkConst `Lean.Name.anonymous | Name.str p s _ => mkAppB (mkConst `Lean.Name.mkStr) (toExprAux p) (toExpr s) | Name.num p n _ => mkAppB (mkConst `Lean.Name.mkNum) (toExprAux p) (toExpr n) instance : ToExpr Name where toExpr := Name.toExprAux toTypeExpr := mkConst `Name instance {α : Type} [ToExpr α] : ToExpr (Option α) := let type := toTypeExpr α { toExpr := fun o => match o with | none => mkApp (mkConst `Option.none [levelZero]) type | some a => mkApp2 (mkConst `Option.cons [levelZero]) type (toExpr a), toTypeExpr := mkApp (mkConst `Option [levelZero]) type } def List.toExprAux {α} [ToExpr α] (nilFn : Expr) (consFn : Expr) : List α → Expr | [] => nilFn | a::as => mkApp2 consFn (toExpr a) (toExprAux nilFn consFn as) instance {α : Type} [ToExpr α] : ToExpr (List α) := let type := toTypeExpr α let nil := mkApp (mkConst `List.nil [levelZero]) type let cons := mkApp (mkConst `List.cons [levelZero]) type { toExpr := List.toExprAux nil cons, toTypeExpr := mkApp (mkConst `List [levelZero]) type } instance {α : Type} [ToExpr α] : ToExpr (Array α) := let type := toTypeExpr α { toExpr := fun as => mkApp2 (mkConst `List.toArray [levelZero]) type (toExpr as.toList), toTypeExpr := mkApp (mkConst `Array [levelZero]) type } instance {α : Type} {β : Type} [ToExpr α] [ToExpr β] : ToExpr (α × β) := let αType := toTypeExpr α let βType := toTypeExpr β { toExpr := fun ⟨a, b⟩ => mkApp4 (mkConst `Prod.mk [levelZero, levelZero]) αType βType (toExpr a) (toExpr b), toTypeExpr := mkApp2 (mkConst `Prod [levelZero, levelZero]) αType βType } end Lean
0a2eed328dab9149ac16a15baa8402deec50928b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/polynomial/degree/card_pow_degree.lean
97d35000554b12475fe3adad299b432588f51f84
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
3,709
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.order.euclidean_absolute_value import data.polynomial.field_division /-! # Absolute value on polynomials over a finite field. Let `Fq` be a finite field of cardinality `q`, then the map sending a polynomial `p` to `q ^ degree p` (where `q ^ degree 0 = 0`) is an absolute value. ## Main definitions * `polynomial.card_pow_degree` is an absolute value on `𝔽_q[t]`, the ring of polynomials over a finite field of cardinality `q`, mapping a polynomial `p` to `q ^ degree p` (where `q ^ degree 0 = 0`) ## Main results * `polynomial.card_pow_degree_is_euclidean`: `card_pow_degree` respects the Euclidean domain structure on the ring of polynomials -/ namespace polynomial variables {Fq : Type*} [field Fq] [fintype Fq] open absolute_value open_locale classical /-- `card_pow_degree` is the absolute value on `𝔽_q[t]` sending `f` to `q ^ degree f`. `card_pow_degree 0` is defined to be `0`. -/ noncomputable def card_pow_degree : absolute_value (polynomial Fq) ℤ := have card_pos : 0 < fintype.card Fq := fintype.card_pos_iff.mpr infer_instance, have pow_pos : ∀ n, 0 < (fintype.card Fq : ℤ) ^ n := λ n, pow_pos (int.coe_nat_pos.mpr card_pos) n, { to_fun := λ p, if p = 0 then 0 else fintype.card Fq ^ p.nat_degree, nonneg' := λ p, by { dsimp, split_ifs, { refl }, exact pow_nonneg (int.coe_zero_le _) _ }, eq_zero' := λ p, ite_eq_left_iff.trans $ ⟨λ h, by { contrapose! h, exact ⟨h, (pow_pos _).ne'⟩ }, absurd⟩, add_le' := λ p q, begin by_cases hp : p = 0, { simp [hp] }, by_cases hq : q = 0, { simp [hq] }, by_cases hpq : p + q = 0, { simp only [hpq, hp, hq, eq_self_iff_true, if_true, if_false], exact add_nonneg (pow_pos _).le (pow_pos _).le }, simp only [hpq, hp, hq, if_false], refine le_trans (pow_le_pow (by linarith) (polynomial.nat_degree_add_le _ _)) _, refine le_trans (le_max_iff.mpr _) (max_le_add_of_nonneg (pow_nonneg (by linarith) _) (pow_nonneg (by linarith) _)), exact (max_choice p.nat_degree q.nat_degree).imp (λ h, by rw [h]) (λ h, by rw [h]) end, map_mul' := λ p q, begin by_cases hp : p = 0, { simp [hp] }, by_cases hq : q = 0, { simp [hq] }, have hpq : p * q ≠ 0 := mul_ne_zero hp hq, simp only [hpq, hp, hq, eq_self_iff_true, if_true, if_false, polynomial.nat_degree_mul hp hq, pow_add], end } lemma card_pow_degree_apply (p : polynomial Fq) : card_pow_degree p = if p = 0 then 0 else fintype.card Fq ^ nat_degree p := rfl @[simp] lemma card_pow_degree_zero : card_pow_degree (0 : polynomial Fq) = 0 := if_pos rfl @[simp] lemma card_pow_degree_nonzero (p : polynomial Fq) (hp : p ≠ 0) : card_pow_degree p = fintype.card Fq ^ p.nat_degree := if_neg hp lemma card_pow_degree_is_euclidean : is_euclidean (card_pow_degree : absolute_value (polynomial Fq) ℤ) := have card_pos : 0 < fintype.card Fq := fintype.card_pos_iff.mpr infer_instance, have pow_pos : ∀ n, 0 < (fintype.card Fq : ℤ) ^ n := λ n, pow_pos (int.coe_nat_pos.mpr card_pos) n, { map_lt_map_iff' := λ p q, begin simp only [euclidean_domain.r, card_pow_degree_apply], split_ifs with hp hq hq, { simp only [hp, hq, lt_self_iff_false] }, { simp only [hp, hq, degree_zero, ne.def, bot_lt_iff_ne_bot, degree_eq_bot, pow_pos, not_false_iff] }, { simp only [hp, hq, degree_zero, not_lt_bot, (pow_pos _).not_lt] }, { rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe, pow_lt_pow_iff], exact_mod_cast @fintype.one_lt_card Fq _ _ }, end } end polynomial
0e6e56f489da38d2c67737de9433a563530b2ef5
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/metric_space/gromov_hausdorff_realized.lean
3cbe80c69dc6170aafabd214d856985ab4556384
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
26,160
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance noncomputable theory open_locale classical open_locale topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : nnreal := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.val ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : add_le_add_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : add_le_add_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact f (candidates_lipschitz fA).continuous lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b α β).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed_inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows -/ private lemma compact_candidates_b : is_compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) (default β) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) (default α) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0) (default β), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0) (default α), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : premetric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist premetric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := premetric.metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist α β (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist α β (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
15ac721415decce0e21d00dd2d162605d7963c8a
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0101.lean
fd733cd57821daaf22af8d899c16271d90649a96
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
161
lean
constant m : nat constant n : nat constants b1 b2 : bool #check m #check n #check n + 0 #check m * (n + 0) #check b1 #check b1 && b2 #check b1 || b2 #check tt
017e097e628d1ab07bb6480fc7b8bf507f3f61a6
4fa161becb8ce7378a709f5992a594764699e268
/src/topology/metric_space/emetric_space.lean
112141c25eeee905b02ce35afb4a0ce7ff0afd29
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
39,956
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.ennreal import topology.uniform_space.uniform_embedding import topology.uniform_space.pi import topology.uniform_space.uniform_convergence /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 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) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], 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 [edist_comm] } section prio set_option default_priority 100 -- see Note [default priority] -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric 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 an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ @[nolint ge_or_gt] -- see Note [nolint_ge] class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) end prio /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y := le_zero_iff_eq.trans edist_eq_zero /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z) /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ennreal) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add' hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} := emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_edist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ennreal} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases dense ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ennreal) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : nnreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem uniform_embedding_iff' [emetric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete emetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp [← nhds_within_univ, ← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff] /-- Expressing uniform convergence using `edist`. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } end emetric open emetric /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.coe_ext.2) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, 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 } lemma prod.edist_eq [emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist 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 (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h @[nolint ge_or_gt] -- see Note [nolint_ge] theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist @[nolint ge_or_gt] -- see Note [nolint_ge] theorem nhds_eq : 𝓝 x = (⨅ε>0, principal (ball x ε)) := nhds_basis_eball.eq_binfi @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff @[nolint ge_or_gt] -- see Note [nolint_ge] theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff @[nolint ge_or_gt] -- see Note [nolint_ge] theorem tendsto_at_top [nonempty β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `nnreal` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' @[nolint ge_or_gt] -- see Note [nolint_ge] theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { 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 }}, /-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, finite.countable], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], 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⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, 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 first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section second_countable open topological_space /-- A separable emetric 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 (α : Type u) [emetric_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⁻¹)}, { apply S_countable.bUnion, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.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 ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff_forall_edist_le {d : ennreal} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff_forall_edist_le.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := le_zero_iff_eq.1 $ diam_le_of_forall_edist_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _ /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [zero_lt_iff_ne_zero, exists_prop] using this end lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add' ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
5249b4f6a01900f7ded866eb06c4466809f3704c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/dbgMacros.lean
8d0d9e23f67332b1802545d23b097f371968b5a1
[ "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
372
lean
def f (x : Nat) := if x = 0 then panic! "unexpected zero" else x - 1 #eval f 0 #eval f 10 def g (x : Nat) := if x = 0 then unreachable! else x - 1 #eval g 0 def h (x : Nat) := assert! x != 0; x - 1 #eval h 1 #eval h 0 def f2 (x : Nat) := dbg_trace "f2, x: {x}"; x + 1 #eval f2 10 def g2 (x : Nat) : IO Nat := do IO.println "g2 started"; pure (x + 1) #eval g2 10
a333b08a7a7ab48bc211564ba4634e2b17eeb95c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/boolean_algebra.lean
0bb2f78a6b2dee25890f6d34ceac0dd096a824fd
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,579
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Type class hierarchy for Boolean algebras. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.bounded_lattice import Mathlib.PostPort universes u_1 l u v namespace Mathlib /-- Set / lattice complement -/ class has_compl (α : Type u_1) where compl : α → α postfix:0 "ᶜ" => Mathlib.has_compl.compl /-- A boolean algebra is a bounded distributive lattice with a complementation operation `-` such that `x ⊓ - x = ⊥` and `x ⊔ - x = ⊤`. This is a generalization of (classical) logic of propositions, or the powerset lattice. -/ class boolean_algebra (α : Type u_1) extends has_sdiff α, has_compl α, bounded_distrib_lattice α where inf_compl_le_bot : ∀ (x : α), x ⊓ (xᶜ) ≤ ⊥ top_le_sup_compl : ∀ (x : α), ⊤ ≤ x ⊔ (xᶜ) sdiff_eq : ∀ (x y : α), x \ y = x ⊓ (yᶜ) @[simp] theorem inf_compl_eq_bot {α : Type u} {x : α} [boolean_algebra α] : x ⊓ (xᶜ) = ⊥ := bot_unique (boolean_algebra.inf_compl_le_bot x) @[simp] theorem compl_inf_eq_bot {α : Type u} {x : α} [boolean_algebra α] : xᶜ ⊓ x = ⊥ := Eq.trans inf_comm inf_compl_eq_bot @[simp] theorem sup_compl_eq_top {α : Type u} {x : α} [boolean_algebra α] : x ⊔ (xᶜ) = ⊤ := top_unique (boolean_algebra.top_le_sup_compl x) @[simp] theorem compl_sup_eq_top {α : Type u} {x : α} [boolean_algebra α] : xᶜ ⊔ x = ⊤ := Eq.trans sup_comm sup_compl_eq_top theorem is_compl_compl {α : Type u} {x : α} [boolean_algebra α] : is_compl x (xᶜ) := is_compl.of_eq inf_compl_eq_bot sup_compl_eq_top theorem is_compl.compl_eq {α : Type u} {x : α} {y : α} [boolean_algebra α] (h : is_compl x y) : xᶜ = y := Eq.symm (is_compl.right_unique h is_compl_compl) theorem disjoint_compl_right {α : Type u} {x : α} [boolean_algebra α] : disjoint x (xᶜ) := is_compl.disjoint is_compl_compl theorem disjoint_compl_left {α : Type u} {x : α} [boolean_algebra α] : disjoint (xᶜ) x := disjoint.symm disjoint_compl_right theorem sdiff_eq {α : Type u} {x : α} {y : α} [boolean_algebra α] : x \ y = x ⊓ (yᶜ) := boolean_algebra.sdiff_eq x y theorem compl_unique {α : Type u} {x : α} {y : α} [boolean_algebra α] (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : xᶜ = y := is_compl.compl_eq (is_compl.of_eq i s) @[simp] theorem compl_top {α : Type u} [boolean_algebra α] : ⊤ᶜ = ⊥ := is_compl.compl_eq is_compl_top_bot @[simp] theorem compl_bot {α : Type u} [boolean_algebra α] : ⊥ᶜ = ⊤ := is_compl.compl_eq is_compl_bot_top @[simp] theorem compl_compl {α : Type u} [boolean_algebra α] (x : α) : xᶜᶜ = x := is_compl.compl_eq (is_compl.symm is_compl_compl) theorem compl_injective {α : Type u} [boolean_algebra α] : function.injective compl := function.involutive.injective compl_compl @[simp] theorem compl_inj_iff {α : Type u} {x : α} {y : α} [boolean_algebra α] : xᶜ = (yᶜ) ↔ x = y := function.injective.eq_iff compl_injective theorem is_compl.compl_eq_iff {α : Type u} {x : α} {y : α} {z : α} [boolean_algebra α] (h : is_compl x y) : zᶜ = y ↔ z = x := is_compl.compl_eq h ▸ compl_inj_iff @[simp] theorem compl_eq_top {α : Type u} {x : α} [boolean_algebra α] : xᶜ = ⊤ ↔ x = ⊥ := is_compl.compl_eq_iff is_compl_bot_top @[simp] theorem compl_eq_bot {α : Type u} {x : α} [boolean_algebra α] : xᶜ = ⊥ ↔ x = ⊤ := is_compl.compl_eq_iff is_compl_top_bot @[simp] theorem compl_inf {α : Type u} {x : α} {y : α} [boolean_algebra α] : x ⊓ yᶜ = xᶜ ⊔ (yᶜ) := is_compl.compl_eq (is_compl.inf_sup is_compl_compl is_compl_compl) @[simp] theorem compl_sup {α : Type u} {x : α} {y : α} [boolean_algebra α] : x ⊔ yᶜ = xᶜ ⊓ (yᶜ) := is_compl.compl_eq (is_compl.sup_inf is_compl_compl is_compl_compl) theorem compl_le_compl {α : Type u} {x : α} {y : α} [boolean_algebra α] (h : y ≤ x) : xᶜ ≤ (yᶜ) := is_compl.antimono is_compl_compl is_compl_compl h @[simp] theorem compl_le_compl_iff_le {α : Type u} {x : α} {y : α} [boolean_algebra α] : yᶜ ≤ (xᶜ) ↔ x ≤ y := sorry theorem le_compl_of_le_compl {α : Type u} {x : α} {y : α} [boolean_algebra α] (h : y ≤ (xᶜ)) : x ≤ (yᶜ) := sorry theorem compl_le_of_compl_le {α : Type u} {x : α} {y : α} [boolean_algebra α] (h : yᶜ ≤ x) : xᶜ ≤ y := sorry theorem le_compl_iff_le_compl {α : Type u} {x : α} {y : α} [boolean_algebra α] : y ≤ (xᶜ) ↔ x ≤ (yᶜ) := { mp := le_compl_of_le_compl, mpr := le_compl_of_le_compl } theorem compl_le_iff_compl_le {α : Type u} {x : α} {y : α} [boolean_algebra α] : xᶜ ≤ y ↔ yᶜ ≤ x := { mp := compl_le_of_compl_le, mpr := compl_le_of_compl_le } theorem sup_sdiff_same {α : Type u} {x : α} {y : α} [boolean_algebra α] : x ⊔ y \ x = x ⊔ y := sorry theorem sdiff_eq_left {α : Type u} {x : α} {y : α} [boolean_algebra α] (h : x ⊓ y = ⊥) : x \ y = x := sorry theorem sdiff_le_sdiff {α : Type u} {w : α} {x : α} {y : α} {z : α} [boolean_algebra α] (h₁ : w ≤ y) (h₂ : z ≤ x) : w \ x ≤ y \ z := eq.mpr (id (Eq._oldrec (Eq.refl (w \ x ≤ y \ z)) sdiff_eq)) (eq.mpr (id (Eq._oldrec (Eq.refl (w ⊓ (xᶜ) ≤ y \ z)) sdiff_eq)) (inf_le_inf h₁ (compl_le_compl h₂))) @[simp] theorem sdiff_idem_right {α : Type u} {x : α} {y : α} [boolean_algebra α] : x \ y \ y = x \ y := sorry protected instance boolean_algebra_Prop : boolean_algebra Prop := boolean_algebra.mk bounded_distrib_lattice.sup bounded_distrib_lattice.le bounded_distrib_lattice.lt sorry sorry sorry sorry sorry sorry bounded_distrib_lattice.inf sorry sorry sorry sorry bounded_distrib_lattice.top sorry bounded_distrib_lattice.bot sorry Not (fun (p q : Prop) => p ∧ ¬q) sorry sorry sorry protected instance pi.boolean_algebra {α : Type u} {β : Type v} [boolean_algebra β] : boolean_algebra (α → β) := boolean_algebra.mk (fun (ᾰ ᾰ_1 : α → β) (i : α) => boolean_algebra.sup (ᾰ i) (ᾰ_1 i)) partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry (fun (ᾰ ᾰ_1 : α → β) (i : α) => boolean_algebra.inf (ᾰ i) (ᾰ_1 i)) sorry sorry sorry sorry (fun (i : α) => boolean_algebra.top) sorry (fun (i : α) => boolean_algebra.bot) sorry (fun (ᾰ : α → β) (i : α) => boolean_algebra.compl (ᾰ i)) (fun (ᾰ ᾰ_1 : α → β) (i : α) => boolean_algebra.sdiff (ᾰ i) (ᾰ_1 i)) sorry sorry sorry
3f273a94e754da2522fef1425e4cbb7978d28135
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/generalizes.lean
c1041b78e7ac2021cd6d262e6091a6d09c564c9c
[ "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
246
lean
open tactic theorem tst (A B : Type) (a : A) (b : B) : a == b → b == a := by do a ← get_local `a, b ← get_local `b, B ← get_local `B, generalizes [a, b, B], intro_lst [`B', `b, `a], H ← intro `H, mk_app `heq.symm [H] >>= exact
e32f8f8ee2353724c0b1032f27043a0ed0f69545
7da5ceac20aaab989eeb795a4be9639982e7b35a
/src/analysis/manifolds/manifold.lean
b9bad907296cfcda7daa1e9b71eb1d590bacbd52
[ "MIT" ]
permissive
formalabstracts/formalabstracts
46c2f1b3a172e62ca6ffeb46fbbdf1705718af49
b0173da1af45421239d44492eeecd54bf65ee0f6
refs/heads/master
1,606,896,370,374
1,572,988,776,000
1,572,988,776,000
96,763,004
165
28
null
1,555,709,319,000
1,499,680,948,000
Lean
UTF-8
Lean
false
false
4,057
lean
import .basic open pfun topological_space set noncomputable theory universes u v w variables {k : ℕ∞} {E : euclidean_space.{u}} /- topological manifolds -/ structure chart (X : Top) (E : euclidean_space) := (iso : X ≃ₜ. E.to_Top) (h1 : is_open iso.to_fun.dom) (h2 : is_open iso.inv_fun.dom) namespace chart variable {X : Top} def to_fun (c : chart X E) : X →. E := c.iso.to_fun def inv_fun (c : chart X E) : E →. X := c.iso.inv_fun def domain (c : chart X E) : set X := dom c.to_fun def codomain (c : chart X E) : set E := dom c.inv_fun def restrict {s : set X} (hs : is_open s) (c : chart X E) : chart (X.restrict s) E := ⟨(phomeo.restrict_phomeo s).trans c.iso, omitted, omitted⟩ end chart def compatible_charts {X : Top} (k : ℕ∞) (c₁ c₂ : chart X E) : Prop := is_smooth k (c₂.to_fun ∘. c₁.inv_fun) ∧ is_smooth k (c₁.to_fun ∘. c₂.inv_fun) structure topological_manifold (E : euclidean_space) := (carrier : Top) (struct2 : t2_space carrier) (struct3 : second_countable_topology carrier) (charts : set (chart carrier E)) (cover : ⋃₀ (chart.domain '' charts) = univ) namespace topological_manifold instance : has_coe (topological_manifold E) Top := ⟨topological_manifold.carrier⟩ def restrict (X : topological_manifold E) {s : set X} (hs : is_open s) : topological_manifold E := ⟨X.carrier.restrict s, omitted, omitted, chart.restrict hs '' X.charts, omitted⟩ end topological_manifold structure differentiable_manifold (k : ℕ∞) (E : euclidean_space) extends topological_manifold E := (compatible : ∀{{c₁ c₂}}, c₁ ∈ charts → c₂ ∈ charts → compatible_charts k c₁ c₂) namespace euclidean_space def to_differentiable_manifold (E : euclidean_space) (k : ℕ∞) : differentiable_manifold k E := ⟨⟨E.to_Top, omitted, omitted, {⟨phomeo.rfl, is_open_univ, is_open_univ⟩}, omitted⟩, omitted⟩ end euclidean_space namespace differentiable_manifold instance : has_coe (differentiable_manifold k E) Top := ⟨λX, X.to_topological_manifold.carrier⟩ /- a maximal atlas is a set of charts which is compatible with all charts of X -/ def max_atlas (X : differentiable_manifold k E) : set (chart X.carrier E) := { c | ∀c' ∈ X.charts, compatible_charts k c c' } /- examples and constructions -/ def restrict (X : differentiable_manifold k E) {s : set X} (hs : is_open s) : differentiable_manifold k E := ⟨X.to_topological_manifold.restrict hs, omitted⟩ def sphere (n : ℕ) : differentiable_manifold ⊤ (euclidean_space.standard_euclidean_space n) := sorry --⟨⟨⟨subtype _, _⟩, _, _, _, _⟩, omitted⟩ /- smooth maps-/ variables {X : differentiable_manifold k E} {Y : differentiable_manifold k E} {Z : differentiable_manifold k E} def respects_charts (f : X → Y) (A : set (chart X.carrier E)) (B : set (chart Y.carrier E)) : Prop := ∀(c ∈ A) (c' ∈ B), is_smooth k (chart.to_fun c' ∘. pfun.lift f ∘. chart.inv_fun c) structure smooth_map (X Y : differentiable_manifold k E) := (map : X → Y) (smooth : respects_charts map X.max_atlas Y.max_atlas) infix ` →ₛ `:25 := smooth_map def incl (X : differentiable_manifold k E) {s : set X} (hs : is_open s) : restrict X hs →ₛ X := ⟨subtype.val, omitted⟩ lemma respects_charts_local (f : X → Y) (A : set (chart X.carrier E)) (B : set (chart Y.carrier E)) (h : ∀x : X, ∃(s : set X) (hs : is_open s), x ∈ s ∧ respects_charts (f ∘ (incl X hs).map) (chart.restrict hs '' A) B) : respects_charts f A B := omitted lemma respects_charts_subset (f : X → Y) (A A' : set (chart X.carrier E)) (B B' : set (chart Y.carrier E)) (hA : ⋃₀ (chart.domain '' A') ⊆ ⋃₀ (chart.domain '' A)) (hB : ⋃₀ (chart.domain '' B') ⊆ ⋃₀ (chart.domain '' B)) (h : respects_charts f A B) : respects_charts f A' B' := omitted namespace smooth_map def id : X →ₛ X := ⟨id, omitted⟩ def comp (g : Y →ₛ Z) (f : X →ₛ Y) : X →ₛ Z := ⟨g.map ∘ f.map, omitted⟩ end smooth_map end differentiable_manifold
544f294ea2d8b788d4f3ac7213007935575582c7
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/meta/match_tactic.lean
f10cc3878ce523cf4efcb174129f08e8eb1e029d
[ "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
4,487
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.function namespace tactic meta structure pattern := /- Term to match. -/ (target : expr) /- Set of universes that is instantiated for each successful match. -/ (uoutput : list level) /- Set of terms that is instantiated for each successful match. -/ (moutput : list expr) /- Number of (temporary) universe meta-variables in this pattern. -/ (nuvars : nat) /- Number of (temporary) meta-variables in this pattern. -/ (nmvars : nat) /- (mk_pattern ls es t u o) creates a new pattern with (length ls) universe meta-variables and (length es) meta-variables. In the produced pattern p, we have that - (pattern.target p) is the term t where the universes ls and expressions es have been replaced with temporary meta-variables. - (pattern.uoutput p) is the list u where the universes ls have been replaced with temporary meta-variables. - (pattern.moutput p) is the list o where the universes ls and expressions es have been replaced with temporary meta-variables. - (pattern.nuvars p) = length ls - (pattern.nmvars p) = length es The tactic fails if o and the types of es do not contain all universes ls and expressions es. -/ meta constant mk_pattern : list level → list expr → expr → list level → list expr → tactic pattern /- (mk_pattern_core m p e) matches (pattern.target p) and e using transparency m. If the matching is successful, then return the instantiation of (pattern.output p). The tactic fails if not all (temporary) meta-variables are assigned. -/ meta constant match_pattern_core : transparency → pattern → expr → tactic (list level × list expr) meta def match_pattern (p : pattern) (e : expr) : tactic (list expr) := prod.snd <$> (match_pattern_core semireducible p e) open expr /- Helper function for converting a term (λ x_1 ... x_n, t) into a pattern where x_1 ... x_n are metavariables -/ private meta def to_pattern_core : expr → tactic (expr × list expr) | (lam n bi d b) := do id ← mk_fresh_name, let x := local_const id n bi d, let new_b := instantiate_var b x, (p, xs) ← to_pattern_core new_b, return (p, x::xs) | e := return (e, []) /- Given a pre-term of the form (λ x_1 ... x_n, t[x_1, ..., x_n]), converts it into the pattern t[?x_1, ..., ?x_n] -/ meta def pexpr_to_pattern (p : pexpr) : tactic pattern := do e ← to_expr p, (new_p, xs) ← to_pattern_core e, mk_pattern [] xs new_p [] xs /- Convert pre-term into a pattern and try to match e. Given p of the form (λ x_1 ... x_n, t[x_1, ..., x_n]), a successful match will produce a list of length n. -/ meta def match_expr (p : pexpr) (e : expr) : tactic (list expr) := do new_p ← pexpr_to_pattern p, match_pattern new_p e private meta def match_subexpr_core : pattern → list expr → tactic (list expr) | p [] := failed | p (e::es) := match_pattern p e <|> match_subexpr_core p es <|> if is_app e then match_subexpr_core p (get_app_args e) else failed /- Similar to match_expr, but it tries to match a subexpression of e. Remark: the procedure does not go inside binders. -/ meta def match_subexpr (p : pexpr) (e : expr) : tactic (list expr) := do new_p ← pexpr_to_pattern p, match_subexpr_core new_p [e] /- Match the main goal target. -/ meta def match_target (p : pexpr) : tactic (list expr) := target >>= match_expr p /- Match a subterm in the main goal target. -/ meta def match_target_subexpr (p : pexpr) : tactic (list expr) := target >>= match_subexpr p private meta def match_hypothesis_core : pattern → list expr → tactic (expr × list expr) | p [] := failed | p (h::hs) := do h_type ← infer_type h, (do r ← match_pattern p h_type, return (h, r)) <|> match_hypothesis_core p hs /- Match hypothesis in the main goal target. The result is pair (hypothesis, substitution). -/ meta def match_hypothesis (p : pexpr) : tactic (expr × list expr) := do ctx ← local_context, new_p ← pexpr_to_pattern p, match_hypothesis_core new_p ctx meta instance : has_to_tactic_format pattern := ⟨λp, do t ← pp p.target, mo ← pp p.moutput, uo ← pp p.uoutput, u ← pp p.nuvars, m ← pp p.nmvars, return $ to_fmt "pattern.mk (" ++ t ++ ") " ++ uo ++ " " ++ mo ++ " " ++ u ++ " " ++ m ++ "" ⟩ end tactic
3590ef06ff2af19d5537ab4931ec0c975534004e
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Meta/LevelDefEq.lean
a7ed14ac204a16712ff4abad1eb2a804a9f9c135
[ "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
4,756
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.CollectMVars import Lean.Meta.Basic import Lean.Meta.InferType import Lean.Meta.DecLevel namespace Lean.Meta /-- Return true iff `lvl` occurs in `max u_1 ... u_n` and `lvl != u_i` for all `i in [1, n]`. That is, `lvl` is a proper level subterm of some `u_i`. -/ private def strictOccursMax (lvl : Level) : Level → Bool | Level.max u v => visit u || visit v | _ => false where visit : Level → Bool | Level.max u v => visit u || visit v | u => u != lvl && lvl.occurs u /-- `mkMaxArgsDiff mvarId (max u_1 ... (mvar mvarId) ... u_n) v` => `max v u_1 ... u_n` -/ private def mkMaxArgsDiff (mvarId : LMVarId) : Level → Level → Level | Level.max u v, acc => mkMaxArgsDiff mvarId v <| mkMaxArgsDiff mvarId u acc | l@(Level.mvar id), acc => if id != mvarId then mkLevelMax' acc l else acc | l, acc => mkLevelMax' acc l /-- Solve `?m =?= max ?m v` by creating a fresh metavariable `?n` and assigning `?m := max ?n v` -/ private def solveSelfMax (mvarId : LMVarId) (v : Level) : MetaM Unit := do assert! v.isMax let n ← mkFreshLevelMVar assignLevelMVar mvarId <| mkMaxArgsDiff mvarId v n private def postponeIsLevelDefEq (lhs : Level) (rhs : Level) : MetaM Unit := do let ref ← getRef let ctx ← read trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" modifyPostponed fun postponed => postponed.push { lhs := lhs, rhs := rhs, ref := ref, ctx? := ctx.defEqCtx? } private def isMVarWithGreaterDepth (v : Level) (mvarId : LMVarId) : MetaM Bool := match v with | Level.mvar mvarId' => return (← mvarId'.getLevel) > (← mvarId.getLevel) | _ => return false mutual private partial def solve (u v : Level) : MetaM LBool := do match u, v with | Level.mvar mvarId, _ => if (← mvarId.isReadOnly) then return LBool.undef else if (← getConfig).ignoreLevelMVarDepth && (← isMVarWithGreaterDepth v mvarId) then -- If both `u` and `v` are both metavariables, but depth of v is greater, then we assign `v := u`. -- This can only happen when `ignoreLevelDepth` is set to true. assignLevelMVar v.mvarId! u return LBool.true else if !u.occurs v then assignLevelMVar u.mvarId! v return LBool.true else if v.isMax && !strictOccursMax u v then solveSelfMax u.mvarId! v return LBool.true else return LBool.undef | _, Level.mvar .. => return LBool.undef -- Let `solve v u` to handle this case | Level.zero, Level.max v₁ v₂ => Bool.toLBool <$> (isLevelDefEqAux levelZero v₁ <&&> isLevelDefEqAux levelZero v₂) | Level.zero, Level.imax _ v₂ => Bool.toLBool <$> isLevelDefEqAux levelZero v₂ | Level.zero, Level.succ .. => return LBool.false | Level.succ u, v => if v.isParam then return LBool.false else if u.isMVar && u.occurs v then return LBool.undef else match (← Meta.decLevel? v) with | some v => Bool.toLBool <$> isLevelDefEqAux u v | none => return LBool.undef | _, _ => return LBool.undef @[export lean_is_level_def_eq] partial def isLevelDefEqAuxImpl : Level → Level → MetaM Bool | Level.succ lhs, Level.succ rhs => isLevelDefEqAux lhs rhs | lhs, rhs => withTraceNode `Meta.isLevelDefEq (return m!"{exceptBoolEmoji ·} {lhs} =?= {rhs}") do if lhs.getLevelOffset == rhs.getLevelOffset then return lhs.getOffset == rhs.getOffset else let lhs' ← instantiateLevelMVars lhs let lhs' := lhs'.normalize let rhs' ← instantiateLevelMVars rhs let rhs' := rhs'.normalize if lhs != lhs' || rhs != rhs' then isLevelDefEqAux lhs' rhs' else let r ← solve lhs rhs; if r != LBool.undef then return r == LBool.true else let r ← solve rhs lhs; if r != LBool.undef then return r == LBool.true else if !(← hasAssignableLevelMVar lhs <||> hasAssignableLevelMVar rhs) then let ctx ← read if ctx.config.isDefEqStuckEx && (lhs.isMVar || rhs.isMVar) then do trace[Meta.isLevelDefEq.stuck] "{lhs} =?= {rhs}" Meta.throwIsDefEqStuck else return false else postponeIsLevelDefEq lhs rhs return true end builtin_initialize registerTraceClass `Meta.isLevelDefEq registerTraceClass `Meta.isLevelDefEq.stuck (inherited := true) end Lean.Meta
1c3e83dad3a448119447a764a5aa350e377f5673
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/inner_product_space/projection.lean
224ae229cb48cea5ec85b370b23ef56255227feb
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
58,670
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Frédéric Dupuis, Heather Macbeth -/ import analysis.convex.basic import analysis.inner_product_space.basic import analysis.normed_space.is_R_or_C /-! # The orthogonal projection Given a nonempty complete subspace `K` of an inner product space `E`, this file constructs `orthogonal_projection K : E →L[𝕜] K`, the orthogonal projection of `E` onto `K`. This map satisfies: for any point `u` in `E`, the point `v = orthogonal_projection K u` in `K` minimizes the distance `∥u - v∥` to `u`. Also a linear isometry equivalence `reflection K : E ≃ₗᵢ[𝕜] E` is constructed, by choosing, for each `u : E`, the point `reflection K u` to satisfy `u + (reflection K u) = 2 • orthogonal_projection K u`. Basic API for `orthogonal_projection` and `reflection` is developed. Next, the orthogonal projection is used to prove a series of more subtle lemmas about the the orthogonal complement of complete subspaces of `E` (the orthogonal complement itself was defined in `analysis.inner_product_space.basic`); the lemma `submodule.sup_orthogonal_of_is_complete`, stating that for a complete subspace `K` of `E` we have `K ⊔ Kᗮ = ⊤`, is a typical example. The last section covers orthonormal bases, etc. The lemma `maximal_orthonormal_iff_orthogonal_complement_eq_bot` states that an orthonormal set in an inner product space is maximal, if and only the orthogonal complement of its span is trivial. Various consequences are stated for finite-dimensional `E`, including that a maximal orthonormal set is a basis (`maximal_orthonormal_iff_basis_of_finite_dimensional`); these consequences require the theory on the orthogonal complement developed earlier in this file. For consequences in infinite dimension (Hilbert bases, etc.), see the file `analysis.inner_product_space.l2_space`. ## References The orthogonal projection construction is adapted from * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators topological_space variables {𝕜 E F : Type*} [is_R_or_C 𝕜] variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local notation `absR` := has_abs.abs /-! ### Orthogonal projection in inner product spaces -/ /-- Existence of minimizers Let `u` be a point in a real inner product space, and let `K` be a nonempty complete convex subset. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set F} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex ℝ K) : ∀ u : F, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, set.forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos le_rfl nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (nhds δ), { have h : tendsto (λ n:ℕ, δ) at_top (nhds δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (nhds δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):F)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):F), let wq := ((w q):F), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (absR ((2:ℝ)) * ∥u - half•(wq + wp)∥) * (absR ((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw _root_.abs_of_nonneg, exact zero_le_two } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by simp [norm_smul] ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (_root_.two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, from (sub_sub_sub_cancel_left _ _ _).symm, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm _ _, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_sq_le_sq, { exact sqrt_nonneg _ }, rw mul_self_sqrt, calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) nat.one_div_pos_of_nat.le) nat.one_div_pos_of_nat.le), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (nhds (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (nhds ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers for the projection on a convex set in a real inner product space. -/ theorem norm_eq_infi_iff_real_inner_le_zero {K : set F} (h : convex ℝ K) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := ⟪u - v, w - v⟫_ℝ, let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * ⟪u - v, w - v⟫_ℝ + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [sq], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_sq, inner_smul_right, norm_smul], simp only [sq], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+absR (θ)*∥w-v∥*(absR (θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), by abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_right this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact sq_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (sq_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_sq_le_sq (norm_nonneg _), have := h w w.2, calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:F) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:F) - v) + ∥(w:F) - v∥^2 : by { rw sq, refine le_add_of_nonneg_right _, exact sq_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_sq.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, sq] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end variables (K : submodule 𝕜 E) /-- Existence of projections on complete subspaces. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a (unique) `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (h : is_complete (↑K : set E)) : ∀ u : E, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (K : set E), ∥u - w∥ := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E, let K' : submodule ℝ E := submodule.restrict_scalars ℝ K, exact exists_norm_eq_infi_of_complete_convex ⟨0, K'.zero_mem⟩ h K'.convex end /-- Characterization of minimizers in the projection on a subspace, in the real case. Let `u` be a point in a real inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`). This is superceded by `norm_eq_infi_iff_inner_eq_zero` that gives the same conclusion over any `is_R_or_C` field. -/ theorem norm_eq_infi_iff_real_inner_eq_zero (K : submodule ℝ F) {u : F} {v : F} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set F), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫_ℝ = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, { rwa [norm_eq_infi_iff_real_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : ⟪u - v, w⟫_ℝ ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : ⟪u - v, w⟫_ℝ ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj, add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, ⟪u - v, w - v⟫_ℝ ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_real_inner_le_zero, exacts [submodule.convex _, hv] end /-- Characterization of minimizers in the projection on a subspace. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` over points in `K` if and only if for all `w ∈ K`, `⟪u - v, w⟫ = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero {u : E} {v : E} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set E), ∥u - w∥) ↔ ∀ w ∈ K, ⟪u - v, w⟫ = 0 := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : module ℝ E := restrict_scalars.module ℝ 𝕜 E, let K' : submodule ℝ E := K.restrict_scalars ℝ, split, { assume H, have A : ∀ w ∈ K, re ⟪u - v, w⟫ = 0 := (norm_eq_infi_iff_real_inner_eq_zero K' hv).1 H, assume w hw, apply ext, { simp [A w hw] }, { symmetry, calc im (0 : 𝕜) = 0 : im.map_zero ... = re ⟪u - v, (-I) • w⟫ : (A _ (K.smul_mem (-I) hw)).symm ... = re ((-I) * ⟪u - v, w⟫) : by rw inner_smul_right ... = im ⟪u - v, w⟫ : by simp } }, { assume H, have : ∀ w ∈ K', ⟪u - v, w⟫_ℝ = 0, { assume w hw, rw [real_inner_eq_re_inner, H w hw], exact zero_re' }, exact (norm_eq_infi_iff_real_inner_eq_zero K' hv).2 this } end section orthogonal_projection variables [complete_space K] /-- The orthogonal projection onto a complete subspace, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (v : E) := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some variables {K} /-- The unbundled orthogonal projection is in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem (v : E) : orthogonal_projection_fn K v ∈ K := (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some /-- The characterization of the unbundled orthogonal projection. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection_fn K v, w⟫ = 0 := begin rw ←norm_eq_infi_iff_inner_eq_zero K (orthogonal_projection_fn_mem v), exact (exists_norm_eq_infi_of_complete_subspace K (complete_space_coe_iff_is_complete.mp ‹_›) v).some_spec.some_spec end /-- The unbundled orthogonal projection is the unique point in `K` with the orthogonality property. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : orthogonal_projection_fn K u = v := begin rw [←sub_eq_zero, ←inner_self_eq_zero], have hvs : orthogonal_projection_fn K u - v ∈ K := submodule.sub_mem K (orthogonal_projection_fn_mem u) hvm, have huo : ⟪u - orthogonal_projection_fn K u, orthogonal_projection_fn K u - v⟫ = 0 := orthogonal_projection_fn_inner_eq_zero u _ hvs, have huv : ⟪u - v, orthogonal_projection_fn K u - v⟫ = 0 := hvo _ hvs, have houv : ⟪(u - v) - (u - orthogonal_projection_fn K u), orthogonal_projection_fn K u - v⟫ = 0, { rw [inner_sub_left, huo, huv, sub_zero] }, rwa sub_sub_sub_cancel_left at houv end variables (K) lemma orthogonal_projection_fn_norm_sq (v : E) : ∥v∥ * ∥v∥ = ∥v - (orthogonal_projection_fn K v)∥ * ∥v - (orthogonal_projection_fn K v)∥ + ∥orthogonal_projection_fn K v∥ * ∥orthogonal_projection_fn K v∥ := begin set p := orthogonal_projection_fn K v, have h' : ⟪v - p, p⟫ = 0, { exact orthogonal_projection_fn_inner_eq_zero _ _ (orthogonal_projection_fn_mem v) }, convert norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (v - p) p h' using 2; simp, end /-- The orthogonal projection onto a complete subspace. -/ def orthogonal_projection : E →L[𝕜] K := linear_map.mk_continuous { to_fun := λ v, ⟨orthogonal_projection_fn K v, orthogonal_projection_fn_mem v⟩, map_add' := λ x y, begin have hm : orthogonal_projection_fn K x + orthogonal_projection_fn K y ∈ K := submodule.add_mem K (orthogonal_projection_fn_mem x) (orthogonal_projection_fn_mem y), have ho : ∀ w ∈ K, ⟪x + y - (orthogonal_projection_fn K x + orthogonal_projection_fn K y), w⟫ = 0, { intros w hw, rw [add_sub_add_comm, inner_add_left, orthogonal_projection_fn_inner_eq_zero _ w hw, orthogonal_projection_fn_inner_eq_zero _ w hw, add_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end, map_smul' := λ c x, begin have hm : c • orthogonal_projection_fn K x ∈ K := submodule.smul_mem K _ (orthogonal_projection_fn_mem x), have ho : ∀ w ∈ K, ⟪c • x - c • orthogonal_projection_fn K x, w⟫ = 0, { intros w hw, rw [←smul_sub, inner_smul_left, orthogonal_projection_fn_inner_eq_zero _ w hw, mul_zero] }, ext, simp [eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hm ho] end } 1 (λ x, begin simp only [one_mul, linear_map.coe_mk], refine le_of_pow_le_pow 2 (norm_nonneg _) (by norm_num) _, change ∥orthogonal_projection_fn K x∥ ^ 2 ≤ ∥x∥ ^ 2, nlinarith [orthogonal_projection_fn_norm_sq K x] end) variables {K} @[simp] lemma orthogonal_projection_fn_eq (v : E) : orthogonal_projection_fn K v = (orthogonal_projection K v : E) := rfl /-- The characterization of the orthogonal projection. -/ @[simp] lemma orthogonal_projection_inner_eq_zero (v : E) : ∀ w ∈ K, ⟪v - orthogonal_projection K v, w⟫ = 0 := orthogonal_projection_fn_inner_eq_zero v /-- The difference of `v` from its orthogonal projection onto `K` is in `Kᗮ`. -/ @[simp] lemma sub_orthogonal_projection_mem_orthogonal (v : E) : v - orthogonal_projection K v ∈ Kᗮ := begin intros w hw, rw inner_eq_zero_sym, exact orthogonal_projection_inner_eq_zero _ _ hw end /-- The orthogonal projection is the unique point in `K` with the orthogonality property. -/ lemma eq_orthogonal_projection_of_mem_of_inner_eq_zero {u v : E} (hvm : v ∈ K) (hvo : ∀ w ∈ K, ⟪u - v, w⟫ = 0) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hvm hvo /-- The orthogonal projections onto equal subspaces are coerced back to the same point in `E`. -/ lemma eq_orthogonal_projection_of_eq_submodule {K' : submodule 𝕜 E} [complete_space K'] (h : K = K') (u : E) : (orthogonal_projection K u : E) = (orthogonal_projection K' u : E) := begin change orthogonal_projection_fn K u = orthogonal_projection_fn K' u, congr, exact h end /-- The orthogonal projection sends elements of `K` to themselves. -/ @[simp] lemma orthogonal_projection_mem_subspace_eq_self (v : K) : orthogonal_projection K v = v := by { ext, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero; simp } /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {v : E} : (orthogonal_projection K v : E) = v ↔ v ∈ K := begin refine ⟨λ h, _, λ h, eq_orthogonal_projection_of_mem_of_inner_eq_zero h _⟩, { rw ← h, simp }, { simp } end lemma linear_isometry.map_orthogonal_projection {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E →ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p] (x : E) : f (orthogonal_projection p x) = orthogonal_projection (p.map f.to_linear_map) (f x) := begin refine (eq_orthogonal_projection_of_mem_of_inner_eq_zero (submodule.apply_coe_mem_map _ _) $ λ y hy, _).symm, rcases hy with ⟨x', hx', rfl : f x' = y⟩, rw [f.coe_to_linear_map, ← f.map_sub, f.inner_map_map, orthogonal_projection_inner_eq_zero x x' hx'] end /-- Orthogonal projection onto the `submodule.map` of a subspace. -/ lemma orthogonal_projection_map_apply {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (p : submodule 𝕜 E) [complete_space p] (x : E') : (orthogonal_projection (p.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x : E') = f (orthogonal_projection p (f.symm x)) := by simpa only [f.coe_to_linear_isometry, f.apply_symm_apply] using (f.to_linear_isometry.map_orthogonal_projection p (f.symm x)).symm /-- The orthogonal projection onto the trivial submodule is the zero map. -/ @[simp] lemma orthogonal_projection_bot : orthogonal_projection (⊥ : submodule 𝕜 E) = 0 := by ext variables (K) /-- The orthogonal projection has norm `≤ 1`. -/ lemma orthogonal_projection_norm_le : ∥orthogonal_projection K∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (by norm_num) _ variables (𝕜) lemma smul_orthogonal_projection_singleton {v : E} (w : E) : (∥v∥ ^ 2 : 𝕜) • (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := begin suffices : ↑(orthogonal_projection (𝕜 ∙ v) ((∥v∥ ^ 2 : 𝕜) • w)) = ⟪v, w⟫ • v, { simpa using this }, apply eq_orthogonal_projection_of_mem_of_inner_eq_zero, { rw submodule.mem_span_singleton, use ⟪v, w⟫ }, { intros x hx, obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.mp hx, have hv : ↑∥v∥ ^ 2 = ⟪v, v⟫ := by { norm_cast, simp [norm_sq_eq_inner] }, simp [inner_sub_left, inner_smul_left, inner_smul_right, ring_equiv.map_div, mul_comm, hv, inner_product_space.conj_sym, hv] } end /-- Formula for orthogonal projection onto a single vector. -/ lemma orthogonal_projection_singleton {v : E} (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = (⟪v, w⟫ / ∥v∥ ^ 2) • v := begin by_cases hv : v = 0, { rw [hv, eq_orthogonal_projection_of_eq_submodule (submodule.span_zero_singleton 𝕜)], { simp }, { apply_instance } }, have hv' : ∥v∥ ≠ 0 := ne_of_gt (norm_pos_iff.mpr hv), have key : ((∥v∥ ^ 2 : 𝕜)⁻¹ * ∥v∥ ^ 2) • ↑(orthogonal_projection (𝕜 ∙ v) w) = ((∥v∥ ^ 2 : 𝕜)⁻¹ * ⟪v, w⟫) • v, { simp [mul_smul, smul_orthogonal_projection_singleton 𝕜 w] }, convert key; field_simp [hv'] end /-- Formula for orthogonal projection onto a single unit vector. -/ lemma orthogonal_projection_unit_singleton {v : E} (hv : ∥v∥ = 1) (w : E) : (orthogonal_projection (𝕜 ∙ v) w : E) = ⟪v, w⟫ • v := by { rw ← smul_orthogonal_projection_singleton 𝕜 w, simp [hv] } end orthogonal_projection section reflection variables {𝕜} (K) [complete_space K] /-- Auxiliary definition for `reflection`: the reflection as a linear equivalence. -/ def reflection_linear_equiv : E ≃ₗ[𝕜] E := linear_equiv.of_involutive (bit0 (K.subtype.comp (orthogonal_projection K).to_linear_map) - linear_map.id) (λ x, by simp [bit0]) /-- Reflection in a complete subspace of an inner product space. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in a subspace, is a more general sense of the word that includes both those common cases. -/ def reflection : E ≃ₗᵢ[𝕜] E := { norm_map' := begin intros x, let w : K := orthogonal_projection K x, let v := x - w, have : ⟪v, w⟫ = 0 := orthogonal_projection_inner_eq_zero x w w.2, convert norm_sub_eq_norm_add this using 2, { rw [linear_equiv.coe_mk, reflection_linear_equiv, linear_equiv.to_fun_eq_coe, linear_equiv.coe_of_involutive, linear_map.sub_apply, linear_map.id_apply, bit0, linear_map.add_apply, linear_map.comp_apply, submodule.subtype_apply, continuous_linear_map.to_linear_map_eq_coe, continuous_linear_map.coe_coe], dsimp [w, v], abel, }, { simp only [add_sub_cancel'_right, eq_self_iff_true], } end, ..reflection_linear_equiv K } variables {K} /-- The result of reflecting. -/ lemma reflection_apply (p : E) : reflection K p = bit0 ↑(orthogonal_projection K p) - p := rfl /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm : (reflection K).symm = reflection K := rfl /-- Reflection is its own inverse. -/ @[simp] lemma reflection_inv : (reflection K)⁻¹ = reflection K := rfl variables (K) /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (p : E) : reflection K (reflection K p) = p := (reflection K).left_inv p /-- Reflection is involutive. -/ lemma reflection_involutive : function.involutive (reflection K) := reflection_reflection K /-- Reflection is involutive. -/ @[simp] lemma reflection_trans_reflection : (reflection K).trans (reflection K) = linear_isometry_equiv.refl 𝕜 E := linear_isometry_equiv.ext $ reflection_involutive K /-- Reflection is involutive. -/ @[simp] lemma reflection_mul_reflection : reflection K * reflection K = 1 := reflection_trans_reflection _ variables {K} /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff (x : E) : reflection K x = x ↔ x ∈ K := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply, sub_eq_iff_eq_add', ← two_smul 𝕜, ← two_smul' 𝕜], refine (smul_right_injective E _).eq_iff, exact two_ne_zero end lemma reflection_mem_subspace_eq_self {x : E} (hx : x ∈ K) : reflection K x = x := (reflection_eq_self_iff x).mpr hx /-- Reflection in the `submodule.map` of a subspace. -/ lemma reflection_map_apply {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [complete_space K] (x : E') : reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) x = f (reflection K (f.symm x)) := by simp [bit0, reflection_apply, orthogonal_projection_map_apply f K x] /-- Reflection in the `submodule.map` of a subspace. -/ lemma reflection_map {E E' : Type*} [inner_product_space 𝕜 E] [inner_product_space 𝕜 E'] (f : E ≃ₗᵢ[𝕜] E') (K : submodule 𝕜 E) [complete_space K] : reflection (K.map (f.to_linear_equiv : E →ₗ[𝕜] E')) = f.symm.trans ((reflection K).trans f) := linear_isometry_equiv.ext $ reflection_map_apply f K /-- Reflection through the trivial subspace {0} is just negation. -/ @[simp] lemma reflection_bot : reflection (⊥ : submodule 𝕜 E) = linear_isometry_equiv.neg 𝕜 := by ext; simp [reflection_apply] end reflection section orthogonal /-- If `K₁` is complete and contained in `K₂`, `K₁` and `K₁ᗮ ⊓ K₂` span `K₂`. -/ lemma submodule.sup_orthogonal_inf_of_complete_space {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) [complete_space K₁] : K₁ ⊔ (K₁ᗮ ⊓ K₂) = K₂ := begin ext x, rw submodule.mem_sup, let v : K₁ := orthogonal_projection K₁ x, have hvm : x - v ∈ K₁ᗮ := sub_orthogonal_projection_mem_orthogonal x, split, { rintro ⟨y, hy, z, hz, rfl⟩, exact K₂.add_mem (h hy) hz.2 }, { exact λ hx, ⟨v, v.prop, x - v, ⟨hvm, K₂.sub_mem hx (h v.prop)⟩, add_sub_cancel'_right _ _⟩ } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` span the whole space. -/ lemma submodule.sup_orthogonal_of_complete_space [complete_space K] : K ⊔ Kᗮ = ⊤ := begin convert submodule.sup_orthogonal_inf_of_complete_space (le_top : K ≤ ⊤), simp end variables (K) /-- If `K` is complete, any `v` in `E` can be expressed as a sum of elements of `K` and `Kᗮ`. -/ lemma submodule.exists_sum_mem_mem_orthogonal [complete_space K] (v : E) : ∃ (y ∈ K) (z ∈ Kᗮ), v = y + z := begin have h_mem : v ∈ K ⊔ Kᗮ := by simp [submodule.sup_orthogonal_of_complete_space], obtain ⟨y, hy, z, hz, hyz⟩ := submodule.mem_sup.mp h_mem, exact ⟨y, hy, z, hz, hyz.symm⟩ end /-- If `K` is complete, then the orthogonal complement of its orthogonal complement is itself. -/ @[simp] lemma submodule.orthogonal_orthogonal [complete_space K] : Kᗮᗮ = K := begin ext v, split, { obtain ⟨y, hy, z, hz, rfl⟩ := K.exists_sum_mem_mem_orthogonal v, intros hv, have hz' : z = 0, { have hyz : ⟪z, y⟫ = 0 := by simp [hz y hy, inner_eq_zero_sym], simpa [inner_add_right, hyz] using hv z hz }, simp [hy, hz'] }, { intros hv w hw, rw inner_eq_zero_sym, exact hw v hv } end lemma submodule.orthogonal_orthogonal_eq_closure [complete_space E] : Kᗮᗮ = K.topological_closure := begin refine le_antisymm _ _, { convert submodule.orthogonal_orthogonal_monotone K.submodule_topological_closure, haveI : complete_space K.topological_closure := K.is_closed_topological_closure.complete_space_coe, rw K.topological_closure.orthogonal_orthogonal }, { exact K.topological_closure_minimal K.le_orthogonal_orthogonal Kᗮ.is_closed_orthogonal } end variables {K} /-- If `K` is complete, `K` and `Kᗮ` are complements of each other. -/ lemma submodule.is_compl_orthogonal_of_complete_space [complete_space K] : is_compl K Kᗮ := ⟨K.orthogonal_disjoint, le_of_eq submodule.sup_orthogonal_of_complete_space.symm⟩ @[simp] lemma submodule.orthogonal_eq_bot_iff [complete_space (K : set E)] : Kᗮ = ⊥ ↔ K = ⊤ := begin refine ⟨_, λ h, by rw [h, submodule.top_orthogonal_eq_bot] ⟩, intro h, have : K ⊔ Kᗮ = ⊤ := submodule.sup_orthogonal_of_complete_space, rwa [h, sup_comm, bot_sup_eq] at this, end /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal [complete_space K] {u v : E} (hv : v ∈ K) (hvo : u - v ∈ Kᗮ) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_fn_of_mem_of_inner_eq_zero hv (λ w, inner_eq_zero_sym.mp ∘ (hvo w)) /-- A point in `K` with the orthogonality property (here characterized in terms of `Kᗮ`) must be the orthogonal projection. -/ lemma eq_orthogonal_projection_of_mem_orthogonal' [complete_space K] {u v z : E} (hv : v ∈ K) (hz : z ∈ Kᗮ) (hu : u = v + z) : (orthogonal_projection K u : E) = v := eq_orthogonal_projection_of_mem_orthogonal hv (by simpa [hu]) /-- The orthogonal projection onto `K` of an element of `Kᗮ` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero [complete_space K] {v : E} (hv : v ∈ Kᗮ) : orthogonal_projection K v = 0 := by { ext, convert eq_orthogonal_projection_of_mem_orthogonal _ _; simp [hv] } /-- The reflection in `K` of an element of `Kᗮ` is its negation. -/ lemma reflection_mem_subspace_orthogonal_complement_eq_neg [complete_space K] {v : E} (hv : v ∈ Kᗮ) : reflection K v = - v := by simp [reflection_apply, orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero hv] /-- The orthogonal projection onto `Kᗮ` of an element of `K` is zero. -/ lemma orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero [complete_space E] {v : E} (hv : v ∈ K) : orthogonal_projection Kᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero (K.le_orthogonal_orthogonal hv) /-- The orthogonal complement satisfies `Kᗮᗮᗮ = Kᗮ`. -/ lemma submodule.triorthogonal_eq_orthogonal [complete_space E] : Kᗮᗮᗮ = Kᗮ := begin rw Kᗮ.orthogonal_orthogonal_eq_closure, exact K.is_closed_orthogonal.submodule_topological_closure_eq, end /-- The closure of `K` is the full space iff `Kᗮ` is trivial. -/ lemma submodule.topological_closure_eq_top_iff [complete_space E] : K.topological_closure = ⊤ ↔ Kᗮ = ⊥ := begin rw ←submodule.orthogonal_orthogonal_eq_closure, split; intro h, { rw [←submodule.triorthogonal_eq_orthogonal, h, submodule.top_orthogonal_eq_bot] }, { rw [h, submodule.bot_orthogonal_eq_top] } end /-- The reflection in `Kᗮ` of an element of `K` is its negation. -/ lemma reflection_mem_subspace_orthogonal_precomplement_eq_neg [complete_space E] {v : E} (hv : v ∈ K) : reflection Kᗮ v = -v := reflection_mem_subspace_orthogonal_complement_eq_neg (K.le_orthogonal_orthogonal hv) /-- The orthogonal projection onto `(𝕜 ∙ v)ᗮ` of `v` is zero. -/ lemma orthogonal_projection_orthogonal_complement_singleton_eq_zero [complete_space E] (v : E) : orthogonal_projection (𝕜 ∙ v)ᗮ v = 0 := orthogonal_projection_mem_subspace_orthogonal_precomplement_eq_zero (submodule.mem_span_singleton_self v) /-- The reflection in `(𝕜 ∙ v)ᗮ` of `v` is `-v`. -/ lemma reflection_orthogonal_complement_singleton_eq_neg [complete_space E] (v : E) : reflection (𝕜 ∙ v)ᗮ v = -v := reflection_mem_subspace_orthogonal_precomplement_eq_neg (submodule.mem_span_singleton_self v) lemma reflection_sub [complete_space F] {v w : F} (h : ∥v∥ = ∥w∥) : reflection (ℝ ∙ (v - w))ᗮ v = w := begin set R : F ≃ₗᵢ[ℝ] F := reflection (ℝ ∙ (v - w))ᗮ, suffices : R v + R v = w + w, { apply smul_right_injective F (by norm_num : (2:ℝ) ≠ 0), simpa [two_smul] using this }, have h₁ : R (v - w) = -(v - w) := reflection_orthogonal_complement_singleton_eq_neg (v - w), have h₂ : R (v + w) = v + w, { apply reflection_mem_subspace_eq_self, apply mem_orthogonal_singleton_of_inner_left, rw real_inner_add_sub_eq_zero_iff, exact h }, convert congr_arg2 (+) h₂ h₁ using 1, { simp }, { abel } end variables (K) /-- In a complete space `E`, a vector splits as the sum of its orthogonal projections onto a complete submodule `K` and onto the orthogonal complement of `K`.-/ lemma eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] (w : E) : w = (orthogonal_projection K w : E) + (orthogonal_projection Kᗮ w : E) := begin obtain ⟨y, hy, z, hz, hwyz⟩ := K.exists_sum_mem_mem_orthogonal w, convert hwyz, { exact eq_orthogonal_projection_of_mem_orthogonal' hy hz hwyz }, { rw add_comm at hwyz, refine eq_orthogonal_projection_of_mem_orthogonal' hz _ hwyz, simp [hy] } end /-- The Pythagorean theorem, for an orthogonal projection.-/ lemma norm_sq_eq_add_norm_sq_projection (x : E) (S : submodule 𝕜 E) [complete_space E] [complete_space S] : ∥x∥^2 = ∥orthogonal_projection S x∥^2 + ∥orthogonal_projection Sᗮ x∥^2 := begin let p1 := orthogonal_projection S, let p2 := orthogonal_projection Sᗮ, have x_decomp : x = p1 x + p2 x := eq_sum_orthogonal_projection_self_orthogonal_complement S x, have x_orth : ⟪ p1 x, p2 x ⟫ = 0 := submodule.inner_right_of_mem_orthogonal (set_like.coe_mem (p1 x)) (set_like.coe_mem (p2 x)), nth_rewrite 0 [x_decomp], simp only [sq, norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero ((p1 x) : E) (p2 x) x_orth, add_left_inj, mul_eq_mul_left_iff, norm_eq_zero, true_or, eq_self_iff_true, submodule.coe_norm, submodule.coe_eq_zero] end /-- In a complete space `E`, the projection maps onto a complete subspace `K` and its orthogonal complement sum to the identity. -/ lemma id_eq_sum_orthogonal_projection_self_orthogonal_complement [complete_space E] [complete_space K] : continuous_linear_map.id 𝕜 E = K.subtypeL.comp (orthogonal_projection K) + Kᗮ.subtypeL.comp (orthogonal_projection Kᗮ) := by { ext w, exact eq_sum_orthogonal_projection_self_orthogonal_complement K w } /-- The orthogonal projection is self-adjoint. -/ lemma inner_orthogonal_projection_left_eq_right [complete_space E] [complete_space K] (u v : E) : ⟪↑(orthogonal_projection K u), v⟫ = ⟪u, orthogonal_projection K v⟫ := begin nth_rewrite 0 eq_sum_orthogonal_projection_self_orthogonal_complement K v, nth_rewrite 1 eq_sum_orthogonal_projection_self_orthogonal_complement K u, rw [inner_add_left, inner_add_right, submodule.inner_right_of_mem_orthogonal (submodule.coe_mem (orthogonal_projection K u)) (submodule.coe_mem (orthogonal_projection Kᗮ v)), submodule.inner_left_of_mem_orthogonal (submodule.coe_mem (orthogonal_projection K v)) (submodule.coe_mem (orthogonal_projection Kᗮ u))], end open finite_dimensional /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.finrank_add_inf_finrank_orthogonal {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) : finrank 𝕜 K₁ + finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = finrank 𝕜 K₂ := begin haveI := submodule.finite_dimensional_of_le h, haveI := proper_is_R_or_C 𝕜 K₁, have hd := submodule.dim_sup_add_dim_inf_eq K₁ (K₁ᗮ ⊓ K₂), rw [←inf_assoc, (submodule.orthogonal_disjoint K₁).eq_bot, bot_inf_eq, finrank_bot, submodule.sup_orthogonal_inf_of_complete_space h] at hd, rw add_zero at hd, exact hd.symm end /-- Given a finite-dimensional subspace `K₂`, and a subspace `K₁` containined in it, the dimensions of `K₁` and the intersection of its orthogonal subspace with `K₂` add to that of `K₂`. -/ lemma submodule.finrank_add_inf_finrank_orthogonal' {K₁ K₂ : submodule 𝕜 E} [finite_dimensional 𝕜 K₂] (h : K₁ ≤ K₂) {n : ℕ} (h_dim : finrank 𝕜 K₁ + n = finrank 𝕜 K₂) : finrank 𝕜 (K₁ᗮ ⊓ K₂ : submodule 𝕜 E) = n := by { rw ← add_right_inj (finrank 𝕜 K₁), simp [submodule.finrank_add_inf_finrank_orthogonal h, h_dim] } /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.finrank_add_finrank_orthogonal [finite_dimensional 𝕜 E] (K : submodule 𝕜 E) : finrank 𝕜 K + finrank 𝕜 Kᗮ = finrank 𝕜 E := begin convert submodule.finrank_add_inf_finrank_orthogonal (le_top : K ≤ ⊤) using 1, { rw inf_top_eq }, { simp } end /-- Given a finite-dimensional space `E` and subspace `K`, the dimensions of `K` and `Kᗮ` add to that of `E`. -/ lemma submodule.finrank_add_finrank_orthogonal' [finite_dimensional 𝕜 E] {K : submodule 𝕜 E} {n : ℕ} (h_dim : finrank 𝕜 K + n = finrank 𝕜 E) : finrank 𝕜 Kᗮ = n := by { rw ← add_right_inj (finrank 𝕜 K), simp [submodule.finrank_add_finrank_orthogonal, h_dim] } local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ /-- In a finite-dimensional inner product space, the dimension of the orthogonal complement of the span of a nonzero vector is one less than the dimension of the space. -/ lemma finrank_orthogonal_span_singleton {n : ℕ} [_i : fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : finrank 𝕜 (𝕜 ∙ v)ᗮ = n := submodule.finrank_add_finrank_orthogonal' $ by simp [finrank_span_singleton hv, _i.elim, add_comm] /-- An element `φ` of the orthogonal group of `F` can be factored as a product of reflections, and specifically at most as many reflections as the dimension of the complement of the fixed subspace of `φ`. -/ lemma linear_isometry_equiv.reflections_generate_dim_aux [finite_dimensional ℝ F] {n : ℕ} (φ : F ≃ₗᵢ[ℝ] F) (hn : finrank ℝ (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).kerᗮ ≤ n) : ∃ l : list F, l.length ≤ n ∧ φ = (l.map (λ v, reflection (ℝ ∙ v)ᗮ)).prod := begin -- We prove this by strong induction on `n`, the dimension of the orthogonal complement of the -- fixed subspace of the endomorphism `φ` induction n with n IH generalizing φ, { -- Base case: `n = 0`, the fixed subspace is the whole space, so `φ = id` refine ⟨[], rfl.le, show φ = 1, from _⟩, have : (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).ker = ⊤, { rwa [nat.le_zero_iff, finrank_eq_zero, submodule.orthogonal_eq_bot_iff] at hn }, symmetry, ext x, have := linear_map.congr_fun (linear_map.ker_eq_top.mp this) x, rwa [continuous_linear_map.coe_sub, linear_map.zero_apply, linear_map.sub_apply, sub_eq_zero] at this }, { -- Inductive step. Let `W` be the fixed subspace of `φ`. We suppose its complement to have -- dimension at most n + 1. let W := (continuous_linear_map.id ℝ F - φ.to_continuous_linear_equiv).ker, have hW : ∀ w ∈ W, φ w = w := λ w hw, (sub_eq_zero.mp hw).symm, by_cases hn' : finrank ℝ Wᗮ ≤ n, { obtain ⟨V, hV₁, hV₂⟩ := IH φ hn', exact ⟨V, hV₁.trans n.le_succ, hV₂⟩ }, -- Take a nonzero element `v` of the orthogonal complement of `W`. haveI : nontrivial Wᗮ := nontrivial_of_finrank_pos (by linarith [zero_le n] : 0 < finrank ℝ Wᗮ), obtain ⟨v, hv⟩ := exists_ne (0 : Wᗮ), have hφv : φ v ∈ Wᗮ, { intros w hw, rw [← hW w hw, linear_isometry_equiv.inner_map_map], exact v.prop w hw }, have hv' : (v:F) ∉ W, { intros h, exact hv ((submodule.mem_left_iff_eq_zero_of_disjoint W.orthogonal_disjoint).mp h) }, -- Let `ρ` be the reflection in `v - φ v`; this is designed to swap `v` and `φ v` let x : F := v - φ v, let ρ := reflection (ℝ ∙ x)ᗮ, -- Notation: Let `V` be the fixed subspace of `φ.trans ρ` let V := (continuous_linear_map.id ℝ F - (φ.trans ρ).to_continuous_linear_equiv).ker, have hV : ∀ w, ρ (φ w) = w → w ∈ V, { intros w hw, change w - ρ (φ w) = 0, rw [sub_eq_zero, hw] }, -- Everything fixed by `φ` is fixed by `φ.trans ρ` have H₂V : W ≤ V, { intros w hw, apply hV, rw hW w hw, refine reflection_mem_subspace_eq_self _, apply mem_orthogonal_singleton_of_inner_left, exact submodule.sub_mem _ v.prop hφv _ hw }, -- `v` is also fixed by `φ.trans ρ` have H₁V : (v : F) ∈ V, { apply hV, have : ρ v = φ v := reflection_sub (φ.norm_map v).symm, rw ←this, exact reflection_reflection _ _, }, -- By dimension-counting, the complement of the fixed subspace of `φ.trans ρ` has dimension at -- most `n` have : finrank ℝ Vᗮ ≤ n, { change finrank ℝ Wᗮ ≤ n + 1 at hn, have : finrank ℝ W + 1 ≤ finrank ℝ V := submodule.finrank_lt_finrank_of_lt (set_like.lt_iff_le_and_exists.2 ⟨H₂V, v, H₁V, hv'⟩), have : finrank ℝ V + finrank ℝ Vᗮ = finrank ℝ F := V.finrank_add_finrank_orthogonal, have : finrank ℝ W + finrank ℝ Wᗮ = finrank ℝ F := W.finrank_add_finrank_orthogonal, linarith }, -- So apply the inductive hypothesis to `φ.trans ρ` obtain ⟨l, hl, hφl⟩ := IH (ρ * φ) this, -- Prepend `ρ` to the factorization into reflections obtained for `φ.trans ρ`; this gives a -- factorization into reflections for `φ`. refine ⟨x :: l, nat.succ_le_succ hl, _⟩, rw [list.map_cons, list.prod_cons], have := congr_arg ((*) ρ) hφl, rwa [←mul_assoc, reflection_mul_reflection, one_mul] at this, } end /-- The orthogonal group of `F` is generated by reflections; specifically each element `φ` of the orthogonal group is a product of at most as many reflections as the dimension of `F`. Special case of the **Cartan–Dieudonné theorem**. -/ lemma linear_isometry_equiv.reflections_generate_dim [finite_dimensional ℝ F] (φ : F ≃ₗᵢ[ℝ] F) : ∃ l : list F, l.length ≤ finrank ℝ F ∧ φ = (l.map (λ v, reflection (ℝ ∙ v)ᗮ)).prod := let ⟨l, hl₁, hl₂⟩ := φ.reflections_generate_dim_aux le_rfl in ⟨l, hl₁.trans (submodule.finrank_le _), hl₂⟩ /-- The orthogonal group of `F` is generated by reflections. -/ lemma linear_isometry_equiv.reflections_generate [finite_dimensional ℝ F] : subgroup.closure (set.range (λ v : F, reflection (ℝ ∙ v)ᗮ)) = ⊤ := begin rw subgroup.eq_top_iff', intros φ, rcases φ.reflections_generate_dim with ⟨l, _, rfl⟩, apply (subgroup.closure _).list_prod_mem, intros x hx, rcases list.mem_map.mp hx with ⟨a, _, hax⟩, exact subgroup.subset_closure ⟨a, hax⟩, end end orthogonal section orthogonal_family variables {ι : Type*} /-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is, they provide an internal direct sum decomposition of `E`) if and only if their span has trivial orthogonal complement. -/ lemma orthogonal_family.is_internal_iff_of_is_complete [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) (hc : is_complete (↑(supr V) : set E)) : direct_sum.is_internal V ↔ (supr V)ᗮ = ⊥ := begin haveI : complete_space ↥(supr V) := hc.complete_space_coe, simp only [direct_sum.is_internal_submodule_iff_independent_and_supr_eq_top, hV.independent, true_and, submodule.orthogonal_eq_bot_iff] end /-- An orthogonal family of subspaces of `E` satisfies `direct_sum.is_internal` (that is, they provide an internal direct sum decomposition of `E`) if and only if their span has trivial orthogonal complement. -/ lemma orthogonal_family.is_internal_iff [decidable_eq ι] [finite_dimensional 𝕜 E] {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) : direct_sum.is_internal V ↔ (supr V)ᗮ = ⊥ := begin haveI h := finite_dimensional.proper_is_R_or_C 𝕜 ↥(supr V), exact hV.is_internal_iff_of_is_complete (complete_space_coe_iff_is_complete.mp infer_instance) end end orthogonal_family section orthonormal_basis /-! ### Existence of orthonormal basis, etc. -/ variables {𝕜 E} {v : set E} open finite_dimensional submodule set /-- An orthonormal set in an `inner_product_space` is maximal, if and only if the orthogonal complement of its span is empty. -/ lemma maximal_orthonormal_iff_orthogonal_complement_eq_bot (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ (span 𝕜 v)ᗮ = ⊥ := begin rw submodule.eq_bot_iff, split, { contrapose!, -- ** direction 1: nonempty orthogonal complement implies nonmaximal rintros ⟨x, hx', hx⟩, -- take a nonzero vector and normalize it let e := (∥x∥⁻¹ : 𝕜) • x, have he : ∥e∥ = 1 := by simp [e, norm_smul_inv_norm hx], have he' : e ∈ (span 𝕜 v)ᗮ := smul_mem' _ _ hx', have he'' : e ∉ v, { intros hev, have : e = 0, { have : e ∈ (span 𝕜 v) ⊓ (span 𝕜 v)ᗮ := ⟨subset_span hev, he'⟩, simpa [(span 𝕜 v).inf_orthogonal_eq_bot] using this }, have : e ≠ 0 := hv.ne_zero ⟨e, hev⟩, contradiction }, -- put this together with `v` to provide a candidate orthonormal basis for the whole space refine ⟨insert e v, v.subset_insert e, ⟨_, _⟩, (v.ne_insert_of_not_mem he'').symm⟩, { -- show that the elements of `insert e v` have unit length rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { simp [ha, he] }, { exact hv.1 ⟨a, ha⟩ } }, { -- show that the elements of `insert e v` are orthogonal have h_end : ∀ a ∈ v, ⟪a, e⟫ = 0, { intros a ha, exact he' a (submodule.subset_span ha) }, rintros ⟨a, ha'⟩, cases eq_or_mem_of_mem_insert ha' with ha ha, { rintros ⟨b, hb'⟩ hab', have hb : b ∈ v, { refine mem_of_mem_insert_of_ne hb' _, intros hbe', apply hab', simp [ha, hbe'] }, rw inner_eq_zero_sym, simpa [ha] using h_end b hb }, rintros ⟨b, hb'⟩ hab', cases eq_or_mem_of_mem_insert hb' with hb hb, { simpa [hb] using h_end a ha }, have : (⟨a, ha⟩ : v) ≠ ⟨b, hb⟩, { intros hab'', apply hab', simpa using hab'' }, exact hv.2 this } }, { -- ** direction 2: empty orthogonal complement implies maximal simp only [subset.antisymm_iff], rintros h u (huv : v ⊆ u) hu, refine ⟨_, huv⟩, intros x hxu, refine ((mt (h x)) (hu.ne_zero ⟨x, hxu⟩)).imp_symm _, intros hxv y hy, have hxv' : (⟨x, hxu⟩ : u) ∉ (coe ⁻¹' v : set u) := by simp [huv, hxv], obtain ⟨l, hl, rfl⟩ : ∃ l ∈ finsupp.supported 𝕜 𝕜 (coe ⁻¹' v : set u), (finsupp.total ↥u E 𝕜 coe) l = y, { rw ← finsupp.mem_span_image_iff_total, simp [huv, inter_eq_self_of_subset_left, hy] }, exact hu.inner_finsupp_eq_zero hxv' hl } end section finite_dimensional variables [finite_dimensional 𝕜 E] /-- An orthonormal set in a finite-dimensional `inner_product_space` is maximal, if and only if it is a basis. -/ lemma maximal_orthonormal_iff_basis_of_finite_dimensional (hv : orthonormal 𝕜 (coe : v → E)) : (∀ u ⊇ v, orthonormal 𝕜 (coe : u → E) → u = v) ↔ ∃ b : basis v 𝕜 E, ⇑b = coe := begin haveI := proper_is_R_or_C 𝕜 (span 𝕜 v), rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hv, have hv_compl : is_complete (span 𝕜 v : set E) := (span 𝕜 v).complete_of_finite_dimensional, rw submodule.orthogonal_eq_bot_iff, have hv_coe : range (coe : v → E) = v := by simp, split, { refine λ h, ⟨basis.mk hv.linear_independent _, basis.coe_mk _ _⟩, convert h }, { rintros ⟨h, coe_h⟩, rw [← h.span_eq, coe_h, hv_coe] } end /-- In a finite-dimensional `inner_product_space`, any orthonormal subset can be extended to an orthonormal basis. -/ lemma exists_subset_is_orthonormal_basis (hv : orthonormal 𝕜 (coe : v → E)) : ∃ (u ⊇ v) (b : basis u 𝕜 E), orthonormal 𝕜 b ∧ ⇑b = coe := begin obtain ⟨u, hus, hu, hu_max⟩ := exists_maximal_orthonormal hv, obtain ⟨b, hb⟩ := (maximal_orthonormal_iff_basis_of_finite_dimensional hu).mp hu_max, exact ⟨u, hus, b, by rwa hb, hb⟩ end variables (𝕜 E) /-- Index for an arbitrary orthonormal basis on a finite-dimensional `inner_product_space`. -/ def orthonormal_basis_index : set E := classical.some (exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E)) /-- A finite-dimensional `inner_product_space` has an orthonormal basis. -/ def std_orthonormal_basis : basis (orthonormal_basis_index 𝕜 E) 𝕜 E := (exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E)).some_spec.some_spec.some lemma std_orthonormal_basis_orthonormal : orthonormal 𝕜 (std_orthonormal_basis 𝕜 E) := (exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E)).some_spec.some_spec.some_spec.1 @[simp] lemma coe_std_orthonormal_basis : ⇑(std_orthonormal_basis 𝕜 E) = coe := (exists_subset_is_orthonormal_basis (orthonormal_empty 𝕜 E)).some_spec.some_spec.some_spec.2 instance : fintype (orthonormal_basis_index 𝕜 E) := @is_noetherian.fintype_basis_index _ _ _ _ _ _ (is_noetherian.iff_fg.2 infer_instance) (std_orthonormal_basis 𝕜 E) variables {𝕜 E} /-- An `n`-dimensional `inner_product_space` has an orthonormal basis indexed by `fin n`. -/ def fin_std_orthonormal_basis {n : ℕ} (hn : finrank 𝕜 E = n) : basis (fin n) 𝕜 E := have h : fintype.card (orthonormal_basis_index 𝕜 E) = n, by rw [← finrank_eq_card_basis (std_orthonormal_basis 𝕜 E), hn], (std_orthonormal_basis 𝕜 E).reindex (fintype.equiv_fin_of_card_eq h) lemma fin_std_orthonormal_basis_orthonormal {n : ℕ} (hn : finrank 𝕜 E = n) : orthonormal 𝕜 (fin_std_orthonormal_basis hn) := suffices orthonormal 𝕜 (std_orthonormal_basis _ _ ∘ equiv.symm _), by { simp only [fin_std_orthonormal_basis, basis.coe_reindex], assumption }, -- simpa doesn't work? (std_orthonormal_basis_orthonormal 𝕜 E).comp _ (equiv.injective _) section subordinate_orthonormal_basis open direct_sum variables {n : ℕ} (hn : finrank 𝕜 E = n) {ι : Type*} [fintype ι] [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : is_internal V) /-- Exhibit a bijection between `fin n` and the index set of a certain basis of an `n`-dimensional inner product space `E`. This should not be accessed directly, but only via the subsequent API. -/ @[irreducible] def direct_sum.is_internal.sigma_orthonormal_basis_index_equiv : (Σ i, orthonormal_basis_index 𝕜 (V i)) ≃ fin n := let b := hV.collected_basis (λ i, std_orthonormal_basis 𝕜 (V i)) in fintype.equiv_fin_of_card_eq $ (finite_dimensional.finrank_eq_card_basis b).symm.trans hn /-- An `n`-dimensional `inner_product_space` equipped with a decomposition as an internal direct sum has an orthonormal basis indexed by `fin n` and subordinate to that direct sum. -/ @[irreducible] def direct_sum.is_internal.subordinate_orthonormal_basis : basis (fin n) 𝕜 E := (hV.collected_basis (λ i, std_orthonormal_basis 𝕜 (V i))).reindex (hV.sigma_orthonormal_basis_index_equiv hn) /-- An `n`-dimensional `inner_product_space` equipped with a decomposition as an internal direct sum has an orthonormal basis indexed by `fin n` and subordinate to that direct sum. This function provides the mapping by which it is subordinate. -/ def direct_sum.is_internal.subordinate_orthonormal_basis_index (a : fin n) : ι := ((hV.sigma_orthonormal_basis_index_equiv hn).symm a).1 /-- The basis constructed in `orthogonal_family.subordinate_orthonormal_basis` is orthonormal. -/ lemma direct_sum.is_internal.subordinate_orthonormal_basis_orthonormal (hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) : orthonormal 𝕜 (hV.subordinate_orthonormal_basis hn) := begin simp only [direct_sum.is_internal.subordinate_orthonormal_basis, basis.coe_reindex], have : orthonormal 𝕜 (hV.collected_basis (λ i, std_orthonormal_basis 𝕜 (V i))) := hV.collected_basis_orthonormal hV' (λ i, std_orthonormal_basis_orthonormal 𝕜 (V i)), exact this.comp _ (equiv.injective _), end /-- The basis constructed in `orthogonal_family.subordinate_orthonormal_basis` is subordinate to the `orthogonal_family` in question. -/ lemma direct_sum.is_internal.subordinate_orthonormal_basis_subordinate (a : fin n) : hV.subordinate_orthonormal_basis hn a ∈ V (hV.subordinate_orthonormal_basis_index hn a) := by simpa only [direct_sum.is_internal.subordinate_orthonormal_basis, basis.coe_reindex] using hV.collected_basis_mem (λ i, std_orthonormal_basis 𝕜 (V i)) ((hV.sigma_orthonormal_basis_index_equiv hn).symm a) attribute [irreducible] direct_sum.is_internal.subordinate_orthonormal_basis_index end subordinate_orthonormal_basis end finite_dimensional end orthonormal_basis
1647242be9251e6687447a802eae685922b5b57b
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/monad/equiv_mon.lean
f29bfa055703666b843931f7ebbda54b9a8c7e59
[ "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
4,249
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.monad.basic import category_theory.monoidal.End import category_theory.monoidal.Mon_ import category_theory.category.Cat /-! # The equivalence between `Monad C` and `Mon_ (C ⥤ C)`. A monad "is just" a monoid in the category of endofunctors. # Definitions/Theorems 1. `to_Mon` associates a monoid object in `C ⥤ C` to any monad on `C`. 2. `Monad_to_Mon` is the functorial version of `to_Mon`. 3. `of_Mon` associates a monad on `C` to any monoid object in `C ⥤ C`. 4. `Monad_Mon_equiv` is the equivalence between `Monad C` and `Mon_ (C ⥤ C)`. -/ namespace category_theory open category universes v u -- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u} [category.{v} C] namespace Monad local attribute [instance, reducible] endofunctor_monoidal_category /-- To every `Monad C` we associated a monoid object in `C ⥤ C`.-/ @[simps] def to_Mon : monad C → Mon_ (C ⥤ C) := λ M, { X := (M : C ⥤ C), one := M.η, mul := M.μ, one_mul' := by { ext, simp }, -- `obviously` provides this, but slowly mul_one' := by { ext, simp }, -- `obviously` provides this, but slowly mul_assoc' := by { ext, dsimp, simp [M.assoc] } } variable (C) /-- Passing from `Monad C` to `Mon_ (C ⥤ C)` is functorial. -/ @[simps] def Monad_to_Mon : monad C ⥤ Mon_ (C ⥤ C) := { obj := to_Mon, map := λ _ _ f, { hom := f.to_nat_trans }, map_id' := by { intros X, refl }, -- `obviously` provides this, but slowly map_comp' := by { intros X Y Z f g, refl, } } variable {C} /-- To every monoid object in `C ⥤ C` we associate a `Monad C`. -/ @[simps] def of_Mon : Mon_ (C ⥤ C) → monad C := λ M, { to_functor := M.X, η' := M.one, μ' := M.mul, left_unit' := λ X, by { rw [←M.one.id_hcomp_app, ←nat_trans.comp_app, M.mul_one], refl }, right_unit' := λ X, by { rw [←M.one.hcomp_id_app, ←nat_trans.comp_app, M.one_mul], refl }, assoc' := λ X, by { rw [←nat_trans.hcomp_id_app, ←nat_trans.comp_app], simp } } variable (C) /-- Passing from `Mon_ (C ⥤ C)` to `Monad C` is functorial. -/ @[simps] def Mon_to_Monad : Mon_ (C ⥤ C) ⥤ monad C := { obj := of_Mon, map := λ _ _ f, { app_η' := begin intro X, erw [←nat_trans.comp_app, f.one_hom], refl, end, app_μ' := begin intro X, erw [←nat_trans.comp_app, f.mul_hom], -- `finish` closes this goal simpa only [nat_trans.naturality, nat_trans.hcomp_app, assoc, nat_trans.comp_app, of_Mon_μ], end, ..f.hom } } namespace Monad_Mon_equiv variable {C} /-- Isomorphism of functors used in `Monad_Mon_equiv` -/ @[simps {rhs_md := semireducible}] def counit_iso : Mon_to_Monad C ⋙ Monad_to_Mon C ≅ 𝟭 _ := { hom := { app := λ _, { hom := 𝟙 _ } }, inv := { app := λ _, { hom := 𝟙 _ } }, hom_inv_id' := by { ext, simp }, -- `obviously` provides these, but slowly inv_hom_id' := by { ext, simp } } /-- Auxiliary definition for `Monad_Mon_equiv` -/ @[simps] def unit_iso_hom : 𝟭 _ ⟶ Monad_to_Mon C ⋙ Mon_to_Monad C := { app := λ _, { app := λ _, 𝟙 _ } } /-- Auxiliary definition for `Monad_Mon_equiv` -/ @[simps] def unit_iso_inv : Monad_to_Mon C ⋙ Mon_to_Monad C ⟶ 𝟭 _ := { app := λ _, { app := λ _, 𝟙 _ } } /-- Isomorphism of functors used in `Monad_Mon_equiv` -/ @[simps] def unit_iso : 𝟭 _ ≅ Monad_to_Mon C ⋙ Mon_to_Monad C := { hom := unit_iso_hom, inv := unit_iso_inv, hom_inv_id' := by { ext, simp }, -- `obviously` provides these, but slowly inv_hom_id' := by { ext, simp } } end Monad_Mon_equiv open Monad_Mon_equiv /-- Oh, monads are just monoids in the category of endofunctors (equivalence of categories). -/ @[simps] def Monad_Mon_equiv : (monad C) ≌ (Mon_ (C ⥤ C)) := { functor := Monad_to_Mon _, inverse := Mon_to_Monad _, unit_iso := unit_iso, counit_iso := counit_iso, functor_unit_iso_comp' := by { intros X, ext, dsimp, simp } } -- `obviously`, slowly -- Sanity check example (A : monad C) {X : C} : ((Monad_Mon_equiv C).unit_iso.app A).hom.app X = 𝟙 _ := rfl end Monad end category_theory
c0f190c103d66f88f1917496e3055afadfd3ebf4
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world5/level2.lean
a83411d8a11e335d7b4e4ae72017c0d7824201d8
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,373
lean
import mynat.add -- + on mynat import mynat.mul -- * on mynat /- Tactic : intro ## Summary: `intro p` will turn a goal `⊢ P → Q` into a hypothesis `p : P` and goal `⊢ Q`. If `P` and `Q` are sets `intro p` means "let $p$ be an arbitrary element of $P$". If `P` and `Q` are propositions then `intro p` says "assume $P$ is true". ## Details If your goal is a function or an implication `⊢ P → Q` then `intro` will always make progress. `intro p` turns `⊢ P → Q` into ``` p : P ⊢ Q ``` The opposite tactic to intro is `revert`; given the situation just above, `revert p` turns the goal back into `⊢ P → Q`. There are two points of view with `intro` -- the function point of view (Function World) and the proposition point of view (Proposition World). ## Example (functions) What does it mean to define a function? Given an arbitrary term of type `P` (or an element of the set `P` if you think set-theoretically) you need to come up with a term of type `Q`, so your first step is to choose `p`, an arbitary element of `P`. `intro p,` is Lean's way of saying "let $p\in P$ be arbitrary". The tactic `intro p` changes ``` ⊢ P → Q ``` into ``` p : P ⊢ Q ``` So `p` is an arbitrary element of `P` about which nothing is known, and our task is to come up with an element of `Q` (which can of course depend on `p`). ## Example (propositions) If your goal is an implication $P\implies Q$ then Lean writes this as `⊢ P → Q`, and `intro p,` can be thought of as meaning "let $p$ be a proof of $P$", or more informally "let's assume that $P$ is true". The goal changes to `⊢ Q` and the hypothesis `p : P` appears in the local context. -/ /- # Function world. ## Level 2: the `intro` tactic. Let's make a function. Let's define the function on the natural numbers which sends a natural number $n$ to $3n+2$. If you delete the `sorry` you will see that our goal is `mynat → mynat`. A mathematician might denote this set with some exotic name such as $\operatorname{Hom}(\mathbb{N},\mathbb{N})$, but computer scientists use notation `X → Y` to denote the set of functions from `X` to `Y` and this name definitely has its merits. In type theory, `X → Y` is a type (the type of all functions from $X$ to $Y$), and `f : X → Y` means that `f` is a term of this type, i.e., $f$ is a function from $X$ to $Y$. To define a function $X\to Y$ we need to choose an arbitrary element $x\in X$ and then, perhaps using $x$, make an element of $Y$. The Lean tactic for "let $x\in X$ be arbitrary" is `intro x`. ## Rule of thumb: If your goal is `P → Q` then `intro p` will make progress. To solve the goal below, you have to come up with a function from `mynat` to `mynat`. Start with `intro n,` (i.e. "let $n\in\mathbb{N}$ be arbitrary") and note that our local context now looks like this: ``` n : mynat ⊢ mynat ``` Our job now is to construct a natural number, which is allowed to depend on $n$. We can do this using `exact` and writing a formula for the function we want to define. For example we imported addition and multiplication at the top of this file, so `exact 3*n+2,` will close the goal, ultimately defining the function $f(n)=3n+2$. -/ /- Definition We define a function from mynat to mynat. -/ example : mynat → mynat := begin [less_leaky] intro n, exact 3*n+2, end -- TODO this is a function
1cebd642d483aa2c71684e875991e443d70c92c2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/PhaseExt.lean
6b532c80364cd2b62795fb781c4598fa8e6b2bd2
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
3,580
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.Compiler.LCNF.PassManager namespace Lean.Compiler.LCNF abbrev DeclExtState := PHashMap Name Decl private abbrev declLt (a b : Decl) := Name.quickLt a.name b.name private abbrev sortDecls (decls : Array Decl) : Array Decl := decls.qsort declLt private abbrev findAtSorted? (decls : Array Decl) (declName : Name) : Option Decl := let tmpDecl : Decl := default let tmpDecl := { tmpDecl with name := declName } decls.binSearch tmpDecl declLt abbrev DeclExt := PersistentEnvExtension Decl Decl DeclExtState def mkDeclExt (name : Name := by exact decl_name%) : IO DeclExt := do registerPersistentEnvExtension { name := name mkInitial := return {} addImportedFn := fun _ => return {} addEntryFn := fun decls decl => decls.insert decl.name decl exportEntriesFn := fun s => let decls := s.foldl (init := #[]) fun decls _ decl => decls.push decl sortDecls decls } builtin_initialize baseExt : PersistentEnvExtension Decl Decl DeclExtState ← mkDeclExt builtin_initialize monoExt : PersistentEnvExtension Decl Decl DeclExtState ← mkDeclExt def getDeclCore? (env : Environment) (ext : DeclExt) (declName : Name) : Option Decl := match env.getModuleIdxFor? declName with | some modIdx => findAtSorted? (ext.getModuleEntries env modIdx) declName | none => ext.getState env |>.find? declName def getBaseDecl? (declName : Name) : CoreM (Option Decl) := do return getDeclCore? (← getEnv) baseExt declName def getMonoDecl? (declName : Name) : CoreM (Option Decl) := do return getDeclCore? (← getEnv) monoExt declName def saveBaseDeclCore (env : Environment) (decl : Decl) : Environment := baseExt.addEntry (env.addExtraName decl.name) decl def saveMonoDeclCore (env : Environment) (decl : Decl) : Environment := monoExt.addEntry (env.addExtraName decl.name) decl def Decl.saveBase (decl : Decl) : CoreM Unit := modifyEnv (saveBaseDeclCore · decl) def Decl.saveMono (decl : Decl) : CoreM Unit := modifyEnv (saveMonoDeclCore · decl) def Decl.save (decl : Decl) : CompilerM Unit := do match (← getPhase) with | .base => decl.saveBase | .mono => decl.saveMono | _ => unreachable! def getDeclAt? (declName : Name) (phase : Phase) : CoreM (Option Decl) := match phase with | .base => getBaseDecl? declName | .mono => getMonoDecl? declName | _ => return none -- TODO def getDecl? (declName : Name) : CompilerM (Option Decl) := do getDeclAt? declName (← getPhase) def getExt (phase : Phase) : DeclExt := match phase with | .base => baseExt | .mono => monoExt | _ => unreachable! def forEachDecl (f : Decl → CoreM Unit) (phase := Phase.base) : CoreM Unit := do let ext := getExt phase let env ← getEnv for modIdx in [:env.allImportedModuleNames.size] do for decl in ext.getModuleEntries env modIdx do f decl ext.getState env |>.forM fun _ decl => f decl def forEachModuleDecl (moduleName : Name) (f : Decl → CoreM Unit) (phase := Phase.base) : CoreM Unit := do let ext := getExt phase let env ← getEnv let some modIdx := env.getModuleIdx? moduleName | throwError "module `{moduleName}` not found" for decl in ext.getModuleEntries env modIdx do f decl def forEachMainModuleDecl (f : Decl → CoreM Unit) (phase := Phase.base) : CoreM Unit := do (getExt phase).getState (← getEnv) |>.forM fun _ decl => f decl end Lean.Compiler.LCNF
a0c466b5a6c94aef0dcd0a198356ce6291d65658
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/computability/primrec.lean
405c30e3d677f12bdf0031ff08072453e36de484
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
50,093
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro The primitive recursive functions are the least collection of functions nat → nat which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) -/ import data.equiv.list open denumerable encodable namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (function.swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (function.swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, pow_succ] end primrec end nat /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim : nat.primrec (λ n, encodable.encode (decode n))) namespace primcodable open nat.primrec @[priority 0] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := (primcodable.prim α).of_eq $ λ n, show _ = encode (option.map e (option.map _ _)), by cases decode α n; simp theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1; simp, {refl}, cases decode β n.unpair.2; simp, {refl}, refl end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (function.swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, -nat.iterate_succ, nat.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ default α) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [function.swap], cases e : p.1 - p.2 with n, { simp [nat.sub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite nat_le snd fst theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode2 : primrec (decode2 α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := fintype.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := nat.iterate (G a) n (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_ge (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, {refl}, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_le_right n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := option_iget.comp₂ list_nth theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_concat]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, { simp [*, list.find_index], congr }] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_concat] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) (equiv.fin_equiv_subtype _) instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (@fin.val n) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y :: IH :: v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' n f) (hg : @vec n m g) : vec (λ v, f v :: g v) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y :: IH :: v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (nat.le_of_sub_eq_zero e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {refl}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
ebc89b9bc86b56c51d0420d2e2cb6c8773364925
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/environment.lean
c303b7f5d5eca685ebfa2e0c1e21ff061d34aa7c
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
6,266
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.declaration init.meta.exceptional init.data.option.basic import init.meta.rb_map meta constant environment : Type namespace environment /-- Information for a projection declaration - `cname` is the name of the constructor associated with the projection. - `nparams` is the number of constructor parameters - `idx` is the parameter being projected by this projection - `is_class` is tt iff this is a class projection. -/ structure projection_info := (cname : name) (nparams : nat) (idx : nat) (is_class : bool) /-- Create a standard environment using the given trust level -/ meta constant mk_std : nat → environment /-- Return the trust level of the given environment -/ meta constant trust_lvl : environment → nat /-- Add a new declaration to the environment -/ meta constant add : environment → declaration → exceptional environment /-- Retrieve a declaration from the environment -/ meta constant get : environment → name → exceptional declaration meta def contains (env : environment) (d : name) : bool := match env.get d with | exceptional.success _ := tt | exceptional.exception ._ _ := ff end /-- Register the given name as a namespace, making it available to the `open` command -/ meta constant add_namespace : environment → name → environment /-- Return tt iff the given name is a namespace -/ meta constant is_namespace : environment → name → bool /-- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta constant add_inductive : environment → name → list name → nat → expr → list (name × expr) → bool → exceptional environment /-- Return tt iff the given name is an inductive datatype -/ meta constant is_inductive : environment → name → bool /-- Return tt iff the given name is a constructor -/ meta constant is_constructor : environment → name → bool /-- Return tt iff the given name is a recursor -/ meta constant is_recursor : environment → name → bool /-- Return tt iff the given name is a recursive inductive datatype -/ meta constant is_recursive : environment → name → bool /-- Return the name of the inductive datatype of the given constructor. -/ meta constant inductive_type_of : environment → name → option name /-- Return the constructors of the inductive datatype with the given name -/ meta constant constructors_of : environment → name → list name /-- Return the recursor of the given inductive datatype -/ meta constant recursor_of : environment → name → option name /-- Return the number of parameters of the inductive datatype -/ meta constant inductive_num_params : environment → name → nat /-- Return the number of indices of the inductive datatype -/ meta constant inductive_num_indices : environment → name → nat /-- Return tt iff the inductive datatype recursor supports dependent elimination -/ meta constant inductive_dep_elim : environment → name → bool /-- Return tt iff the given name is a generalized inductive datatype -/ meta constant is_ginductive : environment → name → bool meta constant is_projection : environment → name → option projection_info /-- Fold over declarations in the environment -/ meta constant fold {α :Type} : environment → α → (declaration → α → α) → α /-- `relation_info env n` returns some value if n is marked as a relation in the given environment. the tuple contains: total number of arguments of the relation, lhs position and rhs position. -/ meta constant relation_info : environment → name → option (nat × nat × nat) /-- `refl_for env R` returns the name of the reflexivity theorem for the relation R -/ meta constant refl_for : environment → name → option name /-- `symm_for env R` returns the name of the symmetry theorem for the relation R -/ meta constant symm_for : environment → name → option name /-- `trans_for env R` returns the name of the transitivity theorem for the relation R -/ meta constant trans_for : environment → name → option name /-- `decl_olean env d` returns the name of the .olean file where d was defined. The result is none if d was not defined in an imported file. -/ meta constant decl_olean : environment → name → option string /-- `decl_pos env d` returns the source location of d if available. -/ meta constant decl_pos : environment → name → option pos /-- Return the fields of the structure with the given name, or `none` if it is not a structure -/ meta constant structure_fields : environment → name → option (list name) /-- `get_class_attribute_symbols env attr_name` return symbols occurring in instances of type classes tagged with the attribute `attr_name`. Example: [algebra] -/ meta constant get_class_attribute_symbols : environment → name → name_set meta constant fingerprint : environment → nat open expr meta constant unfold_untrusted_macros : environment → expr → expr meta constant unfold_all_macros : environment → expr → expr meta def is_constructor_app (env : environment) (e : expr) : bool := is_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e)) meta def is_refl_app (env : environment) (e : expr) : option (name × expr × expr) := match (refl_for env (const_name (get_app_fn e))) with | (some n) := if get_app_num_args e ≥ 2 then some (n, app_arg (app_fn e), app_arg e) else none | none := none end /-- Return true if 'n' has been declared in the current file -/ meta def in_current_file (env : environment) (n : name) : bool := (env.decl_olean n).is_none && env.contains n meta def is_definition (env : environment) (n : name) : bool := match env.get n with | exceptional.success (declaration.defn _ _ _ _ _ _) := tt | _ := ff end end environment meta instance : has_repr environment := ⟨λ e, "[environment]"⟩ meta instance : inhabited environment := ⟨environment.mk_std 0⟩
bbd5ae8906324a5df986bbda801bf954032ee291
e030b0259b777fedcdf73dd966f3f1556d392178
/library/init/algebra/ordered_group.lean
31cfbb7c09a9d076a67027a7c362b2e2710f1e20
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
23,105
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.order init.algebra.group /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe variable u class ordered_mul_cancel_comm_monoid (α : Type u) extends comm_monoid α, left_cancel_semigroup α, right_cancel_semigroup α, order_pair α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (le_of_mul_le_mul_left : ∀ a b c : α, a * b ≤ a * c → b ≤ c) (mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c * a < c * b) (lt_of_mul_lt_mul_left : ∀ a b c : α, a * b < a * c → b < c) @[class] def ordered_cancel_comm_monoid : Type u → Type (max 1 u) := ordered_mul_cancel_comm_monoid instance add_comm_monoid_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_comm_monoid α := @ordered_mul_cancel_comm_monoid.to_comm_monoid α s instance add_left_cancel_semigroup_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_left_cancel_semigroup α := @ordered_mul_cancel_comm_monoid.to_left_cancel_semigroup α s instance add_right_cancel_semigroup_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : add_right_cancel_semigroup α := @ordered_mul_cancel_comm_monoid.to_right_cancel_semigroup α s instance order_pair_of_ordered_cancel_comm_monoid (α : Type u) [s : ordered_cancel_comm_monoid α] : order_pair α := @ordered_mul_cancel_comm_monoid.to_order_pair α s section ordered_cancel_comm_monoid variable {α : Type u} variable [s : ordered_cancel_comm_monoid α] lemma add_le_add_left {a b : α} (h : a ≤ b) (c : α) : c + a ≤ c + b := @ordered_mul_cancel_comm_monoid.mul_le_mul_left α s a b h c lemma le_of_add_le_add_left {a b c : α} (h : a + b ≤ a + c) : b ≤ c := @ordered_mul_cancel_comm_monoid.le_of_mul_le_mul_left α s a b c h lemma add_lt_add_left {a b : α} (h : a < b) (c : α) : c + a < c + b := @ordered_mul_cancel_comm_monoid.mul_lt_mul_left α s a b h c lemma lt_of_add_lt_add_left {a b c : α} (h : a + b < a + c) : b < c := @ordered_mul_cancel_comm_monoid.lt_of_mul_lt_mul_left α s a b c h end ordered_cancel_comm_monoid section ordered_cancel_comm_monoid variable {α : Type u} variable [ordered_cancel_comm_monoid α] lemma add_le_add_right {a b : α} (h : a ≤ b) (c : α) : a + c ≤ b + c := add_comm c a ▸ add_comm c b ▸ add_le_add_left h c theorem add_lt_add_right {a b : α} (h : a < b) (c : α) : a + c < b + c := begin rw [add_comm a c, add_comm b c], exact (add_lt_add_left h c) end lemma add_le_add {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (add_le_add_right h₁ c) (add_le_add_left h₂ b) lemma le_add_of_nonneg_right {a b : α} (h : b ≥ 0) : a ≤ a + b := have a + b ≥ a + 0, from add_le_add_left h a, by rwa add_zero at this lemma le_add_of_nonneg_left {a b : α} (h : b ≥ 0) : a ≤ b + a := have 0 + a ≤ b + a, from add_le_add_right h a, by rwa zero_add at this lemma add_lt_add {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (add_lt_add_right h₁ c) (add_lt_add_left h₂ b) lemma add_lt_add_of_le_of_lt {a b c d : α} (h₁ : a ≤ b) (h₂ : c < d) : a + c < b + d := lt_of_le_of_lt (add_le_add_right h₁ c) (add_lt_add_left h₂ b) lemma add_lt_add_of_lt_of_le {a b c d : α} (h₁ : a < b) (h₂ : c ≤ d) : a + c < b + d := lt_of_lt_of_le (add_lt_add_right h₁ c) (add_le_add_left h₂ b) lemma lt_add_of_pos_right (a : α) {b : α} (h : b > 0) : a < a + b := have a + 0 < a + b, from add_lt_add_left h a, by rwa [add_zero] at this lemma lt_add_of_pos_left (a : α) {b : α} (h : b > 0) : a < b + a := have 0 + a < b + a, from add_lt_add_right h a, by rwa [zero_add] at this lemma le_of_add_le_add_right {a b c : α} (h : a + b ≤ c + b) : a ≤ c := le_of_add_le_add_left (show b + a ≤ b + c, begin rw [add_comm b a, add_comm b c], assumption end) lemma lt_of_add_lt_add_right {a b c : α} (h : a + b < c + b) : a < c := lt_of_add_lt_add_left (show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end) -- here we start using properties of zero. lemma add_nonneg {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := zero_add (0:α) ▸ (add_le_add ha hb) lemma add_pos {a b : α} (ha : 0 < a) (hb : 0 < b) : 0 < a + b := zero_add (0:α) ▸ (add_lt_add ha hb) lemma add_pos_of_pos_of_nonneg {a b : α} (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b := zero_add (0:α) ▸ (add_lt_add_of_lt_of_le ha hb) lemma add_pos_of_nonneg_of_pos {a b : α} (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b := zero_add (0:α) ▸ (add_lt_add_of_le_of_lt ha hb) lemma add_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 := zero_add (0:α) ▸ (add_le_add ha hb) lemma add_neg {a b : α} (ha : a < 0) (hb : b < 0) : a + b < 0 := zero_add (0:α) ▸ (add_lt_add ha hb) lemma add_neg_of_neg_of_nonpos {a b : α} (ha : a < 0) (hb : b ≤ 0) : a + b < 0 := zero_add (0:α) ▸ (add_lt_add_of_lt_of_le ha hb) lemma add_neg_of_nonpos_of_neg {a b : α} (ha : a ≤ 0) (hb : b < 0) : a + b < 0 := zero_add (0:α) ▸ (add_lt_add_of_le_of_lt ha hb) lemma add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume hab : a + b = 0, have ha' : a ≤ 0, from calc a = a + 0 : by rw add_zero ... ≤ a + b : add_le_add_left hb _ ... = 0 : hab, have haz : a = 0, from le_antisymm ha' ha, have hb' : b ≤ 0, from calc b = 0 + b : by rw zero_add ... ≤ a + b : by exact add_le_add_right ha _ ... = 0 : hab, have hbz : b = 0, from le_antisymm hb' hb, and.intro haz hbz) (assume ⟨ha', hb'⟩, by rw [ha', hb', add_zero]) lemma le_add_of_nonneg_of_le {a b c : α} (ha : 0 ≤ a) (hbc : b ≤ c) : b ≤ a + c := zero_add b ▸ add_le_add ha hbc lemma le_add_of_le_of_nonneg {a b c : α} (hbc : b ≤ c) (ha : 0 ≤ a) : b ≤ c + a := add_zero b ▸ add_le_add hbc ha lemma lt_add_of_pos_of_le {a b c : α} (ha : 0 < a) (hbc : b ≤ c) : b < a + c := zero_add b ▸ add_lt_add_of_lt_of_le ha hbc lemma lt_add_of_le_of_pos {a b c : α} (hbc : b ≤ c) (ha : 0 < a) : b < c + a := add_zero b ▸ add_lt_add_of_le_of_lt hbc ha lemma add_le_of_nonpos_of_le {a b c : α} (ha : a ≤ 0) (hbc : b ≤ c) : a + b ≤ c := zero_add c ▸ add_le_add ha hbc lemma add_le_of_le_of_nonpos {a b c : α} (hbc : b ≤ c) (ha : a ≤ 0) : b + a ≤ c := add_zero c ▸ add_le_add hbc ha lemma add_lt_of_neg_of_le {a b c : α} (ha : a < 0) (hbc : b ≤ c) : a + b < c := zero_add c ▸ add_lt_add_of_lt_of_le ha hbc lemma add_lt_of_le_of_neg {a b c : α} (hbc : b ≤ c) (ha : a < 0) : b + a < c := add_zero c ▸ add_lt_add_of_le_of_lt hbc ha lemma lt_add_of_nonneg_of_lt {a b c : α} (ha : 0 ≤ a) (hbc : b < c) : b < a + c := zero_add b ▸ add_lt_add_of_le_of_lt ha hbc lemma lt_add_of_lt_of_nonneg {a b c : α} (hbc : b < c) (ha : 0 ≤ a) : b < c + a := add_zero b ▸ add_lt_add_of_lt_of_le hbc ha lemma lt_add_of_pos_of_lt {a b c : α} (ha : 0 < a) (hbc : b < c) : b < a + c := zero_add b ▸ add_lt_add ha hbc lemma lt_add_of_lt_of_pos {a b c : α} (hbc : b < c) (ha : 0 < a) : b < c + a := add_zero b ▸ add_lt_add hbc ha lemma add_lt_of_nonpos_of_lt {a b c : α} (ha : a ≤ 0) (hbc : b < c) : a + b < c := zero_add c ▸ add_lt_add_of_le_of_lt ha hbc lemma add_lt_of_lt_of_nonpos {a b c : α} (hbc : b < c) (ha : a ≤ 0) : b + a < c := add_zero c ▸ add_lt_add_of_lt_of_le hbc ha lemma add_lt_of_neg_of_lt {a b c : α} (ha : a < 0) (hbc : b < c) : a + b < c := zero_add c ▸ add_lt_add ha hbc lemma add_lt_of_lt_of_neg {a b c : α} (hbc : b < c) (ha : a < 0) : b + a < c := add_zero c ▸ add_lt_add hbc ha end ordered_cancel_comm_monoid class ordered_mul_comm_group (α : Type u) extends comm_group α, order_pair α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c * a < c * b) @[class] def ordered_comm_group : Type u → Type (max 1 u) := ordered_mul_comm_group instance add_comm_group_of_ordered_comm_group (α : Type u) [s : ordered_comm_group α] : add_comm_group α := @ordered_mul_comm_group.to_comm_group α s section ordered_mul_comm_group variable {α : Type u} variable [ordered_mul_comm_group α] lemma ordered_mul_comm_group.le_of_mul_le_mul_left {a b c : α} (h : a * b ≤ a * c) : b ≤ c := have a⁻¹ * (a * b) ≤ a⁻¹ * (a * c), from ordered_mul_comm_group.mul_le_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end lemma ordered_mul_comm_group.lt_of_mul_lt_mul_left {a b c : α} (h : a * b < a * c) : b < c := have a⁻¹ * (a * b) < a⁻¹ * (a * c), from ordered_mul_comm_group.mul_lt_mul_left _ _ h _, begin simp [inv_mul_cancel_left] at this, assumption end end ordered_mul_comm_group instance ordered_mul_comm_group.to_ordered_mul_cancel_comm_monoid (α : Type u) [s : ordered_mul_comm_group α] : ordered_mul_cancel_comm_monoid α := { s with mul_left_cancel := @mul_left_cancel α _, mul_right_cancel := @mul_right_cancel α _, le_of_mul_le_mul_left := @ordered_mul_comm_group.le_of_mul_le_mul_left α _, lt_of_mul_lt_mul_left := @ordered_mul_comm_group.lt_of_mul_lt_mul_left α _ } instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := @ordered_mul_comm_group.to_ordered_mul_cancel_comm_monoid α s section ordered_comm_group variables {α : Type u} [ordered_comm_group α] lemma neg_le_neg {a b : α} (h : a ≤ b) : -b ≤ -a := have 0 ≤ -a + b, from add_left_neg a ▸ add_le_add_left h (-a), have 0 + -b ≤ -a + b + -b, from add_le_add_right this (-b), by rwa [add_neg_cancel_right, zero_add] at this lemma le_of_neg_le_neg {a b : α} (h : -b ≤ -a) : a ≤ b := suffices -(-a) ≤ -(-b), from begin simp [neg_neg] at this, assumption end, neg_le_neg h lemma nonneg_of_neg_nonpos {a : α} (h : -a ≤ 0) : 0 ≤ a := have -a ≤ -0, by rwa neg_zero, le_of_neg_le_neg this lemma neg_nonpos_of_nonneg {a : α} (h : 0 ≤ a) : -a ≤ 0 := have -a ≤ -0, from neg_le_neg h, by rwa neg_zero at this lemma nonpos_of_neg_nonneg {a : α} (h : 0 ≤ -a) : a ≤ 0 := have -0 ≤ -a, by rwa neg_zero, le_of_neg_le_neg this lemma neg_nonneg_of_nonpos {a : α} (h : a ≤ 0) : 0 ≤ -a := have -0 ≤ -a, from neg_le_neg h, by rwa neg_zero at this lemma neg_lt_neg {a b : α} (h : a < b) : -b < -a := have 0 < -a + b, from add_left_neg a ▸ add_lt_add_left h (-a), have 0 + -b < -a + b + -b, from add_lt_add_right this (-b), by rwa [add_neg_cancel_right, zero_add] at this lemma lt_of_neg_lt_neg {a b : α} (h : -b < -a) : a < b := neg_neg a ▸ neg_neg b ▸ neg_lt_neg h lemma pos_of_neg_neg {a : α} (h : -a < 0) : 0 < a := have -a < -0, by rwa neg_zero, lt_of_neg_lt_neg this lemma neg_neg_of_pos {a : α} (h : 0 < a) : -a < 0 := have -a < -0, from neg_lt_neg h, by rwa neg_zero at this lemma neg_of_neg_pos {a : α} (h : 0 < -a) : a < 0 := have -0 < -a, by rwa neg_zero, lt_of_neg_lt_neg this lemma neg_pos_of_neg {a : α} (h : a < 0) : 0 < -a := have -0 < -a, from neg_lt_neg h, by rwa neg_zero at this lemma le_neg_of_le_neg {a b : α} (h : a ≤ -b) : b ≤ -a := begin note h := neg_le_neg h, rwa neg_neg at h end lemma neg_le_of_neg_le {a b : α} (h : -a ≤ b) : -b ≤ a := begin note h := neg_le_neg h, rwa neg_neg at h end lemma lt_neg_of_lt_neg {a b : α} (h : a < -b) : b < -a := begin note h := neg_lt_neg h, rwa neg_neg at h end lemma neg_lt_of_neg_lt {a b : α} (h : -a < b) : -b < a := begin note h := neg_lt_neg h, rwa neg_neg at h end lemma sub_nonneg_of_le {a b : α} (h : b ≤ a) : 0 ≤ a - b := begin note h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonneg {a b : α} (h : 0 ≤ a - b) : b ≤ a := begin note h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_nonpos_of_le {a b : α} (h : a ≤ b) : a - b ≤ 0 := begin note h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonpos {a b : α} (h : a - b ≤ 0) : a ≤ b := begin note h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_pos_of_lt {a b : α} (h : b < a) : 0 < a - b := begin note h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_pos {a b : α} (h : 0 < a - b) : b < a := begin note h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_neg_of_lt {a b : α} (h : a < b) : a - b < 0 := begin note h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_neg {a b : α} (h : a - b < 0) : a < b := begin note h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma add_le_of_le_neg_add {a b c : α} (h : b ≤ -a + c) : a + b ≤ c := begin note h := add_le_add_left h a, rwa add_neg_cancel_left at h end lemma le_neg_add_of_add_le {a b c : α} (h : a + b ≤ c) : b ≤ -a + c := begin note h := add_le_add_left h (-a), rwa neg_add_cancel_left at h end lemma add_le_of_le_sub_left {a b c : α} (h : b ≤ c - a) : a + b ≤ c := begin note h := add_le_add_left h a, rwa [-add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma le_sub_left_of_add_le {a b c : α} (h : a + b ≤ c) : b ≤ c - a := begin note h := add_le_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_le_of_le_sub_right {a b c : α} (h : a ≤ c - b) : a + b ≤ c := begin note h := add_le_add_right h b, rwa sub_add_cancel at h end lemma le_sub_right_of_add_le {a b c : α} (h : a + b ≤ c) : a ≤ c - b := begin note h := add_le_add_right h (-b), rwa add_neg_cancel_right at h end lemma le_add_of_neg_add_le {a b c : α} (h : -b + a ≤ c) : a ≤ b + c := begin note h := add_le_add_left h b, rwa add_neg_cancel_left at h end lemma neg_add_le_of_le_add {a b c : α} (h : a ≤ b + c) : -b + a ≤ c := begin note h := add_le_add_left h (-b), rwa neg_add_cancel_left at h end lemma le_add_of_sub_left_le {a b c : α} (h : a - b ≤ c) : a ≤ b + c := begin note h := add_le_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_le_of_le_add {a b c : α} (h : a ≤ b + c) : a - b ≤ c := begin note h := add_le_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma le_add_of_sub_right_le {a b c : α} (h : a - c ≤ b) : a ≤ b + c := begin note h := add_le_add_right h c, rwa sub_add_cancel at h end lemma sub_right_le_of_le_add {a b c : α} (h : a ≤ b + c) : a - c ≤ b := begin note h := add_le_add_right h (-c), rwa add_neg_cancel_right at h end lemma le_add_of_neg_add_le_left {a b c : α} (h : -b + a ≤ c) : a ≤ b + c := begin rw add_comm at h, exact le_add_of_sub_left_le h end lemma neg_add_le_left_of_le_add {a b c : α} (h : a ≤ b + c) : -b + a ≤ c := begin rw add_comm, exact sub_left_le_of_le_add h end lemma le_add_of_neg_add_le_right {a b c : α} (h : -c + a ≤ b) : a ≤ b + c := begin rw add_comm at h, exact le_add_of_sub_right_le h end lemma neg_add_le_right_of_le_add {a b c : α} (h : a ≤ b + c) : -c + a ≤ b := begin rw add_comm at h, apply neg_add_le_left_of_le_add h end lemma le_add_of_neg_le_sub_left {a b c : α} (h : -a ≤ b - c) : c ≤ a + b := le_add_of_neg_add_le_left (add_le_of_le_sub_right h) lemma neg_le_sub_left_of_le_add {a b c : α} (h : c ≤ a + b) : -a ≤ b - c := begin note h := le_neg_add_of_add_le (sub_left_le_of_le_add h), rwa add_comm at h end lemma le_add_of_neg_le_sub_right {a b c : α} (h : -b ≤ a - c) : c ≤ a + b := le_add_of_sub_right_le (add_le_of_le_sub_left h) lemma neg_le_sub_right_of_le_add {a b c : α} (h : c ≤ a + b) : -b ≤ a - c := le_sub_left_of_add_le (sub_right_le_of_le_add h) lemma sub_le_of_sub_le {a b c : α} (h : a - b ≤ c) : a - c ≤ b := sub_left_le_of_le_add (le_add_of_sub_right_le h) lemma sub_le_sub_left {a b : α} (h : a ≤ b) (c : α) : c - b ≤ c - a := add_le_add_left (neg_le_neg h) c lemma sub_le_sub_right {a b : α} (h : a ≤ b) (c : α) : a - c ≤ b - c := add_le_add_right h (-c) lemma sub_le_sub {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := add_le_add hab (neg_le_neg hcd) lemma add_lt_of_lt_neg_add {a b c : α} (h : b < -a + c) : a + b < c := begin note h := add_lt_add_left h a, rwa add_neg_cancel_left at h end lemma lt_neg_add_of_add_lt {a b c : α} (h : a + b < c) : b < -a + c := begin note h := add_lt_add_left h (-a), rwa neg_add_cancel_left at h end lemma add_lt_of_lt_sub_left {a b c : α} (h : b < c - a) : a + b < c := begin note h := add_lt_add_left h a, rwa [-add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma lt_sub_left_of_add_lt {a b c : α} (h : a + b < c) : b < c - a := begin note h := add_lt_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_lt_of_lt_sub_right {a b c : α} (h : a < c - b) : a + b < c := begin note h := add_lt_add_right h b, rwa sub_add_cancel at h end lemma lt_sub_right_of_add_lt {a b c : α} (h : a + b < c) : a < c - b := begin note h := add_lt_add_right h (-b), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_add_lt {a b c : α} (h : -b + a < c) : a < b + c := begin note h := add_lt_add_left h b, rwa add_neg_cancel_left at h end lemma neg_add_lt_of_lt_add {a b c : α} (h : a < b + c) : -b + a < c := begin note h := add_lt_add_left h (-b), rwa neg_add_cancel_left at h end lemma lt_add_of_sub_left_lt {a b c : α} (h : a - b < c) : a < b + c := begin note h := add_lt_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_lt_of_lt_add {a b c : α} (h : a < b + c) : a - b < c := begin note h := add_lt_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma lt_add_of_sub_right_lt {a b c : α} (h : a - c < b) : a < b + c := begin note h := add_lt_add_right h c, rwa sub_add_cancel at h end lemma sub_right_lt_of_lt_add {a b c : α} (h : a < b + c) : a - c < b := begin note h := add_lt_add_right h (-c), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_add_lt_left {a b c : α} (h : -b + a < c) : a < b + c := begin rw add_comm at h, exact lt_add_of_sub_left_lt h end lemma neg_add_lt_left_of_lt_add {a b c : α} (h : a < b + c) : -b + a < c := begin rw add_comm, exact sub_left_lt_of_lt_add h end lemma lt_add_of_neg_add_lt_right {a b c : α} (h : -c + a < b) : a < b + c := begin rw add_comm at h, exact lt_add_of_sub_right_lt h end lemma neg_add_lt_right_of_lt_add {a b c : α} (h : a < b + c) : -c + a < b := begin rw add_comm at h, apply neg_add_lt_left_of_lt_add h end lemma lt_add_of_neg_lt_sub_left {a b c : α} (h : -a < b - c) : c < a + b := lt_add_of_neg_add_lt_left (add_lt_of_lt_sub_right h) lemma neg_lt_sub_left_of_lt_add {a b c : α} (h : c < a + b) : -a < b - c := begin note h := lt_neg_add_of_add_lt (sub_left_lt_of_lt_add h), rwa add_comm at h end lemma lt_add_of_neg_lt_sub_right {a b c : α} (h : -b < a - c) : c < a + b := lt_add_of_sub_right_lt (add_lt_of_lt_sub_left h) lemma neg_lt_sub_right_of_lt_add {a b c : α} (h : c < a + b) : -b < a - c := lt_sub_left_of_add_lt (sub_right_lt_of_lt_add h) lemma sub_lt_of_sub_lt {a b c : α} (h : a - b < c) : a - c < b := sub_left_lt_of_lt_add (lt_add_of_sub_right_lt h) lemma sub_lt_sub_left {a b : α} (h : a < b) (c : α) : c - b < c - a := add_lt_add_left (neg_lt_neg h) c lemma sub_lt_sub_right {a b : α} (h : a < b) (c : α) : a - c < b - c := add_lt_add_right h (-c) lemma sub_lt_sub {a b c d : α} (hab : a < b) (hcd : c < d) : a - d < b - c := add_lt_add hab (neg_lt_neg hcd) lemma sub_lt_sub_of_le_of_lt {a b c d : α} (hab : a ≤ b) (hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt hab (neg_lt_neg hcd) lemma sub_lt_sub_of_lt_of_le {a b c d : α} (hab : a < b) (hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le hab (neg_le_neg hcd) lemma sub_le_self (a : α) {b : α} (h : b ≥ 0) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg h) _ ... = a : by rw add_zero lemma sub_lt_self (a : α) {b : α} (h : b > 0) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos h) _ ... = a : by rw add_zero lemma add_le_add_three {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a + b + c ≤ d + e + f := begin apply le_trans, apply add_le_add, apply add_le_add, repeat {assumption}, apply le_refl end end ordered_comm_group class decidable_linear_ordered_mul_comm_group (α : Type u) extends comm_group α, decidable_linear_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) (mul_lt_mul_left : ∀ a b : α, a < b → ∀ c : α, c * a < c * b) @[class] def decidable_linear_ordered_comm_group : Type u → Type (max 1 u) := decidable_linear_ordered_mul_comm_group instance add_comm_group_of_decidable_linear_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : add_comm_group α := @decidable_linear_ordered_mul_comm_group.to_comm_group α s instance decidable_linear_order_of_decidable_linear_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : decidable_linear_order α := @decidable_linear_ordered_mul_comm_group.to_decidable_linear_order α s instance decidable_linear_ordered_mul_comm_group.to_ordered_mul_comm_group (α : Type u) [s : decidable_linear_ordered_mul_comm_group α] : ordered_mul_comm_group α := {s with le_of_lt := @le_of_lt α _, lt_of_le_of_lt := @lt_of_le_of_lt α _, lt_of_lt_of_le := @lt_of_lt_of_le α _ } instance decidable_linear_ordered_comm_group.to_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : ordered_comm_group α := @decidable_linear_ordered_mul_comm_group.to_ordered_mul_comm_group α s class decidable_linear_ordered_mul_cancel_comm_monoid (α : Type u) extends ordered_mul_cancel_comm_monoid α, decidable_linear_order α @[class] def decidable_linear_ordered_cancel_comm_monoid : Type u → Type (max 1 u) := decidable_linear_ordered_mul_cancel_comm_monoid instance ordered_cancel_comm_monoid_of_decidable_linear_ordered_cancel_comm_monoid (α : Type u) [s : decidable_linear_ordered_cancel_comm_monoid α] : ordered_cancel_comm_monoid α := @decidable_linear_ordered_mul_cancel_comm_monoid.to_ordered_mul_cancel_comm_monoid α s instance decidable_linear_order_of_decidable_linear_ordered_cancel_comm_monoid (α : Type u) [s : decidable_linear_ordered_cancel_comm_monoid α] : decidable_linear_order α := @decidable_linear_ordered_mul_cancel_comm_monoid.to_decidable_linear_order α s
ecba8d9889dc2f48952611c82ab9e1e3843195b3
9dc8cecdf3c4634764a18254e94d43da07142918
/src/combinatorics/hales_jewett.lean
0102dc5a1bf837d5b629a5e785790a0b9f691299
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
15,455
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import data.fintype.basic import algebra.big_operators.basic /-! # The Hales-Jewett theorem We prove the Hales-Jewett theorem and deduce Van der Waerden's theorem as a corollary. The Hales-Jewett theorem is a result in Ramsey theory dealing with *combinatorial lines*. Given an 'alphabet' `α : Type*` and `a b : α`, an example of a combinatorial line in `α^5` is `{ (a, x, x, b, x) | x : α }`. See `combinatorics.line` for a precise general definition. The Hales-Jewett theorem states that for any fixed finite types `α` and `κ`, there exists a (potentially huge) finite type `ι` such that whenever `ι → α` is `κ`-colored (i.e. for any coloring `C : (ι → α) → κ`), there exists a monochromatic line. We prove the Hales-Jewett theorem using the idea of *color focusing* and a *product argument*. See the proof of `combinatorics.line.exists_mono_in_high_dimension'` for details. The version of Van der Waerden's theorem in this file states that whenever a commutative monoid `M` is finitely colored and `S` is a finite subset, there exists a monochromatic homothetic copy of `S`. This follows from the Hales-Jewett theorem by considering the map `(ι → S) → M` sending `v` to `∑ i : ι, v i`, which sends a combinatorial line to a homothetic copy of `S`. ## Main results - `combinatorics.line.exists_mono_in_high_dimension`: the Hales-Jewett theorem. - `combinatorics.exists_mono_homothetic_copy`: a generalization of Van der Waerden's theorem. ## Implementation details For convenience, we work directly with finite types instead of natural numbers. That is, we write `α, ι, κ` for (finite) types where one might traditionally use natural numbers `n, H, c`. This allows us to work directly with `α`, `option α`, `(ι → α) → κ`, and `ι ⊕ ι'` instead of `fin n`, `fin (n+1)`, `fin (c^(n^H))`, and `fin (H + H')`. ## Todo - Prove a finitary version of Van der Waerden's theorem (either by compactness or by modifying the current proof). - One could reformulate the proof of Hales-Jewett to give explicit upper bounds on the number of coordinates needed. ## Tags combinatorial line, Ramsey theory, arithmetic progession ### References * https://en.wikipedia.org/wiki/Hales%E2%80%93Jewett_theorem -/ open_locale classical open_locale big_operators universes u v namespace combinatorics /-- The type of combinatorial lines. A line `l : line α ι` in the hypercube `ι → α` defines a function `α → ι → α` from `α` to the hypercube, such that for each coordinate `i : ι`, the function `λ x, l x i` is either `id` or constant. We require lines to be nontrivial in the sense that `λ x, l x i` is `id` for at least one `i`. Formally, a line is represented by the function `l.idx_fun : ι → option α` which says whether `λ x, l x i` is `id` (corresponding to `l.idx_fun i = none`) or constantly `y` (corresponding to `l.idx_fun i = some y`). When `α` has size `1` there can be many elements of `line α ι` defining the same function. -/ structure line (α ι : Type*) := (idx_fun : ι → option α) (proper : ∃ i, idx_fun i = none) namespace line /- This lets us treat a line `l : line α ι` as a function `α → ι → α`. -/ instance (α ι) : has_coe_to_fun (line α ι) (λ _, α → ι → α) := ⟨λ l x i, (l.idx_fun i).get_or_else x⟩ /-- A line is monochromatic if all its points are the same color. -/ def is_mono {α ι κ} (C : (ι → α) → κ) (l : line α ι) : Prop := ∃ c, ∀ x, C (l x) = c /-- The diagonal line. It is the identity at every coordinate. -/ def diagonal (α ι) [nonempty ι] : line α ι := { idx_fun := λ _, none, proper := ⟨classical.arbitrary ι, rfl⟩ } instance (α ι) [nonempty ι] : inhabited (line α ι) := ⟨diagonal α ι⟩ /-- The type of lines that are only one color except possibly at their endpoints. -/ structure almost_mono {α ι κ : Type*} (C : (ι → option α) → κ) := (line : line (option α) ι) (color : κ) (has_color : ∀ x : α, C (line (some x)) = color) instance {α ι κ : Type*} [nonempty ι] [inhabited κ] : inhabited (almost_mono (λ v : ι → option α, (default : κ))) := ⟨{ line := default, color := default, has_color := λ _, rfl }⟩ /-- The type of collections of lines such that - each line is only one color except possibly at its endpoint - the lines all have the same endpoint - the colors of the lines are distinct. Used in the proof `exists_mono_in_high_dimension`. -/ structure color_focused {α ι κ : Type*} (C : (ι → option α) → κ) := (lines : multiset (almost_mono C)) (focus : ι → option α) (is_focused : ∀ p ∈ lines, almost_mono.line p none = focus) (distinct_colors : (lines.map almost_mono.color).nodup) instance {α ι κ} (C : (ι → option α) → κ) : inhabited (color_focused C) := ⟨⟨0, λ _, none, λ _, false.elim, multiset.nodup_zero⟩⟩ /-- A function `f : α → α'` determines a function `line α ι → line α' ι`. For a coordinate `i`, `l.map f` is the identity at `i` if `l` is, and constantly `f y` if `l` is constantly `y` at `i`. -/ def map {α α' ι} (f : α → α') (l : line α ι) : line α' ι := { idx_fun := λ i, (l.idx_fun i).map f, proper := ⟨l.proper.some, by rw [l.proper.some_spec, option.map_none'] ⟩ } /-- A point in `ι → α` and a line in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def vertical {α ι ι'} (v : ι → α) (l : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim (some ∘ v) l.idx_fun, proper := ⟨sum.inr l.proper.some, l.proper.some_spec⟩ } /-- A line in `ι → α` and a point in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def horizontal {α ι ι'} (l : line α ι) (v : ι' → α) : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun (some ∘ v), proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } /-- One line in `ι → α` and one in `ι' → α` together determine a line in `ι ⊕ ι' → α`. -/ def prod {α ι ι'} (l : line α ι) (l' : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun l'.idx_fun, proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } lemma apply {α ι} (l : line α ι) (x : α) : l x = λ i, (l.idx_fun i).get_or_else x := rfl lemma apply_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i = none) : l x i = x := by simp only [option.get_or_else_none, h, l.apply] lemma apply_of_ne_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i ≠ none) : some (l x i) = l.idx_fun i := by rw [l.apply, option.get_or_else_of_ne_none h] @[simp] lemma map_apply {α α' ι} (f : α → α') (l : line α ι) (x : α) : l.map f (f x) = f ∘ l x := by simp only [line.apply, line.map, option.get_or_else_map] @[simp] lemma vertical_apply {α ι ι'} (v : ι → α) (l : line α ι') (x : α) : l.vertical v x = sum.elim v (l x) := by { funext i, cases i; refl } @[simp] lemma horizontal_apply {α ι ι'} (l : line α ι) (v : ι' → α) (x : α) : l.horizontal v x = sum.elim (l x) v := by { funext i, cases i; refl } @[simp] lemma prod_apply {α ι ι'} (l : line α ι) (l' : line α ι') (x : α) : l.prod l' x = sum.elim (l x) (l' x) := by { funext i, cases i; refl } @[simp] lemma diagonal_apply {α ι} [nonempty ι] (x : α) : line.diagonal α ι x = λ i, x := by simp_rw [line.apply, line.diagonal, option.get_or_else_none] /-- The Hales-Jewett theorem. This version has a restriction on universe levels which is necessary for the proof. See `exists_mono_in_high_dimension` for a fully universe-polymorphic version. -/ private theorem exists_mono_in_high_dimension' : ∀ (α : Type u) [finite α] (κ : Type (max v u)) [finite κ], ∃ (ι : Type) (_ : fintype ι), ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := -- The proof proceeds by induction on `α`. finite.induction_empty_option -- We have to show that the theorem is invariant under `α ≃ α'` for the induction to work. (λ α α' e, forall_imp $ λ κ, forall_imp $ λ _, Exists.imp $ λ ι, Exists.imp $ λ _ h C, let ⟨l, c, lc⟩ := h (λ v, C (e ∘ v)) in ⟨l.map e, c, e.forall_congr_left.mp $ λ x, by rw [←lc x, line.map_apply]⟩) begin -- This deals with the degenerate case where `α` is empty. introsI κ _, by_cases h : nonempty κ, { resetI, exact ⟨unit, infer_instance, λ C, ⟨default, classical.arbitrary _, pempty.rec _⟩⟩, }, { exact ⟨empty, infer_instance, λ C, (h ⟨C (empty.rec _)⟩).elim⟩, } end begin -- Now we have to show that the theorem holds for `option α` if it holds for `α`. introsI α _ ihα κ _, casesI nonempty_fintype κ, -- Later we'll need `α` to be nonempty. So we first deal with the trivial case where `α` is empty. -- Then `option α` has only one element, so any line is monochromatic. by_cases h : nonempty α, work_on_goal 2 { refine ⟨unit, infer_instance, λ C, ⟨diagonal _ _, C (λ _, none), _⟩⟩, rintros (_ | ⟨a⟩), refl, exact (h ⟨a⟩).elim, }, -- The key idea is to show that for every `r`, in high dimension we can either find -- `r` color focused lines or a monochromatic line. suffices key : ∀ r : ℕ, ∃ (ι : Type) (_ : fintype ι), ∀ C : (ι → (option α)) → κ, (∃ s : color_focused C, s.lines.card = r) ∨ (∃ l, is_mono C l), -- Given the key claim, we simply take `r = |κ| + 1`. We cannot have this many distinct colors so -- we must be in the second case, where there is a monochromatic line. { obtain ⟨ι, _inst, hι⟩ := key (fintype.card κ + 1), refine ⟨ι, _inst, λ C, (hι C).resolve_left _⟩, rintro ⟨s, sr⟩, apply nat.not_succ_le_self (fintype.card κ), rw [←nat.add_one, ←sr, ←multiset.card_map, ←finset.card_mk], exact finset.card_le_univ ⟨_, s.distinct_colors⟩ }, -- We now prove the key claim, by induction on `r`. intro r, induction r with r ihr, -- The base case `r = 0` is trivial as the empty collection is color-focused. { exact ⟨empty, infer_instance, λ C, or.inl ⟨default, multiset.card_zero⟩⟩, }, -- Supposing the key claim holds for `r`, we need to show it for `r+1`. First pick a high enough -- dimension `ι` for `r`. obtain ⟨ι, _inst, hι⟩ := ihr, resetI, -- Then since the theorem holds for `α` with any number of colors, pick a dimension `ι'` such that -- `ι' → α` always has a monochromatic line whenever it is `(ι → option α) → κ`-colored. specialize ihα ((ι → option α) → κ), obtain ⟨ι', _inst, hι'⟩ := ihα, resetI, -- We claim that `ι ⊕ ι'` works for `option α` and `κ`-coloring. refine ⟨ι ⊕ ι', infer_instance, _⟩, intro C, -- A `κ`-coloring of `ι ⊕ ι' → option α` induces an `(ι → option α) → κ`-coloring of `ι' → α`. specialize hι' (λ v' v, C (sum.elim v (some ∘ v'))), -- By choice of `ι'` this coloring has a monochromatic line `l'` with color class `C'`, where -- `C'` is a `κ`-coloring of `ι → α`. obtain ⟨l', C', hl'⟩ := hι', -- If `C'` has a monochromatic line, then so does `C`. We use this in two places below. have mono_of_mono : (∃ l, is_mono C' l) → (∃ l, is_mono C l), { rintro ⟨l, c, hl⟩, refine ⟨l.horizontal (some ∘ l' (classical.arbitrary α)), c, λ x, _⟩, rw [line.horizontal_apply, ←hl, ←hl'], }, -- By choice of `ι`, `C'` either has `r` color-focused lines or a monochromatic line. specialize hι C', rcases hι with ⟨s, sr⟩ | _, -- By above, we are done if `C'` has a monochromatic line. work_on_goal 2 { exact or.inr (mono_of_mono hι) }, -- Here we assume `C'` has `r` color focused lines. We split into cases depending on whether one of -- these `r` lines has the same color as the focus point. by_cases h : ∃ p ∈ s.lines, (p : almost_mono _).color = C' s.focus, -- If so then this is a `C'`-monochromatic line and we are done. { obtain ⟨p, p_mem, hp⟩ := h, refine or.inr (mono_of_mono ⟨p.line, p.color, _⟩), rintro (_ | _), rw [hp, s.is_focused p p_mem], apply p.has_color, }, -- If not, we get `r+1` color focused lines by taking the product of the `r` lines with `l'` and -- adding to this the vertical line obtained by the focus point and `l`. refine or.inl ⟨⟨(s.lines.map _).cons ⟨(l'.map some).vertical s.focus, C' s.focus, λ x, _⟩, sum.elim s.focus (l'.map some none), _, _⟩, _⟩, -- The vertical line is almost monochromatic. { rw [vertical_apply, ←congr_fun (hl' x), line.map_apply], }, { refine λ p, ⟨p.line.prod (l'.map some), p.color, λ x, _⟩, -- The product lines are almost monochromatic. rw [line.prod_apply, line.map_apply, ←p.has_color, ←congr_fun (hl' x)], }, -- Our `r+1` lines have the same endpoint. { simp_rw [multiset.mem_cons, multiset.mem_map], rintros _ (rfl | ⟨q, hq, rfl⟩), { rw line.vertical_apply, }, { rw [line.prod_apply, s.is_focused q hq], }, }, -- Our `r+1` lines have distinct colors (this is why we needed to split into cases above). { rw [multiset.map_cons, multiset.map_map, multiset.nodup_cons, multiset.mem_map], exact ⟨λ ⟨q, hq, he⟩, h ⟨q, hq, he⟩, s.distinct_colors⟩, }, -- Finally, we really do have `r+1` lines! { rw [multiset.card_cons, multiset.card_map, sr], }, end /-- The Hales-Jewett theorem: for any finite types `α` and `κ`, there exists a finite type `ι` such that whenever the hypercube `ι → α` is `κ`-colored, there is a monochromatic combinatorial line. -/ theorem exists_mono_in_high_dimension (α : Type u) [finite α] (κ : Type v) [finite κ] : ∃ (ι : Type) [fintype ι], ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := let ⟨ι, ιfin, hι⟩ := exists_mono_in_high_dimension' α (ulift κ) in ⟨ι, ιfin, λ C, let ⟨l, c, hc⟩ := hι (ulift.up ∘ C) in ⟨l, c.down, λ x, by rw ←hc⟩ ⟩ end line /-- A generalization of Van der Waerden's theorem: if `M` is a finitely colored commutative monoid, and `S` is a finite subset, then there exists a monochromatic homothetic copy of `S`. -/ theorem exists_mono_homothetic_copy {M κ : Type*} [add_comm_monoid M] (S : finset M) [finite κ] (C : M → κ) : ∃ (a > 0) (b : M) (c : κ), ∀ s ∈ S, C (a • s + b) = c := begin obtain ⟨ι, _inst, hι⟩ := line.exists_mono_in_high_dimension S κ, resetI, specialize hι (λ v, C $ ∑ i, v i), obtain ⟨l, c, hl⟩ := hι, set s : finset ι := { i ∈ finset.univ | l.idx_fun i = none } with hs, refine ⟨s.card, finset.card_pos.mpr ⟨l.proper.some, _⟩, ∑ i in sᶜ, ((l.idx_fun i).map coe).get_or_else 0, c, _⟩, { rw [hs, finset.sep_def, finset.mem_filter], exact ⟨finset.mem_univ _, l.proper.some_spec⟩, }, intros x xs, rw ←hl ⟨x, xs⟩, clear hl, congr, rw ←finset.sum_add_sum_compl s, congr' 1, { rw ←finset.sum_const, apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.mem_filter] at hi, rw [l.apply_none _ _ hi.right, subtype.coe_mk], }, { apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.compl_filter, finset.mem_filter] at hi, obtain ⟨y, hy⟩ := option.ne_none_iff_exists.mp hi.right, simp_rw [line.apply, ←hy, option.map_some', option.get_or_else_some], }, end end combinatorics
d34d5ede6df1370881f724e7178f4413c3b7f79e
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/IO3.lean
9d3e7dd3ef25511f3321ecda5fb49db45afd2859
[ "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
217
lean
import system.IO definition main : IO unit := do { l ← get_line, if l = "hello" then put_str "you have typed hello\n" else do {put_str "you did not type hello\n", put_str "-----------\n"} }
6c2c951f6fe475713aa20384a75ab32e9b656990
f7315930643edc12e76c229a742d5446dad77097
/library/data/encodable.lean
3c1619a1120a49e0eb210f1ddfd8dfc0d888c89f
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,365
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.encodable Author: Leonardo de Moura Type class for encodable types. Note that every encodable type is countable. -/ import data.fintype data.list data.sum data.nat data.subtype data.countable open option list nat function structure encodable [class] (A : Type) := (encode : A → nat) (decode : nat → option A) (encodek : ∀ a, decode (encode a) = some a) open encodable definition countable_of_encodable {A : Type} : encodable A → countable A := assume e : encodable A, have inj_encode : injective encode, from λ (a₁ a₂ : A) (h : encode a₁ = encode a₂), assert aux : decode A (encode a₁) = decode A (encode a₂), by rewrite h, by rewrite [*encodek at aux]; exact (option.no_confusion aux (λ e, e)), exists.intro encode inj_encode definition encodable_fintype [instance] {A : Type} [h₁ : fintype A] [h₂ : decidable_eq A] : encodable A := encodable.mk (λ a, find a (elements_of A)) (λ n, nth (elements_of A) n) (λ a, find_nth (fintype.complete a)) definition encodable_nat [instance] : encodable nat := encodable.mk (λ a, a) (λ n, some n) (λ a, rfl) definition encodable_option [instance] {A : Type} [h : encodable A] : encodable (option A) := encodable.mk (λ o, match o with | some a := succ (encode a) | none := 0 end) (λ n, if n = 0 then some none else some (decode A (pred n))) (λ o, begin cases o with [a], begin esimp end, begin esimp, rewrite [if_neg !succ_ne_zero, pred_succ, encodable.encodek] end end) section sum variables {A B : Type} variables [h₁ : encodable A] [h₂ : encodable B] include h₁ h₂ definition encode_sum : sum A B → nat | (sum.inl a) := 2 * encode a | (sum.inr b) := 2 * encode b + 1 definition decode_sum (n : nat) : option (sum A B) := if n mod 2 = 0 then match decode A (n div 2) with | some a := some (sum.inl a) | none := none end else match decode B ((n - 1) div 2) with | some b := some (sum.inr b) | none := none end open decidable theorem decode_encode_sum : ∀ s : sum A B, decode_sum (encode_sum s) = some s | (sum.inl a) := assert aux : 2 > 0, from dec_trivial, begin esimp [encode_sum, decode_sum], rewrite [mul_mod_right, if_pos (eq.refl 0), mul_div_cancel_left _ aux, encodable.encodek] end | (sum.inr b) := assert aux₁ : 2 > 0, from dec_trivial, assert aux₂ : 1 mod 2 = 1, by rewrite [modulo_def], assert aux₃ : 1 ≠ 0, from dec_trivial, begin esimp [encode_sum, decode_sum], rewrite [add.comm, add_mul_mod_self_left aux₁, aux₂, if_neg aux₃, add_sub_cancel_left, mul_div_cancel_left _ aux₁, encodable.encodek] end definition encodable_sum [instance] : encodable (sum A B) := encodable.mk (λ s, encode_sum s) (λ n, decode_sum n) (λ s, decode_encode_sum s) end sum section prod variables {A B : Type} variables [h₁ : encodable A] [h₂ : encodable B] include h₁ h₂ definition encode_prod : A × B → nat | (a, b) := mkpair (encode a) (encode b) definition decode_prod (n : nat) : option (A × B) := match unpair n with | (n₁, n₂) := match decode A n₁ with | some a := match decode B n₂ with | some b := some (a, b) | none := none end | none := none end end theorem decode_encode_prod : ∀ p : A × B, decode_prod (encode_prod p) = some p | (a, b) := begin esimp [encode_prod, decode_prod, prod.cases_on], rewrite [unpair_mkpair], esimp, rewrite [*encodable.encodek] end definition encodable_product [instance] : encodable (A × B) := encodable.mk encode_prod decode_prod decode_encode_prod end prod section list variables {A : Type} variables [h : encodable A] include h definition encode_list_core : list A → nat | [] := 0 | (a::l) := mkpair (encode a) (encode_list_core l) theorem encode_list_core_cons (a : A) (l : list A) : encode_list_core (a::l) = mkpair (encode a) (encode_list_core l) := rfl definition encode_list (l : list A) : nat := mkpair (length l) (encode_list_core l) definition decode_list_core : nat → nat → option (list A) | 0 v := some [] | (succ n) v := match unpair v with | (v₁, v₂) := match decode A v₁ with | some a := match decode_list_core n v₂ with | some l := some (a::l) | none := none end | none := none end end theorem decode_list_core_succ (n v : nat) : decode_list_core (succ n) v = match unpair v with | (v₁, v₂) := match decode A v₁ with | some a := match decode_list_core n v₂ with | some l := some (a::l) | none := none end | none := none end end := rfl definition decode_list (n : nat) : option (list A) := match unpair n with | (l, v) := decode_list_core l v end theorem decode_encode_list_core : ∀ l : list A, decode_list_core (length l) (encode_list_core l) = some l | [] := rfl | (a::l) := begin rewrite [encode_list_core_cons, length_cons, add_one (length l), decode_list_core_succ], rewrite [unpair_mkpair], esimp [prod.cases_on], rewrite [decode_encode_list_core l], rewrite [encodable.encodek], end theorem decode_encode_list (l : list A) : decode_list (encode_list l) = some l := begin esimp [encode_list, decode_list], rewrite [unpair_mkpair], esimp [prod.cases_on], apply decode_encode_list_core end definition encodable_list [instance] : encodable (list A) := encodable.mk encode_list decode_list decode_encode_list end list definition encodable_of_left_injection {A B : Type} [h₁ : encodable A] (f : B → A) (finv : A → option B) (linv : ∀ b, finv (f b) = some b) : encodable B := encodable.mk (λ b, encode (f b)) (λ n, match decode A n with | some a := finv a | none := none end) (λ b, begin esimp, rewrite [encodable.encodek], esimp [option.cases_on], rewrite [linv] end) /- Choice function for encodable types and decidable predicates. We provide the following API choose {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] : (∃ x, p x) → A := choose_spec {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ section find_a parameters {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] include c include d private definition pn (n : nat) : Prop := match decode A n with | some a := p a | none := false end private definition decidable_pn : decidable_pred pn := λ n, match decode A n with | some a := λ e : decode A n = some a, match d a with | decidable.inl t := begin unfold pn, rewrite e, esimp [option.cases_on], exact (decidable.inl t) end | decidable.inr f := begin unfold pn, rewrite e, esimp [option.cases_on], exact (decidable.inr f) end end | none := λ e : decode A n = none, begin unfold pn, rewrite e, esimp [option.cases_on], exact decidable_false end end (eq.refl (decode A n)) private definition ex_pn_of_ex : (∃ x, p x) → (∃ x, pn x) := assume ex, obtain (w : A) (pw : p w), from ex, exists.intro (encode w) begin unfold pn, rewrite [encodek], esimp, exact pw end private lemma decode_ne_none_of_pn {n : nat} : pn n → decode A n ≠ none := assume pnn e, begin rewrite [▸ (match decode A n with | some a := p a | none := false end) at pnn], rewrite [e at pnn], esimp [option.cases_on] at pnn, exact (false.elim pnn) end open subtype private lemma of_nat (n : nat) : pn n → { a : A | p a } := match decode A n with | some a := λ (e : decode A n = some a), begin unfold pn, rewrite e, esimp [option.cases_on], intro pa, exact (tag a pa) end | none := λ (e : decode A n = none) h, absurd e (decode_ne_none_of_pn h) end (eq.refl (decode A n)) private definition find_a : (∃ x, p x) → {a : A | p a} := assume ex : ∃ x, p x, have exn : ∃ x, pn x, from ex_pn_of_ex ex, let r : nat := @nat.choose pn decidable_pn exn in have pnr : pn r, from @nat.choose_spec pn decidable_pn exn, of_nat r pnr end find_a namespace encodable open subtype definition choose {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] : (∃ x, p x) → A := assume ex, elt_of (find_a ex) theorem choose_spec {A : Type} {p : A → Prop} [c : encodable A] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := has_property (find_a ex) theorem axiom_of_choice {A : Type} {B : A → Type} {R : Π x, B x → Prop} [c : Π a, encodable (B a)] [d : ∀ x y, decidable (R x y)] : (∀x, ∃y, R x y) → ∃f, ∀x, R x (f x) := assume H, have H₁ : ∀x, R x (choose (H x)), from take x, choose_spec (H x), exists.intro _ H₁ theorem skolem {A : Type} {B : A → Type} {P : Π x, B x → Prop} [c : Π a, encodable (B a)] [d : ∀ x y, decidable (P x y)] : (∀x, ∃y, P x y) ↔ ∃f, (∀x, P x (f x)) := iff.intro (assume H : (∀x, ∃y, P x y), axiom_of_choice H) (assume H : (∃f, (∀x, P x (f x))), take x, obtain (fw : ∀x, B x) (Hw : ∀x, P x (fw x)), from H, exists.intro (fw x) (Hw x)) end encodable
6183efa58bfeb659c84e86686c4f4b185c6a6855
618003631150032a5676f229d13a079ac875ff77
/src/tactic/omega/int/preterm.lean
3ac51ba3e14a62dc7c1b052786942c266240439e
[ "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
2,807
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Linear integer arithmetic terms in pre-normalized form. -/ import tactic.omega.term namespace omega namespace int /-- The shadow syntax for arithmetic terms. All constants are reified to `cst` (e.g., `-5` is reified to `cst -5`) and all other atomic terms are reified to `exp` (e.g., `-5 * (gcd 14 -7)` is reified to `exp -5 \`(gcd 14 -7)`). `exp` accepts a coefficient of type `int` as its first argument because multiplication by constant is allowed by the omega test. -/ meta inductive exprterm : Type | cst : int → exprterm | exp : int → expr → exprterm | add : exprterm → exprterm → exprterm /-- Similar to `exprterm`, except that all exprs are now replaced with de Brujin indices of type `nat`. This is akin to generalizing over the terms represented by the said exprs. -/ @[derive has_reflect, derive inhabited] inductive preterm : Type | cst : int → preterm | var : int → nat → preterm | add : preterm → preterm → preterm localized "notation `&` k := omega.int.preterm.cst k" in omega.int localized "infix ` ** ` : 300 := omega.int.preterm.var" in omega.int localized "notation t `+*` s := omega.int.preterm.add t s" in omega.int namespace preterm /-- Preterm evaluation -/ @[simp] def val (v : nat → int) : preterm → int | (& i) := i | (i ** n) := if i = 1 then v n else if i = -1 then -(v n) else (v n) * i | (t1 +* t2) := t1.val + t2.val /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index @[simp] def add_one (t : preterm) : preterm := t +* (&1) def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" end preterm open_locale list.func -- get notation for list.func.set /-- Return a term (which is in canonical form by definition) that is equivalent to the input preterm -/ @[simp] def canonize : preterm → term | (& i) := ⟨i, []⟩ | (i ** n) := ⟨0, [] {n ↦ i}⟩ | (t1 +* t2) := term.add (canonize t1) (canonize t2) @[simp] lemma val_canonize {v : nat → int} : ∀ {t : preterm}, (canonize t).val v = t.val v | (& i) := by simp only [preterm.val, add_zero, term.val, canonize, coeffs.val_nil] | (i ** n) := begin simp only [coeffs.val_set, canonize, preterm.val, zero_add, term.val], split_ifs with h1 h2, { simp only [one_mul, h1] }, { simp only [neg_mul_eq_neg_mul_symm, one_mul, h2] }, { rw mul_comm } end | (t +* s) := by simp only [canonize, val_canonize, term.val_add, preterm.val] end int end omega
c38823237e161758ce99b110967b7cb84b0afde6
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/trace2.lean
e0d20eded75dc1485934c7decf0f4ab6b1d33854
[ "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
308
lean
open tactic declare_trace foo.bla example : true := by do when_tracing `foo.bla $ do { trace "hello", trace "world" }, constructor set_option trace.foo.bla true #print "------------" example : true := by do when_tracing `foo.bla $ do { trace "hello", trace "world" }, constructor
17708f6964b5ecaebafe8625f1d0b3f43a8ed352
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Data/RBTree/Basic.lean
2a0513c97c91e940afae53c3e16cb95b425ddfb7
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
2,887
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.RBMap.Basic universes u v w def RBTree (α : Type u) (lt : α → α → Bool) : Type u := RBMap α Unit lt @[inline] def mkRBTree (α : Type u) (lt : α → α → Bool) : RBTree α lt := mkRBMap α Unit lt instance (α : Type u) (lt : α → α → Bool) : HasEmptyc (RBTree α lt) := ⟨mkRBTree α lt⟩ namespace RBTree variables {α : Type u} {β : Type v} {lt : α → α → Bool} @[inline] def empty : RBTree α lt := RBMap.empty @[inline] def depth (f : Nat → Nat → Nat) (t : RBTree α lt) : Nat := RBMap.depth f t @[inline] def fold (f : β → α → β) (b : β) (t : RBTree α lt) : β := RBMap.fold (fun r a _ => f r a) b t @[inline] def revFold (f : β → α → β) (b : β) (t : RBTree α lt) : β := RBMap.revFold (fun r a _ => f r a) b t @[inline] def mfold {m : Type v → Type w} [Monad m] (f : β → α → m β) (b : β) (t : RBTree α lt) : m β := RBMap.mfold (fun r a _ => f r a) b t @[inline] def mfor {m : Type v → Type w} [Monad m] (f : α → m β) (t : RBTree α lt) : m PUnit := t.mfold (fun _ a => f a *> pure ⟨⟩) ⟨⟩ @[inline] def isEmpty (t : RBTree α lt) : Bool := RBMap.isEmpty t @[specialize] def toList (t : RBTree α lt) : List α := t.revFold (fun as a => a::as) [] @[inline] protected def min (t : RBTree α lt) : Option α := match RBMap.min t with | some ⟨a, _⟩ => some a | none => none @[inline] protected def max (t : RBTree α lt) : Option α := match RBMap.max t with | some ⟨a, _⟩ => some a | none => none instance [HasRepr α] : HasRepr (RBTree α lt) := ⟨fun t => "rbtreeOf " ++ repr t.toList⟩ @[inline] def insert (t : RBTree α lt) (a : α) : RBTree α lt := RBMap.insert t a () @[inline] def erase (t : RBTree α lt) (a : α) : RBTree α lt := RBMap.erase t a @[specialize] def ofList : List α → RBTree α lt | [] => mkRBTree _ _ | x::xs => (ofList xs).insert x @[inline] def find? (t : RBTree α lt) (a : α) : Option α := match RBMap.findCore? t a with | some ⟨a, _⟩ => some a | none => none @[inline] def contains (t : RBTree α lt) (a : α) : Bool := (t.find? a).isSome def fromList (l : List α) (lt : α → α → Bool) : RBTree α lt := l.foldl insert (mkRBTree α lt) @[inline] def all (t : RBTree α lt) (p : α → Bool) : Bool := RBMap.all t (fun a _ => p a) @[inline] def any (t : RBTree α lt) (p : α → Bool) : Bool := RBMap.any t (fun a _ => p a) def subset (t₁ t₂ : RBTree α lt) : Bool := t₁.all $ fun a => (t₂.find? a).toBool def seteq (t₁ t₂ : RBTree α lt) : Bool := subset t₁ t₂ && subset t₂ t₁ end RBTree def rbtreeOf {α : Type u} (l : List α) (lt : α → α → Bool) : RBTree α lt := RBTree.fromList l lt
ba02ff8ef0418ea60181b927f89bf531be0e7618
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/computability/tm_to_partrec.lean
0c710e6bd6b2c1aa180fb29f5fe74b03bf2ebdcf
[ "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
81,082
lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import computability.halting import computability.turing_machine import data.num.lemmas import tactic.derive_fintype /-! # Modelling partial recursive functions using Turing machines This file defines a simplified basis for partial recursive functions, and a `turing.TM2` model Turing machine for evaluating these functions. This amounts to a constructive proof that every `partrec` function can be evaluated by a Turing machine. ## Main definitions * `to_partrec.code`: a simplified basis for partial recursive functions, valued in `list ℕ →. list ℕ`. * `to_partrec.code.eval`: semantics for a `to_partrec.code` program * `partrec_to_TM2.tr`: A TM2 turing machine which can evaluate `code` programs -/ open function (update) open relation namespace turing /-! ## A simplified basis for partrec This section constructs the type `code`, which is a data type of programs with `list ℕ` input and output, with enough expressivity to write any partial recursive function. The primitives are: * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `nat.cases_on`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) This basis is convenient because it is closer to the Turing machine model - the key operations are splitting and merging of lists of unknown length, while the messy `n`-ary composition operation from the traditional basis for partial recursive functions is absent - but it retains a compositional semantics. The first step in transitioning to Turing machines is to make a sequential evaluator for this basis, which we take up in the next section. -/ namespace to_partrec /-- The type of codes for primitive recursive functions. Unlike `nat.partrec.code`, this uses a set of operations on `list ℕ`. See `code.eval` for a description of the behavior of the primitives. -/ @[derive [decidable_eq, inhabited]] inductive code | zero' | succ | tail | cons : code → code → code | comp : code → code → code | case : code → code → code | fix : code → code /-- The semantics of the `code` primitives, as partial functions `list ℕ →. list ℕ`. By convention we functions that return a single result return a singleton `[n]`, or in some cases `n :: v` where `v` will be ignored by a subsequent function. * `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`. * `succ` returns the successor of the head of the input, defaulting to zero if there is no head: * `succ [] = [1]` * `succ (n :: v) = [n + 1]` * `tail` returns the tail of the input * `tail [] = []` * `tail (n :: v) = v` * `cons f fs` calls `f` and `fs` on the input and conses the results: * `cons f fs v = (f v).head :: fs v` * `comp f g` calls `f` on the output of `g`: * `comp f g v = f (g v)` * `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or a successor (similar to `nat.cases_on`). * `case f g [] = f []` * `case f g (0 :: v) = f v` * `case f g (n+1 :: v) = g (n :: v)` * `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f` again or finish: * `fix f v = []` if `f v = []` * `fix f v = w` if `f v = 0 :: w` * `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded) -/ @[simp] def code.eval : code → list ℕ →. list ℕ | code.zero' := λ v, pure (0 :: v) | code.succ := λ v, pure [v.head.succ] | code.tail := λ v, pure v.tail | (code.cons f fs) := λ v, do n ← code.eval f v, ns ← code.eval fs v, pure (n.head :: ns) | (code.comp f g) := λ v, g.eval v >>= f.eval | (code.case f g) := λ v, v.head.elim (f.eval v.tail) (λ y _, g.eval (y :: v.tail)) | (code.fix f) := pfun.fix $ λ v, (f.eval v).map $ λ v, if v.head = 0 then sum.inl v.tail else sum.inr v.tail namespace code /-- `nil` is the constant nil function: `nil v = []`. -/ def nil : code := tail.comp succ @[simp] theorem nil_eval (v) : nil.eval v = pure [] := by simp [nil] /-- `id` is the identity function: `id v = v`. -/ def id : code := tail.comp zero' @[simp] theorem id_eval (v) : id.eval v = pure v := by simp [id] /-- `head` gets the head of the input list: `head [] = [0]`, `head (n :: v) = [n]`. -/ def head : code := cons id nil @[simp] theorem head_eval (v) : head.eval v = pure [v.head] := by simp [head] /-- `zero` is the constant zero function: `zero v = [0]`. -/ def zero : code := cons zero' nil @[simp] theorem zero_eval (v) : zero.eval v = pure [0] := by simp [zero] /-- `pred` returns the predecessor of the head of the input: `pred [] = [0]`, `pred (0 :: v) = [0]`, `pred (n+1 :: v) = [n]`. -/ def pred : code := case zero head @[simp] theorem pred_eval (v) : pred.eval v = pure [v.head.pred] := by simp [pred]; cases v.head; simp /-- `rfind f` performs the function of the `rfind` primitive of partial recursive functions. `rfind f v` returns the smallest `n` such that `(f (n :: v)).head = 0`. It is implemented as: rfind f v = pred (fix (λ (n::v), f (n::v) :: n+1 :: v) (0 :: v)) The idea is that the initial state is `0 :: v`, and the `fix` keeps `n :: v` as its internal state; it calls `f (n :: v)` as the exit test and `n+1 :: v` as the next state. At the end we get `n+1 :: v` where `n` is the desired output, and `pred (n+1 :: v) = [n]` returns the result. -/ def rfind (f : code) : code := comp pred $ comp (fix $ cons f $ cons succ tail) zero' /-- `prec f g` implements the `prec` (primitive recursion) operation of partial recursive functions. `prec f g` evaluates as: * `prec f g [] = [f []]` * `prec f g (0 :: v) = [f v]` * `prec f g (n+1 :: v) = [g (n :: prec f g (n :: v) :: v)]` It is implemented as: G (a :: b :: IH :: v) = (b :: a+1 :: b-1 :: g (a :: IH :: v) :: v) F (0 :: f_v :: v) = (f_v :: v) F (n+1 :: f_v :: v) = (fix G (0 :: n :: f_v :: v)).tail.tail prec f g (a :: v) = [(F (a :: f v :: v)).head] Because `fix` always evaluates its body at least once, we must special case the `0` case to avoid calling `g` more times than necessary (which could be bad if `g` diverges). If the input is `0 :: v`, then `F (0 :: f v :: v) = (f v :: v)` so we return `[f v]`. If the input is `n+1 :: v`, we evaluate the function from the bottom up, with initial state `0 :: n :: f v :: v`. The first number counts up, providing arguments for the applications to `g`, while the second number counts down, providing the exit condition (this is the initial `b` in the return value of `G`, which is stripped by `fix`). After the `fix` is complete, the final state is `n :: 0 :: res :: v` where `res` is the desired result, and the rest reduces this to `[res]`. -/ def prec (f g : code) : code := let G := cons tail $ cons succ $ cons (comp pred tail) $ cons (comp g $ cons id $ comp tail tail) $ comp tail $ comp tail tail in let F := case id $ comp (comp (comp tail tail) (fix G)) zero' in cons (comp F (cons head $ cons (comp f tail) tail)) nil local attribute [-simp] part.bind_eq_bind part.map_eq_map part.pure_eq_some theorem exists_code.comp {m n} {f : vector ℕ n →. ℕ} {g : fin n → vector ℕ m →. ℕ} (hf : ∃ c : code, ∀ v : vector ℕ n, c.eval v.1 = pure <$> f v) (hg : ∀ i, ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = pure <$> g i v) : ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = pure <$> (vector.m_of_fn (λ i, g i v) >>= f) := begin suffices : ∃ c : code, ∀ v : vector ℕ m, c.eval v.1 = subtype.val <$> vector.m_of_fn (λ i, g i v), { obtain ⟨cf, hf⟩ := hf, obtain ⟨cg, hg⟩ := this, exact ⟨cf.comp cg, λ v, by { simp [hg, hf, map_bind, seq_bind_eq, (∘), -subtype.val_eq_coe], refl }⟩ }, clear hf f, induction n with n IH, { exact ⟨nil, λ v, by simp [vector.m_of_fn]; refl⟩ }, { obtain ⟨cg, hg₁⟩ := hg 0, obtain ⟨cl, hl⟩ := IH (λ i, hg i.succ), exact ⟨cons cg cl, λ v, by { simp [vector.m_of_fn, hg₁, map_bind, seq_bind_eq, bind_assoc, (∘), hl, -subtype.val_eq_coe], refl }⟩ }, end theorem exists_code {n} {f : vector ℕ n →. ℕ} (hf : nat.partrec' f) : ∃ c : code, ∀ v : vector ℕ n, c.eval v.1 = pure <$> f v := begin induction hf with n f hf, induction hf, case prim zero { exact ⟨zero', λ ⟨[], _⟩, rfl⟩ }, case prim succ { exact ⟨succ, λ ⟨[v], _⟩, rfl⟩ }, case prim nth : n i { refine fin.succ_rec (λ n, _) (λ n i IH, _) i, { exact ⟨head, λ ⟨list.cons a as, _⟩, by simp; refl⟩ }, { obtain ⟨c, h⟩ := IH, exact ⟨c.comp tail, λ v, by simpa [← vector.nth_tail] using h v.tail⟩ } }, case prim comp : m n f g hf hg IHf IHg { simpa [part.bind_eq_bind] using exists_code.comp IHf IHg }, case prim prec : n f g hf hg IHf IHg { obtain ⟨cf, hf⟩ := IHf, obtain ⟨cg, hg⟩ := IHg, simp only [part.map_eq_map, part.map_some, pfun.coe_val] at hf hg, refine ⟨prec cf cg, λ v, _⟩, rw ← v.cons_head_tail, specialize hf v.tail, replace hg := λ a b, hg (a ::ᵥ b ::ᵥ v.tail), simp only [vector.cons_val, vector.tail_val] at hf hg, simp only [part.map_eq_map, part.map_some, vector.cons_val, vector.cons_tail, vector.cons_head, pfun.coe_val, vector.tail_val], simp only [← part.pure_eq_some] at hf hg ⊢, induction v.head with n IH; simp [prec, hf, bind_assoc, ← part.map_eq_map, ← bind_pure_comp_eq_map, show ∀ x, pure x = [x], from λ _, rfl, -subtype.val_eq_coe], suffices : ∀ a b, a + b = n → (n.succ :: 0 :: g (n ::ᵥ (nat.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)) n) ::ᵥ v.tail) :: v.val.tail : list ℕ) ∈ pfun.fix (λ v : list ℕ, do x ← cg.eval (v.head :: v.tail.tail), pure $ if v.tail.head = 0 then sum.inl (v.head.succ :: v.tail.head.pred :: x.head :: v.tail.tail.tail : list ℕ) else sum.inr (v.head.succ :: v.tail.head.pred :: x.head :: v.tail.tail.tail)) (a :: b :: nat.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)) a :: v.val.tail), { rw (_ : pfun.fix _ _ = pure _), swap, exact part.eq_some_iff.2 (this 0 n (zero_add n)), simp only [list.head, pure_bind, list.tail_cons] }, intros a b e, induction b with b IH generalizing a e, { refine pfun.mem_fix_iff.2 (or.inl $ part.eq_some_iff.1 _), simp only [hg, ← e, pure_bind, list.tail_cons], refl }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH (a+1) (by rwa add_right_comm)⟩), simp only [hg, eval, pure_bind, nat.elim_succ, list.tail], exact part.mem_some_iff.2 rfl } }, case comp : m n f g hf hg IHf IHg { exact exists_code.comp IHf IHg }, case rfind : n f hf IHf { obtain ⟨cf, hf⟩ := IHf, refine ⟨rfind cf, λ v, _⟩, replace hf := λ a, hf (a ::ᵥ v), simp only [part.map_eq_map, part.map_some, vector.cons_val, pfun.coe_val, show ∀ x, pure x = [x], from λ _, rfl] at hf ⊢, refine part.ext (λ x, _), simp only [rfind, part.bind_eq_bind, part.pure_eq_some, part.map_eq_map, part.bind_some, exists_prop, eval, list.head, pred_eval, part.map_some, bool.ff_eq_to_bool_iff, part.mem_bind_iff, list.length, part.mem_map_iff, nat.mem_rfind, list.tail, bool.tt_eq_to_bool_iff, part.mem_some_iff, part.map_bind], split, { rintro ⟨v', h1, rfl⟩, suffices : ∀ (v₁ : list ℕ), v' ∈ pfun.fix (λ v, (cf.eval v).bind $ λ y, part.some $ if y.head = 0 then sum.inl (v.head.succ :: v.tail) else sum.inr (v.head.succ :: v.tail)) v₁ → ∀ n, v₁ = n :: v.val → (∀ m < n, ¬f (m ::ᵥ v) = 0) → (∃ (a : ℕ), (f (a ::ᵥ v) = 0 ∧ ∀ {m : ℕ}, m < a → ¬f (m ::ᵥ v) = 0) ∧ [a] = [v'.head.pred]), { exact this _ h1 0 rfl (by rintro _ ⟨⟩) }, clear h1, intros v₀ h1, refine pfun.fix_induction h1 (λ v₁ h2 IH, _), clear h1, rintro n rfl hm, have := pfun.mem_fix_iff.1 h2, simp only [hf, part.bind_some] at this, split_ifs at this, { simp only [list.head, exists_false, or_false, part.mem_some_iff, list.tail_cons, false_and] at this, subst this, exact ⟨_, ⟨h, hm⟩, rfl⟩ }, { simp only [list.head, exists_eq_left, part.mem_some_iff, list.tail_cons, false_or] at this, refine IH _ this (by simp [hf, h, -subtype.val_eq_coe]) _ rfl (λ m h', _), obtain h|rfl := nat.lt_succ_iff_lt_or_eq.1 h', exacts [hm _ h, h] } }, { rintro ⟨n, ⟨hn, hm⟩, rfl⟩, refine ⟨n.succ :: v.1, _, rfl⟩, have : (n.succ :: v.1 : list ℕ) ∈ pfun.fix (λ v, (cf.eval v).bind $ λ y, part.some $ if y.head = 0 then sum.inl (v.head.succ :: v.tail) else sum.inr (v.head.succ :: v.tail)) (n :: v.val) := pfun.mem_fix_iff.2 (or.inl (by simp [hf, hn, -subtype.val_eq_coe])), generalize_hyp : (n.succ :: v.1 : list ℕ) = w at this ⊢, clear hn, induction n with n IH, {exact this}, refine IH (λ m h', hm (nat.lt_succ_of_lt h')) (pfun.mem_fix_iff.2 (or.inr ⟨_, _, this⟩)), simp only [hf, hm n.lt_succ_self, part.bind_some, list.head, eq_self_iff_true, if_false, part.mem_some_iff, and_self, list.tail_cons] } } end end code /-! ## From compositional semantics to sequential semantics Our initial sequential model is designed to be as similar as possible to the compositional semantics in terms of its primitives, but it is a sequential semantics, meaning that rather than defining an `eval c : list ℕ →. list ℕ` function for each program, defined by recursion on programs, we have a type `cfg` with a step function `step : cfg → option cfg` that provides a deterministic evaluation order. In order to do this, we introduce the notion of a *continuation*, which can be viewed as a `code` with a hole in it where evaluation is currently taking place. Continuations can be assigned a `list ℕ →. list ℕ` semantics as well, with the interpretation being that given a `list ℕ` result returned from the code in the hole, the remainder of the program will evaluate to a `list ℕ` final value. The continuations are: * `halt`: the empty continuation: the hole is the whole program, whatever is returned is the final result. In our notation this is just `_`. * `cons₁ fs v k`: evaluating the first part of a `cons`, that is `k (_ :: fs v)`, where `k` is the outer continuation. * `cons₂ ns k`: evaluating the second part of a `cons`: `k (ns.head :: _)`. (Technically we don't need to hold on to all of `ns` here since we are already committed to taking the head, but this is more regular.) * `comp f k`: evaluating the first part of a composition: `k (f _)`. * `fix f k`: waiting for the result of `f` in a `fix f` expression: `k (if _.head = 0 then _.tail else fix f (_.tail))` The type `cfg` of evaluation states is: * `ret k v`: we have received a result, and are now evaluating the continuation `k` with result `v`; that is, `k v` where `k` is ready to evaluate. * `halt v`: we are done and the result is `v`. The main theorem of this section is that for each code `c`, the state `step_normal c halt v` steps to `v'` in finitely many steps if and only if `code.eval c v = some v'`. -/ /-- The type of continuations, built up during evaluation of a `code` expression. -/ @[derive inhabited] inductive cont | halt | cons₁ : code → list ℕ → cont → cont | cons₂ : list ℕ → cont → cont | comp : code → cont → cont | fix : code → cont → cont /-- The semantics of a continuation. -/ def cont.eval : cont → list ℕ →. list ℕ | cont.halt := pure | (cont.cons₁ fs as k) := λ v, do ns ← code.eval fs as, cont.eval k (v.head :: ns) | (cont.cons₂ ns k) := λ v, cont.eval k (ns.head :: v) | (cont.comp f k) := λ v, code.eval f v >>= cont.eval k | (cont.fix f k) := λ v, if v.head = 0 then k.eval v.tail else f.fix.eval v.tail >>= k.eval /-- The set of configurations of the machine: * `halt v`: The machine is about to stop and `v : list ℕ` is the result. * `ret k v`: The machine is about to pass `v : list ℕ` to continuation `k : cont`. We don't have a state corresponding to normal evaluation because these are evaluated immediately to a `ret` "in zero steps" using the `step_normal` function. -/ @[derive inhabited] inductive cfg | halt : list ℕ → cfg | ret : cont → list ℕ → cfg /-- Evaluating `c : code` in a continuation `k : cont` and input `v : list ℕ`. This goes by recursion on `c`, building an augmented continuation and a value to pass to it. * `zero' v = 0 :: v` evaluates immediately, so we return it to the parent continuation * `succ v = [v.head.succ]` evaluates immediately, so we return it to the parent continuation * `tail v = v.tail` evaluates immediately, so we return it to the parent continuation * `cons f fs v = (f v).head :: fs v` requires two sub-evaluations, so we evaluate `f v` in the continuation `k (_.head :: fs v)` (called `cont.cons₁ fs v k`) * `comp f g v = f (g v)` requires two sub-evaluations, so we evaluate `g v` in the continuation `k (f _)` (called `cont.comp f k`) * `case f g v = v.head.cases_on (f v.tail) (λ n, g (n :: v.tail))` has the information needed to evaluate the case statement, so we do that and transition to either `f v` or `g (n :: v.tail)`. * `fix f v = let v' := f v in if v'.head = 0 then k v'.tail else fix f v'.tail` needs to first evaluate `f v`, so we do that and leave the rest for the continuation (called `cont.fix f k`) -/ def step_normal : code → cont → list ℕ → cfg | code.zero' k v := cfg.ret k (0 :: v) | code.succ k v := cfg.ret k [v.head.succ] | code.tail k v := cfg.ret k v.tail | (code.cons f fs) k v := step_normal f (cont.cons₁ fs v k) v | (code.comp f g) k v := step_normal g (cont.comp f k) v | (code.case f g) k v := v.head.elim (step_normal f k v.tail) (λ y _, step_normal g k (y :: v.tail)) | (code.fix f) k v := step_normal f (cont.fix f k) v /-- Evaluating a continuation `k : cont` on input `v : list ℕ`. This is the second part of evaluation, when we receive results from continuations built by `step_normal`. * `cont.halt v = v`, so we are done and transition to the `cfg.halt v` state * `cont.cons₁ fs as k v = k (v.head :: fs as)`, so we evaluate `fs as` now with the continuation `k (v.head :: _)` (called `cons₂ v k`). * `cont.cons₂ ns k v = k (ns.head :: v)`, where we now have everything we need to evaluate `ns.head :: v`, so we return it to `k`. * `cont.comp f k v = k (f v)`, so we call `f v` with `k` as the continuation. * `cont.fix f k v = k (if v.head = 0 then k v.tail else fix f v.tail)`, where `v` is a value, so we evaluate the if statement and either call `k` with `v.tail`, or call `fix f v` with `k` as the continuation (which immediately calls `f` with `cont.fix f k` as the continuation). -/ def step_ret : cont → list ℕ → cfg | cont.halt v := cfg.halt v | (cont.cons₁ fs as k) v := step_normal fs (cont.cons₂ v k) as | (cont.cons₂ ns k) v := step_ret k (ns.head :: v) | (cont.comp f k) v := step_normal f k v | (cont.fix f k) v := if v.head = 0 then step_ret k v.tail else step_normal f (cont.fix f k) v.tail /-- If we are not done (in `cfg.halt` state), then we must be still stuck on a continuation, so this main loop calls `step_ret` with the new continuation. The overall `step` function transitions from one `cfg` to another, only halting at the `cfg.halt` state. -/ def step : cfg → option cfg | (cfg.halt _) := none | (cfg.ret k v) := some (step_ret k v) /-- In order to extract a compositional semantics from the sequential execution behavior of configurations, we observe that continuations have a monoid structure, with `cont.halt` as the unit and `cont.then` as the multiplication. `cont.then k₁ k₂` runs `k₁` until it halts, and then takes the result of `k₁` and passes it to `k₂`. We will not prove it is associative (although it is), but we are instead interested in the associativity law `k₂ (eval c k₁) = eval c (k₁.then k₂)`. This holds at both the sequential and compositional levels, and allows us to express running a machine without the ambient continuation and relate it to the original machine's evaluation steps. In the literature this is usually where one uses Turing machines embedded inside other Turing machines, but this approach allows us to avoid changing the ambient type `cfg` in the middle of the recursion. -/ def cont.then : cont → cont → cont | cont.halt k' := k' | (cont.cons₁ fs as k) k' := cont.cons₁ fs as (k.then k') | (cont.cons₂ ns k) k' := cont.cons₂ ns (k.then k') | (cont.comp f k) k' := cont.comp f (k.then k') | (cont.fix f k) k' := cont.fix f (k.then k') theorem cont.then_eval {k k' : cont} {v} : (k.then k').eval v = k.eval v >>= k'.eval := begin induction k generalizing v; simp only [cont.eval, cont.then, bind_assoc, pure_bind, *], { simp only [← k_ih] }, { split_ifs; [refl, simp only [← k_ih, bind_assoc]] } end /-- The `then k` function is a "configuration homomorphism". Its operation on states is to append `k` to the continuation of a `cfg.ret` state, and to run `k` on `v` if we are in the `cfg.halt v` state. -/ def cfg.then : cfg → cont → cfg | (cfg.halt v) k' := step_ret k' v | (cfg.ret k v) k' := cfg.ret (k.then k') v /-- The `step_normal` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem step_normal_then (c) (k k' : cont) (v) : step_normal c (k.then k') v = (step_normal c k v).then k' := begin induction c with generalizing k v; simp only [cont.then, step_normal, cfg.then, *] {constructor_eq := ff}, case turing.to_partrec.code.cons : c c' ih ih' { rw [← ih, cont.then] }, case turing.to_partrec.code.comp : c c' ih ih' { rw [← ih', cont.then] }, { cases v.head; simp only [nat.elim] }, case turing.to_partrec.code.fix : c ih { rw [← ih, cont.then] }, end /-- The `step_ret` function respects the `then k'` homomorphism. Note that this is an exact equality, not a simulation; the original and embedded machines move in lock-step until the embedded machine reaches the halt state. -/ theorem step_ret_then {k k' : cont} {v} : step_ret (k.then k') v = (step_ret k v).then k' := begin induction k generalizing v; simp only [cont.then, step_ret, cfg.then, *], { rw ← step_normal_then, refl }, { rw ← step_normal_then }, { split_ifs, {rw ← k_ih}, {rw ← step_normal_then, refl} }, end /-- This is a temporary definition, because we will prove in `code_is_ok` that it always holds. It asserts that `c` is semantically correct; that is, for any `k` and `v`, `eval (step_normal c k v) = eval (cfg.ret k (code.eval c v))`, as an equality of partial values (so one diverges iff the other does). In particular, we can let `k = cont.halt`, and then this asserts that `step_normal c cont.halt v` evaluates to `cfg.halt (code.eval c v)`. -/ def code.ok (c : code) := ∀ k v, eval step (step_normal c k v) = code.eval c v >>= λ v, eval step (cfg.ret k v) theorem code.ok.zero {c} (h : code.ok c) {v} : eval step (step_normal c cont.halt v) = cfg.halt <$> code.eval c v := begin rw [h, ← bind_pure_comp_eq_map], congr, funext v, exact part.eq_some_iff.2 (mem_eval.2 ⟨refl_trans_gen.single rfl, rfl⟩), end theorem step_normal.is_ret (c k v) : ∃ k' v', step_normal c k v = cfg.ret k' v' := begin induction c generalizing k v, iterate 3 { exact ⟨_, _, rfl⟩ }, case cons : f fs IHf IHfs { apply IHf }, case comp : f g IHf IHg { apply IHg }, case case : f g IHf IHg { rw step_normal, cases v.head; simp only [nat.elim]; [apply IHf, apply IHg] }, case fix : f IHf { apply IHf }, end theorem cont_eval_fix {f k v} (fok : code.ok f) : eval step (step_normal f (cont.fix f k) v) = f.fix.eval v >>= λ v, eval step (cfg.ret k v) := begin refine part.ext (λ x, _), simp only [part.bind_eq_bind, part.mem_bind_iff], split, { suffices : ∀ c, x ∈ eval step c → ∀ v c', c = cfg.then c' (cont.fix f k) → reaches step (step_normal f cont.halt v) c' → ∃ v₁ ∈ f.eval v, ∃ v₂ ∈ (if list.head v₁ = 0 then pure v₁.tail else f.fix.eval v₁.tail), x ∈ eval step (cfg.ret k v₂), { intro h, obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ := this _ h _ _ (step_normal_then _ cont.halt _ _) refl_trans_gen.refl, refine ⟨v₂, pfun.mem_fix_iff.2 _, h₃⟩, simp only [part.eq_some_iff.2 hv₁, part.map_some], split_ifs at hv₂ ⊢, { rw part.mem_some_iff.1 hv₂, exact or.inl (part.mem_some _) }, { exact or.inr ⟨_, part.mem_some _, hv₂⟩ } }, refine λ c he, eval_induction he (λ y h IH, _), rintro v (⟨v'⟩ | ⟨k',v'⟩) rfl hr; rw cfg.then at h IH, { have := mem_eval.2 ⟨hr, rfl⟩, rw [fok, part.bind_eq_bind, part.mem_bind_iff] at this, obtain ⟨v'', h₁, h₂⟩ := this, rw reaches_eval at h₂, swap, exact refl_trans_gen.single rfl, cases part.mem_unique h₂ (mem_eval.2 ⟨refl_trans_gen.refl, rfl⟩), refine ⟨v', h₁, _⟩, rw [step_ret] at h, revert h, by_cases he : v'.head = 0; simp only [exists_prop, if_pos, if_false, he]; intro h, { refine ⟨_, part.mem_some _, _⟩, rw reaches_eval, exact h, exact refl_trans_gen.single rfl }, { obtain ⟨k₀, v₀, e₀⟩ := step_normal.is_ret f cont.halt v'.tail, have e₁ := step_normal_then f cont.halt (cont.fix f k) v'.tail, rw [e₀, cont.then, cfg.then] at e₁, obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ := IH (step_ret (k₀.then (cont.fix f k)) v₀) _ _ v'.tail _ step_ret_then _, { refine ⟨_, pfun.mem_fix_iff.2 _, h₃⟩, simp only [part.eq_some_iff.2 hv₁, part.map_some, part.mem_some_iff], split_ifs at hv₂ ⊢; [exact or.inl (part.mem_some_iff.1 hv₂), exact or.inr ⟨_, rfl, hv₂⟩] }, { rwa [← @reaches_eval _ _ (cfg.ret (k₀.then (cont.fix f k)) v₀), ← e₁], exact refl_trans_gen.single rfl }, { rw [step_ret, if_neg he, e₁], refl }, { apply refl_trans_gen.single, rw e₀, exact rfl } } }, { rw reaches_eval at h, swap, exact refl_trans_gen.single rfl, exact IH _ h rfl _ _ step_ret_then (refl_trans_gen.tail hr rfl) } }, { rintro ⟨v', he, hr⟩, rw reaches_eval at hr, swap, exact refl_trans_gen.single rfl, refine pfun.fix_induction he (λ v (he : v' ∈ f.fix.eval v) IH, _), rw [fok, part.bind_eq_bind, part.mem_bind_iff], obtain he | ⟨v'', he₁', he₂'⟩ := pfun.mem_fix_iff.1 he, { obtain ⟨v', he₁, he₂⟩ := (part.mem_map_iff _).1 he, split_ifs at he₂; cases he₂, refine ⟨_, he₁, _⟩, rw reaches_eval, swap, exact refl_trans_gen.single rfl, rwa [step_ret, if_pos h] }, { obtain ⟨v₁, he₁, he₂⟩ := (part.mem_map_iff _).1 he₁', split_ifs at he₂; cases he₂, clear he₂ he₁', change _ ∈ f.fix.eval _ at he₂', refine ⟨_, he₁, _⟩, rw reaches_eval, swap, exact refl_trans_gen.single rfl, rwa [step_ret, if_neg h], exact IH v₁.tail he₂' ((part.mem_map_iff _).2 ⟨_, he₁, if_neg h⟩) } } end theorem code_is_ok (c) : code.ok c := begin induction c; intros k v; rw step_normal, iterate 3 { simp only [code.eval, pure_bind] }, case cons : f fs IHf IHfs { rw [code.eval, IHf], simp only [bind_assoc, cont.eval, pure_bind], congr, funext v, rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IHfs], congr, funext v', refine eq.trans _ (eq.symm _); try {exact reaches_eval (refl_trans_gen.single rfl)} }, case comp : f g IHf IHg { rw [code.eval, IHg], simp only [bind_assoc, cont.eval, pure_bind], congr, funext v, rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IHf] }, case case : f g IHf IHg { simp only [code.eval], cases v.head; simp only [nat.elim, code.eval]; [apply IHf, apply IHg] }, case fix : f IHf { rw cont_eval_fix IHf }, end theorem step_normal_eval (c v) : eval step (step_normal c cont.halt v) = cfg.halt <$> c.eval v := (code_is_ok c).zero theorem step_ret_eval {k v} : eval step (step_ret k v) = cfg.halt <$> k.eval v := begin induction k generalizing v, case halt : { simp only [mem_eval, cont.eval, map_pure], exact part.eq_some_iff.2 (mem_eval.2 ⟨refl_trans_gen.refl, rfl⟩) }, case cons₁ : fs as k IH { rw [cont.eval, step_ret, code_is_ok], simp only [← bind_pure_comp_eq_map, bind_assoc], congr, funext v', rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [step_ret, IH, bind_pure_comp_eq_map] }, case cons₂ : ns k IH { rw [cont.eval, step_ret], exact IH }, case comp : f k IH { rw [cont.eval, step_ret, code_is_ok], simp only [← bind_pure_comp_eq_map, bind_assoc], congr, funext v', rw [reaches_eval], swap, exact refl_trans_gen.single rfl, rw [IH, bind_pure_comp_eq_map] }, case fix : f k IH { rw [cont.eval, step_ret], simp only [bind_pure_comp_eq_map], split_ifs, { exact IH }, simp only [← bind_pure_comp_eq_map, bind_assoc, cont_eval_fix (code_is_ok _)], congr, funext, rw [bind_pure_comp_eq_map, ← IH], exact reaches_eval (refl_trans_gen.single rfl) }, end end to_partrec /-! ## Simulating sequentialized partial recursive functions in TM2 At this point we have a sequential model of partial recursive functions: the `cfg` type and `step : cfg → option cfg` function from the previous section. The key feature of this model is that it does a finite amount of computation (in fact, an amount which is statically bounded by the size of the program) between each step, and no individual step can diverge (unlike the compositional semantics, where every sub-part of the computation is potentially divergent). So we can utilize the same techniques as in the other TM simulations in `computability.turing_machine` to prove that each step corresponds to a finite number of steps in a lower level model. (We don't prove it here, but in anticipation of the complexity class P, the simulation is actually polynomial-time as well.) The target model is `turing.TM2`, which has a fixed finite set of stacks, a bit of local storage, with programs selected from a potentially infinite (but finitely accessible) set of program positions, or labels `Λ`, each of which executes a finite sequence of basic stack commands. For this program we will need four stacks, each on an alphabet `Γ'` like so: inductive Γ' | Cons | cons | bit0 | bit1 We represent a number as a bit sequence, lists of numbers by putting `cons` after each element, and lists of lists of natural numbers by putting `Cons` after each list. For example: 0 ~> [] 1 ~> [bit1] 6 ~> [bit0, bit1, bit1] [1, 2] ~> [bit1, cons, bit0, bit1, cons] [[], [1, 2]] ~> [Cons, bit1, cons, bit0, bit1, cons, Cons] The four stacks are `main`, `rev`, `aux`, `stack`. In normal mode, `main` contains the input to the current program (a `list ℕ`) and `stack` contains data (a `list (list ℕ)`) associated to the current continuation, and in `ret` mode `main` contains the value that is being passed to the continuation and `stack` contains the data for the continuation. The `rev` and `aux` stacks are usually empty; `rev` is used to store reversed data when e.g. moving a value from one stack to another, while `aux` is used as a temporary for a `main`/`stack` swap that happens during `cons₁` evaluation. The only local store we need is `option Γ'`, which stores the result of the last pop operation. (Most of our working data are natural numbers, which are too large to fit in the local store.) The continuations from the previous section are data-carrying, containing all the values that have been computed and are awaiting other arguments. In order to have only a finite number of continuations appear in the program so that they can be used in machine states, we separate the data part (anything with type `list ℕ`) from the `cont` type, producing a `cont'` type that lacks this information. The data is kept on the `stack` stack. Because we want to have subroutines for e.g. moving an entire stack to another place, we use an infinite inductive type `Λ'` so that we can execute a program and then return to do something else without having to define too many different kinds of intermediate states. (We must nevertheless prove that only finitely many labels are accessible.) The labels are: * `move p k₁ k₂ q`: move elements from stack `k₁` to `k₂` while `p` holds of the value being moved. The last element, that fails `p`, is placed in neither stack but left in the local store. At the end of the operation, `k₂` will have the elements of `k₁` in reverse order. Then do `q`. * `clear p k q`: delete elements from stack `k` until `p` is true. Like `move`, the last element is left in the local storage. Then do `q`. * `copy q`: Move all elements from `rev` to both `main` and `stack` (in reverse order), then do `q`. That is, it takes `(a, b, c, d)` to `(b.reverse ++ a, [], c, b.reverse ++ d)`. * `push k f q`: push `f s`, where `s` is the local store, to stack `k`, then do `q`. This is a duplicate of the `push` instruction that is part of the TM2 model, but by having a subroutine just for this purpose we can build up programs to execute inside a `goto` statement, where we have the flexibility to be general recursive. * `read (f : option Γ' → Λ')`: go to state `f s` where `s` is the local store. Again this is only here for convenience. * `succ q`: perform a successor operation. Assuming `[n]` is encoded on `main` before, `[n+1]` will be on main after. This implements successor for binary natural numbers. * `pred q₁ q₂`: perform a predecessor operation or `case` statement. If `[]` is encoded on `main` before, then we transition to `q₁` with `[]` on main; if `(0 :: v)` is on `main` before then `v` will be on `main` after and we transition to `q₁`; and if `(n+1 :: v)` is on `main` before then `n :: v` will be on `main` after and we transition to `q₂`. * `ret k`: call continuation `k`. Each continuation has its own interpretation of the data in `stack` and sets up the data for the next continuation. * `ret (cons₁ fs k)`: `v :: k_data` on `stack` and `ns` on `main`, and the next step expects `v` on `main` and `ns :: k_data` on `stack`. So we have to do a little dance here with six reverse-moves using the `aux` stack to perform a three-point swap, each of which involves two reversals. * `ret (cons₂ k)`: `ns :: k_data` is on `stack` and `v` is on `main`, and we have to put `ns.head :: v` on `main` and `k_data` on `stack`. This is done using the `head` subroutine. * `ret (fix f k)`: This stores no data, so we just check if `main` starts with `0` and if so, remove it and call `k`, otherwise `clear` the first value and call `f`. * `ret halt`: the stack is empty, and `main` has the output. Do nothing and halt. In addition to these basic states, we define some additional subroutines that are used in the above: * `push'`, `peek'`, `pop'` are special versions of the builtins that use the local store to supply inputs and outputs. * `unrev`: special case `move ff rev main` to move everything from `rev` back to `main`. Used as a cleanup operation in several functions. * `move_excl p k₁ k₂ q`: same as `move` but pushes the last value read back onto the source stack. * `move₂ p k₁ k₂ q`: double `move`, so that the result comes out in the right order at the target stack. Implemented as `move_excl p k rev; move ff rev k₂`. Assumes that neither `k₁` nor `k₂` is `rev` and `rev` is initially empty. * `head k q`: get the first natural number from stack `k` and reverse-move it to `rev`, then clear the rest of the list at `k` and then `unrev` to reverse-move the head value to `main`. This is used with `k = main` to implement regular `head`, i.e. if `v` is on `main` before then `[v.head]` will be on `main` after; and also with `k = stack` for the `cons` operation, which has `v` on `main` and `ns :: k_data` on `stack`, and results in `k_data` on `stack` and `ns.head :: v` on `main`. * `tr_normal` is the main entry point, defining states that perform a given `code` computation. It mostly just dispatches to functions written above. The main theorem of this section is `tr_eval`, which asserts that for each that for each code `c`, the state `init c v` steps to `halt v'` in finitely many steps if and only if `code.eval c v = some v'`. -/ namespace partrec_to_TM2 section open to_partrec /-- The alphabet for the stacks in the program. `bit0` and `bit1` are used to represent `ℕ` values as lists of binary digits, `cons` is used to separate `list ℕ` values, and `Cons` is used to separate `list (list ℕ)` values. See the section documentation. -/ @[derive [decidable_eq, inhabited, fintype]] inductive Γ' | Cons | cons | bit0 | bit1 /-- The four stacks used by the program. `main` is used to store the input value in `tr_normal` mode and the output value in `Λ'.ret` mode, while `stack` is used to keep all the data for the continuations. `rev` is used to store reversed lists when transferring values between stacks, and `aux` is only used once in `cons₁`. See the section documentation. -/ @[derive [decidable_eq, inhabited]] inductive K' | main | rev | aux | stack open K' /-- Continuations as in `to_partrec.cont` but with the data removed. This is done because we want the set of all continuations in the program to be finite (so that it can ultimately be encoded into the finite state machine of a Turing machine), but a continuation can handle a potentially infinite number of data values during execution. -/ @[derive [decidable_eq, inhabited]] inductive cont' | halt | cons₁ : code → cont' → cont' | cons₂ : cont' → cont' | comp : code → cont' → cont' | fix : code → cont' → cont' /-- The set of program positions. We make extensive use of inductive types here to let us describe "subroutines"; for example `clear p k q` is a program that clears stack `k`, then does `q` where `q` is another label. In order to prevent this from resulting in an infinite number of distinct accessible states, we are careful to be non-recursive (although loops are okay). See the section documentation for a description of all the programs. -/ inductive Λ' | move (p : Γ' → bool) (k₁ k₂ : K') (q : Λ') | clear (p : Γ' → bool) (k : K') (q : Λ') | copy (q : Λ') | push (k : K') (s : option Γ' → option Γ') (q : Λ') | read (f : option Γ' → Λ') | succ (q : Λ') | pred (q₁ q₂ : Λ') | ret (k : cont') instance : inhabited Λ' := ⟨Λ'.ret cont'.halt⟩ instance : decidable_eq Λ' := λ a b, begin induction a generalizing b; cases b; try { apply decidable.is_false, rintro ⟨⟨⟩⟩, done }, all_goals { exactI decidable_of_iff' _ (by simp [function.funext_iff]) }, end /-- The type of TM2 statements used by this machine. -/ @[derive inhabited] def stmt' := TM2.stmt (λ _:K', Γ') Λ' (option Γ') /-- The type of TM2 configurations used by this machine. -/ @[derive inhabited] def cfg' := TM2.cfg (λ _:K', Γ') Λ' (option Γ') open TM2.stmt /-- A predicate that detects the end of a natural number, either `Γ'.cons` or `Γ'.Cons` (or implicitly the end of the list), for use in predicate-taking functions like `move` and `clear`. -/ def nat_end : Γ' → bool | Γ'.Cons := tt | Γ'.cons := tt | _ := ff /-- Pop a value from the stack and place the result in local store. -/ @[simp] def pop' (k : K') : stmt' → stmt' := pop k (λ x v, v) /-- Peek a value from the stack and place the result in local store. -/ @[simp] def peek' (k : K') : stmt' → stmt' := peek k (λ x v, v) /-- Push the value in the local store to the given stack. -/ @[simp] def push' (k : K') : stmt' → stmt' := push k (λ x, x.iget) /-- Move everything from the `rev` stack to the `main` stack (reversed). -/ def unrev := Λ'.move (λ _, ff) rev main /-- Move elements from `k₁` to `k₂` while `p` holds, with the last element being left on `k₁`. -/ def move_excl (p k₁ k₂ q) := Λ'.move p k₁ k₂ $ Λ'.push k₁ id q /-- Move elements from `k₁` to `k₂` without reversion, by performing a double move via the `rev` stack. -/ def move₂ (p k₁ k₂ q) := move_excl p k₁ rev $ Λ'.move (λ _, ff) rev k₂ q /-- Assuming `tr_list v` is on the front of stack `k`, remove it, and push `v.head` onto `main`. See the section documentation. -/ def head (k : K') (q : Λ') : Λ' := Λ'.move nat_end k rev $ Λ'.push rev (λ _, some Γ'.cons) $ Λ'.read $ λ s, (if s = some Γ'.Cons then id else Λ'.clear (λ x, x = Γ'.Cons) k) $ unrev q /-- The program that evaluates code `c` with continuation `k`. This expects an initial state where `tr_list v` is on `main`, `tr_cont_stack k` is on `stack`, and `aux` and `rev` are empty. See the section documentation for details. -/ @[simp] def tr_normal : code → cont' → Λ' | code.zero' k := Λ'.push main (λ _, some Γ'.cons) $ Λ'.ret k | code.succ k := head main $ Λ'.succ $ Λ'.ret k | code.tail k := Λ'.clear nat_end main $ Λ'.ret k | (code.cons f fs) k := Λ'.push stack (λ _, some Γ'.Cons) $ Λ'.move (λ _, ff) main rev $ Λ'.copy $ tr_normal f (cont'.cons₁ fs k) | (code.comp f g) k := tr_normal g (cont'.comp f k) | (code.case f g) k := Λ'.pred (tr_normal f k) (tr_normal g k) | (code.fix f) k := tr_normal f (cont'.fix f k) /-- The main program. See the section documentation for details. -/ @[simp] def tr : Λ' → stmt' | (Λ'.move p k₁ k₂ q) := pop' k₁ $ branch (λ s, s.elim tt p) ( goto $ λ _, q ) ( push' k₂ $ goto $ λ _, Λ'.move p k₁ k₂ q ) | (Λ'.push k f q) := branch (λ s, (f s).is_some) ( push k (λ s, (f s).iget) $ goto $ λ _, q ) ( goto $ λ _, q ) | (Λ'.read q) := goto q | (Λ'.clear p k q) := pop' k $ branch (λ s, s.elim tt p) ( goto $ λ _, q ) ( goto $ λ _, Λ'.clear p k q ) | (Λ'.copy q) := pop' rev $ branch option.is_some ( push' main $ push' stack $ goto $ λ _, Λ'.copy q ) ( goto $ λ _, q ) | (Λ'.succ q) := pop' main $ branch (λ s, s = some Γ'.bit1) ( push rev (λ _, Γ'.bit0) $ goto $ λ _, Λ'.succ q ) $ branch (λ s, s = some Γ'.cons) ( push main (λ _, Γ'.cons) $ push main (λ _, Γ'.bit1) $ goto $ λ _, unrev q ) ( push main (λ _, Γ'.bit1) $ goto $ λ _, unrev q ) | (Λ'.pred q₁ q₂) := pop' main $ branch (λ s, s = some Γ'.bit0) ( push rev (λ _, Γ'.bit1) $ goto $ λ _, Λ'.pred q₁ q₂ ) $ branch (λ s, nat_end s.iget) ( goto $ λ _, q₁ ) ( peek' main $ branch (λ s, nat_end s.iget) ( goto $ λ _, unrev q₂ ) ( push rev (λ _, Γ'.bit0) $ goto $ λ _, unrev q₂ ) ) | (Λ'.ret (cont'.cons₁ fs k)) := goto $ λ _, move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k) | (Λ'.ret (cont'.cons₂ k)) := goto $ λ _, head stack $ Λ'.ret k | (Λ'.ret (cont'.comp f k)) := goto $ λ _, tr_normal f k | (Λ'.ret (cont'.fix f k)) := pop' main $ goto $ λ s, cond (nat_end s.iget) (Λ'.ret k) $ Λ'.clear nat_end main $ tr_normal f (cont'.fix f k) | (Λ'.ret cont'.halt) := load (λ _, none) $ halt /-- Translating a `cont` continuation to a `cont'` continuation simply entails dropping all the data. This data is instead encoded in `tr_cont_stack` in the configuration. -/ def tr_cont : cont → cont' | cont.halt := cont'.halt | (cont.cons₁ c _ k) := cont'.cons₁ c (tr_cont k) | (cont.cons₂ _ k) := cont'.cons₂ (tr_cont k) | (cont.comp c k) := cont'.comp c (tr_cont k) | (cont.fix c k) := cont'.fix c (tr_cont k) /-- We use `pos_num` to define the translation of binary natural numbers. A natural number is represented as a little-endian list of `bit0` and `bit1` elements: 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] In particular, this representation guarantees no trailing `bit0`'s at the end of the list. -/ def tr_pos_num : pos_num → list Γ' | pos_num.one := [Γ'.bit1] | (pos_num.bit0 n) := Γ'.bit0 :: tr_pos_num n | (pos_num.bit1 n) := Γ'.bit1 :: tr_pos_num n /-- We use `num` to define the translation of binary natural numbers. Positive numbers are translated using `tr_pos_num`, and `tr_num 0 = []`. So there are never any trailing `bit0`'s in a translated `num`. 0 = [] 1 = [bit1] 2 = [bit0, bit1] 3 = [bit1, bit1] 4 = [bit0, bit0, bit1] -/ def tr_num : num → list Γ' | num.zero := [] | (num.pos n) := tr_pos_num n /-- Because we use binary encoding, we define `tr_nat` in terms of `tr_num`, using `num`, which are binary natural numbers. (We could also use `nat.binary_rec_on`, but `num` and `pos_num` make for easy inductions.) -/ def tr_nat (n : ℕ) : list Γ' := tr_num n @[simp] theorem tr_nat_zero : tr_nat 0 = [] := rfl /-- Lists are translated with a `cons` after each encoded number. For example: [] = [] [0] = [cons] [1] = [bit1, cons] [6, 0] = [bit0, bit1, bit1, cons, cons] -/ @[simp] def tr_list : list ℕ → list Γ' | [] := [] | (n :: ns) := tr_nat n ++ Γ'.cons :: tr_list ns /-- Lists of lists are translated with a `Cons` after each encoded list. For example: [] = [] [[]] = [Cons] [[], []] = [Cons, Cons] [[0]] = [cons, Cons] [[1, 2], [0]] = [bit1, cons, bit0, bit1, cons, Cons, cons, Cons] -/ @[simp] def tr_llist : list (list ℕ) → list Γ' | [] := [] | (l :: ls) := tr_list l ++ Γ'.Cons :: tr_llist ls /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `tr_llist`. -/ @[simp] def cont_stack : cont → list (list ℕ) | cont.halt := [] | (cont.cons₁ _ ns k) := ns :: cont_stack k | (cont.cons₂ ns k) := ns :: cont_stack k | (cont.comp _ k) := cont_stack k | (cont.fix _ k) := cont_stack k /-- The data part of a continuation is a list of lists, which is encoded on the `stack` stack using `tr_llist`. -/ def tr_cont_stack (k : cont) := tr_llist (cont_stack k) /-- This is the nondependent eliminator for `K'`, but we use it specifically here in order to represent the stack data as four lists rather than as a function `K' → list Γ'`, because this makes rewrites easier. The theorems `K'.elim_update_main` et. al. show how such a function is updated after an `update` to one of the components. -/ @[simp] def K'.elim (a b c d : list Γ') : K' → list Γ' | K'.main := a | K'.rev := b | K'.aux := c | K'.stack := d @[simp] theorem K'.elim_update_main {a b c d a'} : update (K'.elim a b c d) main a' = K'.elim a' b c d := by funext x; cases x; refl @[simp] theorem K'.elim_update_rev {a b c d b'} : update (K'.elim a b c d) rev b' = K'.elim a b' c d := by funext x; cases x; refl @[simp] theorem K'.elim_update_aux {a b c d c'} : update (K'.elim a b c d) aux c' = K'.elim a b c' d := by funext x; cases x; refl @[simp] theorem K'.elim_update_stack {a b c d d'} : update (K'.elim a b c d) stack d' = K'.elim a b c d' := by funext x; cases x; refl /-- The halting state corresponding to a `list ℕ` output value. -/ def halt (v : list ℕ) : cfg' := ⟨none, none, K'.elim (tr_list v) [] [] []⟩ /-- The `cfg` states map to `cfg'` states almost one to one, except that in normal operation the local store contains an arbitrary garbage value. To make the final theorem cleaner we explicitly clear it in the halt state so that there is exactly one configuration corresponding to output `v`. -/ def tr_cfg : cfg → cfg' → Prop | (cfg.ret k v) c' := ∃ s, c' = ⟨some (Λ'.ret (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ | (cfg.halt v) c' := c' = halt v /-- This could be a general list definition, but it is also somewhat specialized to this application. `split_at_pred p L` will search `L` for the first element satisfying `p`. If it is found, say `L = l₁ ++ a :: l₂` where `a` satisfies `p` but `l₁` does not, then it returns `(l₁, some a, l₂)`. Otherwise, if there is no such element, it returns `(L, none, [])`. -/ def split_at_pred {α} (p : α → bool) : list α → list α × option α × list α | [] := ([], none, []) | (a :: as) := cond (p a) ([], some a, as) $ let ⟨l₁, o, l₂⟩ := split_at_pred as in ⟨a :: l₁, o, l₂⟩ theorem split_at_pred_eq {α} (p : α → bool) : ∀ L l₁ o l₂, (∀ x ∈ l₁, p x = ff) → option.elim o (L = l₁ ∧ l₂ = []) (λ a, p a = tt ∧ L = l₁ ++ a :: l₂) → split_at_pred p L = (l₁, o, l₂) | [] _ none _ _ ⟨rfl, rfl⟩ := rfl | [] l₁ (some o) l₂ h₁ ⟨h₂, h₃⟩ := by simp at h₃; contradiction | (a :: L) l₁ o l₂ h₁ h₂ := begin rw [split_at_pred], have IH := split_at_pred_eq L, cases o, { cases l₁ with a' l₁; rcases h₂ with ⟨⟨⟩, rfl⟩, rw [h₁ a (or.inl rfl), cond, IH L none [] _ ⟨rfl, rfl⟩], refl, exact λ x h, h₁ x (or.inr h) }, { cases l₁ with a' l₁; rcases h₂ with ⟨h₂, ⟨⟩⟩, {rw [h₂, cond]}, rw [h₁ a (or.inl rfl), cond, IH l₁ (some o) l₂ _ ⟨h₂, _⟩]; try {refl}, exact λ x h, h₁ x (or.inr h) }, end theorem split_at_pred_ff {α} (L : list α) : split_at_pred (λ _, ff) L = (L, none, []) := split_at_pred_eq _ _ _ _ _ (λ _ _, rfl) ⟨rfl, rfl⟩ theorem move_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → list Γ'} (h₁ : k₁ ≠ k₂) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (Λ'.move p k₁ k₂ q), s, S⟩ ⟨some q, o, update (update S k₁ L₂) k₂ (L₁.reverse_core (S k₂))⟩ := begin induction L₁ with a L₁ IH generalizing S s, { rw [(_ : [].reverse_core _ = _), function.update_eq_self], swap, { rw function.update_noteq h₁.symm, refl }, refine trans_gen.head' rfl _, simp, cases S k₁ with a Sk, {cases e, refl}, simp [split_at_pred] at e ⊢, cases p a; simp at e ⊢, { revert e, rcases split_at_pred p Sk with ⟨_, _, _⟩, rintro ⟨⟩ }, { simp only [e] } }, { refine trans_gen.head rfl _, simp, cases e₁ : S k₁ with a' Sk; rw [e₁, split_at_pred] at e, {cases e}, cases e₂ : p a'; simp only [e₂, cond] at e, swap, {cases e}, rcases e₃ : split_at_pred p Sk with ⟨_, _, _⟩, rw [e₃, split_at_pred] at e, cases e, simp [e₂], convert @IH (update (update S k₁ Sk) k₂ (a :: S k₂)) _ _ using 2; simp [function.update_noteq, h₁, h₁.symm, e₃, list.reverse_core], simp [function.update_comm h₁.symm] } end theorem unrev_ok {q s} {S : K' → list Γ'} : reaches₁ (TM2.step tr) ⟨some (unrev q), s, S⟩ ⟨some q, none, update (update S rev []) main (list.reverse_core (S rev) (S main))⟩ := move_ok dec_trivial $ split_at_pred_ff _ theorem move₂_ok {p k₁ k₂ q s L₁ o L₂} {S : K' → list Γ'} (h₁ : k₁ ≠ rev ∧ k₂ ≠ rev ∧ k₁ ≠ k₂) (h₂ : S rev = []) (e : split_at_pred p (S k₁) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (move₂ p k₁ k₂ q), s, S⟩ ⟨some q, none, update (update S k₁ (o.elim id list.cons L₂)) k₂ (L₁ ++ S k₂)⟩ := begin refine (move_ok h₁.1 e).trans (trans_gen.head rfl _), cases o; simp only [option.elim, tr, id.def], { convert move_ok h₁.2.1.symm (split_at_pred_ff _) using 2, simp only [function.update_comm h₁.1, function.update_idem], rw show update S rev [] = S, by rw [← h₂, function.update_eq_self], simp only [function.update_noteq h₁.2.2.symm, function.update_noteq h₁.2.1, function.update_noteq h₁.1.symm, list.reverse_core_eq, h₂, function.update_same, list.append_nil, list.reverse_reverse] }, { convert move_ok h₁.2.1.symm (split_at_pred_ff _) using 2, simp only [h₂, function.update_comm h₁.1, list.reverse_core_eq, function.update_same, list.append_nil, function.update_idem], rw show update S rev [] = S, by rw [← h₂, function.update_eq_self], simp only [function.update_noteq h₁.1.symm, function.update_noteq h₁.2.2.symm, function.update_noteq h₁.2.1, function.update_same, list.reverse_reverse] }, end theorem clear_ok {p k q s L₁ o L₂} {S : K' → list Γ'} (e : split_at_pred p (S k) = (L₁, o, L₂)) : reaches₁ (TM2.step tr) ⟨some (Λ'.clear p k q), s, S⟩ ⟨some q, o, update S k L₂⟩ := begin induction L₁ with a L₁ IH generalizing S s, { refine trans_gen.head' rfl _, simp, cases S k with a Sk, {cases e, refl}, simp [split_at_pred] at e ⊢, cases p a; simp at e ⊢, { revert e, rcases split_at_pred p Sk with ⟨_, _, _⟩, rintro ⟨⟩ }, { simp only [e] } }, { refine trans_gen.head rfl _, simp, cases e₁ : S k with a' Sk; rw [e₁, split_at_pred] at e, {cases e}, cases e₂ : p a'; simp only [e₂, cond] at e, swap, {cases e}, rcases e₃ : split_at_pred p Sk with ⟨_, _, _⟩, rw [e₃, split_at_pred] at e, cases e, simp [e₂], convert @IH (update S k Sk) _ _ using 2; simp [e₃] } end theorem copy_ok (q s a b c d) : reaches₁ (TM2.step tr) ⟨some (Λ'.copy q), s, K'.elim a b c d⟩ ⟨some q, none, K'.elim (list.reverse_core b a) [] c (list.reverse_core b d)⟩ := begin induction b with x b IH generalizing a d s, { refine trans_gen.single _, simp, refl }, refine trans_gen.head rfl _, simp, exact IH _ _ _, end theorem tr_pos_num_nat_end : ∀ n (x ∈ tr_pos_num n), nat_end x = ff | pos_num.one _ (or.inl rfl) := rfl | (pos_num.bit0 n) _ (or.inl rfl) := rfl | (pos_num.bit0 n) _ (or.inr h) := tr_pos_num_nat_end n _ h | (pos_num.bit1 n) _ (or.inl rfl) := rfl | (pos_num.bit1 n) _ (or.inr h) := tr_pos_num_nat_end n _ h theorem tr_num_nat_end : ∀ n (x ∈ tr_num n), nat_end x = ff | (num.pos n) x h := tr_pos_num_nat_end n x h theorem tr_nat_nat_end (n) : ∀ x ∈ tr_nat n, nat_end x = ff := tr_num_nat_end _ theorem tr_list_ne_Cons : ∀ l (x ∈ tr_list l), x ≠ Γ'.Cons | (a :: l) x h := begin simp [tr_list] at h, obtain h | rfl | h := h, { rintro rfl, cases tr_nat_nat_end _ _ h }, { rintro ⟨⟩ }, { exact tr_list_ne_Cons l _ h } end theorem head_main_ok {q s L} {c d : list Γ'} : reaches₁ (TM2.step tr) ⟨some (head main q), s, K'.elim (tr_list L) [] c d⟩ ⟨some q, none, K'.elim (tr_list [L.head]) [] c d⟩ := begin let o : option Γ' := list.cases_on L none (λ _ _, some Γ'.cons), refine (move_ok dec_trivial (split_at_pred_eq _ _ (tr_nat L.head) o (tr_list L.tail) (tr_nat_nat_end _) _)).trans (trans_gen.head rfl (trans_gen.head rfl _)), { cases L; exact ⟨rfl, rfl⟩ }, simp [show o ≠ some Γ'.Cons, by cases L; rintro ⟨⟩], refine (clear_ok (split_at_pred_eq _ _ _ none [] _ ⟨rfl, rfl⟩)).trans _, { exact λ x h, (to_bool_ff (tr_list_ne_Cons _ _ h)) }, convert unrev_ok, simp [list.reverse_core_eq], end theorem head_stack_ok {q s L₁ L₂ L₃} : reaches₁ (TM2.step tr) ⟨some (head stack q), s, K'.elim (tr_list L₁) [] [] (tr_list L₂ ++ Γ'.Cons :: L₃)⟩ ⟨some q, none, K'.elim (tr_list (L₂.head :: L₁)) [] [] L₃⟩ := begin cases L₂ with a L₂, { refine trans_gen.trans (move_ok dec_trivial (split_at_pred_eq _ _ [] (some Γ'.Cons) L₃ (by rintro _ ⟨⟩) ⟨rfl, rfl⟩)) (trans_gen.head rfl (trans_gen.head rfl _)), convert unrev_ok, simp, refl }, { refine trans_gen.trans (move_ok dec_trivial (split_at_pred_eq _ _ (tr_nat a) (some Γ'.cons) (tr_list L₂ ++ Γ'.Cons :: L₃) (tr_nat_nat_end _) ⟨rfl, by simp⟩)) (trans_gen.head rfl (trans_gen.head rfl _)), simp, refine trans_gen.trans (clear_ok (split_at_pred_eq _ _ (tr_list L₂) (some Γ'.Cons) L₃ (λ x h, (to_bool_ff (tr_list_ne_Cons _ _ h))) ⟨rfl, by simp⟩)) _, convert unrev_ok, simp [list.reverse_core_eq] }, end theorem succ_ok {q s n} {c d : list Γ'} : reaches₁ (TM2.step tr) ⟨some (Λ'.succ q), s, K'.elim (tr_list [n]) [] c d⟩ ⟨some q, none, K'.elim (tr_list [n.succ]) [] c d⟩ := begin simp [tr_nat, num.add_one], cases (n:num) with a, { refine trans_gen.head rfl _, simp, rw if_neg, swap, rintro ⟨⟩, rw if_pos, swap, refl, convert unrev_ok, simp, refl }, simp [num.succ, tr_num, num.succ'], suffices : ∀ l₁, ∃ l₁' l₂' s', list.reverse_core l₁ (tr_pos_num a.succ) = list.reverse_core l₁' l₂' ∧ reaches₁ (TM2.step tr) ⟨some q.succ, s, K'.elim (tr_pos_num a ++ [Γ'.cons]) l₁ c d⟩ ⟨some (unrev q), s', K'.elim (l₂' ++ [Γ'.cons]) l₁' c d⟩, { obtain ⟨l₁', l₂', s', e, h⟩ := this [], simp [list.reverse_core] at e, refine h.trans _, convert unrev_ok using 2, simp [e, list.reverse_core_eq] }, induction a with m IH m IH generalizing s; intro l₁, { refine ⟨Γ'.bit0 :: l₁, [Γ'.bit1], some Γ'.cons, rfl, trans_gen.head rfl (trans_gen.single _)⟩, simp [tr_pos_num] }, { obtain ⟨l₁', l₂', s', e, h⟩ := IH (Γ'.bit0 :: l₁), refine ⟨l₁', l₂', s', e, trans_gen.head _ h⟩, swap, simp [pos_num.succ, tr_pos_num] }, { refine ⟨l₁, _, some Γ'.bit0, rfl, trans_gen.single _⟩, simp, refl }, end theorem pred_ok (q₁ q₂ s v) (c d : list Γ') : ∃ s', reaches₁ (TM2.step tr) ⟨some (Λ'.pred q₁ q₂), s, K'.elim (tr_list v) [] c d⟩ (v.head.elim ⟨some q₁, s', K'.elim (tr_list v.tail) [] c d⟩ (λ n _, ⟨some q₂, s', K'.elim (tr_list (n :: v.tail)) [] c d⟩)) := begin rcases v with _|⟨_|n, v⟩, { refine ⟨none, trans_gen.single _⟩, simp, refl }, { refine ⟨some Γ'.cons, trans_gen.single _⟩, simp, refl }, refine ⟨none, _⟩, simp [tr_nat, num.add_one, num.succ, tr_num], cases (n:num) with a, { simp [tr_pos_num, tr_num, show num.zero.succ' = pos_num.one, from rfl], refine trans_gen.head rfl _, convert unrev_ok, simp, refl }, simp [tr_num, num.succ'], suffices : ∀ l₁, ∃ l₁' l₂' s', list.reverse_core l₁ (tr_pos_num a) = list.reverse_core l₁' l₂' ∧ reaches₁ (TM2.step tr) ⟨some (q₁.pred q₂), s, K'.elim (tr_pos_num a.succ ++ Γ'.cons :: tr_list v) l₁ c d⟩ ⟨some (unrev q₂), s', K'.elim (l₂' ++ Γ'.cons :: tr_list v) l₁' c d⟩, { obtain ⟨l₁', l₂', s', e, h⟩ := this [], simp [list.reverse_core] at e, refine h.trans _, convert unrev_ok using 2, simp [e, list.reverse_core_eq] }, induction a with m IH m IH generalizing s; intro l₁, { refine ⟨Γ'.bit1 :: l₁, [], some Γ'.cons, rfl, trans_gen.head rfl (trans_gen.single _)⟩, simp [tr_pos_num, show pos_num.one.succ = pos_num.one.bit0, from rfl], refl }, { obtain ⟨l₁', l₂', s', e, h⟩ := IH (some Γ'.bit0) (Γ'.bit1 :: l₁), refine ⟨l₁', l₂', s', e, trans_gen.head _ h⟩, simp, refl }, { obtain ⟨a, l, e, h⟩ : ∃ a l, tr_pos_num m = a :: l ∧ nat_end a = ff, { cases m; refine ⟨_, _, rfl, rfl⟩ }, refine ⟨Γ'.bit0 :: l₁, _, some a, rfl, trans_gen.single _⟩, simp [tr_pos_num, pos_num.succ, e, h, nat_end, show some Γ'.bit1 ≠ some Γ'.bit0, from dec_trivial] }, end theorem tr_normal_respects (c k v s) : ∃ b₂, tr_cfg (step_normal c k v) b₂ ∧ reaches₁ (TM2.step tr) ⟨some (tr_normal c (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ b₂ := begin induction c generalizing k v s, case zero' : { refine ⟨_, ⟨s, rfl⟩, trans_gen.single _⟩, simp }, case succ : { refine ⟨_, ⟨none, rfl⟩, head_main_ok.trans succ_ok⟩ }, case tail : { let o : option Γ' := list.cases_on v none (λ _ _, some Γ'.cons), refine ⟨_, ⟨o, rfl⟩, _⟩, convert clear_ok _, simp, swap, refine split_at_pred_eq _ _ (tr_nat v.head) _ _ (tr_nat_nat_end _) _, cases v; exact ⟨rfl, rfl⟩ }, case cons : f fs IHf IHfs { obtain ⟨c, h₁, h₂⟩ := IHf (cont.cons₁ fs v k) v none, refine ⟨c, h₁, trans_gen.head rfl $ (move_ok dec_trivial (split_at_pred_ff _)).trans _⟩, simp [step_normal], refine (copy_ok _ none [] (tr_list v).reverse _ _).trans _, convert h₂ using 2, simp [list.reverse_core_eq, tr_cont_stack] }, case comp : f g IHf IHg { exact IHg (cont.comp f k) v s }, case case : f g IHf IHg { rw step_normal, obtain ⟨s', h⟩ := pred_ok _ _ s v _ _, cases v.head with n, { obtain ⟨c, h₁, h₂⟩ := IHf k _ s', exact ⟨_, h₁, h.trans h₂⟩ }, { obtain ⟨c, h₁, h₂⟩ := IHg k _ s', exact ⟨_, h₁, h.trans h₂⟩ } }, case fix : f IH { apply IH } end theorem tr_ret_respects (k v s) : ∃ b₂, tr_cfg (step_ret k v) b₂ ∧ reaches₁ (TM2.step tr) ⟨some (Λ'.ret (tr_cont k)), s, K'.elim (tr_list v) [] [] (tr_cont_stack k)⟩ b₂ := begin induction k generalizing v s, case halt { exact ⟨_, rfl, trans_gen.single rfl⟩ }, case cons₁ : fs as k IH { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects fs (cont.cons₂ v k) as none, refine ⟨s', h₁, trans_gen.head rfl _⟩, simp, refine (move₂_ok dec_trivial _ (split_at_pred_ff _)).trans _, {refl}, simp, refine (move₂_ok dec_trivial _ _).trans _, swap 4, {refl}, swap 4, {exact (split_at_pred_eq _ _ _ (some Γ'.Cons) _ (λ x h, to_bool_ff (tr_list_ne_Cons _ _ h)) ⟨rfl, rfl⟩)}, refine (move₂_ok dec_trivial _ (split_at_pred_ff _)).trans _, {refl}, simp, exact h₂ }, case cons₂ : ns k IH { obtain ⟨c, h₁, h₂⟩ := IH (ns.head :: v) none, exact ⟨c, h₁, trans_gen.head rfl $ head_stack_ok.trans h₂⟩ }, case comp : f k IH { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects f k v s, exact ⟨_, h₁, trans_gen.head rfl h₂⟩ }, case fix : f k IH { rw [step_ret], have : if v.head = 0 then nat_end (tr_list v).head'.iget = tt ∧ (tr_list v).tail = tr_list v.tail else nat_end (tr_list v).head'.iget = ff ∧ (tr_list v).tail = (tr_nat v.head).tail ++ Γ'.cons :: tr_list v.tail, { cases v with n, {exact ⟨rfl, rfl⟩}, cases n, {exact ⟨rfl, rfl⟩}, rw [tr_list, list.head, tr_nat, nat.cast_succ, num.add_one, num.succ, list.tail], cases (n:num).succ'; exact ⟨rfl, rfl⟩ }, by_cases v.head = 0; simp [h] at this ⊢, { obtain ⟨c, h₁, h₂⟩ := IH v.tail (tr_list v).head', refine ⟨c, h₁, trans_gen.head rfl _⟩, simp [tr_cont, tr_cont_stack, this], exact h₂ }, { obtain ⟨s', h₁, h₂⟩ := tr_normal_respects f (cont.fix f k) v.tail (some Γ'.cons), refine ⟨_, h₁, trans_gen.head rfl $ trans_gen.trans _ h₂⟩, swap 3, simp [tr_cont, this.1], convert clear_ok (split_at_pred_eq _ _ (tr_nat v.head).tail (some Γ'.cons) _ _ _) using 2, { simp }, { exact λ x h, tr_nat_nat_end _ _ (list.tail_subset _ h) }, { exact ⟨rfl, this.2⟩ } } }, end theorem tr_respects : respects step (TM2.step tr) tr_cfg | (cfg.ret k v) _ ⟨s, rfl⟩ := tr_ret_respects _ _ _ | (cfg.halt v) _ rfl := rfl /-- The initial state, evaluating function `c` on input `v`. -/ def init (c : code) (v : list ℕ) : cfg' := ⟨some (tr_normal c cont'.halt), none, K'.elim (tr_list v) [] [] []⟩ theorem tr_init (c v) : ∃ b, tr_cfg (step_normal c cont.halt v) b ∧ reaches₁ (TM2.step tr) (init c v) b := tr_normal_respects _ _ _ _ theorem tr_eval (c v) : eval (TM2.step tr) (init c v) = halt <$> code.eval c v := begin obtain ⟨i, h₁, h₂⟩ := tr_init c v, refine part.ext (λ x, _), rw [reaches_eval h₂.to_refl], simp, refine ⟨λ h, _, _⟩, { obtain ⟨c, hc₁, hc₂⟩ := tr_eval_rev tr_respects h₁ h, simp [step_normal_eval] at hc₂, obtain ⟨v', hv, rfl⟩ := hc₂, exact ⟨_, hv, hc₁.symm⟩ }, { rintro ⟨v', hv, rfl⟩, have := tr_eval tr_respects h₁, simp [step_normal_eval] at this, obtain ⟨_, ⟨⟩, h⟩ := this _ hv rfl, exact h } end /-- The set of machine states reachable via downward label jumps, discounting jumps via `ret`. -/ def tr_stmts₁ : Λ' → finset Λ' | Q@(Λ'.move p k₁ k₂ q) := insert Q $ tr_stmts₁ q | Q@(Λ'.push k f q) := insert Q $ tr_stmts₁ q | Q@(Λ'.read q) := insert Q $ finset.univ.bUnion $ λ s, tr_stmts₁ (q s) | Q@(Λ'.clear p k q) := insert Q $ tr_stmts₁ q | Q@(Λ'.copy q) := insert Q $ tr_stmts₁ q | Q@(Λ'.succ q) := insert Q $ insert (unrev q) $ tr_stmts₁ q | Q@(Λ'.pred q₁ q₂) := insert Q $ tr_stmts₁ q₁ ∪ insert (unrev q₂) (tr_stmts₁ q₂) | Q@(Λ'.ret k) := {Q} theorem tr_stmts₁_trans {q q'} : q' ∈ tr_stmts₁ q → tr_stmts₁ q' ⊆ tr_stmts₁ q := begin induction q; simp only [tr_stmts₁, finset.mem_insert, finset.mem_union, or_imp_distrib, finset.mem_singleton, finset.subset.refl, imp_true_iff, true_and] {contextual := tt}, iterate 4 { exact λ h, finset.subset.trans (q_ih h) (finset.subset_insert _ _) }, { simp, intros s h x h', simp, exact or.inr ⟨_, q_ih s h h'⟩ }, { split, { rintro rfl, apply finset.subset_insert }, { intros h x h', simp, exact or.inr (or.inr $ q_ih h h') } }, { refine ⟨λ h x h', _, λ h x h', _, λ h x h', _⟩; simp, { exact or.inr (or.inr $ or.inl $ q_ih_q₁ h h') }, { cases finset.mem_insert.1 h' with h' h'; simp [h', unrev] }, { exact or.inr (or.inr $ or.inr $ q_ih_q₂ h h') } }, end theorem tr_stmts₁_self (q) : q ∈ tr_stmts₁ q := by induction q; { apply finset.mem_singleton_self <|> apply finset.mem_insert_self } /-- The (finite!) set of machine states visited during the course of evaluation of `c`, including the state `ret k` but not any states after that (that is, the states visited while evaluating `k`). -/ def code_supp' : code → cont' → finset Λ' | c@code.zero' k := tr_stmts₁ (tr_normal c k) | c@code.succ k := tr_stmts₁ (tr_normal c k) | c@code.tail k := tr_stmts₁ (tr_normal c k) | c@(code.cons f fs) k := tr_stmts₁ (tr_normal c k) ∪ (code_supp' f (cont'.cons₁ fs k) ∪ (tr_stmts₁ ( move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k)) ∪ (code_supp' fs (cont'.cons₂ k) ∪ tr_stmts₁ (head stack $ Λ'.ret k)))) | c@(code.comp f g) k := tr_stmts₁ (tr_normal c k) ∪ (code_supp' g (cont'.comp f k) ∪ (tr_stmts₁ (tr_normal f k) ∪ code_supp' f k)) | c@(code.case f g) k := tr_stmts₁ (tr_normal c k) ∪ (code_supp' f k ∪ code_supp' g k) | c@(code.fix f) k := tr_stmts₁ (tr_normal c k) ∪ (code_supp' f (cont'.fix f k) ∪ (tr_stmts₁ (Λ'.clear nat_end main $ tr_normal f (cont'.fix f k)) ∪ {Λ'.ret k})) @[simp] theorem code_supp'_self (c k) : tr_stmts₁ (tr_normal c k) ⊆ code_supp' c k := by cases c; refl <|> exact finset.subset_union_left _ _ /-- The (finite!) set of machine states visited during the course of evaluation of a continuation `k`, not including the initial state `ret k`. -/ def cont_supp : cont' → finset Λ' | (cont'.cons₁ fs k) := tr_stmts₁ ( move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k)) ∪ (code_supp' fs (cont'.cons₂ k) ∪ (tr_stmts₁ (head stack $ Λ'.ret k) ∪ cont_supp k)) | (cont'.cons₂ k) := tr_stmts₁ (head stack $ Λ'.ret k) ∪ cont_supp k | (cont'.comp f k) := code_supp' f k ∪ cont_supp k | (cont'.fix f k) := code_supp' (code.fix f) k ∪ cont_supp k | cont'.halt := ∅ /-- The (finite!) set of machine states visited during the course of evaluation of `c` in continuation `k`. This is actually closed under forward simulation (see `tr_supports`), and the existence of this set means that the machine constructed in this section is in fact a proper Turing machine, with a finite set of states. -/ def code_supp (c : code) (k : cont') : finset Λ' := code_supp' c k ∪ cont_supp k @[simp] theorem code_supp_self (c k) : tr_stmts₁ (tr_normal c k) ⊆ code_supp c k := finset.subset.trans (code_supp'_self _ _) (finset.subset_union_left _ _) @[simp] theorem code_supp_zero (k) : code_supp code.zero' k = tr_stmts₁ (tr_normal code.zero' k) ∪ cont_supp k := rfl @[simp] theorem code_supp_succ (k) : code_supp code.succ k = tr_stmts₁ (tr_normal code.succ k) ∪ cont_supp k := rfl @[simp] theorem code_supp_tail (k) : code_supp code.tail k = tr_stmts₁ (tr_normal code.tail k) ∪ cont_supp k := rfl @[simp] theorem code_supp_cons (f fs k) : code_supp (code.cons f fs) k = tr_stmts₁ (tr_normal (code.cons f fs) k) ∪ code_supp f (cont'.cons₁ fs k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc] @[simp] theorem code_supp_comp (f g k) : code_supp (code.comp f g) k = tr_stmts₁ (tr_normal (code.comp f g) k) ∪ code_supp g (cont'.comp f k) := begin simp [code_supp, code_supp', cont_supp, finset.union_assoc], rw [← finset.union_assoc _ _ (cont_supp k), finset.union_eq_right_iff_subset.2 (code_supp'_self _ _)] end @[simp] theorem code_supp_case (f g k) : code_supp (code.case f g) k = tr_stmts₁ (tr_normal (code.case f g) k) ∪ (code_supp f k ∪ code_supp g k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc, finset.union_left_comm] @[simp] theorem code_supp_fix (f k) : code_supp (code.fix f) k = tr_stmts₁ (tr_normal (code.fix f) k) ∪ code_supp f (cont'.fix f k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc, finset.union_left_comm, finset.union_left_idem] @[simp] theorem cont_supp_cons₁ (fs k) : cont_supp (cont'.cons₁ fs k) = tr_stmts₁ (move₂ (λ _, ff) main aux $ move₂ (λ s, s = Γ'.Cons) stack main $ move₂ (λ _, ff) aux stack $ tr_normal fs (cont'.cons₂ k)) ∪ code_supp fs (cont'.cons₂ k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc] @[simp] theorem cont_supp_cons₂ (k) : cont_supp (cont'.cons₂ k) = tr_stmts₁ (head stack $ Λ'.ret k) ∪ cont_supp k := rfl @[simp] theorem cont_supp_comp (f k) : cont_supp (cont'.comp f k) = code_supp f k := rfl theorem cont_supp_fix (f k) : cont_supp (cont'.fix f k) = code_supp f (cont'.fix f k) := by simp [code_supp, code_supp', cont_supp, finset.union_assoc, finset.subset_iff] {contextual := tt} @[simp] theorem cont_supp_halt : cont_supp cont'.halt = ∅ := rfl /-- The statement `Λ'.supports S q` means that `cont_supp k ⊆ S` for any `ret k` reachable from `q`. (This is a technical condition used in the proof that the machine is supported.) -/ def Λ'.supports (S : finset Λ') : Λ' → Prop | Q@(Λ'.move p k₁ k₂ q) := Λ'.supports q | Q@(Λ'.push k f q) := Λ'.supports q | Q@(Λ'.read q) := ∀ s, Λ'.supports (q s) | Q@(Λ'.clear p k q) := Λ'.supports q | Q@(Λ'.copy q) := Λ'.supports q | Q@(Λ'.succ q) := Λ'.supports q | Q@(Λ'.pred q₁ q₂) := Λ'.supports q₁ ∧ Λ'.supports q₂ | Q@(Λ'.ret k) := cont_supp k ⊆ S /-- A shorthand for the predicate that we are proving in the main theorems `tr_stmts₁_supports`, `code_supp'_supports`, `cont_supp_supports`, `code_supp_supports`. The set `S` is fixed throughout the proof, and denotes the full set of states in the machine, while `K` is a subset that we are currently proving a property about. The predicate asserts that every state in `K` is closed in `S` under forward simulation, i.e. stepping forward through evaluation starting from any state in `K` stays entirely within `S`. -/ def supports (K S : finset Λ') := ∀ q ∈ K, TM2.supports_stmt S (tr q) theorem supports_insert {K S q} : supports (insert q K) S ↔ TM2.supports_stmt S (tr q) ∧ supports K S := by simp [supports] theorem supports_singleton {S q} : supports {q} S ↔ TM2.supports_stmt S (tr q) := by simp [supports] theorem supports_union {K₁ K₂ S} : supports (K₁ ∪ K₂) S ↔ supports K₁ S ∧ supports K₂ S := by simp [supports, or_imp_distrib, forall_and_distrib] theorem supports_bUnion {K:option Γ' → finset Λ'} {S} : supports (finset.univ.bUnion K) S ↔ ∀ a, supports (K a) S := by simp [supports]; apply forall_swap theorem head_supports {S k q} (H : (q:Λ').supports S) : (head k q).supports S := λ _, by dsimp only; split_ifs; exact H theorem ret_supports {S k} (H₁: cont_supp k ⊆ S) : TM2.supports_stmt S (tr (Λ'.ret k)) := begin have W := λ {q}, tr_stmts₁_self q, cases k, case halt { trivial }, case cons₁ { rw [cont_supp_cons₁, finset.union_subset_iff] at H₁, exact λ _, H₁.1 W }, case cons₂ { rw [cont_supp_cons₂, finset.union_subset_iff] at H₁, exact λ _, H₁.1 W }, case comp { rw [cont_supp_comp] at H₁, exact λ _, H₁ (code_supp_self _ _ W) }, case fix { rw [cont_supp_fix] at H₁, have L := @finset.mem_union_left, have R := @finset.mem_union_right, intro s, dsimp only, cases nat_end s.iget, { refine H₁ (R _ $ L _ $ R _ $ R _ $ L _ W) }, { exact H₁ (R _ $ L _ $ R _ $ R _ $ R _ $ finset.mem_singleton_self _) } } end theorem tr_stmts₁_supports {S q} (H₁ : (q:Λ').supports S) (HS₁ : tr_stmts₁ q ⊆ S) : supports (tr_stmts₁ q) S := begin have W := λ {q}, tr_stmts₁_self q, induction q; simp [tr_stmts₁] at HS₁ ⊢, any_goals { cases finset.insert_subset.1 HS₁ with h₁ h₂, id { have h₃ := h₂ W } <|> try { simp [finset.subset_iff] at h₂ } }, { exact supports_insert.2 ⟨⟨λ _, h₃, λ _, h₁⟩, q_ih H₁ h₂⟩ }, -- move { exact supports_insert.2 ⟨⟨λ _, h₃, λ _, h₁⟩, q_ih H₁ h₂⟩ }, -- clear { exact supports_insert.2 ⟨⟨λ _, h₁, λ _, h₃⟩, q_ih H₁ h₂⟩ }, -- copy { exact supports_insert.2 ⟨⟨λ _, h₃, λ _, h₃⟩, q_ih H₁ h₂⟩ }, -- push -- read { refine supports_insert.2 ⟨λ _, h₂ _ W, _⟩, exact supports_bUnion.2 (λ _, q_ih _ (H₁ _) (λ _ h, h₂ _ h)) }, -- succ { refine supports_insert.2 ⟨⟨λ _, h₁, λ _, h₂.1, λ _, h₂.1⟩, _⟩, exact supports_insert.2 ⟨⟨λ _, h₂.2 _ W, λ _, h₂.1⟩, q_ih H₁ h₂.2⟩ }, -- pred { refine supports_insert.2 ⟨⟨λ _, h₁, λ _, h₂.2 _ (or.inl W), λ _, h₂.1, λ _, h₂.1⟩, _⟩, refine supports_insert.2 ⟨⟨λ _, h₂.2 _ (or.inr W), λ _, h₂.1⟩, _⟩, refine supports_union.2 ⟨_, _⟩, { exact q_ih_q₁ H₁.1 (λ _ h, h₂.2 _ (or.inl h)) }, { exact q_ih_q₂ H₁.2 (λ _ h, h₂.2 _ (or.inr h)) } }, -- ret { exact supports_singleton.2 (ret_supports H₁) }, end theorem tr_stmts₁_supports' {S q K} (H₁ : (q:Λ').supports S) (H₂ : tr_stmts₁ q ∪ K ⊆ S) (H₃ : K ⊆ S → supports K S) : supports (tr_stmts₁ q ∪ K) S := begin simp [finset.union_subset_iff] at H₂, exact supports_union.2 ⟨tr_stmts₁_supports H₁ H₂.1, H₃ H₂.2⟩, end theorem tr_normal_supports {S c k} (Hk : code_supp c k ⊆ S) : (tr_normal c k).supports S := begin induction c generalizing k; simp [Λ'.supports, head], case zero' { exact finset.union_subset_right Hk }, case succ { intro, split_ifs; exact finset.union_subset_right Hk }, case tail { exact finset.union_subset_right Hk }, case cons : f fs IHf IHfs { apply IHf, rw code_supp_cons at Hk, exact finset.union_subset_right Hk }, case comp : f g IHf IHg { apply IHg, rw code_supp_comp at Hk, exact finset.union_subset_right Hk }, case case : f g IHf IHg { simp only [code_supp_case, finset.union_subset_iff] at Hk, exact ⟨IHf Hk.2.1, IHg Hk.2.2⟩ }, case fix : f IHf { apply IHf, rw code_supp_fix at Hk, exact finset.union_subset_right Hk }, end theorem code_supp'_supports {S c k} (H : code_supp c k ⊆ S) : supports (code_supp' c k) S := begin induction c generalizing k, iterate 3 { exact tr_stmts₁_supports (tr_normal_supports H) (finset.subset.trans (code_supp_self _ _) H) }, case cons : f fs IHf IHfs { have H' := H, simp only [code_supp_cons, finset.union_subset_iff] at H', refine tr_stmts₁_supports' (tr_normal_supports H) (finset.union_subset_left H) (λ h, _), refine supports_union.2 ⟨IHf H'.2, _⟩, refine tr_stmts₁_supports' (tr_normal_supports _) (finset.union_subset_right h) (λ h, _), { simp only [code_supp, finset.union_subset_iff, cont_supp] at h H ⊢, exact ⟨h.2.2.1, h.2.2.2, H.2⟩ }, refine supports_union.2 ⟨IHfs _, _⟩, { rw [code_supp, cont_supp_cons₁] at H', exact finset.union_subset_right (finset.union_subset_right H'.2) }, exact tr_stmts₁_supports (head_supports $ finset.union_subset_right H) (finset.union_subset_right h) }, case comp : f g IHf IHg { have H' := H, rw [code_supp_comp] at H', have H' := finset.union_subset_right H', refine tr_stmts₁_supports' (tr_normal_supports H) (finset.union_subset_left H) (λ h, _), refine supports_union.2 ⟨IHg H', _⟩, refine tr_stmts₁_supports' (tr_normal_supports _) (finset.union_subset_right h) (λ h, _), { simp only [code_supp', code_supp, finset.union_subset_iff, cont_supp] at h H ⊢, exact ⟨h.2.2, H.2⟩ }, exact IHf (finset.union_subset_right H') }, case case : f g IHf IHg { have H' := H, simp only [code_supp_case, finset.union_subset_iff] at H', refine tr_stmts₁_supports' (tr_normal_supports H) (finset.union_subset_left H) (λ h, _), exact supports_union.2 ⟨IHf H'.2.1, IHg H'.2.2⟩ }, case fix : f IHf { have H' := H, simp only [code_supp_fix, finset.union_subset_iff] at H', refine tr_stmts₁_supports' (tr_normal_supports H) (finset.union_subset_left H) (λ h, _), refine supports_union.2 ⟨IHf H'.2, _⟩, refine tr_stmts₁_supports' (tr_normal_supports _) (finset.union_subset_right h) (λ h, _), { simp only [code_supp', code_supp, finset.union_subset_iff, cont_supp, tr_stmts₁, finset.insert_subset] at h H ⊢, exact ⟨h.1, ⟨H.1.1, h⟩, H.2⟩ }, exact supports_singleton.2 (ret_supports $ finset.union_subset_right H) }, end theorem cont_supp_supports {S k} (H : cont_supp k ⊆ S) : supports (cont_supp k) S := begin induction k, { simp [cont_supp_halt, supports] }, case cons₁ : f k IH { have H₁ := H, rw [cont_supp_cons₁] at H₁, have H₂ := finset.union_subset_right H₁, refine tr_stmts₁_supports' (tr_normal_supports H₂) H₁ (λ h, _), refine supports_union.2 ⟨code_supp'_supports H₂, _⟩, simp only [code_supp, cont_supp_cons₂, finset.union_subset_iff] at H₂, exact tr_stmts₁_supports' (head_supports H₂.2.2) (finset.union_subset_right h) IH }, case cons₂ : k IH { have H' := H, rw [cont_supp_cons₂] at H', exact tr_stmts₁_supports' (head_supports $ finset.union_subset_right H') H' IH }, case comp : f k IH { have H' := H, rw [cont_supp_comp] at H', have H₂ := finset.union_subset_right H', exact supports_union.2 ⟨code_supp'_supports H', IH H₂⟩ }, case fix : f k IH { rw cont_supp at H, exact supports_union.2 ⟨code_supp'_supports H, IH (finset.union_subset_right H)⟩ } end theorem code_supp_supports {S c k} (H : code_supp c k ⊆ S) : supports (code_supp c k) S := supports_union.2 ⟨code_supp'_supports H, cont_supp_supports (finset.union_subset_right H)⟩ /-- The set `code_supp c k` is a finite set that witnesses the effective finiteness of the `tr` Turing machine. Starting from the initial state `tr_normal c k`, forward simulation uses only states in `code_supp c k`, so this is a finite state machine. Even though the underlying type of state labels `Λ'` is infinite, for a given partial recursive function `c` and continuation `k`, only finitely many states are accessed, corresponding roughly to subterms of `c`. -/ theorem tr_supports (c k) : @TM2.supports _ _ _ _ _ ⟨tr_normal c k⟩ tr (code_supp c k) := ⟨code_supp_self _ _ (tr_stmts₁_self _), λ l', code_supp_supports (finset.subset.refl _) _⟩ end end partrec_to_TM2 end turing
60cd9a35018dab6ae54e80d9f3caef79608e5251
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/topology/algebra/infinite_sum.lean
474b6bc9ae60ee71d26ccbfd46b295f01813a449
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
28,983
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 Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `tendsto_sum_nat_of_has_sum`. Reference: * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ import logic.function algebra.big_operators data.set.lattice data.finset topology.metric_space.basic topology.algebra.uniform_group topology.algebra.ring topology.algebra.ordered topology.instances.real noncomputable theory open lattice finset filter function classical open_locale topological_space local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" def option.cases_on' {α β} : option α → β → (α → β) → β | none n s := n | (some a) n s := s a variables {α : Type*} {β : Type*} {γ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute sum operator. This is based on Mario Carneiro's infinite sum in Metamath. For the definition or many statements, α does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `tsum f` is the sum of `f` it exists, or 0 otherwise -/ def tsum (f : β → α) := if h : summable f then classical.some h else 0 notation `∑` binders `, ` r:(scoped f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma has_sum_tsum (ha : summable f) : has_sum f (∑b, f b) := by simp [ha, tsum]; exact some_spec ha lemma summable_spec (ha : has_sum f a) : summable f := ⟨a, ha⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma summable_zero : summable (λb, 0 : β → α) := summable_spec has_sum_zero /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `s.sum f`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (s.sum f) := tendsto_infi' s $ tendsto.congr' (assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _) tendsto_const_nhds lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (finset.univ.sum f) := has_sum_sum_of_ne_finset_zero $ λ a h, h.elim (mem_univ _) lemma summable_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := summable_spec $ has_sum_sum_of_ne_finset_zero hf lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (({b} : finset β).sum f), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma has_sum_of_iso {j : γ → β} {i : β → γ} (hf : has_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : has_sum (f ∘ j) a := have ∀x y, j x = j y → x = y, from assume x y h, have i (j x) = i (j y), by rw [h], by rwa [h₁, h₁] at this, have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j), from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm, show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (𝓝 a), by rw [this]; apply hf.comp (tendsto_finset_image_at_top_at_top h₂) lemma has_sum_iff_has_sum_of_iso {j : γ → β} (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : has_sum (f ∘ j) a ↔ has_sum f a := iff.intro (assume hfj, have has_sum ((f ∘ j) ∘ i) a, from has_sum_of_iso hfj h₂ h₁, by simp [(∘), h₂] at this; assumption) (assume hf, has_sum_of_iso hf h₁ h₂) lemma has_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ] [is_add_monoid_hom g] (h₃ : continuous g) (hf : has_sum f a) : has_sum (g ∘ f) (g a) := have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f), from funext $ assume s, s.sum_hom g, show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (𝓝 (g a)), by rw [this]; exact tendsto.comp (continuous_iff_continuous_at.mp h₃ a) hf /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma tendsto_sum_nat_of_has_sum {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, (range n).sum f) at_top (𝓝 a) := @tendsto.comp _ _ _ finset.range (λ s : finset ℕ, s.sum f) _ _ _ h tendsto_finset_range variable [topological_add_monoid α] lemma has_sum_add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp [has_sum, sum_add_distrib]; exact hf.add hg lemma summable_add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := summable_spec $ has_sum_add (has_sum_tsum hf)(has_sum_tsum hg) lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, s.sum $ λi, f i b) (s.sum a) := finset.induction_on s (by simp [has_sum_zero]) (by simp [has_sum_add] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, s.sum $ λi, f i b) := summable_spec $ has_sum_sum $ assume i hi, has_sum_tsum $ hf i hi lemma has_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (ha : has_sum f a) : has_sum g a := assume s' hs', let ⟨s, hs, hss', hsc⟩ := nhds_is_closed hs', ⟨u, hu⟩ := mem_at_top_sets.mp $ ha $ hs, fsts := u.image sigma.fst, snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b))) in have u_subset : u ⊆ fsts.sigma snds, from subset_iff.mpr $ assume ⟨b, c⟩ hu, have hb : b ∈ fsts, from finset.mem_image.mpr ⟨_, hu, rfl⟩, have hc : c ∈ snds b, from mem_bind.mpr ⟨_, hu, by simp; refl⟩, by simp [mem_sigma, hb, hc] , mem_at_top_sets.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs), have h : ∀cs : Π b ∈ bs, finset (γ b), (⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩ (λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s ≠ ∅, from assume cs, let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f, from sum_sigma.symm, have (bs.sigma cs').sum f ∈ s, from hu _ $ finset.subset.trans u_subset $ sigma_mono hbs $ assume b, @finset.subset_union_right (γ b) _ _ _, set.ne_empty_iff_exists_mem.mpr $ exists.intro cs' $ by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_right] }, have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) (⨅b (h : b ∈ bs), at_top.comap (λp, p b)) (𝓝 (bs.sum g)), from tendsto_finset_sum bs $ assume c hc, tendsto_infi' c $ tendsto_infi' hc $ by apply tendsto.comp (hf c) tendsto_comap, have bs.sum g ∈ s, from mem_of_closed_of_tendsto' this hsc $ forall_sets_neq_empty_iff_neq_bot.mp $ by simp [mem_inf_sets, exists_imp_distrib, and_imp, forall_and_distrib, filter.mem_infi_sets_finset, mem_comap_sets, skolem, mem_at_top_sets, and_comm]; from assume s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp', have (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b), from infi_le_infi $ assume b, infi_le_infi $ assume hb, le_trans (set.preimage_mono $ hp' b hb) (hp b hb), neq_bot_of_le_neq_bot (h _) (le_trans (set.inter_subset_inter (le_trans this hs₂) hs₃) hs₁), hss' this lemma summable_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (hf : ∀b, summable (λc, f ⟨b, c⟩)) (ha : summable f) : summable (λb, ∑c, f ⟨b, c⟩) := summable_spec $ has_sum_sigma (assume b, has_sum_tsum $ hf b) (has_sum_tsum ha) end has_sum section has_sum_iff_has_sum_of_iso_ne_zero variables [add_comm_monoid α] [topological_space α] variables {f : β → α} {g : γ → α} {a : α} lemma has_sum_of_has_sum (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (hf : has_sum g a) : has_sum f a := suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g), from le_trans this hf, by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_sum_iff_has_sum (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) : has_sum f a ↔ has_sum g a := ⟨has_sum_of_has_sum h₂, has_sum_of_has_sum h₁⟩ variables (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) include hi hj hji hij hgj lemma has_sum_of_has_sum_ne_zero : has_sum g a → has_sum f a := have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y), from assume x y hx hy, ⟨assume h, have i (hj hx) = i (hj hy), by simp [h], by rwa [hij, hij] at this; assumption, by simp {contextual := tt}⟩, let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in has_sum_of_has_sum $ assume u, exists.intro (ii u) $ assume v hv, exists.intro (u ∪ jj v) $ and.intro (subset_union_left _ _) $ have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0, from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0, have c ∈ u, from (finset.mem_union.1 hc).resolve_right hnc, have i h ∈ v, from hv $ by simp [mem_bind]; existsi c; simp [h, this], have j (hi h) ∈ jj v, by simp [mem_bind]; existsi i h; simp [h, hi, this], by rw [hji h] at this; exact hnc this, calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset (subset_union_right _ _) this).symm ... = v.sum _ : sum_bind $ by intros x _ y _ _; by_cases f x = 0; by_cases f y = 0; simp [*]; cc ... = v.sum f : sum_congr rfl $ by intros x hx; by_cases f x = 0; simp [*] lemma has_sum_iff_has_sum_of_ne_zero : has_sum f a ↔ has_sum g a := iff.intro (has_sum_of_has_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji]) (has_sum_of_has_sum_ne_zero i hi j hj hji hij hgj) lemma summable_iff_summable_ne_zero : summable g ↔ summable f := exists_congr $ assume a, has_sum_iff_has_sum_of_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji] end has_sum_iff_has_sum_of_iso_ne_zero section has_sum_iff_has_sum_of_bij_ne_zero variables [add_comm_monoid α] [topological_space α] variables {f : β → α} {g : γ → α} {a : α} (i : Π⦃c⦄, g c ≠ 0 → β) (h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂) (h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b) (h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) include i h₁ h₂ h₃ lemma has_sum_iff_has_sum_of_ne_zero_bij : has_sum f a ↔ has_sum g a := have hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0, from assume c h, by simp [h₃, h], let j : Π⦃b⦄, f b ≠ 0 → γ := λb h, some $ h₂ h in have hj : ∀⦃b⦄ (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b, from assume b h, some_spec $ h₂ h, have hj₁ : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0, from assume b h, let ⟨h₁, _⟩ := hj h in h₁, have hj₂ : ∀⦃b⦄ (h : f b ≠ 0), i (hj₁ h) = b, from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂, has_sum_iff_has_sum_of_ne_zero i hi j hj₁ (assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂]) lemma summable_iff_summable_ne_zero_bij : summable f ↔ summable g := exists_congr $ assume a, has_sum_iff_has_sum_of_ne_zero_bij @i h₁ h₂ h₃ end has_sum_iff_has_sum_of_bij_ne_zero section tsum variables [add_comm_monoid α] [topological_space α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_unique : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique at_top_ne_bot lemma tsum_eq_has_sum (ha : has_sum f a) : (∑b, f b) = a := has_sum_unique (has_sum_tsum ⟨a, ha⟩) ha lemma has_sum_iff_of_summable (h : summable f) : has_sum f a ↔ (∑b, f b) = a := iff.intro tsum_eq_has_sum (assume eq, eq ▸ has_sum_tsum h) @[simp] lemma tsum_zero : (∑b:β, 0:α) = 0 := tsum_eq_has_sum has_sum_zero lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : (∑b, f b) = s.sum f := tsum_eq_has_sum $ has_sum_sum_of_ne_finset_zero hf lemma tsum_fintype [fintype β] (f : β → α) : (∑b, f b) = finset.univ.sum f := tsum_eq_has_sum $ has_sum_fintype f lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : (∑b, f b) = f b := tsum_eq_has_sum $ has_sum_single b hf @[simp] lemma tsum_ite_eq (b : β) (a : α) : (∑b', if b' = b then a else 0) = a := tsum_eq_has_sum (has_sum_ite_eq b a) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : (∑b, f b) = (∑c, g c) := by_cases (assume : ∃a, has_sum f a, let ⟨a, hfa⟩ := this in have hga : has_sum g a, from h.mp hfa, by rw [tsum_eq_has_sum hfa, tsum_eq_has_sum hga]) (assume hf : ¬ summable f, have hg : ¬ summable g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩, by simp [tsum, hf, hg]) lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) : (∑i, f i) = (∑j, g j) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_ne_zero i hi j hj hji hij hgj lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂) (h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b) (h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) : (∑i, f i) = (∑j, g j) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_ne_zero_bij i h₁ h₂ h₃ lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_has_sum_iff_has_sum $ assume a, has_sum_iff_has_sum_of_iso i h₁ h₂ lemma tsum_equiv (j : γ ≃ β) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_iso j j.symm (by simp) (by simp) variable [topological_add_monoid α] lemma tsum_add (hf : summable f) (hg : summable g) : (∑b, f b + g b) = (∑b, f b) + (∑b, g b) := tsum_eq_has_sum $ has_sum_add (has_sum_tsum hf) (has_sum_tsum hg) lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : (∑b, s.sum (λi, f i b)) = s.sum (λi, ∑b, f i b) := tsum_eq_has_sum $ has_sum_sum $ assume i hi, has_sum_tsum $ hf i hi lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : (∑p, f p) = (∑b c, f ⟨b, c⟩) := (tsum_eq_has_sum $ has_sum_sigma (assume b, has_sum_tsum $ h₁ b) $ has_sum_tsum h₂).symm end tsum section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_neg : has_sum f a → has_sum (λb, - f b) (- a) := has_sum_hom has_neg.neg continuous_neg lemma summable_neg (hf : summable f) : summable (λb, - f b) := summable_spec $ has_sum_neg $ has_sum_tsum $ hf lemma has_sum_sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by simp; exact has_sum_add hf (has_sum_neg hg) lemma summable_sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := summable_spec $ has_sum_sub (has_sum_tsum hf) (has_sum_tsum hg) section tsum variables [t2_space α] lemma tsum_neg (hf : summable f) : (∑b, - f b) = - (∑b, f b) := tsum_eq_has_sum $ has_sum_neg $ has_sum_tsum $ hf lemma tsum_sub (hf : summable f) (hg : summable g) : (∑b, f b - g b) = (∑b, f b) - (∑b, g b) := tsum_eq_has_sum $ has_sum_sub (has_sum_tsum hf) (has_sum_tsum hg) lemma tsum_eq_zero_add {f : ℕ → α} (hf : summable f) : (∑b, f b) = f 0 + (∑b, f (b + 1)) := begin let f₁ : ℕ → α := λ n, nat.rec (f 0) (λ _ _, 0) n, let f₂ : ℕ → α := λ n, nat.rec 0 (λ k _, f (k+1)) n, have : f = λ n, f₁ n + f₂ n, { ext n, symmetry, cases n, apply add_zero, apply zero_add }, have hf₁ : summable f₁, { fapply summable_sum_of_ne_finset_zero, { exact finset.singleton 0 }, { rintros (_ | n) hn, { exfalso, apply hn, apply finset.mem_singleton_self }, { refl } } }, have hf₂ : summable f₂, { have : f₂ = λ n, f n - f₁ n, ext, rw [eq_sub_iff_add_eq', this], rw [this], apply summable_sub hf hf₁ }, conv_lhs { rw [this] }, rw [tsum_add hf₁ hf₂, tsum_eq_single 0], { congr' 1, fapply tsum_eq_tsum_of_ne_zero_bij (λ n _, n + 1), { intros _ _ _ _, exact nat.succ_inj }, { rintros (_ | n) h, { contradiction }, { exact ⟨n, h, rfl⟩ } }, { intros, refl }, { apply_instance } }, { rintros (_ | n) hn, { contradiction }, { refl } }, { apply_instance } end end tsum end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_mul_left (a₂) : has_sum f a₁ → has_sum (λb, a₂ * f b) (a₂ * a₁) := has_sum_hom _ (continuous_const.mul continuous_id) lemma has_sum_mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) := @has_sum_hom _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _ (continuous_id.mul continuous_const) hf lemma summable_mul_left (a) (hf : summable f) : summable (λb, a * f b) := summable_spec $ has_sum_mul_left _ $ has_sum_tsum hf lemma summable_mul_right (a) (hf : summable f) : summable (λb, f b * a) := summable_spec $ has_sum_mul_right _ $ has_sum_tsum hf section tsum variables [t2_space α] lemma tsum_mul_left (a) (hf : summable f) : (∑b, a * f b) = a * (∑b, f b) := tsum_eq_has_sum $ has_sum_mul_left _ $ has_sum_tsum hf lemma tsum_mul_right (a) (hf : summable f) : (∑b, f b * a) = (∑b, f b) * a := tsum_eq_has_sum $ has_sum_mul_right _ $ has_sum_tsum hf end tsum end topological_semiring section order_topology variables [ordered_comm_monoid α] [topological_space α] [ordered_topology α] variables {f g : β → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto at_top_ne_bot hf hg $ univ_mem_sets' $ assume s, sum_le_sum $ assume b _, h b lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c) (h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (λb _, i b) _ _ _).2 hf, { assume c₁ c₂ h₁ h₂ eq, exact hi eq }, { assume c hc, cases eq : partial_inv i c with b; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective hi] at eq, exact ⟨b, hc, eq⟩ } }, { assume c hc, rw [partial_inv_left hi, option.cases_on'] } end, begin refine has_sum_le (assume c, _) this hg, by_cases c ∈ set.range i, { rcases h with ⟨b, rfl⟩, rw [partial_inv_left hi, option.cases_on'], exact h _ }, { have : partial_inv i c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma sum_le_has_sum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) : s.sum f ≤ a := ge_of_tendsto at_top_ne_bot hf (mem_at_top_sets.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩) lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) : s.sum f ≤ tsum f := sum_le_has_sum s hs (has_sum_tsum hf) lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : (∑b, f b) ≤ (∑b, g b) := has_sum_le h (has_sum_tsum hf) (has_sum_tsum hg) end order_topology section uniform_group variables [add_comm_group α] [uniform_space α] [complete_space α] variables (f g : β → α) {a a₁ a₂ : α} lemma summable_iff_cauchy : summable f ↔ cauchy (map (λ (s : finset β), sum s f) at_top) := (cauchy_map_iff_exists_tendsto at_top_ne_bot).symm variable [uniform_add_group α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → t.sum f ∈ e) := begin simp only [summable_iff_cauchy, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top' (_ : finset β × finset β → α)], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : t₂.sum f - t₁.sum f = (t₂ \ s).sum f - (t₁ \ s).sum f, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ _ (h _ finset.sdiff_disjoint) (h _ finset.sdiff_disjoint) } end /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable_of_summable_of_sub (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := (summable_iff_vanishing g).2 $ assume e he, let ⟨s, hs⟩ := (summable_iff_vanishing f).1 hf e he in ⟨s, assume t ht, have eq : (t.filter (λb, g b = f b)).sum f = t.sum g := calc (t.filter (λb, g b = f b)).sum f = (t.filter (λb, g b = f b)).sum g : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = t.sum g : begin refine finset.sum_subset (finset.filter_subset _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _) ht⟩ lemma summable_comp_of_summable_of_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := suffices summable (λb, if b ∈ set.range i then f b else 0), begin refine (summable_iff_summable_ne_zero_bij (λc _, i c) _ _ _).1 this, { assume c₁ c₂ hc₁ hc₂ eq, exact hi eq }, { assume b hb, split_ifs at hb, { rcases h with ⟨c, rfl⟩, exact ⟨c, hb, rfl⟩ }, { contradiction } }, { assume c hc, exact if_pos (set.mem_range_self _) } end, summable_of_summable_of_sub _ _ hf $ assume b, by by_cases b ∈ set.range i; simp [h] end uniform_group section cauchy_seq open finset.Ico filter /-- If the extended distance between consequent points of a sequence is estimated by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_edist_le_of_summable [emetric_space α] {f : ℕ → α} (d : ℕ → nnreal) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _), -- Actually we need partial sums of `d` to be a Cauchy sequence replace hd : cauchy_seq (λ (n : ℕ), sum (range n) d) := let ⟨_, H⟩ := hd in cauchy_seq_of_tendsto_nhds _ (tendsto_sum_nat_of_has_sum H), -- Now we take the same `N` as in one of the definitions of a Cauchy sequence refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _), have hsum := hN n hn, -- We simplify the known inequality rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum, norm_cast at hsum, replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum, -- Then use `hf` to simplify the goal to the same form apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)), assumption_mod_cast end /-- If the distance between consequent points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ lemma cauchy_seq_of_dist_le_of_summable [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f := begin refine metric.cauchy_seq_iff'.2 (λε εpos, _), replace hd : cauchy_seq (λ (n : ℕ), sum (range n) d) := let ⟨_, H⟩ := hd in cauchy_seq_of_tendsto_nhds _ (tendsto_sum_nat_of_has_sum H), refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _), have hsum := hN n hn, rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum, calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _ ... ≤ (Ico N n).sum d : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k) ... ≤ abs ((Ico N n).sum d) : le_abs_self _ ... < ε : hsum end lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑ m, d (n + m) := begin refine le_of_tendsto at_top_ne_bot (tendsto_dist tendsto_const_nhds ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _, rw [sum_Ico_eq_sum_range], refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _, exact summable_comp_of_summable_of_injective _ hd (add_left_injective n) end lemma dist_le_tsum_of_dist_le_of_tendsto₀ [metric_space α] {f : ℕ → α} (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 lemma dist_le_tsum_dist_of_tendsto [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) : dist (f n) a ≤ ∑ m, dist (f (n+m)) (f (n+m).succ) := show dist (f n) a ≤ ∑ m, (λx, dist (f x) (f x.succ)) (n + m), from dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n lemma dist_le_tsum_dist_of_tendsto₀ [metric_space α] {f : ℕ → α} (h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ ∑ n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 end cauchy_seq
a1015dbf54216ced84463ade6403981fec40466e
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/structInst4.lean
a1b7ad59582fba9f36d8fd30e36fce9683f0aacd
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
492
lean
universes u def a : Array ((Nat × Nat) × Bool) := #[] def b : Array Nat := #[] structure Foo := (x : Array ((Nat × Nat) × Bool) := #[]) (y : Nat := 0) new_frontend #check (b).modifyOp (idx := 1) (fun s => 2) #check { [1] := 2, .. b } #check { [1].fst.2 := 1, .. a } def foo : Foo := {} #check foo.x[1].1.2 #check { x[1].2 := true, .. foo } #check { x[1].fst.snd := 1, .. foo } #check { x[1].1.fst := 1, .. foo } #check { x[1].1.1 := 5, .. foo } #check { x[1].1.2 := 5, .. foo }
6204a381c7ee0737922dc34612b1d5be568f6a0d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/flat.lean
802c2fac29e2132b79d330f1438ba6ecec1e2ff6
[ "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
2,591
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.noetherian /-! # Flat modules A module `M` over a commutative ring `R` is *flat* if for all finitely generated ideals `I` of `R`, the canonical map `I ⊗ M →ₗ M` is injective. This is equivalent to the claim that for all injective `R`-linear maps `f : M₁ → M₂` the induced map `M₁ ⊗ M → M₂ ⊗ M` is injective. See <https://stacks.math.columbia.edu/tag/00HD>. This result is not yet formalised. ## Main declaration * `module.flat`: the predicate asserting that an `R`-module `M` is flat. ## TODO * Show that tensoring with a flat module preserves injective morphisms. Show that this is equivalent to be flat. See <https://stacks.math.columbia.edu/tag/00HD>. To do this, it is probably a good idea to think about a suitable categorical induction principle that should be applied to the category of `R`-modules, and that will take care of the administrative side of the proof. * Define flat `R`-algebras * Define flat ring homomorphisms - Show that the identity is flat - Show that composition of flat morphisms is flat * Show that flatness is stable under base change (aka extension of scalars) For base change, it will be very useful to have a "characteristic predicate" instead of relying on the construction `A ⊗ B`. Indeed, such a predicate should allow us to treat both `A[X]` and `A ⊗ R[X]` as the base change of `R[X]` to `A`. (Similar examples exist with `fin n → R`, `R × R`, `ℤ[i] ⊗ ℝ`, etc...) * Generalize flatness to noncommutative rings. -/ universes u v namespace module open function (injective) open linear_map (lsmul) open_locale tensor_product /-- An `R`-module `M` is flat if for all finitely generated ideals `I` of `R`, the canonical map `I ⊗ M →ₗ M` is injective. -/ class flat (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : Prop := (out : ∀ ⦃I : ideal R⦄ (hI : I.fg), injective (tensor_product.lift ((lsmul R M).comp I.subtype))) namespace flat open tensor_product linear_map _root_.submodule instance self (R : Type u) [comm_ring R] : flat R R := ⟨begin intros I hI, rw ← equiv.injective_comp (tensor_product.rid R I).symm.to_equiv, convert subtype.coe_injective using 1, ext x, simp only [function.comp_app, linear_equiv.coe_to_equiv, rid_symm_apply, comp_apply, mul_one, lift.tmul, subtype_apply, algebra.id.smul_eq_mul, lsmul_apply] end⟩ end flat end module
ed5240bf0f83088dc9da9032bc0f5f32fe67419a
5ee26964f602030578ef0159d46145dd2e357ba5
/src/valuation/canonical.lean
ca99c24a60c5e3fa150826919f15e7e0cac9aa41
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
32,511
lean
import valuation.basic import for_mathlib.quotient_group import for_mathlib.subgroup import for_mathlib.group -- group_equiv /- The purpose of this file is to define a "canonical" valuation equivalent to a given valuation. The whole raison d'etre for this is that there are set-theoretic issues with the equivalence "relation" on valuations, because the target group Gamma can be arbitrary. The main idea is this. If v : R → Γ ∪ {0} is an arbitrary valuation, then v extends to a valuation on K = Frac(R/supp(v)) and hence to a group homomorphism K^* → Γ, whose kernel is A^*, the units in the valuation ring (or equivalently the things in K^* of norm at most 1). This embeds K^*/A^* into Γ and hence gives K^*/A^* the structure of a linearly ordered commutative group. There is an induced map R → (K^*/A^*) ∪ {0}, and we call this the _canonical valuation_ associated to v, and this valuation is equivalent to v. A technical advantage that this valuation has from the point of view of Lean's type theory is that if R is in universe u₁ and Γ in universe u₂, then v : valuation R Γ will be in universe `max u₁ u₂` but the canonical valuation will just be in universe u₁. In particular, if v and v' are equivalent then their associated canonical valuations are isomorphic and furthermore in the same universe. All of the below names are in the `valuation` namespace. `value_group v` is the totally ordered group $K^*/A^* (note that it is isomorphic to the subgroup of Γ which Wedhorn calls the value group), and `value_group.to_Γ` is the group homomorphism to \Gamma. `canonical_valuation v` is the canonical valuation. `canonical_valuation.to_\Gamma v` is the lemma that says that we can recover v from the canonical valuation using the group homomorphism from K^*/A^* to Gamma. We then prove some of Proposition-and-Definition 1.27 of Wedhorn, where we note that we used (iii) for the definition, and we're now using a different definition to Wedhorn for the value group (because it's isomorphic so no mathematician will care, and it's easier for us because it's in a smaller universe). TODO: Do we ever actually use 1.27 now? KMB has left part of it sorried. TODO: Do we need any of the dead code commented out at the end of the file? KMB suspects not. This dead code is all about the workaround we had for getting down to R's universe from Gamma's universe before Johan's idea of using the canonical valuation. -/ local attribute [instance] classical.prop_decidable noncomputable theory universes u u₀ u₁ u₂ u₃ variables {R : Type u₀} [comm_ring R] namespace valuation open with_zero variables {Γ : Type u} [linear_ordered_comm_group Γ] variables (v : valuation R Γ) section canonical_equivalent_valuation instance : comm_group (units (valuation_field v)) := by apply_instance instance valuation.units_preorder : preorder (units (valuation_field v)) := { le := λ u v, u.val ≤ v.val, le_refl := le_refl, le_trans := λ _ _ _, le_trans } definition valuation_field_norm_one := is_group_hom.ker v.on_valuation_field.unit_map instance (v : valuation R Γ) : normal_subgroup (valuation_field_norm_one v) := by unfold valuation_field_norm_one; apply_instance /-- The value group of the canonical valuation.-/ def value_group (v : valuation R Γ) : Type u₀ := quotient_group.quotient (valuation_field_norm_one v) def value_group_quotient (v : valuation R Γ) : units (valuation_field v) → value_group v := quotient.mk' instance value_group.comm_group : comm_group (value_group v) := by unfold value_group; apply_instance def value_group.to_Γ (v : valuation R Γ) : value_group v → Γ := quotient_group.lift (valuation_field_norm_one v) v.on_valuation_field.unit_map $ λ x, (is_group_hom.mem_ker _).1 instance : is_group_hom (value_group.to_Γ v) := by unfold value_group.to_Γ; apply_instance instance value_group_quotient.is_group_hom : is_group_hom (value_group_quotient v) := ⟨λ _ _, rfl⟩ instance : linear_order (value_group v) := { le := λ a' b', -- KMB now worried that this should change to λ s t, s ≤ t with possible breakage quotient.lift_on₂' a' b' (λ s t, v.on_valuation_field ↑s ≤ v.on_valuation_field ↑t) $ λ a b c d hac hbd, begin change a⁻¹ * c ∈ is_group_hom.ker v.on_valuation_field.unit_map at hac, change b⁻¹ * d ∈ is_group_hom.ker v.on_valuation_field.unit_map at hbd, rw [is_group_hom.mem_ker, mul_comm, ←is_group_hom.one_iff_ker_inv] at hac hbd, show (on_valuation_field v) a ≤ (on_valuation_field v) b = ((on_valuation_field v) c ≤ (on_valuation_field v) d), rw [←unit_map_eq, ←unit_map_eq, ←unit_map_eq, ←unit_map_eq, hbd, hac] end, le_refl := λ abar, quotient.induction_on' abar $ λ a, le_refl ((on_valuation_field v) a), le_trans := λ abar bbar cbar, quotient.induction_on₃' abar bbar cbar $ λ a b c, @le_trans _ _ ((on_valuation_field v) a) ((on_valuation_field v) b) ((on_valuation_field v) c), le_antisymm := λ abar bbar, quotient.induction_on₂' abar bbar $ λ a b hab hba, begin have h := @le_antisymm _ _ ((on_valuation_field v) a) ((on_valuation_field v) b) hab hba, apply quotient.sound, change a⁻¹ * b ∈ is_group_hom.ker v.on_valuation_field.unit_map, rw [is_group_hom.mem_ker, mul_comm, ←is_group_hom.one_iff_ker_inv], rw [←unit_map_eq, ←unit_map_eq] at h, replace h := option.injective_some _ h, rw h, end, le_total := λ abar bbar, quotient.induction_on₂' abar bbar $ λ a b, le_total ((on_valuation_field v) a) ((on_valuation_field v) b), } lemma mk_le_mk_iff (x y : units (valuation_field v)) : v.value_group_quotient x ≤ v.value_group_quotient y ↔ v.on_valuation_field x ≤ v.on_valuation_field y := iff.rfl instance : linear_ordered_comm_group (value_group v) := { mul_le_mul_left := begin rintro ⟨a⟩ ⟨b⟩ h ⟨c⟩, change v.on_valuation_field a ≤ v.on_valuation_field b at h, change value_group_quotient v c * value_group_quotient v a ≤ value_group_quotient v c * value_group_quotient v b, rw ←is_group_hom.map_mul (value_group_quotient v), rw ←is_group_hom.map_mul (value_group_quotient v), change v.on_valuation_field (c * a) ≤ v.on_valuation_field (c * b), rw v.on_valuation_field.map_mul, rw v.on_valuation_field.map_mul, exact with_zero.mul_le_mul_left _ _ h _ end} lemma value_group.to_Γ_monotone : monotone (value_group.to_Γ v) := begin rintros ⟨x⟩ ⟨y⟩, erw [mk_le_mk_iff, ← unit_map_eq, ← unit_map_eq, with_bot.some_le_some], exact id, end lemma value_group.to_Γ_injective : function.injective (value_group.to_Γ v) := quotient_group.injective_ker_lift _ lemma value_group.to_Γ_strict_mono : strict_mono (value_group.to_Γ v) := strict_mono_of_monotone_of_injective (value_group.to_Γ_monotone _) (value_group.to_Γ_injective _) -- The canonical valuation associated to v is the obvious map -- from R to value_group v := Frac(R/supp(v)) / A^* -- (thought of as K^*/A^* union 0) -- First define a valuation on K definition valuation_field.canonical_valuation_v : valuation_field v → with_zero (value_group v) := λ k, if h : (k = 0) then 0 else value_group_quotient v ⟨k,k⁻¹,mul_inv_cancel h, inv_mul_cancel h⟩ instance valuation_field.canonical_valuation_v.is_valuation : is_valuation (valuation_field.canonical_valuation_v v) := { map_zero := dif_pos rfl, map_one := begin unfold valuation_field.canonical_valuation_v, rw dif_neg zero_ne_one.symm, apply option.some_inj.2, convert is_group_hom.map_one (value_group_quotient v), exact inv_one end, map_mul := λ x y, begin unfold valuation_field.canonical_valuation_v, split_ifs with hxy hx hy hy hx hy hy, { simp }, { simp }, { simp }, { exfalso, exact or.elim (mul_eq_zero.1 hxy) hx hy}, { exfalso, exact hxy (hx.symm ▸ zero_mul y)}, { exfalso, exact hxy (hx.symm ▸ zero_mul y)}, { exfalso, exact hxy (hy.symm ▸ mul_zero x)}, apply option.some_inj.2, show value_group_quotient v {val := x * y, inv := (x * y)⁻¹, val_inv := _, inv_val := _} = value_group_quotient v {val := x * y, inv := _, val_inv := _, inv_val := _}, apply congr_arg, apply units.ext, refl, end, map_add := λ x y, begin unfold valuation_field.canonical_valuation_v, split_ifs with hxy hx hy hy hx hy hy, { left, exact le_refl _ }, { left, exact le_refl _ }, { right, exact le_refl _ }, { left, exact zero_le }, { exfalso, exact hxy (hx.symm ▸ hy.symm ▸ add_zero _)}, { right, convert le_refl _; rw hx; exact (zero_add y).symm }, { left, convert le_refl _; rw hy; exact (add_zero x).symm }, { rw [with_bot.coe_le_coe,with_bot.coe_le_coe], exact v.on_valuation_field.map_add _ _ } end } /-- The canonical valuation on Frac(R/supp(v)) -/ def valuation_field.canonical_valuation : valuation (valuation_field v) (value_group v) := ⟨valuation_field.canonical_valuation_v v, valuation_field.canonical_valuation_v.is_valuation v⟩ lemma valuation_field.canonical_valuation_unit : unit_map (valuation_field.canonical_valuation v) = value_group_quotient v := begin -- really hard to get to the if ext x, rw ←option.some_inj, rw unit_map_eq, show dite (x.val = 0) (λ (_x : x.val = 0), (0 : with_zero (value_group v))) (λ (h : ¬x.val = 0), (value_group_quotient v {val := ↑x, inv := (↑x)⁻¹, val_inv := _, inv_val := _})) = some (value_group_quotient v x), -- at last! split_ifs with h, { change x.val = 0 at h, have h2 := x.val_inv, rw [h, zero_mul] at h2, exfalso, revert h2, simp }, { show some _ = some _, congr, apply units.ext, refl } end /-- The canonical valuation on R/supp(v) -/ definition quotient.canonical_valuation (v : valuation R Γ) : valuation (ideal.quotient (supp v)) (value_group v) := @comap _ _ _ _ (valuation_field.canonical_valuation v) _ _ (localization.of) (by apply_instance) /-- The canonical valuation on R -/ definition canonical_valuation (v : valuation R Γ) : valuation R (value_group v) := comap (quotient.canonical_valuation v) (ideal.quotient.mk (supp v)) lemma canonical_valuation_eq (v : valuation R Γ) (r : R) : v.canonical_valuation r = if h : (v.valuation_field_mk r = 0) then 0 else some (value_group_quotient v {val := v.valuation_field_mk r, inv := (v.valuation_field_mk r)⁻¹, val_inv := mul_inv_cancel h, inv_val := inv_mul_cancel h}) := rfl lemma canonical_valuation_not_mem_supp_eq (v : valuation R Γ) (r : R) (hr : r ∉ supp v) : v.canonical_valuation r = some (value_group_quotient v (units_valfield_mk v r hr)) := begin rw canonical_valuation_eq, split_ifs, swap, refl, exfalso, apply hr, exact (v.valuation_field_mk_ker r).1 h end end canonical_equivalent_valuation namespace canonical_valuation -- everything in the image of the value group is a ratio of things -- coming from the ring -- Remark (KMB) -- writing this code was surprisingly painful -- Remark (KMB) -- I am not even sure we ever use it! lemma value_group.is_ratio (v : valuation R Γ) (g : value_group v) : ∃ r s : R, r ∉ supp v ∧ s ∉ supp v ∧ canonical_valuation v s * g = canonical_valuation v r := begin rcases g with ⟨u, u', huu', hu'u⟩, rcases u with ⟨⟨r⟩, ⟨s⟩, h⟩, change ideal.quotient.mk _ s ∈ _ at h, use r, use s, have hs : s ∉ supp v, { intro h2, rw @localization.fraction_ring.mem_non_zero_divisors_iff_ne_zero (valuation_ID v) at h, rw (ideal.quotient.eq_zero_iff_mem).2 h2 at h, apply h, refl, }, have hr : r ∉ supp v, { change (localization.mk (submodule.quotient.mk r) (⟨submodule.quotient.mk s, h⟩) * u' : valuation_field v) = 1 at huu', intro hr, rw (submodule.quotient.mk_eq_zero _).2 hr at huu', have : (localization.of (ideal.quotient.mk (supp v) 0) : valuation_field v) / (localization.of (ideal.quotient.mk (supp v) s) : valuation_field v) * u' = 1, simpa using huu', rw ideal.quotient.mk_zero at this, change ((0 : valuation_field v) / localization.of (ideal.quotient.mk (supp v) s) * u' = 1) at this, rw _root_.zero_div at this, rw zero_mul at this, revert this, simp, }, split, exact hr, split, exact hs, let rq := ideal.quotient.mk (supp v) r, let sq := ideal.quotient.mk (supp v) s, have hr' : rq ≠ 0, intro h2, apply hr, exact ideal.quotient.eq_zero_iff_mem.1 h2, have hs' : sq ≠ 0, intro h2, apply hs, exact ideal.quotient.eq_zero_iff_mem.1 h2, show (valuation_field.canonical_valuation_v v (localization.of sq)) * ↑(value_group_quotient v _) = (valuation_field.canonical_valuation_v v (localization.of rq)), unfold valuation_field.canonical_valuation_v, split_ifs, exfalso, exact hs' (localization.fraction_ring.eq_zero_of _ h_1), exfalso, exact hs' (localization.fraction_ring.eq_zero_of _ h_1), exfalso, exact hr' (localization.fraction_ring.eq_zero_of _ h_2), show some _ = some _, congr, show value_group_quotient v _ * value_group_quotient v _ = value_group_quotient v _, rw ←(value_group_quotient.is_group_hom v).map_mul, congr, apply units.ext, show localization.of sq * _ = localization.of rq, suffices : (localization.of sq : valuation_field v) * (localization.mk rq ⟨sq, h⟩ : valuation_field v) = localization.of rq, convert this, rw localization.mk_eq, rw mul_comm, rw mul_assoc, convert mul_one _, convert units.inv_val _, end -- This lemma shows that the valuation v can be reconstructed from its -- associated canonical valuation lemma to_Γ : (canonical_valuation v).map (value_group.to_Γ v) (value_group.to_Γ_monotone _) = v := begin rw valuation.ext, intro r, change with_zero.map _ _ = _, destruct (v r), { intro h, rw h, change r ∈ supp v at h, suffices : canonical_valuation v r = 0, rw this, refl, show valuation_field.canonical_valuation_v v _ = 0, rw ideal.quotient.eq_zero_iff_mem.2 h, exact (valuation_field.canonical_valuation v).map_zero, }, { intro g, intro hr, rw hr, have h2 : v r ≠ none, rw hr, simp, change r ∉ supp v at h2, let r' := (ideal.quotient.mk (supp v) r), have hr' : r' ≠ 0, intro hr', apply h2, exact (submodule.quotient.mk_eq_zero _).1 hr', let r'' := localization.of r', have hr'' : r'' ≠ 0, intro hr'', apply hr', exact localization.fraction_ring.eq_zero_of r' hr'', show with_zero.map (value_group.to_Γ v) (valuation_field.canonical_valuation_v v (r'')) = some g, unfold valuation_field.canonical_valuation_v, split_ifs with h1, contradiction, show some (v.on_valuation_field.unit_map ⟨r'',r''⁻¹,_,_⟩) = some g, rw unit_map_eq, rw ←hr, show (on_valuation_field v) (r'') = v r, let v' := on_quot v (le_refl _), have hv' : supp v' = 0, rw supp_quot_supp, simp, show v'.on_frac_val hv' ⟦⟨r',1⟩⟧ = v r, rw on_frac_val_mk, show v' r' / v' 1 = v r, rw v'.map_one, suffices : v' r' = v r, simpa using this, refl, } end end canonical_valuation end valuation namespace valuation variables {Γ : Type u} [linear_ordered_comm_group Γ] variables {Γ₁ : Type u₁} [linear_ordered_comm_group Γ₁] variables {Γ₂ : Type u₂} [linear_ordered_comm_group Γ₂] variables {Γ₃ : Type u₃} [linear_ordered_comm_group Γ₃] /-- A valuation is equivalent to its canonical valuation -/ lemma canonical_valuation_is_equiv (v : valuation R Γ) : v.canonical_valuation.is_equiv v := begin symmetry, convert is_equiv_of_map_of_strict_mono (value_group.to_Γ v) (value_group.to_Γ_strict_mono _), symmetry, exact canonical_valuation.to_Γ v, end namespace is_equiv -- Various lemmas about valuations being equivalent. variables {v : valuation R Γ} {v₁ : valuation R Γ₁} {v₂ : valuation R Γ₂} {v₃ : valuation R Γ₃} lemma on_quot_comap_self {J : ideal R} (hJ : J ≤ supp v) : is_equiv ((v.on_quot hJ).comap (ideal.quotient.mk J)) v := of_eq (on_quot_comap_eq _ _) lemma comap_on_quot (J : ideal R) (v₁ : valuation J.quotient Γ₁) (v₂ : valuation J.quotient Γ₂) : (v₁.comap (ideal.quotient.mk J)).is_equiv (v₂.comap (ideal.quotient.mk J)) ↔ v₁.is_equiv v₂ := { mp := begin rintros h ⟨x⟩ ⟨y⟩, exact h x y end, mpr := λ h, comap _ h } open localization lemma on_frac_comap_self {R : Type u₀} [integral_domain R] (v : valuation R Γ) (hv : supp v = 0) : is_equiv ((v.on_frac hv).comap of) v := of_eq (on_frac_comap_eq v hv) lemma comap_on_frac {R : Type u₀} [integral_domain R] (v₁ : valuation (fraction_ring R) Γ₁) (v₂ : valuation (fraction_ring R) Γ₂) : (v₁.comap of).is_equiv (v₂.comap of) ↔ is_equiv v₁ v₂ := { mp := begin rintros h ⟨x⟩ ⟨y⟩, erw ← comap_on_frac_eq v₁, erw ← comap_on_frac_eq v₂, dsimp [comap], repeat {erw on_frac_val'}, repeat {erw on_frac_val_mk}, repeat {erw with_zero.div_le_div}, repeat {erw ← valuation.map_mul}, exact h _ _, all_goals { intro H, erw [← mem_supp_iff, comap_supp, (supp _).eq_bot_of_prime] at H, simp at H, replace H := fraction_ring.eq_zero_of _ H, refine fraction_ring.mem_non_zero_divisors_iff_ne_zero.mp _ H, apply subtype.val_prop _, apply_instance }, end, mpr := λ h, comap _ h } /-- Wedhorm 1.27 iii -> ii (part a) -/ lemma supp_eq (h : v₁.is_equiv v₂) : supp v₁ = supp v₂ := ideal.ext $ λ r, calc r ∈ supp v₁ ↔ v₁ r = 0 : mem_supp_iff' _ _ ... ↔ v₁ r ≤ v₁ 0 : eq_zero_iff_le_zero _ ... ↔ v₂ r ≤ v₂ 0 : h r 0 ... ↔ v₂ r = 0 : (eq_zero_iff_le_zero _).symm ... ↔ r ∈ supp v₂ : (mem_supp_iff' _ _).symm lemma v_eq_one_of_v_eq_one (h : v₁.is_equiv v₂) {r : R} : v₁ r = 1 → v₂ r = 1 := begin rw [←v₁.map_one, ←v₂.map_one], intro hr, exact le_antisymm ((h r 1).1 (le_of_eq hr)) ((h 1 r).1 (le_of_eq hr.symm)), end lemma v_eq_one (h : v₁.is_equiv v₂) (r : R) : v₁ r = 1 ↔ v₂ r = 1 := ⟨v_eq_one_of_v_eq_one h,v_eq_one_of_v_eq_one h.symm⟩ lemma canonical_equiv_of_is_equiv (h : v₁.is_equiv v₂) : (canonical_valuation v₁).is_equiv (canonical_valuation v₂) := begin refine is_equiv.trans v₁.canonical_valuation_is_equiv _, refine is_equiv.trans h _, apply is_equiv.symm, exact v₂.canonical_valuation_is_equiv end end is_equiv lemma canonical_valuation_supp (v : valuation R Γ) : supp (v.canonical_valuation) = supp v := (canonical_valuation_is_equiv v).supp_eq section variables {v : valuation R Γ} {v₁ : valuation R Γ₁} {v₂ : valuation R Γ₂} {v₃ : valuation R Γ₃} open is_group_hom quotient_group function -- We now start on the equivalences of Wedhorn 1.27. This one is easy. -- Wedhorn 1.27 (i) => (iii) lemma of_inj_value_group (f : v₁.value_group → v₂.value_group) [is_group_hom f] (hf : strict_mono f) (H : v₂.canonical_valuation = v₁.canonical_valuation.map f (hf.monotone)) : v₁.is_equiv v₂ := begin refine (v₁.canonical_valuation_is_equiv.symm).trans _, refine (is_equiv.trans _ (v₂.canonical_valuation_is_equiv)), rw H, symmetry, exact is_equiv_of_map_of_strict_mono _ _ end def quot_of_quot_of_eq_supp (h : supp v₁ = supp v₂) : valuation_ID v₁ → valuation_ID v₂ := ideal.quotient.lift _ (ideal.quotient.mk _) (λ r hr, ideal.quotient.eq_zero_iff_mem.2 $ h ▸ hr) lemma quot_of_quot_of_eq_supp.id (r : valuation_ID v) : quot_of_quot_of_eq_supp (rfl) r = r := by rcases r;refl lemma quot_of_quot_of_eq_supp.comp (h12 : supp v₁ = supp v₂) (h23 : supp v₂ = supp v₃) (r : valuation_ID v₁) : quot_of_quot_of_eq_supp h23 (quot_of_quot_of_eq_supp h12 r) = quot_of_quot_of_eq_supp (h23 ▸ h12 : supp v₁ = supp v₃) r := by rcases r;refl def valuation_ID.equiv (h : supp v₁ = supp v₂) : valuation_ID v₁ ≃ valuation_ID v₂ := { to_fun := quot_of_quot_of_eq_supp h, inv_fun := quot_of_quot_of_eq_supp (h.symm), left_inv := λ r, by rw quot_of_quot_of_eq_supp.comp h h.symm; exact quot_of_quot_of_eq_supp.id r, right_inv := λ r, by rw quot_of_quot_of_eq_supp.comp h.symm h; exact quot_of_quot_of_eq_supp.id r } @[simp] lemma quot_of_quot_of_eq_supp_quotient_mk (h : supp v₁ = supp v₂) : quot_of_quot_of_eq_supp h ∘ ideal.quotient.mk _ = ideal.quotient.mk _ := funext $ λ x, ideal.quotient.lift_mk lemma quot_of_quot_of_eq_supp_quotient_mk' (h : supp v₁ = supp v₂) (r : R) : quot_of_quot_of_eq_supp h (ideal.quotient.mk _ r) = ideal.quotient.mk _ r := by rw ←quot_of_quot_of_eq_supp_quotient_mk h instance quot_of_quot_of_eq_supp.is_ring_hom (h : supp v₁ = supp v₂) : is_ring_hom (quot_of_quot_of_eq_supp h) := by delta quot_of_quot_of_eq_supp; apply_instance def quot_equiv_quot_of_eq_supp (h : supp v₁ = supp v₂) : valuation_ID v₁ ≃r valuation_ID v₂ := { hom :=quot_of_quot_of_eq_supp.is_ring_hom h, ..valuation_ID.equiv h} def quot_equiv_quot_mk_eq_mk (h : supp v₁ = supp v₂) (r : R) : (quot_equiv_quot_of_eq_supp h).to_equiv (ideal.quotient.mk _ r) = ideal.quotient.mk _ r := quot_of_quot_of_eq_supp_quotient_mk' h r lemma quot_of_quot_of_eq_supp_inj (h : supp v₁ = supp v₂) : injective (quot_of_quot_of_eq_supp h) := injective_of_left_inverse (quot_equiv_quot_of_eq_supp h).left_inv lemma valuation_ID_le_of_le_of_equiv (h : v₁.is_equiv v₂) (a b : valuation_ID v₁) : (a ≤ b) ↔ quot_of_quot_of_eq_supp (is_equiv.supp_eq h) a ≤ quot_of_quot_of_eq_supp (is_equiv.supp_eq h) b := by rcases a; rcases b; exact (h a b) def valuation_ID.preorder_equiv (h : v₁.is_equiv v₂) : preorder_equiv (valuation_ID v₁) (valuation_ID v₂) := { le_map := valuation_ID_le_of_le_of_equiv h, ..valuation_ID.equiv h.supp_eq } section open localization def valfield_of_valfield_of_eq_supp (h : supp v₁ = supp v₂) : valuation_field v₁ → valuation_field v₂ := fraction_ring.map (quot_of_quot_of_eq_supp h) (quot_of_quot_of_eq_supp_inj h) lemma valfield_of_valfield_of_eq_supp_quotient_mk (h : supp v₁ = supp v₂) (r : R) : valfield_of_valfield_of_eq_supp h (of $ ideal.quotient.mk _ r) = of (ideal.quotient.mk _ r) := begin unfold valfield_of_valfield_of_eq_supp, rw fraction_ring.map_of, rw quot_of_quot_of_eq_supp_quotient_mk', end instance (h : supp v₁ = supp v₂) : is_field_hom (valfield_of_valfield_of_eq_supp h) := by delta valfield_of_valfield_of_eq_supp; apply_instance instance (h : supp v₁ = supp v₂) : is_monoid_hom (valfield_of_valfield_of_eq_supp h) := is_semiring_hom.is_monoid_hom (valfield_of_valfield_of_eq_supp h) def valfield_equiv_valfield_of_eq_supp (h : supp v₁ = supp v₂) : valuation_field v₁ ≃r valuation_field v₂ := fraction_ring.equiv_of_equiv (quot_equiv_quot_of_eq_supp h) lemma valfield_equiv_eq_valfield_of_valfield (h : supp v₁ = supp v₂) (q : valuation_field v₁) : (valfield_equiv_valfield_of_eq_supp h).to_equiv q = valfield_of_valfield_of_eq_supp h q := rfl instance valfield_equiv.is_field_hom (h : supp v₁ = supp v₂) : is_field_hom (valfield_equiv_valfield_of_eq_supp h).to_fun := by apply_instance lemma valfield_equiv_valfield_mk_eq_mk (h : supp v₁ = supp v₂) (r : R) : (valfield_equiv_valfield_of_eq_supp h).to_equiv (of $ ideal.quotient.mk _ r) = of (ideal.quotient.mk _ r) := valfield_of_valfield_of_eq_supp_quotient_mk h r lemma is_equiv.comap_quot_of_quot (h : v₁.is_equiv v₂) : (v₁.on_quot (set.subset.refl _)).is_equiv (comap (v₂.on_quot (set.subset.refl _)) (quot_of_quot_of_eq_supp h.supp_eq)) := begin rw [← is_equiv.comap_on_quot, ← comap_comp], simp [h], end lemma is_equiv.on_valuation_field_is_equiv (h : v₁.is_equiv v₂) : v₁.on_valuation_field.is_equiv (comap v₂.on_valuation_field (valfield_of_valfield_of_eq_supp h.supp_eq)) := begin delta valfield_of_valfield_of_eq_supp, delta on_valuation_field, erw [← is_equiv.comap_on_frac, ← comap_comp, on_frac_comap_eq], simp [comap_comp, h.comap_quot_of_quot], end def val_ring_equiv_of_is_equiv_aux (h : v₁.is_equiv v₂) : v₁.valuation_ring ≃ v₂.valuation_ring := equiv.subtype_congr (valfield_equiv_valfield_of_eq_supp h.supp_eq).to_equiv $ begin intro x, show _ ≤ _ ↔ _ ≤ _, erw [← v₁.on_valuation_field.map_one, h.on_valuation_field_is_equiv], convert iff.refl _, symmetry, exact valuation.map_one _, end def val_ring_equiv_of_is_equiv (h : v₁.is_equiv v₂) : v₁.valuation_ring ≃r v₂.valuation_ring := { hom := begin cases (valfield_equiv_valfield_of_eq_supp h.supp_eq).hom, constructor, all_goals { intros, apply subtype.val_injective, apply_assumption, } end, ..val_ring_equiv_of_is_equiv_aux h } -- We could prove here -- lemma val_ring_equiv_mk_eq_mk (h : v₁.is_equiv v₂) (r : R) (hr : v₁ r ≤ 1) : -- val_ring_equiv_of_is_equiv.to_equiv ⟨of $ ideal.quotient.mk _ r, proof it's in val_ring⟩ -- = ⟨of $ ideal.quotient.mk _ r, longer proof it's in val ring⟩ -- but I'm not sure we need it. lemma valfeld_le_of_le_of_equiv (h : v₁.is_equiv v₂) (a b : valuation_field v₁) : (a ≤ b) ↔ valfield_of_valfield_of_eq_supp (h.supp_eq) a ≤ valfield_of_valfield_of_eq_supp (h.supp_eq) b := is_equiv.on_valuation_field_is_equiv h a b def valfield.preorder_equiv (h : v₁.is_equiv v₂) : preorder_equiv (valuation_field v₁) (valuation_field v₂) := { le_map := valfeld_le_of_le_of_equiv h, ..(valfield_equiv_valfield_of_eq_supp h.supp_eq).to_equiv } -- units def valfield_units_of_valfield_units_of_eq_supp (h : supp v₁ = supp v₂) : units (valuation_field v₁) → units (valuation_field v₂) := units.map $ valfield_of_valfield_of_eq_supp h instance valfield_units.is_group_hom (h : supp v₁ = supp v₂) : is_group_hom (valfield_units_of_valfield_units_of_eq_supp h) := by unfold valfield_units_of_valfield_units_of_eq_supp; apply_instance lemma units_valfield_of_units_valfield_of_eq_supp_mk (h : supp v₁ = supp v₂) (r : R) (hr : r ∉ supp v₁) : valfield_units_of_valfield_units_of_eq_supp h (units_valfield_mk v₁ r hr) = units_valfield_mk v₂ r (h ▸ hr) := units.ext $ valfield_equiv_valfield_mk_eq_mk h r def valfield_units_equiv_units_of_eq_supp (h : supp v₁ = supp v₂) : group_equiv (units (valuation_field v₁)) (units (valuation_field v₂)) := let h' := valfield_equiv_valfield_of_eq_supp h in by letI := h'.hom; exact units.map_equiv {hom := ⟨h'.hom.map_mul⟩, ..h'} end lemma valfield_units_equiv_units_mk_eq_mk (h : supp v₁ = supp v₂) (r : R) (hr : r ∉ supp v₁): (valfield_units_equiv_units_of_eq_supp h).to_equiv (units_valfield_mk v₁ r hr) = units_valfield_mk v₂ r (h ▸ hr) := units_valfield_of_units_valfield_of_eq_supp_mk h r hr def valfield_units_preorder_equiv (h : v₁.is_equiv v₂) : preorder_equiv (units (valuation_field v₁)) (units (valuation_field v₂)) := { le_map := λ u v, @le_equiv.le_map _ _ _ _ (valfield.preorder_equiv h) u.val v.val, ..valfield_units_equiv_units_of_eq_supp (h.supp_eq) } -- This explicit instance helps type class inference; it's a shortcut. -- The "by apply_instance" proof needs -- set_option class.instance_max_depth 35 instance (h : is_equiv v₁ v₂) : is_subgroup ((valfield_units_of_valfield_units_of_eq_supp (is_equiv.supp_eq h)) ⁻¹' (valuation_field_norm_one v₂)) := normal_subgroup.to_is_subgroup _ -- Same here -- the `by apply_instance` proof needs max_depth 35 instance (h : is_equiv v₁ v₂) : group (quotient_group.quotient ((valfield_units_of_valfield_units_of_eq_supp (is_equiv.supp_eq h)) ⁻¹' (valuation_field_norm_one v₂))) := quotient_group.group ((valfield_units_of_valfield_units_of_eq_supp (is_equiv.supp_eq h)) ⁻¹' (valuation_field_norm_one v₂)) lemma val_one_iff_unit_val_one (x : units (valuation_field v)) : x ∈ valuation_field_norm_one v ↔ ((on_valuation_field v) ↑x = 1) := begin unfold valuation_field_norm_one, rw [mem_ker, ←option.some_inj, unit_map_eq], refl, end lemma is_equiv.norm_one_eq_norm_one (h : is_equiv v₁ v₂) : valfield_units_of_valfield_units_of_eq_supp (is_equiv.supp_eq h) ⁻¹' valuation_field_norm_one v₂ = valuation_field_norm_one v₁ := begin ext x, rw [set.mem_preimage_eq, val_one_iff_unit_val_one x, is_equiv.v_eq_one (is_equiv.on_valuation_field_is_equiv h) x, val_one_iff_unit_val_one], refl, end -- group part of Wedhorn 1.27 (iii) -> (i) def is_equiv.value_group_equiv (h : is_equiv v₁ v₂) : group_equiv (value_group v₁) (value_group v₂) := group_equiv.quotient (valfield_units_equiv_units_of_eq_supp h.supp_eq) (valuation_field_norm_one v₁) (valuation_field_norm_one v₂) $ is_equiv.norm_one_eq_norm_one h lemma value_group_equiv_units_mk_eq_mk (h : is_equiv v₁ v₂) (r : R) (hr : r ∉ supp v₁) : (h.value_group_equiv).to_equiv (value_group_quotient v₁ (units_valfield_mk v₁ r hr)) = value_group_quotient v₂ (units_valfield_mk v₂ r (h.supp_eq ▸ hr)) := begin rw ←valfield_units_equiv_units_mk_eq_mk (h.supp_eq) r hr, refl, end def is_equiv.with_zero_value_group_equiv (h : is_equiv v₁ v₂) : monoid_equiv (with_zero (value_group v₁)) (with_zero (value_group v₂)) := monoid_equiv.to_with_zero_monoid_equiv $ is_equiv.value_group_equiv h -- ordering part of 1.27 (iii) -> (i) def is_equiv.value_group_order_equiv_aux (h : is_equiv v₁ v₂) (x y : value_group v₁) (h2 : x ≤ y) : h.value_group_equiv.to_equiv x ≤ h.value_group_equiv.to_equiv y := begin induction x with x, induction y, swap, refl, swap, refl, exact (is_equiv.on_valuation_field_is_equiv h x y).1 h2, end def is_equiv.value_group_le_equiv (h : is_equiv v₁ v₂) : (value_group v₁) ≃≤ (value_group v₂) := { le_map := λ x y, linear_order_le_iff_of_monotone_injective (h.value_group_equiv.to_equiv.bijective.1) (is_equiv.value_group_order_equiv_aux h) x y ..h.value_group_equiv.to_equiv} def is_equiv.value_group_equiv_monotone (h : is_equiv v₁ v₂) : monotone (h.value_group_equiv.to_equiv) := λ x y, (@@le_equiv.le_map _ _ (is_equiv.value_group_le_equiv h)).1 def is_equiv.with_zero_value_group_le_equiv (h : is_equiv v₁ v₂) : (with_zero (value_group v₁)) ≃≤ (with_zero (value_group v₂)) := preorder_equiv.to_with_zero_preorder_equiv h.value_group_le_equiv def is_equiv.with_zero_value_group_lt_equiv (h : is_equiv v₁ v₂) : (with_zero (value_group v₁)) ≃< (with_zero (value_group v₂)) := preorder_equiv.to_lt_equiv h.with_zero_value_group_le_equiv lemma is_equiv.with_zero_value_group_equiv_mk_eq_mk (h : v₁.is_equiv v₂) (r : R) : with_zero.map h.value_group_equiv.to_equiv (canonical_valuation v₁ r) = canonical_valuation v₂ r := begin by_cases h1 : (r ∈ supp v₁), { -- zero case have hs1 : r ∈ supp (canonical_valuation v₁) := by rwa v₁.canonical_valuation_supp, have hs2 : r ∈ supp (canonical_valuation v₂), rwa is_equiv.supp_eq h.canonical_equiv_of_is_equiv at hs1, rw (mem_supp_iff _ r).1 hs1, rw (mem_supp_iff _ r).1 hs2, refl, }, { -- not in supp case have h2 : r ∉ supp v₂ := by rwa ←h.supp_eq, rw v₁.canonical_valuation_not_mem_supp_eq _ h1, rw v₂.canonical_valuation_not_mem_supp_eq _ h2, show some _ = some _, congr, exact value_group_equiv_units_mk_eq_mk h r h1, } end end -- section end valuation
453b5cb4251cf23f1e10e5846ad7d7b171828d68
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/list/instances.lean
0a995a9c5ade4ab5ee99ebdf9648082443eaeff6
[]
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,102
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.list.lemmas universes u_1 u namespace Mathlib protected instance list.monad : Monad List := { toApplicative := { toFunctor := { map := list.map, mapConst := fun (α β : Type u_1) => list.map ∘ function.const β }, toPure := { pure := list.ret }, toSeq := { seq := fun (α β : Type u_1) (f : List (α → β)) (x : List α) => list.bind f fun (_x : α → β) => list.map _x x }, toSeqLeft := { seqLeft := fun (α β : Type u_1) (a : List α) (b : List β) => (fun (α β : Type u_1) (f : List (α → β)) (x : List α) => list.bind f fun (_x : α → β) => list.map _x x) β α (list.map (function.const β) a) b }, toSeqRight := { seqRight := fun (α β : Type u_1) (a : List α) (b : List β) => (fun (α β : Type u_1) (f : List (α → β)) (x : List α) => list.bind f fun (_x : α → β) => list.map _x x) β β (list.map (function.const α id) a) b } }, toBind := { bind := list.bind } } protected instance list.is_lawful_monad : is_lawful_monad List := sorry protected instance list.alternative : alternative List := alternative.mk List.nil namespace list protected instance bin_tree_to_list {α : Type u} : has_coe (bin_tree α) (List α) := has_coe.mk bin_tree.to_list protected instance decidable_bex {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : Decidable (∃ (x : α), ∃ (H : x ∈ l), p x) := sorry protected instance decidable_ball {α : Type u} (p : α → Prop) [decidable_pred p] (l : List α) : Decidable (∀ (x : α), x ∈ l → p x) := dite (∃ (x : α), ∃ (H : x ∈ l), ¬p x) (fun (h : ∃ (x : α), ∃ (H : x ∈ l), ¬p x) => isFalse sorry) fun (h : ¬∃ (x : α), ∃ (H : x ∈ l), ¬p x) => is_true sorry
161b88993a89a21d233821f2dd5261b3ffdcc0dd
492a7e27d49633a89f7ce6e1e28f676b062fcbc9
/src/monoidal_categories_reboot/monoidal_functor.lean
f5bbf723d772b0ceac3b3ceccdcfd9abb2f8c4fb
[ "Apache-2.0" ]
permissive
semorrison/monoidal-categories-reboot
9edba30277de48a234b63813cf85b171772ce36f
48b5f1d535daba4e591672042a298ac36be2e6dd
refs/heads/master
1,642,472,396,149
1,560,587,477,000
1,560,587,477,000
156,465,626
0
1
null
1,541,549,278,000
1,541,549,278,000
null
UTF-8
Lean
false
false
7,597
lean
-- -- Copyright (c) 2018 Michael Jendrusch. All rights reserved. -- -- Released under Apache 2.0 license as described in the file LICENSE. -- -- Authors: Michael Jendrusch, Scott Morrison -- import .monoidal_category -- open category_theory -- open tactic -- universes v₁ v₂ v₃ u₁ u₂ u₃ -- open category_theory.category -- open category_theory.functor -- namespace category_theory.monoidal -- section -- open monoidal_category -- variables (C : Sort u₁) [𝒞 : monoidal_category.{v₁} C] -- (D : Sort u₂) [𝒟 : monoidal_category.{v₂} D] -- include 𝒞 𝒟 -- structure lax_monoidal_functor extends C ⥤ D := -- -- unit morphism -- (ε : tensor_unit D ⟶ obj (tensor_unit C)) -- -- tensorator -- (μ : Π X Y : C, (obj X) ⊗ (obj Y) ⟶ obj (X ⊗ Y)) -- (μ_natural' : ∀ (X Y X' Y' : C) -- (f : X ⟶ Y) (g : X' ⟶ Y'), -- ((map f) ⊗ (map g)) ≫ μ Y Y' = μ X X' ≫ map (f ⊗ g) -- . obviously) -- -- associativity of the tensorator -- (associativity' : ∀ (X Y Z : C), -- (μ X Y ⊗ 𝟙 (obj Z)) ≫ μ (X ⊗ Y) Z ≫ map (associator X Y Z).hom -- = (associator (obj X) (obj Y) (obj Z)).hom ≫ (𝟙 (obj X) ⊗ μ Y Z) ≫ μ X (Y ⊗ Z) -- . obviously) -- -- unitality -- (left_unitality' : ∀ X : C, -- (left_unitor (obj X)).hom -- = (ε ⊗ 𝟙 (obj X)) ≫ μ (tensor_unit C) X ≫ map (left_unitor X).hom -- . obviously) -- (right_unitality' : ∀ X : C, -- (right_unitor (obj X)).hom -- = (𝟙 (obj X) ⊗ ε) ≫ μ X (tensor_unit C) ≫ map (right_unitor X).hom -- . obviously) -- restate_axiom lax_monoidal_functor.μ_natural' -- attribute [simp] lax_monoidal_functor.μ_natural -- restate_axiom lax_monoidal_functor.left_unitality' -- attribute [simp] lax_monoidal_functor.left_unitality -- restate_axiom lax_monoidal_functor.right_unitality' -- attribute [simp] lax_monoidal_functor.right_unitality -- restate_axiom lax_monoidal_functor.associativity' -- attribute [simp] lax_monoidal_functor.associativity -- -- When `rewrite_search` lands, add @[search] attributes to -- -- lax_monoidal_functor.μ_natural lax_monoidal_functor.left_unitality -- -- lax_monoidal_functor.right_unitality lax_monoidal_functor.associativity -- structure monoidal_functor -- extends lax_monoidal_functor.{v₁ v₂} C D := -- (ε_is_iso : is_iso ε . obviously) -- (μ_is_iso : Π X Y : C, is_iso (μ X Y) . obviously) -- attribute [instance] monoidal_functor.ε_is_iso monoidal_functor.μ_is_iso -- variables {C D} -- def monoidal_functor.ε_iso (F : monoidal_functor.{v₁ v₂} C D) : -- tensor_unit D ≅ F.obj (tensor_unit C) := -- as_iso F.ε -- def monoidal_functor.μ_iso (F : monoidal_functor.{v₁ v₂} C D) (X Y : C) : -- (F.obj X) ⊗ (F.obj Y) ≅ F.obj (X ⊗ Y) := -- as_iso (F.μ X Y) -- end -- namespace monoidal_functor -- open monoidal_category -- -- In order to express the tensorator as a natural isomorphism, -- -- we need to be in at least `Type 0`, so we have products. -- variables {C : Type u₁} [𝒞 : monoidal_category.{v₁+1} C] -- variables {D : Type u₂} [𝒟 : monoidal_category.{v₂+1} D] -- include 𝒞 𝒟 -- def μ_nat_iso (F : monoidal_functor.{v₁+1 v₂+1} C D) : -- (functor.prod F.to_functor F.to_functor) ⋙ (tensor D) ≅ (tensor C) ⋙ F.to_functor := -- nat_iso.of_components -- (by intros; dsimp; apply F.μ_iso) -- (by intros; dsimp; apply F.to_lax_monoidal_functor.μ_natural) -- end monoidal_functor -- section -- variables (C : Sort u₁) [𝒞 : monoidal_category.{v₁} C] -- include 𝒞 -- def monoidal_functor.id : monoidal_functor.{v₁ v₁} C C := -- { ε := 𝟙 _, -- μ := λ X Y, 𝟙 _, -- .. functor.id C } -- @[simp] lemma id_obj (X : C) : (monoidal_functor.id C).obj X = X := rfl -- @[simp] lemma id_map {X X' : C} (f : X ⟶ X') : (monoidal_functor.id C).map f = f := rfl -- @[simp] lemma id_ε : (monoidal_functor.id C).ε = 𝟙 _ := rfl -- @[simp] lemma id_μ (X Y) : (monoidal_functor.id C).μ X Y = 𝟙 _ := rfl -- variables {C} -- variables {D : Sort u₂} [𝒟 : monoidal_category.{v₂} D] -- variables {E : Sort u₃} [ℰ : monoidal_category.{v₃} E] -- include 𝒟 ℰ -- section -- variables (F : lax_monoidal_functor.{v₁ v₂} C D) (G : lax_monoidal_functor.{v₂ v₃} D E) -- -- The proofs here are horrendous; rewrite_search helps a lot. -- def lax_monoidal_functor.comp : lax_monoidal_functor.{v₁ v₃} C E := -- { ε := G.ε ≫ (G.map F.ε), -- μ := λ X Y, G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y), -- μ_natural' := λ _ _ _ _ f g, -- begin -- simp only [functor.comp_map, assoc], -- conv_lhs { rw [←category.assoc], congr, rw [lax_monoidal_functor.μ_natural] }, -- conv_lhs { rw [category.assoc], congr, skip, rw [←map_comp] }, -- conv_rhs { congr, skip, rw [←map_comp, ←lax_monoidal_functor.μ_natural] } -- end, -- associativity' := λ X Y Z, -- begin -- dsimp, -- rw interchange_right_identity, -- slice_rhs 3 4 { rw [← G.to_functor.map_id, G.μ_natural], }, -- slice_rhs 1 3 { rw ←G.associativity, }, -- rw interchange_left_identity, -- slice_lhs 2 3 { rw [← G.to_functor.map_id, G.μ_natural], }, -- rw [category.assoc, category.assoc, category.assoc, category.assoc, category.assoc, -- ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, ←G.to_functor.map_comp, -- F.associativity], -- end, -- left_unitality' := λ X, -- begin -- dsimp, -- rw [G.left_unitality, interchange_left_identity, category.assoc, category.assoc], -- apply congr_arg, -- rw F.left_unitality, -- conv_lhs { congr, skip, rw [map_comp] }, -- conv_lhs { rw [←category.id_app, ←category.assoc] }, -- conv_lhs { congr, rw [←lax_monoidal_functor.μ_natural] }, -- conv_lhs { congr, congr, congr, skip, rw [functor.category.id_app, map_id] }, -- conv_rhs { rw [←category.assoc] }, -- rw map_comp, -- end, -- right_unitality' := λ X, -- begin -- dsimp, -- rw [G.right_unitality, interchange_right_identity, category.assoc, category.assoc], -- apply congr_arg, -- rw F.right_unitality, -- conv_lhs { congr, skip, rw [map_comp] }, -- conv_lhs { rw [←category.id_app, ←category.assoc] }, -- conv_lhs { congr, rw [←lax_monoidal_functor.μ_natural] }, -- conv_lhs { congr, congr, congr, rw [functor.category.id_app, map_id] }, -- conv_rhs { rw [←category.assoc] }, -- rw map_comp, -- end, -- .. (F.to_functor) ⋙ (G.to_functor) }. -- @[simp] lemma lax_monoidal_functor.comp_obj (X : C) : (F.comp G).obj X = G.obj (F.obj X) := rfl -- @[simp] lemma lax_monoidal_functor.comp_map {X X' : C} (f : X ⟶ X') : -- (F.comp G).map f = (G.map (F.map f) : G.obj (F.obj X) ⟶ G.obj (F.obj X')) := rfl -- @[simp] lemma lax_monoidal_functor.comp_ε : (F.comp G).ε = G.ε ≫ (G.map F.ε) := rfl -- @[simp] lemma lax_monoidal_functor.comp_μ (X Y : C) : (F.comp G).μ X Y = G.μ (F.obj X) (F.obj Y) ≫ G.map (F.μ X Y) := rfl -- end -- section -- variables (F : monoidal_functor.{v₁ v₂} C D) (G : monoidal_functor.{v₂ v₃} D E) -- def monoidal_functor.comp : monoidal_functor.{v₁ v₃} C E := -- { ε_is_iso := by { dsimp, apply_instance }, -- TODO tidy should get this -- μ_is_iso := by { dsimp, apply_instance }, -- TODO tidy should get this -- .. (F.to_lax_monoidal_functor).comp (G.to_lax_monoidal_functor) }. -- end -- end -- end category_theory.monoidal
7211ee9a31ec8b7de6f533639c594e62a31a8317
076f5040b63237c6dd928c6401329ed5adcb0e44
/answers/hw6_prop_logic_key.lean
1e41b8be57ce0c3b24fc9c070b36d826919e2dd2
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
7,097
lean
namespace prop_logic /- [25 points total, as indicated below] This assignment has five problems. The first is to extend our propositional logic syntax and semantics to support the three additional connectives, exclusive or (⊕), implies (which we will write as ⇒), and if and only iff (↔). We first give you the definitions developed in class. You are to extend/modify them to support expressions with the new connectives. The remaining problems use this definition of our language of expressions in propositional logic. -/ /--/ ************** *** SYNTAX *** ************** -/ inductive var : Type | mkVar : ℕ → var inductive unOp : Type | notOp inductive binOp : Type | andOp | orOp /-HW 5 points]-/ | xorOp | implOp | iffOp /-HW-/ inductive pExp : Type | litExp : bool → pExp | varExp : var → pExp | unOpExp : unOp → pExp → pExp | binOpExp : binOp → pExp → pExp → pExp open var open pExp open unOp open binOp -- Shorthand notations def pTrue := litExp tt def pFalse := litExp ff def pNot := unOpExp notOp def pAnd := binOpExp andOp def pOr := binOpExp orOp /-HW- [5 points]-/ def pXor := binOpExp xorOp def pImpl := binOpExp implOp def pIff := binOpExp iffOp /-HW-/ -- conventional notation notation e1 ∧ e2 := pAnd e1 e2 notation e1 ∨ e2 := pOr e1 e2 notation ¬ e := pNot e #print ⇒ /-HW- [5 points] -/ notation e1 ⇒ e2 := pImpl e1 e2 notation e1 ⊕ e2 := pXor e1 e2 notation e1 ↔ e2 := pIff e1 e2 /-HW-/ /- ***************** *** SEMANTICS *** ***************** -/ def interpUnOp : unOp → (bool → bool) | notOp := bnot /- -/ /-HW [5 points] -/ def bimpl : bool → bool → bool | tt ff := ff | _ _ := tt def biff : bool → bool → bool | tt tt := tt | ff ff := tt | _ _ := ff /-HW-/ def interpBinOp : binOp → (bool → bool → bool) | andOp := band | orOp := bor /-HW [5 points] -/ | xorOp := bxor | implOp := bimpl | iffOp := biff /-HW-/ /- Given a pExp and an interpretation for the variables, evaluate the pExp to determine its Boolean truth value. -/ def pEval : pExp → (var → bool) → bool | (litExp b) i := b | (varExp v) i := i v | (unOpExp op e) i := (interpUnOp op) (pEval e i) | (binOpExp op e1 e2) i := (interpBinOp op) (pEval e1 i) (pEval e2 i) /- #2 [5 points]. Define X, Y, and Z to be variable expressions with no "aliases". That is each name should be bound to a distinct variable expression term. Hint: Just look at the prop_logic_test.lean file to remind yourself what we did in class. -/ def X : pExp := varExp (mkVar 0) def Y : pExp := varExp (mkVar 1) def Z : pExp := varExp (mkVar 2) /- [25 points total, as indicated] #3. Here are some English language sentences that you are to re-express in propositional logic. Here's one example. -/ /- EXAMPLE: Formalize the following proposition, as a formula in propositional logic: If it's raining then it's raining. -/ -- Solution def R : pExp := varExp (mkVar 4) def p1 : pExp := R ⇒ R /- Explanation: We first choose to represent the smaller proposition, "it's raining", by the variable expression, R. We then formalize the overall natural language expression, if R then R, as the formula, R ⇒ R. Note: R ⇒ R can be pronounced as any of: - if R is true then R is true - if R then R - the truth of R implies the truth of R - R implies R The second and fourth pronounciations are the two that we prefer to use. -/ /- For the remaining problems, use the variables expressions, X, Y, and Z, as already defined. Use parentheses if needed to group sub-expressions. -/ /- A. [5 points] If it's raining and the streets are wet then it's raining. -/ def p2 : pExp := (X ∧ Y) ⇒ X /- [5 points] B. If it's raining and the streets are wet, then the streets are wet and it's raining. -/ def p3 := (X ∧ Y) ⇒ (Y ∧ X) /- [5 points] C. If it's raining then if the streets are wet then it's raining and the streets are wet. -/ def p4 := X ⇒ (Y ⇒ (X ∧ Y)) /- [5 points] D. If it's raining then it's raining or the moon is made of green cheese. -/ def p5 := X ⇒ (X ∨ Y) /- [5 points] E. If it's raining, then if it's raining implies that the streets are wet, then the streets are wet. -/ #check X ⇒ (X ⇒ Y) ⇒ Y /- #4. For each of the propositional logic expressions below, write a truth table and based on your result, state whether the expression is unsatisfiable, satisfiable but not valid, or valid. Here's an example solution for the expression, (X ∧ Y) ⇒ Y. X Y X ∧ Y (X ∧ Y) ⇒ Y - - ----- ----------- T T T T ⇒ T = T T F F F ⇒ F = T F T F F ⇒ T = T F F F F ⇒ F = T The proposition is thus valid. -/ /- [5 points] A. After the #check give your answer for the checked proposition. Important to know: implies is right associative. -/ #check (X ⇒ Y) ⇒ (¬ X ⇒ ¬ Y) /- X Y X ⇒ Y ¬ X ⇒ ¬ Y Result - - ----- --------- ------ T T T T T T F F T T F T T F F F F T T T Formula is satisfiable but not valid. -/ /- B. [10 points] -/ #check ((X ⇒ Y) ∧ (Y ⇒ X)) ⇒ (X ⇒ Z) /- THE ORIGINAL ANSWER KEY GAVE ANSWER FOR A DIFFERENT QUESTION. THIS ANSWER IS CORRECT. X Y Z X ⇒ Y Y ⇒ X (X ⇒ Y) ∧ (Y ⇒ X) X ⇒ Z Result - - - ----- ----- ----------------- ----- ------ T T T T T T T T T T F T T T F F T F T F T F T T T F F F T F F T F T T T F F T T F T F T F F T T F F T T T T T T F F F T T T T T This formula is NOT valid. -/ /- C. [5 points] -/ #check pFalse ⇒ (X ∧ ¬ X) /- Truth table answers omitted here and below. Maybe a TA will fill in answers. This proposition is valid. -/ /- D. [5 points] -/ #check pTrue ⇒ (X ∧ ¬ X) -- Unsatisfiable. /- E. [5 points] -/ #check (X ∨ Y) ∧ X ⇒ ¬ Y -- Satisfiable but not valid. /- [15 points total] #5. Find and present an interpretation that causes the following proposition to be satisfied (to evaluate to true). (X ∨ Y) ∧ (¬ Y ∨ Z) Answer [5 points]: Next determine how many interpretations satisfy it. Answer [10 points]: X Y Z (X ∨ Y) (¬ Y or Z) (X ∨ Y) ∧ (¬ Y ∨ Z) T T T T F F T T F T F F T F T T F F T F F T T T * model F T T T T T * model F T F T F F F F T F T F F F F F T F ANSWER: Two interpretations satisfy the formula, as per the truth table above, which gives the two satisfying assignments of values to the variables (models). -/ end prop_logic
8dc048899ecc57d77849e6ce2a4bfbcff0b9bc7b
abd85493667895c57a7507870867b28124b3998f
/src/ring_theory/noetherian.lean
55f3ba6460830cda5b8e1c5d377b521f39ed2aba
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
23,154
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal_operations import linear_algebra.basis /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set namespace submodule variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ideal.quotient.mk_one] at hr1 hc1 ⊢, rw [ideal.quotient.mk_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, finite_union ht₁.1 ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_group P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, finite_image _ ht.1, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨prod.inl '' tb ∪ prod.inr '' tc, finite_union (finite_image _ htb.1) (finite_image _ htc.1), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [ring R] [add_comm_group M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext i, cases i, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext i, cases i with i his, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext i, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function @[nolint ge_or_gt] -- see Note [nolint_ge] theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, finite_insert _ hs, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nonzero R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (subtype.val : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, order_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (subtype.val ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((subtype.val ∘ f) '' {m | m ≤ a}) ≤ span R ((subtype.val ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff zero_ne_one hs (this a) (this b), set.image_subset_image_iff (subtype.val_injective.comp f.inj), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((subtype.val ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one R h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨s.attach.sum (λ i, f i • i.1), N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change s.attach.sum (λ i, (f i + g i) • _) = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change s.attach.sum (λ i, (c • f i) • _) = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x.1, subtype.eq _⟩, change s.attach.sum (λ i, l i.1 • i.1) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin unfold is_noetherian_ring at H ⊢, rw is_noetherian_iff_well_founded at H ⊢, convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace is_noetherian_ring variables {R : Type*} [integral_domain R] [is_noetherian_ring R] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : R, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set R)) (well_founded_submodule_gt _ _) lemma exists_irreducible_factor {a : R} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : R → Prop} (a : R) (h0 : P 0) (hu : ∀ u : R, is_unit u → P u) (hi : ∀ a i : R, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : R) : a ≠ 0 → ∃f : multiset R, (∀b ∈ f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) local attribute [instance] set.pointwise_mul_semiring theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, set.pointwise_mul_finite hfm hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
3d89b02c17ed1f4268299d0bcc78ba992f1b5d9a
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Elab/Deriving/BEq.lean
7357f952f7cf693aff5ed684ca076bfe94840e67
[ "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
4,447
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Transform import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util namespace Lean.Elab.Deriving.BEq open Lean.Parser.Term open Meta def mkBEqHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do mkHeader ctx `BEq 2 indVal def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Syntax := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkElseAlt : TermElabM Syntax := do let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.numIndices] do patterns := patterns.push (← `(_)) patterns := patterns.push (← `(_)) patterns := patterns.push (← `(_)) let altRhs ← `(false) `(matchAltExpr| | $[$patterns:term],* => $altRhs:term) mkAlts : TermElabM (Array Syntax) := do let mut alts := #[] for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do let type ← Core.betaReduce type -- we 'beta-reduce' to eliminate "artificial" dependencies let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.numIndices] do patterns := patterns.push (← `(_)) let mut ctorArgs1 := #[] let mut ctorArgs2 := #[] let mut rhs ← `(true) -- add `_` for inductive parameters, they are inaccessible for i in [:indVal.numParams] do ctorArgs1 := ctorArgs1.push (← `(_)) ctorArgs2 := ctorArgs2.push (← `(_)) for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i] if type.containsFVar x.fvarId! then -- If resulting type depends on this field, we don't need to compare ctorArgs1 := ctorArgs1.push (← `(_)) ctorArgs2 := ctorArgs2.push (← `(_)) else let a := mkIdent (← mkFreshUserName `a) let b := mkIdent (← mkFreshUserName `b) ctorArgs1 := ctorArgs1.push a ctorArgs2 := ctorArgs2.push b if (← inferType x).isAppOf indVal.name then rhs ← `($rhs && $(mkIdent auxFunName):ident $a:ident $b:ident) else rhs ← `($rhs && $a:ident == $b:ident) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs1:term*)) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs2:term*)) `(matchAltExpr| | $[$patterns:term],* => $rhs:term) alts := alts.push alt alts := alts.push (← mkElseAlt) return alts def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do let auxFunName ← ctx.auxFunNames[i] let indVal ← ctx.typeInfos[i] let header ← mkBEqHeader ctx indVal let mut body ← mkMatch ctx header indVal auxFunName if ctx.usePartial then let letDecls ← mkLocalInstanceLetDecls ctx `BEq header.argNames body ← mkLet letDecls body let binders := header.binders if ctx.usePartial then `(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : Bool := $body:term) else `(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : Bool := $body:term) def mkMutualBlock (ctx : Context) : TermElabM Syntax := do let mut auxDefs := #[] for i in [:ctx.typeInfos.size] do auxDefs := auxDefs.push (← mkAuxFunction ctx i) `(mutual set_option match.ignoreUnusedAlts true $auxDefs:command* end) private def mkBEqInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do let ctx ← mkContext "beq" declNames[0] let cmds := #[← mkMutualBlock ctx] ++ (← mkInstanceCmds ctx `BEq declNames) trace[Elab.Deriving.beq] "\n{cmds}" return cmds open Command def mkBEqInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if (← declNames.allM isInductive) && declNames.size > 0 then let cmds ← liftTermElabM none <| mkBEqInstanceCmds declNames cmds.forM elabCommand return true else return false builtin_initialize registerBuiltinDerivingHandler `BEq mkBEqInstanceHandler registerTraceClass `Elab.Deriving.beq end Lean.Elab.Deriving.BEq
12fb475bd7d5fb0b381018fb4538d3dabd5fe36d
649957717d58c43b5d8d200da34bf374293fe739
/src/tactic/norm_num.lean
cf907f4baae25e41238a5b68bba63e9594b0e945
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
18,836
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro Evaluating arithmetic expressions including *, +, -, ^, ≤ -/ import algebra.group_power data.rat.basic data.nat.prime import tactic.interactive tactic.converter.interactive universes u v w namespace expr protected meta def to_pos_rat : expr → option ℚ | `(%%e₁ / %%e₂) := do m ← e₁.to_nat, n ← e₂.to_nat, some (rat.mk m n) | e := do n ← e.to_nat, return (rat.of_int n) protected meta def to_rat : expr → option ℚ | `(has_neg.neg %%e) := do q ← e.to_pos_rat, some (-q) | e := e.to_pos_rat protected meta def of_rat (α : expr) : ℚ → tactic expr | ⟨(n:ℕ), d, h, c⟩ := do e₁ ← expr.of_nat α n, if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂] | ⟨-[1+n], d, h, c⟩ := do e₁ ← expr.of_nat α (n+1), e ← (if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂]), tactic.mk_app ``has_neg.neg [e] end expr namespace tactic meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e end tactic open tactic namespace norm_num variable {α : Type u} lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] theorem bit0_zero [add_group α] : bit0 (0 : α) = 0 := add_zero _ theorem bit1_zero [add_group α] [has_one α] : bit1 (0 : α) = 1 := by rw [bit1, bit0_zero, zero_add] lemma pow_bit0_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) : a ^ bit0 b = t * t := by simp [pow_bit0, h] lemma pow_bit1_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) : a ^ bit1 b = t * t * a := by simp [pow_bit1, h] lemma lt_add_of_pos_helper [ordered_cancel_comm_monoid α] (a b c : α) (h : a + b = c) (h₂ : 0 < b) : a < c := h ▸ (lt_add_iff_pos_right _).2 h₂ lemma nat_div_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a / b = q := by rw [← h, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a % b = r := by rw [← h, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] meta def eval_pow (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := match m with | `(nat.has_pow) := mk_app ``nat.pow [e₁, e₂] >>= eval_pow | `(@monoid.has_pow %%α %%m) := mk_app ``monoid.pow [e₁, e₂] >>= eval_pow | _ := failed end | `(monoid.pow %%e₁ 0) := do p ← mk_app ``pow_zero [e₁], a ← infer_type e₁, o ← mk_app ``has_one.one [a], return (o, p) | `(monoid.pow %%e₁ 1) := do p ← mk_app ``pow_one [e₁], return (e₁, p) | `(monoid.pow %%e₁ (bit0 %%e₂)) := do e ← mk_app ``monoid.pow [e₁, e₂], (e', p) ← simp e, p' ← mk_app ``norm_num.pow_bit0_helper [e₁, e', e₂, p], e'' ← to_expr ``(%%e' * %%e'), return (e'', p') | `(monoid.pow %%e₁ (bit1 %%e₂)) := do e ← mk_app ``monoid.pow [e₁, e₂], (e', p) ← simp e, p' ← mk_app ``norm_num.pow_bit1_helper [e₁, e', e₂, p], e'' ← to_expr ``(%%e' * %%e' * %%e₁), return (e'', p') | `(nat.pow %%e₁ %%e₂) := do p₁ ← mk_app ``nat.pow_eq_pow [e₁, e₂], e ← mk_app ``monoid.pow [e₁, e₂], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := failed meta def prove_pos : instance_cache → expr → tactic (instance_cache × expr) | c `(has_one.one _) := do (c, p) ← c.mk_app ``zero_lt_one [], return (c, p) | c `(bit0 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit0_pos [e, p], return (c, p) | c `(bit1 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit1_pos' [e, p], return (c, p) | c `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos c e₁, (c, p₂) ← prove_pos c e₂, (c, p) ← c.mk_app ``div_pos_of_pos_of_pos [e₁, e₂, p₁, p₂], return (c, p) | c e := failed meta def prove_lt (simp : expr → tactic (expr × expr)) : instance_cache → expr → expr → tactic (instance_cache × expr) | c `(- %%e₁) `(- %%e₂) := do (c, p) ← prove_lt c e₁ e₂, (c, p) ← c.mk_app ``neg_lt_neg [e₁, e₂, p], return (c, p) | c `(- %%e₁) `(has_zero.zero _) := do (c, p) ← prove_pos c e₁, (c, p) ← c.mk_app ``neg_neg_of_pos [e₁, p], return (c, p) | c `(- %%e₁) e₂ := do (c, p₁) ← prove_pos c e₁, (c, me₁) ← c.mk_app ``has_neg.neg [e₁], (c, p₁) ← c.mk_app ``neg_neg_of_pos [e₁, p₁], (c, p₂) ← prove_pos c e₂, (c, z) ← c.mk_app ``has_zero.zero [], (c, p) ← c.mk_app ``lt_trans [me₁, z, e₂, p₁, p₂], return (c, p) | c `(has_zero.zero _) e₂ := prove_pos c e₂ | c e₁ e₂ := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, d ← expr.of_rat c.α (n₂ - n₁), (c, e₃) ← c.mk_app ``has_add.add [e₁, d], (e₂', p) ← norm_num e₃, guard (e₂'.is_num_eq e₂), (c, p') ← prove_pos c d, (c, p) ← c.mk_app ``norm_num.lt_add_of_pos_helper [e₁, d, e₂, p, p'], return (c, p) private meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk <$> mk_const `true <*> mk_app ``eq_true_intro [p] private meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk <$> mk_const `false <*> mk_app ``eq_false_intro [p] meta def eval_ineq (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt simp c e₁ e₂, true_intro p else do (c, p) ← if n₁ = n₂ then c.mk_app ``lt_irrefl [e₁] else (do (c, p') ← prove_lt simp c e₂ e₁, c.mk_app ``not_lt_of_gt [e₁, e₂, p']), false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (c, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else (do (c, p') ← prove_lt simp c e₁ e₂, c.mk_app ``le_of_lt [e₁, e₂, p']), true_intro p else do (c, p) ← prove_lt simp c e₂ e₁, (c, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (c, p) ← prove_lt simp c e₁ e₂, (c, p) ← c.mk_app ``ne_of_lt [e₁, e₂, p], false_intro p else if n₂ < n₁ then do (c, p) ← prove_lt simp c e₂ e₁, (c, p) ← c.mk_app ``ne_of_gt [e₁, e₂, p], false_intro p else mk_eq_refl e₁ >>= true_intro | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= simp | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= simp | `(%%e₁ ≠ %%e₂) := do e ← mk_app ``eq [e₁, e₂], mk_app ``not [e] >>= simp | _ := failed meta def eval_div_ext (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(has_inv.inv %%e) := do c ← infer_type e >>= mk_instance_cache, (c, p₁) ← c.mk_app ``inv_eq_one_div [e], (c, o) ← c.mk_app ``has_one.one [], (c, e') ← c.mk_app ``has_div.div [o, e], (do (e'', p₂) ← simp e', p ← mk_eq_trans p₁ p₂, return (e'', p)) <|> return (e', p₁) | `(%%e₁ / %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, match α with | `(nat) := do n₁ ← e₁.to_nat, n₂ ← e₂.to_nat, q ← expr.of_nat α (n₁ / n₂), r ← expr.of_nat α (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, p') ← prove_lt simp c r e₂, p ← mk_app ``norm_num.nat_div_helper [e₁, e₂, q, r, p, p'], return (q, p) | `(int) := match e₂ with | `(- %%e₂') := do (c, p₁) ← c.mk_app ``int.div_neg [e₁, e₂'], (c, e) ← c.mk_app ``has_div.div [e₁, e₂'], (c, e) ← c.mk_app ``has_neg.neg [e], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := do n₁ ← e₁.to_int, n₂ ← e₂.to_int, q ← expr.of_rat α $ rat.of_int (n₁ / n₂), r ← expr.of_rat α $ rat.of_int (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, r0) ← c.mk_app ``has_zero.zero [], (c, r0) ← c.mk_app ``has_le.le [r0, r], (_, p₁) ← simp r0, p₁ ← mk_app ``of_eq_true [p₁], (c, p₂) ← prove_lt simp c r e₂, p ← mk_app ``norm_num.int_div_helper [e₁, e₂, q, r, p, p₁, p₂], return (q, p) end | _ := failed end | `(%%e₁ % %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, match α with | `(nat) := do n₁ ← e₁.to_nat, n₂ ← e₂.to_nat, q ← expr.of_nat α (n₁ / n₂), r ← expr.of_nat α (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, p') ← prove_lt simp c r e₂, p ← mk_app ``norm_num.nat_mod_helper [e₁, e₂, q, r, p, p'], return (r, p) | `(int) := match e₂ with | `(- %%e₂') := do let p₁ := (expr.const ``int.mod_neg []).mk_app [e₁, e₂'], (c, e) ← c.mk_app ``has_mod.mod [e₁, e₂'], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := do n₁ ← e₁.to_int, n₂ ← e₂.to_int, q ← expr.of_rat α $ rat.of_int (n₁ / n₂), r ← expr.of_rat α $ rat.of_int (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, r0) ← c.mk_app ``has_zero.zero [], (c, r0) ← c.mk_app ``has_le.le [r0, r], (_, p₁) ← simp r0, p₁ ← mk_app ``of_eq_true [p₁], (c, p₂) ← prove_lt simp c r e₂, p ← mk_app ``norm_num.int_mod_helper [e₁, e₂, q, r, p, p₁, p₂], return (r, p) end | _ := failed end | `(%%e₁ ∣ %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, n ← match α with | `(nat) := return ``nat.dvd_iff_mod_eq_zero | `(int) := return ``int.dvd_iff_mod_eq_zero | _ := failed end, p₁ ← mk_app ``propext [@expr.const tt n [] e₁ e₂], (e', p₂) ← simp `(%%e₂ % %%e₁ = 0), p' ← mk_eq_trans p₁ p₂, return (e', p') | _ := failed lemma not_prime_helper (a b n : ℕ) (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ nat.prime n := by rw ← h; exact nat.not_prime_mul h₁ h₂ lemma is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := nat.prime_def_min_fac.2 ⟨h₁, h₂⟩ lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 := by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]] def min_fac_helper (n k : ℕ) : Prop := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n := nat.pos_iff_ne_zero.2 $ λ e, by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2 lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := by rw bit0_eq_two_mul; exact λ e, absurd ((nat.dvd_add_iff_right (by simp [bit0_eq_two_mul n])).2 (dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) dec_trivial lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := begin refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩, refine @lt_of_le_of_ne ℕ _ _ _ (nat.min_fac_pos _) _, intro e, have := nat.min_fac_prime _, { rw ← e at this, exact nat.not_prime_one this }, { exact ne_of_gt (nat.bit1_lt h) } end lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := begin rw ← e, refine ⟨nat.succ_pos _, (lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _) min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩, { rw add_right_comm, exact h.2 }, { rw add_right_comm, exact np.symm } end lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k') (np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw ← e₁ at np, exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos) end lemma min_fac_helper_3 (n k k' : ℕ) (e : k + 1 = k') (nd : bit1 k ∣ bit1 n = false) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw [eq_false, ← e₁] at nd, exact nd (nat.min_fac_dvd _) end lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 k ∣ bit1 n = true) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := by rw eq_true at hd; exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := begin refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2 ⟨nat.bit1_lt h.n_pos, _⟩)).2, rw ← e at hd, intros m m2 hm md, have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm), rw nat.le_sqrt at this, exact not_le_of_lt hd this end meta def prove_non_prime (simp : expr → tactic (expr × expr)) (e : expr) (n d₁ : ℕ) : tactic expr := do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt simp c `(1) e₁, let d₂ := n / d₁, let e₂ := reflect d₂, (e', p) ← mk_app ``has_mul.mul [e₁, e₂] >>= norm_num, guard (e' =ₐ e), (c, p₂) ← prove_lt simp c `(1) e₂, return $ (expr.const ``not_prime_helper []).mk_app [e₁, e₂, e, p, p₁, p₂] meta def prove_min_fac (simp : expr → tactic (expr × expr)) (e₁ : expr) (n1 : ℕ) : expr → expr → tactic (expr × expr) | e₂ p := do k ← e₂.to_nat, let k1 := bit1 k, e₁1 ← mk_app ``bit1 [e₁], e₂1 ← mk_app ``bit1 [e₂], if n1 < k1*k1 then do c ← mk_instance_cache `(nat), (c, e') ← c.mk_app ``has_mul.mul [e₂1, e₂1], (e', p₁) ← norm_num e', (c, p₂) ← prove_lt simp c e₁1 e', p' ← mk_app ``min_fac_helper_5 [e₁, e₂, e', p₁, p₂, p], return (e₁1, p') else let d := k1.min_fac in if to_bool (d < k1) then do (e', p₁) ← norm_num `(%%e₂ + 1), p₂ ← prove_non_prime simp e₂1 k1 d, mk_app ``min_fac_helper_2 [e₁, e₂, e', p₁, p₂, p] >>= prove_min_fac e' else do (_, p₂) ← simp `((%%e₂1 : ℕ) ∣ %%e₁1), if k1 ∣ n1 then do p' ← mk_app ``min_fac_helper_4 [e₁, e₂, p₂, p], return (e₂1, p') else do (e', p₁) ← norm_num `(%%e₂ + 1), mk_app ``min_fac_helper_3 [e₁, e₂, e', p₁, p₂, p] >>= prove_min_fac e' meta def eval_prime (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(nat.prime %%e) := do n ← e.to_nat, match n with | 0 := false_intro `(nat.not_prime_zero) | 1 := false_intro `(nat.not_prime_one) | _ := let d₁ := n.min_fac in if d₁ < n then prove_non_prime simp e n d₁ >>= false_intro else do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt simp c `(1) e₁, (e₁, p) ← simp `(nat.min_fac %%e), true_intro $ (expr.const ``is_prime_helper []).mk_app [e, p₁, p] end | `(nat.min_fac 0) := refl_conv (reflect (0:ℕ)) | `(nat.min_fac 1) := refl_conv (reflect (1:ℕ)) | `(nat.min_fac (bit0 %%e)) := prod.mk `(2) <$> mk_app ``min_fac_bit0 [e] | `(nat.min_fac (bit1 %%e)) := do n ← e.to_nat, c ← mk_instance_cache `(nat), (c, p) ← prove_pos c e, mk_app ``min_fac_helper_0 [e, p] >>= prove_min_fac simp e (bit1 n) `(1) | _ := failed meta def derive1 (simp : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := norm_num e <|> eval_div_ext simp e <|> eval_pow simp e <|> eval_ineq simp e <|> eval_prime simp e meta def derive : expr → tactic (expr × expr) | e := do e ← instantiate_mvars e, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← derive1 derive e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) end norm_num namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← tactic.replace_at derive ns loc.include_goal | fail "norm_num failed to simplify", when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` `<` `≤` over ordered fields (or other appropriate classes), as well as `-` `/` `%` over `ℤ` and `ℕ`. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := repeat1 $ orelse' (norm_num1 l) $ simp_core {} (norm_num1 (loc.ns [none])) ff hs [] l meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ end tactic.interactive namespace conv.interactive open conv interactive tactic.interactive open norm_num (derive) meta def norm_num1 : conv unit := replace_lhs derive meta def norm_num (hs : parse simp_arg_list) : conv unit := repeat1 $ orelse' norm_num1 $ simp_core {} norm_num1 ff hs [] (loc.ns [none]) end conv.interactive
7a986d2b1acf2a62c19916ea66995ffaac2291cd
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/analysis/topology/uniform_space.lean
ab01d36489e88481567be85c7ddb9b17632981a8
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
77,489
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 Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * completion (on Cauchy filters instead of Cauchy sequences) * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact One reason to directly formalize uniform spaces is foundational: we define ℝ as a completion of ℚ. The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.quot analysis.topology.topological_space analysis.topology.continuity open set lattice filter classical local attribute [instance] prop_decidable set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U.sets) x, (x, x) ∈ r) (symm : ∀ r ∈ U.sets, {p | prod.swap p ∈ r} ∈ U.sets) (comp : ∀ r ∈ U.sets, ∃ t ∈ U.sets, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity.sets, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity.sets)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity.sets)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity : filter (α × α) := (@uniform_space.to_core α _).uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (@uniformity α _).sets) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : uniformity.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto prod.swap (@uniformity α _) uniformity := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ_, (a, a)) f uniformity := assume s hs, show {x | (a, a) ∈ s} ∈ f.sets, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s := have s ∈ (uniformity.lift' (λt:set (α×α), comp_rel t t)).sets, from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : uniformity ≤ (@prod.swap α α) <$> uniformity := by rw [map_swap_eq_vmap_swap]; from map_le_iff_le_vmap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : uniformity.lift (λs, g (preimage prod.swap s)) ≤ f) : uniformity.lift g ≤ f := calc uniformity.lift g ≤ (filter.map prod.swap (@uniformity α _)).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f := calc uniformity.lift (λs, f (comp_rel s s)) = (uniformity.lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity := calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) = uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = uniformity.lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ uniformity : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : (s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) := ⟨ begin simp [mem_nhds_sets_iff, is_open_uniformity], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_vmap_uniformity {x : α} : nhds x = uniformity.vmap (prod.mk x) := filter.ext.2 $ assume s, by rw [mem_nhds_uniformity_iff, mem_vmap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, uniformity.upwards_sets h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : nhds x = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) := filter_eq $ set.ext $ assume s, begin rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, uniformity.upwards_sets h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {y : α | (x, y) ∈ s} ∈ (nhds x).sets := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {x : α | (x, y) ∈ s} ∈ (nhds y).sets := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) uniformity := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) uniformity := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_preimage $ monotone_comp monotone_preimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> uniformity).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_preimage hg ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = uniformity.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ (nhds (x, y)).sets, begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ (uniformity.lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ uniformity : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ (@uniformity α _).sets, by filter_upwards [hs] this, by simp [this]) (assume s hs, (uniformity.lift' interior).upwards_sets (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : interior s ∈ (@uniformity α _).sets := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed [uniform_space α] {s : set (α×α)} (h : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, is_closed t ∧ t ⊆ s := have s ∈ ((@uniformity α _).lift' closure).sets, by rwa [uniformity_eq_uniformity_closure] at h, have ∃t∈(@uniformity α _).sets, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, uniformity.upwards_sets ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) uniformity uniformity theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ (@uniformity β _).sets, {x : α × α | (f x.1, f x.2) ∈ r} ∈ (@uniformity α _).sets := iff.rfl lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b uniformity lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (g ∘ f) := hf.comp hg def uniform_embedding [uniform_space β] (f : α → β) := function.injective f ∧ vmap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity theorem uniform_embedding_def [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ (@uniformity α _).sets ↔ ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by rw [uniform_embedding, eq_comm, filter.ext]; simp [subset_def] theorem uniform_embedding_def' [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ s, s ∈ (@uniformity α _).sets → ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by simp [uniform_embedding_def, uniform_continuous_def]; exact ⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩, λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s, λ ⟨t, tu, h⟩, upwards_sets _ (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩ lemma uniform_embedding.uniform_continuous [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := (uniform_embedding_def'.1 hf).2.1 lemma uniform_embedding.uniform_continuous_iff [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hg : uniform_embedding g) : uniform_continuous f ↔ uniform_continuous (g ∘ f) := by simp [uniform_continuous, tendsto]; rw [← hg.2, ← map_le_iff_le_vmap, filter.map_map] lemma uniform_embedding.dense_embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) (hd : ∀x, x ∈ closure (range f)) : dense_embedding f := { dense := hd, inj := h.left, induced := begin intro a, simp [h.right.symm, nhds_eq_uniformity], rw [vmap_lift'_eq, vmap_lift'_eq2], refl, exact monotone_preimage, exact monotone_preimage end } lemma uniform_continuous.continuous [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_tendsto.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_preimage, exact monotone_preimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) lemma closure_image_mem_nhds_of_uniform_embedding [uniform_space α] [uniform_space β] {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_embedding e) (he₂ : dense_embedding e) (hs : s ∈ (@uniformity α _).sets) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ (nhds b).sets := have s ∈ (vmap (λp:α×α, (e p.1, e p.2)) $ uniformity).sets, from he₁.right.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ (vmap e $ nhds b).sets, from preimage_mem_vmap $ mem_nhds_left b ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := inhabited_of_mem_sets (he₂.vmap_nhds_neq_bot) this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ (@uniformity β _).sets → {y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s} ≠ ∅, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ (vmap e $ nhds b').sets, from preimage_mem_vmap $ mem_nhds_left b' $ inter_mem_sets hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := inhabited_of_mem_sets (he₂.vmap_nhds_neq_bot) this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ne_empty_of_mem this, have ∀b', (b, b') ∈ t → nhds b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥, begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_neq_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb', ⟨a, (nhds b).upwards_sets (mem_nhds_left b htu) this⟩ /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity lemma cauchy_iff [uniform_space α] {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀s∈(@uniformity α _).sets, ∃t∈f.sets, set.prod t t ⊆ s)) := and_congr (iff.refl _) $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ uniformity.lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ uniformity : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (return_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp [closure_eq_nhds, inf_comm], exact assume h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ assume s, le_infi $ assume hs, begin rw [←forall_sets_neq_empty_iff_neq_bot] at adhs, simp [this s hs], exact f.upwards_sets hs subset_closure end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (assume s t h x h', closure_mono h h') monotone_preimage end ... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact assume s t h, closure_mono h, exact monotone_preimage end ... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [←uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) uniformity : map_mono hf.right ... ≤ uniformity : hm⟩ lemma cauchy_vmap [uniform_space β] {f : filter β} {m : α → β} (hm : vmap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity) (hf : cauchy f) (hb : vmap m f ≠ ⊥) : cauchy (vmap m f) := ⟨hb, calc filter.prod (vmap m f) (vmap m f) = vmap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_vmap_vmap_eq ... ≤ vmap (λp:α×α, (m p.1, m p.2)) uniformity : vmap_mono hf.right ... ≤ uniformity : hm⟩ /- separated uniformity -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (@uniformity α _).sets lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ (@uniformity α _).sets), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ protected def separation_setoid (α : Type u) [u : uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ @[class] def separated (α : Type u) [uniform_space α] := separation_rel α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, (∀ r ∈ (@uniformity α _).sets, (x, y) ∈ r) → x = y := by simp [separated, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, x ≠ y → ∃ r ∈ (@uniformity α _).sets, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [classical.not_forall] instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := separated_def'.1 s x y h in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ (nhds x).sets, from mem_nhds_left x hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ (nhds y).sets, from mem_nhds_right y hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ instance separated_regular [separated α] : regular_space α := { regular := λs a hs ha, have -s ∈ (nhds a).sets, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ uniformity.sets, from mem_nhds_uniformity_iff.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ uniformity.sets, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ (nhds a).sets, from (nhds a).upwards_sets (mem_nhds_left a hd) subset_closure, have nhds a ⊓ principal (-closure e) = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (principal (- closure e)) (principal (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨- closure e, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..separated_t2 } /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ (@uniformity α _).sets, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, let f : u → α := λ x, classical.some x.2.2, have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := finite_subset fk (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, have := ks xs, simp at this, rcases this with ⟨y, hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, simp, exact ⟨_, ⟨_, z.2, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_subset [uniform_space α] {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_closure [uniform_space α] {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : closure_eq_of_is_closed $ is_closed_Union hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ lemma totally_bounded_image [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ (@uniformity α _).sets, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image f hfc, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp [-mem_image], exact let ⟨i, hi, ht⟩ := hct x hx in ⟨f i, mem_image_of_mem f hi, ht⟩ end⟩ lemma totally_bounded_preimage [uniform_space α] [uniform_space β] {f : α → β} {s : set β} (hf : uniform_embedding f) (hs : totally_bounded s) : totally_bounded (f ⁻¹' s) := λ t ht, begin rw ← hf.2 at ht, rcases mem_vmap_sets.2 ht with ⟨t', ht', ts⟩, rcases totally_bounded_iff_subset.1 (totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩, refine ⟨f ⁻¹' c, finite_preimage hf.1 hfc, λ x h, _⟩, have := hct (mem_image_of_mem f h), simp at this ⊢, rcases this with ⟨z, zc, zt⟩, rcases cs zc with ⟨y, yc, rfl⟩, exact ⟨y, zc, ts (by exact zt)⟩ end lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from f.upwards_sets (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).upwards_sets (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa using hs, let f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_eq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.upwards_sets this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_of_totally_bounded_complete {s : set α} (ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) : compact s := begin rw [compact_iff_ultrafilter_le_nhds], rw [totally_bounded_iff_ultrafilter] at ht, exact assume f hf hfs, hc (ht _ hf hfs) hfs end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α] [inhabited α] {f : filter α} (hf : cauchy f) : f ≤ nhds (lim f) := lim_spec (complete_space.complete hf) lemma complete_of_is_closed [complete_space α] {s : set α} {f : filter α} (h : is_closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x := let ⟨x, hx⟩ := complete_space.complete hf in have x ∈ s, from is_closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $ le_inf hx hfs, ⟨x, this, hx⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := @compact_of_totally_bounded_complete α _ s ht $ assume f, complete_of_is_closed hc lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (range m)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ f.upwards_sets ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have vmap m g ≠ ⊥, from vmap_neq_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (range m) ≠ ⊥, by simp [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (range m)) _ $ mem_nhds_left x ht', have h₂ : range m ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (range m)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ range m ∈ (nhds x ⊓ principal (range m)).sets, from @inter_mem_sets α (nhds x ⊓ principal (range m)) _ _ h₁ h₂, let ⟨y, xyt', b, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).upwards_sets hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.vmap m g), from cauchy_vmap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.vmap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.vmap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ /- separation space -/ section separation_space local attribute [instance] separation_setoid instance {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity, refl := assume s hs ⟨a, b⟩ (h : a = b), have ∀a:α, (a, a) ∈ preimage (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) s, from assume a, refl_mem_uniformity hs, h ▸ quotient.induction_on a this, symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_map, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) = uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, uniformity.upwards_sets ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, uniformity.upwards_sets h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma vmap_quotient_le_uniformity : vmap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity ≤ uniformity := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (@uniformity α _).upwards_sets hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma vmap_quotient_eq_uniformity : vmap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity = uniformity := le_antisymm vmap_quotient_le_uniformity le_vmap_map lemma complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (vmap (λx, ⟦x⟧) f), from cauchy_vmap vmap_quotient_le_uniformity hf $ vmap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : vmap (λx, ⟦x⟧) f ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f ≤ map (λx, ⟦x⟧) (vmap (λx, ⟦x⟧) f) : le_map_vmap $ assume b, quotient.exists_rep _ ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_tendsto.mp uniform_continuous_quotient_mk.continuous _⟩⟩ lemma separated_separation [h : complete_space α] : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (vmap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity).sets, from vmap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp, exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ end separation_space section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (range e)) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := (h_e.dense_embedding h_dense).extend f lemma uniformly_extend_of_emb [cγ : complete_space γ] [sγ : separated γ] {b : β} : ψ (e b) = f b := dense_embedding.extend_e_eq _ $ continuous_iff_tendsto.mp h_f.continuous b lemma uniformly_extend_exists [complete_space γ] [sγ : separated γ] {a : α} : ∃c, tendsto f (vmap e (nhds a)) (nhds c) := let de := (h_e.dense_embedding h_dense) in have cauchy (nhds a), from cauchy_nhds, have cauchy (vmap e (nhds a)), from cauchy_vmap (le_of_eq h_e.right) this de.vmap_nhds_neq_bot, have cauchy (map f (vmap e (nhds a))), from cauchy_map h_f this, complete_space.complete this lemma uniformly_extend_spec [complete_space γ] [sγ : separated γ] {a : α} : tendsto f (vmap e (nhds a)) (nhds (ψ a)) := @lim_spec _ (id _) _ _ $ uniformly_extend_exists h_e h_dense h_f lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] [sγ : separated γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have h_pnt : ∀{a m}, m ∈ (nhds a).sets → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : map f (vmap e (nhds a)) ≠ ⊥, from map_ne_bot (h_e.dense_embedding h_dense).vmap_nhds_neq_bot, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ (map f (vmap e (nhds a))).sets, from inter_mem_sets (image_mem_map $ preimage_mem_vmap $ hm) (uniformly_extend_spec h_e h_dense h_f $ inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs)), inhabited_of_mem_sets nb this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (vmap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rwa [h_e.right.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).upwards_sets (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension end uniform_space end /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ (filter.prod (p.1.val) (p.2.val)).sets } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap (uniformity.lift' gen) ≤ uniformity.lift' gen := calc map prod.swap (uniformity.lift' gen) = uniformity.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2.val) (p.1.val)).sets }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ uniformity.lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val.sets, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).upwards_sets (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : (uniformity.lift' gen).lift' (λs, comp_rel s s) ≤ uniformity.lift' gen := calc (uniformity.lift' gen).lift' (λs, comp_rel s s) = uniformity.lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ uniformity.lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = (uniformity.lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ uniformity.lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance completion_space : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := uniformity.lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, ∀ f g : Cauchy α, t ∈ (filter.prod f.1 g.1).sets → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc vmap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity.lift' gen) = uniformity.lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : vmap_lift'_eq monotone_gen ... = uniformity : by simp [this]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ (filter.prod (f.val) (f.val)).sets, from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ (filter.prod f.val (pure x)).sets, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ uniformity.lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).upwards_sets (prod_mem_prod ht' $ mem_pure hx) h, f.upwards_sets ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end end Cauchy instance nonempty_Cauchy {α : Type u} [h : nonempty α] [uniform_space α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a instance inhabited_Cauchy {α : Type u} [inhabited α] [uniform_space α] : inhabited (Cauchy α) := ⟨Cauchy.pure_cauchy $ default α⟩ section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, s.uniformity ≤ t.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, @le_trans _ _ c.uniformity b.uniformity a.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_bot (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ to_topological_space := ⊤, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := by rw [topological_space.lattice.has_top]; simp [subset_def, id_rel] {contextual := tt } }⟩ instance : complete_lattice (uniform_space α) := { 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 h₁ h₂, Sup_le $ assume t', begin simp, intro h, cases h with h h, repeat { subst h; assumption } end, inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := assume a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := assume a b, Sup_le $ assume x ⟨ha, hb⟩, ha, inf_le_right := assume a b, Sup_le $ assume x ⟨ha, hb⟩, hb, top := ⊤, le_top := assume u, u.refl, bot := ⊥, bot_le := assume a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := assume s u, le_Sup, Sup_le := assume s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := assume s a hs, le_Sup hs, Inf_le := assume s a ha, Sup_le $ assume u hs, hs _ ha, ..uniform_space.partial_order } lemma supr_uniformity {ι : Sort*} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _) lemma sup_uniformity {u v : uniform_space α} : (u ⊔ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊔ v) = (⨆i (h : i = u ∨ i = v), i), by simp [supr_or, supr_sup_eq], calc (u ⊔ v).uniformity = ((⨆i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [supr_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.vmap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.vmap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (vmap_mono u.refl), symm := by simp [tendsto_vmap_iff, prod.swap, (∘)]; exact tendsto_vmap.comp tendsto_swap_uniformity, comp := le_trans begin rw [vmap_lift'_eq, vmap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (vmap_mono u.comp), is_open_uniformity := begin intro s, change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced_eq_vmap, mem_nhds_uniformity_iff, filter.vmap, and_comm], exact (ball_congr $ assume x hx, ⟨assume ⟨t, hts, ht⟩, ⟨_, ht, assume ⟨x₁, x₂⟩, by simp [*, subset_def] at * {contextual := tt} ⟩, assume ⟨t, ht, hts⟩, ⟨{y:β | (f x, y) ∈ t}, assume y (hy : (f x, f y) ∈ t), @hts (x, y) hy rfl, mem_nhds_uniformity_iff.mp $ mem_nhds_left _ ht⟩⟩) end } lemma uniform_continuous_vmap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.vmap f u) u f := tendsto_vmap theorem to_topological_space_vmap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.vmap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp [nhds_induced_eq_vmap, nhds_eq_uniformity, nhds_eq_uniformity], change vmap f (uniformity.lift' (preimage (λb, (f a, b)))) = (u.uniformity.vmap (λp:α×α, (f p.1, f p.2))).lift' (preimage (λa', (a, a'))), rw [vmap_lift'_eq monotone_preimage, vmap_lift'_eq2 monotone_preimage], exact rfl end lemma uniform_continuous_vmap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.vmap f v) g := tendsto_vmap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := rfl lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := bot_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊥) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have univ ⊆ _, from hs x hx, have s = univ, from top_unique $ assume y hy, @this (x, y) ⟨⟩ rfl, this.symm ▸ @is_open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort*} {u : ι → uniform_space α} : @uniform_space.to_topological_space α (supr u) = (⨆i, @uniform_space.to_topological_space α (u i)) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (preimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, @nhds_eq_uniformity α (u i) a), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (supr u) = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ assume i, to_topological_space_mono $ le_supr _ _)) lemma to_topological_space_Sup {s : set (uniform_space α)} : @uniform_space.to_topological_space α (Sup s) = (⨆i∈s, @uniform_space.to_topological_space α i) := begin rw [Sup_eq_supr, to_topological_space_supr], apply congr rfl, funext x, exact to_topological_space_supr end lemma to_topological_space_sup {u v : uniform_space α} : @uniform_space.to_topological_space α (u ⊔ v) = @uniform_space.to_topological_space α u ⊔ @uniform_space.to_topological_space α v := ord_continuous_sup $ assume s, to_topological_space_Sup instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.vmap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : (@uniformity (subtype p) _) = vmap (λq:subtype p × subtype p, (q.1.1, q.2.1)) uniformity := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_vmap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_vmap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ (nhds a).sets) : tendsto f (nhds a) (nhds (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_tendsto.mp hf.continuous _) instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.vmap prod.fst ⊔ u₂.vmap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.vmap prod.fst ⊔ u₂.vmap prod.snd).to_topological_space : by rw [to_topological_space_sup, to_topological_space_vmap, to_topological_space_vmap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : @uniformity (α × β) _ = uniformity.vmap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ uniformity.vmap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := sup_uniformity lemma uniform_embedding_subtype_emb {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (de.subtype_emb p) := ⟨(de.subtype p).inj, by simp [vmap_vmap_comp, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.right.symm]⟩ lemma uniform_extend_subtype {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [complete_space γ] [inhabited γ] [separated γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e)) (hb : closure (e '' s) ∈ (nhds b).sets) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (vmap e (nhds b)) (nhds c) := have de : dense_embedding e, from he.dense_embedding hd, have de' : dense_embedding (de.subtype_emb p), by exact de.subtype p, have ue' : uniform_embedding (de.subtype_emb p), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ mono_image $ hp) (mem_of_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (vmap (de.subtype_emb p) (nhds ⟨b, this⟩)) (nhds c))⟩ := uniformly_extend_exists ue' de'.dense hf in begin rw [nhds_subtype_eq_vmap] at hc, simp [vmap_vmap_comp] at hc, change (tendsto (f ∘ @subtype.val α p) (vmap (e ∘ @subtype.val α p) (nhds b)) (nhds c)) at hc, rw [←vmap_vmap_comp] at hc, existsi c, apply tendsto_vmap'' s _ _ hc, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ s, rw [←closure_induced, closure_eq_nhds], dsimp, rw [nhds_induced_eq_vmap, de.induced], change x ∈ {x | nhds x ⊓ principal s ≠ ⊥} → x ∈ s, rw [←closure_eq_nhds, closure_eq_of_is_closed hs], exact id, exact de.inj end⟩, exact (assume x hx, ⟨⟨x, hp x hx⟩, rfl⟩) end /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : @uniformity (α×β) _ = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod uniformity uniformity) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = vmap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_vmap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, vmap_inf, vmap_vmap_comp, vmap_vmap_comp] lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ (@uniformity α _).sets) (hb : b ∈ (@uniformity β _).sets) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _).sets := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_vmap ha) (preimage_mem_vmap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) uniformity uniformity := le_trans (map_mono (@le_sup_left (uniform_space (α×β)) _ _ _)) map_vmap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) uniformity uniformity := le_trans (map_mono (@le_sup_right (uniform_space (α×β)) _ _ _)) map_vmap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd lemma uniform_continuous.prod_mk [uniform_space α] [uniform_space β] [uniform_space γ] {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_vmap_iff.2 h₁, tendsto_vmap_iff.2 h₂⟩ lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α] [uniform_space β] [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, by simp [prod.mk.inj_iff]; exact assume eq₁ eq₂, ⟨h₁.left eq₁, h₂.left eq₂⟩, by simp [(∘), uniformity_prod, h₁.right.symm, h₂.right.symm, vmap_inf, vmap_vmap_comp]⟩ lemma to_topological_space_prod [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl end constructions
908b974c69fa4e3bfd3235783aaaf4231d56d298
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/nat/totient.lean
ccb0ee180f622c90773fa280afc5ec09bae86280
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
7,735
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 algebra.big_operators.basic import data.nat.prime import data.zmod.basic /-! # Euler's totient function This file defines [Euler's totient function][https://en.wikipedia.org/wiki/Euler's_totient_function] `nat.totient n` which counts the number of naturals less than `n` that are coprime with `n`. We prove the divisor sum formula, namely that `n` equals `φ` summed over the divisors of `n`. See `sum_totient`. We also prove two lemmas to help compute totients, namely `totient_mul` and `totient_prime_pow`. -/ open finset open_locale big_operators namespace nat /-- Euler's totient function. This counts the number of naturals strictly less than `n` which are coprime with `n`. -/ def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card localized "notation `φ` := nat.totient" in nat @[simp] theorem totient_zero : φ 0 = 0 := rfl @[simp] theorem totient_one : φ 1 = 1 := by simp [totient] lemma totient_eq_card_coprime (n : ℕ) : φ n = ((range n).filter (nat.coprime n)).card := rfl lemma totient_le (n : ℕ) : φ n ≤ n := calc totient n ≤ (range n).card : card_filter_le _ _ ... = n : card_range _ lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 := dec_trivial | 1 := by simp [totient] | (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩ open zmod @[simp] lemma _root_.zmod.card_units_eq_totient (n : ℕ) [fact (0 < n)] : fintype.card (units (zmod n)) = φ n := calc fintype.card (units (zmod n)) = fintype.card {x : zmod n // x.val.coprime n} : fintype.card_congr zmod.units_equiv_coprime ... = φ n : begin apply finset.card_congr (λ (a : {x : zmod n // x.val.coprime n}) _, a.1.val), { intro a, simp [(a : zmod n).val_lt, a.prop.symm] {contextual := tt} }, { intros _ _ _ _ h, rw subtype.ext_iff_val, apply val_injective, exact h, }, { intros b hb, rw [finset.mem_filter, finset.mem_range] at hb, refine ⟨⟨b, _⟩, finset.mem_univ _, _⟩, { let u := unit_of_coprime b hb.2.symm, exact val_coe_unit_coprime u }, { show zmod.val (b : zmod n) = b, rw [val_nat_cast, nat.mod_eq_of_lt hb.1], } } end lemma totient_mul {m n : ℕ} (h : m.coprime n) : φ (m * n) = φ m * φ n := if hmn0 : m * n = 0 then by cases nat.mul_eq_zero.1 hmn0 with h h; simp only [totient_zero, mul_zero, zero_mul, h] else begin haveI : fact (0 < (m * n)) := ⟨nat.pos_of_ne_zero hmn0⟩, haveI : fact (0 < m) := ⟨nat.pos_of_ne_zero $ left_ne_zero_of_mul hmn0⟩, haveI : fact (0 < n) := ⟨nat.pos_of_ne_zero $ right_ne_zero_of_mul hmn0⟩, rw [← zmod.card_units_eq_totient, ← zmod.card_units_eq_totient, ← zmod.card_units_eq_totient, fintype.card_congr (units.map_equiv (chinese_remainder h).to_mul_equiv).to_equiv, fintype.card_congr (@mul_equiv.prod_units (zmod m) (zmod n) _ _).to_equiv, fintype.card_prod] end lemma sum_totient (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n := if hn0 : n = 0 then by simp [hn0] else calc ∑ m in (range n.succ).filter (∣ n), φ m = ∑ d in (range n.succ).filter (∣ n), ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card : eq.symm $ sum_bij (λ d _, n / d) (λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩) (λ _ _, rfl) (λ a b ha hb h, have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2, have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *), by rw [← nat.mul_left_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2]) (λ b hb, have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb, have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩, have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn, ⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩, by rw [← nat.mul_left_inj (nat.pos_of_ne_zero hnb0), nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩) ... = ∑ d in (range n.succ).filter (∣ n), ((range n).filter (λ m, gcd n m = d)).card : sum_congr rfl (λ d hd, have hd : d ∣ n, from (mem_filter.1 hd).2, have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)), card_congr (λ m hm, d * m) (λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm, mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸ (mul_lt_mul_left hd0).2 hm.1, by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩) (λ a b ha hb h, (nat.mul_right_inj hd0).1 h) (λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb, ⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1 (by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _), nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)), hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩, hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩)) ... = ((filter (∣ n) (range n.succ)).bUnion (λ d, (range n).filter (λ m, gcd n m = d))).card : (card_bUnion (by intros; apply disjoint_filter.2; cc)).symm ... = (range n).card : congr_arg card (finset.ext (λ m, ⟨by finish, λ hm, have h : m < n, from mem_range.1 hm, mem_bUnion.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (zero_le _) h) (gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩)) ... = n : card_range _ /-- When `p` is prime, then the totient of `p ^ (n + 1)` is `p ^ n * (p - 1)` -/ lemma totient_prime_pow_succ {p : ℕ} (hp : p.prime) (n : ℕ) : φ (p ^ (n + 1)) = p ^ n * (p - 1) := calc φ (p ^ (n + 1)) = ((range (p ^ (n + 1))).filter (coprime (p ^ (n + 1)))).card : totient_eq_card_coprime _ ... = (range (p ^ (n + 1)) \ ((range (p ^ n)).image (* p))).card : congr_arg card begin rw [sdiff_eq_filter], apply filter_congr, simp only [mem_range, mem_filter, coprime_pow_left_iff n.succ_pos, mem_image, not_exists, hp.coprime_iff_not_dvd], intros a ha, split, { rintros hap b _ rfl, exact hap (dvd_mul_left _ _) }, { rintros h ⟨b, rfl⟩, rw [pow_succ] at ha, exact h b (lt_of_mul_lt_mul_left ha (zero_le _)) (mul_comm _ _) } end ... = _ : have h1 : set.inj_on (* p) (range (p ^ n)), from λ x _ y _, (nat.mul_left_inj hp.pos).1, have h2 : (range (p ^ n)).image (* p) ⊆ range (p ^ (n + 1)), from λ a, begin simp only [mem_image, mem_range, exists_imp_distrib], rintros b h rfl, rw [pow_succ'], exact (mul_lt_mul_right hp.pos).2 h end, begin rw [card_sdiff h2, card_image_of_inj_on h1, card_range, card_range, ← one_mul (p ^ n), pow_succ, ← nat.mul_sub_right_distrib, one_mul, mul_comm] end /-- When `p` is prime, then the totient of `p ^ ` is `p ^ (n - 1) * (p - 1)` -/ lemma totient_prime_pow {p : ℕ} (hp : p.prime) {n : ℕ} (hn : 0 < n) : φ (p ^ n) = p ^ (n - 1) * (p - 1) := by rcases exists_eq_succ_of_ne_zero (pos_iff_ne_zero.1 hn) with ⟨m, rfl⟩; exact totient_prime_pow_succ hp _ lemma totient_prime {p : ℕ} (hp : p.prime) : φ p = p - 1 := by rw [← pow_one p, totient_prime_pow hp]; simp @[simp] lemma totient_two : φ 2 = 1 := (totient_prime prime_two).trans (by norm_num) end nat
36c7f6801eb18c0b0620f16b9a9d75bc5457089d
618003631150032a5676f229d13a079ac875ff77
/src/tactic/reassoc_axiom.lean
6bdd3951cb4b9849b9e233333627c97b830ba680
[ "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,051
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import category_theory.category /-! # 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 >>= mk_local_pis, (vs',t) ← whnf t >>= mk_local_pis, let vs := vs ++ vs', (lhs,rhs) ← match_eq t, struct_inst ← get_cat_inst lhs <|> get_cat_inst rhs <|> fail "no composition found in statement", `(@has_hom.hom _ %%hom_inst %%X %%Y) ← infer_type lhs, C ← infer_type X, X' ← mk_local' `X' binder_info.implicit C, ft ← to_expr ``(@has_hom.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"] }
0f1328593c1920a612b08dbc06446c7658cd6e6f
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/rat/order.lean
01e4b2a865001e6d2b2d3af8c8934d5fa4739b88
[ "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
9,351
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.basic /-! # Order for Rational Numbers ## Summary We define the order on `ℚ`, prove that `ℚ` is a discrete, linearly ordered field, and define functions such as `abs` and `sqrt` that depend on this order. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, order, ordering, sqrt, abs -/ namespace rat variables (a b c : ℚ) open_locale rat protected def nonneg : ℚ → Prop | ⟨n, d, h, c⟩ := 0 ≤ n @[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : 0 < b) : (a /. b).nonneg ↔ 0 ≤ a := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, simp [rat.nonneg], have d0 := int.coe_nat_lt.2 h₁, have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha, constructor; intro h₂, { apply nonneg_of_mul_nonneg_right _ d0, rw this, exact mul_nonneg h₂ (le_of_lt h) }, { apply nonneg_of_mul_nonneg_right _ h, rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) }, end protected lemma nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], intros n₁0 n₂0, apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}, end protected lemma nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], exact mul_nonneg end protected lemma nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 := num_denom_cases_on' a $ λ n d h, begin have d0 : 0 < (d:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h), simp [d0, h], exact λ h₁ h₂, le_antisymm h₂ h₁ end protected lemma nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) := by cases a with n; exact or.imp_right neg_nonneg_of_nonpos (le_total 0 n) instance decidable_nonneg : decidable (rat.nonneg a) := by cases a; unfold rat.nonneg; apply_instance protected def le (a b : ℚ) := rat.nonneg (b - a) instance : has_le ℚ := ⟨rat.le⟩ instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop) | a b := show decidable (rat.nonneg (b - a)), by apply_instance protected theorem le_def {a b c d : ℤ} (b0 : 0 < b) (d0 : 0 < d) : a /. b ≤ c /. d ↔ a * d ≤ c * b := begin show rat.nonneg _ ↔ _, rw ← sub_nonneg, simp [sub_eq_add_neg, ne_of_gt b0, ne_of_gt d0, mul_pos d0 b0] end protected theorem le_refl : a ≤ a := show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ) protected theorem le_total : a ≤ b ∨ b ≤ a := by have := rat.nonneg_total (b - a); rwa neg_sub at this protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b := by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa); rwa neg_neg at this protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc, by simpa [sub_eq_add_neg, add_comm, add_left_comm] instance : decidable_linear_order ℚ := { le := rat.le, le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := rat.le_total, decidable_eq := by apply_instance, decidable_le := assume a b, rat.decidable_nonneg (b - a) } /- Extra instances to short-circuit type class resolution -/ instance : has_lt ℚ := by apply_instance instance : distrib_lattice ℚ := by apply_instance instance : lattice ℚ := by apply_instance instance : semilattice_inf ℚ := by apply_instance instance : semilattice_sup ℚ := by apply_instance instance : has_inf ℚ := by apply_instance instance : has_sup ℚ := by apply_instance instance : linear_order ℚ := by apply_instance instance : partial_order ℚ := by apply_instance instance : preorder ℚ := by apply_instance protected lemma le_def' {p q : ℚ} : p ≤ q ↔ p.num * q.denom ≤ q.num * p.denom := begin rw [←(@num_denom q), ←(@num_denom p)], conv_rhs { simp only [num_denom] }, exact rat.le_def (by exact_mod_cast p.pos) (by exact_mod_cast q.pos) end protected lemma lt_def {p q : ℚ} : p < q ↔ p.num * q.denom < q.num * p.denom := begin rw [lt_iff_le_and_ne, rat.le_def'], suffices : p ≠ q ↔ p.num * q.denom ≠ q.num * p.denom, by { split; intro h, { exact lt_iff_le_and_ne.elim_right ⟨h.left, (this.elim_left h.right)⟩ }, { have tmp := lt_iff_le_and_ne.elim_left h, exact ⟨tmp.left, this.elim_right tmp.right⟩ }}, exact (not_iff_not.elim_right eq_iff_mul_eq_mul) end theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a := show rat.nonneg a ↔ rat.nonneg (a - 0), by simp theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a | ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩ protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b := by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb instance : discrete_linear_ordered_field ℚ := { zero_lt_one := dec_trivial, add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab, mul_pos := assume a b ha hb, lt_of_le_of_ne (rat.mul_nonneg (le_of_lt ha) (le_of_lt hb)) (mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm, ..rat.field, ..rat.decidable_linear_order, ..rat.semiring } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_field ℚ := by apply_instance instance : decidable_linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_ring ℚ := by apply_instance instance : ordered_ring ℚ := by apply_instance instance : decidable_linear_ordered_semiring ℚ := by apply_instance instance : linear_ordered_semiring ℚ := by apply_instance instance : ordered_semiring ℚ := by apply_instance instance : decidable_linear_ordered_add_comm_group ℚ := by apply_instance instance : ordered_add_comm_group ℚ := by apply_instance instance : ordered_cancel_add_comm_monoid ℚ := by apply_instance instance : ordered_add_comm_monoid ℚ := by apply_instance attribute [irreducible] rat.le theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a := lt_iff_lt_of_le_iff_le $ by simpa [(by cases a; refl : (-a).num = -a.num)] using @num_nonneg_iff_zero_le (-a) lemma div_lt_div_iff_mul_lt_mul {a b c d : ℤ} (b_pos : 0 < b) (d_pos : 0 < d) : (a : ℚ) / b < c / d ↔ a * d < c * b := begin simp only [lt_iff_le_not_le], apply and_congr, { simp [div_num_denom, (rat.le_def b_pos d_pos)] }, { apply not_iff_not_of_iff, simp [div_num_denom, (rat.le_def d_pos b_pos)] } end lemma lt_one_iff_num_lt_denom {q : ℚ} : q < 1 ↔ q.num < q.denom := begin cases decidable.em (0 < q) with q_pos q_nonpos, { simp [rat.lt_def] }, { replace q_nonpos : q ≤ 0, from not_lt.elim_left q_nonpos, have : q.num < q.denom, by { have : ¬0 < q.num ↔ ¬0 < q, from not_iff_not.elim_right num_pos_iff_pos, simp only [not_lt] at this, exact lt_of_le_of_lt (this.elim_right q_nonpos) (by exact_mod_cast q.pos) }, simp only [this, (lt_of_le_of_lt q_nonpos zero_lt_one)] } end theorem abs_def (q : ℚ) : abs q = q.num.nat_abs /. q.denom := begin have hz : (0:ℚ) = 0 /. 1 := rfl, cases le_total q 0 with hq hq, { rw [abs_of_nonpos hq], rw [←(@num_denom q), hz, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one, mul_one, zero_mul] at hq, rw [int.of_nat_nat_abs_of_nonpos hq, ← neg_def, num_denom] }, { rw [abs_of_nonneg hq], rw [←(@num_denom q), hz, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos), mul_one, zero_mul] at hq, rw [int.nat_abs_of_nonneg hq, num_denom] } end section sqrt @[pp_nodot] def sqrt (q : ℚ) : ℚ := rat.mk (int.sqrt q.num) (nat.sqrt q.denom) theorem sqrt_eq (q : ℚ) : rat.sqrt (q*q) = abs q := by rw [sqrt, mul_self_num, mul_self_denom, int.sqrt_eq, nat.sqrt_eq, abs_def] theorem exists_mul_self (x : ℚ) : (∃ q, q * q = x) ↔ rat.sqrt x * rat.sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, abs_mul_abs_self], λ h, ⟨rat.sqrt x, h⟩⟩ theorem sqrt_nonneg (q : ℚ) : 0 ≤ rat.sqrt q := nonneg_iff_zero_le.1 $ (mk_nonneg _ $ int.coe_nat_pos.2 $ nat.pos_of_ne_zero $ λ H, nat.pos_iff_ne_zero.1 q.pos $ nat.sqrt_eq_zero.1 H).2 trivial end sqrt end rat
abca62e9197cf2964e1a36439cc3609752980ab9
626e312b5c1cb2d88fca108f5933076012633192
/src/algebra/field_power.lean
03054085300048b4358b05822c8956301429f17c
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,127
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import algebra.group_with_zero.power import tactic.linarith /-! # Integer power operation on fields and division rings This file collects basic facts about the operation of raising an element of a `division_ring` to an integer power. More specialised results are provided in the case of a linearly ordered field. -/ universe u @[simp] lemma ring_hom.map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K →+* L) : ∀ (a : K) (n : ℤ), f (a ^ n) = f a ^ n := f.to_monoid_with_zero_hom.map_fpow @[simp] lemma fpow_bit0_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit0 n) = x ^ bit0 n := by rw [fpow_bit0', fpow_bit0', neg_mul_neg] lemma fpow_even_neg {K : Type*} [division_ring K] (a : K) {n : ℤ} (h : even n) : (-a) ^ n = a ^ n := begin obtain ⟨k, rfl⟩ := h, simp [←bit0_eq_two_mul] end @[simp] lemma fpow_bit1_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit1 n) = - x ^ bit1 n := by rw [fpow_bit1', fpow_bit1', neg_mul_neg, neg_mul_eq_mul_neg] section ordered_field_power open int variables {K : Type u} [linear_ordered_field K] {a : K} {n : ℤ} lemma fpow_eq_zero_iff (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨fpow_eq_zero, _⟩, rintros rfl, exact zero_fpow _ hn.ne' end lemma fpow_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z | (n : ℕ) := by { rw gpow_coe_nat, exact pow_nonneg ha _ } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) } lemma fpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z | (n : ℕ) := by { rw gpow_coe_nat, exact pow_pos ha _ } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) } lemma fpow_le_of_le {x : K} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := begin induction a with a a; induction b with b b, { simp only [of_nat_eq_coe, gpow_coe_nat], apply pow_le_pow hx, apply le_of_coe_nat_le_coe_nat h }, { apply absurd h, apply not_le_of_gt, exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) }, { simp only [gpow_neg_succ_of_nat, one_div, of_nat_eq_coe, gpow_coe_nat], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [gpow_neg_succ_of_nat], apply (inv_le_inv _ _).2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma pow_le_max_of_min_le {x : K} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) := begin wlog hle : a ≤ b, have hnle : -b ≤ -a, from neg_le_neg hle, have hfle : x ^ (-b) ≤ x ^ (-a), from fpow_le_of_le hx hnle, have : x ^ (-c) ≤ x ^ (-a), { apply fpow_le_of_le hx, simpa only [min_eq_left hle, neg_le_neg_iff] using h }, simpa only [max_eq_left hfle] end lemma fpow_le_one_of_nonpos {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 := calc p ^ z ≤ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp lemma one_le_fpow_of_nonneg {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : 0 ≤ z) : 1 ≤ p ^ z := calc p ^ z ≥ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp theorem fpow_bit0_nonneg (a : K) (n : ℤ) : 0 ≤ a ^ bit0 n := by { rw fpow_bit0, exact mul_self_nonneg _ } theorem fpow_two_nonneg (a : K) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 theorem fpow_bit0_pos {a : K} (h : a ≠ 0) (n : ℤ) : 0 < a ^ bit0 n := (fpow_bit0_nonneg a n).lt_of_ne (fpow_ne_zero _ h).symm theorem fpow_two_pos_of_ne_zero (a : K) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 @[simp] theorem fpow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ fpow_nonneg h' _, λ h, by rw [bit1, fpow_add_one h.ne]; exact mul_neg_of_pos_of_neg (fpow_bit0_pos h.ne _) h⟩ @[simp] theorem fpow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 fpow_bit1_neg_iff @[simp] theorem fpow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := begin rw [le_iff_lt_or_eq, fpow_bit1_neg_iff], split, { rintro (h | h), { exact h.le }, { exact (fpow_eq_zero h).le } }, { intro h, rcases eq_or_lt_of_le h with rfl|h, { exact or.inr (zero_fpow _ (bit1_ne_zero n)) }, { exact or.inl h } } end @[simp] theorem fpow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le fpow_bit1_nonpos_iff lemma fpow_even_nonneg (a : K) {n : ℤ} (hn : even n) : 0 ≤ a ^ n := begin cases le_or_lt 0 a with h h, { exact fpow_nonneg h _ }, { rw [←fpow_even_neg _ hn], replace h : 0 ≤ -a := neg_nonneg_of_nonpos (le_of_lt h), exact fpow_nonneg h _ } end theorem fpow_even_pos (ha : a ≠ 0) (hn : even n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit0_pos ha k theorem fpow_odd_nonneg (ha : 0 ≤ a) (hn : odd n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_nonneg_iff.mpr ha theorem fpow_odd_pos (ha : 0 < a) (hn : odd n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_pos_iff.mpr ha theorem fpow_odd_nonpos (ha : a ≤ 0) (hn : odd n) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_nonpos_iff.mpr ha theorem fpow_odd_neg (ha : a < 0) (hn : odd n) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_neg_iff.mpr ha lemma fpow_even_abs (a : K) {p : ℤ} (hp : even p) : abs a ^ p = a ^ p := begin cases le_or_lt a (-a) with h h; simp [abs_eq_max_neg, h, max_eq_left_of_lt, fpow_even_neg _ hp] end @[simp] lemma fpow_bit0_abs (a : K) (p : ℤ) : (abs a) ^ bit0 p = a ^ bit0 p := fpow_even_abs _ (even_bit0 _) lemma abs_fpow_even (a : K) {p : ℤ} (hp : even p) : abs (a ^ p) = a ^ p := begin rw [←fpow_even_abs _ hp, abs_eq_self], exact fpow_even_nonneg _ hp end @[simp] lemma abs_fpow_bit0 (a : K) (p : ℤ) : abs (a ^ bit0 p) = a ^ bit0 p := abs_fpow_even _ (even_bit0 _) end ordered_field_power lemma one_lt_pow {K} [linear_ordered_semiring K] {p : K} (hp : 1 < p) : ∀ {n : ℕ}, 1 ≤ n → 1 < p ^ n | 1 h := by simp; assumption | (k+2) h := begin rw [←one_mul (1 : K), pow_succ], apply mul_lt_mul, { assumption }, { apply le_of_lt, simpa using one_lt_pow (nat.le_add_left 1 k)}, { apply zero_lt_one }, { apply le_of_lt (lt_trans zero_lt_one hp) } end section local attribute [semireducible] int.nonneg lemma one_lt_fpow {K} [linear_ordered_field K] {p : K} (hp : 1 < p) : ∀ z : ℤ, 0 < z → 1 < p ^ z | (n : ℕ) h := by { rw [gpow_coe_nat], exact one_lt_pow hp (nat.succ_le_of_lt (int.lt_of_coe_nat_lt_coe_nat h)) } end section ordered variables {K : Type*} [linear_ordered_field K] lemma nat.fpow_pos_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : 0 < (p:K)^n := by { apply fpow_pos_of_pos, exact_mod_cast h } lemma nat.fpow_ne_zero_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : (p:K)^n ≠ 0 := ne_of_gt (nat.fpow_pos_of_pos h n) lemma fpow_strict_mono {x : K} (hx : 1 < x) : strict_mono (λ n:ℤ, x ^ n) := λ m n h, show x ^ m < x ^ n, begin have xpos : 0 < x := zero_lt_one.trans hx, have h₀ : x ≠ 0 := xpos.ne', have hxm : 0 < x^m := fpow_pos_of_pos xpos m, have hxm₀ : x^m ≠ 0 := ne_of_gt hxm, suffices : 1 < x^(n-m), { replace := mul_lt_mul_of_pos_right this hxm, simp [sub_eq_add_neg] at this, simpa [*, fpow_add, mul_assoc, fpow_neg, inv_mul_cancel], }, apply one_lt_fpow hx, linarith, end @[simp] lemma fpow_lt_iff_lt {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m < x ^ n ↔ m < n := (fpow_strict_mono hx).lt_iff_lt @[simp] lemma fpow_le_iff_le {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m ≤ x ^ n ↔ m ≤ n := (fpow_strict_mono hx).le_iff_le @[simp] lemma pos_div_pow_pos {a b : K} (ha : 0 < a) (hb : 0 < b) (k : ℕ) : 0 < a/b^k := div_pos ha (pow_pos hb k) @[simp] lemma div_pow_le {a b : K} (ha : 0 < a) (hb : 1 ≤ b) (k : ℕ) : a/b^k ≤ a := (div_le_iff $ pow_pos (lt_of_lt_of_le zero_lt_one hb) k).mpr (calc a = a * 1 : (mul_one a).symm ... ≤ a*b^k : (mul_le_mul_left ha).mpr $ one_le_pow_of_one_le hb _) lemma fpow_injective {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) : function.injective ((^) x : ℤ → K) := begin intros m n h, rcases lt_trichotomy x 1 with H|rfl|H, { apply (fpow_strict_mono (one_lt_inv h₀ H)).injective, show x⁻¹ ^ m = x⁻¹ ^ n, rw [← fpow_neg_one, ← fpow_mul, ← fpow_mul, mul_comm _ m, mul_comm _ n, fpow_mul, fpow_mul, h], }, { contradiction }, { exact (fpow_strict_mono H).injective h, }, end @[simp] lemma fpow_inj {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) {m n : ℤ} : x ^ m = x ^ n ↔ m = n := (fpow_injective h₀ h₁).eq_iff end ordered section variables {K : Type*} [field K] @[simp, norm_cast] theorem rat.cast_fpow [char_zero K] (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : K) = q ^ n := (rat.cast_hom K).map_fpow q n end
a3cc3c14bc4100423ab5471b443f8a2c42558303
649957717d58c43b5d8d200da34bf374293fe739
/src/topology/Top/adjunctions.lean
3ff6336f4990ee47340e761c4f7105a855b68fc6
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
844
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Patrick Massot, Mario Carneiro import topology.Top.basic import category_theory.adjunction.basic universe u open category_theory open Top namespace Top def adj₁ : discrete ⊣ forget := { hom_equiv := λ X Y, { to_fun := λ f, f, inv_fun := λ f, ⟨f, continuous_bot⟩, left_inv := by tidy, right_inv := by tidy }, unit := { app := λ X, id }, counit := { app := λ X, ⟨id, continuous_bot⟩ } } def adj₂ : forget ⊣ trivial := { hom_equiv := λ X Y, { to_fun := λ f, ⟨f, continuous_top⟩, inv_fun := λ f, f, left_inv := by tidy, right_inv := by tidy }, unit := { app := λ X, ⟨id, continuous_top⟩ }, counit := { app := λ X, id } } end Top
153443104c94f6a5628ea4c920fa97fee68c400d
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tst10.lean
c0221bb8b4a6b0b03b767e65be962461dee5dde1
[ "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
361
lean
variable a : Bool variable b : Bool -- Conjunctions print a && b print a && b && a print a /\ b print a ∧ b print (and a b) print and a b -- Disjunctions print a || b print a \/ b print a ∨ b print (or a b) print or a (or a b) -- Simple Formulas print a → b → a check a → b eval a → a eval true → a -- Simple proof axiom H1 : a axiom H2 : a → b
a1adadee024c1a410dd20f197b62a1589a943de2
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/group_ring_action.lean
c8b778a4d0c2935d2708c4bbca8dae1096d54f74
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,460
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 group_theory.group_action.group import data.equiv.ring import deprecated.subring /-! # Group action on rings This file defines the typeclass of monoid acting on semirings `mul_semiring_action M R`, and the corresponding typeclass of invariant subrings. Note that `algebra` does not satisfy the axioms of `mul_semiring_action`. ## Implementation notes There is no separate typeclass for group acting on rings, group acting on fields, etc. They are all grouped under `mul_semiring_action`. ## Tags group action, invariant subring -/ universes u v open_locale big_operators /-- Typeclass for multiplicative actions by monoids on semirings. -/ class mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R] extends distrib_mul_action M R := (smul_one : ∀ (g : M), (g • 1 : R) = 1) (smul_mul : ∀ (g : M) (x y : R), g • (x * y) = (g • x) * (g • y)) export mul_semiring_action (smul_one) /-- Typeclass for faithful multiplicative actions by monoids on semirings. -/ class faithful_mul_semiring_action (M : Type u) [monoid M] (R : Type v) [semiring R] extends mul_semiring_action M R := (eq_of_smul_eq_smul' : ∀ {m₁ m₂ : M}, (∀ r : R, m₁ • r = m₂ • r) → m₁ = m₂) section semiring variables (M G : Type u) [monoid M] [group G] variables (A R S F : Type v) [add_monoid A] [semiring R] [comm_semiring S] [field F] variables {M R} lemma smul_mul' [mul_semiring_action M R] (g : M) (x y : R) : g • (x * y) = (g • x) * (g • y) := mul_semiring_action.smul_mul g x y variables {M} (R) theorem eq_of_smul_eq_smul [faithful_mul_semiring_action M R] {m₁ m₂ : M} : (∀ r : R, m₁ • r = m₂ • r) → m₁ = m₂ := faithful_mul_semiring_action.eq_of_smul_eq_smul' variables (M R) /-- Each element of the monoid defines a additive monoid homomorphism. -/ def distrib_mul_action.to_add_monoid_hom [distrib_mul_action M A] (x : M) : A →+ A := { to_fun := (•) x, map_zero' := smul_zero x, map_add' := smul_add x } /-- Each element of the group defines an additive monoid isomorphism. -/ def distrib_mul_action.to_add_equiv [distrib_mul_action G A] (x : G) : A ≃+ A := { .. distrib_mul_action.to_add_monoid_hom G A x, .. mul_action.to_perm G A x } /-- Each element of the group defines an additive monoid homomorphism. -/ def distrib_mul_action.hom_add_monoid_hom [distrib_mul_action M A] : M →* add_monoid.End A := { to_fun := distrib_mul_action.to_add_monoid_hom M A, map_one' := add_monoid_hom.ext $ λ x, one_smul M x, map_mul' := λ x y, add_monoid_hom.ext $ λ z, mul_smul x y z } /-- Each element of the monoid defines a semiring homomorphism. -/ def mul_semiring_action.to_semiring_hom [mul_semiring_action M R] (x : M) : R →+* R := { map_one' := smul_one x, map_mul' := smul_mul' x, .. distrib_mul_action.to_add_monoid_hom M R x } theorem to_semiring_hom_injective [faithful_mul_semiring_action M R] : function.injective (mul_semiring_action.to_semiring_hom M R) := λ m₁ m₂ h, eq_of_smul_eq_smul R $ λ r, ring_hom.ext_iff.1 h r /-- Each element of the group defines a semiring isomorphism. -/ def mul_semiring_action.to_semiring_equiv [mul_semiring_action G R] (x : G) : R ≃+* R := { .. distrib_mul_action.to_add_equiv G R x, .. mul_semiring_action.to_semiring_hom G R x } section prod variables [mul_semiring_action M R] [mul_semiring_action M S] lemma list.smul_prod (g : M) (L : list R) : g • L.prod = (L.map $ (•) g).prod := monoid_hom.map_list_prod (mul_semiring_action.to_semiring_hom M R g : R →* R) L lemma multiset.smul_prod (g : M) (m : multiset S) : g • m.prod = (m.map $ (•) g).prod := monoid_hom.map_multiset_prod (mul_semiring_action.to_semiring_hom M S g : S →* S) m lemma smul_prod (g : M) {ι : Type*} (f : ι → S) (s : finset ι) : g • ∏ i in s, f i = ∏ i in s, g • f i := monoid_hom.map_prod (mul_semiring_action.to_semiring_hom M S g : S →* S) f s end prod section simp_lemmas variables {M G A R} attribute [simp] smul_one smul_mul' smul_zero smul_add @[simp] lemma smul_inv [mul_semiring_action M F] (x : M) (m : F) : x • m⁻¹ = (x • m)⁻¹ := (mul_semiring_action.to_semiring_hom M F x).map_inv _ @[simp] lemma smul_pow [mul_semiring_action M R] (x : M) (m : R) (n : ℕ) : x • m ^ n = (x • m) ^ n := nat.rec_on n (smul_one x) $ λ n ih, (smul_mul' x m (m ^ n)).trans $ congr_arg _ ih end simp_lemmas end semiring section ring variables (M : Type u) [monoid M] {R : Type v} [ring R] [mul_semiring_action M R] variables (S : set R) [is_subring S] open mul_action set_option old_structure_cmd false /-- A subring invariant under the action. -/ class is_invariant_subring : Prop := (smul_mem : ∀ (m : M) {x : R}, x ∈ S → m • x ∈ S) variables [is_invariant_subring M S] local attribute [instance] subset.ring instance is_invariant_subring.to_mul_semiring_action : mul_semiring_action M S := { smul := λ m x, ⟨m • x, is_invariant_subring.smul_mem m x.2⟩, one_smul := λ s, subtype.eq $ one_smul M s, mul_smul := λ m₁ m₂ s, subtype.eq $ mul_smul m₁ m₂ s, smul_add := λ m s₁ s₂, subtype.eq $ smul_add m s₁ s₂, smul_zero := λ m, subtype.eq $ smul_zero m, smul_one := λ m, subtype.eq $ smul_one m, smul_mul := λ m s₁ s₂, subtype.eq $ smul_mul' m s₁ s₂ } end ring
5250f4562c0f0a02d158b4956520324dcde493e1
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/inj1.lean
71505264f1a4393b283ccc85596fc2b8ac6075fc
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
930
lean
new_frontend theorem test1 {α} (a b : α) (as bs : List α) (h : a::as = b::bs) : a = b := by { injection h; assumption; } theorem test2 {α} (a b : α) (as bs : List α) (h : a::as = b::bs) : a = b := by { injection h with h1 h2; exact h1 } theorem test3 {α} (a b : α) (as bs : List α) (h : (x : List α) → (y : List α) → x = y) : as = bs := have a::as = b::bs from h (a::as) (b::bs); by { injection this with h1 h2; exact h2 } theorem test4 {α} (a b : α) (as bs : List α) (h : (x : List α) → (y : List α) → x = y) : as = bs := by { injection h (a::as) (b::bs) with h1 h2; exact h2 } theorem test5 {α} (a : α) (as : List α) (h : a::as = []) : 0 > 1 := by { injection h } theorem test6 (n : Nat) (h : n+1 = 0) : 0 > 1 := by { injection h } theorem test7 (n m k : Nat) (h : n + 1 = m + 1) : m = k → n = k := by { injection h with h₁; subst h₁; intro h₂; exact h₂ }
707d5ef4d8e34cdcef8cc7187eada076e8a7e64a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/analysis/calculus/extend_deriv_auto.lean
a3d70c45f334080e8c8790d96b71699aefa0c233
[]
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,531
lean
/- Copyright (c) 2019 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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.analysis.calculus.mean_value import Mathlib.tactic.monotonicity.default import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Extending differentiability to the boundary We investigate how differentiable functions inside a set extend to differentiable functions on the boundary. For this, it suffices that the function and its derivative admit limits there. A general version of this statement is given in `has_fderiv_at_boundary_of_tendsto_fderiv`. One-dimensional versions, in which one wants to obtain differentiability at the left endpoint or the right endpoint of an interval, are given in `has_deriv_at_interval_left_endpoint_of_tendsto_deriv` and `has_deriv_at_interval_right_endpoint_of_tendsto_deriv`. These versions are formulated in terms of the one-dimensional derivative `deriv ℝ f`. -/ /-- If a function `f` is differentiable in a convex open set and continuous on its closure, and its derivative converges to a limit `f'` at a point on the boundary, then `f` is differentiable there with derivative `f'`. -/ theorem has_fderiv_at_boundary_of_tendsto_fderiv {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_2} [normed_group F] [normed_space ℝ F] {f : E → F} {s : set E} {x : E} {f' : continuous_linear_map ℝ E F} (f_diff : differentiable_on ℝ f s) (s_conv : convex s) (s_open : is_open s) (f_cont : ∀ (y : E), y ∈ closure s → continuous_within_at f s y) (h : filter.tendsto (fun (y : E) => fderiv ℝ f y) (nhds_within x s) (nhds f')) : has_fderiv_within_at f f' (closure s) x := sorry /-- If a function is differentiable on the right of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the right at `a`. -/ theorem has_deriv_at_interval_left_endpoint_of_tendsto_deriv {E : Type u_1} [normed_group E] [normed_space ℝ E] {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ nhds_within a (set.Ioi a)) (f_lim' : filter.tendsto (fun (x : ℝ) => deriv f x) (nhds_within a (set.Ioi a)) (nhds e)) : has_deriv_within_at f e (set.Ici a) a := sorry /-- If a function is differentiable on the left of a point `a : ℝ`, continuous at `a`, and its derivative also converges at `a`, then `f` is differentiable on the left at `a`. -/ theorem has_deriv_at_interval_right_endpoint_of_tendsto_deriv {E : Type u_1} [normed_group E] [normed_space ℝ E] {s : set ℝ} {e : E} {a : ℝ} {f : ℝ → E} (f_diff : differentiable_on ℝ f s) (f_lim : continuous_within_at f s a) (hs : s ∈ nhds_within a (set.Iio a)) (f_lim' : filter.tendsto (fun (x : ℝ) => deriv f x) (nhds_within a (set.Iio a)) (nhds e)) : has_deriv_within_at f e (set.Iic a) a := sorry /-- If a real function `f` has a derivative `g` everywhere but at a point, and `f` and `g` are continuous at this point, then `g` is also the derivative of `f` at this point. -/ theorem has_deriv_at_of_has_deriv_at_of_ne {E : Type u_1} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {g : ℝ → E} {x : ℝ} (f_diff : ∀ (y : ℝ), y ≠ x → has_deriv_at f (g y) y) (hf : continuous_at f x) (hg : continuous_at g x) : has_deriv_at f (g x) x := sorry end Mathlib
ef4ab6ec0558970791fb60657da8f8a79c3faa84
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/add_interactive.lean
7d211ef6740d575e028cb3cc6b4f5a4be716ce90
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
293
lean
namespace foo namespace bla open lean.parser interactive interactive.types meta def my_exact (q : parse texpr) := tactic.interactive.exact q /- Copy tactic my_exact to tactic.interactive. -/ run_cmd add_interactive [`my_exact] end bla example : true := begin my_exact trivial end end foo
9f2fcc15b71d4d6e1976d28d7c0f0fc20551c168
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/limits/shapes/kernel_pair.lean
8ede928ca3455ac88647f853695dfff0087f8a1f
[ "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
6,164
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.regular_mono /-! # Kernel pairs This file defines what it means for a parallel pair of morphisms `a b : R ⟶ X` to be the kernel pair for a morphism `f`. Some properties of kernel pairs are given, namely allowing one to transfer between the kernel pair of `f₁ ≫ f₂` to the kernel pair of `f₁`. It is also proved that if `f` is a coequalizer of some pair, and `a`,`b` is a kernel pair for `f` then it is a coequalizer of `a`,`b`. ## Implementation The definition is essentially just a wrapper for `is_limit (pullback_cone.mk _ _ _)`, but the constructions given here are useful, yet awkward to present in that language, so a basic API is developed here. ## TODO - Internal equivalence relations (or congruences) and the fact that every kernel pair induces one, and the converse in an effective regular category (WIP by b-mehta). -/ universes v u u₂ namespace category_theory open category_theory category_theory.category category_theory.limits variables {C : Type u} [category.{v} C] variables {R X Y Z : C} (f : X ⟶ Y) (a b : R ⟶ X) /-- `is_kernel_pair f a b` expresses that `(a, b)` is a kernel pair for `f`, i.e. `a ≫ f = b ≫ f` and the square R → X ↓ ↓ X → Y is a pullback square. This is essentially just a convenience wrapper over `is_limit (pullback_cone.mk _ _ _)`. -/ structure is_kernel_pair := (comm : a ≫ f = b ≫ f) (is_limit : is_limit (pullback_cone.mk _ _ comm)) attribute [reassoc] is_kernel_pair.comm namespace is_kernel_pair /-- The data expressing that `(a, b)` is a kernel pair is subsingleton. -/ instance : subsingleton (is_kernel_pair f a b) := ⟨λ P Q, by { cases P, cases Q, congr, }⟩ /-- If `f` is a monomorphism, then `(𝟙 _, 𝟙 _)` is a kernel pair for `f`. -/ def id_of_mono [mono f] : is_kernel_pair f (𝟙 _) (𝟙 _) := ⟨rfl, pullback_cone.is_limit_mk_id_id _⟩ instance [mono f] : inhabited (is_kernel_pair f (𝟙 _) (𝟙 _)) := ⟨id_of_mono f⟩ variables {f a b} /-- Given a pair of morphisms `p`, `q` to `X` which factor through `f`, they factor through any kernel pair of `f`. -/ def lift' {S : C} (k : is_kernel_pair f a b) (p q : S ⟶ X) (w : p ≫ f = q ≫ f) : { t : S ⟶ R // t ≫ a = p ∧ t ≫ b = q } := pullback_cone.is_limit.lift' k.is_limit _ _ w /-- If `(a,b)` is a kernel pair for `f₁ ≫ f₂` and `a ≫ f₁ = b ≫ f₁`, then `(a,b)` is a kernel pair for just `f₁`. That is, to show that `(a,b)` is a kernel pair for `f₁` it suffices to only show the square commutes, rather than to additionally show it's a pullback. -/ def cancel_right {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} (comm : a ≫ f₁ = b ≫ f₁) (big_k : is_kernel_pair (f₁ ≫ f₂) a b) : is_kernel_pair f₁ a b := { comm := comm, is_limit := pullback_cone.is_limit_aux' _ $ λ s, begin let s' : pullback_cone (f₁ ≫ f₂) (f₁ ≫ f₂) := pullback_cone.mk s.fst s.snd (s.condition_assoc _), refine ⟨big_k.is_limit.lift s', big_k.is_limit.fac _ walking_cospan.left, big_k.is_limit.fac _ walking_cospan.right, λ m m₁ m₂, _⟩, apply big_k.is_limit.hom_ext, refine ((pullback_cone.mk a b _) : pullback_cone (f₁ ≫ f₂) _).equalizer_ext _ _, apply m₁.trans (big_k.is_limit.fac s' walking_cospan.left).symm, apply m₂.trans (big_k.is_limit.fac s' walking_cospan.right).symm, end } /-- If `(a,b)` is a kernel pair for `f₁ ≫ f₂` and `f₂` is mono, then `(a,b)` is a kernel pair for just `f₁`. The converse of `comp_of_mono`. -/ def cancel_right_of_mono {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} [mono f₂] (big_k : is_kernel_pair (f₁ ≫ f₂) a b) : is_kernel_pair f₁ a b := cancel_right (begin rw [← cancel_mono f₂, assoc, assoc, big_k.comm] end) big_k /-- If `(a,b)` is a kernel pair for `f₁` and `f₂` is mono, then `(a,b)` is a kernel pair for `f₁ ≫ f₂`. The converse of `cancel_right_of_mono`. -/ def comp_of_mono {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} [mono f₂] (small_k : is_kernel_pair f₁ a b) : is_kernel_pair (f₁ ≫ f₂) a b := { comm := by rw [small_k.comm_assoc], is_limit := pullback_cone.is_limit_aux' _ $ λ s, begin refine ⟨_, _, _, _⟩, apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).1, rw [← cancel_mono f₂, assoc, s.condition, assoc], apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.1, apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.2, intros m m₁ m₂, apply small_k.is_limit.hom_ext, refine ((pullback_cone.mk a b _) : pullback_cone f₁ _).equalizer_ext _ _, rwa (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.1, rwa (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.2, end } /-- If `(a,b)` is the kernel pair of `f`, and `f` is a coequalizer morphism for some parallel pair, then `f` is a coequalizer morphism of `a` and `b`. -/ def to_coequalizer (k : is_kernel_pair f a b) [r : regular_epi f] : is_colimit (cofork.of_π f k.comm) := begin let t := k.is_limit.lift (pullback_cone.mk _ _ r.w), have ht : t ≫ a = r.left := k.is_limit.fac _ walking_cospan.left, have kt : t ≫ b = r.right := k.is_limit.fac _ walking_cospan.right, apply cofork.is_colimit.mk _ _ _ _, { intro s, apply (cofork.is_colimit.desc' r.is_colimit s.π _).1, rw [← ht, assoc, s.condition, reassoc_of kt] }, { intro s, apply (cofork.is_colimit.desc' r.is_colimit s.π _).2 }, { intros s m w, apply r.is_colimit.hom_ext, rintro ⟨⟩, change (r.left ≫ f) ≫ m = (r.left ≫ f) ≫ _, rw [assoc, assoc], congr' 1, erw (cofork.is_colimit.desc' r.is_colimit s.π _).2, apply w walking_parallel_pair.one, erw (cofork.is_colimit.desc' r.is_colimit s.π _).2, apply w walking_parallel_pair.one } end end is_kernel_pair end category_theory
ff79c94e54f2f66d10b5932af95638c3bd57b9c6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/tactic/ring_exp.lean
c4c6e06c0807985c8a22c8b8e7264c29a3003fc6
[ "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
57,247
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baanen -/ import tactic.norm_num import control.traversable.basic /-! # `ring_exp` tactic A tactic for solving equations in commutative (semi)rings, where the exponents can also contain variables. More precisely, expressions of the following form are supported: - constants (non-negative integers) - variables - coefficients (any rational number, embedded into the (semi)ring) - addition of expressions - multiplication of expressions - exponentiation of expressions (the exponent must have type `ℕ`) - subtraction and negation of expressions (if the base is a full ring) The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`, something that the `ring` tactic cannot do, but `ring_exp` can. ## Implementation notes The basic approach to prove equalities is to normalise both sides and check for equality. The normalisation is guided by building a value in the type `ex` at the meta level, together with a proof (at the base level) that the original value is equal to the normalised version. The normalised version and normalisation proofs are also stored in the `ex` type. The outline of the file: - Define an inductive family of types `ex`, parametrised over `ex_type`, which can represent expressions with `+`, `*`, `^` and rational numerals. The parametrisation over `ex_type` ensures that associativity and distributivity are applied, by restricting which kinds of subexpressions appear as arguments to the various operators. - Represent addition, multiplication and exponentiation in the `ex` type, thus allowing us to map expressions to `ex` (the `eval` function drives this). We apply associativity and distributivity of the operators here (helped by `ex_type`) and commutativity as well (by sorting the subterms; unfortunately not helped by anything). Any expression not of the above formats is treated as an atom (the same as a variable). There are some details we glossed over which make the plan more complicated: - The order on atoms is not initially obvious. We construct a list containing them in order of initial appearance in the expression, then use the index into the list as a key to order on. - In the tactic, a normalized expression `ps : ex` lives in the meta-world, but the normalization proofs live in the real world. Thus, we cannot directly say `ps.orig = ps.pretty` anywhere, but we have to carefully construct the proof when we compute `ps`. This was a major source of bugs in development! - For `pow`, the exponent must be a natural number, while the base can be any semiring `α`. We swap out operations for the base ring `α` with those for the exponent ring `ℕ` as soon as we deal with exponents. This is accomplished by the `in_exponent` function and is relatively painless since we work in a `reader` monad. - The normalized form of an expression is the one that is useful for the tactic, but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`. ## Caveats and future work Subtraction cancels out identical terms, but division does not. That is: `a - a = 0 := by ring_exp` solves the goal, but `a / a := 1 by ring_exp` doesn't. Note that `0 / 0` is generally defined to be `0`, so division cancelling out is not true in general. Multiplication of powers can be simplified a little bit further: `2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works. This feature wasn't needed yet, so it's not implemented yet. ## Tags ring, semiring, exponent, power -/ -- The base ring `α` will have a universe level `u`. -- We do not introduce `α` as a variable yet, -- in order to make it explicit or implicit as required. universes u namespace tactic.ring_exp open nat /-- The `atom` structure is used to represent atomic expressions: those which `ring_exp` cannot parse any further. For instance, `a + (a % b)` has `a` and `(a % b)` as atoms. The `ring_exp_eq` tactic does not normalize the subexpressions in atoms, but `ring_exp` does if `ring_exp_eq` was not sufficient. Atoms in fact represent equivalence classes of expressions, modulo definitional equality. The field `index : ℕ` should be a unique number for each class, while `value : expr` contains a representative of this class. The function `resolve_atom` determines the appropriate atom for a given expression. -/ meta structure atom : Type := (value : expr) (index : ℕ) namespace atom /-- The `eq` operation on `atom`s works modulo definitional equality, ignoring their `value`s. The invariants on `atom` ensure indices are unique per value. Thus, `eq` indicates equality as long as the `atom`s come from the same context. -/ meta def eq (a b : atom) : bool := a.index = b.index /-- We order `atom`s on the order of appearance in the main expression. -/ meta def lt (a b : atom) : bool := a.index < b.index meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩ end atom section expression /-! ### `expression` section In this section, we define the `ex` type and its basic operations. First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`. For understanding the code, it's easier to check out `ex` itself first, then refer back to the supporting types. The arithmetic operations on `ex` need additional definitions, so they are defined in a later section. -/ /-- Coefficients in the expression are stored in a wrapper structure, allowing for easier modification of the data structures. The modifications might be caching of the result of `expr.of_rat`, or using a different meta representation of numerals. -/ @[derive decidable_eq, derive inhabited] structure coeff : Type := (value : ℚ) /-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/ @[derive decidable_eq, derive inhabited] inductive ex_type : Type | base : ex_type | sum : ex_type | prod : ex_type | exp : ex_type open ex_type /-- Each `ex` stores information for its normalization proof. The `orig` expression is the expression that was passed to `eval`. The `pretty` expression is the normalised form that the `ex` represents. (I didn't call this something like `norm`, because there are already too many things called `norm` in mathematics!) The field `proof` contains an optional proof term of type `%%orig = %%pretty`. The value `none` for the proof indicates that everything reduces to reflexivity. (Which saves space in quite a lot of cases.) -/ meta structure ex_info : Type := (orig : expr) (pretty : expr) (proof : option expr) /-- The `ex` type is an abstract representation of an expression with `+`, `*` and `^`. Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively. The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented by (something along the lines of) `sum 1 (sum 2 zero)`. The `coeff` constructor is the base case for `ex prod`, and is used for numerals. The code maintains the invariant that the coefficient is never `0`. The `var` constructor is the base case for `ex exp`, and is used for atoms. The `sum_b` constructor allows for addition in the base of an exponentiation; it serves a similar purpose as the parentheses in `(a + b)^c`. The code maintains the invariant that the argument to `sum_b` is not `zero` or `sum _ zero`. All of the constructors contain an `ex_info` field, used to carry around (arguments to) proof terms. While the `ex_type` parameter enforces some simplification invariants, the following ones must be manually maintained at the risk of insufficient power: - the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`) - the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`) - normalisation proofs of subexpressions must be `refl ps.pretty` - if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted according to the `lt` relation defined further down; similarly for `prod` and `coeff` (to ensure `a + b = b + a`). The first two invariants could be encoded in a subtype of `ex`, but aren't (yet) to spare some implementation burden. The other invariants cannot be encoded because we need the `tactic` monad to check them. (For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.) -/ meta inductive ex : ex_type → Type | zero (info : ex_info) : ex sum | sum (info : ex_info) : ex prod → ex sum → ex sum | coeff (info : ex_info) : coeff → ex prod | prod (info : ex_info) : ex exp → ex prod → ex prod | var (info : ex_info) : atom → ex base | sum_b (info : ex_info) : ex sum → ex base | exp (info : ex_info) : ex base → ex prod → ex exp /-- Return the proof information associated to the `ex`. -/ meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info | sum (ex.zero i) := i | sum (ex.sum i _ _) := i | prod (ex.coeff i _) := i | prod (ex.prod i _ _) := i | base (ex.var i _) := i | base (ex.sum_b i _) := i | exp (ex.exp i _ _) := i /-- Return the original, non-normalized version of this `ex`. Note that arguments to another `ex` are always "pre-normalized": their `orig` and `pretty` are equal, and their `proof` is reflexivity. -/ meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig /-- Return the normalized version of this `ex`. -/ meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty /-- Return the normalisation proof of the given expression. If the proof is `refl`, we give `none` instead, which helps to control the size of proof terms. To get an actual term, use `ex.proof_term`, or use `mk_proof` with the correct set of arguments. -/ meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof /-- Update the `orig` and `proof` fields of the `ex_info`. Intended for use in `ex.set_info`. -/ meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info := {orig := o.get_or_else i.pretty, proof := pf, .. i} /-- Update the `ex_info` of the given expression. We use this to combine intermediate normalisation proofs. Since `pretty` only depends on the subexpressions, which do not change, we do not set `pretty`. -/ meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et | sum (ex.zero i) o pf := ex.zero (i.set o pf) | sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps | prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x | prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps | base (ex.var i x) o pf := ex.var (i.set o pf) x | base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps | exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩ /-- Convert an `ex` to a `string`. -/ meta def ex.repr : Π {et : ex_type}, ex et → string | sum (ex.zero _) := "0" | sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps | prod (ex.coeff _ x) := repr x | prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps | base (ex.var _ x) := repr x | base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")" | exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩ /-- Equality test for expressions. Since equivalence of `atom`s is not the same as equality, we cannot make a true `(=)` operator for `ex` either. -/ meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool | sum (ex.zero _) (ex.zero _) := tt | sum (ex.zero _) (ex.sum _ _ _) := ff | sum (ex.sum _ _ _) (ex.zero _) := ff | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs | prod (ex.coeff _ x) (ex.coeff _ y) := x = y | prod (ex.coeff _ _) (ex.prod _ _ _) := ff | prod (ex.prod _ _ _) (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs | base (ex.var _ x) (ex.var _ y) := x.eq y | base (ex.var _ _) (ex.sum_b _ _) := ff | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs /-- The ordering on expressions. As for `ex.eq`, this is a linear order only in one context. -/ meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool | sum _ (ex.zero _) := ff | sum (ex.zero _) _ := tt | sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs) | prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1 | prod (ex.coeff _ _) _ := tt | prod _ (ex.coeff _ _) := ff | prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs) | base (ex.var _ x) (ex.var _ y) := x.lt y | base (ex.var _ _) (ex.sum_b _ _) := tt | base (ex.sum_b _ _) (ex.var _ _) := ff | base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs | exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs) end expression section operations /-! ### `operations` section This section defines the operations (on `ex`) that use tactics. They live in the `ring_exp_m` monad, which adds a cache and a list of encountered atoms to the `tactic` monad. Throughout this section, we will be constructing proof terms. The lemmas used in the construction are all defined over a commutative semiring α. -/ variables {α : Type u} [comm_semiring α] open tactic open ex_type /-- Stores the information needed in the `eval` function and its dependencies, so they can (re)construct expressions. The `eval_info` structure stores this information for one type, and the `context` combines the two types, one for bases and one for exponents. -/ meta structure eval_info := (α : expr) (univ : level) -- Cache the instances for optimization and consistency (csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr) -- Optional instances (only required for (-) and (/) respectively) (ring_instance : option expr) (dr_instance : option expr) -- Cache common constants. (zero : expr) (one : expr) /-- The `context` contains the full set of information needed for the `eval` function. This structure has two copies of `eval_info`: one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`). When evaluating an exponent, we put `info_e` in `info_b`. -/ meta structure context := (info_b : eval_info) (info_e : eval_info) (transp : transparency) /-- The `ring_exp_m` monad is used instead of `tactic` to store the context. -/ @[derive [monad, alternative]] meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α /-- Access the instance cache. -/ meta def get_context : ring_exp_m context := reader_t.read /-- Lift an operation in the `tactic` monad to the `ring_exp_m` monad. This operation will not access the cache. -/ meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m) /-- Change the context of the given computation, so that expressions are evaluated in the exponent ring, instead of the base ring. -/ meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do ctx ← get_context, reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩ /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args /-- Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`. Should be faster because it can use the cached instances. -/ meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class f (ctx.info_b.csr_instance) args /-- Specialized version of `mk_app ``has_add.add`. Should be faster because it can use the cached instances. -/ meta def mk_add (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_add.add ctx.info_b.ha_instance args /-- Specialized version of `mk_app ``has_mul.mul`. Should be faster because it can use the cached instances. -/ meta def mk_mul (args : list expr) : ring_exp_m expr := do ctx ← get_context, mk_app_class ``has_mul.mul ctx.info_b.hm_instance args /-- Specialized version of `mk_app ``has_pow.pow`. Should be faster because it can use the cached instances. -/ meta def mk_pow (args : list expr) : ring_exp_m expr := do ctx ← get_context, pure $ (@expr.const tt ``has_pow.pow [ctx.info_b.univ, ctx.info_e.univ] ctx.info_b.α ctx.info_e.α ctx.info_b.hp_instance).mk_app args /-- Construct a normalization proof term or return the cached one. -/ meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr := match ps.proof with | none := lift $ tactic.mk_eq_refl ps.pretty | (some p) := pure p end /-- Construct a normalization proof term or return the cached one. -/ meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term /-- If all `ex_info` have trivial proofs, return a trivial proof. Otherwise, construct all proof terms. Useful in applications where trivial proofs combine to another trivial proof, most importantly to pass to `mk_proof_or_refl`. -/ meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr)) | [] := pure none | (x :: xs) := do xs_pfs ← none_or_proof_term xs, match (x.proof, xs_pfs) with | (none, none) := pure none | (some x_pf, none) := do xs_pfs ← traverse ex_info.proof_term xs, pure (some (x_pf :: xs_pfs)) | (_, some xs_pfs) := do x_pf ← x.proof_term, pure (some (x_pf :: xs_pfs)) end /-- Use the proof terms as arguments to the given lemma. If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.` -/ meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs' ← traverse ex_info.proof_term hs, mk_app_csr lem (args ++ hs') /-- Use the proof terms as arguments to the given lemma. Often, we construct a proof term using congruence where reflexivity suffices. To solve this, the following function tries to get away with reflexivity. -/ meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do hs_full ← none_or_proof_term hs, match hs_full with | none := lift $ mk_eq_refl term | (some hs') := mk_app_csr lem (args ++ hs') end /-- A shortcut for adding the original terms of two expressions. -/ meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_add [ps.orig, qs.orig] /-- A shortcut for multiplying the original terms of two expressions. -/ meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_mul [ps.orig, qs.orig] /-- A shortcut for exponentiating the original terms of two expressions. -/ meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr := mk_pow [ps.orig, qs.orig] /-- Congruence lemma for constructing `ex.sum`. -/ lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc /-- Congruence lemma for constructing `ex.prod`. -/ lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc /-- Congruence lemma for constructing `ex.exp`. -/ lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc /-- Constructs `ex.zero` with the correct arguments. -/ meta def ex_zero : ring_exp_m (ex sum) := do ctx ← get_context, pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩ /-- Constructs `ex.sum` with the correct arguments. -/ meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do pps_o ← add_orig p ps, pps_p ← mk_add [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``sum_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.coeff` with the correct arguments. There are more efficient constructors for specific numerals: if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`. -/ meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do ctx ← get_context, x_p ← lift $ expr.of_rat ctx.info_b.α x, pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩) /-- Constructs `ex.coeff 1` with the correct arguments. This is a special case for optimization purposes. -/ meta def ex_one : ring_exp_m (ex prod) := do ctx ← get_context, pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩ /-- Constructs `ex.prod` with the correct arguments. -/ meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do pps_o ← mul_orig p ps, pps_p ← mk_mul [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``prod_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) /-- Constructs `ex.var` with the correct arguments. -/ meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p) /-- Constructs `ex.sum_b` with the correct arguments. -/ meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) := pure (ex.sum_b ps.info (ps.set_info none none)) /-- Constructs `ex.exp` with the correct arguments. -/ meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do ctx ← get_context, pps_o ← pow_orig p ps, pps_p ← mk_pow [p.pretty, ps.pretty], pps_pf ← mk_proof_or_refl pps_p ``exp_congr [p.orig, p.pretty, ps.orig, ps.pretty] [p.info, ps.info], pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none)) lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp /-- Conversion from `ex base` to `ex exp`. -/ meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do o ← in_exponent $ ex_one, ps ← ex_exp p o, pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp /-- Conversion from `ex exp` to `ex prod`. -/ meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do o ← ex_one, ps ← ex_prod p o, pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp /-- Conversion from `ex prod` to `ex sum`. -/ meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do z ← ex_zero, ps ← ex_sum p z, pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info], pure $ ps.set_info p.orig pf lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp /-- A more efficient conversion from `atom` to `ex sum`. The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`, except we need to calculate less intermediate steps. -/ meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do p' ← ex_var p, o ← in_exponent $ ex_one, p' ← ex_exp p' o, o ← ex_one, p' ← ex_prod p' o, z ← ex_zero, p' ← ex_sum p' z, pf ← mk_proof ``atom_to_sum_pf [p.1] [], pure $ p'.set_info p.1 pf /-- Compute the sum of two coefficients. Note that the result might not be a valid expression: if `p = -q`, then the result should be `ex.zero : ex sum` instead. The caller must detect when this happens! The returned value is of the form `ex.coeff _ (p + q)`, with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`. -/ meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do ctx ← get_context, pq_o ← mk_add [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.eval_field pq_o, pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩ lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p /-- Compute the product of two coefficients. The returned value is of the form `ex.coeff _ (p * q)`, with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`. -/ meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := match p.1, q.1 with -- Special case to speed up multiplication with 1. | ⟨1, 1, _, _⟩, _ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p], pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩ | _, ⟨1, 1, _, _⟩ := do ctx ← get_context, pq_o ← mk_mul [p_p, q_p], pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p], pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩ | _, _ := do ctx ← get_context, pq' ← mk_mul [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.eval_field pq', pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩ end section rewrite /-! ### `rewrite` section In this section we deal with rewriting terms to fit in the basic grammar of `eval`. For example, `nat.succ n` is rewritten to `n + 1` before it is evaluated further. -/ /-- Given a proof that the expressions `ps_o` and `ps'.orig` are equal, show that `ps_o` and `ps'.pretty` are equal. Useful to deal with aliases in `eval`. For instance, `nat.succ p` can be handled as an alias of `p + 1` as follows: ``` | ps_o@`(nat.succ %%p_o) := do ps' ← eval `(%%p_o + 1), pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o], rewrite ps_o ps' pf ``` -/ meta def rewrite (ps_o : expr) (ps' : ex sum) (pf : expr) : ring_exp_m (ex sum) := do ps'_pf ← ps'.info.proof_term, pf ← lift $ mk_eq_trans pf ps'_pf, pure $ ps'.set_info ps_o pf end rewrite /-- Represents the way in which two products are equal except coefficient. This type is used in the function `add_overlap`. In order to deal with equations of the form `a * 2 + a = 3 * a`, the `add` function will add up overlapping products, turning `a * 2 + a` into `a * 3`. We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this, and the `overlap` type carries the information on how it overlaps. The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`; the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a` (the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`); the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`. We distinguish those two cases because in the second, the whole product reduces to `0`. A potential extension to the tactic would also do this for the base of exponents, e.g. to show `2^n * 2^n = 4^n`. -/ meta inductive overlap : Type | none : overlap | nonzero : ex prod → overlap | zero : ex sum → overlap lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * pq : by rw pq_pf lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _) ... = p * 0 : by rw pq_pf ... = 0 : mul_zero _ /-- Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients). For other arguments, return `overlap.none`. -/ meta def add_overlap : ex prod → ex prod → ring_exp_m overlap | (ex.coeff x_i x) (ex.coeff y_i y) := do xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y | lift $ fail "internal error: add_coeff should return ex.coeff", if xy_c.1 = 0 then do z ← ex_zero, pure $ overlap.zero (z.set_info xy.orig xy.proof) else pure $ overlap.nonzero xy | (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none | (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none | pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q then do pq_ol ← add_overlap ps qs, pqs_o ← add_orig pps qqs, match pq_ol with | overlap.none := pure overlap.none | (overlap.nonzero pq) := do pqs ← ex_prod p pq, pf ← mk_proof ``add_overlap_pf [ps.pretty, qs.pretty, pq.pretty, p.pretty] [pq.info], pure $ overlap.nonzero (pqs.set_info pqs_o pf) | (overlap.zero pq) := do z ← ex_zero, pf ← mk_proof ``add_overlap_pf_zero [ps.pretty, qs.pretty, p.pretty] [pq.info], pure $ overlap.zero (z.set_info pqs_o pf) end else pure overlap.none section addition lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc ps + qs = 0 + qs' : by rw [ps_pf, qs_pf] ... = qs' : zero_add _ lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc ps + qs = ps' + 0 : by rw [ps_pf, qs_pf] ... = ps' : add_zero _ lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} : pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} : pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs := λ pps_pf qqs_pf pq_pf pqs_pf, calc pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf] ... = (p + q) + (ps + qs) : by cc ... = 0 + pqs : by rw [pq_pf, pqs_pf] ... = pqs : zero_add _ lemma add_pf_sum_lt {pps p ps qqs pqs : α} : pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc lemma add_pf_sum_gt {pps qqs q qs pqs : α} : qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc /-- Add two expressions. * `0 + qs = 0` * `ps + 0 = 0` * `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`) * `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`) * `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`) -/ meta def add : ex sum → ex sum → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ qs.set_info pqs_o pf | ps qs@(ex.zero qs_i) := do pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pqs_o ← add_orig ps qs, pure $ ps.set_info pqs_o pf | pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do ol ← add_overlap p q, ppqqs_o ← add_orig pps qqs, match ol with | (overlap.nonzero pq) := do pqs ← add ps qs, pqqs ← ex_sum pq pqs, qqs_pf ← qqs.proof_term, pf ← mk_proof ``add_pf_sum_overlap [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf | (overlap.zero pq) := do pqs ← add ps qs, pf ← mk_proof ``add_pf_sum_overlap_zero [pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [pps.info, qqs.info, pq.info, pqs.info], pure $ pqs.set_info ppqqs_o pf | overlap.none := if p.lt q then do pqs ← add ps qqs, ppqs ← ex_sum p pqs, pf ← mk_proof ``add_pf_sum_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← add pps qs, pqqs ← ex_sum q pqs, pf ← mk_proof ``add_pf_sum_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end end addition section multiplication lemma mul_pf_c_c {ps ps' qs qs' pq : α} : ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc lemma mul_pf_c_prod {ps qqs q qs pqs : α} : qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc lemma mul_pf_prod_c {pps p ps qs pqs : α} : pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} : pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs → p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs := λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, pow_add, ps_pf, qs_pf]; ac_refl lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} : pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} : qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc /-- Multiply two expressions. * `x * y = (x * y)` (for `x`, `y` coefficients) * `x * (q * qs) = q * (qs * x)` (for `x` coefficient) * `(p * ps) * y = p * (ps * y)` (for `y` coefficient) * `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)` (if `p_e` and `q_e` are identical except coefficient) * `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`) * `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`) -/ meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do pq ← mul_coeff ps.pretty qs.pretty x y, pq_o ← mul_orig ps qs, pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c [ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty] [ps.info, qs.info, pq.info], pure $ pq.set_info pq_o pf | ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do pqs ← mul_pp ps qs, pqqs ← ex_prod q pqs, pqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_c_prod [ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info pqqs_o pf | pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do pqs ← mul_pp ps qs, ppqs ← ex_prod p pqs, ppqs_o ← mul_orig pps qs, pf ← mk_proof ``mul_pf_prod_c [pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqs_o pf | pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do ppqqs_o ← mul_orig pps qqs, pq_ol ← in_exponent $ add_overlap p_e q_e, match pq_ol, p_b.eq q_b with | (overlap.nonzero pq_e), tt := do psqs ← mul_pp ps qs, pq ← ex_exp p_b pq_e, ppsqqs ← ex_prod pq psqs, pf ← mk_proof ``mul_pp_pf_overlap [pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty] [pps.info, qqs.info, ppsqqs.info], pure $ ppsqqs.set_info ppqqs_o pf | _, _ := if p.lt q then do pqs ← mul_pp ps qqs, ppqs ← ex_prod p pqs, pf ← mk_proof ``mul_pp_pf_prod_lt [pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty] [pps.info, pqs.info], pure $ ppqs.set_info ppqqs_o pf else do pqs ← mul_pp pps qs, pqqs ← ex_prod q pqs, pf ← mk_proof ``mul_pp_pf_prod_gt [pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty] [qqs.info, pqs.info], pure $ pqqs.set_info ppqqs_o pf end lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 := λ ps_pf, by rw [ps_pf, zero_mul] lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps → p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc pps * qs = (p + ps) * qs : by rw [pps_pf] ... = p * qs + ps * qs : add_mul _ _ _ ... = ppsqs : ppsqs_pf /-- Multiply two expressions. * `0 * qs = 0` * `(p + ps) * qs = (p * qs) + (ps * qs)` -/ meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum) | ps@(ex.zero ps_i) qs := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info], pure $ z.set_info z_o pf | pps@(ex.sum pps_i p ps) qs := do pqs ← mul_pp p qs >>= prod_to_sum, psqs ← mul_p ps qs, ppsqs ← add pqs psqs, pps_pf ← pps.proof_term, ppsqs_o ← mul_orig pps qs, ppsqs_pf ← ppsqs.proof_term, pf ← mk_proof ``mul_p_pf_sum [pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty] [pps.info, ppsqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 := λ qs_pf, by rw [qs_pf, mul_zero] lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs → ps * qqs = psqqs := λ qs_pf psqqs_pf, calc ps * qqs = ps * (q + qs) : by rw [qs_pf] ... = ps * q + ps * qs : mul_add _ _ _ ... = psqqs : psqqs_pf /-- Multiply two expressions. * `ps * 0 = 0` * `ps * (q + qs) = (ps * q) + (ps * qs)` -/ meta def mul : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do z ← ex_zero, z_o ← mul_orig ps qs, pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info], pure $ z.set_info z_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← mul_p ps q, psqs ← mul ps qs, psqqs ← add psq psqs, psqqs_o ← mul_orig ps qqs, pf ← mk_proof ``mul_pf_sum [ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end multiplication section exponentiation lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} : pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs := λ pps_pf psqs_pf, calc pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf] ... = p ^ (ps * qs) : symm (pow_mul _ _ _) ... = p ^ psqs : by rw [psqs_pf] /-- Compute the exponentiation of two coefficients. The returned value is of the form `ex.coeff _ (p ^ q)`, with the proof of `expr.of_rat p ^ expr.of_rat q = expr.of_rat (p ^ q)`. -/ meta def pow_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do ctx ← get_context, pq' ← mk_pow [p_p, q_p], (pq_p, pq_pf) ← lift $ norm_num.eval_pow pq', pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩ /-- Exponentiate two expressions. * `(p ^ ps) ^ qs = p ^ (ps * qs)` -/ meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp) | pps@(ex.exp pps_i p ps) qs := do psqs ← in_exponent $ mul_pp ps qs, ppsqs ← ex_exp p psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_e_pf_exp [pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty] [pps.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 := λ ps_pf, by rw [ps_pf, one_pow] lemma pow_pf_c_c {ps ps' pq : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps' ^ qs' = pq → ps ^ qs = pq := by cc lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 := by simp; cc lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps → p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs := λ pps_pf pqs_pf psqs_pf, calc pps ^ qs = (p * ps) ^ qs : by rw [pps_pf] ... = p ^ qs * ps ^ qs : mul_pow _ _ _ ... = pqs * psqs : by rw [pqs_pf, psqs_pf] /-- Exponentiate two expressions. * `1 ^ qs = 1` * `x ^ qs = x ^ qs` (for `x` coefficient) * `(p * ps) ^ qs = p ^ qs + ps ^ qs` -/ meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod) | ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info], pure $ o.set_info o_o pf | ps@(ex.coeff ps_i x) qs@(ex.coeff qs_i y) := do pq ← pow_coeff ps.pretty qs.pretty x y, pq_o ← pow_orig ps qs, pf ← mk_proof_or_refl pq.pretty ``pow_pf_c_c [ps.orig, ps.pretty, pq.pretty, qs.orig, qs.pretty] [ps.info, qs.info, pq.info], pure $ pq.set_info pq_o pf | ps@(ex.coeff ps_i x) qs := do ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b, pqs ← ex_exp ps'' qs, pqs_o ← pow_orig ps qs, pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c [ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty] [ps.info, qs.info, pqs.info], pqs' ← exp_to_prod pqs, pure $ pqs'.set_info pqs_o pf | pps@(ex.prod pps_i p ps) qs := do pqs ← pow_e p qs, psqs ← pow_pp ps qs, ppsqs ← ex_prod pqs psqs, ppsqs_o ← pow_orig pps qs, pf ← mk_proof ``pow_pp_pf_prod [pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig] [pps.info, pqs.info, psqs.info], pure $ ppsqs.set_info ppsqs_o pf lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' := λ ps_pf qs_pf, calc ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf] ... = ps' : pow_one _ lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 := λ ps_pf qs_pf, calc ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf] ... = 0 : zero_pow (succ_pos qs') lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} : qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs := λ qs_pf pqqs_pf, calc ps ^ qs = ps ^ succ qs' : by rw [qs_pf] ... = ps * ps ^ qs' : pow_succ _ _ ... = pqqs : by rw [pqqs_pf] lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} : pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs := λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf] lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} : ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc /-- Exponentiate two expressions. * `ps ^ 1 = ps` * `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`) * `(p + 0) ^ qs = p ^ qs` * `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`) * `ps ^ qs = ps ^ qs` (otherwise) -/ meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum) | ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do ps_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info], pure $ ps.set_info ps_o pf | ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do ctx ← get_context, z ← ex_zero, qs_pred ← lift $ expr.of_nat ctx.info_e.α y, pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info], z_o ← pow_orig ps qs, pure $ z.set_info z_o pf | pps@(ex.sum pps_i p (ex.zero _)) qqs := do pqs ← pow_pp p qqs, pqs_o ← pow_orig pps qqs, pf ← mk_proof ``pow_p_pf_singleton [pps.orig, p.pretty, pqs.pretty, qqs.orig] [pps.info, pqs.info], prod_to_sum $ pqs.set_info pqs_o pf | ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩, pqs ← pow_p ps qs', pqqs ← mul ps pqs, pqqs_o ← pow_orig ps qs, pf ← mk_proof ``pow_p_pf_succ [ps.orig, pqqs.pretty, qs.orig, qs'.pretty] [qs.info, pqqs.info], pure $ pqqs.set_info pqqs_o pf | pps qqs := do -- fallback: treat them as atoms pps' ← ex_sum_b pps, psqs ← ex_exp pps' qqs, psqs_o ← pow_orig pps qqs, pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons [pps.orig, pps.pretty, qqs.orig, qqs.pretty] [pps.info, qqs.info], exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc ps ^ qs = ps ^ 0 : by rw [qs_pf] ... = 1 : pow_zero _ lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs → ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf] ... = ps ^ q * ps ^ qs : pow_add _ _ _ ... = psqqs : psqqs_pf /-- Exponentiate two expressions. * `ps ^ 0 = 1` * `ps ^ (q + qs) = ps ^ q * ps ^ qs` -/ meta def pow : ex sum → ex sum → ring_exp_m (ex sum) | ps qs@(ex.zero qs_i) := do o ← ex_one, o_o ← pow_orig ps qs, pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info], prod_to_sum $ o.set_info o_o pf | ps qqs@(ex.sum qqs_i q qs) := do psq ← pow_p ps q, psqs ← pow ps qs, psqqs ← mul psq psqs, psqqs_o ← pow_orig ps qqs, pf ← mk_proof ``pow_pf_sum [ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty] [qqs.info, psqqs.info], pure $ psqqs.set_info psqqs_o pf end exponentiation lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp /-- Give a simpler, more human-readable representation of the normalized expression. Normalized expressions might have the form `a^1 * 1 + 0`, since the dummy operations reduce special cases in pattern-matching. Humans prefer to read `a` instead. This tactic gets rid of the dummy additions, multiplications and exponentiations. Returns a normalized expression `e'` and a proof that `e.pretty = e'`. -/ meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr) | sum pps@(ex.sum pps_i p (ex.zero _)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf] | sum (ex.sum pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_add [p_p, ps_p] <*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf] | prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := prod.mk pps.pretty <$> lift (mk_eq_refl pps.pretty) | (some ringi) := do (p_p, p_pf) ← p.simple, prod.mk <$> lift (mk_app ``has_neg.neg [p_p]) <*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf] end | prod (ex.prod pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← ps.simple, prod.mk <$> mk_mul [p_p, ps_p] <*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | base (ex.sum_b pps_i ps) := ps.simple | exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do (p_p, p_pf) ← p.simple, prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf] | exp (ex.exp pps_i p ps) := do (p_p, p_pf) ← p.simple, (ps_p, ps_pf) ← in_exponent $ ps.simple, prod.mk <$> mk_pow [p_p, ps_p] <*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf] | et ps := prod.mk ps.pretty <$> lift (mk_eq_refl ps.pretty) /-- Performs a lookup of the atom `a` in the list of known atoms, or allocates a new one. If `a` is not definitionally equal to any of the list's entries, a new atom is appended to the list and returned. The index of this atom is kept track of in the second inductive argument. This function is mostly useful in `resolve_atom`, which updates the state with the new list of atoms. -/ meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom) | [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm]) | bas@(b :: as) n := do ctx ← get_context, (lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do (atm, as') ← resolve_atom_aux as (succ n), pure (atm, b :: as') /-- Convert the expression to an atom: either look up a definitionally equal atom, or allocate it as a new atom. You probably want to use `eval_base` if `eval` doesn't work instead of directly calling `resolve_atom`, since `eval_base` can also handle numerals. -/ meta def resolve_atom (a : expr) : ring_exp_m atom := do atoms ← reader_t.lift $ state_t.get, (atm, atoms') ← resolve_atom_aux a atoms 0, reader_t.lift $ state_t.put atoms', pure atm /-- Treat the expression atomically: as a coefficient or atom. Handles cases where `eval` cannot treat the expression as a known operation because it is just a number or single variable. -/ meta def eval_base (ps : expr) : ring_exp_m (ex sum) := match ps.to_rat with | some ⟨0, 1, _, _⟩ := ex_zero | some x := ex_coeff x >>= prod_to_sum | none := do a ← resolve_atom ps, atom_to_sum a end lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp /-- Negate an expression by multiplying with `-1`. Only works if there is a `ring` instance; otherwise it will `fail`. -/ meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, match ctx.info_b.ring_instance with | none := lift $ fail "internal error: negate called in semiring" | (some ring_instance) := do minus_one ← ex_coeff (-1) >>= prod_to_sum, ps' ← mul minus_one ps, ps_pf ← ps'.proof_term, pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf], ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig], pure $ ps'.set_info ps'_o pf end lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} : ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' := by cc /-- Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom. Only works if there is a `division_ring` instance; otherwise it will `fail`. -/ meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only supported in a division ring" | (some dri) := pure dri end, (ps_simple, ps_simple_pf) ← ps.simple, e ← lift $ mk_app ``has_inv.inv [ps_simple], (e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)), e'' ← eval_base e', ps_pf ← ps.proof_term, e''_pf ← e''.proof_term, pf ← mk_app_class ``inverse_pf dri [ ps.orig, ps.pretty, ps_simple, e', e''.pretty, ps_pf, ps_simple_pf, e_pf, e''_pf], e''_o ← lift $ mk_app ``has_inv.inv [ps.orig], pure $ e''.set_info e''_o pf lemma sub_pf {α} [ring α] {ps qs psqs : α} (h : ps + -qs = psqs) : ps - qs = psqs := by rwa sub_eq_add_neg lemma div_pf {α} [division_ring α] {ps qs psqs : α} (h : ps * qs⁻¹ = psqs) : ps / qs = psqs := by rwa div_eq_mul_inv end operations section wiring /-! ### `wiring` section This section deals with going from `expr` to `ex` and back. The main attraction is `eval`, which uses `add`, `mul`, etc. to calculate an `ex` from a given `expr`. Other functions use `ex`es to produce `expr`s together with a proof, or produce the context to run `ring_exp_m` from an `expr`. -/ open tactic open ex_type /-- Compute a normalized form (of type `ex`) from an expression (of type `expr`). This is the main driver of the `ring_exp` tactic, calling out to `add`, `mul`, `pow`, etc. to parse the `expr`. -/ meta def eval : expr → ring_exp_m (ex sum) | e@`(%%ps + %%qs) := do ps' ← eval ps, qs' ← eval qs, add ps' qs' | ps_o@`(nat.succ %%p_o) := do ps' ← eval `(%%p_o + 1), pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o], rewrite ps_o ps' pf | e@`(%%ps - %%qs) := (do ctx ← get_context, ri ← match ctx.info_b.ring_instance with | none := lift $ fail "subtraction is not directly supported in a semiring" | (some ri) := pure ri end, ps' ← eval ps, qs' ← eval qs >>= negate, psqs ← add ps' qs', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(- %%ps) := do ps' ← eval ps, negate ps' <|> eval_base e | e@`(%%ps * %%qs) := do ps' ← eval ps, qs' ← eval qs, mul ps' qs' | e@`(has_inv.inv %%ps) := do ps' ← eval ps, inverse ps' <|> eval_base e | e@`(%%ps / %%qs) := do ctx ← get_context, dri ← match ctx.info_b.dr_instance with | none := lift $ fail "division is only directly supported in a division ring" | (some dri) := pure dri end, ps' ← eval ps, qs' ← eval qs, (do qs'' ← inverse qs', psqs ← mul ps' qs'', psqs_pf ← psqs.proof_term, pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf], pure (psqs.set_info e pf)) <|> eval_base e | e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do ps' ← eval ps, qs' ← in_exponent $ eval qs, psqs ← pow ps' qs', psqs_pf ← psqs.proof_term, (do has_pow_pf ← match hp_instance with | `(monoid.has_pow) := lift $ mk_eq_refl e | _ := lift $ fail "has_pow instance must be nat.has_pow or monoid.has_pow" end, pf ← lift $ mk_eq_trans has_pow_pf psqs_pf, pure $ psqs.set_info e pf) <|> eval_base e | ps := eval_base ps /-- Run `eval` on the expression and return the result together with normalization proof. See also `eval_simple` if you want something that behaves like `norm_num`. -/ meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do e' ← eval e, prod.mk e' <$> e'.proof_term /-- Run `eval` on the expression and simplify the result. Returns a simplified normalized expression, together with an equality proof. See also `eval_with_proof` if you just want to check the equality of two expressions. -/ meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do (complicated, complicated_pf) ← eval_with_proof e, (simple, simple_pf) ← complicated.simple, prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf) /-- Compute the `eval_info` for a given type `α`. -/ meta def make_eval_info (α : expr) : tactic eval_info := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance, ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none), dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none), ha_instance ← mk_app ``has_add [α] >>= mk_instance, hm_instance ← mk_app ``has_mul [α] >>= mk_instance, hp_instance ← mk_mapp ``monoid.has_pow [some α, none], z ← mk_mapp ``has_zero.zero [α, none], o ← mk_mapp ``has_one.one [α, none], pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩ /-- Use `e` to build the context for running `mx`. -/ meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do info_b ← infer_type e >>= make_eval_info, info_e ← mk_const ``nat >>= make_eval_info, (λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) []) /-- Repeatedly apply `eval_simple` on (sub)expressions. -/ meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do (_, e', pf') ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (e'', pf) ← run_ring_exp transp e $ eval_simple e, guard (¬ e'' =ₐ e), return ((), e'', some pf, ff)) (λ _ _ _ _ _, failed) `eq e, pure (e', pf') end wiring end tactic.ring_exp namespace tactic.interactive open interactive interactive.types lean.parser tactic tactic.ring_exp local postfix (name := parser.optional) `?`:9001 := optional /-- Tactic for solving equations of *commutative* (semi)rings, allowing variables in the exponent. This version of `ring_exp` fails if the target is not an equality. The variant `ring_exp_eq!` will use a more aggressive reducibility setting to determine equality of atoms. -/ meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do `(eq %%ps %%qs) ← target >>= whnf, let transp := if red.is_some then semireducible else reducible, ((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $ prod.mk <$> eval_with_proof ps <*> eval_with_proof qs, if ps'.eq qs' then do qs_pf_inv ← mk_eq_symm qs_pf, pf ← mk_eq_trans ps_pf qs_pf_inv, tactic.interactive.exact ``(%%pf) else fail "ring_exp failed to prove equality" /-- Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the exponent. This tactic extends `ring`: it should solve every goal that `ring` can solve. Additionally, it knows how to evaluate expressions with complicated exponents (where `ring` only understands constant exponents). The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine equality of atoms. For example: ```lean example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp example (x y : ℕ) : x + id y = y + id x := by ring_exp! ``` -/ meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := ring_exp_eq red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp) ns loc.include_goal | fail "ring_exp failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "ring_exp", category := doc_category.tactic, decl_names := [`tactic.interactive.ring_exp], tags := ["arithmetic", "simplification", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive open tactic tactic.interactive (ring_exp_eq) open tactic.ring_exp (normalize) local postfix (name := parser.optional) `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring_exp`. -/ meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring_exp_eq red) <|> replace_lhs (normalize transp) <|> fail "ring_exp failed to simplify" end conv.interactive
0fedab747eb15dc897e9791fbfc0580c8c5a04d4
6b66bef80b7e8adaed86c183cf24aa8f92f20803
/LeanTools.lean
066dc82830247f8002f3ef3572ea2e48291aabc9
[ "MIT" ]
permissive
JasonGross/lean-tools
f5495e6a24061a2f268fd0871c88cb4ece8d3355
110f63934b9d8c9088b0a944a38ed975b740a507
refs/heads/main
1,679,568,529,028
1,616,441,204,000
1,616,441,204,000
349,493,484
1
0
null
null
null
null
UTF-8
Lean
false
false
1,157
lean
import LeanTools.FindBug import LeanTools.CommandLineColors --import Cli --open Cli open LeanTools /- def run (args : Parsed) : IO UInt32 := pure 0 def cmd : Cmd := `[Cli| LeanTools VIA run; ["0.0.1"] "A collection of command-line tools for processing Lean files." FLAGS: SUBCOMMANDS: FindBug.cmd ] def main (args : List String) : IO UInt32 := do cmd.validate! args -/ structure Driver where name : String act : List String → IO UInt32 def known_drivers : List Driver := [ { name := "find-bug", act := FindBug.run' } ] def usage : List String := [] def print_usage {A} (ret : A) : IO A := pure ret def main (args : List String) : IO UInt32 := do match args with | [] => print_usage 1 | ["-h"] => print_usage 0 | ["--help"] => print_usage 0 | driver :: rest_args => match List.find? (λ d => driver = d.name) known_drivers with | Option.some d => d.act rest_args | Option.none => do let valid_drivers := List.map Driver.name known_drivers IO.println s!"{ANSI.red}Error{ANSI.reset}: Invalid driver {driver}, expected -h, --help, or one of: {valid_drivers}" pure 1
49a9092a601bdfa9c6dd26eb5754f77fca952bde
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/limits/constructions/finite_products_of_binary_products.lean
3506c733d254869d6bba59c8fdd38339cfd96869
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
13,110
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.preserves.shapes.products import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.finite_products import category_theory.pempty import logic.equiv.fin /-! # Constructing finite products from binary products and terminal. If a category has binary products and a terminal object then it has finite products. If a functor preserves binary products and the terminal object then it preserves finite products. # TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ universes v v' u u' noncomputable theory open category_theory category_theory.category category_theory.limits namespace category_theory variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variables {D : Type u'} [category.{v'} D] /-- Given `n+1` objects of `C`, a fan for the last `n` with point `c₁.X` and a binary fan on `c₁.X` and `f 0`, we can build a fan for all `n+1`. In `extend_fan_is_limit` we show that if the two given fans are limits, then this fan is also a limit. -/ @[simps {rhs_md := semireducible}] def extend_fan {n : ℕ} {f : fin (n+1) → C} (c₁ : fan (λ (i : fin n), f i.succ)) (c₂ : binary_fan (f 0) c₁.X) : fan f := fan.mk c₂.X begin refine fin.cases _ _, { apply c₂.fst }, { intro i, apply c₂.snd ≫ c₁.π.app ⟨i⟩ }, end /-- Show that if the two given fans in `extend_fan` are limits, then the constructed fan is also a limit. -/ def extend_fan_is_limit {n : ℕ} (f : fin (n+1) → C) {c₁ : fan (λ (i : fin n), f i.succ)} {c₂ : binary_fan (f 0) c₁.X} (t₁ : is_limit c₁) (t₂ : is_limit c₂) : is_limit (extend_fan c₁ c₂) := { lift := λ s, begin apply (binary_fan.is_limit.lift' t₂ (s.π.app ⟨0⟩) _).1, apply t₁.lift ⟨_, discrete.nat_trans (λ ⟨i⟩, s.π.app ⟨i.succ⟩)⟩ end, fac' := λ s ⟨j⟩, begin apply fin.induction_on j, { apply (binary_fan.is_limit.lift' t₂ _ _).2.1 }, { rintro i -, dsimp only [extend_fan_π_app], rw [fin.cases_succ, ← assoc, (binary_fan.is_limit.lift' t₂ _ _).2.2, t₁.fac], refl } end, uniq' := λ s m w, begin apply binary_fan.is_limit.hom_ext t₂, { rw (binary_fan.is_limit.lift' t₂ _ _).2.1, apply w ⟨0⟩ }, { rw (binary_fan.is_limit.lift' t₂ _ _).2.2, apply t₁.uniq ⟨_, _⟩, rintro ⟨j⟩, rw assoc, dsimp only [discrete.nat_trans_app, extend_fan_is_limit._match_1], rw ← w ⟨j.succ⟩, dsimp only [extend_fan_π_app], rw fin.cases_succ } end } section variables [has_binary_products C] [has_terminal C] /-- If `C` has a terminal object and binary products, then it has a product for objects indexed by `fin n`. This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_product_fin : Π (n : ℕ) (f : fin n → C), has_product f | 0 := λ f, begin letI : has_limits_of_shape (discrete (fin 0)) C := has_limits_of_shape_of_equivalence (discrete.equivalence.{0} fin_zero_equiv'.symm), apply_instance, end | (n+1) := λ f, begin haveI := has_product_fin n, apply has_limit.mk ⟨_, extend_fan_is_limit f (limit.is_limit _) (limit.is_limit _)⟩, end /-- If `C` has a terminal object and binary products, then it has limits of shape `discrete (fin n)` for any `n : ℕ`. This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_limits_of_shape_fin (n : ℕ) : has_limits_of_shape (discrete (fin n)) C := { has_limit := λ K, begin letI := has_product_fin n (λ n, K.obj ⟨n⟩), let : discrete.functor (λ n, K.obj ⟨n⟩) ≅ K := discrete.nat_iso (λ ⟨i⟩, iso.refl _), apply has_limit_of_iso this, end } /-- If `C` has a terminal object and binary products, then it has finite products. -/ lemma has_finite_products_of_has_binary_and_terminal : has_finite_products C := ⟨λ J 𝒥, begin resetI, apply has_limits_of_shape_of_equivalence (discrete.equivalence (fintype.equiv_fin J)).symm, refine has_limits_of_shape_fin (fintype.card J), end⟩ end section preserves variables (F : C ⥤ D) variables [preserves_limits_of_shape (discrete walking_pair) F] variables [preserves_limits_of_shape (discrete.{0} pempty) F] variables [has_finite_products.{v} C] /-- If `F` preserves the terminal object and binary products, then it preserves products indexed by `fin n` for any `n`. -/ noncomputable def preserves_fin_of_preserves_binary_and_terminal : Π (n : ℕ) (f : fin n → C), preserves_limit (discrete.functor f) F | 0 := λ f, begin letI : preserves_limits_of_shape (discrete (fin 0)) F := preserves_limits_of_shape_of_equiv.{0 0} (discrete.equivalence fin_zero_equiv'.symm) _, apply_instance, end | (n+1) := begin haveI := preserves_fin_of_preserves_binary_and_terminal n, intro f, refine preserves_limit_of_preserves_limit_cone (extend_fan_is_limit f (limit.is_limit _) (limit.is_limit _)) _, apply (is_limit_map_cone_fan_mk_equiv _ _ _).symm _, let := extend_fan_is_limit (λ i, F.obj (f i)) (is_limit_of_has_product_of_preserves_limit F _) (is_limit_of_has_binary_product_of_preserves_limit F _ _), refine is_limit.of_iso_limit this _, apply cones.ext _ _, apply iso.refl _, rintro ⟨j⟩, apply fin.induction_on j, { apply (category.id_comp _).symm }, { rintro i -, dsimp only [extend_fan_π_app, iso.refl_hom, fan.mk_π_app], rw [fin.cases_succ, fin.cases_succ], change F.map _ ≫ _ = 𝟙 _ ≫ _, rw [id_comp, ←F.map_comp], refl } end /-- If `F` preserves the terminal object and binary products, then it preserves limits of shape `discrete (fin n)`. -/ def preserves_shape_fin_of_preserves_binary_and_terminal (n : ℕ) : preserves_limits_of_shape (discrete (fin n)) F := { preserves_limit := λ K, begin let : discrete.functor (λ n, K.obj ⟨n⟩) ≅ K := discrete.nat_iso (λ ⟨i⟩, iso.refl _), haveI := preserves_fin_of_preserves_binary_and_terminal F n (λ n, K.obj ⟨n⟩), apply preserves_limit_of_iso_diagram F this, end } /-- If `F` preserves the terminal object and binary products then it preserves finite products. -/ def preserves_finite_products_of_preserves_binary_and_terminal (J : Type) [fintype J] : preserves_limits_of_shape (discrete J) F := begin classical, let e := fintype.equiv_fin J, haveI := preserves_shape_fin_of_preserves_binary_and_terminal F (fintype.card J), apply preserves_limits_of_shape_of_equiv.{0 0} (discrete.equivalence e).symm, end end preserves /-- Given `n+1` objects of `C`, a cofan for the last `n` with point `c₁.X` and a binary cofan on `c₁.X` and `f 0`, we can build a cofan for all `n+1`. In `extend_cofan_is_colimit` we show that if the two given cofans are colimits, then this cofan is also a colimit. -/ @[simps {rhs_md := semireducible}] def extend_cofan {n : ℕ} {f : fin (n+1) → C} (c₁ : cofan (λ (i : fin n), f i.succ)) (c₂ : binary_cofan (f 0) c₁.X) : cofan f := cofan.mk c₂.X begin refine fin.cases _ _, { apply c₂.inl }, { intro i, apply c₁.ι.app ⟨i⟩ ≫ c₂.inr }, end /-- Show that if the two given cofans in `extend_cofan` are colimits, then the constructed cofan is also a colimit. -/ def extend_cofan_is_colimit {n : ℕ} (f : fin (n+1) → C) {c₁ : cofan (λ (i : fin n), f i.succ)} {c₂ : binary_cofan (f 0) c₁.X} (t₁ : is_colimit c₁) (t₂ : is_colimit c₂) : is_colimit (extend_cofan c₁ c₂) := { desc := λ s, begin apply (binary_cofan.is_colimit.desc' t₂ (s.ι.app ⟨0⟩) _).1, apply t₁.desc ⟨_, discrete.nat_trans (λ i, s.ι.app ⟨i.as.succ⟩)⟩ end, fac' := λ s, begin rintro ⟨j⟩, apply fin.induction_on j, { apply (binary_cofan.is_colimit.desc' t₂ _ _).2.1 }, { rintro i -, dsimp only [extend_cofan_ι_app], rw [fin.cases_succ, assoc, (binary_cofan.is_colimit.desc' t₂ _ _).2.2, t₁.fac], refl } end, uniq' := λ s m w, begin apply binary_cofan.is_colimit.hom_ext t₂, { rw (binary_cofan.is_colimit.desc' t₂ _ _).2.1, apply w ⟨0⟩ }, { rw (binary_cofan.is_colimit.desc' t₂ _ _).2.2, apply t₁.uniq ⟨_, _⟩, rintro ⟨j⟩, dsimp only [discrete.nat_trans_app], rw ← w ⟨j.succ⟩, dsimp only [extend_cofan_ι_app], rw [fin.cases_succ, assoc], } end } section variables [has_binary_coproducts C] [has_initial C] /-- If `C` has an initial object and binary coproducts, then it has a coproduct for objects indexed by `fin n`. This is a helper lemma for `has_cofinite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_coproduct_fin : Π (n : ℕ) (f : fin n → C), has_coproduct f | 0 := λ f, begin letI : has_colimits_of_shape (discrete (fin 0)) C := has_colimits_of_shape_of_equivalence (discrete.equivalence.{0} fin_zero_equiv'.symm), apply_instance, end | (n+1) := λ f, begin haveI := has_coproduct_fin n, apply has_colimit.mk ⟨_, extend_cofan_is_colimit f (colimit.is_colimit _) (colimit.is_colimit _)⟩, end /-- If `C` has an initial object and binary coproducts, then it has colimits of shape `discrete (fin n)` for any `n : ℕ`. This is a helper lemma for `has_cofinite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_colimits_of_shape_fin (n : ℕ) : has_colimits_of_shape (discrete (fin n)) C := { has_colimit := λ K, begin letI := has_coproduct_fin n (λ n, K.obj ⟨n⟩), let : K ≅ discrete.functor (λ n, K.obj ⟨n⟩) := discrete.nat_iso (λ ⟨i⟩, iso.refl _), apply has_colimit_of_iso this, end } /-- If `C` has an initial object and binary coproducts, then it has finite coproducts. -/ lemma has_finite_coproducts_of_has_binary_and_terminal : has_finite_coproducts C := ⟨λ J 𝒥, begin resetI, apply has_colimits_of_shape_of_equivalence (discrete.equivalence (fintype.equiv_fin J)).symm, refine has_colimits_of_shape_fin (fintype.card J), end⟩ end section preserves variables (F : C ⥤ D) variables [preserves_colimits_of_shape (discrete walking_pair) F] variables [preserves_colimits_of_shape (discrete.{0} pempty) F] variables [has_finite_coproducts.{v} C] /-- If `F` preserves the initial object and binary coproducts, then it preserves products indexed by `fin n` for any `n`. -/ noncomputable def preserves_fin_of_preserves_binary_and_initial : Π (n : ℕ) (f : fin n → C), preserves_colimit (discrete.functor f) F | 0 := λ f, begin letI : preserves_colimits_of_shape (discrete (fin 0)) F := preserves_colimits_of_shape_of_equiv.{0 0} (discrete.equivalence fin_zero_equiv'.symm) _, apply_instance, end | (n+1) := begin haveI := preserves_fin_of_preserves_binary_and_initial n, intro f, refine preserves_colimit_of_preserves_colimit_cocone (extend_cofan_is_colimit f (colimit.is_colimit _) (colimit.is_colimit _)) _, apply (is_colimit_map_cocone_cofan_mk_equiv _ _ _).symm _, let := extend_cofan_is_colimit (λ i, F.obj (f i)) (is_colimit_of_has_coproduct_of_preserves_colimit F _) (is_colimit_of_has_binary_coproduct_of_preserves_colimit F _ _), refine is_colimit.of_iso_colimit this _, apply cocones.ext _ _, apply iso.refl _, rintro ⟨j⟩, apply fin.induction_on j, { apply category.comp_id }, { rintro i -, dsimp only [extend_cofan_ι_app, iso.refl_hom, cofan.mk_ι_app], rw [fin.cases_succ, fin.cases_succ], erw [comp_id, ←F.map_comp], refl, } end /-- If `F` preserves the initial object and binary coproducts, then it preserves colimits of shape `discrete (fin n)`. -/ def preserves_shape_fin_of_preserves_binary_and_initial (n : ℕ) : preserves_colimits_of_shape (discrete (fin n)) F := { preserves_colimit := λ K, begin let : discrete.functor (λ n, K.obj ⟨n⟩) ≅ K := discrete.nat_iso (λ ⟨i⟩, iso.refl _), haveI := preserves_fin_of_preserves_binary_and_initial F n (λ n, K.obj ⟨n⟩), apply preserves_colimit_of_iso_diagram F this, end } /-- If `F` preserves the initial object and binary coproducts then it preserves finite products. -/ def preserves_finite_coproducts_of_preserves_binary_and_initial (J : Type) [fintype J] : preserves_colimits_of_shape (discrete J) F := begin classical, let e := fintype.equiv_fin J, haveI := preserves_shape_fin_of_preserves_binary_and_initial F (fintype.card J), apply preserves_colimits_of_shape_of_equiv.{0 0} (discrete.equivalence e).symm, end end preserves end category_theory
ef658b5f16a0d36663e2723f9073568160d69007
7d5ad87afb17e514aee234fcf0a24412eed6384f
/src/zfc.lean
221bd156c1508b92e4dfdeea5afc2871b9e9a6df
[]
no_license
digama0/flypitch
764f849eaef59c045dfbeca142a0f827973e70c1
2ec14b8da6a3964f09521d17e51f363d255b030f
refs/heads/master
1,586,980,069,651
1,547,078,141,000
1,547,078,283,000
164,965,135
1
0
null
1,547,082,858,000
1,547,082,857,000
null
UTF-8
Lean
false
false
14,322
lean
import .fol set_theory.zfc tactic.tidy open fol namespace zfc inductive ZFC_rel : ℕ → Type 1 | ϵ : ZFC_rel 2 def L_ZFC : Language.{1} := ⟨λ_, ulift empty, ZFC_rel⟩ /- Note from Mario: should try using L_ZFC' -/ def ZFC_el : L_ZFC.relations 2 := ZFC_rel.ϵ local infix ` ∈' `:100 := bounded_formula_of_relation ZFC_el ---ugly but working (str_formula says it's not well-founded recursion, but it evaluates anyways) --def str_preterm : ∀ n m : ℕ, ℕ → bounded_preterm L_ZFC n m → string -- | n m z &k := "x" ++ to_string(z - k) -- | _ _ _ _ := "h" --def str_term: ∀ n : ℕ, ℕ → bounded_term L_ZFC n → string -- | n m &k := "x" ++ to_string(m - k.val) -- | _ _ _ := "n" --def str_preformula : ∀ n m : ℕ, ℕ → bounded_preformula L_ZFC n m → string -- | _ _ _ (bd_falsum ) := "⊥" -- | n m z (bd_equal a b) := str_preterm n m z a ++ " = " ++ str_preterm n m z b -- | n m z (a ⟹ b) := str_preformula n m z a ++ " ⟹ " ++ str_preformula n m z b -- | n m z (bd_rel _) := "∈" -- | n m z (bd_apprel a b) := str_preformula n (m+1) z a ++ "(" ++ str_term n z b ++ ")" -- | n m z (∀' t) := "(∀x" ++ to_string(z+1) ++ "," ++ str_preformula (n+1) m (z+1) t ++ ")" --def str_formula : ∀ {n : ℕ}, bounded_formula L_ZFC n → ℕ → string -- | n ((f₁ ⟹ (f₂ ⟹ bd_falsum)) ⟹ bd_falsum) m:= "(" ++ str_formula f₁ m ++ "∧" ++ str_formula f₂ m ++ ")" -- | n ((f₁ ⟹ bd_falsum) ⟹ f₂) m := "(" ++ str_formula f₁ m ++ " ∨ " ++ str_formula f₂ m ++ ")" -- | n (bd_equal s1 s2) m := "(" ++ str_term n m s1 ++ " = " ++ str_term n m s2 ++ ")" -- | n (∀' f) m := "(∀x"++ to_string(m + 1) ++ "," ++ (str_formula f (m+1) ) ++ ")" -- | _ bd_falsum _ := "⊥" -- | n (f ⟹ bd_falsum) m := "~" ++ str_formula f m -- | n (bd_apprel (f₁) f₂) m := str_preformula n 1 m f₁ ++ "(" ++ str_term n m f₂ ++ ")" -- | n (bd_imp a b) m := "(" ++ str_formula a m ++ " ⟹ " ++ str_formula b m ++ ")" -- --def print_formula : ∀ {n : ℕ}, bounded_formula L_ZFC n → string := λ n f, str_formula f n notation `lift_cast` := by {repeat{apply nat.succ_le_succ}, apply nat.zero_le} -- section test -- /- ∀ x, ∀ y, x = y → ∀ z, z = x → z = y -/ -- def testsentence : sentence L_ZFC := ∀' ∀' (&1 ≃ &0 ⟹ ∀' (&0 ≃ &2 ⟹ &0 ≃ &1)) -- end test ---------------------------------------------------------------------------- def Class : Type 1 := bounded_formula L_ZFC 1 def small {n} (c : bounded_formula L_ZFC (n+1)) : bounded_formula L_ZFC n := ∃' ∀' (&0 ∈' &1 ⇔ (c ↑' 1 # 1)) def subclass (c₁ c₂ : Class) : sentence L_ZFC := ∀' (c₁ ⟹ c₂) def functional {n} (c : bounded_formula L_ZFC (n+2)) : bounded_formula L_ZFC n := -- ∀x ∃y ∀z, c z x ↔ z = y ∀' ∃' ∀' (c ↑' 1 # 1 ⇔ &0 ≃ &1) def subset : bounded_formula L_ZFC 2 := ∀' (&0 ∈' &1 ⟹ &0 ∈' &2) def is_emptyset : bounded_formula L_ZFC 1 := ∼ ∃' (&0 ∈' &1) def pair : bounded_formula L_ZFC 3 := (&0 ≃ &1 : bounded_formula L_ZFC 3) ⊔ (&0 ≃ &2 : bounded_formula L_ZFC 3) def singl : bounded_formula L_ZFC 2 := &0 ≃ &1 def binary_union : bounded_formula L_ZFC 3 := &0 ∈' &1 ⊔ &0 ∈' &2 def succ : bounded_formula L_ZFC 2 := (&0 ≃ &1 : bounded_formula L_ZFC 2) ⊔ &0 ∈' &1 def ordered_pair : bounded_formula L_ZFC 3 := ∀'(&0 ∈' &1 ⇔ (&0 ≃ &3 : bounded_formula L_ZFC 4) ⊔ ∀'(&0 ∈' &1 ⇔ pair ↑' 1 # 1 ↑' 1 # 1)) -- &0 is an ordered pair of &2 and &1 (z = ⟨x, y⟩) def ordered_pair' : bounded_formula L_ZFC 3 := ∀'(&0 ∈' &3 ⇔ (&0 ≃ &2 : bounded_formula L_ZFC 4) ⊔ ∀'(&0 ∈' &1 ⇔ (pair ↑' 1 # 1).cast(lift_cast))) -- &2 is an ordered pair of &1 and &0 (x = ⟨y,z⟩) def is_ordered_pair : bounded_formula L_ZFC 1 := ∃' ∃' ordered_pair --&0 is an ordered pair of some two elements-- def relation : bounded_formula L_ZFC 1 := ∀' ((&0 ∈' &1) ⟹ is_ordered_pair ↑' 1 # 1) --&0 is a relation (is a set of ordered pairs) def function : bounded_formula L_ZFC 1 := relation ⊓ ∀'∀'∀'∀'∀'(&1 ∈' &5 ⊓ ordered_pair ↑' 1 # 3 ↑' 1 # 1 ↑' 1 # 0 ⊓ ((&0 ∈' &5 : bounded_formula L_ZFC 6) ⊓ (ordered_pair ↑' 1 # 2 ↑' 1 # 1).cast(lift_cast)) ⟹ (&3 ≃ &2 : bounded_formula L_ZFC 6)) -- X is a function iff X is a relation and the following holds: -- ∀x ∀y ∀z ∀w ∀t, ((w ∈ X) ∧ (w = ⟨x, y⟩) ∧ (z ∈ X) ∧ (z = ⟨x, z⟩ ))) → y = z def fn_app : bounded_formula L_ZFC 3 := ∃'(&0 ∈' &3 ⊓ ∀'(&0 ∈' &1 ⇔ ((&0 ≃ &3): bounded_formula L_ZFC 5) ⊔ (pair ↑' 1 # 1).cast(lift_cast))) -- ⟨&1, &0⟩ ∈ &2 -- &0 = &2(&1) def fn_domain : bounded_formula L_ZFC 2 := ∀'(&0 ∈' &2 ⇔ ∃'∃'(ordered_pair ↑' 1 # 1 ↑' 1 # 1 ⊓ &0 ∈' &3)) -- &1 is the domain of &0 def fn_range : bounded_formula L_ZFC 2 := ∀'(&0 ∈' &2 ⇔ ∃'∃'(∀'(&0 ∈' &1 ⇔ (&0 ≃ &2 : bounded_formula L_ZFC 6) ⊔ (pair ↑' 1 # 1).cast(lift_cast)) ⊓ &0 ∈' &3)) --&1 is the range of &0 def inverse_relation : bounded_formula L_ZFC 2 := ∀'(&0 ∈' &1 ⇔ ∃'∃'(∃'(∀'(&0 ∈' &1 ⇔ (&0 ≃ &2 : bounded_formula L_ZFC 7) ⊔ (pair ↑' 1 # 1).cast(lift_cast)) ⊓ &0 ∈' &5 : bounded_formula L_ZFC 6)) ⊓ (ordered_pair'.cast(lift_cast))) -- &0 is the inverse relation of &1 def function_one_one : bounded_formula L_ZFC 1 := function ⊓ ∀' (inverse_relation ⟹ function.cast(lift_cast)) def irreflexive_relation : bounded_formula L_ZFC 2 := (∀'(&0 ∈' &2 ⟹ (∀'(∀'(&0 ∈' &1) ⇔ ((&0 ≃ &2 : bounded_formula L_ZFC 4) ⊔ ∀'(&0 ∈' &1 ⇔ (&0 ≃ &3 : bounded_formula L_ZFC 5))) ⟹ ∼(&0 ∈' &3))))) ⊓ relation.cast(lift_cast) -- &0 is an irreflexive relation on &1 def transitive_relation : bounded_formula L_ZFC 2 := ((∀'∀'∀'((((&2 ∈' &4 : bounded_formula L_ZFC 5) ⊓ (&1 ∈' &4)) ⊓ (&0 ∈' &4)) ⊓ ∃'((ordered_pair ↑' 1 # 1).cast(lift_cast) ⊓ (&0 ∈' &4 : bounded_formula L_ZFC 6)) ⊓ ∃'(ordered_pair.cast(lift_cast) ⊓ &0 ∈' &4 : bounded_formula L_ZFC 6) ⟹ ∃'((ordered_pair ↑' 1 # 2).cast(lift_cast) ⊓ &0 ∈' &4 : bounded_formula L_ZFC 6)))) ⊓ relation.cast(lift_cast) --&0 is a transitive relation on &1 -- X Tr Y iff X is a relation and the following holds: -- ∀u ∀v ∀w, (u ∈ Y ∧ v ∈ Y ∧ w ∈ Y ∧ ⟨u, v⟩ ∈ X ∧ ⟨v,w⟩ ∈ X) → ⟨u,w⟩ ∈ X def partial_order_zfc : bounded_formula L_ZFC 2 := irreflexive_relation ⊓ transitive_relation def connected_relation : bounded_formula L_ZFC 2 := relation ↑' 1 # 1 ⊓ ∀'∀'((bd_and (bd_and (&0 ∈' &3) (&1 ∈' &3)) ∼(bd_equal &0 &1)) ⟹ ∃'((&0 ∈' &3 : bounded_formula L_ZFC 5) ⊓ ((ordered_pair ↑' 1 # 3 ↑' 1 # 3) ⊔ ∀'(&0 ∈' &1 ⇔ (&0 ≃ &2 : bounded_formula L_ZFC 6) ⊔ (pair ↑' 1 # 1).cast(lift_cast))))) --&0 is a connected relation on &1 -- X Con Y iff Rel(X) and ∀u ∀v (u ∈ Y ∧ v ∈ Y ∧ u ≠ v) → ⟨u,v⟩ ∈ X ∨ ⟨v, u⟩ ∈ X def total_order : bounded_formula L_ZFC 2 := irreflexive_relation ⊓ transitive_relation ⊓ connected_relation def well_order : bounded_formula L_ZFC 2 := irreflexive_relation ⊓ ∀'(subset ↑' 1 # 2 ⊓ ∃'(&0 ∈' &1) ⟹ ∃'(&0 ∈' &1 ⊓ ∀'(((&0 ∈' &2) ⊓ ∼(&0 ≃ &1 : bounded_formula L_ZFC 5)) ⟹ ∃'(ordered_pair.cast(lift_cast) ⊓ (&0 ∈' &4 : bounded_formula L_ZFC 6)) ⊓ ∼∃'(∀'(&0 ∈' &1 ⇔ (( &0 ≃ &2 : bounded_formula L_ZFC 7) ⊔ (pair ↑' 1 # 1).cast(lift_cast) )) ⊓ &0 ∈' &4)))) -- &0 well-orders &1 def membership_relation : bounded_formula L_ZFC 1 := relation ⊓ ∀'(&0 ∈' &1 ⇔ ∃'∃'∀'(&0 ∈' &3 ⇔ ((bd_equal &0 &2) ⊔ pair ↑' 1 # 3 ↑' 1 # 3) ⊓ &2 ∈' &1)) -- &0 is E, the membership relation {⟨x,y⟩ | x ∈ y} def transitive_zfc : bounded_formula L_ZFC 1 := ∀' ((&0 ∈' &1) ⟹ subset) --&0 is transitive def fn_zfc_equiv : bounded_formula L_ZFC 3 := ((function_one_one.cast(lift_cast)) ⊓ (fn_domain ↑' 1 # 1)) ⊓ (fn_range ↑' 1 # 2) def zfc_equiv : bounded_formula L_ZFC 2 := ∃' fn_zfc_equiv --&0 ≃ &1, i.e. they are equinumerous def is_powerset : bounded_formula L_ZFC 2 := ∀' ((&0 ∈' &2) ⇔ subset ↑' 1 # 2) --&1 is P(&0) def is_suc_of : bounded_formula L_ZFC 2 := ∀' ((&0 ∈' &2) ⇔ ((&0 ∈' &1) ⊔ ( &0 ≃ &1 : bounded_formula L_ZFC 3))) -- &1 = succ(&0) def is_ordinal : bounded_formula L_ZFC 1 := (∀' ((membership_relation.cast(lift_cast)) ⟹ well_order)) ⊓ transitive_zfc def is_suc_ordinal : bounded_formula L_ZFC 1 := is_ordinal ⊓ ∃' is_suc_of --&0 is a successor ordinal def ordinal_lt : bounded_formula L_ZFC 2 := (is_ordinal.cast(lift_cast)) ⊓ (is_ordinal ↑' 1 # 0) ⊓ (&0 ∈' &1) -- &0 < &1 def ordinal_le : bounded_formula L_ZFC 2 := ordinal_lt ⊔ (bd_equal &0 &1) -- &0 ≤ &1 def is_first_infinite_ordinal : bounded_formula L_ZFC 1 := ∀' ((&0 ∈' &1) ⇔ (((is_emptyset ⊔ is_suc_ordinal)↑' 1 # 1) ⊓ ∀'((&0 ∈' &1) ⟹ ((is_emptyset ⊔ is_suc_ordinal).cast(lift_cast))))) --&0 = ω def is_uncountable_ordinal : bounded_formula L_ZFC 1 := ∀' ((is_first_infinite_ordinal.cast(lift_cast)) ⟹ ∀' (subset.cast(lift_cast) ⟹(∼(zfc_equiv ↑' 1 # 1)))) --&0 ≥ ω₁ def is_first_uncountable_ordinal : bounded_formula L_ZFC 1 := is_uncountable_ordinal ⊓ (∀' ((is_uncountable_ordinal ↑' 1 # 1) ⟹ ordinal_le)) --&0 = ω₁ /- Statement of CH -/ def continuum_hypothesis : sentence L_ZFC := ∀' ∀' ((∃'((is_first_infinite_ordinal ↑' 1 # 1 ↑' 1 # 1) ⊓ (is_powerset ↑' 1 # 2)) ⊓ (is_first_uncountable_ordinal ↑' 1 #0)) ⟹ zfc_equiv) #eval print_formula continuum_hypothesis def axiom_of_extensionality : sentence L_ZFC := ∀' ∀' (∀' (&0 ∈' &1 ⇔ &0 ∈' &2) ⟹ &0 ≃ &1) def axiom_of_union : sentence L_ZFC := ∀' (small ∃' (&1 ∈' &0 ⊓ &0 ∈' &2)) -- todo: c can have free variables. Note that c y x is interpreted as y is the image of x def axiom_of_replacement (c : bounded_formula L_ZFC 2) : sentence L_ZFC := -- ∀α small (λy, ∃x, x ∈ α ∧ c y x) functional c ⟹ ∀' (small ∃' (&0 ∈' &2 ⊓ c.cast1)) def axiom_of_powerset : sentence L_ZFC := -- the class of all subsets of x is small ∀' small subset def axiom_of_infinity : sentence L_ZFC := --∀x∃y(x ∈ y ∧ ∀z(z ∈ y → ∃w(z ∈ w ∧ w ∈ y))) ∀' ∃' (&1 ∈' &0 ⊓ ∀'(&0 ∈' &1 ⟹ ∃' (bd_and (&1 ∈' &0) (&0 ∈' &2)))) def axiom_of_choice : sentence L_ZFC := ∀'∀'(fn_domain ⟹ ∃'∀'(&0 ∈' &2 ⟹∀'(fn_app ↑' 1 # 2 ↑' 1 # 2 ⟹ (∀'(fn_app ↑' 1 # 1 ↑' 1 # 4 ↑' 1 # 4 ⊓ ∃'(&0 ∈' &2)) ⟹ &0 ∈' &1)))) def axiom_of_emptyset : sentence L_ZFC := small ⊥ -- todo: c can have free variables def axiom_of_separation (c : Class) : sentence L_ZFC := ∀' (small $ &0 ∈' &1 ⊓ c.cast1) -- the class consisting of the unordered pair {x, y} def axiom_of_pairing : sentence L_ZFC := ∀' ∀' small pair --the class consisting of the ordered pair ⟨x, y⟩ def axiom_of_ordered_pairing : sentence L_ZFC := ∀' ∀' small ordered_pair def ZF : Theory L_ZFC := {axiom_of_extensionality, axiom_of_union, axiom_of_powerset, axiom_of_infinity} ∪ (λ(c : bounded_formula L_ZFC 2), axiom_of_replacement c) '' set.univ def ZFC : Theory L_ZFC := ZF ∪ {axiom_of_choice} universe variable u def L_ZFC_structure_of_Set : Structure L_ZFC := begin refine ⟨Set,_,_⟩, {intros n f, repeat{cases f}}, {intros n r v, cases r, cases v, cases v_xs, exact v_x ∈ v_xs_x} end local notation `Set'` := L_ZFC_structure_of_Set instance has_mem_Set'_Set' : (has_mem Set' Set') := ⟨Set.mem⟩ instance has_mem_Set_Set' : has_mem Set.{0} Set' := ⟨Set.mem⟩ instance has_emptyc_Set' : has_emptyc Set' := ⟨Set.empty⟩ lemma empty_subset : ∀ x: Set', Set.empty ⊆ x := by tidy lemma Set'_has_mem : has_mem ↥Set' ↥Set' := ⟨ Set.mem ⟩ local notation h :: t := dvector.cons h t local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l example : Set' ⊨ (∃' is_emptyset) := begin unfold is_emptyset, simp[realize_sentence_ex], refine ⟨∅, _⟩, tidy end @[simp]lemma Set'_rel_mem {x y : Set} : (Structure.rel_map Set' ZFC_rel.ϵ ( [x,y] ) ) = (x ∈ y) := by tidy @[simp] lemma Set'_mem_mem {n : ℕ} {x y : bounded_term L_ZFC n} {v : dvector ↥Set' n} : realize_bounded_formula v (x ∈' y) dvector.nil = ((realize_bounded_term v x dvector.nil) ∈ (realize_bounded_term v y dvector.nil)) := begin simp [ZFC_el, bounded_formula_of_relation, realize_bounded_formula, bd_apps_rel] end @[simp]lemma realize_bounded_formula_biimp { n : ℕ } {L : Language } { S : Structure L} {f₁ f₂ : bounded_formula L n} {v : dvector ↥S n} : (realize_bounded_formula v (f₁ ⇔ f₂) dvector.nil) = ((realize_bounded_formula v f₁ dvector.nil) ↔ (realize_bounded_formula v f₂ dvector.nil)) := by {rw[bd_biimp], tidy} -- set_option trace.simplify.rewrite true lemma Set'_models_extensionality : axiom_of_extensionality ∈ Th Set' := begin simp [Th, axiom_of_extensionality, fin.val, has_one.one, fin.of_nat], intros x y, intro h, apply Set.ext, intro z, revert h, intro h, have := h z, exact this end lemma Set'_models_union : axiom_of_union ∈ Th Set' := begin simp only [Th, axiom_of_union, small], intro x, conv {congr, skip, congr, congr, congr, skip, change (∃' (&1 ∈' &0 ⊓ &0 ∈' &3) : bounded_formula L_ZFC 3)}, simp, change ∃ U, ∀ z, z ∈ U ↔ ∃ w, z ∈ w ∧ w ∈ x, refine ⟨⋃ x, _⟩, intro z, rw[@Set.mem_Union x z], finish end lemma Set'_models_powerset : axiom_of_powerset ∈ Th Set' := sorry lemma Set'_models_choice : axiom_of_choice ∈ Th Set' := sorry lemma Set'_models_infinity : axiom_of_infinity ∈ Th Set' := begin simp [has_mem.mem, set.mem, Th, set_of, axiom_of_infinity,satisfied_in], sorry end lemma Set'_models_replacement: ∀ c : bounded_formula L_ZFC 2, axiom_of_replacement c ∈ Th Set' := sorry lemma Set_extends_ZFC : ZFC ⊆ Th Set' := begin intros f hf, cases hf with zf choice, repeat{cases zf}, exact Set'_models_infinity, exact Set'_models_powerset, exact Set'_models_union, exact Set'_models_extensionality, dsimp at zf_h, cases zf_h with a b, subst b, revert zf_w, simp, exact Set'_models_replacement, repeat{cases choice}, exact Set'_models_choice end end zfc
5c2740702545469e6fe546bb0315d338957683c4
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/linear_algebra/affine_space/affine_equiv.lean
29ab17b6a9d414dbd7f816a6dd639359f1c4d508
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,991
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import linear_algebra.affine_space.affine_map import algebra.invertible /-! # Affine equivalences In this file we define `affine_equiv k P₁ P₂` (notation: `P₁ ≃ᵃ[k] P₂`) to be the type of affine equivalences between `P₁` and `P₂, i.e., equivalences such that both forward and inverse maps are affine maps. We define the following equivalences: * `affine_equiv.refl k P`: the identity map as an `affine_equiv`; * `e.symm`: the inverse map of an `affine_equiv` as an `affine_equiv`; * `e.trans e'`: composition of two `affine_equiv`s; note that the order follows `mathlib`'s `category_theory` convention (apply `e`, then `e'`), not the convention used in function composition and compositions of bundled morphisms. ## Tags affine space, affine equivalence -/ open function set open_locale affine /-- An affine equivalence is an equivalence between affine spaces such that both forward and inverse maps are affine. We define it using an `equiv` for the map and a `linear_equiv` for the linear part in order to allow affine equivalences with good definitional equalities. -/ @[nolint has_inhabited_instance] structure affine_equiv (k P₁ P₂ : Type*) {V₁ V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] extends P₁ ≃ P₂ := (linear : V₁ ≃ₗ[k] V₂) (map_vadd' : ∀ (p : P₁) (v : V₁), to_equiv (v +ᵥ p) = linear v +ᵥ to_equiv p) notation P₁ ` ≃ᵃ[`:25 k:25 `] `:0 P₂:0 := affine_equiv k P₁ P₂ instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] : has_coe_to_fun (P1 ≃ᵃ[k] P2) := ⟨_, λ e, e.to_fun⟩ variables {k V₁ V₂ V₃ V₄ P₁ P₂ P₃ P₄ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] [add_comm_group V₃] [module k V₃] [add_torsor V₃ P₃] [add_comm_group V₄] [module k V₄] [add_torsor V₄ P₄] namespace linear_equiv /-- Interpret a linear equivalence between modules as an affine equivalence. -/ def to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : V₁ ≃ᵃ[k] V₂ := { to_equiv := e.to_equiv, linear := e, map_vadd' := λ p v, e.map_add v p } @[simp] lemma coe_to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : ⇑e.to_affine_equiv = e := rfl end linear_equiv namespace affine_equiv variables (k P₁) include V₁ /-- Identity map as an `affine_equiv`. -/ @[refl] def refl : P₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.refl P₁, linear := linear_equiv.refl k V₁, map_vadd' := λ _ _, rfl } @[simp] lemma coe_refl : ⇑(refl k P₁) = id := rfl lemma refl_apply (x : P₁) : refl k P₁ x = x := rfl @[simp] lemma to_equiv_refl : (refl k P₁).to_equiv = equiv.refl P₁ := rfl @[simp] lemma linear_refl : (refl k P₁).linear = linear_equiv.refl k V₁ := rfl variables {k P₁} include V₂ @[simp] lemma map_vadd (e : P₁ ≃ᵃ[k] P₂) (p : P₁) (v : V₁) : e (v +ᵥ p) = e.linear v +ᵥ e p := e.map_vadd' p v @[simp] lemma coe_to_equiv (e : P₁ ≃ᵃ[k] P₂) : ⇑e.to_equiv = e := rfl /-- Reinterpret an `affine_equiv` as an `affine_map`. -/ def to_affine_map (e : P₁ ≃ᵃ[k] P₂) : P₁ →ᵃ[k] P₂ := { to_fun := e, .. e } @[simp] lemma coe_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : (e.to_affine_map : P₁ → P₂) = (e : P₁ → P₂) := rfl @[simp] lemma to_affine_map_mk (f : P₁ ≃ P₂) (f' : V₁ ≃ₗ[k] V₂) (h) : to_affine_map (mk f f' h) = ⟨f, f', h⟩ := rfl @[simp] lemma linear_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : e.to_affine_map.linear = e.linear := rfl lemma to_affine_map_injective : injective (to_affine_map : (P₁ ≃ᵃ[k] P₂) → (P₁ →ᵃ[k] P₂)) := begin rintros ⟨e, el, h⟩ ⟨e', el', h'⟩ H, simp only [to_affine_map_mk, equiv.coe_inj, linear_equiv.to_linear_map_inj] at H, congr, exacts [H.1, H.2] end @[simp] lemma to_affine_map_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_affine_map = e'.to_affine_map ↔ e = e' := to_affine_map_injective.eq_iff @[ext] lemma ext {e e' : P₁ ≃ᵃ[k] P₂} (h : ∀ x, e x = e' x) : e = e' := to_affine_map_injective $ affine_map.ext h lemma coe_fn_injective : injective (λ (e : P₁ ≃ᵃ[k] P₂) (x : P₁), e x) := λ e e' H, ext $ congr_fun H @[simp, norm_cast] lemma coe_fn_inj {e e' : P₁ ≃ᵃ[k] P₂} : ⇑e = e' ↔ e = e' := coe_fn_injective.eq_iff lemma to_equiv_injective : injective (to_equiv : (P₁ ≃ᵃ[k] P₂) → (P₁ ≃ P₂)) := λ e e' H, ext $ equiv.ext_iff.1 H @[simp] lemma to_equiv_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_equiv = e'.to_equiv ↔ e = e' := to_equiv_injective.eq_iff /-- Construct an affine equivalence by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `e : P₁ → P₂`, a linear equivalence `e' : V₁ ≃ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `e p' = e' (p' -ᵥ p) +ᵥ e p`. -/ def mk' (e : P₁ → P₂) (e' : V₁ ≃ₗ[k] V₂) (p : P₁) (h : ∀ p' : P₁, e p' = e' (p' -ᵥ p) +ᵥ e p) : P₁ ≃ᵃ[k] P₂ := { to_fun := e, inv_fun := λ q' : P₂, e'.symm (q' -ᵥ e p) +ᵥ p, left_inv := λ p', by simp [h p'], right_inv := λ q', by simp [h (e'.symm (q' -ᵥ e p) +ᵥ p)], linear := e', map_vadd' := λ p' v, by { simp [h p', h (v +ᵥ p'), vadd_vsub_assoc, vadd_vadd] } } @[simp] lemma coe_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl @[simp] lemma linear_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : (mk' e e' p h).linear = e' := rfl /-- Inverse of an affine equivalence as an affine equivalence. -/ @[symm] def symm (e : P₁ ≃ᵃ[k] P₂) : P₂ ≃ᵃ[k] P₁ := { to_equiv := e.to_equiv.symm, linear := e.linear.symm, map_vadd' := λ v p, e.to_equiv.symm.apply_eq_iff_eq_symm_apply.2 $ by simpa using (e.to_equiv.apply_symm_apply v).symm } @[simp] lemma symm_to_equiv (e : P₁ ≃ᵃ[k] P₂) : e.to_equiv.symm = e.symm.to_equiv := rfl @[simp] lemma symm_linear (e : P₁ ≃ᵃ[k] P₂) : e.linear.symm = e.symm.linear := rfl protected lemma bijective (e : P₁ ≃ᵃ[k] P₂) : bijective e := e.to_equiv.bijective protected lemma surjective (e : P₁ ≃ᵃ[k] P₂) : surjective e := e.to_equiv.surjective protected lemma injective (e : P₁ ≃ᵃ[k] P₂) : injective e := e.to_equiv.injective @[simp] lemma range_eq (e : P₁ ≃ᵃ[k] P₂) : range e = univ := e.surjective.range_eq @[simp] lemma apply_symm_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₂) : e (e.symm p) = p := e.to_equiv.apply_symm_apply p @[simp] lemma symm_apply_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₁) : e.symm (e p) = p := e.to_equiv.symm_apply_apply p lemma apply_eq_iff_eq_symm_apply (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂} : e p₁ = p₂ ↔ p₁ = e.symm p₂ := e.to_equiv.apply_eq_iff_eq_symm_apply @[simp] lemma apply_eq_iff_eq (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂ : P₁} : e p₁ = e p₂ ↔ p₁ = p₂ := e.to_equiv.apply_eq_iff_eq omit V₂ @[simp] lemma symm_refl : (refl k P₁).symm = refl k P₁ := rfl include V₂ V₃ /-- Composition of two `affine_equiv`alences, applied left to right. -/ @[trans] def trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : P₁ ≃ᵃ[k] P₃ := { to_equiv := e.to_equiv.trans e'.to_equiv, linear := e.linear.trans e'.linear, map_vadd' := λ p v, by simp only [linear_equiv.trans_apply, coe_to_equiv, (∘), equiv.coe_trans, map_vadd] } @[simp] lemma coe_trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : ⇑(e.trans e') = e' ∘ e := rfl lemma trans_apply (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) (p : P₁) : e.trans e' p = e' (e p) := rfl include V₄ lemma trans_assoc (e₁ : P₁ ≃ᵃ[k] P₂) (e₂ : P₂ ≃ᵃ[k] P₃) (e₃ : P₃ ≃ᵃ[k] P₄) : (e₁.trans e₂).trans e₃ = e₁.trans (e₂.trans e₃) := ext $ λ _, rfl omit V₃ V₄ @[simp] lemma trans_refl (e : P₁ ≃ᵃ[k] P₂) : e.trans (refl k P₂) = e := ext $ λ _, rfl @[simp] lemma refl_trans (e : P₁ ≃ᵃ[k] P₂) : (refl k P₁).trans e = e := ext $ λ _, rfl @[simp] lemma trans_symm (e : P₁ ≃ᵃ[k] P₂) : e.trans e.symm = refl k P₁ := ext e.symm_apply_apply @[simp] lemma symm_trans (e : P₁ ≃ᵃ[k] P₂) : e.symm.trans e = refl k P₂ := ext e.apply_symm_apply @[simp] lemma apply_line_map (e : P₁ ≃ᵃ[k] P₂) (a b : P₁) (c : k) : e (affine_map.line_map a b c) = affine_map.line_map (e a) (e b) c := e.to_affine_map.apply_line_map a b c omit V₂ instance : group (P₁ ≃ᵃ[k] P₁) := { one := refl k P₁, mul := λ e e', e'.trans e, inv := symm, mul_assoc := λ e₁ e₂ e₃, trans_assoc _ _ _, one_mul := trans_refl, mul_one := refl_trans, mul_left_inv := trans_symm } lemma one_def : (1 : P₁ ≃ᵃ[k] P₁) = refl k P₁ := rfl @[simp] lemma coe_one : ⇑(1 : P₁ ≃ᵃ[k] P₁) = id := rfl lemma mul_def (e e' : P₁ ≃ᵃ[k] P₁) : e * e' = e'.trans e := rfl @[simp] lemma coe_mul (e e' : P₁ ≃ᵃ[k] P₁) : ⇑(e * e') = e ∘ e' := rfl lemma inv_def (e : P₁ ≃ᵃ[k] P₁) : e⁻¹ = e.symm := rfl variable (k) /-- The map `v ↦ v +ᵥ b` as an affine equivalence between a module `V` and an affine space `P` with tangent space `V`. -/ def vadd_const (b : P₁) : V₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.vadd_const b, linear := linear_equiv.refl _ _, map_vadd' := λ p v, add_vadd _ _ _ } @[simp] lemma linear_vadd_const (b : P₁) : (vadd_const k b).linear = linear_equiv.refl k V₁ := rfl @[simp] lemma vadd_const_apply (b : P₁) (v : V₁) : vadd_const k b v = v +ᵥ b := rfl @[simp] lemma vadd_const_symm_apply (b p : P₁) : (vadd_const k b).symm p = p -ᵥ b := rfl /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P₁) : P₁ ≃ᵃ[k] V₁ := { to_equiv := equiv.const_vsub p, linear := linear_equiv.neg k, map_vadd' := λ p' v, by simp [vsub_vadd_eq_vsub_sub, neg_add_eq_sub] } @[simp] lemma coe_const_vsub (p : P₁) : ⇑(const_vsub k p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P₁) : ⇑(const_vsub k p).symm = λ v, -v +ᵥ p := rfl variable (P₁) /-- The map `p ↦ v +ᵥ p` as an affine automorphism of an affine space. -/ def const_vadd (v : V₁) : P₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.const_vadd P₁ v, linear := linear_equiv.refl _ _, map_vadd' := λ p w, vadd_comm _ _ _ } @[simp] lemma linear_const_vadd (v : V₁) : (const_vadd k P₁ v).linear = linear_equiv.refl _ _ := rfl @[simp] lemma const_vadd_apply (v : V₁) (p : P₁) : const_vadd k P₁ v p = v +ᵥ p := rfl @[simp] lemma const_vadd_symm_apply (v : V₁) (p : P₁) : (const_vadd k P₁ v).symm p = -v +ᵥ p := rfl variable {P₁} open function /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : P₁) : P₁ ≃ᵃ[k] P₁ := (const_vsub k x).trans (vadd_const k x) lemma point_reflection_apply (x y : P₁) : point_reflection k x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_symm (x : P₁) : (point_reflection k x).symm = point_reflection k x := to_equiv_injective $ equiv.point_reflection_symm x @[simp] lemma to_equiv_point_reflection (x : P₁) : (point_reflection k x).to_equiv = equiv.point_reflection x := rfl @[simp] lemma point_reflection_self (x : P₁) : point_reflection k x x = x := vsub_vadd _ _ lemma point_reflection_involutive (x : P₁) : involutive (point_reflection k x : P₁ → P₁) := equiv.point_reflection_involutive x /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_injective_bit0 {x y : P₁} (h : injective (bit0 : V₁ → V₁)) : point_reflection k x y = y ↔ y = x := equiv.point_reflection_fixed_iff_of_injective_bit0 h lemma injective_point_reflection_left_of_injective_bit0 (h : injective (bit0 : V₁ → V₁)) (y : P₁) : injective (λ x : P₁, point_reflection k x y) := equiv.injective_point_reflection_left_of_injective_bit0 h y lemma injective_point_reflection_left_of_module [invertible (2:k)]: ∀ y, injective (λ x : P₁, point_reflection k x y) := injective_point_reflection_left_of_injective_bit0 k $ λ x y h, by rwa [bit0, bit0, ← two_smul k x, ← two_smul k y, (is_unit_of_invertible (2:k)).smul_left_cancel] at h lemma point_reflection_fixed_iff_of_module [invertible (2:k)] {x y : P₁} : point_reflection k x y = y ↔ y = x := ((injective_point_reflection_left_of_module k y).eq_iff' (point_reflection_self k y)).trans eq_comm end affine_equiv namespace affine_map open affine_equiv include V₁ lemma line_map_vadd (v v' : V₁) (p : P₁) (c : k) : line_map v v' c +ᵥ p = line_map (v +ᵥ p) (v' +ᵥ p) c := (vadd_const k p).apply_line_map v v' c lemma line_map_vsub (p₁ p₂ p₃ : P₁) (c : k) : line_map p₁ p₂ c -ᵥ p₃ = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₃) c := (vadd_const k p₃).symm.apply_line_map p₁ p₂ c lemma vsub_line_map (p₁ p₂ p₃ : P₁) (c : k) : p₁ -ᵥ line_map p₂ p₃ c = line_map (p₁ -ᵥ p₂) (p₁ -ᵥ p₃) c := (const_vsub k p₁).apply_line_map p₂ p₃ c lemma vadd_line_map (v : V₁) (p₁ p₂ : P₁) (c : k) : v +ᵥ line_map p₁ p₂ c = line_map (v +ᵥ p₁) (v +ᵥ p₂) c := (const_vadd k P₁ v).apply_line_map p₁ p₂ c variables {R' : Type*} [comm_ring R'] [module R' V₁] lemma homothety_neg_one_apply (c p : P₁) : homothety c (-1:R') p = point_reflection R' c p := by simp [homothety_apply, point_reflection_apply] end affine_map
1954106705381ea126f88d332f07bdf1b6ea0c29
2cf781335f4a6706b7452ab07ce323201e2e101f
/lean/deps/galois_stdlib/src/galois/data/fin.lean
317a807603dd5ff1ca7df11e72f1e61fb441807a
[ "Apache-2.0" ]
permissive
simonjwinwood/reopt-vcg
697cdd5e68366b5aa3298845eebc34fc97ccfbe2
6aca24e759bff4f2230bb58270bac6746c13665e
refs/heads/master
1,586,353,878,347
1,549,667,148,000
1,549,667,148,000
159,409,828
0
0
null
1,543,358,444,000
1,543,358,444,000
null
UTF-8
Lean
false
false
1,767
lean
namespace fin section parameter (n:ℕ) parameter (P:fin n → Prop) parameter [dp:decidable_pred P] def extend_lt {i j} : fin i → i < j → fin j | x i_le_j := ⟨x.val, nat.lt_trans x.is_lt i_le_j⟩ def extend {i j} : fin i → i ≤ j → fin j | x i_le_j := ⟨x.val, nat.lt_of_lt_of_le x.is_lt i_le_j⟩ def decidable_forall.partial : ∀(i:ℕ) (h:i ≤ n), decidable (Π(j:fin i), P (extend j h)) | 0 h := decidable.is_true begin intros j, have f := nat.not_lt_zero j.val j.is_lt, contradiction, end | (nat.succ i) h := match dp ⟨i, h⟩ with | (decidable.is_false i_false) := decidable.is_false begin by_contradiction assumption, apply i_false, exact (assumption ⟨i, nat.lt.base i⟩), end | (decidable.is_true i_ok) := match decidable_forall.partial i (nat.le_of_succ_le h) with | (decidable.is_false rec_false) := decidable.is_false begin by_contradiction assumption, apply rec_false, intro j, exact assumption ⟨j.val, nat.lt_succ_of_lt j.is_lt⟩ end | (decidable.is_true rec_ok) := decidable.is_true begin simp [extend] at rec_ok, simp [extend], intro j, cases j, -- Split on value of j induced by proof j < i+1 cases j_is_lt, { exact i_ok, }, { exact rec_ok ⟨j_val, j_is_lt_a⟩, }, end end end /-- This proves that quantification over fin is decidable. -/ instance decidable_forall : decidable (Π(j:fin n), P j) := decidable_of_decidable_of_eq (decidable_forall.partial n (nat.le_refl n)) begin apply propext, apply forall_congr, intro j, apply eq.to_iff, apply congr_arg, cases j, simp [extend], end end end fin
aa6e54d386c77d292f4d321e6b9ed6f0f27b1829
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/integral/mean_inequalities.lean
ed7518c25ad77542fee774e59193e515c18cbcb3
[ "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,799
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.integral.lebesgue import analysis.mean_inequalities import analysis.mean_inequalities_pow import measure_theory.function.special_functions /-! # Mean value inequalities for integrals In this file we prove several inequalities on integrals, notably the Hölder inequality and the Minkowski inequality. The versions for finite sums are in `analysis.mean_inequalities`. ## Main results Hölder's inequality for the Lebesgue integral of `ℝ≥0∞` and `ℝ≥0` functions: we prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents and `α→(e)nnreal` functions in two cases, * `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions, * `nnreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0 functions. Minkowski's inequality for the Lebesgue integral of measurable functions with `ℝ≥0∞` values: we prove `(∫ (f + g)^p ∂μ) ^ (1/p) ≤ (∫ f^p ∂μ) ^ (1/p) + (∫ g^p ∂μ) ^ (1/p)` for `1 ≤ p`. -/ section lintegral /-! ### Hölder's inequality for the Lebesgue integral of ℝ≥0∞ and nnreal functions We prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents and `α→(e)nnreal` functions in several cases, the first two being useful only to prove the more general results: * `ennreal.lintegral_mul_le_one_of_lintegral_rpow_eq_one` : ℝ≥0∞ functions for which the integrals on the right are equal to 1, * `ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top` : ℝ≥0∞ functions for which the integrals on the right are neither ⊤ nor 0, * `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions, * `nnreal.lintegral_mul_le_Lp_mul_Lq` : nnreal functions. -/ noncomputable theory open_locale classical big_operators nnreal ennreal open measure_theory variables {α : Type*} [measurable_space α] {μ : measure α} namespace ennreal lemma lintegral_mul_le_one_of_lintegral_rpow_eq_one {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_norm : ∫⁻ a, (f a)^p ∂μ = 1) (hg_norm : ∫⁻ a, (g a)^q ∂μ = 1) : ∫⁻ a, (f * g) a ∂μ ≤ 1 := begin calc ∫⁻ (a : α), ((f * g) a) ∂μ ≤ ∫⁻ (a : α), ((f a)^p / ennreal.of_real p + (g a)^q / ennreal.of_real q) ∂μ : lintegral_mono (λ a, young_inequality (f a) (g a) hpq) ... = 1 : begin simp only [div_eq_mul_inv], rw lintegral_add', { rw [lintegral_mul_const'' _ (hf.pow_const p), lintegral_mul_const'' _ (hg.pow_const q), hf_norm, hg_norm, ← div_eq_mul_inv, ← div_eq_mul_inv, hpq.inv_add_inv_conj_ennreal], }, { exact (hf.pow_const _).mul_const _, }, { exact (hg.pow_const _).mul_const _, }, end end /-- Function multiplied by the inverse of its p-seminorm `(∫⁻ f^p ∂μ) ^ 1/p`-/ def fun_mul_inv_snorm (f : α → ℝ≥0∞) (p : ℝ) (μ : measure α) : α → ℝ≥0∞ := λ a, (f a) * ((∫⁻ c, (f c) ^ p ∂μ) ^ (1 / p))⁻¹ lemma fun_eq_fun_mul_inv_snorm_mul_snorm {p : ℝ} (f : α → ℝ≥0∞) (hf_nonzero : ∫⁻ a, (f a) ^ p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) {a : α} : f a = (fun_mul_inv_snorm f p μ a) * (∫⁻ c, (f c)^p ∂μ)^(1/p) := by simp [fun_mul_inv_snorm, mul_assoc, inv_mul_cancel, hf_nonzero, hf_top] lemma fun_mul_inv_snorm_rpow {p : ℝ} (hp0 : 0 < p) {f : α → ℝ≥0∞} {a : α} : (fun_mul_inv_snorm f p μ a) ^ p = (f a)^p * (∫⁻ c, (f c) ^ p ∂μ)⁻¹ := begin rw [fun_mul_inv_snorm, mul_rpow_of_nonneg _ _ (le_of_lt hp0)], suffices h_inv_rpow : ((∫⁻ (c : α), f c ^ p ∂μ) ^ (1 / p))⁻¹ ^ p = (∫⁻ (c : α), f c ^ p ∂μ)⁻¹, by rw h_inv_rpow, rw [inv_rpow, ← rpow_mul, one_div_mul_cancel hp0.ne', rpow_one] end lemma lintegral_rpow_fun_mul_inv_snorm_eq_one {p : ℝ} (hp0_lt : 0 < p) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) : ∫⁻ c, (fun_mul_inv_snorm f p μ c)^p ∂μ = 1 := begin simp_rw fun_mul_inv_snorm_rpow hp0_lt, rw [lintegral_mul_const'' _ (hf.pow_const p), mul_inv_cancel hf_nonzero hf_top], end /-- Hölder's inequality in case of finite non-zero integrals -/ lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_nontop : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) (hg_nontop : ∫⁻ a, (g a)^q ∂μ ≠ ⊤) (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) := begin let npf := (∫⁻ (c : α), (f c) ^ p ∂μ) ^ (1/p), let nqg := (∫⁻ (c : α), (g c) ^ q ∂μ) ^ (1/q), calc ∫⁻ (a : α), (f * g) a ∂μ = ∫⁻ (a : α), ((fun_mul_inv_snorm f p μ * fun_mul_inv_snorm g q μ) a) * (npf * nqg) ∂μ : begin refine lintegral_congr (λ a, _), rw [pi.mul_apply, fun_eq_fun_mul_inv_snorm_mul_snorm f hf_nonzero hf_nontop, fun_eq_fun_mul_inv_snorm_mul_snorm g hg_nonzero hg_nontop, pi.mul_apply], ring, end ... ≤ npf * nqg : begin rw lintegral_mul_const' (npf * nqg) _ (by simp [hf_nontop, hg_nontop, hf_nonzero, hg_nonzero]), nth_rewrite 1 ←one_mul (npf * nqg), refine mul_le_mul _ (le_refl (npf * nqg)), have hf1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.pos hf hf_nonzero hf_nontop, have hg1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.symm.pos hg hg_nonzero hg_nontop, exact lintegral_mul_le_one_of_lintegral_rpow_eq_one hpq (hf.mul_const _) (hg.mul_const _) hf1 hg1, end end lemma ae_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0_lt : 0 < p) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) : f =ᵐ[μ] 0 := begin rw lintegral_eq_zero_iff' (hf.pow_const p) at hf_zero, refine filter.eventually.mp hf_zero (filter.eventually_of_forall (λ x, _)), dsimp only, rw [pi.zero_apply, rpow_eq_zero_iff], intro hx, cases hx, { exact hx.left, }, { exfalso, linarith, }, end lemma lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0_lt : 0 < p) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) : ∫⁻ a, (f * g) a ∂μ = 0 := begin rw ←@lintegral_zero_fun α _ μ, refine lintegral_congr_ae _, suffices h_mul_zero : f * g =ᵐ[μ] 0 * g , by rwa zero_mul at h_mul_zero, have hf_eq_zero : f =ᵐ[μ] 0, from ae_eq_zero_of_lintegral_rpow_eq_zero hp0_lt hf hf_zero, exact filter.eventually_eq.mul hf_eq_zero (ae_eq_refl g), end lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top {p q : ℝ} (hp0_lt : 0 < p) (hq0 : 0 ≤ q) {f g : α → ℝ≥0∞} (hf_top : ∫⁻ a, (f a)^p ∂μ = ⊤) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) := begin refine le_trans le_top (le_of_eq _), have hp0_inv_lt : 0 < 1/p, by simp [hp0_lt], rw [hf_top, ennreal.top_rpow_of_pos hp0_inv_lt], simp [hq0, hg_nonzero], end /-- Hölder's inequality for functions `α → ℝ≥0∞`. The integral of the product of two functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem lintegral_mul_le_Lp_mul_Lq (μ : measure α) {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) := begin by_cases hf_zero : ∫⁻ a, (f a) ^ p ∂μ = 0, { refine le_trans (le_of_eq _) (zero_le _), exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.pos hf hf_zero, }, by_cases hg_zero : ∫⁻ a, (g a) ^ q ∂μ = 0, { refine le_trans (le_of_eq _) (zero_le _), rw mul_comm, exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.symm.pos hg hg_zero, }, by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤, { exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.pos hpq.symm.nonneg hf_top hg_zero, }, by_cases hg_top : ∫⁻ a, (g a) ^ q ∂μ = ⊤, { rw [mul_comm, mul_comm ((∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p))], exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.symm.pos hpq.nonneg hg_top hf_zero, }, -- non-⊤ non-zero case exact ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top hpq hf hg hf_top hg_top hf_zero hg_zero, end lemma lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top {p : ℝ} {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ < ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ < ⊤) (hp1 : 1 ≤ p) : ∫⁻ a, ((f + g) a) ^ p ∂μ < ⊤ := begin have hp0_lt : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, calc ∫⁻ (a : α), (f a + g a) ^ p ∂μ ≤ ∫⁻ a, ((2:ℝ≥0∞)^(p-1) * (f a) ^ p + (2:ℝ≥0∞)^(p-1) * (g a) ^ p) ∂ μ : begin refine lintegral_mono (λ a, _), dsimp only, have h_zero_lt_half_rpow : (0 : ℝ≥0∞) < (1 / 2) ^ p, { rw [←ennreal.zero_rpow_of_pos hp0_lt], exact ennreal.rpow_lt_rpow (by simp [zero_lt_one]) hp0_lt, }, have h_rw : (1 / 2) ^ p * (2:ℝ≥0∞) ^ (p - 1) = 1 / 2, { rw [sub_eq_add_neg, ennreal.rpow_add _ _ ennreal.two_ne_zero ennreal.coe_ne_top, ←mul_assoc, ←ennreal.mul_rpow_of_nonneg _ _ hp0, one_div, ennreal.inv_mul_cancel ennreal.two_ne_zero ennreal.coe_ne_top, ennreal.one_rpow, one_mul, ennreal.rpow_neg_one], }, rw ←ennreal.mul_le_mul_left (ne_of_lt h_zero_lt_half_rpow).symm _, { rw [mul_add, ← mul_assoc, ← mul_assoc, h_rw, ←ennreal.mul_rpow_of_nonneg _ _ hp0, mul_add], refine ennreal.rpow_arith_mean_le_arith_mean2_rpow (1/2 : ℝ≥0∞) (1/2 : ℝ≥0∞) (f a) (g a) _ hp1, rw [ennreal.div_add_div_same, one_add_one_eq_two, ennreal.div_self ennreal.two_ne_zero ennreal.coe_ne_top], }, { rw ← lt_top_iff_ne_top, refine ennreal.rpow_lt_top_of_nonneg hp0 _, rw [one_div, ennreal.inv_ne_top], exact ennreal.two_ne_zero, }, end ... < ⊤ : begin rw [lintegral_add', lintegral_const_mul'' _ (hf.pow_const p), lintegral_const_mul'' _ (hg.pow_const p), ennreal.add_lt_top], { have h_two : (2 : ℝ≥0∞) ^ (p - 1) < ⊤, from ennreal.rpow_lt_top_of_nonneg (by simp [hp1]) ennreal.coe_ne_top, repeat {rw ennreal.mul_lt_top_iff}, simp [hf_top, hg_top, h_two], }, { exact (hf.pow_const _).const_mul _ }, { exact (hg.pow_const _).const_mul _ }, end end lemma lintegral_Lp_mul_le_Lq_mul_Lr {α} [measurable_space α] {p q r : ℝ} (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) (μ : measure α) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : (∫⁻ a, ((f * g) a)^p ∂μ) ^ (1/p) ≤ (∫⁻ a, (f a)^q ∂μ) ^ (1/q) * (∫⁻ a, (g a)^r ∂μ) ^ (1/r) := begin have hp0_ne : p ≠ 0, from (ne_of_lt hp0_lt).symm, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, have hq0_lt : 0 < q, from lt_of_le_of_lt hp0 hpq, have hq0_ne : q ≠ 0, from (ne_of_lt hq0_lt).symm, have h_one_div_r : 1/r = 1/p - 1/q, by simp [hpqr], have hr0_ne : r ≠ 0, { have hr_inv_pos : 0 < 1/r, by rwa [h_one_div_r, sub_pos, one_div_lt_one_div hq0_lt hp0_lt], rw [one_div, _root_.inv_pos] at hr_inv_pos, exact (ne_of_lt hr_inv_pos).symm, }, let p2 := q/p, let q2 := p2.conjugate_exponent, have hp2q2 : p2.is_conjugate_exponent q2, from real.is_conjugate_exponent_conjugate_exponent (by simp [lt_div_iff, hpq, hp0_lt]), calc (∫⁻ (a : α), ((f * g) a) ^ p ∂μ) ^ (1 / p) = (∫⁻ (a : α), (f a)^p * (g a)^p ∂μ) ^ (1 / p) : by simp_rw [pi.mul_apply, ennreal.mul_rpow_of_nonneg _ _ hp0] ... ≤ ((∫⁻ a, (f a)^(p * p2) ∂ μ)^(1/p2) * (∫⁻ a, (g a)^(p * q2) ∂ μ)^(1/q2)) ^ (1/p) : begin refine ennreal.rpow_le_rpow _ (by simp [hp0]), simp_rw ennreal.rpow_mul, exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hp2q2 (hf.pow_const _) (hg.pow_const _) end ... = (∫⁻ (a : α), (f a) ^ q ∂μ) ^ (1 / q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1 / r) : begin rw [@ennreal.mul_rpow_of_nonneg _ _ (1/p) (by simp [hp0]), ←ennreal.rpow_mul, ←ennreal.rpow_mul], have hpp2 : p * p2 = q, { symmetry, rw [mul_comm, ←div_eq_iff hp0_ne], }, have hpq2 : p * q2 = r, { rw [← inv_inv₀ r, ← one_div, ← one_div, h_one_div_r], field_simp [q2, real.conjugate_exponent, p2, hp0_ne, hq0_ne] }, simp_rw [div_mul_div, mul_one, mul_comm p2, mul_comm q2, hpp2, hpq2], end end lemma lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) : ∫⁻ a, (f a) * (g a) ^ (p - 1) ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^p ∂μ) ^ (1/q) := begin refine le_trans (ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf (hg.pow_const _)) _, by_cases hf_zero_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) = 0, { rw [hf_zero_rpow, zero_mul], exact zero_le _, }, have hf_top_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) ≠ ⊤, { by_contra h, refine hf_top _, have hp_not_neg : ¬ p < 0, by simp [hpq.nonneg], simpa [hpq.pos, hp_not_neg] using h, }, refine (ennreal.mul_le_mul_left hf_zero_rpow hf_top_rpow).mpr (le_of_eq _), congr, ext1 a, rw [←ennreal.rpow_mul, hpq.sub_one_mul_conj], end lemma lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) : ∫⁻ a, ((f + g) a)^p ∂ μ ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p)) * (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) := begin calc ∫⁻ a, ((f+g) a) ^ p ∂μ ≤ ∫⁻ a, ((f + g) a) * ((f + g) a) ^ (p - 1) ∂μ : begin refine lintegral_mono (λ a, _), dsimp only, by_cases h_zero : (f + g) a = 0, { rw [h_zero, ennreal.zero_rpow_of_pos hpq.pos], exact zero_le _, }, by_cases h_top : (f + g) a = ⊤, { rw [h_top, ennreal.top_rpow_of_pos hpq.sub_one_pos, ennreal.top_mul_top], exact le_top, }, refine le_of_eq _, nth_rewrite 1 ←ennreal.rpow_one ((f + g) a), rw [←ennreal.rpow_add _ _ h_zero h_top, add_sub_cancel'_right], end ... = ∫⁻ (a : α), f a * (f + g) a ^ (p - 1) ∂μ + ∫⁻ (a : α), g a * (f + g) a ^ (p - 1) ∂μ : begin have h_add_m : ae_measurable (λ (a : α), ((f + g) a) ^ (p-1)) μ, from (hf.add hg).pow_const _, have h_add_apply : ∫⁻ (a : α), (f + g) a * (f + g) a ^ (p - 1) ∂μ = ∫⁻ (a : α), (f a + g a) * (f + g) a ^ (p - 1) ∂μ, from rfl, simp_rw [h_add_apply, add_mul], rw lintegral_add' (hf.mul h_add_m) (hg.mul h_add_m), end ... ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p)) * (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) : begin rw add_mul, exact add_le_add (lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hf (hf.add hg) hf_top) (lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hg (hf.add hg) hg_top), end end private lemma lintegral_Lp_add_le_aux {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) (h_add_zero : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ 0) (h_add_top : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤) : (∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) := begin have hp_not_nonpos : ¬ p ≤ 0, by simp [hpq.pos], have htop_rpow : (∫⁻ a, ((f+g) a) ^ p ∂μ)^(1/p) ≠ ⊤, { by_contra h, exact h_add_top (@ennreal.rpow_eq_top_of_nonneg _ (1/p) (by simp [hpq.nonneg]) h), }, have h0_rpow : (∫⁻ a, ((f+g) a) ^ p ∂ μ) ^ (1/p) ≠ 0, by simp [h_add_zero, h_add_top, hpq.nonneg, hp_not_nonpos, -pi.add_apply], suffices h : 1 ≤ (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ -(1/p) * ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)), by rwa [←mul_le_mul_left h0_rpow htop_rpow, ←mul_assoc, ←rpow_add _ _ h_add_zero h_add_top, ←sub_eq_add_neg, _root_.sub_self, rpow_zero, one_mul, mul_one] at h, have h : ∫⁻ (a : α), ((f+g) a)^p ∂μ ≤ ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)) * (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ (1/q), from lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add hpq hf hf_top hg hg_top, have h_one_div_q : 1/q = 1 - 1/p, by { nth_rewrite 1 ←hpq.inv_add_inv_conj, ring, }, simp_rw [h_one_div_q, sub_eq_add_neg 1 (1/p), ennreal.rpow_add _ _ h_add_zero h_add_top, rpow_one] at h, nth_rewrite 1 mul_comm at h, nth_rewrite 0 ←one_mul (∫⁻ (a : α), ((f+g) a) ^ p ∂μ) at h, rwa [←mul_assoc, ennreal.mul_le_mul_right h_add_zero h_add_top, mul_comm] at h, end /-- Minkowski's inequality for functions `α → ℝ≥0∞`: the `ℒp` seminorm of the sum of two functions is bounded by the sum of their `ℒp` seminorms. -/ theorem lintegral_Lp_add_le {p : ℝ} {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : (∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) := begin have hp_pos : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤, { simp [hf_top, hp_pos], }, by_cases hg_top : ∫⁻ a, (g a) ^ p ∂μ = ⊤, { simp [hg_top, hp_pos], }, by_cases h1 : p = 1, { refine le_of_eq _, simp_rw [h1, one_div_one, ennreal.rpow_one], exact lintegral_add' hf hg, }, have hp1_lt : 1 < p, by { refine lt_of_le_of_ne hp1 _, symmetry, exact h1, }, have hpq := real.is_conjugate_exponent_conjugate_exponent hp1_lt, by_cases h0 : ∫⁻ a, ((f+g) a) ^ p ∂ μ = 0, { rw [h0, @ennreal.zero_rpow_of_pos (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1])], exact zero_le _, }, have htop : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤, { rw ← ne.def at hf_top hg_top, rw ← lt_top_iff_ne_top at hf_top hg_top ⊢, exact lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top hf hf_top hg hg_top hp1, }, exact lintegral_Lp_add_le_aux hpq hf hf_top hg hg_top h0 htop, end end ennreal /-- Hölder's inequality for functions `α → ℝ≥0`. The integral of the product of two functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem nnreal.lintegral_mul_le_Lp_mul_Lq {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) := begin simp_rw [pi.mul_apply, ennreal.coe_mul], exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf.coe_nnreal_ennreal hg.coe_nnreal_ennreal, end end lintegral
c145784fec4deac6c254823f401661b3fa99c1e7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/doNotation2.lean
4989812923f0beb360a3bffca4154a90a1a6fb2a
[ "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
4,128
lean
def f (x : Nat) : IO Nat := do IO.println "hello world" let aux (y : Nat) (z : Nat) : IO Nat := do IO.println "aux started" IO.println s!"y: {y}, z: {z}" pure (x+y) discard <| aux x (x + 1) -- It is part of the application since it is indented discard <| aux x (x -- parentheses use `withoutPosition` -1) discard <| aux x x; aux x x #eval f 10 def g (xs : List Nat) : StateT Nat Id Nat := do let mut xs := xs if xs.isEmpty then xs := [← get] dbg_trace ">>> xs: {xs}" return xs.length #eval g [1, 2, 3] |>.run' 10 #eval g [] |>.run' 10 theorem ex1 : (g [1, 2, 4, 5] |>.run' 0) = 4 := rfl theorem ex2 : (g [] |>.run' 0) = 1 := rfl def h (x : Nat) (y : Nat) : Nat := Id.run <| do let mut x := x let mut y := y if x > 0 then let y' := x + 1 x := y' else y := y + 1 return x + y theorem ex3 (y : Nat) : h 0 y = 0 + (y + 1) := rfl theorem ex4 (y : Nat) : h 1 y = (1 + 1) + y := rfl def sumOdd (xs : List Nat) (threshold : Nat) : Nat := Id.run <| do let mut sum := 0 for x in xs do if x % 2 == 1 then sum := sum + x if sum > threshold then break unless x % 2 == 1 do continue dbg_trace ">> x: {x}" return sum #eval sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10 theorem ex5 : sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10 = 16 := rfl -- We need `Id.run` because we still have `Monad Option` def find? (xs : List Nat) (p : Nat → Bool) : Option Nat := Id.run do let mut result := none for x in xs do if p x then result := x break return result def sumDiff (ps : List (Nat × Nat)) : Nat := Id.run do let mut sum := 0 for (x, y) in ps do sum := sum + x - y return sum theorem ex7 : sumDiff [(2, 1), (10, 5)] = 6 := rfl def f1 (x : Nat) : IO Unit := do let rec loop : Nat → IO Unit | 0 => pure () | x+1 => do IO.println x; loop x loop x #eval f1 10 partial def f2 (x : Nat) : IO Unit := do let rec isEven : Nat → Bool | 0 => true | x+1 => isOdd x, isOdd : Nat → Bool | 0 => false | x+1 => isEven x IO.println ("isOdd(" ++ toString x ++ "): " ++ toString (isOdd x)) #eval f2 11 #eval f2 10 def split (xs : List Nat) : List Nat × List Nat := Id.run do let mut evens := [] let mut odds := [] for x in xs.reverse do if x % 2 == 0 then evens := x :: evens else odds := x :: odds return (evens, odds) theorem ex8 : split [1, 2, 3, 4] = ([2, 4], [1, 3]) := rfl def f3 (x : Nat) : IO Bool := do let y ← cond (x == 0) (do IO.println "hello"; pure true) (pure false); pure !y def f4 (x y : Nat) : Nat × Nat := Id.run <| do let mut (x, y) := (x, y) match x with | 0 => y := y + 1 | _ => x := x + y return (x, y) #eval f4 0 10 #eval f4 5 10 theorem ex9 (y : Nat) : f4 0 y = (0, y+1) := rfl theorem ex10 (x y : Nat) : f4 (x+1) y = ((x+1)+y, y) := rfl def f5 (x y : Nat) : Nat × Nat := Id.run <| do let mut (x, y) := (x, y) match x with | 0 => y := y + 1 | z+1 => dbg_trace "z: {z}"; x := x + y return (x, y) #eval f5 5 6 theorem ex11 (x y : Nat) : f5 (x+1) y = ((x+1)+y, y) := rfl def f6 (x : Nat) : Nat := Id.run <| do let mut x := x if x > 10 then return 0 x := x + 1 return x theorem ex12 : f6 11 = 0 := rfl theorem ex13 : f6 5 = 6 := rfl def findOdd (xs : List Nat) : Nat := Id.run <| do for x in xs do if x % 2 == 1 then return x return 0 theorem ex14 : findOdd [2, 4, 5, 8, 7] = 5 := rfl theorem ex15 : findOdd [2, 4, 8, 10] = 0 := rfl def f7 (ref : IO.Ref (Option (Nat × Nat))) : IO Nat := do let some (x, y) ← ref.get | pure 100 IO.println (toString x ++ ", " ++ toString y) return x+y def f7Test : IO Unit := do unless (← f7 (← IO.mkRef (some (10, 20)))) == 30 do throw $ IO.userError "unexpected" unless (← f7 (← IO.mkRef none)) == 100 do throw $ IO.userError "unexpected" #eval f7Test def f8 (x : Nat) : IO Nat := do let y ← if x == 0 then IO.println "x is zero" return 100 -- returns from the `do`-block else pure (x + 1) IO.println ("y: " ++ toString y) return y def f8Test : IO Unit := do unless (← f8 0) == 100 do throw $ IO.userError "unexpected" unless (← f8 1) == 2 do throw $ IO.userError "unexpected" #eval f8Test
d9c932d4f0830397a1c042088fc7a2a867f06c24
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/FinVect/limits.lean
b32cdaf9da322e569d972432fdb019da8b7adf48
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,862
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.FinVect import algebra.category.Module.limits import algebra.category.Module.products import algebra.category.Module.epi_mono import category_theory.limits.creates import category_theory.limits.shapes.finite_limits import category_theory.limits.constructions.limits_of_products_and_equalizers /-! # `forget₂ (FinVect K) (Module K)` creates all finite limits. And hence `FinVect K` has all finite limits. ## Future work After generalising `FinVect` to allow the ring and the module to live in different universes, generalize this construction so we can take limits over smaller diagrams, as is done for the other algebraic categories. -/ noncomputable theory universes v u open category_theory open category_theory.limits namespace FinVect variables {J : Type v} [small_category J] [fin_category J] variables {k : Type v} [field k] instance {J : Type v} [fintype J] (Z : J → Module.{v} k) [∀ j, finite_dimensional k (Z j)] : finite_dimensional k (∏ λ j, Z j : Module.{v} k) := begin haveI : finite_dimensional k (Module.of k (Π j, Z j)), { dsimp, apply_instance, }, exact finite_dimensional.of_injective (Module.pi_iso_pi.{v v v} _).hom ((Module.mono_iff_injective _).1 (by apply_instance)), end /-- Finite limits of finite finite dimensional vectors spaces are finite dimensional, because we can realise them as subobjects of a finite product. -/ instance (F : J ⥤ FinVect k) : finite_dimensional k (limit (F ⋙ forget₂ (FinVect k) (Module.{v} k)) : Module.{v} k) := begin haveI : ∀ j, finite_dimensional k ((F ⋙ forget₂ (FinVect k) (Module.{v} k)).obj j), { intro j, change finite_dimensional k (F.obj j), apply_instance, }, exact finite_dimensional.of_injective (limit_subobject_product (F ⋙ forget₂ (FinVect k) (Module.{v} k))) ((Module.mono_iff_injective _).1 (by apply_instance)), end /-- The forgetful functor from `FinVect k` to `Module k` creates all finite limits. -/ def forget₂_creates_limit (F : J ⥤ FinVect k) : creates_limit F (forget₂ (FinVect k) (Module.{v} k)) := creates_limit_of_fully_faithful_of_iso ⟨(limit (F ⋙ forget₂ (FinVect k) (Module.{v} k)) : Module.{v} k), by apply_instance⟩ (iso.refl _) instance : creates_limits_of_shape J (forget₂ (FinVect k) (Module.{v} k)) := { creates_limit := λ F, forget₂_creates_limit F, } instance : has_finite_limits (FinVect k) := { out := λ J _ _, by exactI has_limits_of_shape_of_has_limits_of_shape_creates_limits_of_shape (forget₂ (FinVect k) (Module.{v} k)), } instance : preserves_finite_limits (forget₂ (FinVect k) (Module.{v} k)) := { preserves_finite_limits := λ J _ _, by exactI infer_instance, } end FinVect
24ba74eafba315d96106b8ded5973a99797ffa8d
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/ring/boolean_ring.lean
dabfc1b598cdc8e650700a9bd60c85ca2973d458
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,213
lean
/- Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bryan Gin-ge Chen -/ import tactic.ring import tactic.abel /-! # Boolean rings A Boolean ring is a ring where multiplication is idempotent. They are equivalent to Boolean algebras. ## Main declarations * `boolean_ring`: a typeclass for rings where multiplication is idempotent. * `boolean_ring.to_boolean_algebra`: every Boolean ring is a Boolean algebra; this definition and the `sup` and `inf` notations for `boolean_ring` are localized as instances in the `boolean_algebra_of_boolean_ring` locale. ## Tags boolean ring, boolean algebra -/ /-- A Boolean ring is a ring where multiplication is idempotent. -/ class boolean_ring α extends ring α := (mul_self : ∀ a : α, a * a = a) section boolean_ring variables {α : Type*} [boolean_ring α] (a b : α) instance : is_idempotent α (*) := ⟨boolean_ring.mul_self⟩ @[simp] lemma mul_self : a * a = a := boolean_ring.mul_self _ @[simp] lemma add_self : a + a = 0 := have a + a = a + a + (a + a) := calc a + a = (a+a) * (a+a) : by rw mul_self ... = a*a + a*a + (a*a + a*a) : by rw [add_mul, mul_add] ... = a + a + (a + a) : by rw mul_self, by rwa self_eq_add_left at this @[simp] lemma neg_eq : -a = a := calc -a = -a + 0 : by rw add_zero ... = -a + -a + a : by rw [←neg_add_self, add_assoc] ... = a : by rw [add_self, zero_add] lemma add_eq_zero : a + b = 0 ↔ a = b := calc a + b = 0 ↔ a = -b : add_eq_zero_iff_eq_neg ... ↔ a = b : by rw neg_eq lemma mul_add_mul : a*b + b*a = 0 := have a + b = a + b + (a*b + b*a) := calc a + b = (a + b) * (a + b) : by rw mul_self ... = a*a + a*b + (b*a + b*b) : by rw [add_mul, mul_add, mul_add] ... = a + a*b + (b*a + b) : by simp only [mul_self] ... = a + b + (a*b + b*a) : by abel, by rwa self_eq_add_right at this @[simp] lemma sub_eq_add : a - b = a + b := by rw [sub_eq_add_neg, add_right_inj, neg_eq] end boolean_ring namespace boolean_ring variables {α : Type*} [boolean_ring α] @[priority 100] -- Note [lower instance priority] instance : comm_ring α := { mul_comm := λ a b, by rw [←add_eq_zero, mul_add_mul], .. (infer_instance : boolean_ring α) } /-- The join operation in a Boolean ring is `x + y + x*y`. -/ def has_sup : has_sup α := ⟨λ x y, x + y + x*y⟩ /-- The meet operation in a Boolean ring is `x * y`. -/ def has_inf : has_inf α := ⟨(*)⟩ -- Note [lower instance priority] localized "attribute [instance, priority 100] boolean_ring.has_sup" in boolean_algebra_of_boolean_ring localized "attribute [instance, priority 100] boolean_ring.has_inf" in boolean_algebra_of_boolean_ring lemma sup_comm (a b : α) : a ⊔ b = b ⊔ a := by { dsimp only [(⊔)], ring } lemma inf_comm (a b : α) : a ⊓ b = b ⊓ a := by { dsimp only [(⊓)], ring } lemma sup_assoc (a b c : α) : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := by { dsimp only [(⊔)], ring } lemma inf_assoc (a b c : α) : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by { dsimp only [(⊓)], ring } lemma sup_inf_self (a b : α) : a ⊔ a ⊓ b = a := by { dsimp only [(⊔), (⊓)], assoc_rw [mul_self, add_self, add_zero] } lemma inf_sup_self (a b : α) : a ⊓ (a ⊔ b) = a := by { dsimp only [(⊔), (⊓)], assoc_rw [mul_add, mul_add, mul_self, mul_self, add_self, add_zero] } lemma le_sup_inf_aux (a b c : α) : (a + b + a * b) * (a + c + a * c) = a + b * c + a * (b * c) := calc (a + b + a * b) * (a + c + a * c) = a * a + b * c + a * (b * c) + (a * b + (a * a) * b) + (a * c + (a * a) * c) + (a * b * c + (a * a) * b * c) : by ring ... = a + b * c + a * (b * c) : by simp only [mul_self, add_self, add_zero] lemma le_sup_inf (a b c : α) : (a ⊔ b) ⊓ (a ⊔ c) ⊔ (a ⊔ b ⊓ c) = a ⊔ b ⊓ c := by { dsimp only [(⊔), (⊓)], rw [le_sup_inf_aux, add_self, mul_self, zero_add] } /-- The Boolean algebra structure on a Boolean ring. The data is defined so that: * `a ⊔ b` unfolds to `a + b + a * b` * `a ⊓ b` unfolds to `a * b` * `a ≤ b` unfolds to `a + b + a * b = b` * `⊥` unfolds to `0` * `⊤` unfolds to `1` * `aᶜ` unfolds to `1 + a` * `a \ b` unfolds to `a * (1 + a)` -/ def to_boolean_algebra : boolean_algebra α := { le_sup_inf := le_sup_inf, top := 1, le_top := λ a, show a + 1 + a * 1 = 1, by assoc_rw [mul_one, add_comm, add_self, add_zero], bot := 0, bot_le := λ a, show 0 + a + 0 * a = a, by rw [zero_mul, zero_add, add_zero], compl := λ a, 1 + a, sdiff := λ a b, a * (1 + b), inf_compl_le_bot := λ a, show a*(1+a) + 0 + a*(1+a)*0 = 0, by norm_num [mul_add, mul_self, add_self], top_le_sup_compl := λ a, begin change 1 + (a + (1+a) + a*(1+a)) + 1*(a + (1+a) + a*(1+a)) = a + (1+a) + a*(1+a), norm_num [mul_add, mul_self], rw [←add_assoc, add_self], end, sdiff_eq := λ a b, rfl, .. lattice.mk' sup_comm sup_assoc inf_comm inf_assoc sup_inf_self inf_sup_self } localized "attribute [instance, priority 100] boolean_ring.to_boolean_algebra" in boolean_algebra_of_boolean_ring end boolean_ring
4fb5a37b6c86f184c8dd37c0fae364b94077abbf
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/test-symbolic/Main.lean
41c4a41c40e5d2f89b2d52ae8134415282a73256
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
2,257
lean
-- import system.io import Galois.Init.Io -- FIXME!! this is from the simulator import Main.Translate import X86Semantics.SymbolicBackend import DecodeX86.DecodeX86 import SMTLIB.Syntax namespace x86 namespace symbolic def throwS {a : Type} {m : Type -> Type} [MonadIO m] (e : String) : m a := monadLift (throw (IO.userError e) : IO a) -- def evaluate_one (s : machine_state) : (Nat × sum unknown_byte instruction) -> except String machine_state -- | (n, sum.inl err) => throw "Got an unknown byte" -- | (n, sum.inr inst) := eval_instruction {s with ip => s.ip + bitvec.of_nat _ n} inst -- def lift_eval {α : Type *} | evaluator α) : io a -- def dump_state (s : system_state linux.x86_64.os_state) : IO Unit := do -- let line := s.ip.pp_hex ++ ": " ++ s.print_regs ++ " " ++ s.print_set_flags; -- IO.println line def bytesToByteArray (xs : List String) : ByteArray := let bs := List.map (fun x => UInt8.ofNat ((String.toNat? x).getD 0)) xs; bs.toByteArray def doit (bs : List String) : IO Unit := do let text_bytes := bytesToByteArray bs; let d := decodex86.mk_decoder text_bytes 0; let ((init_s, stdlib), (idGen', init_script)) := SMT.runsmtM SMT.IdGen.empty (do init_s <- machine_state.declare_const; stdlib <- StdLib.make; pure (init_s, stdlib)); IO.println "Prelude:"; _ <- init_script.mapM (fun c => IO.println (toString (toSExpr c))); IO.println "\nInstruction:"; let inst := decodex86.decode d 0; match inst with | (Sum.inl b) => throwS "Unknown byte" | (Sum.inr i) => do -- let s' := {s with ip := s.ip + bitvec.of_nat _ i.nbytes }; -- let os' := {os with current_ip := s.ip}; -- IO.println (repr i); let r := (eval_instruction (symbolicBackend stdlib) i).run { os_state.empty with idGen := idGen' } init_s; match r with | Except.ok ((_, s''), os'') => do _ <- os''.trace.reverse.mapM (fun (e : Event) => IO.println (repr e)); IO.println (machine_state.print_regs s''); pure () | Except.error e => throwS ("Eval failed: " ++ e) end symbolic end x86 def main (xs : List String) : IO UInt32 := do x86.symbolic.doit xs; pure 0
fcd8bed6212380d47556633291278abc724fcf16
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/solve_by_elim.lean
b51b2f5c7490c238be089763bf4f4afdb335c188
[ "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
15,187
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import tactic.core /-! # solve_by_elim A depth-first search backwards reasoner. `solve_by_elim` takes a list of lemmas, and repeating tries to `apply` these against the goals, recursively acting on any generated subgoals. It accepts a variety of configuration options described below, enabling * backtracking across multiple goals, * pruning the search tree, and * invoking other tactics before or after trying to apply lemmas. At present it has no "premise selection", and simply tries the supplied lemmas in order at each step of the search. -/ namespace tactic namespace solve_by_elim /-- `mk_assumption_set` builds a collection of lemmas for use in the backtracking search in `solve_by_elim`. * By default, it includes all local hypotheses, along with `rfl`, `trivial`, `congr_fun` and `congr_arg`. * The flag `no_dflt` removes these. * The argument `hs` is a list of `simp_arg_type`s, and can be used to add, or remove, lemmas or expressions from the set. * The argument `attr : list name` adds all lemmas tagged with one of a specified list of attributes. `mk_assumption_set` returns not a `list expr`, but a `list (tactic expr) × tactic (list expr)`. There are two separate problems that need to be solved. ### Relevant local hypotheses `solve_by_elim*` works with multiple goals, and we need to use separate sets of local hypotheses for each goal. The second component of the returned value provides these local hypotheses. (Essentially using `local_context`, along with some filtering to remove hypotheses that have been explicitly removed via `only` or `[-h]`.) ### Stuck metavariables Lemmas with implicit arguments would be filled in with metavariables if we created the `expr` objects immediately, so instead we return thunks that generate the expressions on demand. This is the first component, with type `list (tactic expr)`. As an example, we have `def rfl : ∀ {α : Sort u} {a : α}, a = a`, which on elaboration will become `@rfl ?m_1 ?m_2`. Because `solve_by_elim` works by repeated application of lemmas against subgoals, the first time such a lemma is successfully applied, those metavariables will be unified, and thereafter have fixed values. This would make it impossible to apply the lemma a second time with different values of the metavariables. See https://github.com/leanprover-community/mathlib/issues/2269 As an optimisation, after we build the list of `tactic expr`s, we actually run them, and replace any that do not in fact produce metavariables with a simple `return` tactic. -/ meta def mk_assumption_set (no_dflt : bool) (hs : list simp_arg_type) (attr : list name) : tactic (list (tactic expr) × tactic (list expr)) := -- We lock the tactic state so that any spurious goals generated during -- elaboration of pre-expressions are discarded lock_tactic_state $ do -- `hs` are expressions specified explicitly, -- `hex` are exceptions (specified via `solve_by_elim [-h]`) referring to local hypotheses, -- `gex` are the other exceptions (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, -- Recall, per the discussion above, we produce `tactic expr` thunks rather than actual `expr`s. -- Note that while we evaluate these thunks on two occasions below while preparing the list, -- this is a one-time cost during `mk_assumption_set`, rather than a cost proportional to the -- length of the search `solve_by_elim` executes. let hs := hs.map (λ h, i_to_expr_for_apply h), l ← attr.mmap $ λ a, attribute.get_instances a, let l := l.join, let m := l.map (λ h, mk_const h), -- In order to remove the expressions we need to evaluate the thunks. hs ← (hs ++ m).mfilter $ λ h, (do h ← h, return $ expr.const_name h ∉ gex), let hs := if no_dflt then hs else ([`rfl, `trivial, `congr_fun, `congr_arg].map (λ n, (mk_const n))) ++ hs, let locals : tactic (list expr) := if ¬ no_dflt ∨ all_hyps then do ctx ← local_context, -- Remove local exceptions specified in `hex`: return $ ctx.filter (λ h : expr, h.local_uniq_name ∉ hex) else return [], -- Finally, run all of the tactics: any that return an expression without metavariables can safely -- be replaced by a `return` tactic. hs ← hs.mmap (λ h : tactic expr, do e ← h, if e.has_meta_var then return h else return (return e)), return (hs, locals) /-- Configuration options for `solve_by_elim`. * `accept : list expr → tactic unit` determines whether the current branch should be explored. At each step, before the lemmas are applied, `accept` is passed the proof terms for the original goals, as reported by `get_goals` when `solve_by_elim` started. These proof terms may be metavariables (if no progress has been made on that goal) or may contain metavariables at some leaf nodes (if the goal has been partially solved by previous `apply` steps). If the `accept` tactic fails `solve_by_elim` aborts searching this branch and backtracks. By default `accept := λ _, skip` always succeeds. (There is an example usage in `tests/solve_by_elim.lean`.) * `pre_apply : tactic unit` specifies an additional tactic to run before each round of `apply`. * `discharger : tactic unit` specifies an additional tactic to apply on subgoals for which no lemma applies. If that tactic succeeds, `solve_by_elim` will continue applying lemmas on resulting goals. -/ meta structure basic_opt extends apply_any_opt := (accept : list expr → tactic unit := λ _, skip) (pre_apply : tactic unit := skip) (discharger : tactic unit := failed) (max_depth : ℕ := 3) declare_trace solve_by_elim -- trace attempted lemmas /-- A helper function for trace messages, prepending '....' depending on the current search depth. -/ meta def solve_by_elim_trace (n : ℕ) (f : format) : tactic unit := trace_if_enabled `solve_by_elim (format!"[solve_by_elim {(list.replicate (n+1) '.').as_string} " ++ f ++ "]") /-- A helper function to generate trace messages on successful applications. -/ meta def on_success (g : format) (n : ℕ) (e : expr) : tactic unit := do pp ← pp e, solve_by_elim_trace n (format!"✅ `{pp}` solves `⊢ {g}`") /-- A helper function to generate trace messages on unsuccessful applications. -/ meta def on_failure (g : format) (n : ℕ) : tactic unit := solve_by_elim_trace n (format!"❌ failed to solve `⊢ {g}`") /-- A helper function to generate the tactic that print trace messages. This function exists to ensure the target is pretty printed only as necessary. -/ meta def trace_hooks (n : ℕ) : tactic ((expr → tactic unit) × tactic unit) := if is_trace_enabled_for `solve_by_elim then do g ← target >>= pp, return (on_success g n, on_failure g n) else return (λ _, skip, skip) /-- The internal implementation of `solve_by_elim`, with a limiting counter. -/ meta def solve_by_elim_aux (opt : basic_opt) (original_goals : list expr) (lemmas : list (tactic expr)) (ctx : tactic (list expr)) : ℕ → tactic unit | n := do -- First, check that progress so far is `accept`able. lock_tactic_state (original_goals.mmap instantiate_mvars >>= opt.accept), -- Then check if we've finished. (done >> solve_by_elim_trace (opt.max_depth - n) "success!") <|> (do -- Otherwise, if there's more time left, (guard (n > 0) <|> solve_by_elim_trace opt.max_depth "🛑 aborting, hit depth limit" >> failed), -- run the `pre_apply` tactic, then opt.pre_apply, -- try either applying a lemma and recursing, (on_success, on_failure) ← trace_hooks (opt.max_depth - n), ctx_lemmas ← ctx, (apply_any_thunk (lemmas ++ (ctx_lemmas.map return)) opt.to_apply_any_opt (solve_by_elim_aux (n-1)) on_success on_failure) <|> -- or if that doesn't work, run the discharger and recurse. (opt.discharger >> solve_by_elim_aux (n-1))) /-- Arguments for `solve_by_elim`: * By default `solve_by_elim` operates only on the first goal, but with `backtrack_all_goals := true`, it operates on all goals at once, backtracking across goals as needed, and only succeeds if it discharges all goals. * `lemmas` specifies the list of lemmas to use in the backtracking search. If `none`, `solve_by_elim` uses the local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`. * `lemma_thunks` provides the lemmas as a list of `tactic expr`, which are used to regenerate the `expr` objects to avoid binding metavariables. It should not usually be specified by the user. (If both `lemmas` and `lemma_thunks` are specified, only `lemma_thunks` is used.) * `ctx_thunk` is for internal use only: it returns the local hypotheses which will be used. * `max_depth` bounds the depth of the search. -/ meta structure opt extends basic_opt := (backtrack_all_goals : bool := ff) (lemmas : option (list expr) := none) (lemma_thunks : option (list (tactic expr)) := lemmas.map (λ l, l.map return)) (ctx_thunk : tactic (list expr) := local_context) /-- If no lemmas have been specified, generate the default set (local hypotheses, along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`). -/ meta def opt.get_lemma_thunks (opt : opt) : tactic (list (tactic expr) × tactic (list expr)) := match opt.lemma_thunks with | none := mk_assumption_set ff [] [] | some lemma_thunks := return (lemma_thunks, opt.ctx_thunk) end end solve_by_elim open solve_by_elim /-- `solve_by_elim` repeatedly tries `apply`ing a lemma from the list of assumptions (passed via the `opt` argument), recursively operating on any generated subgoals, backtracking as necessary. `solve_by_elim` succeeds only if it discharges the goal. (By default, `solve_by_elim` focuses on the first goal, and only attempts to solve that. With the option `backtrack_all_goals := tt`, it attempts to solve all goals, and only succeeds if it does so. With `backtrack_all_goals := tt`, `solve_by_elim` will backtrack a solution it has found for one goal if it then can't discharge other goals.) If passed an empty list of assumptions, `solve_by_elim` builds a default set as per the interactive tactic, using the `local_context` along with `rfl`, `trivial`, `congr_arg`, and `congr_fun`. To pass a particular list of assumptions, use the `lemmas` field in the configuration argument. This expects an `option (list expr)`. In certain situations it may be necessary to instead use the `lemma_thunks` field, which expects a `option (list (tactic expr))`. This allows for regenerating metavariables for each application, which might otherwise get stuck. See also the simpler tactic `apply_rules`, which does not perform backtracking. -/ meta def solve_by_elim (opt : opt := { }) : tactic unit := do tactic.fail_if_no_goals, (lemmas, ctx_lemmas) ← opt.get_lemma_thunks, (if opt.backtrack_all_goals then id else focus1) $ (do gs ← get_goals, solve_by_elim_aux opt.to_basic_opt gs lemmas ctx_lemmas opt.max_depth <|> fail ("`solve_by_elim` failed.\n" ++ "Try `solve_by_elim { max_depth := N }` for `N > " ++ (to_string opt.max_depth) ++ "`\n" ++ "or use `set_option trace.solve_by_elim true` to view the search.")) setup_tactic_parser namespace interactive /-- `apply_assumption` looks for an assumption of the form `... → ∀ _, ... → head` where `head` matches the current goal. If this fails, `apply_assumption` will call `symmetry` and try again. If this also fails, `apply_assumption` will call `exfalso` and try again, so that if there is an assumption of the form `P → ¬ Q`, the new tactic state will have two goals, `P` and `Q`. Optional arguments: - `lemmas`: a list of expressions to apply, instead of the local constants - `tac`: a tactic to run on each subgoal after applying an assumption; if this tactic fails, the corresponding assumption will be rejected and the next one will be attempted. -/ meta def apply_assumption (lemmas : parse pexpr_list?) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := do lemmas ← match lemmas with | none := local_context | some lemmas := lemmas.mmap to_expr end, tactic.apply_any lemmas opt tac add_tactic_doc { name := "apply_assumption", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_assumption], tags := ["context management", "lemma application"] } /-- `solve_by_elim` calls `apply` on the main goal to find an assumption whose head matches and then repeatedly calls `apply` on the generated subgoals until no subgoals remain, performing at most `max_depth` recursive steps. `solve_by_elim` discharges the current goal or fails. `solve_by_elim` performs back-tracking if subgoals can not be solved. By default, the assumptions passed to `apply` are the local context, `rfl`, `trivial`, `congr_fun` and `congr_arg`. The assumptions can be modified with similar syntax as for `simp`: * `solve_by_elim [h₁, h₂, ..., hᵣ]` also applies the named lemmas. * `solve_by_elim with attr₁ ... attrᵣ` also applies all lemmas tagged with the specified attributes. * `solve_by_elim only [h₁, h₂, ..., hᵣ]` does not include the local context, `rfl`, `trivial`, `congr_fun`, or `congr_arg` unless they are explicitly included. * `solve_by_elim [-id_1, ... -id_n]` uses the default assumptions, removing the specified ones. `solve_by_elim*` tries to solve all goals together, using backtracking if a solution for one goal makes other goals impossible. optional arguments passed via a configuration argument as `solve_by_elim { ... }` - max_depth: number of attempts at discharging generated sub-goals - discharger: a subsidiary tactic to try at each step when no lemmas apply (e.g. `cc` may be helpful). - pre_apply: a subsidiary tactic to run at each step before applying lemmas (e.g. `intros`). - accept: a subsidiary tactic `list expr → tactic unit` that at each step, before any lemmas are applied, is passed the original proof terms as reported by `get_goals` when `solve_by_elim` started (but which may by now have been partially solved by previous `apply` steps). If the `accept` tactic fails, `solve_by_elim` will abort searching the current branch and backtrack. This may be used to filter results, either at every step of the search, or filtering complete results (by testing for the absence of metavariables, and then the filtering condition). -/ meta def solve_by_elim (all_goals : parse $ (tk "*")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : solve_by_elim.opt := { }) : tactic unit := do (lemma_thunks, ctx_thunk) ← mk_assumption_set no_dflt hs attr_names, tactic.solve_by_elim { backtrack_all_goals := all_goals.is_some ∨ opt.backtrack_all_goals, lemma_thunks := some lemma_thunks, ctx_thunk := ctx_thunk, ..opt } add_tactic_doc { name := "solve_by_elim", category := doc_category.tactic, decl_names := [`tactic.interactive.solve_by_elim], tags := ["search"] } end interactive end tactic
731e7b17dce144bfdb34786a387ef94c2a75cdcd
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/nat_bug2.lean
ee29522d742151ffbe5a64534131138b49e6543c
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
707
lean
import logic open eq.ops namespace experiment inductive nat : Type := zero : nat, succ : nat → nat namespace nat definition plus (x y : nat) : nat := nat.rec x (λn r, succ r) y definition to_nat [coercion] (n : num) : nat := num.rec zero (λn, pos_num.rec (succ zero) (λn r, plus r (plus r (succ zero))) (λn r, plus r r) n) n definition add (x y : nat) : nat := plus x y constant le : nat → nat → Prop infixl `+` := add infix `≤` := le axiom add_one (n:nat) : n + (succ zero) = succ n axiom add_le_right {n m : nat} (H : n ≤ m) (k : nat) : n + k ≤ m + k theorem succ_le {n m : nat} (H : n ≤ m) : succ n ≤ succ m := add_one m ▸ add_one n ▸ add_le_right H 1 end nat end experiment
680bb4e44bf9a900cf44f082f2242fbe6c55e733
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/group/basic.lean
1d0f5dac1609fd30e03d0c792373530983e3d52a
[ "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
16,518
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, Simon Hudon, Mario Carneiro -/ import algebra.group.defs import logic.function.basic /-! # Basic lemmas about semigroups, monoids, and groups This file lists various basic lemmas about semigroups, monoids, and groups. Most proofs are one-liners from the corresponding axioms. For the definitions of semigroups, monoids and groups, see `algebra/group/defs.lean`. -/ universe u section associative variables {α : Type u} (f : α → α → α) [is_associative α f] (x y : α) /-- Composing two associative operations of `f : α → α → α` on the left is equal to an associative operation on the left. -/ lemma comp_assoc_left : (f x) ∘ (f y) = (f (f x y)) := by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] } /-- Composing two associative operations of `f : α → α → α` on the right is equal to an associative operation on the right. -/ lemma comp_assoc_right : (λ z, f z x) ∘ (λ z, f z y) = (λ z, f z (f y x)) := by { ext z, rw [function.comp_apply, @is_associative.assoc _ f] } end associative section semigroup variables {α : Type*} /-- Composing two multiplications on the left by `y` then `x` is equal to a multiplication on the left by `x * y`. -/ @[simp, to_additive "Composing two additions on the left by `y` then `x` is equal to a addition on the left by `x + y`."] lemma comp_mul_left [semigroup α] (x y : α) : ((*) x) ∘ ((*) y) = ((*) (x * y)) := comp_assoc_left _ _ _ /-- Composing two multiplications on the right by `y` and `x` is equal to a multiplication on the right by `y * x`. -/ @[simp, to_additive "Composing two additions on the right by `y` and `x` is equal to a addition on the right by `y + x`."] lemma comp_mul_right [semigroup α] (x y : α) : (* x) ∘ (* y) = (* (y * x)) := comp_assoc_right _ _ _ end semigroup section mul_one_class variables {M : Type u} [mul_one_class M] @[to_additive] lemma ite_mul_one {P : Prop} [decidable P] {a b : M} : ite P (a * b) 1 = ite P a 1 * ite P b 1 := by { by_cases h : P; simp [h], } @[to_additive] lemma eq_one_iff_eq_one_of_mul_eq_one {a b : M} (h : a * b = 1) : a = 1 ↔ b = 1 := by split; { rintro rfl, simpa using h } @[to_additive] lemma one_mul_eq_id : ((*) (1 : M)) = id := funext one_mul @[to_additive] lemma mul_one_eq_id : (* (1 : M)) = id := funext mul_one end mul_one_class section comm_semigroup variables {G : Type u} [comm_semigroup G] @[no_rsimp, to_additive] lemma mul_left_comm : ∀ a b c : G, a * (b * c) = b * (a * c) := left_comm has_mul.mul mul_comm mul_assoc attribute [no_rsimp] add_left_comm @[to_additive] lemma mul_right_comm : ∀ a b c : G, a * b * c = a * c * b := right_comm has_mul.mul mul_comm mul_assoc @[to_additive] theorem mul_mul_mul_comm (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) := by simp only [mul_left_comm, mul_assoc] end comm_semigroup local attribute [simp] mul_assoc sub_eq_add_neg section add_monoid variables {M : Type u} [add_monoid M] {a b c : M} @[simp] lemma bit0_zero : bit0 (0 : M) = 0 := add_zero _ @[simp] lemma bit1_zero [has_one M] : bit1 (0 : M) = 1 := by rw [bit1, bit0_zero, zero_add] end add_monoid section comm_monoid variables {M : Type u} [comm_monoid M] {x y z : M} @[to_additive] lemma inv_unique (hy : x * y = 1) (hz : x * z = 1) : y = z := left_inv_eq_right_inv (trans (mul_comm _ _) hy) hz end comm_monoid section left_cancel_monoid variables {M : Type u} [left_cancel_monoid M] {a b : M} @[simp, to_additive] lemma mul_right_eq_self : a * b = a ↔ b = 1 := calc a * b = a ↔ a * b = a * 1 : by rw mul_one ... ↔ b = 1 : mul_left_cancel_iff @[simp, to_additive] lemma self_eq_mul_right : a = a * b ↔ b = 1 := eq_comm.trans mul_right_eq_self end left_cancel_monoid section right_cancel_monoid variables {M : Type u} [right_cancel_monoid M] {a b : M} @[simp, to_additive] lemma mul_left_eq_self : a * b = b ↔ a = 1 := calc a * b = b ↔ a * b = 1 * b : by rw one_mul ... ↔ a = 1 : mul_right_cancel_iff @[simp, to_additive] lemma self_eq_mul_left : b = a * b ↔ a = 1 := eq_comm.trans mul_left_eq_self end right_cancel_monoid section div_inv_monoid variables {G : Type u} [div_inv_monoid G] @[to_additive] lemma inv_eq_one_div (x : G) : x⁻¹ = 1 / x := by rw [div_eq_mul_inv, one_mul] @[to_additive] lemma mul_one_div (x y : G) : x * (1 / y) = x / y := by rw [div_eq_mul_inv, one_mul, div_eq_mul_inv] lemma mul_div_assoc {a b c : G} : a * b / c = a * (b / c) := by rw [div_eq_mul_inv, div_eq_mul_inv, mul_assoc _ _ _] lemma mul_div_assoc' (a b c : G) : a * (b / c) = (a * b) / c := mul_div_assoc.symm @[simp, to_additive] lemma one_div (a : G) : 1 / a = a⁻¹ := (inv_eq_one_div a).symm end div_inv_monoid section group variables {G : Type u} [group G] {a b c : G} @[simp, to_additive] lemma inv_mul_cancel_right (a b : G) : a * b⁻¹ * b = a := by simp [mul_assoc] @[simp, to_additive neg_zero] lemma one_inv : 1⁻¹ = (1 : G) := inv_eq_of_mul_eq_one (one_mul 1) @[to_additive] theorem left_inverse_inv (G) [group G] : function.left_inverse (λ a : G, a⁻¹) (λ a, a⁻¹) := inv_inv @[simp, to_additive] lemma inv_involutive : function.involutive (has_inv.inv : G → G) := inv_inv @[to_additive] lemma inv_injective : function.injective (has_inv.inv : G → G) := inv_involutive.injective @[simp, to_additive] theorem inv_inj : a⁻¹ = b⁻¹ ↔ a = b := inv_injective.eq_iff @[simp, to_additive] lemma mul_inv_cancel_left (a b : G) : a * (a⁻¹ * b) = b := by rw [← mul_assoc, mul_right_inv, one_mul] @[to_additive] theorem mul_left_surjective (a : G) : function.surjective ((*) a) := λ x, ⟨a⁻¹ * x, mul_inv_cancel_left a x⟩ @[to_additive] theorem mul_right_surjective (a : G) : function.surjective (λ x, x * a) := λ x, ⟨x * a⁻¹, inv_mul_cancel_right x a⟩ @[simp, to_additive neg_add_rev] lemma mul_inv_rev (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := inv_eq_of_mul_eq_one $ by simp @[to_additive] lemma eq_inv_of_eq_inv (h : a = b⁻¹) : b = a⁻¹ := by simp [h] @[to_additive] lemma eq_inv_of_mul_eq_one (h : a * b = 1) : a = b⁻¹ := have a⁻¹ = b, from inv_eq_of_mul_eq_one h, by simp [this.symm] @[to_additive] lemma eq_mul_inv_of_mul_eq (h : a * c = b) : a = b * c⁻¹ := by simp [h.symm] @[to_additive] lemma eq_inv_mul_of_mul_eq (h : b * a = c) : a = b⁻¹ * c := by simp [h.symm] @[to_additive] lemma inv_mul_eq_of_eq_mul (h : b = a * c) : a⁻¹ * b = c := by simp [h] @[to_additive] lemma mul_inv_eq_of_eq_mul (h : a = c * b) : a * b⁻¹ = c := by simp [h] @[to_additive] lemma eq_mul_of_mul_inv_eq (h : a * c⁻¹ = b) : a = b * c := by simp [h.symm] @[to_additive] lemma eq_mul_of_inv_mul_eq (h : b⁻¹ * a = c) : a = b * c := by simp [h.symm, mul_inv_cancel_left] @[to_additive] lemma mul_eq_of_eq_inv_mul (h : b = a⁻¹ * c) : a * b = c := by rw [h, mul_inv_cancel_left] @[to_additive] lemma mul_eq_of_eq_mul_inv (h : a = c * b⁻¹) : a * b = c := by simp [h] @[simp, to_additive] theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 := by rw [← @inv_inj _ _ a 1, one_inv] @[simp, to_additive] theorem one_eq_inv : 1 = a⁻¹ ↔ a = 1 := by rw [eq_comm, inv_eq_one] @[to_additive] theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 := not_congr inv_eq_one @[to_additive] theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ := ⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩ @[to_additive] theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a := eq_comm.trans $ eq_inv_iff_eq_inv.trans eq_comm @[to_additive] theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ := ⟨eq_inv_of_mul_eq_one, λ h, by rw [h, mul_left_inv]⟩ @[to_additive] theorem mul_eq_one_iff_inv_eq : a * b = 1 ↔ a⁻¹ = b := by rw [mul_eq_one_iff_eq_inv, eq_inv_iff_eq_inv, eq_comm] @[to_additive] theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 := mul_eq_one_iff_eq_inv.symm @[to_additive] theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 := mul_eq_one_iff_inv_eq.symm @[to_additive] theorem eq_mul_inv_iff_mul_eq : a = b * c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq : a = b⁻¹ * c ↔ b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul : a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul : a * b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ @[to_additive] theorem mul_inv_eq_one : a * b⁻¹ = 1 ↔ a = b := by rw [mul_eq_one_iff_eq_inv, inv_inv] @[to_additive] theorem inv_mul_eq_one : a⁻¹ * b = 1 ↔ a = b := by rw [mul_eq_one_iff_eq_inv, inv_inj] @[to_additive] lemma div_left_injective : function.injective (λ a, a / b) := by simpa only [div_eq_mul_inv] using λ a a' h, mul_left_injective (b⁻¹) h @[to_additive] lemma div_right_injective : function.injective (λ a, b / a) := by simpa only [div_eq_mul_inv] using λ a a' h, inv_injective (mul_right_injective b h) -- The unprimed version is used by `group_with_zero`. This is the preferred choice. -- See https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/.60div_one'.60 @[simp, to_additive sub_zero] lemma div_one' (a : G) : a / 1 = a := calc a / 1 = a * 1⁻¹ : div_eq_mul_inv a 1 ... = a * 1 : congr_arg _ one_inv ... = a : mul_one a end group section add_group variables {G : Type u} [add_group G] {a b c d : G} @[simp] lemma sub_self (a : G) : a - a = 0 := by rw [sub_eq_add_neg, add_right_neg a] @[simp] lemma sub_add_cancel (a b : G) : a - b + b = a := by rw [sub_eq_add_neg, neg_add_cancel_right a b] @[simp] lemma add_sub_cancel (a b : G) : a + b - b = a := by rw [sub_eq_add_neg, add_neg_cancel_right a b] lemma add_sub_assoc (a b c : G) : a + b - c = a + (b - c) := by rw [sub_eq_add_neg, add_assoc, ←sub_eq_add_neg] lemma eq_of_sub_eq_zero (h : a - b = 0) : a = b := calc a = a - b + b : (sub_add_cancel a b).symm ... = b : by rw [h, zero_add] lemma sub_ne_zero_of_ne (h : a ≠ b) : a - b ≠ 0 := mt eq_of_sub_eq_zero h @[simp] lemma sub_neg_eq_add (a b : G) : a - (-b) = a + b := by rw [sub_eq_add_neg, neg_neg] @[simp] lemma neg_sub (a b : G) : -(a - b) = b - a := neg_eq_of_add_eq_zero (by rw [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, add_right_neg]) local attribute [simp] add_assoc lemma add_sub (a b c : G) : a + (b - c) = a + b - c := by simp lemma sub_add_eq_sub_sub_swap (a b c : G) : a - (b + c) = a - c - b := by simp @[simp] lemma add_sub_add_right_eq_sub (a b c : G) : (a + c) - (b + c) = a - b := by rw [sub_add_eq_sub_sub_swap]; simp lemma eq_sub_of_add_eq (h : a + c = b) : a = b - c := by simp [← h] lemma sub_eq_of_eq_add (h : a = c + b) : a - b = c := by simp [h] lemma eq_add_of_sub_eq (h : a - c = b) : a = b + c := by simp [← h] lemma add_eq_of_eq_sub (h : a = c - b) : a + b = c := by simp [h] @[simp] lemma sub_right_inj : a - b = a - c ↔ b = c := sub_right_injective.eq_iff @[simp] lemma sub_left_inj : b - a = c - a ↔ b = c := by { rw [sub_eq_add_neg, sub_eq_add_neg], exact add_left_inj _ } lemma sub_add_sub_cancel (a b c : G) : (a - b) + (b - c) = a - c := by rw [← add_sub_assoc, sub_add_cancel] lemma sub_sub_sub_cancel_right (a b c : G) : (a - c) - (b - c) = a - b := by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel] theorem sub_sub_assoc_swap : a - (b - c) = a + c - b := by simp theorem sub_eq_zero : a - b = 0 ↔ a = b := ⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩ alias sub_eq_zero ↔ _ sub_eq_zero_of_eq theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b := not_congr sub_eq_zero @[simp] theorem sub_eq_self : a - b = a ↔ b = 0 := by rw [sub_eq_add_neg, add_right_eq_self, neg_eq_zero] theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b := by rw [sub_eq_add_neg, eq_add_neg_iff_add_eq] theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b := by rw [sub_eq_add_neg, add_neg_eq_iff_eq_add] theorem eq_iff_eq_of_sub_eq_sub (H : a - b = c - d) : a = b ↔ c = d := by rw [← sub_eq_zero, H, sub_eq_zero] theorem left_inverse_sub_add_left (c : G) : function.left_inverse (λ x, x - c) (λ x, x + c) := assume x, add_sub_cancel x c theorem left_inverse_add_left_sub (c : G) : function.left_inverse (λ x, x + c) (λ x, x - c) := assume x, sub_add_cancel x c theorem left_inverse_add_right_neg_add (c : G) : function.left_inverse (λ x, c + x) (λ x, - c + x) := assume x, add_neg_cancel_left c x theorem left_inverse_neg_add_add_right (c : G) : function.left_inverse (λ x, - c + x) (λ x, c + x) := assume x, neg_add_cancel_left c x end add_group section comm_group variables {G : Type u} [comm_group G] @[to_additive neg_add] lemma mul_inv (a b : G) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by rw [mul_inv_rev, mul_comm] end comm_group section add_comm_group variables {G : Type u} [add_comm_group G] {a b c d : G} local attribute [simp] add_assoc add_comm add_left_comm sub_eq_add_neg lemma sub_add_eq_sub_sub (a b c : G) : a - (b + c) = a - b - c := by simp lemma neg_add_eq_sub (a b : G) : -a + b = b - a := by simp lemma sub_add_eq_add_sub (a b c : G) : a - b + c = a + c - b := by simp lemma sub_sub (a b c : G) : a - b - c = a - (b + c) := by simp lemma sub_add (a b c : G) : a - b + c = a - (b - c) := by simp @[simp] lemma add_sub_add_left_eq_sub (a b c : G) : (c + a) - (c + b) = a - b := by simp lemma eq_sub_of_add_eq' (h : c + a = b) : a = b - c := by simp [h.symm] lemma sub_eq_of_eq_add' (h : a = b + c) : a - b = c := begin simp [h], rw [add_left_comm], simp end lemma eq_add_of_sub_eq' (h : a - b = c) : a = b + c := by simp [h.symm] lemma add_eq_of_eq_sub' (h : b = c - a) : a + b = c := begin simp [h], rw [add_comm c, add_neg_cancel_left] end lemma sub_sub_self (a b : G) : a - (a - b) = b := begin simp, rw [add_comm b, add_neg_cancel_left] end lemma add_sub_comm (a b c d : G) : a + b - (c + d) = (a - c) + (b - d) := by simp lemma sub_eq_sub_add_sub (a b c : G) : a - b = c - b + (a - c) := begin simp, rw [add_left_comm c], simp end lemma neg_neg_sub_neg (a b : G) : - (-a - -b) = a - b := by simp @[simp] lemma sub_sub_cancel (a b : G) : a - (a - b) = b := sub_sub_self a b lemma sub_eq_neg_add (a b : G) : a - b = -b + a := by rw [sub_eq_add_neg, add_comm _ _] theorem neg_add' (a b : G) : -(a + b) = -a - b := by rw [sub_eq_add_neg, neg_add a b] @[simp] lemma neg_sub_neg (a b : G) : -a - -b = b - a := by simp [sub_eq_neg_add, add_comm] lemma eq_sub_iff_add_eq' : a = b - c ↔ c + a = b := by rw [eq_sub_iff_add_eq, add_comm] lemma sub_eq_iff_eq_add' : a - b = c ↔ a = b + c := by rw [sub_eq_iff_eq_add, add_comm] @[simp] lemma add_sub_cancel' (a b : G) : a + b - a = b := by rw [sub_eq_neg_add, neg_add_cancel_left] @[simp] lemma add_sub_cancel'_right (a b : G) : a + (b - a) = b := by rw [← add_sub_assoc, add_sub_cancel'] -- This lemma is in the `simp` set under the name `add_neg_cancel_comm_assoc`, -- defined in `algebra/group/commute` lemma add_add_neg_cancel'_right (a b : G) : a + (b + -a) = b := by rw [← sub_eq_add_neg, add_sub_cancel'_right a b] lemma sub_right_comm (a b c : G) : a - b - c = a - c - b := by { repeat { rw sub_eq_add_neg }, exact add_right_comm _ _ _ } @[simp] lemma add_add_sub_cancel (a b c : G) : (a + c) + (b - c) = a + b := by rw [add_assoc, add_sub_cancel'_right] @[simp] lemma sub_add_add_cancel (a b c : G) : (a - c) + (b + c) = a + b := by rw [add_left_comm, sub_add_cancel, add_comm] @[simp] lemma sub_add_sub_cancel' (a b c : G) : (a - b) + (c - a) = c - b := by rw add_comm; apply sub_add_sub_cancel @[simp] lemma add_sub_sub_cancel (a b c : G) : (a + b) - (a - c) = b + c := by rw [← sub_add, add_sub_cancel'] @[simp] lemma sub_sub_sub_cancel_left (a b c : G) : (c - a) - (c - b) = b - a := by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel] lemma sub_eq_sub_iff_add_eq_add : a - b = c - d ↔ a + d = c + b := begin rw [sub_eq_iff_eq_add, sub_add_eq_add_sub, eq_comm, sub_eq_iff_eq_add'], simp only [add_comm, eq_comm] end lemma sub_eq_sub_iff_sub_eq_sub : a - b = c - d ↔ a - c = b - d := by rw [sub_eq_iff_eq_add, sub_add_eq_add_sub, sub_eq_iff_eq_add', add_sub_assoc] end add_comm_group
cc172153d7dda50075aa822944ee3b90dab7e3bd
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Data/List/Perm.lean
0913120f43c9a6107b1a9c328129b95aa0bded4f
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
2,222
lean
import Mathlib.Init.Set import Mathlib.Data.List.Basic namespace List /-- `Perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are Permutations of each other. This is defined by induction using pairwise swaps. -/ inductive Perm : List α → List α → Prop | nil : Perm [] [] | cons : ∀ (x : α) {l₁ l₂ : List α}, Perm l₁ l₂ → Perm (x::l₁) (x::l₂) | swap : ∀ (x y : α) (l : List α), Perm (y::x::l) (x::y::l) | trans : ∀ {l₁ l₂ l₃ : List α}, Perm l₁ l₂ → Perm l₂ l₃ → Perm l₁ l₃ open Perm infixl:50 " ~ " => Perm protected theorem Perm.refl : ∀ (l : List α), l ~ l | [] => Perm.nil | (x::xs) => (Perm.refl xs).cons x protected theorem Perm.symm {l₁ l₂ : List α} (p : l₁ ~ l₂) : l₂ ~ l₁ := by induction p with | nil => exact Perm.nil | cons x _ ih => exact Perm.cons x ih | swap x y l => exact Perm.swap y x l | trans _ _ ih₁ ih₂ => exact Perm.trans ih₂ ih₁ theorem Perm_comm {l₁ l₂ : List α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨Perm.symm, Perm.symm⟩ theorem Perm.swap' (x y : α) {l₁ l₂ : List α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ := have h1 : y :: l₁ ~ y :: l₂ := Perm.cons y p have h2 : x :: y :: l₁ ~ x :: y :: l₂ := Perm.cons x h1 have h3 : y :: x :: l₁ ~ x :: y :: l₁ := Perm.swap x y l₁ Perm.trans h3 h2 theorem Perm.Equivalence : Equivalence (@Perm α) := ⟨Perm.refl, Perm.symm, Perm.trans⟩ instance (α : Type u) : Setoid (List α) := ⟨Perm, Perm.Equivalence⟩ theorem Perm.subset {α : Type u} {l₁ l₂ : List α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ := by induction p with | nil => exact nil_subset _ | cons _ _ ih => exact cons_subset_cons _ ih | swap x y l => intro a rw [mem_cons] exact fun | Or.inl a_eq_y => Or.inr (Or.inl a_eq_y) | Or.inr eq_or_mem => match eq_or_mem with | Or.inl a_eq_x => Or.inl a_eq_x | Or.inr a_mem_l => Or.inr (Or.inr a_mem_l) | trans h1 h2 ih₁ ih₂ => exact subset.trans ih₁ ih₂ theorem perm_middle {a : α} : ∀ {l₁ l₂ : List α}, l₁++a::l₂ ~ a::(l₁++l₂) | [], l₂ => Perm.refl _ | (b::l₁), l₂ => let h2 := @perm_middle α a l₁ l₂ (h2.cons _).trans (swap a b _)
0f178464202da9e693dd5e38762f80416ab60b8e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/stone_cech.lean
522e2f27ea8e7f1091daac08dbc8d6ff900657e7
[ "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
11,205
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 topology.bases import topology.dense_embedding /-! # Stone-Čech compactification Construction of the Stone-Čech compactification using ultrafilters. Parts of the formalization are based on "Ultrafilters and Topology" by Marius Stekelenburg, particularly section 5. -/ noncomputable theory open filter set open_locale topological_space universes u v section ultrafilter /- The set of ultrafilters on α carries a natural topology which makes it the Stone-Čech compactification of α (viewed as a discrete space). -/ /-- Basis for the topology on `ultrafilter α`. -/ def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) := range $ λ s : set α, {u | s ∈ u} variables {α : Type u} instance : topological_space (ultrafilter α) := topological_space.generate_from (ultrafilter_basis α) lemma ultrafilter_basis_is_basis : topological_space.is_topological_basis (ultrafilter_basis α) := ⟨begin rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩, refine ⟨_, ⟨a ∩ b, rfl⟩, inter_mem_sets ua ub, assume v hv, ⟨_, _⟩⟩; apply mem_sets_of_superset hv; simp [inter_subset_right a b] end, eq_univ_of_univ_subset $ subset_sUnion_of_mem $ ⟨univ, eq_univ_of_forall (λ u, univ_mem_sets)⟩, rfl⟩ /-- The basic open sets for the topology on ultrafilters are open. -/ lemma ultrafilter_is_open_basic (s : set α) : is_open {u : ultrafilter α | s ∈ u} := ultrafilter_basis_is_basis.is_open ⟨s, rfl⟩ /-- The basic open sets for the topology on ultrafilters are also closed. -/ lemma ultrafilter_is_closed_basic (s : set α) : is_closed {u : ultrafilter α | s ∈ u} := begin rw ← is_open_compl_iff, convert ultrafilter_is_open_basic sᶜ, ext u, exact ultrafilter.compl_mem_iff_not_mem.symm end /-- Every ultrafilter `u` on `ultrafilter α` converges to a unique point of `ultrafilter α`, namely `mjoin u`. -/ lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} : ↑u ≤ 𝓝 x ↔ x = mjoin u := begin rw [eq_comm, ← ultrafilter.coe_le_coe], change ↑u ≤ 𝓝 x ↔ ∀ s ∈ x, {v : ultrafilter α | s ∈ v} ∈ u, simp only [topological_space.nhds_generate_from, le_infi_iff, ultrafilter_basis, le_principal_iff, mem_set_of_eq], split, { intros h a ha, exact h _ ⟨ha, a, rfl⟩ }, { rintros h a ⟨xi, a, rfl⟩, exact h _ xi } end instance ultrafilter_compact : compact_space (ultrafilter α) := ⟨is_compact_iff_ultrafilter_le_nhds.mpr $ assume f _, ⟨mjoin f, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩ instance ultrafilter.t2_space : t2_space (ultrafilter α) := t2_iff_ultrafilter.mpr $ assume x y f fx fy, have hx : x = mjoin f, from ultrafilter_converges_iff.mp fx, have hy : y = mjoin f, from ultrafilter_converges_iff.mp fy, hx.trans hy.symm lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (𝓝 b) ≤ b := begin rw topological_space.nhds_generate_from, simp only [comap_infi, comap_principal], intros s hs, rw ←le_principal_iff, refine infi_le_of_le {u | s ∈ u} _, refine infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _, exact principal_mono.2 (λ a, id) end section embedding lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) := begin intros x y h, have : {x} ∈ (pure x : ultrafilter α) := singleton_mem_pure_sets, rw h at this, exact (mem_singleton_iff.mp (mem_pure_sets.mp this)).symm end open topological_space /-- The range of `pure : α → ultrafilter α` is dense in `ultrafilter α`. -/ lemma dense_range_pure : dense_range (pure : α → ultrafilter α) := λ x, mem_closure_iff_ultrafilter.mpr ⟨x.map pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩ /-- The map `pure : α → ultra_filter α` induces on `α` the discrete topology. -/ lemma induced_topology_pure : topological_space.induced (pure : α → ultrafilter α) ultrafilter.topological_space = ⊥ := begin apply eq_bot_of_singletons_open, intros x, use [{u : ultrafilter α | {x} ∈ u}, ultrafilter_is_open_basic _], simp, end /-- `pure : α → ultrafilter α` defines a dense inducing of `α` in `ultrafilter α`. -/ lemma dense_inducing_pure : @dense_inducing _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥; exact ⟨⟨induced_topology_pure.symm⟩, dense_range_pure⟩ -- The following refined version will never be used /-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/ lemma dense_embedding_pure : @dense_embedding _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥ ; exact { inj := ultrafilter_pure_injective, ..dense_inducing_pure } end embedding section extension /- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a unique extension to a continuous function `ultrafilter α → γ`. We already know it must be unique because `α → ultrafilter α` is a dense embedding and `γ` is Hausdorff. For existence, we will invoke `dense_embedding.continuous_extend`. -/ variables {γ : Type*} [topological_space γ] /-- The extension of a function `α → γ` to a function `ultrafilter α → γ`. When `γ` is a compact Hausdorff space it will be continuous. -/ def ultrafilter.extend (f : α → γ) : ultrafilter α → γ := by letI : topological_space α := ⊥; exact dense_inducing_pure.extend f variables [t2_space γ] lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f := begin letI : topological_space α := ⊥, haveI : discrete_topology α := ⟨rfl⟩, exact funext (dense_inducing_pure.extend_eq continuous_of_discrete_topology) end variables [compact_space γ] lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) := have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap pure (𝓝 b)) (𝓝 c) := assume b, -- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ. let ⟨c, _, h⟩ := compact_univ.ultrafilter_le_nhds (b.map f) (by rw [le_principal_iff]; exact univ_mem_sets) in ⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩, begin letI : topological_space α := ⊥, haveI : normal_space γ := normal_of_compact_t2, exact dense_inducing_pure.continuous_extend this end /-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the unique limit of the ultrafilter `b.map f` in `γ`. -/ lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} : ultrafilter.extend f b = c ↔ ↑(b.map f) ≤ 𝓝 c := ⟨assume h, begin -- Write b as an ultrafilter limit of pure ultrafilters, and use -- the facts that ultrafilter.extend is a continuous extension of f. let b' : ultrafilter (ultrafilter α) := b.map pure, have t : ↑b' ≤ 𝓝 b, from ultrafilter_converges_iff.mpr (bind_pure _).symm, rw ←h, have := (continuous_ultrafilter_extend f).tendsto b, refine le_trans _ (le_trans (map_mono t) this), change _ ≤ map (ultrafilter.extend f ∘ pure) ↑b, rw ultrafilter_extend_extends, exact le_refl _ end, assume h, by letI : topological_space α := ⊥; exact dense_inducing_pure.extend_eq_of_tendsto (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩ end extension end ultrafilter section stone_cech /- Now, we start with a (not necessarily discrete) topological space α and we want to construct its Stone-Čech compactification. We can build it as a quotient of `ultrafilter α` by the relation which identifies two points if the extension of every continuous function α → γ to a compact Hausdorff space sends the two points to the same point of γ. -/ variables (α : Type u) [topological_space α] instance stone_cech_setoid : setoid (ultrafilter α) := { r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI ∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f), ultrafilter.extend f x = ultrafilter.extend f y, iseqv := ⟨assume x γ tγ h₁ h₂ f hf, rfl, assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm, assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ } /-- The Stone-Čech compactification of a topological space. -/ def stone_cech : Type u := quotient (stone_cech_setoid α) variables {α} instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance instance [inhabited α] : inhabited (stone_cech α) := by unfold stone_cech; apply_instance /-- The natural map from α to its Stone-Čech compactification. -/ def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧ /-- The image of stone_cech_unit is dense. (But stone_cech_unit need not be an embedding, for example if α is not Hausdorff.) -/ lemma dense_range_stone_cech_unit : dense_range (stone_cech_unit : α → stone_cech α) := dense_range_pure.quotient section extension variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ] variables {f : α → γ} (hf : continuous f) local attribute [elab_with_expected_type] quotient.lift /-- The extension of a continuous function from α to a compact Hausdorff space γ to the Stone-Čech compactification of α. -/ def stone_cech_extend : stone_cech α → γ := quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf) lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f := ultrafilter_extend_extends f lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) := continuous_quot_lift _ (continuous_ultrafilter_extend f) end extension lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : ↑u ≤ 𝓝 x) : u ≈ pure x := assume γ tγ h₁ h₂ f hf, begin resetI, transitivity f x, swap, symmetry, all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) }, { apply pure_le_nhds }, { exact ux } end lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) := continuous_iff_ultrafilter.mpr $ λ x g gx, have ↑(g.map pure) ≤ 𝓝 g, by rw ultrafilter_converges_iff; exact (bind_pure _).symm, have (g.map stone_cech_unit : filter (stone_cech α)) ≤ 𝓝 ⟦g⟧, from continuous_at_iff_ultrafilter.mp (continuous_quotient_mk.tendsto g) _ this, by rwa (show ⟦g⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this instance stone_cech.t2_space : t2_space (stone_cech α) := begin rw t2_iff_ultrafilter, rintros ⟨x⟩ ⟨y⟩ g gx gy, apply quotient.sound, intros γ tγ h₁ h₂ f hf, resetI, let ff := stone_cech_extend hf, change ff ⟦x⟧ = ff ⟦y⟧, have lim := λ (z : ultrafilter α) (gz : (g : filter (stone_cech α)) ≤ 𝓝 ⟦z⟧), ((continuous_stone_cech_extend hf).tendsto _).mono_left gz, exact tendsto_nhds_unique (lim x gx) (lim y gy) end instance stone_cech.compact_space : compact_space (stone_cech α) := quotient.compact_space end stone_cech
4a0a446007cdf1d0857aa51061dc0650250fd39d
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/apply4.lean
e3ea11c88ba8aca3246bf33c40b4d118a39c8ca8
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,006
lean
open tactic bool universe variables u constant foo {A : Type u} [inhabited A] (a b : A) : a = default A → a = b example (a b : nat) : a = 0 → a = b := by do intro `H, apply (expr.const `foo [level.of_nat 0]), trace_state, assumption definition ex : inhabited (nat × nat × bool) := by apply_instance set_option pp.all true print ex set_option pp.all false example (a b : nat) : a = 0 → a = b := by do intro `H, apply_core semireducible ff tt ff (expr.const `foo [level.of_nat 0]), trace_state, a ← get_local `a, trace_state, mk_app `inhabited.mk [a] >>= exact, trace "--------", trace_state, reflexivity print "----------------" set_option pp.all true example (a b : nat) : a = 0 → a = b := by do intro `H, foo ← mk_const `foo, trace foo, apply foo, trace_state, assumption example (a b : nat) : a = 0 → a = b := by do `[intro], apply_core semireducible ff tt ff (expr.const `foo [level.of_nat 0]), `[exact inhabited.mk a], reflexivity
7ce969155bafb2d3c25a684276e7e7eb83bbf97d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/implicit.lean
21bbda6901e3adabe4118e743c6fb8347675d5ba
[ "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
20,906
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.inverse import analysis.normed_space.complemented /-! # Implicit function theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We prove three versions of the implicit function theorem. First we define a structure `implicit_function_data` that holds arguments for the most general version of the implicit function theorem, see `implicit_function_data.implicit_function` and `implicit_function_data.to_implicit_function`. This version allows a user to choose a specific implicit function but provides only a little convenience over the inverse function theorem. Then we define `implicit_function_of_complemented`: implicit function defined by `f (g z y) = z`, where `f : E → F` is a function strictly differentiable at `a` such that its derivative `f'` is surjective and has a `complemented` kernel. Finally, if the codomain of `f` is a finite dimensional space, then we can automatically prove that the kernel of `f'` is complemented, hence the only assumptions are `has_strict_fderiv_at` and `f'.range = ⊤`. This version is named `implicit_function`. ## TODO * Add a version for a function `f : E × F → G` such that $$\frac{\partial f}{\partial y}$$ is invertible. * Add a version for `f : 𝕜 × 𝕜 → 𝕜` proving `has_strict_deriv_at` and `deriv φ = ...`. * Prove that in a real vector space the implicit function has the same smoothness as the original one. * If the original function is differentiable in a neighborhood, then the implicit function is differentiable in a neighborhood as well. Current setup only proves differentiability at one point for the implicit function constructed in this file (as opposed to an unspecified implicit function). One of the ways to overcome this difficulty is to use uniqueness of the implicit function in the general version of the theorem. Another way is to prove that *any* implicit function satisfying some predicate is strictly differentiable. ## Tags implicit function, inverse function -/ noncomputable theory open_locale topology open filter open continuous_linear_map (fst snd smul_right ker_prod) open continuous_linear_equiv (of_bijective) open linear_map (ker range) /-! ### General version Consider two functions `f : E → F` and `g : E → G` and a point `a` such that * both functions are strictly differentiable at `a`; * the derivatives are surjective; * the kernels of the derivatives are complementary subspaces of `E`. Note that the map `x ↦ (f x, g x)` has a bijective derivative, hence it is a local homeomorphism between `E` and `F × G`. We use this fact to define a function `φ : F → G → E` (see `implicit_function_data.implicit_function`) such that for `(y, z)` close enough to `(f a, g a)` we have `f (φ y z) = y` and `g (φ y z) = z`. We also prove a formula for $$\frac{\partial\varphi}{\partial z}.$$ Though this statement is almost symmetric with respect to `F`, `G`, we interpret it in the following way. Consider a family of surfaces `{x | f x = y}`, `y ∈ 𝓝 (f a)`. Each of these surfaces is parametrized by `φ y`. There are many ways to choose a (differentiable) function `φ` such that `f (φ y z) = y` but the extra condition `g (φ y z) = z` allows a user to select one of these functions. If we imagine that the level surfaces `f = const` form a local horizontal foliation, then the choice of `g` fixes a transverse foliation `g = const`, and `φ` is the inverse function of the projection of `{x | f x = y}` along this transverse foliation. This version of the theorem is used to prove the other versions and can be used if a user needs to have a complete control over the choice of the implicit function. -/ /-- Data for the general version of the implicit function theorem. It holds two functions `f : E → F` and `g : E → G` (named `left_fun` and `right_fun`) and a point `a` (named `pt`) such that * both functions are strictly differentiable at `a`; * the derivatives are surjective; * the kernels of the derivatives are complementary subspaces of `E`. -/ @[nolint has_nonempty_instance] structure implicit_function_data (𝕜 : Type*) [nontrivially_normed_field 𝕜] (E : Type*) [normed_add_comm_group E] [normed_space 𝕜 E] [complete_space E] (F : Type*) [normed_add_comm_group F] [normed_space 𝕜 F] [complete_space F] (G : Type*) [normed_add_comm_group G] [normed_space 𝕜 G] [complete_space G] := (left_fun : E → F) (left_deriv : E →L[𝕜] F) (right_fun : E → G) (right_deriv : E →L[𝕜] G) (pt : E) (left_has_deriv : has_strict_fderiv_at left_fun left_deriv pt) (right_has_deriv : has_strict_fderiv_at right_fun right_deriv pt) (left_range : range left_deriv = ⊤) (right_range : range right_deriv = ⊤) (is_compl_ker : is_compl (ker left_deriv) (ker right_deriv)) namespace implicit_function_data variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [complete_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [complete_space F] {G : Type*} [normed_add_comm_group G] [normed_space 𝕜 G] [complete_space G] (φ : implicit_function_data 𝕜 E F G) /-- The function given by `x ↦ (left_fun x, right_fun x)`. -/ def prod_fun (x : E) : F × G := (φ.left_fun x, φ.right_fun x) @[simp] lemma prod_fun_apply (x : E) : φ.prod_fun x = (φ.left_fun x, φ.right_fun x) := rfl protected lemma has_strict_fderiv_at : has_strict_fderiv_at φ.prod_fun (φ.left_deriv.equiv_prod_of_surjective_of_is_compl φ.right_deriv φ.left_range φ.right_range φ.is_compl_ker : E →L[𝕜] F × G) φ.pt := φ.left_has_deriv.prod φ.right_has_deriv /-- Implicit function theorem. If `f : E → F` and `g : E → G` are two maps strictly differentiable at `a`, their derivatives `f'`, `g'` are surjective, and the kernels of these derivatives are complementary subspaces of `E`, then `x ↦ (f x, g x)` defines a local homeomorphism between `E` and `F × G`. In particular, `{x | f x = f a}` is locally homeomorphic to `G`. -/ def to_local_homeomorph : local_homeomorph E (F × G) := φ.has_strict_fderiv_at.to_local_homeomorph _ /-- Implicit function theorem. If `f : E → F` and `g : E → G` are two maps strictly differentiable at `a`, their derivatives `f'`, `g'` are surjective, and the kernels of these derivatives are complementary subspaces of `E`, then `implicit_function_of_is_compl_ker` is the unique (germ of a) map `φ : F → G → E` such that `f (φ y z) = y` and `g (φ y z) = z`. -/ def implicit_function : F → G → E := function.curry $ φ.to_local_homeomorph.symm @[simp] lemma to_local_homeomorph_coe : ⇑(φ.to_local_homeomorph) = φ.prod_fun := rfl lemma to_local_homeomorph_apply (x : E) : φ.to_local_homeomorph x = (φ.left_fun x, φ.right_fun x) := rfl lemma pt_mem_to_local_homeomorph_source : φ.pt ∈ φ.to_local_homeomorph.source := φ.has_strict_fderiv_at.mem_to_local_homeomorph_source lemma map_pt_mem_to_local_homeomorph_target : (φ.left_fun φ.pt, φ.right_fun φ.pt) ∈ φ.to_local_homeomorph.target := φ.to_local_homeomorph.map_source $ φ.pt_mem_to_local_homeomorph_source lemma prod_map_implicit_function : ∀ᶠ (p : F × G) in 𝓝 (φ.prod_fun φ.pt), φ.prod_fun (φ.implicit_function p.1 p.2) = p := φ.has_strict_fderiv_at.eventually_right_inverse.mono $ λ ⟨z, y⟩ h, h lemma left_map_implicit_function : ∀ᶠ (p : F × G) in 𝓝 (φ.prod_fun φ.pt), φ.left_fun (φ.implicit_function p.1 p.2) = p.1 := φ.prod_map_implicit_function.mono $ λ z, congr_arg prod.fst lemma right_map_implicit_function : ∀ᶠ (p : F × G) in 𝓝 (φ.prod_fun φ.pt), φ.right_fun (φ.implicit_function p.1 p.2) = p.2 := φ.prod_map_implicit_function.mono $ λ z, congr_arg prod.snd lemma implicit_function_apply_image : ∀ᶠ x in 𝓝 φ.pt, φ.implicit_function (φ.left_fun x) (φ.right_fun x) = x := φ.has_strict_fderiv_at.eventually_left_inverse lemma map_nhds_eq : map φ.left_fun (𝓝 φ.pt) = 𝓝 (φ.left_fun φ.pt) := show map (prod.fst ∘ φ.prod_fun) (𝓝 φ.pt) = 𝓝 (φ.prod_fun φ.pt).1, by rw [← map_map, φ.has_strict_fderiv_at.map_nhds_eq_of_equiv, map_fst_nhds] lemma implicit_function_has_strict_fderiv_at (g'inv : G →L[𝕜] E) (hg'inv : φ.right_deriv.comp g'inv = continuous_linear_map.id 𝕜 G) (hg'invf : φ.left_deriv.comp g'inv = 0) : has_strict_fderiv_at (φ.implicit_function (φ.left_fun φ.pt)) g'inv (φ.right_fun φ.pt) := begin have := φ.has_strict_fderiv_at.to_local_inverse, simp only [prod_fun] at this, convert this.comp (φ.right_fun φ.pt) ((has_strict_fderiv_at_const _ _).prod (has_strict_fderiv_at_id _)), simp only [continuous_linear_map.ext_iff, continuous_linear_map.coe_comp', function.comp_app] at hg'inv hg'invf ⊢, simp [continuous_linear_equiv.eq_symm_apply, *] end end implicit_function_data namespace has_strict_fderiv_at section complemented /-! ### Case of a complemented kernel In this section we prove the following version of the implicit function theorem. Consider a map `f : E → F` and a point `a : E` such that `f` is strictly differentiable at `a`, its derivative `f'` is surjective and the kernel of `f'` is a complemented subspace of `E` (i.e., it has a closed complementary subspace). Then there exists a function `φ : F → ker f' → E` such that for `(y, z)` close to `(f a, 0)` we have `f (φ y z) = y` and the derivative of `φ (f a)` at zero is the embedding `ker f' → E`. Note that a map with these properties is not unique. E.g., different choices of a subspace complementary to `ker f'` lead to different maps `φ`. -/ variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [complete_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [complete_space F] {f : E → F} {f' : E →L[𝕜] F} {a : E} section defs variables (f f') /-- Data used to apply the generic implicit function theorem to the case of a strictly differentiable map such that its derivative is surjective and has a complemented kernel. -/ @[simp] def implicit_function_data_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : implicit_function_data 𝕜 E F (ker f') := { left_fun := f, left_deriv := f', right_fun := λ x, classical.some hker (x - a), right_deriv := classical.some hker, pt := a, left_has_deriv := hf, right_has_deriv := (classical.some hker).has_strict_fderiv_at.comp a ((has_strict_fderiv_at_id a).sub_const a), left_range := hf', right_range := linear_map.range_eq_of_proj (classical.some_spec hker), is_compl_ker := linear_map.is_compl_of_proj (classical.some_spec hker) } /-- A local homeomorphism between `E` and `F × f'.ker` sending level surfaces of `f` to vertical subspaces. -/ def implicit_to_local_homeomorph_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : local_homeomorph E (F × (ker f')) := (implicit_function_data_of_complemented f f' hf hf' hker).to_local_homeomorph /-- Implicit function `g` defined by `f (g z y) = z`. -/ def implicit_function_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : F → (ker f') → E := (implicit_function_data_of_complemented f f' hf hf' hker).implicit_function end defs @[simp] lemma implicit_to_local_homeomorph_of_complemented_fst (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) (x : E) : (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker x).fst = f x := rfl lemma implicit_to_local_homeomorph_of_complemented_apply (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) (y : E) : hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker y = (f y, classical.some hker (y - a)) := rfl @[simp] lemma implicit_to_local_homeomorph_of_complemented_apply_ker (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) (y : ker f') : hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker (y + a) = (f (y + a), y) := by simp only [implicit_to_local_homeomorph_of_complemented_apply, add_sub_cancel, classical.some_spec hker] @[simp] lemma implicit_to_local_homeomorph_of_complemented_self (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker a = (f a, 0) := by simp [hf.implicit_to_local_homeomorph_of_complemented_apply] lemma mem_implicit_to_local_homeomorph_of_complemented_source (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : a ∈ (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).source := mem_to_local_homeomorph_source _ lemma mem_implicit_to_local_homeomorph_of_complemented_target (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : (f a, (0 : ker f')) ∈ (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).target := by simpa only [implicit_to_local_homeomorph_of_complemented_self] using ((hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).map_source $ (hf.mem_implicit_to_local_homeomorph_of_complemented_source hf' hker)) /-- `implicit_function_of_complemented` sends `(z, y)` to a point in `f ⁻¹' z`. -/ lemma map_implicit_function_of_complemented_eq (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : ∀ᶠ (p : F × (ker f')) in 𝓝 (f a, 0), f (hf.implicit_function_of_complemented f f' hf' hker p.1 p.2) = p.1 := ((hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).eventually_right_inverse $ hf.mem_implicit_to_local_homeomorph_of_complemented_target hf' hker).mono $ λ ⟨z, y⟩ h, congr_arg prod.fst h /-- Any point in some neighborhood of `a` can be represented as `implicit_function` of some point. -/ lemma eq_implicit_function_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : ∀ᶠ x in 𝓝 a, hf.implicit_function_of_complemented f f' hf' hker (f x) (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker x).snd = x := (implicit_function_data_of_complemented f f' hf hf' hker).implicit_function_apply_image @[simp] lemma implicit_function_of_complemented_apply_image (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : hf.implicit_function_of_complemented f f' hf' hker (f a) 0 = a := begin convert (hf.implicit_to_local_homeomorph_of_complemented f f' hf' hker).left_inv (hf.mem_implicit_to_local_homeomorph_of_complemented_source hf' hker), exact congr_arg prod.snd (hf.implicit_to_local_homeomorph_of_complemented_self hf' hker).symm end lemma to_implicit_function_of_complemented (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (hker : (ker f').closed_complemented) : has_strict_fderiv_at (hf.implicit_function_of_complemented f f' hf' hker (f a)) (ker f').subtypeL 0 := begin convert (implicit_function_data_of_complemented f f' hf hf' hker).implicit_function_has_strict_fderiv_at (ker f').subtypeL _ _, swap, { ext, simp only [classical.some_spec hker, implicit_function_data_of_complemented, continuous_linear_map.coe_comp', submodule.coe_subtypeL', submodule.coe_subtype, function.comp_app, continuous_linear_map.coe_id', id.def] }, swap, { ext, simp only [continuous_linear_map.coe_comp', submodule.coe_subtypeL', submodule.coe_subtype, function.comp_app, linear_map.map_coe_ker, continuous_linear_map.zero_apply] }, simp only [implicit_function_data_of_complemented, map_sub, sub_self], end end complemented /-! ### Finite dimensional case In this section we prove the following version of the implicit function theorem. Consider a map `f : E → F` from a Banach normed space to a finite dimensional space. Take a point `a : E` such that `f` is strictly differentiable at `a` and its derivative `f'` is surjective. Then there exists a function `φ : F → ker f' → E` such that for `(y, z)` close to `(f a, 0)` we have `f (φ y z) = y` and the derivative of `φ (f a)` at zero is the embedding `ker f' → E`. This version deduces that `ker f'` is a complemented subspace from the fact that `F` is a finite dimensional space, then applies the previous version. Note that a map with these properties is not unique. E.g., different choices of a subspace complementary to `ker f'` lead to different maps `φ`. -/ section finite_dimensional variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [complete_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [finite_dimensional 𝕜 F] (f : E → F) (f' : E →L[𝕜] F) {a : E} /-- Given a map `f : E → F` to a finite dimensional space with a surjective derivative `f'`, returns a local homeomorphism between `E` and `F × ker f'`. -/ def implicit_to_local_homeomorph (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : local_homeomorph E (F × (ker f')) := by haveI := finite_dimensional.complete 𝕜 F; exact hf.implicit_to_local_homeomorph_of_complemented f f' hf' f'.ker_closed_complemented_of_finite_dimensional_range /-- Implicit function `g` defined by `f (g z y) = z`. -/ def implicit_function (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : F → (ker f') → E := function.curry $ (hf.implicit_to_local_homeomorph f f' hf').symm variables {f f'} @[simp] lemma implicit_to_local_homeomorph_fst (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (x : E) : (hf.implicit_to_local_homeomorph f f' hf' x).fst = f x := rfl @[simp] lemma implicit_to_local_homeomorph_apply_ker (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) (y : ker f') : hf.implicit_to_local_homeomorph f f' hf' (y + a) = (f (y + a), y) := by apply implicit_to_local_homeomorph_of_complemented_apply_ker @[simp] lemma implicit_to_local_homeomorph_self (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : hf.implicit_to_local_homeomorph f f' hf' a = (f a, 0) := by apply implicit_to_local_homeomorph_of_complemented_self lemma mem_implicit_to_local_homeomorph_source (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : a ∈ (hf.implicit_to_local_homeomorph f f' hf').source := mem_to_local_homeomorph_source _ lemma mem_implicit_to_local_homeomorph_target (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : (f a, (0 : ker f')) ∈ (hf.implicit_to_local_homeomorph f f' hf').target := by apply mem_implicit_to_local_homeomorph_of_complemented_target lemma tendsto_implicit_function (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) {α : Type*} {l : filter α} {g₁ : α → F} {g₂ : α → ker f'} (h₁ : tendsto g₁ l (𝓝 $ f a)) (h₂ : tendsto g₂ l (𝓝 0)) : tendsto (λ t, hf.implicit_function f f' hf' (g₁ t) (g₂ t)) l (𝓝 a) := begin refine ((hf.implicit_to_local_homeomorph f f' hf').tendsto_symm (hf.mem_implicit_to_local_homeomorph_source hf')).comp _, rw [implicit_to_local_homeomorph_self], exact h₁.prod_mk_nhds h₂ end alias tendsto_implicit_function ← _root_.filter.tendsto.implicit_function /-- `implicit_function` sends `(z, y)` to a point in `f ⁻¹' z`. -/ lemma map_implicit_function_eq (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : ∀ᶠ (p : F × (ker f')) in 𝓝 (f a, 0), f (hf.implicit_function f f' hf' p.1 p.2) = p.1 := by apply map_implicit_function_of_complemented_eq @[simp] lemma implicit_function_apply_image (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : hf.implicit_function f f' hf' (f a) 0 = a := by apply implicit_function_of_complemented_apply_image /-- Any point in some neighborhood of `a` can be represented as `implicit_function` of some point. -/ lemma eq_implicit_function (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : ∀ᶠ x in 𝓝 a, hf.implicit_function f f' hf' (f x) (hf.implicit_to_local_homeomorph f f' hf' x).snd = x := by apply eq_implicit_function_of_complemented lemma to_implicit_function (hf : has_strict_fderiv_at f f' a) (hf' : range f' = ⊤) : has_strict_fderiv_at (hf.implicit_function f f' hf' (f a)) (ker f').subtypeL 0 := by apply to_implicit_function_of_complemented end finite_dimensional end has_strict_fderiv_at
600b9d9f6740d18b623fc6621b3daa774ce2fdf2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/pplevel.lean
06bc3ba33c84284a6b6fa248123250802f8e329d
[ "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
180
lean
universe u v w set_option pp.universes true #check Type (max u v w) #check Type u #check @id.{max u v w} #check Monad.{max u v, w+1} #check Type (max (u+1) w (v+2)) #check Type _
2dcd279521be4efe0d09e57d05a2bb13d98d1cc9
92b50235facfbc08dfe7f334827d47281471333b
/hott/types/hprop_trunc.hlean
44060c3d3d436934e423b6d2b5ebd495cba2ef6f
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
1,793
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Proof of the theorem that (is_trunc n A) is a mere proposition We prove this here to avoid circular dependency of files We want to use this in .equiv; .equiv is imported by .function and .function is imported by .trunc -/ import .pi open equiv sigma sigma.ops eq function pi namespace is_trunc definition is_contr.sigma_char (A : Type) : (Σ (center : A), Π (a : A), center = a) ≃ (is_contr A) := begin fapply equiv.MK, { intro S, exact (is_contr.mk S.1 S.2)}, { intro H, cases H with H', cases H' with ce co, exact ⟨ce, co⟩}, { intro H, cases H with H', cases H' with ce co, exact idp}, { intro S, cases S, apply idp} end definition is_trunc.pi_char (n : trunc_index) (A : Type) : (Π (x y : A), is_trunc n (x = y)) ≃ (is_trunc (n .+1) A) := begin fapply equiv.MK, { intro H, apply is_trunc_succ_intro}, { intro H x y, apply is_trunc_eq}, { intro H, cases H, apply idp}, { intro P, apply eq_of_homotopy, intro a, apply eq_of_homotopy, intro b, esimp [is_trunc_eq], esimp[compose,is_trunc_succ_intro], generalize (P a b), intro H, cases H, apply idp}, end definition is_hprop_is_trunc [instance] (n : trunc_index) : Π (A : Type), is_hprop (is_trunc n A) := begin induction n, { intro A, apply is_trunc_is_equiv_closed, { apply equiv.to_is_equiv, apply is_contr.sigma_char}, apply is_hprop.mk, intros, fapply sigma_eq, apply x.2, apply is_hprop.elimo}, { intro A, apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv, apply is_trunc.pi_char}, end end is_trunc
042bd55c1e22e8082a3c916b1aff3940af2c4e16
32317185abf7e7c963f4c67c190aec61af6b3628
/library/theories/combinatorics/choose.lean
464de0efc87d2d171921d38647ba56ef7382125b
[ "Apache-2.0" ]
permissive
Andrew-Zipperer-unorganized/lean
198a2317f21198cd8d26e7085e484b86277f17f7
dcb35008e1474a0abebe632b1dced120e5f8c009
refs/heads/master
1,622,526,520,945
1,453,576,559,000
1,454,612,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,528
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Binomial coefficients, "n choose k". -/ import data.nat.div data.nat.fact data.finset open decidable namespace nat /- choose -/ definition choose : ℕ → ℕ → ℕ | 0 0 := 1 | 0 (succ k) := 0 | (succ n) 0 := 1 | (succ n) (succ k) := choose n (succ k) + choose n k theorem choose_zero_right (n : ℕ) : choose n 0 = 1 := nat.cases_on n rfl (take m, rfl) theorem choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl theorem choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n (succ k) + choose n k := rfl theorem choose_eq_zero_of_lt {n : ℕ} : ∀{k : ℕ}, n < k → choose n k = 0 := nat.induction_on n (take k, assume H : 0 < k, obtain k' (H : k = succ k'), from exists_eq_succ_of_pos H, by rewrite H) (take n', assume IH: ∀ k, n' < k → choose n' k = 0, take k, suppose succ n' < k, obtain k' (keq : k = succ k'), from exists_eq_succ_of_lt this, assert n' < k', by rewrite keq at this; apply lt_of_succ_lt_succ this, by rewrite [keq, choose_succ_succ, IH _ this, IH _ (lt.trans this !lt_succ_self)]) theorem choose_self (n : ℕ) : choose n n = 1 := begin induction n with [n, ih], {apply rfl}, rewrite [choose_succ_succ, ih, choose_eq_zero_of_lt !lt_succ_self] end theorem choose_succ_self (n : ℕ) : choose (succ n) n = succ n := begin induction n with [n, ih], {apply rfl}, rewrite [choose_succ_succ, ih, choose_self, add.comm] end theorem choose_one_right (n : ℕ) : choose n 1 = n := begin induction n with [n, ih], {apply rfl}, change choose (succ n) (succ 0) = succ n, rewrite [choose_succ_succ, ih, choose_zero_right] end theorem choose_pos {n : ℕ} : ∀ {k : ℕ}, k ≤ n → choose n k > 0 := begin induction n with [n, ih], {intros [k, H], have k = 0, from eq_of_le_of_ge H !zero_le, subst k, rewrite choose_zero_right; apply zero_lt_one}, intro k, cases k with k, {intros, rewrite [choose_zero_right], apply zero_lt_one}, suppose succ k ≤ succ n, assert k ≤ n, from le_of_succ_le_succ this, by rewrite [choose_succ_succ]; apply add_pos_right (ih this) end -- A key identity. The proof is subtle. theorem succ_mul_choose_eq (n : ℕ) : ∀ k, succ n * (choose n k) = choose (succ n) (succ k) * succ k := begin induction n with [n, ih], {intro k, cases k with k', {rewrite [*choose_self, one_mul, mul_one]}, {have H : 1 < succ (succ k'), from succ_lt_succ !zero_lt_succ, krewrite [one_mul, choose_zero_succ, choose_eq_zero_of_lt H, zero_mul]}}, intro k, cases k with k', {rewrite [choose_zero_right, choose_one_right]}, rewrite [choose_succ_succ (succ n), right_distrib, -ih (succ k')], rewrite [choose_succ_succ at {1}, left_distrib, *succ_mul (succ n), mul_succ, -ih k'], rewrite [*add.assoc, add.left_comm (choose n _)] end theorem choose_mul_fact_mul_fact {n : ℕ} : ∀ {k : ℕ}, k ≤ n → choose n k * fact k * fact (n - k) = fact n := begin induction n using nat.strong_induction_on with [n, ih], cases n with n, {intro k H, have k = 0, from eq_zero_of_le_zero H, rewrite this}, intro k, intro H, -- k ≤ n, cases k with k, {rewrite [choose_zero_right, fact_zero, *one_mul]}, have k ≤ n, from le_of_succ_le_succ H, show choose (succ n) (succ k) * fact (succ k) * fact (succ n - succ k) = fact (succ n), from begin rewrite [succ_sub_succ, fact_succ, -mul.assoc, -succ_mul_choose_eq], rewrite [fact_succ n, -ih n !lt_succ_self this, *mul.assoc] end end theorem choose_def_alt {n k : ℕ} (H : k ≤ n) : choose n k = fact n / (fact k * fact (n -k)) := eq.symm (nat.div_eq_of_eq_mul_left (mul_pos !fact_pos !fact_pos) (by rewrite [-mul.assoc, choose_mul_fact_mul_fact H])) theorem fact_mul_fact_dvd_fact {n k : ℕ} (H : k ≤ n) : fact k * fact (n - k) ∣ fact n := by rewrite [-choose_mul_fact_mul_fact H, mul.assoc]; apply dvd_mul_left open finset /- the number of subsets of s of size k is n choose k -/ section card_subsets variables {A : Type} [deceqA : decidable_eq A] include deceqA private theorem aux₀ (s : finset A) : {t ∈ powerset s | card t = 0} = '{∅} := ext (take t, iff.intro (assume H, assert t = ∅, from eq_empty_of_card_eq_zero (of_mem_sep H), show t ∈ '{ ∅ }, by rewrite [this, mem_singleton_iff]) (assume H, assert t = ∅, by rewrite mem_singleton_iff at H; assumption, by substvars; exact mem_sep_of_mem !empty_mem_powerset rfl)) private theorem aux₁ (k : ℕ) : {t ∈ powerset (∅ : finset A) | card t = succ k} = ∅ := eq_empty_of_forall_not_mem (take t, assume H, assert t ∈ powerset ∅, from mem_of_mem_sep H, assert t = ∅, by rewrite [powerset_empty at this, mem_singleton_iff at this]; assumption, have card (∅ : finset A) = succ k, by rewrite -this; apply of_mem_sep H, nat.no_confusion this) private theorem aux₂ {a : A} {s t : finset A} (anins : a ∉ s) (tpows : t ∈ powerset s) : a ∉ t := suppose a ∈ t, have a ∈ s, from mem_of_subset_of_mem (subset_of_mem_powerset tpows) this, anins this private theorem aux₃ {a : A} {s t : finset A} (anins : a ∉ s) (k : ℕ) : t ∈ (insert a) ' (powerset s) ∧ card t = succ k ↔ t ∈ (insert a) ' {t' ∈ powerset s | card t' = k} := iff.intro (assume H, obtain H' cardt, from H, obtain t' [(t'pows : t' ∈ powerset s) (teq : insert a t' = t)], from exists_of_mem_image H', assert aint : a ∈ t, by rewrite -teq; apply mem_insert, assert anint' : a ∉ t', from (assume aint', have a ∈ s, from mem_of_subset_of_mem (subset_of_mem_powerset t'pows) aint', anins this), assert t' = erase a t, by rewrite [-teq, erase_insert (aux₂ anins t'pows)], have card t' = k, by rewrite [this, card_erase_of_mem aint, cardt], mem_image (mem_sep_of_mem t'pows this) teq) (assume H, obtain t' [Ht' (teq : insert a t' = t)], from exists_of_mem_image H, assert t'pows : t' ∈ powerset s, from mem_of_mem_sep Ht', assert cardt' : card t' = k, from of_mem_sep Ht', and.intro (show t ∈ (insert a) ' (powerset s), from mem_image t'pows teq) (show card t = succ k, by rewrite [-teq, card_insert_of_not_mem (aux₂ anins t'pows), cardt'])) private theorem aux₄ {a : A} {s : finset A} (anins : a ∉ s) (k : ℕ) : {t ∈ powerset (insert a s)| card t = succ k} = {t ∈ powerset s | card t = succ k} ∪ (insert a) ' {t ∈ powerset s | card t = k} := begin apply ext, intro t, rewrite [powerset_insert anins, mem_union_iff, *mem_sep_iff, mem_union_iff, and.right_distrib, aux₃ anins] end private theorem aux₅ {a : A} {s : finset A} (anins : a ∉ s) (k : ℕ) : {t ∈ powerset s | card t = succ k} ∩ (insert a) ' {t ∈ powerset s | card t = k} = ∅ := inter_eq_empty (take t, assume Ht₁ Ht₂, have tpows : t ∈ powerset s, from mem_of_mem_sep Ht₁, have anint : a ∉ t, from aux₂ anins tpows, obtain t' [Ht' (teq : insert a t' = t)], from exists_of_mem_image Ht₂, have aint : a ∈ t, by rewrite -teq; apply mem_insert, show false, from anint aint) private theorem aux₆ {a : A} {s : finset A} (anins : a ∉ s) (k : ℕ) : card ((insert a) ' {t ∈ powerset s | card t = k}) = card {t ∈ powerset s | card t = k} := have set.inj_on (insert a) (ts {t ∈ powerset s| card t = k}), from take t₁ t₂, assume Ht₁ Ht₂, assume Heq : insert a t₁ = insert a t₂, have t₁ ∈ powerset s, from mem_of_mem_sep Ht₁, assert anint₁ : a ∉ t₁, from aux₂ anins this, have t₂ ∈ powerset s, from mem_of_mem_sep Ht₂, assert anint₂ : a ∉ t₂, from aux₂ anins this, calc t₁ = erase a (insert a t₁) : by rewrite (erase_insert anint₁) ... = erase a (insert a t₂) : Heq ... = t₂ : by rewrite (erase_insert anint₂), card_image_eq_of_inj_on this theorem card_subsets (s : finset A) : ∀k, card {t ∈ powerset s | card t = k} = choose (card s) k := begin induction s with a s anins ih, {intro k, cases k with k, {rewrite aux₀}, rewrite aux₁}, intro k, cases k with k, {rewrite [aux₀, choose_zero_right]}, rewrite [*(card_insert_of_not_mem anins), aux₄ anins, card_union_of_disjoint (aux₅ anins k), aux₆ anins k, *ih] end end card_subsets end nat
5cea39b798e37b89bc3b1d94a9a048a1a6cb64c4
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/geometry/manifold/local_invariant_properties.lean
7ad8c5f6bc848aecd0a1fab8ce3b4c5338fad8a0
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
25,432
lean
/- Copyright (c) 2020 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 geometry.manifold.smooth_manifold_with_corners /-! # Local properties invariant under a groupoid We study properties of a triple `(g, s, x)` where `g` is a function between two spaces `H` and `H'`, `s` is a subset of `H` and `x` is a point of `H`. Our goal is to register how such a property should behave to make sense in charted spaces modelled on `H` and `H'`. The main examples we have in mind are the properties "`g` is differentiable at `x` within `s`", or "`g` is smooth at `x` within `s`". We want to develop general results that, when applied in these specific situations, say that the notion of smooth function in a manifold behaves well under restriction, intersection, is local, and so on. ## Main definitions * `local_invariant_prop G G' P` says that a property `P` of a triple `(g, s, x)` is local, and invariant under composition by elements of the groupoids `G` and `G'` of `H` and `H'` respectively. * `charted_space.lift_prop_within_at` (resp. `lift_prop_at`, `lift_prop_on` and `lift_prop`): given a property `P` of `(g, s, x)` where `g : H → H'`, define the corresponding property for functions `M → M'` where `M` and `M'` are charted spaces modelled respectively on `H` and `H'`. We define these properties within a set at a point, or at a point, or on a set, or in the whole space. This lifting process (obtained by restricting to suitable chart domains) can always be done, but it only behaves well under locality and invariance assumptions. Given `hG : local_invariant_prop G G' P`, we deduce many properties of the lifted property on the charted spaces. For instance, `hG.lift_prop_within_at_inter` says that `P g s x` is equivalent to `P g (s ∩ t) x` whenever `t` is a neighborhood of `x`. ## Implementation notes We do not use dot notation for properties of the lifted property. For instance, we have `hG.lift_prop_within_at_congr` saying that if `lift_prop_within_at P g s x` holds, and `g` and `g'` coincide on `s`, then `lift_prop_within_at P g' s x` holds. We can't call it `lift_prop_within_at.congr` as it is in the namespace associated to `local_invariant_prop`, not in the one for `lift_prop_within_at`. -/ noncomputable theory open_locale classical manifold topological_space open set variables {H : Type*} {M : Type*} [topological_space H] [topological_space M] [charted_space H M] {H' : Type*} {M' : Type*} [topological_space H'] [topological_space M'] [charted_space H' M'] namespace structure_groupoid variables (G : structure_groupoid H) (G' : structure_groupoid H') /-- Structure recording good behavior of a property of a triple `(f, s, x)` where `f` is a function, `s` a set and `x` a point. Good behavior here means locality and invariance under given groupoids (both in the source and in the target). Given such a good behavior, the lift of this property to charted spaces admitting these groupoids will inherit the good behavior. -/ structure local_invariant_prop (P : (H → H') → (set H) → H → Prop) : Prop := (is_local : ∀ {s x u} {f : H → H'}, is_open u → x ∈ u → (P f s x ↔ P f (s ∩ u) x)) (right_invariance : ∀ {s x f} {e : local_homeomorph H H}, e ∈ G → x ∈ e.source → P f s x → P (f ∘ e.symm) (e.target ∩ e.symm ⁻¹' s) (e x)) (congr : ∀ {s x} {f g : H → H'}, (∀ y ∈ s, f y = g y) → (f x = g x) → P f s x → P g s x) (left_invariance : ∀ {s x f} {e' : local_homeomorph H' H'}, e' ∈ G' → s ⊆ f ⁻¹' (e'.source) → f x ∈ e'.source → P f s x → P (e' ∘ f) s x) end structure_groupoid /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property in a charted space, by requiring that it holds at the preferred chart at this point. (When the property is local and invariant, it will in fact hold using any chart, see `lift_prop_within_at_indep_chart`). We require continuity in the lifted property, as otherwise one single chart might fail to capture the behavior of the function. -/ def charted_space.lift_prop_within_at (P : (H → H') → set H → H → Prop) (f : M → M') (s : set M) (x : M) : Prop := continuous_within_at f s x ∧ P ((chart_at H' (f x)) ∘ f ∘ (chart_at H x).symm) ((chart_at H x).target ∩ (chart_at H x).symm ⁻¹' (s ∩ f ⁻¹' (chart_at H' (f x)).source)) (chart_at H x x) /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of functions on sets in a charted space, by requiring that it holds around each point of the set, in the preferred charts. -/ def charted_space.lift_prop_on (P : (H → H') → set H → H → Prop) (f : M → M') (s : set M) := ∀ x ∈ s, charted_space.lift_prop_within_at P f s x /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of a function at a point in a charted space, by requiring that it holds in the preferred chart. -/ def charted_space.lift_prop_at (P : (H → H') → set H → H → Prop) (f : M → M') (x : M) := charted_space.lift_prop_within_at P f univ x /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of a function in a charted space, by requiring that it holds in the preferred chart around every point. -/ def charted_space.lift_prop (P : (H → H') → set H → H → Prop) (f : M → M') := ∀ x, charted_space.lift_prop_at P f x open charted_space namespace structure_groupoid variables {G : structure_groupoid H} {G' : structure_groupoid H'} {e e' : local_homeomorph M H} {f f' : local_homeomorph M' H'} {P : (H → H') → set H → H → Prop} {g g' : M → M'} {s t : set M} {x : M} {Q : (H → H) → set H → H → Prop} lemma lift_prop_within_at_univ : lift_prop_within_at P g univ x ↔ lift_prop_at P g x := iff.rfl lemma lift_prop_on_univ : lift_prop_on P g univ ↔ lift_prop P g := by simp [lift_prop_on, lift_prop, lift_prop_at] namespace local_invariant_prop variable (hG : G.local_invariant_prop G' P) include hG /-- If a property of a germ of function `g` on a pointed set `(s, x)` is invariant under the structure groupoid (by composition in the source space and in the target space), then expressing it in charted spaces does not depend on the element of the maximal atlas one uses both in the source and in the target manifolds, provided they are defined around `x` and `g x` respectively, and provided `g` is continuous within `s` at `x` (otherwise, the local behavior of `g` at `x` can not be captured with a chart in the target). -/ lemma lift_prop_within_at_indep_chart_aux (he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source) (he' : e' ∈ G.maximal_atlas M) (xe' : x ∈ e'.source) (hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) (hf' : f' ∈ G'.maximal_atlas M') (xf' : g x ∈ f'.source) (hgs : continuous_within_at g s x) (h : P (f ∘ g ∘ e.symm) (e.target ∩ e.symm ⁻¹' (s ∩ g⁻¹' f.source)) (e x)) : P (f' ∘ g ∘ e'.symm) (e'.target ∩ e'.symm ⁻¹' (s ∩ g⁻¹' f'.source)) (e' x) := begin obtain ⟨o, o_open, xo, oe, oe', of, of'⟩ : ∃ (o : set M), is_open o ∧ x ∈ o ∧ o ⊆ e.source ∧ o ⊆ e'.source ∧ o ∩ s ⊆ g ⁻¹' f.source ∧ o ∩ s ⊆ g⁻¹' f'.to_local_equiv.source, { have : f.source ∩ f'.source ∈ 𝓝 (g x) := mem_nhds_sets (is_open_inter f.open_source f'.open_source) ⟨xf, xf'⟩, rcases mem_nhds_within.1 (hgs.preimage_mem_nhds_within this) with ⟨u, u_open, xu, hu⟩, refine ⟨u ∩ e.source ∩ e'.source, _, ⟨⟨xu, xe⟩, xe'⟩, _, _, _, _⟩, { exact is_open_inter (is_open_inter u_open e.open_source) e'.open_source }, { assume x hx, exact hx.1.2 }, { assume x hx, exact hx.2 }, { assume x hx, exact (hu ⟨hx.1.1.1, hx.2⟩).1 }, { assume x hx, exact (hu ⟨hx.1.1.1, hx.2⟩).2 } }, have A : P (f ∘ g ∘ e.symm) (e.target ∩ e.symm ⁻¹' (s ∩ g⁻¹' f.source) ∩ (e.target ∩ e.symm ⁻¹' o)) (e x), { apply (hG.is_local _ _).1 h, { exact e.continuous_on_symm.preimage_open_of_open e.open_target o_open }, { simp only [xe, xo] with mfld_simps} }, have B : P ((f.symm ≫ₕ f') ∘ (f ∘ g ∘ e.symm)) (e.target ∩ e.symm ⁻¹' (s ∩ g⁻¹' f.source) ∩ (e.target ∩ e.symm ⁻¹' o)) (e x), { refine hG.left_invariance (compatible_of_mem_maximal_atlas hf hf') (λ y hy, _) (by simp only [xe, xf, xf'] with mfld_simps) A, simp only with mfld_simps at hy, have : e.symm y ∈ o ∩ s, by simp only [hy] with mfld_simps, simpa only [hy] with mfld_simps using of' this }, have C : P (f' ∘ g ∘ e.symm) (e.target ∩ e.symm ⁻¹' (s ∩ g⁻¹' f.source) ∩ (e.target ∩ e.symm ⁻¹' o)) (e x), { refine hG.congr (λ y hy, _) (by simp only [xe, xf] with mfld_simps) B, simp only [local_homeomorph.coe_trans, function.comp_app], rw f.left_inv, apply of, simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, let w := e.symm ≫ₕ e', let ow := w.target ∩ w.symm ⁻¹' (e.target ∩ e.symm ⁻¹' (s ∩ g⁻¹' f.source) ∩ (e.target ∩ e.symm ⁻¹' o)), have wG : w ∈ G := compatible_of_mem_maximal_atlas he he', have D : P ((f' ∘ g ∘ e.symm) ∘ w.symm) ow (w (e x)) := hG.right_invariance wG (by simp only [w, xe, xe'] with mfld_simps) C, have E : P (f' ∘ g ∘ e'.symm) ow (w (e x)), { refine hG.congr _ (by simp only [xe, xe'] with mfld_simps) D, assume y hy, simp only with mfld_simps, rw e.left_inv, simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, have : w (e x) = e' x, by simp only [w, xe] with mfld_simps, rw this at E, have : ow = (e'.target ∩ e'.symm ⁻¹' (s ∩ g⁻¹' f'.source)) ∩ (w.target ∩ (e'.target ∩ e'.symm ⁻¹' o)), { ext y, split, { assume hy, have : e.symm (e ((e'.symm) y)) = e'.symm y, by { simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, simp only [this] with mfld_simps at hy, have : g (e'.symm y) ∈ f'.source, by { apply of', simp only [hy] with mfld_simps }, simp only [hy, this] with mfld_simps }, { assume hy, simp only with mfld_simps at hy, have : g (e'.symm y) ∈ f.source, by { apply of, simp only [hy] with mfld_simps }, simp only [this, hy] with mfld_simps } }, rw this at E, apply (hG.is_local _ _).2 E, { exact is_open_inter w.open_target (e'.continuous_on_symm.preimage_open_of_open e'.open_target o_open) }, { simp only [xe', xe, xo] with mfld_simps }, end lemma lift_prop_within_at_indep_chart [has_groupoid M G] [has_groupoid M' G'] (he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source) (hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) : lift_prop_within_at P g s x ↔ continuous_within_at g s x ∧ P (f ∘ g ∘ e.symm) (e.target ∩ e.symm ⁻¹' (s ∩ g⁻¹' f.source)) (e x) := ⟨λ H, ⟨H.1, hG.lift_prop_within_at_indep_chart_aux (chart_mem_maximal_atlas _ _) (mem_chart_source _ _) he xe (chart_mem_maximal_atlas _ _) (mem_chart_source _ _) hf xf H.1 H.2⟩, λ H, ⟨H.1, hG.lift_prop_within_at_indep_chart_aux he xe (chart_mem_maximal_atlas _ _) (mem_chart_source _ _) hf xf (chart_mem_maximal_atlas _ _) (mem_chart_source _ _) H.1 H.2⟩⟩ lemma lift_prop_on_indep_chart [has_groupoid M G] [has_groupoid M' G'] (he : e ∈ G.maximal_atlas M) (hf : f ∈ G'.maximal_atlas M') (h : lift_prop_on P g s) : ∀ y ∈ e.target ∩ e.symm ⁻¹' (s ∩ g ⁻¹' f.source), P (f ∘ g ∘ e.symm) (e.target ∩ e.symm ⁻¹' (s ∩ g ⁻¹' f.source)) y := begin assume y hy, simp only with mfld_simps at hy, have : e.symm y ∈ s, by simp only [hy] with mfld_simps, convert ((hG.lift_prop_within_at_indep_chart he _ hf _).1 (h _ this)).2, repeat { simp only [hy] with mfld_simps }, end lemma lift_prop_within_at_inter' (ht : t ∈ nhds_within x s) : lift_prop_within_at P g (s ∩ t) x ↔ lift_prop_within_at P g s x := begin by_cases hcont : ¬ (continuous_within_at g s x), { have : ¬ (continuous_within_at g (s ∩ t) x), by rwa [continuous_within_at_inter' ht], simp only [lift_prop_within_at, hcont, this, false_and] }, push_neg at hcont, have A : continuous_within_at g (s ∩ t) x, by rwa [continuous_within_at_inter' ht], obtain ⟨o, o_open, xo, oc, oc', ost⟩ : ∃ (o : set M), is_open o ∧ x ∈ o ∧ o ⊆ (chart_at H x).source ∧ o ∩ s ⊆ g ⁻¹' (chart_at H' (g x)).source ∧ o ∩ s ⊆ t, { rcases mem_nhds_within.1 ht with ⟨u, u_open, xu, ust⟩, have : (chart_at H' (g x)).source ∈ 𝓝 (g x) := mem_nhds_sets ((chart_at H' (g x))).open_source (mem_chart_source H' (g x)), rcases mem_nhds_within.1 (hcont.preimage_mem_nhds_within this) with ⟨v, v_open, xv, hv⟩, refine ⟨u ∩ v ∩ (chart_at H x).source, _, ⟨⟨xu, xv⟩, mem_chart_source _ _⟩, _, _, _⟩, { exact is_open_inter (is_open_inter u_open v_open) (chart_at H x).open_source }, { assume y hy, exact hy.2 }, { assume y hy, exact hv ⟨hy.1.1.2, hy.2⟩ }, { assume y hy, exact ust ⟨hy.1.1.1, hy.2⟩ } }, simp only [lift_prop_within_at, A, hcont, true_and, preimage_inter], have B : is_open ((chart_at H x).target ∩ (chart_at H x).symm⁻¹' o) := (chart_at H x).preimage_open_of_open_symm o_open, have C : (chart_at H x) x ∈ (chart_at H x).target ∩ (chart_at H x).symm⁻¹' o, by simp only [xo] with mfld_simps, conv_lhs { rw hG.is_local B C }, conv_rhs { rw hG.is_local B C }, congr' 2, have : ∀ y, y ∈ o ∩ s → y ∈ t := ost, mfld_set_tac end lemma lift_prop_within_at_inter (ht : t ∈ 𝓝 x) : lift_prop_within_at P g (s ∩ t) x ↔ lift_prop_within_at P g s x := hG.lift_prop_within_at_inter' (mem_nhds_within_of_mem_nhds ht) lemma lift_prop_at_of_lift_prop_within_at (h : lift_prop_within_at P g s x) (hs : s ∈ 𝓝 x) : lift_prop_at P g x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, hG.lift_prop_within_at_inter hs] at h, end lemma lift_prop_within_at_of_lift_prop_at_of_mem_nhds (h : lift_prop_at P g x) (hs : s ∈ 𝓝 x) : lift_prop_within_at P g s x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, hG.lift_prop_within_at_inter hs], end lemma lift_prop_on_of_locally_lift_prop_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ lift_prop_on P g (s ∩ u)) : lift_prop_on P g s := begin assume x hx, rcases h x hx with ⟨u, u_open, xu, hu⟩, have := hu x ⟨hx, xu⟩, rwa hG.lift_prop_within_at_inter at this, exact mem_nhds_sets u_open xu, end lemma lift_prop_of_locally_lift_prop_on (h : ∀x, ∃u, is_open u ∧ x ∈ u ∧ lift_prop_on P g u) : lift_prop P g := begin rw ← lift_prop_on_univ, apply hG.lift_prop_on_of_locally_lift_prop_on (λ x hx, _), simp [h x], end lemma lift_prop_within_at_congr (h : lift_prop_within_at P g s x) (h₁ : ∀ y ∈ s, g' y = g y) (hx : g' x = g x) : lift_prop_within_at P g' s x := begin refine ⟨h.1.congr h₁ hx, _⟩, have A : s ∩ g' ⁻¹' (chart_at H' (g' x)).source = s ∩ g ⁻¹' (chart_at H' (g' x)).source, { ext y, split, { assume hy, simp only with mfld_simps at hy, simp only [hy, ← h₁ _ hy.1] with mfld_simps }, { assume hy, simp only with mfld_simps at hy, simp only [hy, h₁ _ hy.1] with mfld_simps } }, have := h.2, rw [← hx, ← A] at this, convert hG.congr _ _ this using 2, { assume y hy, simp only with mfld_simps at hy, have : (chart_at H x).symm y ∈ s, by simp only [hy], simp only [hy, h₁ _ this] with mfld_simps }, { simp only [hx] with mfld_simps } end lemma lift_prop_within_at_congr_iff (h₁ : ∀ y ∈ s, g' y = g y) (hx : g' x = g x) : lift_prop_within_at P g' s x ↔ lift_prop_within_at P g s x := ⟨λ h, hG.lift_prop_within_at_congr h (λ y hy, (h₁ y hy).symm) hx.symm, λ h, hG.lift_prop_within_at_congr h h₁ hx⟩ lemma lift_prop_within_at_congr_of_eventually_eq (h : lift_prop_within_at P g s x) (h₁ : g' =ᶠ[nhds_within x s] g) (hx : g' x = g x) : lift_prop_within_at P g' s x := begin rcases h₁.exists_mem with ⟨t, t_nhd, ht⟩, rw ← hG.lift_prop_within_at_inter' t_nhd at h ⊢, exact hG.lift_prop_within_at_congr h (λ y hy, ht _ hy.2) hx end lemma lift_prop_within_at_congr_iff_of_eventually_eq (h₁ : g' =ᶠ[nhds_within x s] g) (hx : g' x = g x) : lift_prop_within_at P g' s x ↔ lift_prop_within_at P g s x := ⟨λ h, hG.lift_prop_within_at_congr_of_eventually_eq h h₁.symm hx.symm, λ h, hG.lift_prop_within_at_congr_of_eventually_eq h h₁ hx⟩ lemma lift_prop_at_congr_of_eventually_eq (h : lift_prop_at P g x) (h₁ : g' =ᶠ[𝓝 x] g) : lift_prop_at P g' x := begin apply hG.lift_prop_within_at_congr_of_eventually_eq h _ h₁.eq_of_nhds, convert h₁, rw nhds_within_univ end lemma lift_prop_at_congr_iff_of_eventually_eq (h₁ : g' =ᶠ[𝓝 x] g) : lift_prop_at P g' x ↔ lift_prop_at P g x := ⟨λ h, hG.lift_prop_at_congr_of_eventually_eq h h₁.symm, λ h, hG.lift_prop_at_congr_of_eventually_eq h h₁⟩ lemma lift_prop_on_congr (h : lift_prop_on P g s) (h₁ : ∀ y ∈ s, g' y = g y) : lift_prop_on P g' s := λ x hx, hG.lift_prop_within_at_congr (h x hx) h₁ (h₁ x hx) lemma lift_prop_on_congr_iff (h₁ : ∀ y ∈ s, g' y = g y) : lift_prop_on P g' s ↔ lift_prop_on P g s := ⟨λ h, hG.lift_prop_on_congr h (λ y hy, (h₁ y hy).symm), λ h, hG.lift_prop_on_congr h h₁⟩ omit hG lemma lift_prop_within_at_mono (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop_within_at P g t x) (hst : s ⊆ t) : lift_prop_within_at P g s x := begin refine ⟨h.1.mono hst, _⟩, apply mono (λ y hy, _) h.2, simp only with mfld_simps at hy, simp only [hy, hst _] with mfld_simps, end lemma lift_prop_within_at_of_lift_prop_at (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop_at P g x) : lift_prop_within_at P g s x := begin rw ← lift_prop_within_at_univ at h, exact lift_prop_within_at_mono mono h (subset_univ _), end lemma lift_prop_on_mono (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop_on P g t) (hst : s ⊆ t) : lift_prop_on P g s := λ x hx, lift_prop_within_at_mono mono (h x (hst hx)) hst lemma lift_prop_on_of_lift_prop (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop P g) : lift_prop_on P g s := begin rw ← lift_prop_on_univ at h, exact lift_prop_on_mono mono h (subset_univ _) end lemma lift_prop_at_of_mem_maximal_atlas [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) (hx : x ∈ e.source) : lift_prop_at Q e x := begin suffices h : Q (e ∘ e.symm) e.target (e x), { rw [lift_prop_at, hG.lift_prop_within_at_indep_chart he hx G.id_mem_maximal_atlas (mem_univ _)], refine ⟨(e.continuous_at hx).continuous_within_at, _⟩, simpa only with mfld_simps }, have A : Q id e.target (e x), { have : e x ∈ e.target, by simp only [hx] with mfld_simps, simpa only with mfld_simps using (hG.is_local e.open_target this).1 (hQ (e x)) }, apply hG.congr _ _ A; simp only [hx] with mfld_simps {contextual := tt} end lemma lift_prop_on_of_mem_maximal_atlas [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) : lift_prop_on Q e e.source := begin assume x hx, apply hG.lift_prop_within_at_of_lift_prop_at_of_mem_nhds (hG.lift_prop_at_of_mem_maximal_atlas hQ he hx), apply mem_nhds_sets e.open_source hx, end lemma lift_prop_at_symm_of_mem_maximal_atlas [has_groupoid M G] {x : H} (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) (hx : x ∈ e.target) : lift_prop_at Q e.symm x := begin suffices h : Q (e ∘ e.symm) e.target x, { have A : e.symm ⁻¹' e.source ∩ e.target = e.target, by mfld_set_tac, have : e.symm x ∈ e.source, by simp only [hx] with mfld_simps, rw [lift_prop_at, hG.lift_prop_within_at_indep_chart G.id_mem_maximal_atlas (mem_univ _) he this], refine ⟨(e.symm.continuous_at hx).continuous_within_at, _⟩, simp only with mfld_simps, rwa [hG.is_local e.open_target hx, A] }, have A : Q id e.target x, by simpa only with mfld_simps using (hG.is_local e.open_target hx).1 (hQ x), apply hG.congr _ _ A; simp only [hx] with mfld_simps {contextual := tt} end lemma lift_prop_on_symm_of_mem_maximal_atlas [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) : lift_prop_on Q e.symm e.target := begin assume x hx, apply hG.lift_prop_within_at_of_lift_prop_at_of_mem_nhds (hG.lift_prop_at_symm_of_mem_maximal_atlas hQ he hx), apply mem_nhds_sets e.open_target hx, end lemma lift_prop_at_chart [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_at Q (chart_at H x) x := hG.lift_prop_at_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) (mem_chart_source H x) lemma lift_prop_on_chart [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_on Q (chart_at H x) (chart_at H x).source := hG.lift_prop_on_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) lemma lift_prop_at_chart_symm [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_at Q (chart_at H x).symm ((chart_at H x) x) := hG.lift_prop_at_symm_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) (by simp) lemma lift_prop_on_chart_symm [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_on Q (chart_at H x).symm (chart_at H x).target := hG.lift_prop_on_symm_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) lemma lift_prop_id (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop Q (id : M → M) := begin assume x, dsimp [lift_prop_at, lift_prop_within_at], refine ⟨continuous_within_at_id, _⟩, let t := ((chart_at H x).target ∩ (chart_at H x).symm ⁻¹' (chart_at H x).source), suffices H : Q id t ((chart_at H x) x), { simp only with mfld_simps, refine hG.congr (λ y hy, _) (by simp) H, simp only with mfld_simps at hy, simp only [hy] with mfld_simps }, have : t = univ ∩ (chart_at H x).target, by mfld_set_tac, rw this, exact (hG.is_local (chart_at H x).open_target (by simp)).1 (hQ _) end end local_invariant_prop section local_structomorph variables (G) open local_homeomorph /-- A function from a model space `H` to itself is a local structomorphism, with respect to a structure groupoid `G` for `H`, relative to a set `s` in `H`, if for all points `x` in the set, the function agrees with a `G`-structomorphism on `s` in a neighbourhood of `x`. -/ def is_local_structomorph_within_at (f : H → H) (s : set H) (x : H) : Prop := (x ∈ s) → ∃ (e : local_homeomorph H H), e ∈ G ∧ eq_on f e.to_fun (s ∩ e.source) ∧ x ∈ e.source /-- For a groupoid `G` which is `closed_under_restriction`, being a local structomorphism is a local invariant property. -/ lemma is_local_structomorph_within_at_local_invariant_prop [closed_under_restriction G] : local_invariant_prop G G (is_local_structomorph_within_at G) := { is_local := begin intros s x u f hu hux, split, { rintros h hx, rcases h hx.1 with ⟨e, heG, hef, hex⟩, have : s ∩ u ∩ e.source ⊆ s ∩ e.source := by mfld_set_tac, exact ⟨e, heG, hef.mono this, hex⟩ }, { rintros h hx, rcases h ⟨hx, hux⟩ with ⟨e, heG, hef, hex⟩, refine ⟨e.restr (interior u), _, _, _⟩, { exact closed_under_restriction' heG (is_open_interior) }, { have : s ∩ u ∩ e.source = s ∩ (e.source ∩ u) := by mfld_set_tac, simpa only [this, interior_interior, interior_eq_of_open hu] with mfld_simps using hef }, { simp only [*, interior_interior, interior_eq_of_open hu] with mfld_simps } } end, right_invariance := begin intros s x f e' he'G he'x h hx, have hxs : x ∈ s := by simpa only [e'.left_inv he'x] with mfld_simps using hx.2, rcases h hxs with ⟨e, heG, hef, hex⟩, refine ⟨e'.symm.trans e, G.trans (G.symm he'G) heG, _, _⟩, { intros y hy, simp only with mfld_simps at hy, simp only [hef ⟨hy.1.2, hy.2.2⟩] with mfld_simps }, { simp only [hex, he'x] with mfld_simps } end, congr := begin intros s x f g hfgs hfg' h hx, rcases h hx with ⟨e, heG, hef, hex⟩, refine ⟨e, heG, _, hex⟩, intros y hy, rw [← hef hy, hfgs y hy.1] end, left_invariance := begin intros s x f e' he'G he' hfx h hx, rcases h hx with ⟨e, heG, hef, hex⟩, refine ⟨e.trans e', G.trans heG he'G, _, _⟩, { intros y hy, simp only with mfld_simps at hy, simp only [hef ⟨hy.1, hy.2.1⟩] with mfld_simps }, { simpa only [hex, hef ⟨hx, hex⟩] with mfld_simps using hfx } end } end local_structomorph end structure_groupoid
8a18537eed1320024b1d884bd0383b51249c9d1a
61c3861020ef87c6c325fc3c3dcbabf5d6b07985
/init/pathover.lean
eb0c04991e7468a41cb870c1c25948a776aa7b09
[ "Apache-2.0" ]
permissive
jonas-frey/hott3
a623be2959e8a713c03fa1b0f34bf76a561dfa87
a944051b4eb5919bdc70978ee15fcbb48a824811
refs/heads/master
1,628,408,720,559
1,510,267,042,000
1,510,267,042,000
106,760,764
0
0
null
1,507,856,238,000
1,507,856,238,000
null
UTF-8
Lean
false
false
20,225
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Basic theorems about pathovers -/ import .path .equiv universes u v l hott_theory namespace hott open equiv is_equiv function variables {A : Type _} {A' : Type _} {B : A → Type _} {B' : A → Type _} {B'' : A' → Type _} {C : Π⦃a⦄, B a → Type _} {a a₂ a₃ a₄ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {p₃ : a₃ = a₄} {p₁₃ : a = a₃} {b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄} {c : C b} {c₂ : C b₂} namespace eq inductive pathover (B : A → Type.{l}) (b : B a) : Π{a₂ : A}, a = a₂ → B a₂ → Type.{l} | idpatho : pathover (refl a) b notation b ` =[`:50 p:0 `] `:0 b₂:50 := pathover _ b p b₂ notation b ` =[`:50 p:0 `; `:0 B `] `:0 b₂:50 := pathover B b p b₂ @[hott, refl, reducible] def idpo : b =[refl a] b := pathover.idpatho b @[hott, reducible] def idpatho (b : B a) : b =[refl a] b := pathover.idpatho b /- equivalences with equality using transport -/ @[hott] def pathover_of_tr_eq (r : p ▸ b = b₂) : b =[p] b₂ := by induction p; induction r; constructor @[hott] def pathover_of_eq_tr (r : b = p⁻¹ ▸ b₂) : b =[p] b₂ := begin induction p, change b = b₂ at r, induction r, constructor end @[hott] def tr_eq_of_pathover (r : b =[p] b₂) : p ▸ b = b₂ := by induction r; reflexivity @[hott] def eq_tr_of_pathover (r : b =[p] b₂) : b = p⁻¹ ▸ b₂ := by induction r; reflexivity @[hott] def pathover_equiv_tr_eq (p : a = a₂) (b : B a) (b₂ : B a₂) : (b =[p] b₂) ≃ (p ▸ b = b₂) := begin fapply equiv.MK, { exact tr_eq_of_pathover}, { exact pathover_of_tr_eq}, { intro r, induction p, induction r, apply idp}, { intro r, induction r, apply idp}, end @[hott] def pathover_equiv_eq_tr (p : a = a₂) (b : B a) (b₂ : B a₂) : (b =[p] b₂) ≃ (b = p⁻¹ ▸ b₂) := begin fapply equiv.MK, { exact eq_tr_of_pathover}, { exact pathover_of_eq_tr}, { intro r, induction p, change b = b₂ at r, induction r, apply idp}, { intro r, induction r, apply idp}, end @[hott] def pathover_tr (p : a = a₂) (b : B a) : b =[p] p ▸ b := by induction p; constructor @[hott] def tr_pathover (p : a = a₂) (b : B a₂) : p⁻¹ ▸ b =[p] b := by induction p; constructor @[hott] def concato (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) : b =[p ⬝ p₂] b₃ := by induction r₂; exact r @[hott] def inverseo (r : b =[p] b₂) : b₂ =[p⁻¹] b := by induction r; constructor @[hott] def concato_eq (r : b =[p] b₂) (q : b₂ = b₂') : b =[p] b₂' := by induction q; exact r @[hott] def eq_concato (q : b = b') (r : b' =[p] b₂) : b =[p] b₂ := by induction q; exact r @[hott] def change_path (q : p = p') (r : b =[p] b₂) : b =[p'] b₂ := q ▸ r @[hott, hsimp] def change_path_idp (r : b =[p] b₂) : change_path idp r = r := by reflexivity -- infix ` ⬝ ` := concato infix ` ⬝o `:72 := concato infix ` ⬝op `:73 := concato_eq infix ` ⬝po `:73 := eq_concato -- postfix `⁻¹` := inverseo postfix `⁻¹ᵒ`:(max+10) := inverseo @[hott] def pathover_cancel_right (q : b =[p ⬝ p₂] b₃) (r : b₃ =[p₂⁻¹] b₂) : b =[p] b₂ := change_path (con_inv_cancel_right _ _) (q ⬝o r) @[hott] def pathover_cancel_right' (q : b =[p₁₃ ⬝ p₂⁻¹] b₂) (r : b₂ =[p₂] b₃) : b =[p₁₃] b₃ := change_path (inv_con_cancel_right _ _) (q ⬝o r) @[hott] def pathover_cancel_left (q : b₂ =[p⁻¹] b) (r : b =[p ⬝ p₂] b₃) : b₂ =[p₂] b₃ := change_path (inv_con_cancel_left _ _) (q ⬝o r) @[hott] def pathover_cancel_left' (q : b =[p] b₂) (r : b₂ =[p⁻¹ ⬝ p₁₃] b₃) : b =[p₁₃] b₃ := change_path (con_inv_cancel_left _ _) (q ⬝o r) /- Some of the theorems analogous to theorems for = in init.path -/ @[hott, hsimp] def idpo_invo : idpo⁻¹ᵒ = idpo :> b =[idp] b := by refl @[hott, hsimp] def cono_idpo (r : b =[p] b₂) : r ⬝o idpo = r := by refl @[hott] def idpo_cono (r : b =[p] b₂) : idpo ⬝o r =[idp_con p; λ x, b =[x] b₂] r := by induction r; refl @[hott] def cono.assoc' (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) : r ⬝o (r₂ ⬝o r₃) =[con.assoc' _ _ _; λ x, b =[x] b₄] ((r ⬝o r₂) ⬝o r₃) := by induction r₃; induction r₂; induction r; refl @[hott] def cono.assoc (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) : (r ⬝o r₂) ⬝o r₃ =[con.assoc _ _ _; λ x, b =[x] b₄] r ⬝o (r₂ ⬝o r₃) := by induction r₃; induction r₂; induction r; refl @[hott] def cono.right_inv (r : b =[p] b₂) : r ⬝o r⁻¹ᵒ =[con.right_inv _; λ x, b =[x] b] idpo := by induction r; refl @[hott] def cono.left_inv (r : b =[p] b₂) : r⁻¹ᵒ ⬝o r =[con.left_inv _; λ x, b₂ =[x] b₂] idpo := by induction r; refl @[hott] def eq_of_pathover {a' a₂' : A'} (q : a' =[p; λ _, A'] a₂') : a' = a₂' := by induction q; refl @[hott] def pathover_of_eq (p : a = a₂) {a' a₂' : A'} (q : a' = a₂') : a' =[p; λ _, A'] a₂' := by induction p; induction q; constructor @[hott] def pathover_constant (p : a = a₂) (a' a₂' : A') : a' =[p; λ _, A'] a₂' ≃ a' = a₂' := begin fapply equiv.MK, { exact eq_of_pathover}, { exact pathover_of_eq p}, abstract { intro r, induction p, induction r, refl}, abstract { intro r, induction r, refl}, end @[hott] def pathover_of_eq_tr_constant_inv (p : a = a₂) (a' : A') : pathover_of_eq p (tr_constant p a')⁻¹ = pathover_tr p a' := by induction p; constructor @[hott, elab_simple] def eq_of_pathover_idp {b' : B a} (q : b =[idpath a] b') : b = b' := tr_eq_of_pathover q variable (B) @[hott] def pathover_idp_of_eq {b' : B a} (q : b = b') : b =[idpath a] b' := pathover_of_tr_eq q @[hott] def pathover_idp (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' := begin fapply equiv.MK, {exact eq_of_pathover_idp}, {exact pathover_idp_of_eq B}, {intros, refine to_right_inv (pathover_equiv_tr_eq _ _ _) _ }, {intro r, refine to_left_inv (pathover_equiv_tr_eq _ _ _) r, } end variable {B} @[hott, hsimp] def eq_of_pathover_idp_pathover_of_eq {A X : Type _} (x : X) {a a' : A} (p : a = a') : eq_of_pathover_idp (pathover_of_eq (idpath x) p) = p := by induction p; refl variable (B) @[hott, hsimp] def idpo_concato_eq (r : b = b') : eq_of_pathover_idp (@idpo A B a b ⬝op r) = r := by induction r; reflexivity variable {B} -- def pathover_idp (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' := -- pathover_equiv_tr_eq idp b b' -- def eq_of_pathover_idp [reducible] {b' : B a} (q : b =[idpath a] b') : b = b' := -- to_fun !pathover_idp q -- def pathover_idp_of_eq [reducible] {b' : B a} (q : b = b') : b =[idpath a] b' := -- to_inv !pathover_idp q @[hott, elab_as_eliminator, reducible, recursor] def idp_rec_on {P : Π⦃b₂ : B a⦄, b =[idpath a] b₂ → Sort u} {b₂ : B a} (r : b =[idpath a] b₂) (H : P idpo) : P r := by exact have H2 : P (pathover_idp_of_eq B (eq_of_pathover_idp r)), from eq.rec_on (eq_of_pathover_idp r) H, have H3 : pathover_idp_of_eq B (eq_of_pathover_idp r) = r, from to_left_inv (pathover_idp B b b₂) r, H3 ▸ H2 @[hott] def rec_on_right {P : Π⦃b₂ : B a₂⦄, b =[p] b₂ → Type _} {b₂ : B a₂} (r : b =[p] b₂) (H : P (pathover_tr _ _)) : P r := by induction r; exact H @[hott] def rec_on_left {P : Π⦃b : B a⦄, b =[p] b₂ → Type _} {b : B a} (r : b =[p] b₂) (H : P (tr_pathover _ _)) : P r := by induction r; exact H --pathover with fibration B' ∘ f @[hott] def pathover_ap (B' : A' → Type _) (f : A → A') {p : a = a₂} {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p; B' ∘ f] b₂) : b =[ap f p] b₂ := by induction q; constructor @[hott] def pathover_of_pathover_ap (B' : A' → Type u) (f : A → A') {p : a = a₂} {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[ap f p] b₂) : b =[p; B' ∘ f] b₂ := begin induction p, induction q using hott.eq.idp_rec_on, exact idpo end @[hott] def pathover_compose (B' : A' → Type _) (f : A → A') (p : a = a₂) (b : B' (f a)) (b₂ : B' (f a₂)) : b =[p; B' ∘ f] b₂ ≃ b =[ap f p] b₂ := begin fapply equiv.MK, { exact pathover_ap B' f}, { exact pathover_of_pathover_ap B' f}, { intro q, induction p, induction q using hott.eq.idp_rec_on, refl}, { intro q, induction q, refl}, end @[hott] def pathover_of_pathover_tr (q : b =[p ⬝ p₂] p₂ ▸ b₂) : b =[p] b₂ := pathover_cancel_right q (pathover_tr _ _)⁻¹ᵒ @[hott] def pathover_tr_of_pathover (q : b =[p₁₃ ⬝ p₂⁻¹] b₂) : b =[p₁₃] p₂ ▸ b₂ := pathover_cancel_right' q (pathover_tr _ _) @[hott] def pathover_of_tr_pathover (q : p ▸ b =[p⁻¹ ⬝ p₁₃] b₃) : b =[p₁₃] b₃ := pathover_cancel_left' (pathover_tr _ _) q @[hott] def tr_pathover_of_pathover (q : b =[p ⬝ p₂] b₃) : p ▸ b =[p₂] b₃ := pathover_cancel_left (pathover_tr _ _)⁻¹ᵒ q @[hott] def pathover_tr_of_eq (q : b = b') : b =[p] p ▸ b' := by induction q;apply pathover_tr @[hott] def tr_pathover_of_eq (q : b₂ = b₂') : p⁻¹ ▸ b₂ =[p] b₂' := by induction q;apply tr_pathover @[hott] def eq_of_parallel_po_right (q : b =[p] b₂) (q' : b =[p] b₂') : b₂ = b₂' := begin apply @eq_of_pathover_idp A B, apply change_path (con.left_inv p), exact q⁻¹ᵒ ⬝o q' end @[hott] def eq_of_parallel_po_left (q : b =[p] b₂) (q' : b' =[p] b₂) : b = b' := begin apply @eq_of_pathover_idp A B, apply change_path (con.right_inv p), exact q ⬝o q'⁻¹ᵒ end variable (C) @[hott, elab_simple] def transporto (r : b =[p] b₂) (c : C b) : C b₂ := by induction r;exact c infix ` ▸o `:75 := transporto _ @[hott] def fn_tro_eq_tro_fn {C' : Π ⦃a : A⦄, B a → Type _} (q : b =[p] b₂) (f : Π⦃a : A⦄ (b : B a), C b → C' b) (c : C b) : f b₂ (q ▸o c) = q ▸o (f b c) := by induction q; reflexivity variable {C} /- various variants of ap for pathovers -/ @[hott] def apd (f : Πa, B a) (p : a = a₂) : f a =[p] f a₂ := by induction p; constructor @[hott] def apd_idp (f : Πa, B a) : apd f idp = @idpo A B a (f a) := by reflexivity @[hott] def apo {f : A → A'} (g : Πa, B a → B'' (f a)) (q : b =[p] b₂) : g a b =[p; B'' ∘ f] g a₂ b₂ := by induction q; constructor @[hott] def apd011 (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂) : f a b = f a₂ b₂ := by induction Hb; reflexivity @[hott] def apd0111 (f : Πa b, C b → A') (Ha : a = a₂) (Hb : b =[Ha] b₂) (Hc : c =[apd011 C Ha Hb; id] c₂) : f a b c = f a₂ b₂ c₂ := by induction Hb; induction Hc using hott.eq.idp_rec_on; refl @[hott] def apod11 {f : Πb, C b} {g : Πb₂, C b₂} (r : f =[p; λ a, Π b : B a, C b] g) {b : B a} {b₂ : B a₂} (q : b =[p] b₂) : f b =[apd011 C p q; id] g b₂ := by induction r; induction q using hott.eq.idp_rec_on; constructor @[hott] def apdo10 {f : Πb, C b} {g : Πb₂, C b₂} (r : f =[p; λ a, Π b : B a, C b] g) (b : B a) : f b =[apd011 C p (pathover_tr _ _); id] g (p ▸ b) := by induction r; constructor @[hott] def apo10 {f : B a → B' a} {g : B a₂ → B' a₂} (r : f =[p; λ a, B a → B' a] g) (b : B a) : f b =[p] g (p ▸ b) := by induction r; constructor @[hott] def apo10_constant_right {f : B a → A'} {g : B a₂ → A'} (r : f =[p; λ a, B a → A'] g) (b : B a) : f b = g (p ▸ b) := by induction r; constructor @[hott] def apo10_constant_left {f : A' → B a} {g : A' → B a₂} (r : f =[p; λ a, A' → B a] g) (a' : A') : f a' =[p] g a' := by induction r; constructor @[hott] def apo11 {f : B a → B' a} {g : B a₂ → B' a₂} (r : f =[p; λ a, B a → B' a] g) (q : b =[p] b₂) : f b =[p] g b₂ := by induction q; exact apo10 r b @[hott] def apo011 {A : Type _} {B C D : A → Type _} {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {c : C a} {c' : C a'} (f : Π⦃a⦄, B a → C a → D a) (q : b =[p] b') (r : c =[p] c') : f b c =[p] f b' c' := begin induction q, induction r using hott.eq.idp_rec_on, exact idpo end @[hott] def apdo011 {A : Type _} {B : A → Type _} {C : Π⦃a⦄, B a → Type _} (f : Π⦃a⦄ (b : B a), C b) {a a' : A} (p : a = a') {b : B a} {b' : B a'} (q : b =[p] b') : f b =[apd011 C p q; id] f b' := by induction q; constructor @[hott] def apdo0111 {A : Type _} {B : A → Type _} {C C' : Π⦃a⦄, B a → Type _} (f : Π⦃a⦄ {b : B a}, C b → C' b) {a a' : A} (p : a = a') {b : B a} {b' : B a'} (q : b =[p] b') {c : C b} {c' : C b'} (r : c =[apd011 C p q; id] c') : f c =[apd011 C' p q; id] f c' := begin induction q, dsimp [apd011] at r, induction r using hott.eq.idp_rec_on, refl end @[hott] def apo11_constant_right {f : B a → A'} {g : B a₂ → A'} (q : f =[p; λ a, B a → A'] g) (r : b =[p] b₂) : f b = g b₂ := eq_of_pathover (apo11 q r) /- properties about these "ap"s, transporto and pathover_ap -/ @[hott] def apd_con (f : Πa, B a) (p : a = a₂) (q : a₂ = a₃) : apd f (p ⬝ q) = apd f p ⬝o apd f q := by induction p; induction q; reflexivity @[hott] def apd_inv (f : Πa, B a) (p : a = a₂) : apd f p⁻¹ = (apd f p)⁻¹ᵒ := by induction p; reflexivity @[hott] def apd_eq_pathover_of_eq_ap (f : A → A') (p : a = a₂) : apd f p = pathover_of_eq p (ap f p) := eq.rec_on p idp @[hott] def apo_invo (f : Πa, B a → B' a) {Ha : a = a₂} (Hb : b =[Ha] b₂) : (apo f Hb)⁻¹ᵒ = apo f Hb⁻¹ᵒ := by induction Hb; reflexivity @[hott] def apd011_inv (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂) : (apd011 f Ha Hb)⁻¹ = (apd011 f Ha⁻¹ Hb⁻¹ᵒ) := by induction Hb; reflexivity @[hott] def cast_apd011 (q : b =[p] b₂) (c : C b) : cast (apd011 C p q) c = q ▸o c := by induction q; reflexivity @[hott] def apd_compose1 (g : Πa, B a → B' a) (f : Πa, B a) (p : a = a₂) : apd (g ∘' f) p = apo g (apd f p) := by induction p; reflexivity @[hott] def apd_compose2 (g : Πa', B'' a') (f : A → A') (p : a = a₂) : apd (λa, g (f a)) p = pathover_of_pathover_ap B'' f (apd g (ap f p)) := by induction p; reflexivity @[hott] def apo_tro (C : Π⦃a⦄, B' a → Type _) (f : Π⦃a⦄, B a → B' a) (q : b =[p] b₂) (c : C (f b)) : apo f q ▸o c = q ▸o c := by induction q; reflexivity @[hott] def pathover_ap_tro {B' : A' → Type _} (C : Π⦃a'⦄, B' a' → Type _) (f : A → A') {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p; B' ∘ f] b₂) (c : C b) : pathover_ap B' f q ▸o c = q ▸o c := by induction q; reflexivity @[hott] def pathover_ap_invo_tro {B' : A' → Type _} (C : Π⦃a'⦄, B' a' → Type _) (f : A → A') {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p; B' ∘ f] b₂) (c : C b₂) : (pathover_ap B' f q)⁻¹ᵒ ▸o c = q⁻¹ᵒ ▸o c := by induction q; reflexivity @[hott, elab_simple] def pathover_tro (q : b =[p] b₂) (c : C b) : c =[apd011 C p q; id] q ▸o c := by induction q; constructor @[hott] def pathover_ap_invo {B' : A' → Type _} (f : A → A') {p : a = a₂} {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p; B' ∘ f] b₂) : pathover_ap B' f q⁻¹ᵒ =[ap_inv f p; λ x, b₂ =[x] b] (pathover_ap B' f q)⁻¹ᵒ := by induction q; exact idpo @[hott] def tro_invo_tro {A : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') (c : C b') : q ▸o (q⁻¹ᵒ ▸o c) = c := by induction q; reflexivity @[hott] def invo_tro_tro {A : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') (c : C b) : q⁻¹ᵒ ▸o (q ▸o c) = c := by induction q; reflexivity @[hott] def cono_tro {A : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a₁ a₂ a₃ : A} {p₁ : a₁ = a₂} {p₂ : a₂ = a₃} {b₁ : B a₁} {b₂ : B a₂} {b₃ : B a₃} (q₁ : b₁ =[p₁] b₂) (q₂ : b₂ =[p₂] b₃) (c : C b₁) : transporto C (q₁ ⬝o q₂) c = transporto C q₂ (transporto C q₁ c) := by induction q₂; reflexivity @[hott] def is_equiv_transporto {A : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') : is_equiv (transporto C q) := begin fapply adjointify, { exact transporto C q⁻¹ᵒ}, { exact tro_invo_tro C q}, { exact invo_tro_tro C q} end @[hott] def equiv_apd011 {A : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') : C b ≃ C b' := equiv.mk (transporto C q) (is_equiv_transporto _ _) /- some cancellation laws for concato_eq an variants -/ @[hott] def cono.right_inv_eq (q : b = b') : pathover_idp_of_eq B q ⬝op q⁻¹ = (idpo : b =[refl a] b) := by induction q;constructor @[hott] def cono.right_inv_eq' (q : b = b') : q ⬝po (pathover_idp_of_eq B q⁻¹) = (idpo : b =[refl a] b) := by induction q;constructor @[hott] def cono.left_inv_eq (q : b = b') : pathover_idp_of_eq B q⁻¹ ⬝op q = (idpo : b' =[refl a] b') := by induction q;constructor @[hott] def cono.left_inv_eq' (q : b = b') : q⁻¹ ⬝po pathover_idp_of_eq B q = (idpo : b' =[refl a] b') := by induction q;constructor @[hott] def pathover_of_fn_pathover_fn (f : Π{a}, B a ≃ B' a) (r : f.to_fun b =[p] f.to_fun b₂) : b =[p] b₂ := (left_inv f.to_fun b)⁻¹ ⬝po apo (λa, to_fun f⁻¹ᵉ) r ⬝op left_inv f.to_fun b₂ /- a pathover in a pathover type where the only thing which varies is the path is the same as an equality with a change_path -/ @[hott] def change_path_of_pathover (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) (q : r =[s; λ p, b =[p] b₂] r') : change_path s r = r' := by induction s; induction q using hott.eq.idp_rec_on; reflexivity @[hott] def pathover_of_change_path (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) (q : change_path s r = r') : r =[s; λ p, b =[p] b₂] r' := by induction s; induction q; constructor @[hott] def pathover_pathover_path (s : p = p') (r : b =[p] b₂) (r' : b =[p'] b₂) : (r =[s; λ p, b =[p] b₂] r') ≃ change_path s r = r' := begin fapply equiv.MK, { apply change_path_of_pathover}, { apply pathover_of_change_path}, { intro q, induction s, induction q, reflexivity}, { intro q, induction s, induction q using hott.eq.idp_rec_on, reflexivity}, end /- variants of inverse2 and concat2 -/ @[hott] def inverseo2 {r r' : b =[p] b₂} (s : r = r') : r⁻¹ᵒ = r'⁻¹ᵒ := by induction s; reflexivity @[hott] def concato2 {r r' : b =[p] b₂} {r₂ r₂' : b₂ =[p₂] b₃} (s : r = r') (s₂ : r₂ = r₂') : r ⬝o r₂ = r' ⬝o r₂' := by induction s; induction s₂; reflexivity infixl ` ◾o `:75 := concato2 postfix [parsing_only] `⁻²ᵒ`:(max+10) := inverseo2 --this notation is abusive, should we use it? -- find a better name for this @[hott] def fn_tro_eq_tro_fn2 (q : b =[p] b₂) {k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b)) (c : C b) : m (q ▸o c) = (pathover_ap B k (apo l q)) ▸o (m c) := by induction q; reflexivity @[hott] def apd0111_precompose (f : Π⦃a⦄ {b : B a}, C b → A') {k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b)) {q : b =[p] b₂} (c : C b) : apd0111 (λa b (c : C b), f (m c)) p q (pathover_tro q c) ⬝ ap (@f _ _) (fn_tro_eq_tro_fn2 q m c) = apd0111 f (ap k p) (pathover_ap B k (apo l q)) (pathover_tro _ (m c)) := by induction q; reflexivity end eq end hott
6c592c99ad92ff79b257e16c118a96ac98db5a6e
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/algebra/ordered_group.lean
a684706866283b33cbdc2f57b9b563f3765f70de
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
19,999
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.order init.algebra.group /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u class ordered_cancel_comm_monoid (α : Type u) extends add_comm_monoid α, add_left_cancel_semigroup α, add_right_cancel_semigroup α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (le_of_add_le_add_left : ∀ a b c : α, a + b ≤ a + c → b ≤ c) section ordered_cancel_comm_monoid variable {α : Type u} variable [s : ordered_cancel_comm_monoid α] lemma add_le_add_left {a b : α} (h : a ≤ b) (c : α) : c + a ≤ c + b := @ordered_cancel_comm_monoid.add_le_add_left α s a b h c lemma le_of_add_le_add_left {a b c : α} (h : a + b ≤ a + c) : b ≤ c := @ordered_cancel_comm_monoid.le_of_add_le_add_left α s a b c h end ordered_cancel_comm_monoid section ordered_cancel_comm_monoid variable {α : Type u} variable [ordered_cancel_comm_monoid α] lemma add_lt_add_left {a b : α} (h : a < b) (c : α) : c + a < c + b := lt_of_le_not_le (add_le_add_left (le_of_lt h) _) $ mt le_of_add_le_add_left (not_le_of_gt h) lemma lt_of_add_lt_add_left {a b c : α} (h : a + b < a + c) : b < c := lt_of_le_not_le (le_of_add_le_add_left (le_of_lt h)) $ mt (λ h, add_le_add_left h _) (not_le_of_gt h) lemma add_le_add_right {a b : α} (h : a ≤ b) (c : α) : a + c ≤ b + c := add_comm c a ▸ add_comm c b ▸ add_le_add_left h c theorem add_lt_add_right {a b : α} (h : a < b) (c : α) : a + c < b + c := begin rw [add_comm a c, add_comm b c], exact (add_lt_add_left h c) end lemma add_le_add {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (add_le_add_right h₁ c) (add_le_add_left h₂ b) lemma le_add_of_nonneg_right {a b : α} (h : b ≥ 0) : a ≤ a + b := have a + b ≥ a + 0, from add_le_add_left h a, by rwa add_zero at this lemma le_add_of_nonneg_left {a b : α} (h : b ≥ 0) : a ≤ b + a := have 0 + a ≤ b + a, from add_le_add_right h a, by rwa zero_add at this lemma add_lt_add {a b c d : α} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (add_lt_add_right h₁ c) (add_lt_add_left h₂ b) lemma add_lt_add_of_le_of_lt {a b c d : α} (h₁ : a ≤ b) (h₂ : c < d) : a + c < b + d := lt_of_le_of_lt (add_le_add_right h₁ c) (add_lt_add_left h₂ b) lemma add_lt_add_of_lt_of_le {a b c d : α} (h₁ : a < b) (h₂ : c ≤ d) : a + c < b + d := lt_of_lt_of_le (add_lt_add_right h₁ c) (add_le_add_left h₂ b) lemma lt_add_of_pos_right (a : α) {b : α} (h : b > 0) : a < a + b := have a + 0 < a + b, from add_lt_add_left h a, by rwa [add_zero] at this lemma lt_add_of_pos_left (a : α) {b : α} (h : b > 0) : a < b + a := have 0 + a < b + a, from add_lt_add_right h a, by rwa [zero_add] at this lemma le_of_add_le_add_right {a b c : α} (h : a + b ≤ c + b) : a ≤ c := le_of_add_le_add_left (show b + a ≤ b + c, begin rw [add_comm b a, add_comm b c], assumption end) lemma lt_of_add_lt_add_right {a b c : α} (h : a + b < c + b) : a < c := lt_of_add_lt_add_left (show b + a < b + c, begin rw [add_comm b a, add_comm b c], assumption end) -- here we start using properties of zero. lemma add_nonneg {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := zero_add (0:α) ▸ (add_le_add ha hb) lemma add_pos {a b : α} (ha : 0 < a) (hb : 0 < b) : 0 < a + b := zero_add (0:α) ▸ (add_lt_add ha hb) lemma add_pos_of_pos_of_nonneg {a b : α} (ha : 0 < a) (hb : 0 ≤ b) : 0 < a + b := zero_add (0:α) ▸ (add_lt_add_of_lt_of_le ha hb) lemma add_pos_of_nonneg_of_pos {a b : α} (ha : 0 ≤ a) (hb : 0 < b) : 0 < a + b := zero_add (0:α) ▸ (add_lt_add_of_le_of_lt ha hb) lemma add_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : a + b ≤ 0 := zero_add (0:α) ▸ (add_le_add ha hb) lemma add_neg {a b : α} (ha : a < 0) (hb : b < 0) : a + b < 0 := zero_add (0:α) ▸ (add_lt_add ha hb) lemma add_neg_of_neg_of_nonpos {a b : α} (ha : a < 0) (hb : b ≤ 0) : a + b < 0 := zero_add (0:α) ▸ (add_lt_add_of_lt_of_le ha hb) lemma add_neg_of_nonpos_of_neg {a b : α} (ha : a ≤ 0) (hb : b < 0) : a + b < 0 := zero_add (0:α) ▸ (add_lt_add_of_le_of_lt ha hb) lemma add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume hab : a + b = 0, have ha' : a ≤ 0, from calc a = a + 0 : by rw add_zero ... ≤ a + b : add_le_add_left hb _ ... = 0 : hab, have haz : a = 0, from le_antisymm ha' ha, have hb' : b ≤ 0, from calc b = 0 + b : by rw zero_add ... ≤ a + b : by exact add_le_add_right ha _ ... = 0 : hab, have hbz : b = 0, from le_antisymm hb' hb, and.intro haz hbz) (assume ⟨ha', hb'⟩, by rw [ha', hb', add_zero]) lemma le_add_of_nonneg_of_le {a b c : α} (ha : 0 ≤ a) (hbc : b ≤ c) : b ≤ a + c := zero_add b ▸ add_le_add ha hbc lemma le_add_of_le_of_nonneg {a b c : α} (hbc : b ≤ c) (ha : 0 ≤ a) : b ≤ c + a := add_zero b ▸ add_le_add hbc ha lemma lt_add_of_pos_of_le {a b c : α} (ha : 0 < a) (hbc : b ≤ c) : b < a + c := zero_add b ▸ add_lt_add_of_lt_of_le ha hbc lemma lt_add_of_le_of_pos {a b c : α} (hbc : b ≤ c) (ha : 0 < a) : b < c + a := add_zero b ▸ add_lt_add_of_le_of_lt hbc ha lemma add_le_of_nonpos_of_le {a b c : α} (ha : a ≤ 0) (hbc : b ≤ c) : a + b ≤ c := zero_add c ▸ add_le_add ha hbc lemma add_le_of_le_of_nonpos {a b c : α} (hbc : b ≤ c) (ha : a ≤ 0) : b + a ≤ c := add_zero c ▸ add_le_add hbc ha lemma add_lt_of_neg_of_le {a b c : α} (ha : a < 0) (hbc : b ≤ c) : a + b < c := zero_add c ▸ add_lt_add_of_lt_of_le ha hbc lemma add_lt_of_le_of_neg {a b c : α} (hbc : b ≤ c) (ha : a < 0) : b + a < c := add_zero c ▸ add_lt_add_of_le_of_lt hbc ha lemma lt_add_of_nonneg_of_lt {a b c : α} (ha : 0 ≤ a) (hbc : b < c) : b < a + c := zero_add b ▸ add_lt_add_of_le_of_lt ha hbc lemma lt_add_of_lt_of_nonneg {a b c : α} (hbc : b < c) (ha : 0 ≤ a) : b < c + a := add_zero b ▸ add_lt_add_of_lt_of_le hbc ha lemma lt_add_of_pos_of_lt {a b c : α} (ha : 0 < a) (hbc : b < c) : b < a + c := zero_add b ▸ add_lt_add ha hbc lemma lt_add_of_lt_of_pos {a b c : α} (hbc : b < c) (ha : 0 < a) : b < c + a := add_zero b ▸ add_lt_add hbc ha lemma add_lt_of_nonpos_of_lt {a b c : α} (ha : a ≤ 0) (hbc : b < c) : a + b < c := zero_add c ▸ add_lt_add_of_le_of_lt ha hbc lemma add_lt_of_lt_of_nonpos {a b c : α} (hbc : b < c) (ha : a ≤ 0) : b + a < c := add_zero c ▸ add_lt_add_of_lt_of_le hbc ha lemma add_lt_of_neg_of_lt {a b c : α} (ha : a < 0) (hbc : b < c) : a + b < c := zero_add c ▸ add_lt_add ha hbc lemma add_lt_of_lt_of_neg {a b c : α} (hbc : b < c) (ha : a < 0) : b + a < c := add_zero c ▸ add_lt_add hbc ha end ordered_cancel_comm_monoid class ordered_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (add_lt_add_left : ∀ a b : α, a < b → ∀ c : α, c + a < c + b) section ordered_comm_group variable {α : Type u} variable [ordered_comm_group α] lemma ordered_comm_group.le_of_add_le_add_left {a b c : α} (h : a + b ≤ a + c) : b ≤ c := have -a + (a + b) ≤ -a + (a + c), from ordered_comm_group.add_le_add_left _ _ h _, begin simp [neg_add_cancel_left] at this, assumption end lemma ordered_comm_group.lt_of_add_lt_add_left {a b c : α} (h : a + b < a + c) : b < c := have -a + (a + b) < -a + (a + c), from ordered_comm_group.add_lt_add_left _ _ h _, begin simp [neg_add_cancel_left] at this, assumption end end ordered_comm_group instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @ordered_comm_group.le_of_add_le_add_left α _, ..s } section ordered_comm_group variables {α : Type u} [ordered_comm_group α] lemma neg_le_neg {a b : α} (h : a ≤ b) : -b ≤ -a := have 0 ≤ -a + b, from add_left_neg a ▸ add_le_add_left h (-a), have 0 + -b ≤ -a + b + -b, from add_le_add_right this (-b), by rwa [add_neg_cancel_right, zero_add] at this lemma le_of_neg_le_neg {a b : α} (h : -b ≤ -a) : a ≤ b := suffices -(-a) ≤ -(-b), from begin simp [neg_neg] at this, assumption end, neg_le_neg h lemma nonneg_of_neg_nonpos {a : α} (h : -a ≤ 0) : 0 ≤ a := have -a ≤ -0, by rwa neg_zero, le_of_neg_le_neg this lemma neg_nonpos_of_nonneg {a : α} (h : 0 ≤ a) : -a ≤ 0 := have -a ≤ -0, from neg_le_neg h, by rwa neg_zero at this lemma nonpos_of_neg_nonneg {a : α} (h : 0 ≤ -a) : a ≤ 0 := have -0 ≤ -a, by rwa neg_zero, le_of_neg_le_neg this lemma neg_nonneg_of_nonpos {a : α} (h : a ≤ 0) : 0 ≤ -a := have -0 ≤ -a, from neg_le_neg h, by rwa neg_zero at this lemma neg_lt_neg {a b : α} (h : a < b) : -b < -a := have 0 < -a + b, from add_left_neg a ▸ add_lt_add_left h (-a), have 0 + -b < -a + b + -b, from add_lt_add_right this (-b), by rwa [add_neg_cancel_right, zero_add] at this lemma lt_of_neg_lt_neg {a b : α} (h : -b < -a) : a < b := neg_neg a ▸ neg_neg b ▸ neg_lt_neg h lemma pos_of_neg_neg {a : α} (h : -a < 0) : 0 < a := have -a < -0, by rwa neg_zero, lt_of_neg_lt_neg this lemma neg_neg_of_pos {a : α} (h : 0 < a) : -a < 0 := have -a < -0, from neg_lt_neg h, by rwa neg_zero at this lemma neg_of_neg_pos {a : α} (h : 0 < -a) : a < 0 := have -0 < -a, by rwa neg_zero, lt_of_neg_lt_neg this lemma neg_pos_of_neg {a : α} (h : a < 0) : 0 < -a := have -0 < -a, from neg_lt_neg h, by rwa neg_zero at this lemma le_neg_of_le_neg {a b : α} (h : a ≤ -b) : b ≤ -a := begin have h := neg_le_neg h, rwa neg_neg at h end lemma neg_le_of_neg_le {a b : α} (h : -a ≤ b) : -b ≤ a := begin have h := neg_le_neg h, rwa neg_neg at h end lemma lt_neg_of_lt_neg {a b : α} (h : a < -b) : b < -a := begin have h := neg_lt_neg h, rwa neg_neg at h end lemma neg_lt_of_neg_lt {a b : α} (h : -a < b) : -b < a := begin have h := neg_lt_neg h, rwa neg_neg at h end lemma sub_nonneg_of_le {a b : α} (h : b ≤ a) : 0 ≤ a - b := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonneg {a b : α} (h : 0 ≤ a - b) : b ≤ a := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_nonpos_of_le {a b : α} (h : a ≤ b) : a - b ≤ 0 := begin have h := add_le_add_right h (-b), rwa add_right_neg at h end lemma le_of_sub_nonpos {a b : α} (h : a - b ≤ 0) : a ≤ b := begin have h := add_le_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_pos_of_lt {a b : α} (h : b < a) : 0 < a - b := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_pos {a b : α} (h : 0 < a - b) : b < a := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma sub_neg_of_lt {a b : α} (h : a < b) : a - b < 0 := begin have h := add_lt_add_right h (-b), rwa add_right_neg at h end lemma lt_of_sub_neg {a b : α} (h : a - b < 0) : a < b := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, zero_add] at h end lemma add_le_of_le_neg_add {a b c : α} (h : b ≤ -a + c) : a + b ≤ c := begin have h := add_le_add_left h a, rwa add_neg_cancel_left at h end lemma le_neg_add_of_add_le {a b c : α} (h : a + b ≤ c) : b ≤ -a + c := begin have h := add_le_add_left h (-a), rwa neg_add_cancel_left at h end lemma add_le_of_le_sub_left {a b c : α} (h : b ≤ c - a) : a + b ≤ c := begin have h := add_le_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma le_sub_left_of_add_le {a b c : α} (h : a + b ≤ c) : b ≤ c - a := begin have h := add_le_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_le_of_le_sub_right {a b c : α} (h : a ≤ c - b) : a + b ≤ c := begin have h := add_le_add_right h b, rwa sub_add_cancel at h end lemma le_sub_right_of_add_le {a b c : α} (h : a + b ≤ c) : a ≤ c - b := begin have h := add_le_add_right h (-b), rwa add_neg_cancel_right at h end lemma le_add_of_neg_add_le {a b c : α} (h : -b + a ≤ c) : a ≤ b + c := begin have h := add_le_add_left h b, rwa add_neg_cancel_left at h end lemma neg_add_le_of_le_add {a b c : α} (h : a ≤ b + c) : -b + a ≤ c := begin have h := add_le_add_left h (-b), rwa neg_add_cancel_left at h end lemma le_add_of_sub_left_le {a b c : α} (h : a - b ≤ c) : a ≤ b + c := begin have h := add_le_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_le_of_le_add {a b c : α} (h : a ≤ b + c) : a - b ≤ c := begin have h := add_le_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma le_add_of_sub_right_le {a b c : α} (h : a - c ≤ b) : a ≤ b + c := begin have h := add_le_add_right h c, rwa sub_add_cancel at h end lemma sub_right_le_of_le_add {a b c : α} (h : a ≤ b + c) : a - c ≤ b := begin have h := add_le_add_right h (-c), rwa add_neg_cancel_right at h end lemma le_add_of_neg_add_le_left {a b c : α} (h : -b + a ≤ c) : a ≤ b + c := begin rw add_comm at h, exact le_add_of_sub_left_le h end lemma neg_add_le_left_of_le_add {a b c : α} (h : a ≤ b + c) : -b + a ≤ c := begin rw add_comm, exact sub_left_le_of_le_add h end lemma le_add_of_neg_add_le_right {a b c : α} (h : -c + a ≤ b) : a ≤ b + c := begin rw add_comm at h, exact le_add_of_sub_right_le h end lemma neg_add_le_right_of_le_add {a b c : α} (h : a ≤ b + c) : -c + a ≤ b := begin rw add_comm at h, apply neg_add_le_left_of_le_add h end lemma le_add_of_neg_le_sub_left {a b c : α} (h : -a ≤ b - c) : c ≤ a + b := le_add_of_neg_add_le_left (add_le_of_le_sub_right h) lemma neg_le_sub_left_of_le_add {a b c : α} (h : c ≤ a + b) : -a ≤ b - c := begin have h := le_neg_add_of_add_le (sub_left_le_of_le_add h), rwa add_comm at h end lemma le_add_of_neg_le_sub_right {a b c : α} (h : -b ≤ a - c) : c ≤ a + b := le_add_of_sub_right_le (add_le_of_le_sub_left h) lemma neg_le_sub_right_of_le_add {a b c : α} (h : c ≤ a + b) : -b ≤ a - c := le_sub_left_of_add_le (sub_right_le_of_le_add h) lemma sub_le_of_sub_le {a b c : α} (h : a - b ≤ c) : a - c ≤ b := sub_left_le_of_le_add (le_add_of_sub_right_le h) lemma sub_le_sub_left {a b : α} (h : a ≤ b) (c : α) : c - b ≤ c - a := add_le_add_left (neg_le_neg h) c lemma sub_le_sub_right {a b : α} (h : a ≤ b) (c : α) : a - c ≤ b - c := add_le_add_right h (-c) lemma sub_le_sub {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := add_le_add hab (neg_le_neg hcd) lemma add_lt_of_lt_neg_add {a b c : α} (h : b < -a + c) : a + b < c := begin have h := add_lt_add_left h a, rwa add_neg_cancel_left at h end lemma lt_neg_add_of_add_lt {a b c : α} (h : a + b < c) : b < -a + c := begin have h := add_lt_add_left h (-a), rwa neg_add_cancel_left at h end lemma add_lt_of_lt_sub_left {a b c : α} (h : b < c - a) : a + b < c := begin have h := add_lt_add_left h a, rwa [← add_sub_assoc, add_comm a c, add_sub_cancel] at h end lemma lt_sub_left_of_add_lt {a b c : α} (h : a + b < c) : b < c - a := begin have h := add_lt_add_right h (-a), rwa [add_comm a b, add_neg_cancel_right] at h end lemma add_lt_of_lt_sub_right {a b c : α} (h : a < c - b) : a + b < c := begin have h := add_lt_add_right h b, rwa sub_add_cancel at h end lemma lt_sub_right_of_add_lt {a b c : α} (h : a + b < c) : a < c - b := begin have h := add_lt_add_right h (-b), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_add_lt {a b c : α} (h : -b + a < c) : a < b + c := begin have h := add_lt_add_left h b, rwa add_neg_cancel_left at h end lemma neg_add_lt_of_lt_add {a b c : α} (h : a < b + c) : -b + a < c := begin have h := add_lt_add_left h (-b), rwa neg_add_cancel_left at h end lemma lt_add_of_sub_left_lt {a b c : α} (h : a - b < c) : a < b + c := begin have h := add_lt_add_right h b, rwa [sub_add_cancel, add_comm] at h end lemma sub_left_lt_of_lt_add {a b c : α} (h : a < b + c) : a - b < c := begin have h := add_lt_add_right h (-b), rwa [add_comm b c, add_neg_cancel_right] at h end lemma lt_add_of_sub_right_lt {a b c : α} (h : a - c < b) : a < b + c := begin have h := add_lt_add_right h c, rwa sub_add_cancel at h end lemma sub_right_lt_of_lt_add {a b c : α} (h : a < b + c) : a - c < b := begin have h := add_lt_add_right h (-c), rwa add_neg_cancel_right at h end lemma lt_add_of_neg_add_lt_left {a b c : α} (h : -b + a < c) : a < b + c := begin rw add_comm at h, exact lt_add_of_sub_left_lt h end lemma neg_add_lt_left_of_lt_add {a b c : α} (h : a < b + c) : -b + a < c := begin rw add_comm, exact sub_left_lt_of_lt_add h end lemma lt_add_of_neg_add_lt_right {a b c : α} (h : -c + a < b) : a < b + c := begin rw add_comm at h, exact lt_add_of_sub_right_lt h end lemma neg_add_lt_right_of_lt_add {a b c : α} (h : a < b + c) : -c + a < b := begin rw add_comm at h, apply neg_add_lt_left_of_lt_add h end lemma lt_add_of_neg_lt_sub_left {a b c : α} (h : -a < b - c) : c < a + b := lt_add_of_neg_add_lt_left (add_lt_of_lt_sub_right h) lemma neg_lt_sub_left_of_lt_add {a b c : α} (h : c < a + b) : -a < b - c := begin have h := lt_neg_add_of_add_lt (sub_left_lt_of_lt_add h), rwa add_comm at h end lemma lt_add_of_neg_lt_sub_right {a b c : α} (h : -b < a - c) : c < a + b := lt_add_of_sub_right_lt (add_lt_of_lt_sub_left h) lemma neg_lt_sub_right_of_lt_add {a b c : α} (h : c < a + b) : -b < a - c := lt_sub_left_of_add_lt (sub_right_lt_of_lt_add h) lemma sub_lt_of_sub_lt {a b c : α} (h : a - b < c) : a - c < b := sub_left_lt_of_lt_add (lt_add_of_sub_right_lt h) lemma sub_lt_sub_left {a b : α} (h : a < b) (c : α) : c - b < c - a := add_lt_add_left (neg_lt_neg h) c lemma sub_lt_sub_right {a b : α} (h : a < b) (c : α) : a - c < b - c := add_lt_add_right h (-c) lemma sub_lt_sub {a b c d : α} (hab : a < b) (hcd : c < d) : a - d < b - c := add_lt_add hab (neg_lt_neg hcd) lemma sub_lt_sub_of_le_of_lt {a b c d : α} (hab : a ≤ b) (hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt hab (neg_lt_neg hcd) lemma sub_lt_sub_of_lt_of_le {a b c d : α} (hab : a < b) (hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le hab (neg_le_neg hcd) lemma sub_le_self (a : α) {b : α} (h : b ≥ 0) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg h) _ ... = a : by rw add_zero lemma sub_lt_self (a : α) {b : α} (h : b > 0) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos h) _ ... = a : by rw add_zero lemma add_le_add_three {a b c d e f : α} (h₁ : a ≤ d) (h₂ : b ≤ e) (h₃ : c ≤ f) : a + b + c ≤ d + e + f := begin apply le_trans, apply add_le_add, apply add_le_add, assumption', apply le_refl end end ordered_comm_group class decidable_linear_ordered_comm_group (α : Type u) extends add_comm_group α, decidable_linear_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (add_lt_add_left : ∀ a b : α, a < b → ∀ c : α, c + a < c + b) instance decidable_linear_ordered_comm_group.to_ordered_comm_group (α : Type u) [s : decidable_linear_ordered_comm_group α] : ordered_comm_group α := { add := s.add, ..s } class decidable_linear_ordered_cancel_comm_monoid (α : Type u) extends ordered_cancel_comm_monoid α, decidable_linear_order α
802a826456c686bc80b4b4ecd9e8c930486a9bbe
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/order/monotone_convergence.lean
fa813e949b10c6c24f8d777a879ca15135a5c93d
[ "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
13,769
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Yury Kudryashov -/ import topology.algebra.order.basic /-! # Bounded monotone sequences converge In this file we prove a few theorems of the form “if the range of a monotone function `f : ι → α` admits a least upper bound `a`, then `f x` tends to `a` as `x → ∞`”, as well as version of this statement for (conditionally) complete lattices that use `⨆ x, f x` instead of `is_lub`. These theorems work for linear orders with order topologies as well as their products (both in terms of `prod` and in terms of function types). In order to reduce code duplication, we introduce two typeclasses (one for the property formulated above and one for the dual property), prove theorems assuming one of these typeclasses, and provide instances for linear orders and their products. We also prove some "inverse" results: if `f n` is a monotone sequence and `a` is its limit, then `f n ≤ a` for all `n`. ## Tags monotone convergence -/ open filter set function open_locale filter topological_space classical variables {α β : Type*} /-- We say that `α` is a `Sup_convergence_class` if the following holds. Let `f : ι → α` be a monotone function, let `a : α` be a least upper bound of `set.range f`. Then `f x` tends to `𝓝 a` as `x → ∞` (formally, at the filter `filter.at_top`). We require this for `ι = (s : set α)`, `f = coe` in the definition, then prove it for any `f` in `tendsto_at_top_is_lub`. This property holds for linear orders with order topology as well as their products. -/ class Sup_convergence_class (α : Type*) [preorder α] [topological_space α] : Prop := (tendsto_coe_at_top_is_lub : ∀ (a : α) (s : set α), is_lub s a → tendsto (coe : s → α) at_top (𝓝 a)) /-- We say that `α` is an `Inf_convergence_class` if the following holds. Let `f : ι → α` be a monotone function, let `a : α` be a greatest lower bound of `set.range f`. Then `f x` tends to `𝓝 a` as `x → -∞` (formally, at the filter `filter.at_bot`). We require this for `ι = (s : set α)`, `f = coe` in the definition, then prove it for any `f` in `tendsto_at_bot_is_glb`. This property holds for linear orders with order topology as well as their products. -/ class Inf_convergence_class (α : Type*) [preorder α] [topological_space α] : Prop := (tendsto_coe_at_bot_is_glb : ∀ (a : α) (s : set α), is_glb s a → tendsto (coe : s → α) at_bot (𝓝 a)) instance order_dual.Sup_convergence_class [preorder α] [topological_space α] [Inf_convergence_class α] : Sup_convergence_class αᵒᵈ := ⟨‹Inf_convergence_class α›.1⟩ instance order_dual.Inf_convergence_class [preorder α] [topological_space α] [Sup_convergence_class α] : Inf_convergence_class αᵒᵈ := ⟨‹Sup_convergence_class α›.1⟩ @[priority 100] -- see Note [lower instance priority] instance linear_order.Sup_convergence_class [topological_space α] [linear_order α] [order_topology α] : Sup_convergence_class α := begin refine ⟨λ a s ha, tendsto_order.2 ⟨λ b hb, _, λ b hb, _⟩⟩, { rcases ha.exists_between hb with ⟨c, hcs, bc, bca⟩, lift c to s using hcs, refine (eventually_ge_at_top c).mono (λ x hx, bc.trans_le hx) }, { exact eventually_of_forall (λ x, (ha.1 x.2).trans_lt hb) } end @[priority 100] -- see Note [lower instance priority] instance linear_order.Inf_convergence_class [topological_space α] [linear_order α] [order_topology α] : Inf_convergence_class α := show Inf_convergence_class αᵒᵈᵒᵈ, from order_dual.Inf_convergence_class section variables {ι : Type*} [preorder ι] [topological_space α] section is_lub variables [preorder α] [Sup_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_top_is_lub (h_mono : monotone f) (ha : is_lub (set.range f) a) : tendsto f at_top (𝓝 a) := begin suffices : tendsto (range_factorization f) at_top at_top, from (Sup_convergence_class.tendsto_coe_at_top_is_lub _ _ ha).comp this, exact h_mono.range_factorization.tendsto_at_top_at_top (λ b, b.2.imp $ λ a ha, ha.ge) end lemma tendsto_at_bot_is_lub (h_anti : antitone f) (ha : is_lub (set.range f) a) : tendsto f at_bot (𝓝 a) := by convert tendsto_at_top_is_lub h_anti.dual_left ha end is_lub section is_glb variables [preorder α] [Inf_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_bot_is_glb (h_mono : monotone f) (ha : is_glb (set.range f) a) : tendsto f at_bot (𝓝 a) := by convert tendsto_at_top_is_lub h_mono.dual ha.dual lemma tendsto_at_top_is_glb (h_anti : antitone f) (ha : is_glb (set.range f) a) : tendsto f at_top (𝓝 a) := by convert tendsto_at_bot_is_lub h_anti.dual ha.dual end is_glb section csupr variables [conditionally_complete_lattice α] [Sup_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_top_csupr (h_mono : monotone f) (hbdd : bdd_above $ range f) : tendsto f at_top (𝓝 (⨆i, f i)) := begin casesI is_empty_or_nonempty ι, exacts [tendsto_of_is_empty, tendsto_at_top_is_lub h_mono (is_lub_csupr hbdd)] end lemma tendsto_at_bot_csupr (h_anti : antitone f) (hbdd : bdd_above $ range f) : tendsto f at_bot (𝓝 (⨆ i, f i)) := by convert tendsto_at_top_csupr h_anti.dual hbdd.dual end csupr section cinfi variables [conditionally_complete_lattice α] [Inf_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_bot_cinfi (h_mono : monotone f) (hbdd : bdd_below $ range f) : tendsto f at_bot (𝓝 (⨅ i, f i)) := by convert tendsto_at_top_csupr h_mono.dual hbdd.dual lemma tendsto_at_top_cinfi (h_anti : antitone f) (hbdd : bdd_below $ range f) : tendsto f at_top (𝓝 (⨅ i, f i)) := by convert tendsto_at_bot_csupr h_anti.dual hbdd.dual end cinfi section supr variables [complete_lattice α] [Sup_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_top_supr (h_mono : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) := tendsto_at_top_csupr h_mono (order_top.bdd_above _) lemma tendsto_at_bot_supr (h_anti : antitone f) : tendsto f at_bot (𝓝 (⨆i, f i)) := tendsto_at_bot_csupr h_anti (order_top.bdd_above _) end supr section infi variables [complete_lattice α] [Inf_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_bot_infi (h_mono : monotone f) : tendsto f at_bot (𝓝 (⨅i, f i)) := tendsto_at_bot_cinfi h_mono (order_bot.bdd_below _) lemma tendsto_at_top_infi (h_anti : antitone f) : tendsto f at_top (𝓝 (⨅i, f i)) := tendsto_at_top_cinfi h_anti (order_bot.bdd_below _) end infi end instance [preorder α] [preorder β] [topological_space α] [topological_space β] [Sup_convergence_class α] [Sup_convergence_class β] : Sup_convergence_class (α × β) := begin constructor, rintro ⟨a, b⟩ s h, rw [is_lub_prod, ← range_restrict, ← range_restrict] at h, have A : tendsto (λ x : s, (x : α × β).1) at_top (𝓝 a), from tendsto_at_top_is_lub (monotone_fst.restrict s) h.1, have B : tendsto (λ x : s, (x : α × β).2) at_top (𝓝 b), from tendsto_at_top_is_lub (monotone_snd.restrict s) h.2, convert A.prod_mk_nhds B, ext1 ⟨⟨x, y⟩, h⟩, refl end instance [preorder α] [preorder β] [topological_space α] [topological_space β] [Inf_convergence_class α] [Inf_convergence_class β] : Inf_convergence_class (α × β) := show Inf_convergence_class (αᵒᵈ × βᵒᵈ)ᵒᵈ, from order_dual.Inf_convergence_class instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)] [Π i, Sup_convergence_class (α i)] : Sup_convergence_class (Π i, α i) := begin refine ⟨λ f s h, _⟩, simp only [is_lub_pi, ← range_restrict] at h, exact tendsto_pi_nhds.2 (λ i, tendsto_at_top_is_lub ((monotone_eval _).restrict _) (h i)) end instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)] [Π i, Inf_convergence_class (α i)] : Inf_convergence_class (Π i, α i) := show Inf_convergence_class (Π i, (α i)ᵒᵈ)ᵒᵈ, from order_dual.Inf_convergence_class instance pi.Sup_convergence_class' {ι : Type*} [preorder α] [topological_space α] [Sup_convergence_class α] : Sup_convergence_class (ι → α) := pi.Sup_convergence_class instance pi.Inf_convergence_class' {ι : Type*} [preorder α] [topological_space α] [Inf_convergence_class α] : Inf_convergence_class (ι → α) := pi.Inf_convergence_class lemma tendsto_of_monotone {ι α : Type*} [preorder ι] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) : tendsto f at_top at_top ∨ (∃ l, tendsto f at_top (𝓝 l)) := if H : bdd_above (range f) then or.inr ⟨_, tendsto_at_top_csupr h_mono H⟩ else or.inl $ tendsto_at_top_at_top_of_monotone' h_mono H lemma tendsto_iff_tendsto_subseq_of_monotone {ι₁ ι₂ α : Type*} [semilattice_sup ι₁] [preorder ι₂] [nonempty ι₁] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] [no_max_order α] {f : ι₂ → α} {φ : ι₁ → ι₂} {l : α} (hf : monotone f) (hg : tendsto φ at_top at_top) : tendsto f at_top (𝓝 l) ↔ tendsto (f ∘ φ) at_top (𝓝 l) := begin split; intro h, { exact h.comp hg }, { rcases tendsto_of_monotone hf with h' | ⟨l', hl'⟩, { exact (not_tendsto_at_top_of_tendsto_nhds h (h'.comp hg)).elim }, { rwa tendsto_nhds_unique h (hl'.comp hg) } } end /-! The next family of results, such as `is_lub_of_tendsto_at_top` and `supr_eq_of_tendsto`, are converses to the standard fact that bounded monotone functions converge. They state, that if a monotone function `f` tends to `a` along `filter.at_top`, then that value `a` is a least upper bound for the range of `f`. Related theorems above (`is_lub.is_lub_of_tendsto`, `is_glb.is_glb_of_tendsto` etc) cover the case when `f x` tends to `a` as `x` tends to some point `b` in the domain. -/ lemma monotone.ge_of_tendsto [topological_space α] [preorder α] [order_closed_topology α] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) (ha : tendsto f at_top (𝓝 a)) (b : β) : f b ≤ a := begin haveI : nonempty β := nonempty.intro b, exact ge_of_tendsto ha ((eventually_ge_at_top b).mono (λ _ hxy, hf hxy)) end lemma monotone.le_of_tendsto [topological_space α] [preorder α] [order_closed_topology α] [semilattice_inf β] {f : β → α} {a : α} (hf : monotone f) (ha : tendsto f at_bot (𝓝 a)) (b : β) : a ≤ f b := hf.dual.ge_of_tendsto ha b lemma antitone.le_of_tendsto [topological_space α] [preorder α] [order_closed_topology α] [semilattice_sup β] {f : β → α} {a : α} (hf : antitone f) (ha : tendsto f at_top (𝓝 a)) (b : β) : a ≤ f b := hf.dual_right.ge_of_tendsto ha b lemma antitone.ge_of_tendsto [topological_space α] [preorder α] [order_closed_topology α] [semilattice_inf β] {f : β → α} {a : α} (hf : antitone f) (ha : tendsto f at_bot (𝓝 a)) (b : β) : f b ≤ a := hf.dual_right.le_of_tendsto ha b lemma is_lub_of_tendsto_at_top [topological_space α] [preorder α] [order_closed_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) (ha : tendsto f at_top (𝓝 a)) : is_lub (set.range f) a := begin split, { rintros _ ⟨b, rfl⟩, exact hf.ge_of_tendsto ha b }, { exact λ _ hb, le_of_tendsto' ha (λ x, hb (set.mem_range_self x)) } end lemma is_glb_of_tendsto_at_bot [topological_space α] [preorder α] [order_closed_topology α] [nonempty β] [semilattice_inf β] {f : β → α} {a : α} (hf : monotone f) (ha : tendsto f at_bot (𝓝 a)) : is_glb (set.range f) a := @is_lub_of_tendsto_at_top αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ hf.dual ha lemma is_lub_of_tendsto_at_bot [topological_space α] [preorder α] [order_closed_topology α] [nonempty β] [semilattice_inf β] {f : β → α} {a : α} (hf : antitone f) (ha : tendsto f at_bot (𝓝 a)) : is_lub (set.range f) a := @is_lub_of_tendsto_at_top α βᵒᵈ _ _ _ _ _ _ _ hf.dual_left ha lemma is_glb_of_tendsto_at_top [topological_space α] [preorder α] [order_closed_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : antitone f) (ha : tendsto f at_top (𝓝 a)) : is_glb (set.range f) a := @is_glb_of_tendsto_at_bot α βᵒᵈ _ _ _ _ _ _ _ hf.dual_left ha lemma supr_eq_of_tendsto {α β} [topological_space α] [complete_linear_order α] [order_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) : tendsto f at_top (𝓝 a) → supr f = a := tendsto_nhds_unique (tendsto_at_top_supr hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : antitone f) : tendsto f at_top (𝓝 a) → infi f = a := tendsto_nhds_unique (tendsto_at_top_infi hf) lemma supr_eq_supr_subseq_of_monotone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α] {l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : monotone f) (hφ : tendsto φ l at_top) : (⨆ i, f i) = (⨆ i, f (φ i)) := le_antisymm (supr_mono' $ λ i, exists_imp_exists (λ j (hj : i ≤ φ j), hf hj) (hφ.eventually $ eventually_ge_at_top i).exists) (supr_mono' $ λ i, ⟨φ i, le_rfl⟩) lemma infi_eq_infi_subseq_of_monotone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α] {l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : monotone f) (hφ : tendsto φ l at_bot) : (⨅ i, f i) = (⨅ i, f (φ i)) := supr_eq_supr_subseq_of_monotone hf.dual hφ
8f0785bb46a108b7e2ce1050e3dac560560846e1
392d28f7e76ae84b38b6424255b29b4a4af0d129
/assignments/assignment_3/assignment_3.lean
e1c2179f33b77f8474f974e8d28a409b5f9f8421
[]
no_license
dg-1225/complogic-s21
dd7349fd5288ec6c7bad3b0fe27987cfe176dc67
f46b0bce48bbefbfbcdbc3da904a85c5f643ef58
refs/heads/master
1,678,017,116,497
1,613,794,266,000
1,613,794,266,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,679
lean
/- HIGHER-ORDER FUNCTION WARMUP -/ /- 1. Write a function, double, that takes a natural number and returns its double. Write it using the following recursive definition: - double 0 = 0 - double (n' + 1) = double n' + 2 -/ -- ANSWER HERE /- 2. Write a function, map_list_nat, that takes as its arguments (1) a list, l, of natural numbers, and (2) a function, f, from nat to nat, and that returns a new list of natural numbers constructed by applying f to each element of l. Make f the first argument and l the second. The function will work by case analysis and recursion on l. -/ -- ANSWER HERE /- 3. Test your map_list_nat function by applying it to several lists, both empty and not, passing double as the function value. Include [], [2], and [1,2,3] in your set of test inputs and use comments to document the expected return values. -/ /- 4. In Lean, repr is an "overloaded" function. When applied to a value of a type for which it's defined (we'll see later how that happens) it returns a string representation of the value. It is defined for the nat type, and so when applied to a nat value it returns a corresponding string. It's "toString" for Lean. Here's an example. -/ #eval repr 5 /- Write a function map_list_nat_string that takes a list of nat values and returns a list of strings in which each nat in the given list has been converted to a string using repr. -/ -- ANSWER HERE /- 5. Write a function, filterZeros, that takes a list of natural numbers and returns the same list but with any and all zero values removed. Given [0], for example, it should return []; given [1,2,0,3,4,0, 0, 5] it should return [1,2,3,4,5]. -/ -- ANSWER HERE /- 6. Write a function, isEqN, that takes a natural number, n, and returns a function that takes a natural number, m, and returns true (tt) if m = n and that returns false (ff) otherwise. Be sure to test your function. -/ -- ANSWER HERE /- 7. Write a function filterNs that takes a function, pred, from nat to bool and a list, l, of natural numbers, and that returns a list like l but with all the numbers that satisfy the predicate function removed. Test your function using isEqN to produce a few predicate functions (functions that for a given argument return true or false). -/ -- ANSWER HERE /- 8. Write a function, iterate, that takes as its arguments (1) a function, f, of type nat → nat, and (2) a natural number, n, and that returns a function that takes an argument, (m : nat), and that returns the result of applying f to m n times. For example, if n = 3, it should return f (f (f m)). The result of applying f zero times is just m. Hint: use case analysis on n, and recursion. Test your function using nat.succ, your double function, and (nat.add 4) as function arguments. -/ -- ANSWER HERE /- 9. Write a function, list_add, that takes a list of natural numbers and returns the sum of all the numbers in the list. -/ -- ANSWER HERE /- 10. Write a function, list_mul, that takes a list of natural numbers and returns the product of all the numbers in the list. -/ -- ANSWER HERE /- 11. Write a function, list_has_zero, that takes a list of natural numbers and returns tt if the list contains any zero values and that returns false otherwise. Use isEqN in your solution. Test your solution on both empty and non-empty lists including lists that both have and don't have zero values. -/ -- ANSWER HERE /- 12. Write a function, compose_nat_nat, that takes two functions, f : ℕ → ℕ, and g : ℕ → ℕ, and that returns a function that takes a nat, n, and that returns g (f n). Test your function using at least nat.succ and double as argument values. -/ -- ANSWER HERE /- 13. Write a polymorphic map_box function of type Π (α β : Type u), (α → β) → box α → box β that takes a function, f, of type (α → β), and a box, b, containing a value of type α and that returns a box containing that value transformed by the application of f. -/ -- ANSWER HERE /- 14. Write a function, map_option, that takes a function, f, of type α → β and an option α and that transforms it into an option β, where none goes to none, and some (a : α) goes to some b, where b is a transformed by f. -/ -- ANSWER HERE /- 15. Write three functions, default_nat, default_bool, and default_list α, each taking no arguments (other than a type, argument, α, in the third case), and each returning a default value of the given type: a nat, a bool, and a list. Don't overthink this: Yes, a function that takes no arguments is basically a constant. You'll need to declare a universe variable for the list problem. -/ -- ANSWER HERE
3438a18e09436a66e52d21e04537effc2e7dfb31
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/algebra/ring/basic.lean
98bdd6052f24e04bcda0866a8df877a7279b4a8f
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
42,236
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland -/ import algebra.divisibility import data.set.basic /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types. The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. ## Tags `ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `integral_domain`, `nonzero`, `units` -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} set_option old_structure_cmd true open function /-! ### `distrib` class -/ /-- A typeclass stating that multiplication is left and right distributive over addition. -/ @[protect_proj, ancestor has_mul has_add] class distrib (R : Type*) extends has_mul R, has_add R := (left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c alias left_distrib ← mul_add lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c alias right_distrib ← add_mul /-- Pullback a `distrib` instance along an injective function. -/ protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S] (f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib R := { mul := (*), add := (+), left_distrib := λ x y z, hf $ by simp only [*, left_distrib], right_distrib := λ x y z, hf $ by simp only [*, right_distrib] } /-- Pushforward a `distrib` instance along a surjective function. -/ protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S] (f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib S := { mul := (*), add := (+), left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib], right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] } /-! ### Semirings -/ /-- A semiring is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative monoid (`monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). The actual definition extends `monoid_with_zero` instead of `monoid` and `mul_zero_class`. -/ @[protect_proj, ancestor add_comm_monoid monoid_with_zero distrib] class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α section semiring variables [semiring α] /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pushforward a `semiring` instance along a surjective function. -/ protected def function.surjective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `∑ x in s, (f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = ite P a 0 * b := by { by_cases h : P; simp [h], } lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = a * ite P b 0 := by { by_cases h : P; simp [h], } /-- An element `a` of a semiring is even if there exists `k` such `a = 2*k`. -/ def even (a : α) : Prop := ∃ k, a = 2*k lemma even_iff_two_dvd {a : α} : even a ↔ 2 ∣ a := iff.rfl /-- An element `a` of a semiring is odd if there exists `k` such `a = 2*k + 1`. -/ def odd (a : α) : Prop := ∃ k, a = 2*k + 1 theorem dvd_add {a b c : α} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma coe_mul_right {R : Type*} [semiring R] (r : R) : ⇑(mul_right r) = (* r) := rfl lemma mul_right_apply {R : Type*} [semiring R] (a r : R) : mul_right r a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. This extends from both `monoid_hom` and `monoid_with_zero_hom` in order to put the fields in a sensible order, even though `monoid_with_zero_hom` already extends `monoid_hom`. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β, monoid_with_zero_hom α β infixr ` →+* `:25 := ring_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a `monoid_with_zero_hom R S`. The `simp`-normal form is `(f : monoid_with_zero_hom R S)`. -/ add_decl_doc ring_hom.to_monoid_with_zero_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a monoid homomorphism `R →* S`. The `simp`-normal form is `(f : R →* S)`. -/ add_decl_doc ring_hom.to_monoid_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as an additive monoid homomorphism `R →+ S`. The `simp`-normal form is `(f : R →+ S)`. -/ add_decl_doc ring_hom.to_add_monoid_hom namespace ring_hom section coe /-! Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ variables {rα : semiring α} {rβ : semiring β} include rα rβ instance : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ initialize_simps_projections ring_hom (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl instance has_coe_monoid_hom : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp] lemma to_monoid_hom_eq_coe (f : α →+* β) : f.to_monoid_hom = f := rfl @[simp] lemma coe_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →* β) = ⟨f, h₁, h₂⟩ := rfl instance has_coe_add_monoid_hom : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_add_monoid_hom (f : α →+* β) : ⇑(f : α →+ β) = f := rfl @[simp] lemma to_add_monoid_hom_eq_coe (f : α →+* β) : f.to_add_monoid_hom = f := rfl @[simp] lemma coe_add_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →+ β) = ⟨f, h₃, h₄⟩ := rfl end coe variables [rα : semiring α] [rβ : semiring β] section include rα rβ variables (f : α →+* β) {x y : α} {rα rβ} theorem congr_fun {f g : α →+* β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →+* β, h x) h theorem congr_arg (f : α →+* β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma mk_coe (f : α →+* β) (h₁ h₂ h₃ h₄) : ring_hom.mk f h₁ h₂ h₃ h₄ = f := ext $ λ _, rfl theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, ext (λ x, add_monoid_hom.congr_fun h x) theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, ext (λ x, monoid_hom.congr_fun h x) /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b /-- Ring homomorphisms preserve `bit0`. -/ @[simp] lemma map_bit0 (f : α →+* β) (a : α) : f (bit0 a) = bit0 (f a) := map_add _ _ _ /-- Ring homomorphisms preserve `bit1`. -/ @[simp] lemma map_bit1 (f : α →+* β) (a : α) : f (bit1 a) = bit1 (f a) := by simp [bit1] /-- `f : R →+* S` has a trivial codomain iff `f 1 = 0`. -/ lemma codomain_trivial_iff_map_one_eq_zero : (0 : β) = 1 ↔ f 1 = 0 := by rw [map_one, eq_comm] /-- `f : R →+* S` has a trivial codomain iff it has a trivial range. -/ lemma codomain_trivial_iff_range_trivial : (0 : β) = 1 ↔ (∀ x, f x = 0) := f.codomain_trivial_iff_map_one_eq_zero.trans ⟨λ h x, by rw [←mul_one x, map_mul, h, mul_zero], λ h, h 1⟩ /-- `f : R →+* S` has a trivial codomain iff its range is `{0}`. -/ lemma codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ set.range f = {0} := f.codomain_trivial_iff_range_trivial.trans ⟨ λ h, set.ext (λ y, ⟨λ ⟨x, hx⟩, by simp [←hx, h x], λ hy, ⟨0, by simpa using hy.symm⟩⟩), λ h x, set.mem_singleton_iff.mp (h ▸ set.mem_range_self x)⟩ /-- `f : R →+* S` doesn't map `1` to `0` if `S` is nontrivial -/ lemma map_one_ne_zero [nontrivial β] : f 1 ≠ 0 := mt f.codomain_trivial_iff_map_one_eq_zero.mpr zero_ne_one /-- If there is a homomorphism `f : R →+* S` and `S` is nontrivial, then `R` is nontrivial. -/ lemma domain_nontrivial [nontrivial β] : nontrivial α := ⟨⟨1, 0, mt (λ h, show f 1 = 0, by rw [h, map_zero]) f.map_one_ne_zero⟩⟩ lemma is_unit_map (f : α →+* β) {a : α} (h : is_unit a) : is_unit (f a) := h.map (f.to_monoid_hom) end /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα instance : inhabited (α →+* α) := ⟨id α⟩ @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom /-- A commutative semiring is a `semiring` with commutative multiplication. In other words, it is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative commutative monoid (`comm_monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). -/ @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α := { .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α } section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := by simp only [two_mul, add_mul, mul_add, add_assoc, mul_comm b] @[simp] theorem two_dvd_bit0 : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩ lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /-! ### Rings -/ /-- A ring is a type with the following structures: additive commutative group (`add_comm_group`), multiplicative monoid (`monoid`), and distributive laws (`distrib`). Equivalently, a ring is a `semiring` with a negation operation making it an additive group. -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ @[priority 200] instance ring.to_semiring : semiring α := { zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0, by rw [← add_mul, zero_add, add_zero], mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0, by rw [← mul_add, add_zero, add_zero], ..‹ring α› } /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.injective.ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : ring β := { .. hf.add_comm_group_sub f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.surjective.ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : ring β := { .. hf.add_comm_group_sub f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul } lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := by simpa only [sub_eq_add_neg, neg_mul_eq_mul_neg] using mul_add a b (-c) alias mul_sub_left_distrib ← mul_sub lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := by simpa only [sub_eq_add_neg, neg_mul_eq_neg_mul] using add_mul a (-b) c alias mul_sub_right_distrib ← sub_mul /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl @[simp, norm_cast] protected theorem coe_neg_one : ((-1 : units α) : α) = -1 := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [semiring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom /-- A commutative ring is a `ring` with commutative multiplication. -/ @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_semigroup α @[priority 100] -- see Note [lower instance priority] instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} /-- Pullback a `comm_ring` instance along an injective function. -/ protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.injective.comm_ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : comm_ring β := { .. hf.ring_sub f zero one add mul neg sub, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function. -/ protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.surjective.comm_ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : comm_ring β := { .. hf.ring_sub f zero one add mul neg sub, .. hf.comm_semigroup f mul } local attribute [simp] add_assoc add_comm add_left_comm mul_comm theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := by { rw sub_eq_add_neg, exact dvd_add h₁ (dvd_neg_of_dvd h₂) } theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] lemma mul_self_sub_one (a : α) : a * a - 1 = (a + 1) * (a - 1) := by rw [← mul_self_sub_mul_self, mul_one] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end comm_ring lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by simpa [sub_eq_add_neg] using h))) /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α, nontrivial α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) section domain variable [domain α] @[priority 100] -- see Note [lower instance priority] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α := { mul_left_cancel_of_ne_zero := λ a b c ha, by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] }, mul_right_cancel_of_ne_zero := λ a b c hb, by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] }, .. (infer_instance : semiring α) } /-- Pullback a `domain` instance along an injective function. -/ protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : domain β := { .. hf.ring f zero one add mul neg, .. pullback_nonzero f zero one, .. hf.no_zero_divisors f zero mul } end domain /-! ### Integral domains -/ /-- An integral domain is a commutative ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, an integral domain is a domain with commutative multiplication. -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} @[priority 100] -- see Note [lower instance priority] instance integral_domain.to_comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero α := { ..comm_semiring.to_comm_monoid_with_zero, ..domain.to_cancel_monoid_with_zero } /-- Pullback an `integral_domain` instance along an injective function. -/ protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : integral_domain β := { .. hf.comm_ring f zero one add mul neg, .. hf.domain f zero one add mul neg } lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b := by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero, add_eq_zero_iff_eq_neg] lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 := by rw [← mul_self_eq_mul_self_iff, one_mul] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff } /-- Makes a ring homomorphism from an additive group homomorphism from a commutative ring to an integral domain that commutes with self multiplication, assumes that two is nonzero and one is sent to one. -/ def add_monoid_hom.mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h : ∀ x, f (x * x) = f x * f x) (h_two : (2 : α) ≠ 0) (h_one : f 1 = 1) : β →+* α := { map_one' := h_one, map_mul' := begin intros x y, have hxy := h (x + y), rw [mul_add, add_mul, add_mul, f.map_add, f.map_add, f.map_add, f.map_add, h x, h y, add_mul, mul_add, mul_add, ← sub_eq_zero_iff_eq, add_comm, ← sub_sub, ← sub_sub, ← sub_sub, mul_comm y x, mul_comm (f y) (f x)] at hxy, simp only [add_assoc, add_sub_assoc, add_sub_cancel'_right] at hxy, rw [sub_sub, ← two_mul, ← add_sub_assoc, ← two_mul, ← mul_sub, mul_eq_zero, sub_eq_zero_iff_eq, or_iff_not_imp_left] at hxy, exact hxy h_two, end, ..f } @[simp] lemma add_monoid_hom.coe_fn_mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h h_two h_one) : (f.mk_ring_hom_of_mul_self_of_two_ne_zero h h_two h_one : β → α) = f := rfl @[simp] lemma add_monoid_hom.coe_add_monoid_hom_mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h h_two h_one) : (f.mk_ring_hom_of_mul_self_of_two_ne_zero h h_two h_one : β →+ α) = f := by {ext, simp} end integral_domain namespace ring variables {M₀ : Type*} [monoid_with_zero M₀] open_locale classical /-- Introduce a function `inverse` on a monoid with zero `M₀`, which sends `x` to `x⁻¹` if `x` is invertible and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. Note that while this is in the `ring` namespace for brevity, it requires the weaker assumption `monoid_with_zero M₀` instead of `ring M₀`. -/ noncomputable def inverse : M₀ → M₀ := λ x, if h : is_unit x then (((classical.some h)⁻¹ : units M₀) : M₀) else 0 /-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/ @[simp] lemma inverse_unit (u : units M₀) : inverse (u : M₀) = (u⁻¹ : units M₀) := begin simp only [is_unit_unit, inverse, dif_pos], exact units.inv_unique (classical.some_spec (is_unit_unit u)) end /-- By definition, if `x` is not invertible then `inverse x = 0`. -/ @[simp] lemma inverse_non_unit (x : M₀) (h : ¬(is_unit x)) : inverse x = 0 := dif_neg h end ring /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) -- The linter does not recognize that is_integral_domain.to_nontrivial is a structure -- projection, disable it attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) } namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] variables [ring R] {a b x y x' y' : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := by simpa only [sub_eq_add_neg] using h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := by simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left end semiconj_by namespace commute @[simp] theorem add_right [distrib R] {a b c : R} : commute a b → commute a c → commute a (b + c) := semiconj_by.add_right @[simp] theorem add_left [distrib R] {a b c : R} : commute a c → commute b c → commute (a + b) c := semiconj_by.add_left variables [ring R] {a b c : R} theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right @[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left @[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff @[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a @[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a @[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right @[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left end commute
013f10c96eb0425edee61fb0090344b7a523cb80
d744d97b07fc1e61b0ebea192b2d624125898128
/test/nat_test.lean
37967ca95d3ac8fa6f5369741d039edfa59e1fa8
[ "MIT" ]
permissive
parkersullivan/leanstuff
019c757848dd8f5db185e6973969141aee6fef7c
3da132c44d365ecd933de64fa04ba66b9e620683
refs/heads/master
1,599,036,040,845
1,573,316,625,000
1,573,316,625,000
219,181,711
0
0
null
null
null
null
UTF-8
Lean
false
false
410
lean
import ..src.nat open my_nat /-testing the decrement function-/ #eval dec my_nat.nat.zero #eval dec (my_nat.nat.succ my_nat.nat.zero) #eval dec (my_nat.nat.succ (my_nat.nat.succ my_nat.nat.zero)) def n0 := my_nat.nat.zero def n1 := my_nat.nat.succ n0 def n2 := my_nat.nat.succ n1 def n3 := my_nat.nat.succ n2 def n4 := my_nat.nat.succ n3 #eval ltb n0 n1 #eval ltb n1 n0 #eval ltb n3 n4 #eval ltb n4 n3
844cd2583914a92647c4c6dedf3d80c910fff167
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/ordered_group_auto.lean
4f5f5ca5dd3efad54f597e57f9006eb5ad46262e
[]
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
43,551
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.ordered_monoid import Mathlib.PostPort universes u l u_1 u_2 namespace Mathlib /-! # Ordered groups This file develops the basics of ordered groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ class ordered_add_comm_group (α : Type u) extends partial_order α, add_comm_group α where add_le_add_left : ∀ (a b : α), a ≤ b → ∀ (c : α), c + a ≤ c + b /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ class ordered_comm_group (α : Type u) extends comm_group α, partial_order α where mul_le_mul_left : ∀ (a b : α), a ≤ b → ∀ (c : α), c * a ≤ c * b /--The units of an ordered commutative monoid form an ordered commutative group. -/ protected instance add_units.ordered_add_comm_group {α : Type u} [ordered_add_comm_monoid α] : ordered_add_comm_group (add_units α) := ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry partial_order.le partial_order.lt sorry sorry sorry sorry theorem ordered_comm_group.mul_lt_mul_left' {α : Type u} [ordered_comm_group α] (a : α) (b : α) (h : a < b) (c : α) : c * a < c * b := sorry theorem ordered_comm_group.le_of_mul_le_mul_left {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a * b ≤ a * c) : b ≤ c := sorry theorem ordered_comm_group.lt_of_mul_lt_mul_left {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a * b < a * c) : b < c := sorry protected instance ordered_add_comm_group.to_ordered_cancel_add_comm_monoid (α : Type u) [s : ordered_add_comm_group α] : ordered_cancel_add_comm_monoid α := ordered_cancel_add_comm_monoid.mk ordered_add_comm_group.add ordered_add_comm_group.add_assoc sorry ordered_add_comm_group.zero ordered_add_comm_group.zero_add ordered_add_comm_group.add_zero ordered_add_comm_group.add_comm sorry ordered_add_comm_group.le ordered_add_comm_group.lt ordered_add_comm_group.le_refl ordered_add_comm_group.le_trans ordered_add_comm_group.le_antisymm ordered_add_comm_group.add_le_add_left ordered_add_comm_group.le_of_add_le_add_left theorem neg_le_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a ≤ b) : -b ≤ -a := sorry theorem le_of_inv_le_inv {α : Type u} [ordered_comm_group α] {a : α} {b : α} (h : b⁻¹ ≤ (a⁻¹)) : a ≤ b := sorry theorem one_le_of_inv_le_one {α : Type u} [ordered_comm_group α] {a : α} (h : a⁻¹ ≤ 1) : 1 ≤ a := (fun (this : a⁻¹ ≤ (1⁻¹)) => le_of_inv_le_inv this) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ ≤ (1⁻¹))) one_inv)) h) theorem inv_le_one_of_one_le {α : Type u} [ordered_comm_group α] {a : α} (h : 1 ≤ a) : a⁻¹ ≤ 1 := (fun (this : a⁻¹ ≤ (1⁻¹)) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ ≤ (1⁻¹))) one_inv) this) (inv_le_inv' h) theorem le_one_of_one_le_inv {α : Type u} [ordered_comm_group α] {a : α} (h : 1 ≤ (a⁻¹)) : a ≤ 1 := (fun (this : 1⁻¹ ≤ (a⁻¹)) => le_of_inv_le_inv this) (eq.mpr (id (Eq._oldrec (Eq.refl (1⁻¹ ≤ (a⁻¹))) one_inv)) h) theorem neg_nonneg_of_nonpos {α : Type u} [ordered_add_comm_group α] {a : α} (h : a ≤ 0) : 0 ≤ -a := (fun (this : -0 ≤ -a) => eq.mp (Eq._oldrec (Eq.refl (-0 ≤ -a)) neg_zero) this) (neg_le_neg h) theorem neg_lt_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a < b) : -b < -a := sorry theorem lt_of_neg_lt_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : -b < -a) : a < b := neg_neg a ▸ neg_neg b ▸ neg_lt_neg h theorem pos_of_neg_neg {α : Type u} [ordered_add_comm_group α] {a : α} (h : -a < 0) : 0 < a := (fun (this : -a < -0) => lt_of_neg_lt_neg this) (eq.mpr (id (Eq._oldrec (Eq.refl (-a < -0)) neg_zero)) h) theorem inv_inv_of_one_lt {α : Type u} [ordered_comm_group α] {a : α} (h : 1 < a) : a⁻¹ < 1 := (fun (this : a⁻¹ < (1⁻¹)) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ < (1⁻¹))) one_inv) this) (inv_lt_inv' h) theorem inv_of_one_lt_inv {α : Type u} [ordered_comm_group α] {a : α} (h : 1 < (a⁻¹)) : a < 1 := (fun (this : 1⁻¹ < (a⁻¹)) => lt_of_inv_lt_inv this) (eq.mpr (id (Eq._oldrec (Eq.refl (1⁻¹ < (a⁻¹))) one_inv)) h) theorem one_lt_inv_of_inv {α : Type u} [ordered_comm_group α] {a : α} (h : a < 1) : 1 < (a⁻¹) := (fun (this : 1⁻¹ < (a⁻¹)) => eq.mp (Eq._oldrec (Eq.refl (1⁻¹ < (a⁻¹))) one_inv) this) (inv_lt_inv' h) theorem le_inv_of_le_inv {α : Type u} [ordered_comm_group α] {a : α} {b : α} (h : a ≤ (b⁻¹)) : b ≤ (a⁻¹) := eq.mp (Eq._oldrec (Eq.refl (b⁻¹⁻¹ ≤ (a⁻¹))) (inv_inv b)) (inv_le_inv' h) theorem neg_le_of_neg_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : -a ≤ b) : -b ≤ a := eq.mp (Eq._oldrec (Eq.refl (-b ≤ --a)) (neg_neg a)) (neg_le_neg h) theorem lt_inv_of_lt_inv {α : Type u} [ordered_comm_group α] {a : α} {b : α} (h : a < (b⁻¹)) : b < (a⁻¹) := eq.mp (Eq._oldrec (Eq.refl (b⁻¹⁻¹ < (a⁻¹))) (inv_inv b)) (inv_lt_inv' h) theorem neg_lt_of_neg_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : -a < b) : -b < a := eq.mp (Eq._oldrec (Eq.refl (-b < --a)) (neg_neg a)) (neg_lt_neg h) theorem add_le_of_le_neg_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : b ≤ -a + c) : a + b ≤ c := eq.mp (Eq._oldrec (Eq.refl (a + b ≤ a + (-a + c))) (add_neg_cancel_left a c)) (add_le_add_left h a) theorem le_inv_mul_of_mul_le {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a * b ≤ c) : b ≤ a⁻¹ * c := eq.mp (Eq._oldrec (Eq.refl (a⁻¹ * (a * b) ≤ a⁻¹ * c)) (inv_mul_cancel_left a b)) (mul_le_mul_left' h (a⁻¹)) theorem le_mul_of_inv_mul_le {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : b⁻¹ * a ≤ c) : a ≤ b * c := eq.mp (Eq._oldrec (Eq.refl (b * (b⁻¹ * a) ≤ b * c)) (mul_inv_cancel_left b a)) (mul_le_mul_left' h b) theorem inv_mul_le_of_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a ≤ b * c) : b⁻¹ * a ≤ c := eq.mp (Eq._oldrec (Eq.refl (b⁻¹ * a ≤ b⁻¹ * (b * c))) (inv_mul_cancel_left b c)) (mul_le_mul_left' h (b⁻¹)) theorem le_mul_of_inv_mul_le_left {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : b⁻¹ * a ≤ c) : a ≤ b * c := le_mul_of_inv_mul_le h theorem neg_add_le_left_of_le_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a ≤ b + c) : -b + a ≤ c := neg_add_le_of_le_add h theorem le_add_of_neg_add_le_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : -c + a ≤ b) : a ≤ b + c := eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ b + c)) (add_comm b c))) (le_add_of_neg_add_le h) theorem inv_mul_le_right_of_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : a ≤ b * c) : c⁻¹ * a ≤ b := inv_mul_le_left_of_le_mul (eq.mp (Eq._oldrec (Eq.refl (a ≤ b * c)) (mul_comm b c)) h) theorem mul_lt_of_lt_inv_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : b < a⁻¹ * c) : a * b < c := eq.mp (Eq._oldrec (Eq.refl (a * b < a * (a⁻¹ * c))) (mul_inv_cancel_left a c)) (mul_lt_mul_left' h a) theorem lt_neg_add_of_add_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a + b < c) : b < -a + c := eq.mp (Eq._oldrec (Eq.refl (-a + (a + b) < -a + c)) (neg_add_cancel_left a b)) (add_lt_add_left h (-a)) theorem lt_mul_of_inv_mul_lt {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} (h : b⁻¹ * a < c) : a < b * c := eq.mp (Eq._oldrec (Eq.refl (b * (b⁻¹ * a) < b * c)) (mul_inv_cancel_left b a)) (mul_lt_mul_left' h b) theorem neg_add_lt_of_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a < b + c) : -b + a < c := eq.mp (Eq._oldrec (Eq.refl (-b + a < -b + (b + c))) (neg_add_cancel_left b c)) (add_lt_add_left h (-b)) theorem lt_add_of_neg_add_lt_left {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : -b + a < c) : a < b + c := lt_add_of_neg_add_lt h theorem neg_add_lt_left_of_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a < b + c) : -b + a < c := neg_add_lt_of_lt_add h theorem lt_add_of_neg_add_lt_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : -c + a < b) : a < b + c := eq.mpr (id (Eq._oldrec (Eq.refl (a < b + c)) (add_comm b c))) (lt_add_of_neg_add_lt h) theorem neg_add_lt_right_of_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : a < b + c) : -c + a < b := neg_add_lt_of_lt_add (eq.mp (Eq._oldrec (Eq.refl (a < b + c)) (add_comm b c)) h) @[simp] theorem neg_neg_iff_pos {α : Type u} [ordered_add_comm_group α] {a : α} : -a < 0 ↔ 0 < a := { mp := pos_of_neg_neg, mpr := neg_neg_of_pos } @[simp] theorem neg_le_neg_iff {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a ≤ -b ↔ b ≤ a := sorry theorem inv_le' {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := (fun (this : a⁻¹ ≤ (b⁻¹⁻¹) ↔ b⁻¹ ≤ a) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ ≤ (b⁻¹⁻¹) ↔ b⁻¹ ≤ a)) (inv_inv b)) this) inv_le_inv_iff theorem le_inv' {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a ≤ (b⁻¹) ↔ b ≤ (a⁻¹) := (fun (this : a⁻¹⁻¹ ≤ (b⁻¹) ↔ b ≤ (a⁻¹)) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹⁻¹ ≤ (b⁻¹) ↔ b ≤ (a⁻¹))) (inv_inv a)) this) inv_le_inv_iff theorem inv_le_iff_one_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a⁻¹ ≤ b ↔ 1 ≤ b * a := iff.trans (iff.symm (mul_le_mul_iff_right a)) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * a ≤ b * a ↔ 1 ≤ b * a)) (inv_mul_self a))) (iff.refl (1 ≤ b * a))) theorem neg_le_iff_add_nonneg' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a ≤ b ↔ 0 ≤ a + b := iff.trans (iff.symm (add_le_add_iff_left a)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + -a ≤ a + b ↔ 0 ≤ a + b)) (add_neg_self a))) (iff.refl (0 ≤ a + b))) theorem inv_lt_iff_one_lt_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a⁻¹ < b ↔ 1 < b * a := iff.trans (iff.symm (mul_lt_mul_iff_right a)) (eq.mpr (id (Eq._oldrec (Eq.refl (a⁻¹ * a < b * a ↔ 1 < b * a)) (inv_mul_self a))) (iff.refl (1 < b * a))) theorem neg_lt_iff_pos_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a < b ↔ 0 < a + b := iff.trans (iff.symm (add_lt_add_iff_left a)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + -a < a + b ↔ 0 < a + b)) (add_neg_self a))) (iff.refl (0 < a + b))) theorem le_neg_iff_add_nonpos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a ≤ -b ↔ a + b ≤ 0 := iff.trans (iff.symm (add_le_add_iff_right b)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + b ≤ -b + b ↔ a + b ≤ 0)) (neg_add_self b))) (iff.refl (a + b ≤ 0))) theorem le_inv_iff_mul_le_one' {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a ≤ (b⁻¹) ↔ b * a ≤ 1 := iff.trans (iff.symm (mul_le_mul_iff_left b)) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a ≤ b * (b⁻¹) ↔ b * a ≤ 1)) (mul_inv_self b))) (iff.refl (b * a ≤ 1))) theorem lt_neg_iff_add_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a < -b ↔ a + b < 0 := iff.trans (iff.symm (add_lt_add_iff_right b)) (eq.mpr (id (Eq._oldrec (Eq.refl (a + b < -b + b ↔ a + b < 0)) (neg_add_self b))) (iff.refl (a + b < 0))) theorem lt_inv_iff_mul_lt_one' {α : Type u} [ordered_comm_group α] {a : α} {b : α} : a < (b⁻¹) ↔ b * a < 1 := iff.trans (iff.symm (mul_lt_mul_iff_left b)) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a < b * (b⁻¹) ↔ b * a < 1)) (mul_inv_self b))) (iff.refl (b * a < 1))) @[simp] theorem inv_le_one' {α : Type u} [ordered_comm_group α] {a : α} : a⁻¹ ≤ 1 ↔ 1 ≤ a := (fun (this : a⁻¹ ≤ (1⁻¹) ↔ 1 ≤ a) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ ≤ (1⁻¹) ↔ 1 ≤ a)) one_inv) this) inv_le_inv_iff @[simp] theorem one_le_inv' {α : Type u} [ordered_comm_group α] {a : α} : 1 ≤ (a⁻¹) ↔ a ≤ 1 := (fun (this : 1⁻¹ ≤ (a⁻¹) ↔ a ≤ 1) => eq.mp (Eq._oldrec (Eq.refl (1⁻¹ ≤ (a⁻¹) ↔ a ≤ 1)) one_inv) this) inv_le_inv_iff theorem inv_le_self {α : Type u} [ordered_comm_group α] {a : α} (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (iff.mpr inv_le_one' h) h theorem self_le_inv {α : Type u} [ordered_comm_group α] {a : α} (h : a ≤ 1) : a ≤ (a⁻¹) := le_trans h (iff.mpr one_le_inv' h) @[simp] theorem neg_lt_neg_iff {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a < -b ↔ b < a := sorry theorem neg_lt_zero {α : Type u} [ordered_add_comm_group α] {a : α} : -a < 0 ↔ 0 < a := (fun (this : -a < -0 ↔ 0 < a) => eq.mp (Eq._oldrec (Eq.refl (-a < -0 ↔ 0 < a)) neg_zero) this) neg_lt_neg_iff theorem one_lt_inv' {α : Type u} [ordered_comm_group α] {a : α} : 1 < (a⁻¹) ↔ a < 1 := (fun (this : 1⁻¹ < (a⁻¹) ↔ a < 1) => eq.mp (Eq._oldrec (Eq.refl (1⁻¹ < (a⁻¹) ↔ a < 1)) one_inv) this) inv_lt_inv_iff theorem neg_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : -a < b ↔ -b < a := (fun (this : -a < --b ↔ -b < a) => eq.mp (Eq._oldrec (Eq.refl (-a < --b ↔ -b < a)) (neg_neg b)) this) neg_lt_neg_iff theorem lt_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a < -b ↔ b < -a := (fun (this : --a < -b ↔ b < -a) => eq.mp (Eq._oldrec (Eq.refl ( --a < -b ↔ b < -a)) (neg_neg a)) this) neg_lt_neg_iff theorem neg_lt_self {α : Type u} [ordered_add_comm_group α] {a : α} (h : 0 < a) : -a < a := has_lt.lt.trans (iff.mpr neg_lt_zero h) h theorem le_inv_mul_iff_mul_le {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : b ≤ a⁻¹ * c ↔ a * b ≤ c := (fun (this : a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c) => eq.mp (Eq._oldrec (Eq.refl (a⁻¹ * (a * b) ≤ a⁻¹ * c ↔ a * b ≤ c)) (inv_mul_cancel_left a b)) this) (mul_le_mul_iff_left (a⁻¹)) @[simp] theorem inv_mul_le_iff_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : b⁻¹ * a ≤ c ↔ a ≤ b * c := (fun (this : b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c) => eq.mp (Eq._oldrec (Eq.refl (b⁻¹ * a ≤ b⁻¹ * (b * c) ↔ a ≤ b * c)) (inv_mul_cancel_left b c)) this) (mul_le_mul_iff_left (b⁻¹)) theorem mul_inv_le_iff_le_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : a * (c⁻¹) ≤ b ↔ a ≤ b * c := sorry @[simp] theorem mul_inv_le_iff_le_mul' {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : a * (b⁻¹) ≤ c ↔ a ≤ b * c := eq.mpr (id (Eq._oldrec (Eq.refl (a * (b⁻¹) ≤ c ↔ a ≤ b * c)) (Eq.symm (propext inv_mul_le_iff_le_mul)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * (b⁻¹) ≤ c ↔ b⁻¹ * a ≤ c)) (mul_comm a (b⁻¹)))) (iff.refl (b⁻¹ * a ≤ c))) theorem neg_add_le_iff_le_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -c + a ≤ b ↔ a ≤ b + c := eq.mpr (id (Eq._oldrec (Eq.refl (-c + a ≤ b ↔ a ≤ b + c)) (propext neg_add_le_iff_le_add))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ c + b ↔ a ≤ b + c)) (add_comm c b))) (iff.refl (a ≤ b + c))) @[simp] theorem lt_neg_add_iff_add_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : b < -a + c ↔ a + b < c := (fun (this : -a + (a + b) < -a + c ↔ a + b < c) => eq.mp (Eq._oldrec (Eq.refl (-a + (a + b) < -a + c ↔ a + b < c)) (neg_add_cancel_left a b)) this) (add_lt_add_iff_left (-a)) @[simp] theorem inv_mul_lt_iff_lt_mul {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : b⁻¹ * a < c ↔ a < b * c := (fun (this : b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c) => eq.mp (Eq._oldrec (Eq.refl (b⁻¹ * a < b⁻¹ * (b * c) ↔ a < b * c)) (inv_mul_cancel_left b c)) this) (mul_lt_mul_iff_left (b⁻¹)) theorem inv_mul_lt_iff_lt_mul_right {α : Type u} [ordered_comm_group α] {a : α} {b : α} {c : α} : c⁻¹ * a < b ↔ a < b * c := eq.mpr (id (Eq._oldrec (Eq.refl (c⁻¹ * a < b ↔ a < b * c)) (propext inv_mul_lt_iff_lt_mul))) (eq.mpr (id (Eq._oldrec (Eq.refl (a < c * b ↔ a < b * c)) (mul_comm c b))) (iff.refl (a < b * c))) theorem add_neg_le_add_neg_iff {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} {d : α} : a + -b ≤ c + -d ↔ a + d ≤ c + b := sorry theorem sub_le_sub {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} {d : α} (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := sorry theorem sub_lt_sub {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} {d : α} (hab : a < b) (hcd : c < d) : a - d < b - c := sorry @[simp] theorem sub_le_self_iff {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} : a - b ≤ a ↔ 0 ≤ b := sorry theorem sub_le_self {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} : 0 ≤ b → a - b ≤ a := iff.mpr (sub_le_self_iff a) @[simp] theorem sub_lt_self_iff {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} : a - b < a ↔ 0 < b := sorry theorem sub_lt_self {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} : 0 < b → a - b < a := iff.mpr (sub_lt_self_iff a) theorem sub_le_sub_iff {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} {d : α} : a - b ≤ c - d ↔ a + d ≤ c + b := sorry @[simp] theorem sub_le_sub_iff_left {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} {c : α} : a - b ≤ a - c ↔ c ≤ b := sorry theorem sub_le_sub_left {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a ≤ b) (c : α) : c - b ≤ c - a := iff.mpr (sub_le_sub_iff_left c) h @[simp] theorem sub_le_sub_iff_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (c : α) : a - c ≤ b - c ↔ a ≤ b := sorry theorem sub_le_sub_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a ≤ b) (c : α) : a - c ≤ b - c := iff.mpr (sub_le_sub_iff_right c) h @[simp] theorem sub_lt_sub_iff_left {α : Type u} [ordered_add_comm_group α] (a : α) {b : α} {c : α} : a - b < a - c ↔ c < b := sorry theorem sub_lt_sub_left {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a < b) (c : α) : c - b < c - a := iff.mpr (sub_lt_sub_iff_left c) h @[simp] theorem sub_lt_sub_iff_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (c : α) : a - c < b - c ↔ a < b := sorry theorem sub_lt_sub_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} (h : a < b) (c : α) : a - c < b - c := iff.mpr (sub_lt_sub_iff_right c) h @[simp] theorem sub_nonneg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : 0 ≤ a - b ↔ b ≤ a := eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ a - b ↔ b ≤ a)) (Eq.symm (sub_self a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - a ≤ a - b ↔ b ≤ a)) (propext (sub_le_sub_iff_left a)))) (iff.refl (b ≤ a))) theorem sub_nonneg_of_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : b ≤ a → 0 ≤ a - b := iff.mpr sub_nonneg @[simp] theorem sub_nonpos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a - b ≤ 0 ↔ a ≤ b := eq.mpr (id (Eq._oldrec (Eq.refl (a - b ≤ 0 ↔ a ≤ b)) (Eq.symm (sub_self b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - b ≤ b - b ↔ a ≤ b)) (propext (sub_le_sub_iff_right b)))) (iff.refl (a ≤ b))) theorem le_of_sub_nonpos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a - b ≤ 0 → a ≤ b := iff.mp sub_nonpos @[simp] theorem sub_pos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : 0 < a - b ↔ b < a := eq.mpr (id (Eq._oldrec (Eq.refl (0 < a - b ↔ b < a)) (Eq.symm (sub_self a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - a < a - b ↔ b < a)) (propext (sub_lt_sub_iff_left a)))) (iff.refl (b < a))) theorem lt_of_sub_pos {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : 0 < a - b → b < a := iff.mp sub_pos @[simp] theorem sub_lt_zero {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a - b < 0 ↔ a < b := eq.mpr (id (Eq._oldrec (Eq.refl (a - b < 0 ↔ a < b)) (Eq.symm (sub_self b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a - b < b - b ↔ a < b)) (propext (sub_lt_sub_iff_right b)))) (iff.refl (a < b))) theorem lt_of_sub_neg {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} : a - b < 0 → a < b := iff.mp sub_lt_zero theorem le_sub_iff_add_le' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : b ≤ c - a ↔ a + b ≤ c := sorry theorem le_sub_iff_add_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a ≤ c - b ↔ a + b ≤ c := eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ c - b ↔ a + b ≤ c)) (propext le_sub_iff_add_le'))) (eq.mpr (id (Eq._oldrec (Eq.refl (b + a ≤ c ↔ a + b ≤ c)) (add_comm b a))) (iff.refl (a + b ≤ c))) theorem add_le_of_le_sub_right {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a ≤ c - b → a + b ≤ c := iff.mp le_sub_iff_add_le theorem sub_le_iff_le_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b ≤ c ↔ a ≤ b + c := sorry theorem le_sub_left_of_add_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a + b ≤ c → b ≤ c - a := iff.mpr le_sub_iff_add_le' theorem sub_le_iff_le_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - c ≤ b ↔ a ≤ b + c := eq.mpr (id (Eq._oldrec (Eq.refl (a - c ≤ b ↔ a ≤ b + c)) (propext sub_le_iff_le_add'))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ c + b ↔ a ≤ b + c)) (add_comm c b))) (iff.refl (a ≤ b + c))) @[simp] theorem neg_le_sub_iff_le_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -b ≤ a - c ↔ c ≤ a + b := iff.trans le_sub_iff_add_le neg_add_le_iff_le_add' theorem neg_le_sub_iff_le_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -a ≤ b - c ↔ c ≤ a + b := eq.mpr (id (Eq._oldrec (Eq.refl (-a ≤ b - c ↔ c ≤ a + b)) (propext neg_le_sub_iff_le_add))) (eq.mpr (id (Eq._oldrec (Eq.refl (c ≤ b + a ↔ c ≤ a + b)) (add_comm b a))) (iff.refl (c ≤ a + b))) theorem sub_le {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b ≤ c ↔ a - c ≤ b := iff.trans sub_le_iff_le_add' (iff.symm sub_le_iff_le_add) theorem le_sub {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a ≤ b - c ↔ c ≤ b - a := iff.trans le_sub_iff_add_le' (iff.symm le_sub_iff_add_le) theorem lt_sub_iff_add_lt' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : b < c - a ↔ a + b < c := sorry theorem add_lt_of_lt_sub_left {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : b < c - a → a + b < c := iff.mp lt_sub_iff_add_lt' theorem lt_sub_iff_add_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a < c - b ↔ a + b < c := eq.mpr (id (Eq._oldrec (Eq.refl (a < c - b ↔ a + b < c)) (propext lt_sub_iff_add_lt'))) (eq.mpr (id (Eq._oldrec (Eq.refl (b + a < c ↔ a + b < c)) (add_comm b a))) (iff.refl (a + b < c))) theorem lt_sub_right_of_add_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a + b < c → a < c - b := iff.mpr lt_sub_iff_add_lt theorem sub_lt_iff_lt_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b < c ↔ a < b + c := sorry theorem lt_add_of_sub_left_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b < c → a < b + c := iff.mp sub_lt_iff_lt_add' theorem sub_lt_iff_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - c < b ↔ a < b + c := eq.mpr (id (Eq._oldrec (Eq.refl (a - c < b ↔ a < b + c)) (propext sub_lt_iff_lt_add'))) (eq.mpr (id (Eq._oldrec (Eq.refl (a < c + b ↔ a < b + c)) (add_comm c b))) (iff.refl (a < b + c))) theorem sub_right_lt_of_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a < b + c → a - c < b := iff.mpr sub_lt_iff_lt_add @[simp] theorem neg_lt_sub_iff_lt_add {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -b < a - c ↔ c < a + b := iff.trans lt_sub_iff_add_lt neg_add_lt_iff_lt_add_right theorem neg_lt_sub_iff_lt_add' {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : -a < b - c ↔ c < a + b := eq.mpr (id (Eq._oldrec (Eq.refl (-a < b - c ↔ c < a + b)) (propext neg_lt_sub_iff_lt_add))) (eq.mpr (id (Eq._oldrec (Eq.refl (c < b + a ↔ c < a + b)) (add_comm b a))) (iff.refl (c < a + b))) theorem sub_lt {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a - b < c ↔ a - c < b := iff.trans sub_lt_iff_lt_add' (iff.symm sub_lt_iff_lt_add) theorem lt_sub {α : Type u} [ordered_add_comm_group α] {a : α} {b : α} {c : α} : a < b - c ↔ c < b - a := iff.trans lt_sub_iff_add_lt' (iff.symm lt_sub_iff_add_lt) /-! ### Linearly ordered commutative groups -/ /-- A linearly ordered additive commutative group is an additive commutative group with a linear order in which addition is monotone. -/ class linear_ordered_add_comm_group (α : Type u) extends add_comm_group α, linear_order α where add_le_add_left : ∀ (a b : α), a ≤ b → ∀ (c : α), c + a ≤ c + b /-- A linearly ordered commutative group is a commutative group with a linear order in which multiplication is monotone. -/ class linear_ordered_comm_group (α : Type u) extends linear_order α, comm_group α where mul_le_mul_left : ∀ (a b : α), a ≤ b → ∀ (c : α), c * a ≤ c * b protected instance linear_ordered_comm_group.to_ordered_comm_group (α : Type u) [s : linear_ordered_comm_group α] : ordered_comm_group α := ordered_comm_group.mk linear_ordered_comm_group.mul linear_ordered_comm_group.mul_assoc linear_ordered_comm_group.one linear_ordered_comm_group.one_mul linear_ordered_comm_group.mul_one linear_ordered_comm_group.inv linear_ordered_comm_group.div linear_ordered_comm_group.mul_left_inv linear_ordered_comm_group.mul_comm linear_ordered_comm_group.le linear_ordered_comm_group.lt linear_ordered_comm_group.le_refl linear_ordered_comm_group.le_trans linear_ordered_comm_group.le_antisymm linear_ordered_comm_group.mul_le_mul_left protected instance linear_ordered_add_comm_group.to_linear_ordered_cancel_add_comm_monoid {α : Type u} [linear_ordered_add_comm_group α] : linear_ordered_cancel_add_comm_monoid α := linear_ordered_cancel_add_comm_monoid.mk linear_ordered_add_comm_group.add linear_ordered_add_comm_group.add_assoc sorry linear_ordered_add_comm_group.zero linear_ordered_add_comm_group.zero_add linear_ordered_add_comm_group.add_zero linear_ordered_add_comm_group.add_comm sorry linear_ordered_add_comm_group.le linear_ordered_add_comm_group.lt linear_ordered_add_comm_group.le_refl linear_ordered_add_comm_group.le_trans linear_ordered_add_comm_group.le_antisymm linear_ordered_add_comm_group.add_le_add_left sorry linear_ordered_add_comm_group.le_total linear_ordered_add_comm_group.decidable_le linear_ordered_add_comm_group.decidable_eq linear_ordered_add_comm_group.decidable_lt theorem linear_ordered_add_comm_group.add_lt_add_left {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (h : a < b) (c : α) : c + a < c + b := ordered_add_comm_group.add_lt_add_left a b h c theorem le_of_forall_pos_le_add {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} [densely_ordered α] (h : ∀ (ε : α), 0 < ε → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense fun (c : α) (hc : c > b) => trans_rel_left LessEq (h (c - b) (sub_pos_of_lt hc)) (add_sub_cancel'_right b c) theorem min_neg_neg {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : min (-a) (-b) = -max a b := Eq.symm (monotone.map_max fun (a b : α) => neg_le_neg) theorem max_neg_neg {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : max (-a) (-b) = -min a b := Eq.symm (monotone.map_min fun (a b : α) => neg_le_neg) theorem min_sub_sub_right {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : min (a - c) (b - c) = min a b - c := sorry theorem max_sub_sub_right {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : max (a - c) (b - c) = max a b - c := sorry theorem min_sub_sub_left {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : min (a - b) (a - c) = a - max b c := sorry theorem max_sub_sub_left {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : max (a - b) (a - c) = a - min b c := sorry theorem max_zero_sub_eq_self {α : Type u} [linear_ordered_add_comm_group α] (a : α) : max a 0 - max (-a) 0 = a := sorry /-- `abs a` is the absolute value of `a`. -/ def abs {α : Type u} [linear_ordered_add_comm_group α] (a : α) : α := max a (-a) theorem abs_of_nonneg {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : 0 ≤ a) : abs a = a := max_eq_left (has_le.le.trans (iff.mpr neg_nonpos h) h) theorem abs_of_pos {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : 0 < a) : abs a = a := abs_of_nonneg (has_lt.lt.le h) theorem abs_of_nonpos {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : a ≤ 0) : abs a = -a := max_eq_right (has_le.le.trans h (iff.mpr neg_nonneg h)) theorem abs_of_neg {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : a < 0) : abs a = -a := abs_of_nonpos (has_lt.lt.le h) @[simp] theorem abs_zero {α : Type u} [linear_ordered_add_comm_group α] : abs 0 = 0 := abs_of_nonneg le_rfl @[simp] theorem abs_neg {α : Type u} [linear_ordered_add_comm_group α] (a : α) : abs (-a) = abs a := sorry @[simp] theorem abs_pos {α : Type u} [linear_ordered_add_comm_group α] {a : α} : 0 < abs a ↔ a ≠ 0 := sorry theorem abs_pos_of_pos {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : 0 < a) : 0 < abs a := iff.mpr abs_pos (ne.symm (has_lt.lt.ne h)) theorem abs_pos_of_neg {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : a < 0) : 0 < abs a := iff.mpr abs_pos (has_lt.lt.ne h) theorem abs_sub {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : abs (a - b) = abs (b - a) := eq.mpr (id (Eq._oldrec (Eq.refl (abs (a - b) = abs (b - a))) (Eq.symm (neg_sub b a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (abs (-(b - a)) = abs (b - a))) (abs_neg (b - a)))) (Eq.refl (abs (b - a)))) theorem abs_le' {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} : abs a ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff theorem abs_le {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} : abs a ≤ b ↔ -b ≤ a ∧ a ≤ b := eq.mpr (id (Eq._oldrec (Eq.refl (abs a ≤ b ↔ -b ≤ a ∧ a ≤ b)) (propext abs_le'))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ b ∧ -a ≤ b ↔ -b ≤ a ∧ a ≤ b)) (propext and.comm))) (eq.mpr (id (Eq._oldrec (Eq.refl (-a ≤ b ∧ a ≤ b ↔ -b ≤ a ∧ a ≤ b)) (propext neg_le))) (iff.refl (-b ≤ a ∧ a ≤ b)))) theorem le_abs_self {α : Type u} [linear_ordered_add_comm_group α] (a : α) : a ≤ abs a := le_max_left a (-a) theorem neg_le_abs_self {α : Type u} [linear_ordered_add_comm_group α] (a : α) : -a ≤ abs a := le_max_right a (-a) theorem abs_nonneg {α : Type u} [linear_ordered_add_comm_group α] (a : α) : 0 ≤ abs a := or.elim (le_total 0 a) (fun (h : 0 ≤ a) => has_le.le.trans h (le_abs_self a)) fun (h : a ≤ 0) => has_le.le.trans (iff.mpr neg_nonneg h) (neg_le_abs_self a) @[simp] theorem abs_abs {α : Type u} [linear_ordered_add_comm_group α] (a : α) : abs (abs a) = abs a := abs_of_nonneg (abs_nonneg a) @[simp] theorem abs_eq_zero {α : Type u} [linear_ordered_add_comm_group α] {a : α} : abs a = 0 ↔ a = 0 := iff.mp not_iff_not (iff.trans ne_comm (iff.trans (iff.symm (has_le.le.lt_iff_ne (abs_nonneg a))) abs_pos)) @[simp] theorem abs_nonpos_iff {α : Type u} [linear_ordered_add_comm_group α] {a : α} : abs a ≤ 0 ↔ a = 0 := iff.trans (has_le.le.le_iff_eq (abs_nonneg a)) abs_eq_zero theorem abs_lt {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} : abs a < b ↔ -b < a ∧ a < b := iff.trans max_lt_iff (iff.trans and.comm (eq.mpr (id (Eq._oldrec (Eq.refl (-a < b ∧ a < b ↔ -b < a ∧ a < b)) (propext neg_lt))) (iff.refl (-b < a ∧ a < b)))) theorem lt_abs {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} : a < abs b ↔ a < b ∨ a < -b := lt_max_iff theorem max_sub_min_eq_abs' {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : max a b - min a b = abs (a - b) := sorry theorem max_sub_min_eq_abs {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : max a b - min a b = abs (b - a) := eq.mpr (id (Eq._oldrec (Eq.refl (max a b - min a b = abs (b - a))) (abs_sub b a))) (max_sub_min_eq_abs' a b) theorem abs_add {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : abs (a + b) ≤ abs a + abs b := sorry theorem abs_sub_le_iff {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := sorry theorem abs_sub_lt_iff {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} : abs (a - b) < c ↔ a - b < c ∧ b - a < c := sorry theorem sub_le_of_abs_sub_le_left {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : abs (a - b) ≤ c) : b - c ≤ a := iff.mp sub_le (and.right (iff.mp abs_sub_le_iff h)) theorem sub_le_of_abs_sub_le_right {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub a b ▸ h) theorem sub_lt_of_abs_sub_lt_left {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : abs (a - b) < c) : b - c < a := iff.mp sub_lt (and.right (iff.mp abs_sub_lt_iff h)) theorem sub_lt_of_abs_sub_lt_right {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h) theorem abs_sub_abs_le_abs_sub {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : abs a - abs b ≤ abs (a - b) := sorry theorem abs_abs_sub_abs_le_abs_sub {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) : abs (abs a - abs b) ≤ abs (a - b) := sorry theorem abs_eq {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} (hb : 0 ≤ b) : abs a = b ↔ a = b ∨ a = -b := sorry theorem abs_le_max_abs_abs {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {c : α} (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) := sorry theorem abs_le_abs {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} (h₀ : a ≤ b) (h₁ : -a ≤ b) : abs a ≤ abs b := has_le.le.trans (iff.mpr abs_le' { left := h₀, right := h₁ }) (le_abs_self b) theorem abs_max_sub_max_le_abs {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : abs (max a c - max b c) ≤ abs (a - b) := sorry theorem eq_zero_of_neg_eq {α : Type u} [linear_ordered_add_comm_group α] {a : α} (h : -a = a) : a = 0 := sorry theorem eq_of_abs_sub_eq_zero {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} (h : abs (a - b) = 0) : a = b := iff.mp sub_eq_zero (iff.mp abs_eq_zero h) theorem abs_by_cases {α : Type u} [linear_ordered_add_comm_group α] (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := sup_ind a (-a) h1 h2 theorem abs_sub_le {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := sorry theorem abs_add_three {α : Type u} [linear_ordered_add_comm_group α] (a : α) (b : α) (c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := has_le.le.trans (abs_add (a + b) c) (add_le_add_right (abs_add a b) (abs c)) theorem dist_bdd_within_interval {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} {lb : α} {ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := iff.mpr abs_sub_le_iff { left := sub_le_sub hau hbl, right := sub_le_sub hbu hal } theorem eq_of_abs_sub_nonpos {α : Type u} [linear_ordered_add_comm_group α] {a : α} {b : α} (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) theorem exists_zero_lt {α : Type u} [linear_ordered_add_comm_group α] [nontrivial α] : ∃ (a : α), 0 < a := sorry protected instance linear_ordered_add_comm_group.to_no_top_order {α : Type u} [linear_ordered_add_comm_group α] [nontrivial α] : no_top_order α := no_top_order.mk (Exists.dcases_on exists_zero_lt fun (y : α) (hy : 0 < y) (a : α) => Exists.intro (a + y) (lt_add_of_pos_right a hy)) protected instance linear_ordered_add_comm_group.to_no_bot_order {α : Type u} [linear_ordered_add_comm_group α] [nontrivial α] : no_bot_order α := no_bot_order.mk (Exists.dcases_on exists_zero_lt fun (y : α) (hy : 0 < y) (a : α) => Exists.intro (a - y) (sub_lt_self a hy)) /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (α : Type u_1) extends add_comm_group α where nonneg : α → Prop pos : α → Prop pos_iff : autoParam (∀ (a : α), pos a ↔ nonneg a ∧ ¬nonneg (-a)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.order_laws_tac") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "order_laws_tac") []) zero_nonneg : nonneg 0 add_nonneg : ∀ {a b : α}, nonneg a → nonneg b → nonneg (a + b) nonneg_antisymm : ∀ {a : α}, nonneg a → nonneg (-a) → a = 0 namespace nonneg_add_comm_group protected instance to_ordered_add_comm_group {α : Type u} [s : nonneg_add_comm_group α] : ordered_add_comm_group α := ordered_add_comm_group.mk add add_assoc zero zero_add add_zero neg sub add_left_neg add_comm (fun (a b : α) => nonneg (b - a)) (fun (a b : α) => pos (b - a)) sorry sorry sorry sorry theorem nonneg_def {α : Type u} [s : nonneg_add_comm_group α] {a : α} : nonneg a ↔ 0 ≤ a := sorry theorem pos_def {α : Type u} [s : nonneg_add_comm_group α] {a : α} : pos a ↔ 0 < a := sorry theorem not_zero_pos {α : Type u} [s : nonneg_add_comm_group α] : ¬pos 0 := mt (iff.mp pos_def) (lt_irrefl 0) theorem zero_lt_iff_nonneg_nonneg {α : Type u} [s : nonneg_add_comm_group α] {a : α} : 0 < a ↔ nonneg a ∧ ¬nonneg (-a) := iff.trans (iff.symm pos_def) (pos_iff a) theorem nonneg_total_iff {α : Type u} [s : nonneg_add_comm_group α] : (∀ (a : α), nonneg a ∨ nonneg (-a)) ↔ ∀ (a b : α), a ≤ b ∨ b ≤ a := sorry /-- A `nonneg_add_comm_group` is a `linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_linear_ordered_add_comm_group {α : Type u} [s : nonneg_add_comm_group α] [decidable_pred nonneg] (nonneg_total : ∀ (a : α), nonneg a ∨ nonneg (-a)) : linear_ordered_add_comm_group α := linear_ordered_add_comm_group.mk ordered_add_comm_group.add sorry ordered_add_comm_group.zero sorry sorry ordered_add_comm_group.neg ordered_add_comm_group.sub sorry sorry LessEq Less sorry sorry sorry sorry (fun (a b : α) => _inst_1 (b - a)) (linear_order.decidable_eq._default LessEq Less sorry sorry sorry fun (a b : α) => _inst_1 (b - a)) (fun (a b : α) => Mathlib.decidable_lt_of_decidable_le a b) sorry end nonneg_add_comm_group namespace order_dual protected instance ordered_add_comm_group {α : Type u} [ordered_add_comm_group α] : ordered_add_comm_group (order_dual α) := ordered_add_comm_group.mk ordered_add_comm_monoid.add sorry ordered_add_comm_monoid.zero sorry sorry add_comm_group.neg (fun (a b : order_dual α) => a - b) sorry sorry ordered_add_comm_monoid.le ordered_add_comm_monoid.lt sorry sorry sorry sorry protected instance linear_ordered_add_comm_group {α : Type u} [linear_ordered_add_comm_group α] : linear_ordered_add_comm_group (order_dual α) := linear_ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry linear_order.le linear_order.lt sorry sorry sorry sorry linear_order.decidable_le linear_order.decidable_eq linear_order.decidable_lt sorry end order_dual namespace prod protected instance ordered_add_comm_group {G : Type u_1} {H : Type u_2} [ordered_add_comm_group G] [ordered_add_comm_group H] : ordered_add_comm_group (G × H) := ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry partial_order.le partial_order.lt sorry sorry sorry sorry end prod protected instance multiplicative.ordered_comm_group {α : Type u} [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := ordered_comm_group.mk comm_group.mul sorry comm_group.one sorry sorry comm_group.inv comm_group.div sorry sorry ordered_comm_monoid.le ordered_comm_monoid.lt sorry sorry sorry sorry protected instance additive.ordered_add_comm_group {α : Type u} [ordered_comm_group α] : ordered_add_comm_group (additive α) := ordered_add_comm_group.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry ordered_add_comm_monoid.le ordered_add_comm_monoid.lt sorry sorry sorry sorry end Mathlib