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
392d2df7e9043d08cda1c6419ba451dccaf6711b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/mod_implicit.lean
255dd812a725181ed797778f2bf6a6321b6df71f
[ "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
540
lean
import tactic.interactive import data.nat.basic variables (p : ℕ → Prop) (a b : ℕ) example (h : p (a + b)) : p (b + a) := begin rw add_comm, -- `guard_target` fails because the instances don't match success_if_fail { guard_target p (a + b) }, guard_target_mod_implicit p (a + b), assumption end example (h : p (b + a)) : p (a + b) := begin rw add_comm at h, -- `guard_hyp` fails because the instances don't match success_if_fail { guard_hyp h : p (a + b) }, guard_hyp_mod_implicit h : p (a + b), assumption end
8147824ec2e465a89f06b3b769385846f1cda1d7
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/stage0/src/Lean/Elab/PreDefinition/Basic.lean
3e0ce92a6aae11057f86e8c53190fece409b9228
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
7,235
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.SCC import Lean.Meta.AbstractNestedProofs import Lean.Elab.Term import Lean.Elab.DefView import Lean.Elab.PreDefinition.MkInhabitant namespace Lean.Elab open Meta open Term /-- A (potentially recursive) definition. The elaborator converts it into Kernel definitions using many different strategies. -/ structure PreDefinition where ref : Syntax kind : DefKind levelParams : List Name modifiers : Modifiers declName : Name type : Expr value : Expr deriving Inhabited def instantiateMVarsAtPreDecls (preDefs : Array PreDefinition) : TermElabM (Array PreDefinition) := preDefs.mapM fun preDef => do pure { preDef with type := (← instantiateMVars preDef.type), value := (← instantiateMVars preDef.value) } private def levelMVarToParamPreDeclsAux (preDefs : Array PreDefinition) : StateRefT Nat TermElabM (Array PreDefinition) := preDefs.mapM fun preDef => do pure { preDef with type := (← levelMVarToParam' preDef.type), value := (← levelMVarToParam' preDef.value) } def levelMVarToParamPreDecls (preDefs : Array PreDefinition) : TermElabM (Array PreDefinition) := (levelMVarToParamPreDeclsAux preDefs).run' 1 private def getLevelParamsPreDecls (preDefs : Array PreDefinition) (scopeLevelNames allUserLevelNames : List Name) : TermElabM (List Name) := do let mut s : CollectLevelParams.State := {} for preDef in preDefs do s := collectLevelParams s preDef.type s := collectLevelParams s preDef.value match sortDeclLevelParams scopeLevelNames allUserLevelNames s.params with | Except.error msg => throwError msg | Except.ok levelParams => pure levelParams def fixLevelParams (preDefs : Array PreDefinition) (scopeLevelNames allUserLevelNames : List Name) : TermElabM (Array PreDefinition) := do -- We used to use `shareCommon` here, but is was a bottleneck let levelParams ← getLevelParamsPreDecls preDefs scopeLevelNames allUserLevelNames let us := levelParams.map mkLevelParam let fixExpr (e : Expr) : Expr := e.replace fun c => match c with | Expr.const declName _ _ => if preDefs.any fun preDef => preDef.declName == declName then some $ Lean.mkConst declName us else none | _ => none pure $ preDefs.map fun preDef => { preDef with type := fixExpr preDef.type, value := fixExpr preDef.value, levelParams := levelParams } def applyAttributesOf (preDefs : Array PreDefinition) (applicationTime : AttributeApplicationTime) : TermElabM Unit := do for preDef in preDefs do applyAttributesAt preDef.declName preDef.modifiers.attrs applicationTime def abstractNestedProofs (preDef : PreDefinition) : MetaM PreDefinition := if preDef.kind.isTheorem || preDef.kind.isExample then pure preDef else do let value ← Meta.abstractNestedProofs preDef.declName preDef.value pure { preDef with value := value } /- Auxiliary method for (temporarily) adding pre definition as an axiom -/ def addAsAxiom (preDef : PreDefinition) : MetaM Unit := do withRef preDef.ref do addDecl <| Declaration.axiomDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, isUnsafe := preDef.modifiers.isUnsafe } private def shouldGenCodeFor (preDef : PreDefinition) : Bool := !preDef.kind.isTheorem && !preDef.modifiers.isNoncomputable private def compileDecl (decl : Declaration) : TermElabM Bool := do try Lean.compileDecl decl catch ex => if (← read).isNoncomputableSection then return false else throw ex return true private def addNonRecAux (preDef : PreDefinition) (compile : Bool) : TermElabM Unit := withRef preDef.ref do let preDef ← abstractNestedProofs preDef let env ← getEnv let decl := match preDef.kind with | DefKind.«theorem» => Declaration.thmDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value } | DefKind.«opaque» => Declaration.opaqueDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value, isUnsafe := preDef.modifiers.isUnsafe } | DefKind.«abbrev» => Declaration.defnDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value, hints := ReducibilityHints.«abbrev», safety := if preDef.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } | _ => -- definitions and examples Declaration.defnDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value, hints := ReducibilityHints.regular (getMaxHeight env preDef.value + 1), safety := if preDef.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } addDecl decl withSaveInfoContext do -- save new env addTermInfo preDef.ref (← mkConstWithLevelParams preDef.declName) (isBinder := true) applyAttributesOf #[preDef] AttributeApplicationTime.afterTypeChecking if compile && shouldGenCodeFor preDef then unless (← compileDecl decl) do return () applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation def addAndCompileNonRec (preDef : PreDefinition) : TermElabM Unit := do addNonRecAux preDef true def addNonRec (preDef : PreDefinition) : TermElabM Unit := do addNonRecAux preDef false def addAndCompileUnsafe (preDefs : Array PreDefinition) (safety := DefinitionSafety.unsafe) : TermElabM Unit := withRef preDefs[0].ref do let decl := Declaration.mutualDefnDecl $ preDefs.toList.map fun preDef => { name := preDef.declName levelParams := preDef.levelParams type := preDef.type value := preDef.value safety := safety hints := ReducibilityHints.opaque } addDecl decl withSaveInfoContext do -- save new env for preDef in preDefs do addTermInfo preDef.ref (← mkConstWithLevelParams preDef.declName) (isBinder := true) applyAttributesOf preDefs AttributeApplicationTime.afterTypeChecking unless (← compileDecl decl) do return () applyAttributesOf preDefs AttributeApplicationTime.afterCompilation return () def addAndCompilePartialRec (preDefs : Array PreDefinition) : TermElabM Unit := do if preDefs.all shouldGenCodeFor then addAndCompileUnsafe (safety := DefinitionSafety.partial) <| preDefs.map fun preDef => { preDef with declName := Compiler.mkUnsafeRecName preDef.declName, value := preDef.value.replace fun e => match e with | Expr.const declName us _ => if preDefs.any fun preDef => preDef.declName == declName then some $ mkConst (Compiler.mkUnsafeRecName declName) us else none | _ => none, modifiers := {} } end Lean.Elab
583a218e84aaa5ca022b1e72a574d56c44cbe142
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/rat/floor.lean
48218e3a14fa33f81465e7beae5864a3ec33d896
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,435
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, Kevin Kappelmann -/ import algebra.floor import tactic.field_simp /-! # Floor Function for Rational Numbers ## Summary We define the `floor` function and the `floor_ring` instance on `ℚ`. Some technical lemmas relating `floor` to integer division and modulo arithmetic are derived as well as some simple inequalities. ## Tags rat, rationals, ℚ, floor -/ open int namespace rat /-- `floor q` is the largest integer `z` such that `z ≤ q` -/ protected def floor : ℚ → ℤ | ⟨n, d, h, c⟩ := n / d protected theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ rat.floor r ↔ (z : ℚ) ≤ r | ⟨n, d, h, c⟩ := begin simp [rat.floor], rw [num_denom'], have h' := int.coe_nat_lt.2 h, conv { to_rhs, rw [coe_int_eq_mk, rat.le_def zero_lt_one h', mul_one] }, exact int.le_div_iff_mul_le h' end instance : floor_ring ℚ := floor_ring.of_floor ℚ rat.floor $ λ a z, rat.le_floor.symm protected lemma floor_def {q : ℚ} : ⌊q⌋ = q.num / q.denom := by { cases q, refl } lemma floor_int_div_nat_eq_div {n : ℤ} {d : ℕ} : ⌊(↑n : ℚ) / (↑d : ℚ)⌋ = n / (↑d : ℤ) := begin rw [rat.floor_def], cases decidable.em (d = 0) with d_eq_zero d_ne_zero, { simp [d_eq_zero] }, { cases decidable.em (n = 0) with n_eq_zero n_ne_zero, { simp [n_eq_zero] }, { set q := (n : ℚ) / d with q_eq, obtain ⟨c, n_eq_c_mul_num, d_eq_c_mul_denom⟩ : ∃ c, n = c * q.num ∧ (d : ℤ) = c * q.denom, by { rw q_eq, exact_mod_cast (@rat.exists_eq_mul_div_num_and_eq_mul_div_denom n d n_ne_zero (by exact_mod_cast d_ne_zero)) }, suffices : q.num / q.denom = c * q.num / (c * q.denom), by rwa [n_eq_c_mul_num, d_eq_c_mul_denom], suffices : c > 0, by solve_by_elim [int.mul_div_mul_of_pos], have q_denom_mul_c_pos : (0 : ℤ) < q.denom * c, by { have : (d : ℤ) > 0, by exact_mod_cast (pos_iff_ne_zero.elim_right d_ne_zero), rwa [d_eq_c_mul_denom, mul_comm] at this }, suffices : (0 : ℤ) ≤ q.denom, from pos_of_mul_pos_left q_denom_mul_c_pos this, exact_mod_cast (le_of_lt q.pos) } } end end rat lemma int.mod_nat_eq_sub_mul_floor_rat_div {n : ℤ} {d : ℕ} : n % d = n - d * ⌊(n : ℚ) / d⌋ := by rw [(eq_sub_of_add_eq $ int.mod_add_div n d), rat.floor_int_div_nat_eq_div] lemma nat.coprime_sub_mul_floor_rat_div_of_coprime {n d : ℕ} (n_coprime_d : n.coprime d) : ((n : ℤ) - d * ⌊(n : ℚ)/ d⌋).nat_abs.coprime d := begin have : (n : ℤ) % d = n - d * ⌊(n : ℚ)/ d⌋, from int.mod_nat_eq_sub_mul_floor_rat_div, rw ←this, have : d.coprime n, from n_coprime_d.symm, rwa [nat.coprime, nat.gcd_rec] at this end namespace rat lemma num_lt_succ_floor_mul_denom (q : ℚ) : q.num < (⌊q⌋ + 1) * q.denom := begin suffices : (q.num : ℚ) < (⌊q⌋ + 1) * q.denom, by exact_mod_cast this, suffices : (q.num : ℚ) < (q - fract q + 1) * q.denom, by { have : (⌊q⌋ : ℚ) = q - fract q, from (eq_sub_of_add_eq $ floor_add_fract q), rwa this }, suffices : (q.num : ℚ) < q.num + (1 - fract q) * q.denom, by { have : (q - fract q + 1) * q.denom = q.num + (1 - fract q) * q.denom, calc (q - fract q + 1) * q.denom = (q + (1 - fract q)) * q.denom : by ring ... = q * q.denom + (1 - fract q) * q.denom : by rw add_mul ... = q.num + (1 - fract q) * q.denom : by simp, rwa this }, suffices : 0 < (1 - fract q) * q.denom, by { rw ←sub_lt_iff_lt_add', simpa }, have : 0 < 1 - fract q, by { have : fract q < 1, from fract_lt_one q, have : 0 + fract q < 1, by simp [this], rwa lt_sub_iff_add_lt }, exact mul_pos this (by exact_mod_cast q.pos) end lemma fract_inv_num_lt_num_of_pos {q : ℚ} (q_pos : 0 < q): (fract q⁻¹).num < q.num := begin -- we know that the numerator must be positive have q_num_pos : 0 < q.num, from rat.num_pos_iff_pos.elim_right q_pos, -- we will work with the absolute value of the numerator, which is equal to the numerator have q_num_abs_eq_q_num : (q.num.nat_abs : ℤ) = q.num, from (int.nat_abs_of_nonneg q_num_pos.le), set q_inv := (q.denom : ℚ) / q.num with q_inv_def, have q_inv_eq : q⁻¹ = q_inv, from rat.inv_def', suffices : (q_inv - ⌊q_inv⌋).num < q.num, by rwa q_inv_eq, suffices : ((q.denom - q.num * ⌊q_inv⌋ : ℚ) / q.num).num < q.num, by field_simp [this, (ne_of_gt q_num_pos)], suffices : (q.denom : ℤ) - q.num * ⌊q_inv⌋ < q.num, by { -- use that `q.num` and `q.denom` are coprime to show that the numerator stays unreduced have : ((q.denom - q.num * ⌊q_inv⌋ : ℚ) / q.num).num = q.denom - q.num * ⌊q_inv⌋, by { suffices : ((q.denom : ℤ) - q.num * ⌊q_inv⌋).nat_abs.coprime q.num.nat_abs, by exact_mod_cast (rat.num_div_eq_of_coprime q_num_pos this), have : (q.num.nat_abs : ℚ) = (q.num : ℚ), by exact_mod_cast q_num_abs_eq_q_num, have tmp := nat.coprime_sub_mul_floor_rat_div_of_coprime q.cop.symm, simpa only [this, q_num_abs_eq_q_num] using tmp }, rwa this }, -- to show the claim, start with the following inequality have q_inv_num_denom_ineq : q⁻¹.num - ⌊q⁻¹⌋ * q⁻¹.denom < q⁻¹.denom, by { have : q⁻¹.num < (⌊q⁻¹⌋ + 1) * q⁻¹.denom, from rat.num_lt_succ_floor_mul_denom q⁻¹, have : q⁻¹.num < ⌊q⁻¹⌋ * q⁻¹.denom + q⁻¹.denom, by rwa [right_distrib, one_mul] at this, rwa [←sub_lt_iff_lt_add'] at this }, -- use that `q.num` and `q.denom` are coprime to show that q_inv is the unreduced reciprocal -- of `q` have : q_inv.num = q.denom ∧ q_inv.denom = q.num.nat_abs, by { have coprime_q_denom_q_num : q.denom.coprime q.num.nat_abs, from q.cop.symm, have : int.nat_abs q.denom = q.denom, by simp, rw ←this at coprime_q_denom_q_num, rw q_inv_def, split, { exact_mod_cast (rat.num_div_eq_of_coprime q_num_pos coprime_q_denom_q_num) }, { suffices : (((q.denom : ℚ) / q.num).denom : ℤ) = q.num.nat_abs, by exact_mod_cast this, rw q_num_abs_eq_q_num, exact_mod_cast (rat.denom_div_eq_of_coprime q_num_pos coprime_q_denom_q_num) } }, rwa [q_inv_eq, this.left, this.right, q_num_abs_eq_q_num, mul_comm] at q_inv_num_denom_ineq end end rat
cbe67305bb5dc8549fcb7340871e661f48b59740
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/test/lock/lakefile.lean
cdc964be56af022d30e8f39584e93b1740c58ccf
[ "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
101
lean
import Lake open Lake DSL package «lock» lean_lib Loop lean_lib Nop lean_lib Error lean_lib Wait
1bd7d70ae2bd6bbae13e9bce32d4898e3843a926
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1937.lean
d440730148f9cc08ff4bb83f30a65f43a4891990
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,789
lean
structure BundledFunction (α β : Sort _) := (toFun : α → β) namespace BundledFunction -- `simp` doesn't seem to unify partial applications of structure projections: -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/.60simp.60.20failing.20on.20partial.20application.20of.20projections def id (α) : BundledFunction α α := ⟨λ a => a⟩ @[simp] theorem coe_id : (id α).toFun = _root_.id := rfl example (x : α) : (id α).toFun x = x := by simp only [coe_id, id_eq] -- should succeed example (x : α) : (id α).toFun x = x := by rw [coe_id, id_eq] -- succeeds -- seems to be another instance of the same behaviour: -- https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/.60simp.60.20calls.20broken.20in.20mathlib4.23922/near/314790371 def otherProjection (f : BundledFunction α β) : α → β := f.toFun -- Projections functions are expanded when populating the discrimination tree, and are indexed as `Expr.proj` objects. -- `@toFun α β` cannot be expanded into `Expr.proj` since there is a missing argument. The workaround is to add the missing argument. -- Then, we get `a.1 = otherProjection a` @[simp] theorem toFun_eq_otherProjection : @toFun α β a = otherProjection a := rfl @[simp] theorem id_apply : (id α).otherProjection x = x := rfl example : (id α).toFun x = x := by simp only [toFun_eq_otherProjection, id_apply]; done -- should work example : (id α).toFun x = x := by rw [toFun_eq_otherProjection, id_apply] -- succeeds end BundledFunction -- `simp` is happy with partial applications in other functions: def id2 (x : α) := x @[simp] theorem id2_eq_id : @id2 α = id := rfl example : id2 x = x := by simp only [id2_eq_id, id_eq] -- works fine example : id2 x = x := by rw [id2_eq_id, id_eq] -- succeeds
51becc2f04a2cda38aafe29bd0c82c675a26d76c
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Data/Stack.lean
47ab22409b01d44455ccc4ac025b0b1bfa983031
[ "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
197
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ prelude import Init.Data.Stack.Basic
d87afd3182f11b9d10bc5e7816c13ba18f213fc5
590f94277ab689acdc713c44e3bbca2e012fc074
/Sequent Calculus (Lean)/src/rightRules.lean
65102e4105fdba46c821736c5a2f51e1bd652824
[]
no_license
Bpalkmim/iALC
bd3f882ad942c876d65c2d33cb50a36b2f8e5d16
9c2982ae916d01d9ebab9d58e0842292ed974876
refs/heads/master
1,689,527,062,560
1,631,502,537,000
1,631,502,537,000
108,029,498
0
0
null
null
null
null
UTF-8
Lean
false
false
1,949
lean
-- Regras do lado direito do sequente de SCiALC. -- Autor: Bernardo Alkmim -- bpalkmim@gmail.com import .basics namespace rightRulesSCiALC open iALCbasics -- Subjunção constant subj_r {Δ : list Formula} {α β : Formula} : Proof (Sequent (α :: Δ) β) → Proof (Sequent Δ (Formula.subj α β)) -- Subjunção com nominals constant subj_r_n {Δ : list Formula} {α β : Formula} {X : Nominal} : Proof (Sequent (Formula.elemOf X α :: Δ) (Formula.elemOf X β)) → Proof (Sequent Δ (Formula.elemOf X (Formula.subj α β))) -- Conjunção constant conj_r {Δ : list Formula} {α β : Formula} : Proof (Sequent Δ α) → Proof (Sequent Δ β) → Proof (Sequent Δ (Formula.conj α β)) -- Disjunção (duas regras) constant disj_r1 {Δ : list Formula} {α : Formula} (β : Formula) : Proof (Sequent Δ α) → Proof (Sequent Δ (Formula.disj α β)) constant disj_r2 {Δ : list Formula} {β : Formula} (α : Formula): Proof (Sequent Δ β) → Proof (Sequent Δ (Formula.disj α β)) -- Disjunção com nominals (duas regras) constant disj_r1_n {Δ : list Formula} {α : Formula} (β : Formula) (X : Nominal) : Proof (Sequent Δ (Formula.elemOf X α)) → Proof (Sequent Δ (Formula.elemOf X (Formula.disj α β))) constant disj_r2_n {Δ : list Formula} {β : Formula} (α : Formula) (X : Nominal): Proof (Sequent Δ (Formula.elemOf X β)) → Proof (Sequent Δ (Formula.elemOf X (Formula.disj α β))) -- Restrição universal constant forall_r {Δ : list Formula} {R : Role} {X Y : Nominal} {α : Formula} : Proof (Sequent (Formula.relation R X Y :: Δ) (Formula.elemOf Y α)) → Proof (Sequent Δ (Formula.elemOf X (Formula.univ R α))) -- Restrição existencial constant exists_r {Δ : list Formula} {R : Role} {X Y : Nominal} {α : Formula} : Proof (Sequent Δ (Formula.relation R X Y)) → Proof (Sequent Δ (Formula.elemOf Y α)) → Proof (Sequent Δ (Formula.elemOf X (Formula.exis R α))) end rightRulesSCiALC
f8470379cb531819bcd92bc18985d41dec13b1f4
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/attribute.lean
031381a0951be9450b3b28ff8503841d87d5d803
[ "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
2,269
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.meta.tactic init.meta.rb_map init.meta.has_reflect meta constant attribute.get_instances : name → tactic (list name) meta constant attribute.fingerprint : name → tactic nat meta structure user_attribute := (name : name) (descr : string) /- Optional handler that will be called after the attribute has been applied to a declaration. Failing the tactic will fail the entire `attribute/def/...` command, i.e. the attribute will not be applied after all. Declaring an `after_set` handler without a `before_unset` handler will make the attribute non-removable. -/ (after_set : option (Π (decl : _root_.name) (prio : nat) (persistent : bool), command) := none) /- Optional handler that will be called before the attribute is removed from a declaration. -/ (before_unset : option (Π (decl : _root_.name) (persistent : bool), command) := none) /- Registers a new user-defined attribute. The argument must be the name of a definition of type `user_attribute` or a sub-structure. -/ meta def attribute.register (decl : name) : command := tactic.set_basic_attribute ``user_attribute decl tt meta structure caching_user_attribute (α : Type) extends user_attribute := (mk_cache : list _root_.name → tactic α) (dependencies : list _root_.name) meta constant caching_user_attribute.get_cache : Π {α : Type}, caching_user_attribute α → tactic α open tactic meta def register_attribute := attribute.register meta def mk_name_set_attr (attr_name : name) : command := do let t := `(caching_user_attribute name_set), let v := `({name := attr_name, descr := "name_set attribute", mk_cache := λ ns, return (name_set.of_list ns), dependencies := [] } : caching_user_attribute name_set), add_meta_definition attr_name [] t v, register_attribute attr_name meta def get_name_set_for_attr (attr_name : name) : tactic name_set := do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute name_set) cnst, caching_user_attribute.get_cache attr
7057131bccc4d2b450d00197cd7405cbfbafd036
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_topology/cech_nerve.lean
9c21341cfe6cb8f09f6f5a5a3804b367e00bb27c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,911
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import algebraic_topology.simplicial_object import category_theory.limits.shapes.wide_pullbacks import category_theory.arrow /-! # The Čech Nerve This file provides a definition of the Čech nerve associated to an arrow, provided the base category has the correct wide pullbacks. Several variants are provided, given `f : arrow C`: 1. `f.cech_nerve` is the Čech nerve, considered as a simplicial object in `C`. 2. `f.augmented_cech_nerve` is the augmented Čech nerve, considered as an augmented simplicial object in `C`. 3. `simplicial_object.cech_nerve` and `simplicial_object.augmented_cech_nerve` are functorial versions of 1 resp. 2. -/ open category_theory open category_theory.limits noncomputable theory universes v u variables {C : Type u} [category.{v} C] namespace category_theory.arrow variables (f : arrow C) variables [∀ n : ℕ, has_wide_pullback f.right (λ i : ulift (fin (n+1)), f.left) (λ i, f.hom)] /-- The Čech nerve associated to an arrow. -/ @[simps] def cech_nerve : simplicial_object C := { obj := λ n, wide_pullback f.right (λ i : ulift (fin (n.unop.len + 1)), f.left) (λ i, f.hom), map := λ m n g, wide_pullback.lift (wide_pullback.base _) (λ i, wide_pullback.π (λ i, f.hom) $ ulift.up $ g.unop.to_order_hom i.down) $ λ j, by simp, map_id' := λ x, by { ext ⟨⟩, { simpa }, { simp } }, map_comp' := λ x y z f g, by { ext ⟨⟩, { simpa }, { simp } } } /-- The morphism between Čech nerves associated to a morphism of arrows. -/ @[simps] def map_cech_nerve {f g : arrow C} [∀ n : ℕ, has_wide_pullback f.right (λ i : ulift (fin (n+1)), f.left) (λ i, f.hom)] [∀ n : ℕ, has_wide_pullback g.right (λ i : ulift (fin (n+1)), g.left) (λ i, g.hom)] (F : f ⟶ g) : f.cech_nerve ⟶ g.cech_nerve := { app := λ n, wide_pullback.lift (wide_pullback.base _ ≫ F.right) (λ i, wide_pullback.π _ i ≫ F.left) $ λ j, by simp, naturality' := λ x y f, by { ext ⟨⟩, { simp }, { simp } } } /-- The augmented Čech nerve associated to an arrow. -/ @[simps] def augmented_cech_nerve : simplicial_object.augmented C := { left := f.cech_nerve, right := f.right, hom := { app := λ i, wide_pullback.base _, naturality' := λ x y f, by { dsimp, simp } } } /-- The morphism between augmented Čech nerve associated to a morphism of arrows. -/ @[simps] def map_augmented_cech_nerve {f g : arrow C} [∀ n : ℕ, has_wide_pullback f.right (λ i : ulift (fin (n+1)), f.left) (λ i, f.hom)] [∀ n : ℕ, has_wide_pullback g.right (λ i : ulift (fin (n+1)), g.left) (λ i, g.hom)] (F : f ⟶ g) : f.augmented_cech_nerve ⟶ g.augmented_cech_nerve := { left := map_cech_nerve F, right := F.right, w' := by { ext, simp } } end category_theory.arrow namespace category_theory namespace simplicial_object variables [∀ (n : ℕ) (f : arrow C), has_wide_pullback f.right (λ i : ulift (fin (n+1)), f.left) (λ i, f.hom)] /-- The Čech nerve construction, as a functor from `arrow C`. -/ @[simps] def cech_nerve : arrow C ⥤ simplicial_object C := { obj := λ f, f.cech_nerve, map := λ f g F, arrow.map_cech_nerve F, map_id' := λ i, by { ext, { simp }, { simp } }, map_comp' := λ x y z f g, by { ext, { simp }, { simp } } } /-- The augmented Čech nerve construction, as a functor from `arrow C`. -/ @[simps] def augmented_cech_nerve : arrow C ⥤ simplicial_object.augmented C := { obj := λ f, f.augmented_cech_nerve, map := λ f g F, arrow.map_augmented_cech_nerve F, map_id' := λ x, by { ext, { simp }, { simp }, { refl } }, map_comp' := λ x y z f g, by { ext, { simp }, { simp }, { refl } } } /-- A helper function used in defining the Čech adjunction. -/ @[simps] def equivalence_right_to_left (X : simplicial_object.augmented C) (F : arrow C) (G : X ⟶ F.augmented_cech_nerve) : augmented.to_arrow.obj X ⟶ F := { left := G.left.app _ ≫ wide_pullback.π (λ i, F.hom) ⟨0⟩, right := G.right, w' := begin have := G.w, apply_fun (λ e, e.app (opposite.op $ simplex_category.mk 0)) at this, simpa using this, end } /-- A helper function used in defining the Čech adjunction. -/ @[simps] def equivalence_left_to_right (X : simplicial_object.augmented C) (F : arrow C) (G : augmented.to_arrow.obj X ⟶ F) : X ⟶ F.augmented_cech_nerve := { left := { app := λ x, limits.wide_pullback.lift (X.hom.app _ ≫ G.right) (λ i, X.left.map (simplex_category.const x.unop i.down).op ≫ G.left) (λ i, by { dsimp, erw [category.assoc, arrow.w, augmented.to_arrow_obj_hom, nat_trans.naturality_assoc, functor.const.obj_map, category.id_comp] } ), naturality' := begin intros x y f, ext, { dsimp, simp only [wide_pullback.lift_π, category.assoc], rw [← category.assoc, ← X.left.map_comp], refl }, { dsimp, simp only [functor.const.obj_map, nat_trans.naturality_assoc, wide_pullback.lift_base, category.assoc], erw category.id_comp } end }, right := G.right, w' := by { ext, dsimp, simp } } /-- A helper function used in defining the Čech adjunction. -/ @[simps] def cech_nerve_equiv (X : simplicial_object.augmented C) (F : arrow C) : (augmented.to_arrow.obj X ⟶ F) ≃ (X ⟶ F.augmented_cech_nerve) := { to_fun := equivalence_left_to_right _ _, inv_fun := equivalence_right_to_left _ _, left_inv := begin intro A, dsimp, ext, { dsimp, erw wide_pullback.lift_π, nth_rewrite 1 ← category.id_comp A.left, congr' 1, convert X.left.map_id _, rw ← op_id, congr' 1, ext ⟨a,ha⟩, change a < 1 at ha, change 0 = a, linarith }, { refl, } end, right_inv := begin intro A, ext _ ⟨j⟩, { dsimp, simp only [arrow.cech_nerve_map, wide_pullback.lift_π, nat_trans.naturality_assoc], erw wide_pullback.lift_π, refl }, { erw wide_pullback.lift_base, have := A.w, apply_fun (λ e, e.app x) at this, rw nat_trans.comp_app at this, erw this, refl }, { refl } end } /-- The augmented Čech nerve construction is right adjoint to the `to_arrow` functor. -/ abbreviation cech_nerve_adjunction : (augmented.to_arrow : _ ⥤ arrow C) ⊣ augmented_cech_nerve := adjunction.mk_of_hom_equiv { hom_equiv := cech_nerve_equiv, hom_equiv_naturality_left_symm' := λ x y f g h, by { ext, { simp }, { simp } }, hom_equiv_naturality_right' := λ x y f g h, by { ext, { simp }, { simp }, { refl } } } end simplicial_object end category_theory namespace category_theory.arrow variables (f : arrow C) variables [∀ n : ℕ, has_wide_pushout f.left (λ i : ulift (fin (n+1)), f.right) (λ i, f.hom)] /-- The Čech conerve associated to an arrow. -/ @[simps] def cech_conerve : cosimplicial_object C := { obj := λ n, wide_pushout f.left (λ i : ulift (fin (n.len + 1)), f.right) (λ i, f.hom), map := λ m n g, wide_pushout.desc (wide_pushout.head _) (λ i, wide_pushout.ι (λ i, f.hom) $ ulift.up $ g.to_order_hom i.down) $ λ i, by { rw [wide_pushout.arrow_ι (λ i, f.hom)] }, map_id' := λ x, by { ext ⟨⟩, { simpa }, { simp } }, map_comp' := λ x y z f g, by { ext ⟨⟩, { simpa }, { simp } } } /-- The morphism between Čech conerves associated to a morphism of arrows. -/ @[simps] def map_cech_conerve {f g : arrow C} [∀ n : ℕ, has_wide_pushout f.left (λ i : ulift (fin (n+1)), f.right) (λ i, f.hom)] [∀ n : ℕ, has_wide_pushout g.left (λ i : ulift (fin (n+1)), g.right) (λ i, g.hom)] (F : f ⟶ g) : f.cech_conerve ⟶ g.cech_conerve := { app := λ n, wide_pushout.desc (F.left ≫ wide_pushout.head _) (λ i, F.right ≫ wide_pushout.ι _ i) $ λ i, by { rw [← arrow.w_assoc F, wide_pushout.arrow_ι (λ i, g.hom)] }, naturality' := λ x y f, by { ext, { simp }, { simp } } } /-- The augmented Čech conerve associated to an arrow. -/ @[simps] def augmented_cech_conerve : cosimplicial_object.augmented C := { left := f.left, right := f.cech_conerve, hom := { app := λ i, wide_pushout.head _, naturality' := λ x y f, by { dsimp, simp } } } /-- The morphism between augmented Čech conerves associated to a morphism of arrows. -/ @[simps] def map_augmented_cech_conerve {f g : arrow C} [∀ n : ℕ, has_wide_pushout f.left (λ i : ulift (fin (n+1)), f.right) (λ i, f.hom)] [∀ n : ℕ, has_wide_pushout g.left (λ i : ulift (fin (n+1)), g.right) (λ i, g.hom)] (F : f ⟶ g) : f.augmented_cech_conerve ⟶ g.augmented_cech_conerve := { left := F.left, right := map_cech_conerve F, w' := by { ext, simp } } end category_theory.arrow namespace category_theory namespace cosimplicial_object variables [∀ (n : ℕ) (f : arrow C), has_wide_pushout f.left (λ i : ulift (fin (n+1)), f.right) (λ i, f.hom)] /-- The Čech conerve construction, as a functor from `arrow C`. -/ @[simps] def cech_conerve : arrow C ⥤ cosimplicial_object C := { obj := λ f, f.cech_conerve, map := λ f g F, arrow.map_cech_conerve F, map_id' := λ i, by { ext, { dsimp, simp }, { dsimp, simp } }, map_comp' := λ f g h F G, by { ext, { simp }, { simp } } } /-- The augmented Čech conerve construction, as a functor from `arrow C`. -/ @[simps] def augmented_cech_conerve : arrow C ⥤ cosimplicial_object.augmented C := { obj := λ f, f.augmented_cech_conerve, map := λ f g F, arrow.map_augmented_cech_conerve F, map_id' := λ f, by { ext, { refl }, { dsimp, simp }, { dsimp, simp } }, map_comp' := λ f g h F G, by { ext, { refl }, { simp }, { simp } } } /-- A helper function used in defining the Čech conerve adjunction. -/ @[simps] def equivalence_left_to_right (F : arrow C) (X : cosimplicial_object.augmented C) (G : F.augmented_cech_conerve ⟶ X) : F ⟶ augmented.to_arrow.obj X := { left := G.left, right := (wide_pushout.ι (λ i, F.hom) (_root_.ulift.up 0) ≫ G.right.app (simplex_category.mk 0) : _), w' := begin have := G.w, apply_fun (λ e, e.app (simplex_category.mk 0)) at this, simpa only [category_theory.functor.id_map, augmented.to_arrow_obj_hom, wide_pushout.arrow_ι_assoc (λ i, F.hom)], end } /-- A helper function used in defining the Čech conerve adjunction. -/ @[simps] def equivalence_right_to_left (F : arrow C) (X : cosimplicial_object.augmented C) (G : F ⟶ augmented.to_arrow.obj X) : F.augmented_cech_conerve ⟶ X := { left := G.left, right := { app := λ x, limits.wide_pushout.desc (G.left ≫ X.hom.app _) (λ i, G.right ≫ X.right.map (simplex_category.const x i.down)) begin rintros ⟨j⟩, rw ← arrow.w_assoc G, have t := X.hom.naturality (x.const j), dsimp at t ⊢, simp only [category.id_comp] at t, rw ← t, end, naturality' := begin intros x y f, ext, { dsimp, simp only [wide_pushout.ι_desc_assoc, wide_pushout.ι_desc], rw [category.assoc, ←X.right.map_comp], refl }, { dsimp, simp only [functor.const.obj_map, ←nat_trans.naturality, wide_pushout.head_desc_assoc, wide_pushout.head_desc, category.assoc], erw category.id_comp } end }, w' := by { ext, simp } } /-- A helper function used in defining the Čech conerve adjunction. -/ @[simps] def cech_conerve_equiv (F : arrow C) (X : cosimplicial_object.augmented C) : (F.augmented_cech_conerve ⟶ X) ≃ (F ⟶ augmented.to_arrow.obj X) := { to_fun := equivalence_left_to_right _ _, inv_fun := equivalence_right_to_left _ _, left_inv := begin intro A, dsimp, ext _, { refl }, ext _ ⟨⟩, -- A bug in the `ext` tactic? { dsimp, simp only [arrow.cech_conerve_map, wide_pushout.ι_desc, category.assoc, ← nat_trans.naturality, wide_pushout.ι_desc_assoc], refl }, { erw wide_pushout.head_desc, have := A.w, apply_fun (λ e, e.app x) at this, rw nat_trans.comp_app at this, erw this, refl }, end, right_inv := begin intro A, ext, { refl, }, { dsimp, erw wide_pushout.ι_desc, nth_rewrite 1 ← category.comp_id A.right, congr' 1, convert X.right.map_id _, ext ⟨a,ha⟩, change a < 1 at ha, change 0 = a, linarith }, end } /-- The augmented Čech conerve construction is left adjoint to the `to_arrow` functor. -/ abbreviation cech_conerve_adjunction : augmented_cech_conerve ⊣ (augmented.to_arrow : _ ⥤ arrow C) := adjunction.mk_of_hom_equiv { hom_equiv := cech_conerve_equiv, hom_equiv_naturality_left_symm' := λ x y f g h, by { ext, { refl }, { simp }, { simp } }, hom_equiv_naturality_right' := λ x y f g h, by { ext, { simp }, { simp } } } end cosimplicial_object end category_theory
97122f053a0937d7275cd9a6d4f3ec853ab9f296
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/category_theory/is_connected.lean
dbd3cee42c779ade098d6c19ce8f680cbdb51c17
[ "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,447
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.list.chain import category_theory.punit import category_theory.groupoid /-! # Connected category Define a connected category as a _nonempty_ category for which every functor to a discrete category is isomorphic to the constant functor. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. We give some equivalent definitions: - A nonempty category for which every functor to a discrete category is constant on objects. See `any_functor_const_on_obj` and `connected.of_any_functor_const_on_obj`. - A nonempty category for which every function `F` for which the presence of a morphism `f : j₁ ⟶ j₂` implies `F j₁ = F j₂` must be constant everywhere. See `constant_of_preserves_morphisms` and `connected.of_constant_of_preserves_morphisms`. - A nonempty category for which any subset of its elements containing the default and closed under morphisms is everything. See `induct_on_objects` and `connected.of_induct`. - A nonempty category for which every object is related under the reflexive transitive closure of the relation "there is a morphism in some direction from `j₁` to `j₂`". See `connected_zigzag` and `zigzag_connected`. - A nonempty category for which for any two objects there is a sequence of morphisms (some reversed) from one to the other. See `exists_zigzag'` and `connected_of_zigzag`. We also prove the result that the functor given by `(X × -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X × -)`. This appears in `category_theory.limits.connected`. -/ universes v₁ v₂ u₁ u₂ noncomputable theory open category_theory.category namespace category_theory /-- A possibly empty category for which every functor to a discrete category is constant. -/ class is_preconnected (J : Type u₁) [category.{v₁} J] : Prop := (iso_constant : Π {α : Type u₁} (F : J ⥤ discrete α) (j : J), nonempty (F ≅ (functor.const J).obj (F.obj j))) /-- We define a connected category as a _nonempty_ category for which every functor to a discrete category is constant. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. This allows us to show that the functor X ⨯ - preserves connected limits. See https://stacks.math.columbia.edu/tag/002S -/ class is_connected (J : Type u₁) [category.{v₁} J] extends is_preconnected J : Prop := [is_nonempty : nonempty J] attribute [instance, priority 100] is_connected.is_nonempty variables {J : Type u₁} [category.{v₁} J] variables {K : Type u₂} [category.{v₂} K] /-- If `J` is connected, any functor `F : J ⥤ discrete α` is isomorphic to the constant functor with value `F.obj j` (for any choice of `j`). -/ def iso_constant [is_preconnected J] {α : Type u₁} (F : J ⥤ discrete α) (j : J) : F ≅ (functor.const J).obj (F.obj j) := (is_preconnected.iso_constant F j).some /-- If J is connected, any functor to a discrete category is constant on objects. The converse is given in `is_connected.of_any_functor_const_on_obj`. -/ lemma any_functor_const_on_obj [is_preconnected J] {α : Type u₁} (F : J ⥤ discrete α) (j j' : J) : F.obj j = F.obj j' := ((iso_constant F j').hom.app j).down.1 /-- If any functor to a discrete category is constant on objects, J is connected. The converse of `any_functor_const_on_obj`. -/ lemma is_connected.of_any_functor_const_on_obj [nonempty J] (h : ∀ {α : Type u₁} (F : J ⥤ discrete α), ∀ (j j' : J), F.obj j = F.obj j') : is_connected J := { iso_constant := λ α F j', ⟨nat_iso.of_components (λ j, eq_to_iso (h F j j')) (λ _ _ _, subsingleton.elim _ _)⟩ } /-- If `J` is connected, then given any function `F` such that the presence of a morphism `j₁ ⟶ j₂` implies `F j₁ = F j₂`, we have that `F` is constant. This can be thought of as a local-to-global property. The converse is shown in `is_connected.of_constant_of_preserves_morphisms` -/ lemma constant_of_preserves_morphisms [is_preconnected J] {α : Type u₁} (F : J → α) (h : ∀ (j₁ j₂ : J) (f : j₁ ⟶ j₂), F j₁ = F j₂) (j j' : J) : F j = F j' := any_functor_const_on_obj { obj := F, map := λ _ _ f, eq_to_hom (h _ _ f) } j j' /-- `J` is connected if: given any function `F : J → α` which is constant for any `j₁, j₂` for which there is a morphism `j₁ ⟶ j₂`, then `F` is constant. This can be thought of as a local-to-global property. The converse of `constant_of_preserves_morphisms`. -/ lemma is_connected.of_constant_of_preserves_morphisms [nonempty J] (h : ∀ {α : Type u₁} (F : J → α), (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), F j₁ = F j₂) → (∀ j j' : J, F j = F j')) : is_connected J := is_connected.of_any_functor_const_on_obj (λ _ F, h F.obj (λ _ _ f, (F.map f).down.1)) /-- An inductive-like property for the objects of a connected category. If the set `p` is nonempty, and `p` is closed under morphisms of `J`, then `p` contains all of `J`. The converse is given in `is_connected.of_induct`. -/ lemma induct_on_objects [is_preconnected J] (p : set J) {j₀ : J} (h0 : j₀ ∈ p) (h1 : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) (j : J) : j ∈ p := begin injection (constant_of_preserves_morphisms (λ k, ulift.up (k ∈ p)) (λ j₁ j₂ f, _) j j₀) with i, rwa i, dsimp, exact congr_arg ulift.up (propext (h1 f)), end /-- If any maximal connected component containing some element j₀ of J is all of J, then J is connected. The converse of `induct_on_objects`. -/ lemma is_connected.of_induct [nonempty J] {j₀ : J} (h : ∀ (p : set J), j₀ ∈ p → (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) → ∀ (j : J), j ∈ p) : is_connected J := is_connected.of_constant_of_preserves_morphisms (λ α F a, begin have w := h {j | F j = F j₀} rfl (λ _ _ f, by simp [a f]), dsimp at w, intros j j', rw [w j, w j'], end) /-- Another induction principle for `is_preconnected J`: given a type family `Z : J → Sort*` and a rule for transporting in *both* directions along a morphism in `J`, we can transport an `x : Z j₀` to a point in `Z j` for any `j`. -/ lemma is_preconnected_induction [is_preconnected J] (Z : J → Sort*) (h₁ : Π {j₁ j₂ : J} (f : j₁ ⟶ j₂), Z j₁ → Z j₂) (h₂ : Π {j₁ j₂ : J} (f : j₁ ⟶ j₂), Z j₂ → Z j₁) {j₀ : J} (x : Z j₀) (j : J) : nonempty (Z j) := (induct_on_objects {j | nonempty (Z j)} ⟨x⟩ (λ j₁ j₂ f, ⟨by { rintro ⟨y⟩, exact ⟨h₁ f y⟩, }, by { rintro ⟨y⟩, exact ⟨h₂ f y⟩, }⟩) j : _) /-- If `J` and `K` are equivalent, then if `J` is preconnected then `K` is as well. -/ lemma is_preconnected_of_equivalent {K : Type u₁} [category.{v₂} K] [is_preconnected J] (e : J ≌ K) : is_preconnected K := { iso_constant := λ α F k, ⟨ calc F ≅ e.inverse ⋙ e.functor ⋙ F : (e.inv_fun_id_assoc F).symm ... ≅ e.inverse ⋙ (functor.const J).obj ((e.functor ⋙ F).obj (e.inverse.obj k)) : iso_whisker_left e.inverse (iso_constant (e.functor ⋙ F) (e.inverse.obj k)) ... ≅ e.inverse ⋙ (functor.const J).obj (F.obj k) : iso_whisker_left _ ((F ⋙ functor.const J).map_iso (e.counit_iso.app k)) ... ≅ (functor.const K).obj (F.obj k) : nat_iso.of_components (λ X, iso.refl _) (by simp), ⟩ } /-- If `J` and `K` are equivalent, then if `J` is connected then `K` is as well. -/ lemma is_connected_of_equivalent {K : Type u₁} [category.{v₂} K] (e : J ≌ K) [is_connected J] : is_connected K := { is_nonempty := nonempty.map e.functor.obj (by apply_instance), to_is_preconnected := is_preconnected_of_equivalent e } /-- j₁ and j₂ are related by `zag` if there is a morphism between them. -/ @[reducible] def zag (j₁ j₂ : J) : Prop := nonempty (j₁ ⟶ j₂) ∨ nonempty (j₂ ⟶ j₁) lemma zag_symmetric : symmetric (@zag J _) := λ j₂ j₁ h, h.swap /-- `j₁` and `j₂` are related by `zigzag` if there is a chain of morphisms from `j₁` to `j₂`, with backward morphisms allowed. -/ @[reducible] def zigzag : J → J → Prop := relation.refl_trans_gen zag lemma zigzag_symmetric : symmetric (@zigzag J _) := relation.refl_trans_gen.symmetric zag_symmetric lemma zigzag_equivalence : _root_.equivalence (@zigzag J _) := mk_equivalence _ relation.reflexive_refl_trans_gen zigzag_symmetric relation.transitive_refl_trans_gen /-- The setoid given by the equivalence relation `zigzag`. A quotient for this setoid is a connected component of the category. -/ def zigzag.setoid (J : Type u₂) [category.{v₁} J] : setoid J := { r := zigzag, iseqv := zigzag_equivalence } /-- If there is a zigzag from `j₁` to `j₂`, then there is a zigzag from `F j₁` to `F j₂` as long as `F` is a functor. -/ lemma zigzag_obj_of_zigzag (F : J ⥤ K) {j₁ j₂ : J} (h : zigzag j₁ j₂) : zigzag (F.obj j₁) (F.obj j₂) := begin refine relation.refl_trans_gen_lift _ _ h, intros j k, exact or.imp (nonempty.map (λ f, F.map f)) (nonempty.map (λ f, F.map f)) end -- TODO: figure out the right way to generalise this to `zigzag`. lemma zag_of_zag_obj (F : J ⥤ K) [full F] {j₁ j₂ : J} (h : zag (F.obj j₁) (F.obj j₂)) : zag j₁ j₂ := or.imp (nonempty.map F.preimage) (nonempty.map F.preimage) h /-- Any equivalence relation containing (⟶) holds for all pairs of a connected category. -/ lemma equiv_relation [is_connected J] (r : J → J → Prop) (hr : _root_.equivalence r) (h : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), r j₁ j₂) : ∀ (j₁ j₂ : J), r j₁ j₂ := begin have z : ∀ (j : J), r (classical.arbitrary J) j := induct_on_objects (λ k, r (classical.arbitrary J) k) (hr.1 (classical.arbitrary J)) (λ _ _ f, ⟨λ t, hr.2.2 t (h f), λ t, hr.2.2 t (hr.2.1 (h f))⟩), intros, apply hr.2.2 (hr.2.1 (z _)) (z _) end /-- In a connected category, any two objects are related by `zigzag`. -/ lemma is_connected_zigzag [is_connected J] (j₁ j₂ : J) : zigzag j₁ j₂ := equiv_relation _ zigzag_equivalence (λ _ _ f, relation.refl_trans_gen.single (or.inl (nonempty.intro f))) _ _ /-- If any two objects in an nonempty category are related by `zigzag`, the category is connected. -/ lemma zigzag_is_connected [nonempty J] (h : ∀ (j₁ j₂ : J), zigzag j₁ j₂) : is_connected J := begin apply is_connected.of_induct, intros p hp hjp j, have: ∀ (j₁ j₂ : J), zigzag j₁ j₂ → (j₁ ∈ p ↔ j₂ ∈ p), { introv k, induction k with _ _ rt_zag zag, { refl }, { rw k_ih, rcases zag with ⟨⟨_⟩⟩ | ⟨⟨_⟩⟩, apply hjp zag, apply (hjp zag).symm } }, rwa this j (classical.arbitrary J) (h _ _) end lemma exists_zigzag' [is_connected J] (j₁ j₂ : J) : ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂ := list.exists_chain_of_relation_refl_trans_gen (is_connected_zigzag _ _) /-- If any two objects in an nonempty category are linked by a sequence of (potentially reversed) morphisms, then J is connected. The converse of `exists_zigzag'`. -/ lemma is_connected_of_zigzag [nonempty J] (h : ∀ (j₁ j₂ : J), ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂) : is_connected J := begin apply zigzag_is_connected, intros j₁ j₂, rcases h j₁ j₂ with ⟨l, hl₁, hl₂⟩, apply list.relation_refl_trans_gen_of_exists_chain l hl₁ hl₂, end /-- If `discrete α` is connected, then `α` is (type-)equivalent to `punit`. -/ def discrete_is_connected_equiv_punit {α : Type u₁} [is_connected (discrete α)] : α ≃ punit := discrete.equiv_of_equivalence { functor := functor.star α, inverse := discrete.functor (λ _, classical.arbitrary _), unit_iso := by { exact (iso_constant _ (classical.arbitrary _)), }, counit_iso := functor.punit_ext _ _ } variables {C : Type u₂} [category.{u₁} C] /-- For objects `X Y : C`, any natural transformation `α : const X ⟶ const Y` from a connected category must be constant. This is the key property of connected categories which we use to establish properties about limits. -/ lemma nat_trans_from_is_connected [is_preconnected J] {X Y : C} (α : (functor.const J).obj X ⟶ (functor.const J).obj Y) : ∀ (j j' : J), α.app j = (α.app j' : X ⟶ Y) := @constant_of_preserves_morphisms _ _ _ (X ⟶ Y) (λ j, α.app j) (λ _ _ f, (by { have := α.naturality f, erw [id_comp, comp_id] at this, exact this.symm })) instance [is_connected J] : full (functor.const J : C ⥤ J ⥤ C) := { preimage := λ X Y f, f.app (classical.arbitrary J), witness' := λ X Y f, begin ext j, apply nat_trans_from_is_connected f (classical.arbitrary J) j, end } instance nonempty_hom_of_connected_groupoid {G} [groupoid G] [is_connected G] : ∀ (x y : G), nonempty (x ⟶ y) := begin refine equiv_relation _ _ (λ j₁ j₂, nonempty.intro), exact ⟨λ j, ⟨𝟙 _⟩, λ j₁ j₂, nonempty.map (λ f, inv f), λ _ _ _, nonempty.map2 (≫)⟩, end end category_theory
f194954daef9b58050ba0cfa5c9b75c9bea000fb
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/algebra/theories/category.lean
3e21b5b03998df205b86ac5f78deffe56f3e5050
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
3,505
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .monoid import .group import .action namespace algebra /- signature command cannot handle operation parameters, so we define category_sig manually; category_hom is missing. -/ structure category_sig {α : Type*} (β : α → α → Type*) := (op (a b c : α) : β a b → β b c → β a c) (id (a : α) : β a a) namespace category_sig variables {α : Type*} {β : α → α → Type*} (s : category_sig β) @[signature_instance] definition to_monoid (a : α) : monoid_sig (β a a) := { op := s.op a a a , id := s.id a } @[signature_instance] definition to_left_action (a b : α) : left_action_sig (β a a) (β a b) := { act := s.op a a b } @[signature_instance] definition to_right_action (a b : α) : right_action_sig (β a a) (β b a) := { act := s.op b a a } end category_sig /- TODO: fix theory attribute to handle parameters correctly -/ class category {α : Type*} {β : α → α → Type*} (s : category_sig β) : Prop := intro :: (assoc (a b c d) : identity.op_compatibility (s.op a c d) (s.op a b c) (s.op a b d) (s.op b c d)) (left_identity (a b) : identity.op_left_identity (s.op a a b) (s.id a)) (right_identity (a b) : identity.op_right_identity (s.op a b b) (s.id b)) attribute [identity_instance] category.assoc attribute [identity_instance] category.left_identity attribute [identity_instance] category.right_identity namespace category variables {α : Type*} {β : α → α → Type*} (s : category_sig β) [i : category s] definition infer [Π (a b c d), class.op_compatibility (s.op a c d) (s.op a b c) (s.op a b d) (s.op b c d)] [Π (a b), class.op_left_identity (s.op a a b) (s.id a)] [Π (a b), class.op_right_identity (s.op a b b) (s.id b)] : category s := category.intro (λ _ _ _ _, op_compatibility _ _ _ _) (λ _ _, op_left_identity _ _) (λ _ _, op_right_identity _ _) include i instance to_monoid (a : α) : monoid (s.to_monoid a) := monoid.infer _ instance to_left_monoid_action (a b : α) : left_monoid_action (s.to_monoid a) (s.to_left_action a b) := left_monoid_action.infer _ _ instance to_right_monoid_action (a b : α) : right_monoid_action (s.to_monoid a) (s.to_right_action a b) := right_monoid_action.infer _ _ end category end algebra /- move to monoid when ready -/ namespace algebra namespace monoid_sig variables {α : Type*} (s : monoid_sig α) @[signature_instance] definition to_category : category_sig (λ (_ _ : unit), α) := { op := λ _ _ _, s.op , id := λ _, s.id } end monoid_sig namespace monoid variables {α : Type*} (s : monoid_sig α) [monoid s] @[identity_instance] theorem to_category_compatibility (a b c d : unit) : identity.op_compatibility (s.to_category.op a c d) (s.to_category.op a b c) (s.to_category.op a b d) (s.to_category.op b c d) := show identity.op_compatibility s.op s.op s.op s.op, from op_associative s.op @[identity_instance] theorem to_category_left_identity (a b : unit) : identity.op_left_identity (s.to_category.op a a b) (s.to_category.id a) := show identity.op_left_identity s.op s.id, from op_left_identity s.op s.id @[identity_instance] theorem to_category_right_identity (a b : unit) : identity.op_right_identity (s.to_category.op a b b) (s.to_category.id b) := show identity.op_right_identity s.op s.id, from op_right_identity s.op s.id instance to_category : category s.to_category := category.infer _ end monoid end algebra
6ecc4e544eeef5a72f0a3e0d5ff892054ddbc700
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/setoid/partition.lean
665d242399391e9b1266e801a10761ea62ada402
[ "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
14,910
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen, Patrick Massot -/ import data.setoid.basic import data.set.pairwise /-! # Equivalence relations: partitions This file comprises properties of equivalence relations viewed as partitions. There are two implementations of partitions here: * A collection `c : set (set α)` of sets is a partition of `α` if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. This is expressed as `is_partition c` * An indexed partition is a map `s : ι → α` whose image is a partition. This is expressed as `indexed_partition s`. Of course both implementations are related to `quotient` and `setoid`. ## Tags setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class -/ namespace setoid variables {α : Type*} /-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/ lemma eq_of_mem_eqv_class {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') : b = b' := (H x).unique2 hc hb hc' hb' /-- Makes an equivalence relation from a set of sets partitioning α. -/ def mk_classes (c : set (set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) : setoid α := ⟨λ x y, ∀ s ∈ c, x ∈ s → y ∈ s, ⟨λ _ _ _ hx, hx, λ x y h s hs hy, (H x).elim2 $ λ t ht hx _, have s = t, from eq_of_mem_eqv_class H hs hy ht (h t ht hx), this.symm ▸ hx, λ x y z h1 h2 s hs hx, (H y).elim2 $ λ t ht hy _, (H z).elim2 $ λ t' ht' hz _, have hst : s = t, from eq_of_mem_eqv_class H hs (h1 _ hs hx) ht hy, have htt' : t = t', from eq_of_mem_eqv_class H ht (h2 _ ht hy) ht' hz, (hst.trans htt').symm ▸ hz⟩⟩ /-- Makes the equivalence classes of an equivalence relation. -/ def classes (r : setoid α) : set (set α) := {s | ∃ y, s = {x | r.rel x y}} lemma mem_classes (r : setoid α) (y) : {x | r.rel x y} ∈ r.classes := ⟨y, rfl⟩ /-- Two equivalence relations are equal iff all their equivalence classes are equal. -/ lemma eq_iff_classes_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ ∀ x, {y | r₁.rel x y} = {y | r₂.rel x y} := ⟨λ h x, h ▸ rfl, λ h, ext' $ λ x, set.ext_iff.1 $ h x⟩ lemma rel_iff_exists_classes (r : setoid α) {x y} : r.rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c := ⟨λ h, ⟨_, r.mem_classes y, h, r.refl' y⟩, λ ⟨c, ⟨z, hz⟩, hx, hy⟩, by { subst c, exact r.trans' hx (r.symm' hy) }⟩ /-- Two equivalence relations are equal iff their equivalence classes are equal. -/ lemma classes_inj {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.classes = r₂.classes := ⟨λ h, h ▸ rfl, λ h, ext' $ λ a b, by simp only [rel_iff_exists_classes, exists_prop, h] ⟩ /-- The empty set is not an equivalence class. -/ lemma empty_not_mem_classes {r : setoid α} : ∅ ∉ r.classes := λ ⟨y, hy⟩, set.not_mem_empty y $ hy.symm ▸ r.refl' y /-- Equivalence classes partition the type. -/ lemma classes_eqv_classes {r : setoid α} (a) : ∃! b ∈ r.classes, a ∈ b := exists_unique.intro2 {x | r.rel x a} (r.mem_classes a) (r.refl' _) $ begin rintros _ ⟨y, rfl⟩ ha, ext x, exact ⟨λ hx, r.trans' hx (r.symm' ha), λ hx, r.trans' hx ha⟩ end /-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/ lemma eq_of_mem_classes {r : setoid α} {x b} (hc : b ∈ r.classes) (hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' := eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb' /-- The elements of a set of sets partitioning α are the equivalence classes of the equivalence relation defined by the set of sets. -/ lemma eq_eqv_class_of_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) : s = {x | (mk_classes c H).rel x y} := set.ext $ λ x, ⟨λ hs', symm' (mk_classes c H) $ λ b' hb' h', eq_of_mem_eqv_class H hs hy hb' h' ▸ hs', λ hx, (H x).elim2 $ λ b' hc' hb' h', (eq_of_mem_eqv_class H hs hy hc' $ hx b' hc' hb').symm ▸ hb'⟩ /-- The equivalence classes of the equivalence relation defined by a set of sets partitioning α are elements of the set of sets. -/ lemma eqv_class_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} : {x | (mk_classes c H).rel x y} ∈ c := (H y).elim2 $ λ b hc hy hb, eq_eqv_class_of_mem H hc hy ▸ hc lemma eqv_class_mem' {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x} : {y : α | (mk_classes c H).rel x y} ∈ c := by { convert setoid.eqv_class_mem H, ext, rw setoid.comm' } /-- Distinct elements of a set of sets partitioning α are disjoint. -/ lemma eqv_classes_disjoint {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) : c.pairwise_disjoint id := λ b₁ h₁ b₂ h₂ h, set.disjoint_left.2 $ λ x hx1 hx2, (H x).elim2 $ λ b hc hx hb, h $ eq_of_mem_eqv_class H h₁ hx1 h₂ hx2 /-- A set of disjoint sets covering α partition α (classical). -/ lemma eqv_classes_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : c.pairwise_disjoint id) (a) : ∃! b ∈ c, a ∈ b := let ⟨b, hc, ha⟩ := set.mem_sUnion.1 $ show a ∈ _, by rw hu; exact set.mem_univ a in exists_unique.intro2 b hc ha $ λ b' hc' ha', H.elim_set hc' hc a ha' ha /-- Makes an equivalence relation from a set of disjoints sets covering α. -/ def setoid_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : c.pairwise_disjoint id) : setoid α := setoid.mk_classes c $ eqv_classes_of_disjoint_union hu H /-- The equivalence relation made from the equivalence classes of an equivalence relation r equals r. -/ theorem mk_classes_classes (r : setoid α) : mk_classes r.classes classes_eqv_classes = r := ext' $ λ x y, ⟨λ h, r.symm' (h {z | r.rel z x} (r.mem_classes x) $ r.refl' x), λ h b hb hx, eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩ @[simp] theorem sUnion_classes (r : setoid α) : ⋃₀ r.classes = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 ⟨{ y | r.rel y x }, ⟨x, rfl⟩, setoid.refl _⟩ section partition /-- A collection `c : set (set α)` of sets is a partition of `α` into pairwise disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/ def is_partition (c : set (set α)) := ∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b /-- A partition of `α` does not contain the empty set. -/ lemma nonempty_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (h : s ∈ c) : s.nonempty := set.ne_empty_iff_nonempty.1 $ λ hs0, hc.1 $ hs0 ▸ h lemma is_partition_classes (r : setoid α) : is_partition r.classes := ⟨empty_not_mem_classes, classes_eqv_classes⟩ lemma is_partition.pairwise_disjoint {c : set (set α)} (hc : is_partition c) : c.pairwise_disjoint id := eqv_classes_disjoint hc.2 lemma is_partition.sUnion_eq_univ {c : set (set α)} (hc : is_partition c) : ⋃₀ c = set.univ := set.eq_univ_of_forall $ λ x, set.mem_sUnion.2 $ let ⟨t, ht⟩ := hc.2 x in ⟨t, by clear_aux_decl; finish⟩ /-- All elements of a partition of α are the equivalence class of some y ∈ α. -/ lemma exists_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (hs : s ∈ c) : ∃ y, s = {x | (mk_classes c hc.2).rel x y} := let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs in ⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩ /-- The equivalence classes of the equivalence relation defined by a partition of α equal the original partition. -/ theorem classes_mk_classes (c : set (set α)) (hc : is_partition c) : (mk_classes c hc.2).classes = c := set.ext $ λ s, ⟨λ ⟨y, hs⟩, (hc.2 y).elim2 $ λ b hm hb hy, by rwa (show s = b, from hs.symm ▸ set.ext (λ x, ⟨λ hx, symm' (mk_classes c hc.2) hx b hm hb, λ hx b' hc' hx', eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩)), exists_of_mem_partition hc⟩ /-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/ instance partition.le : has_le (subtype (@is_partition α)) := ⟨λ x y, mk_classes x.1 x.2.2 ≤ mk_classes y.1 y.2.2⟩ /-- Defining a partial order on partitions as the partial order on their induced equivalence relations. -/ instance partition.partial_order : partial_order (subtype (@is_partition α)) := { le := (≤), lt := λ x y, x ≤ y ∧ ¬y ≤ x, le_refl := λ _, @le_refl (setoid α) _ _, le_trans := λ _ _ _, @le_trans (setoid α) _ _ _ _, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ x y hx hy, let h := @le_antisymm (setoid α) _ _ _ hx hy in by rw [subtype.ext_iff_val, ←classes_mk_classes x.1 x.2, ←classes_mk_classes y.1 y.2, h] } variables (α) /-- The order-preserving bijection between equivalence relations on a type `α`, and partitions of `α` into subsets. -/ protected def partition.order_iso : setoid α ≃o {C : set (set α) // is_partition C} := { to_fun := λ r, ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩, inv_fun := λ C, mk_classes C.1 C.2.2, left_inv := mk_classes_classes, right_inv := λ C, by rw [subtype.ext_iff_val, ←classes_mk_classes C.1 C.2], map_rel_iff' := λ r s, by { conv_rhs { rw [←mk_classes_classes r, ←mk_classes_classes s] }, refl } } variables {α} /-- A complete lattice instance for partitions; there is more infrastructure for the equivalent complete lattice on equivalence relations. -/ instance partition.complete_lattice : complete_lattice (subtype (@is_partition α)) := galois_insertion.lift_complete_lattice $ @order_iso.to_galois_insertion _ (subtype (@is_partition α)) _ (partial_order.to_preorder _) $ partition.order_iso α end partition end setoid /-- Constructive information associated with a partition of a type `α` indexed by another type `ι`, `s : ι → set α`. `indexed_partition.index` sends an element to its index, while `indexed_partition.some` sends an index to an element of the corresponding set. This type is primarily useful for definitional control of `s` - if this is not needed, then `setoid.ker index` by itself may be sufficient. -/ structure indexed_partition {ι α : Type*} (s : ι → set α) := (eq_of_mem : ∀ {x i j}, x ∈ s i → x ∈ s j → i = j) (some : ι → α) (some_mem : ∀ i, some i ∈ s i) (index : α → ι) (mem_index : ∀ x, x ∈ s (index x)) /-- The non-constructive constructor for `indexed_partition`. -/ noncomputable def indexed_partition.mk' {ι α : Type*} (s : ι → set α) (dis : ∀ i j, i ≠ j → disjoint (s i) (s j)) (nonempty : ∀ i, (s i).nonempty) (ex : ∀ x, ∃ i, x ∈ s i) : indexed_partition s := { eq_of_mem := λ x i j hxi hxj, classical.by_contradiction $ λ h, dis _ _ h ⟨hxi, hxj⟩, some := λ i, (nonempty i).some, some_mem := λ i, (nonempty i).some_spec, index := λ x, (ex x).some, mem_index := λ x, (ex x).some_spec } namespace indexed_partition open set variables {ι α : Type*} {s : ι → set α} (hs : indexed_partition s) /-- On a unique index set there is the obvious trivial partition -/ instance [unique ι] [inhabited α] : inhabited (indexed_partition (λ i : ι, (set.univ : set α))) := ⟨{ eq_of_mem := λ x i j hi hj, subsingleton.elim _ _, some := λ i, default α, some_mem := set.mem_univ, index := λ a, default ι, mem_index := set.mem_univ }⟩ attribute [simp] some_mem mem_index include hs lemma exists_mem (x : α) : ∃ i, x ∈ s i := ⟨hs.index x, hs.mem_index x⟩ lemma Union : (⋃ i, s i) = univ := by { ext x, simp [hs.exists_mem x] } lemma disjoint : ∀ {i j}, i ≠ j → disjoint (s i) (s j) := λ i j h x ⟨hxi, hxj⟩, h (hs.eq_of_mem hxi hxj) lemma mem_iff_index_eq {x i} : x ∈ s i ↔ hs.index x = i := ⟨λ hxi, (hs.eq_of_mem hxi (hs.mem_index x)).symm, λ h, h ▸ hs.mem_index _⟩ lemma eq (i) : s i = {x | hs.index x = i} := set.ext $ λ _, hs.mem_iff_index_eq /-- The equivalence relation associated to an indexed partition. Two elements are equivalent if they belong to the same set of the partition. -/ protected abbreviation setoid (hs : indexed_partition s) : setoid α := setoid.ker hs.index @[simp] lemma index_some (i : ι) : hs.index (hs.some i) = i := (mem_iff_index_eq _).1 $ hs.some_mem i lemma some_index (x : α) : hs.setoid.rel (hs.some (hs.index x)) x := hs.index_some (hs.index x) /-- The quotient associated to an indexed partition. -/ protected def quotient := quotient hs.setoid /-- The projection onto the quotient associated to an indexed partition. -/ def proj : α → hs.quotient := quotient.mk' instance [inhabited α] : inhabited (hs.quotient) := ⟨hs.proj (default α)⟩ lemma proj_eq_iff {x y : α} : hs.proj x = hs.proj y ↔ hs.index x = hs.index y := quotient.eq_rel @[simp] lemma proj_some_index (x : α) : hs.proj (hs.some (hs.index x)) = hs.proj x := quotient.eq'.2 (hs.some_index x) /-- The obvious equivalence between the quotient associated to an indexed partition and the indexing type. -/ def equiv_quotient : ι ≃ hs.quotient := (setoid.quotient_ker_equiv_of_right_inverse hs.index hs.some $ hs.index_some).symm @[simp] lemma equiv_quotient_index_apply (x : α) : hs.equiv_quotient (hs.index x) = hs.proj x := hs.proj_eq_iff.mpr (some_index hs x) @[simp] lemma equiv_quotient_symm_proj_apply (x : α) : hs.equiv_quotient.symm (hs.proj x) = hs.index x := rfl lemma equiv_quotient_index : hs.equiv_quotient ∘ hs.index = hs.proj := funext hs.equiv_quotient_index_apply /-- A map choosing a representative for each element of the quotient associated to an indexed partition. This is a computable version of `quotient.out'` using `indexed_partition.some`. -/ def out : hs.quotient ↪ α := hs.equiv_quotient.symm.to_embedding.trans ⟨hs.some, function.left_inverse.injective hs.index_some⟩ /-- This lemma is analogous to `quotient.mk_out'`. -/ @[simp] lemma out_proj (x : α) : hs.out (hs.proj x) = hs.some (hs.index x) := rfl /-- The indices of `quotient.out'` and `indexed_partition.out` are equal. -/ lemma index_out' (x : hs.quotient) : hs.index (x.out') = hs.index (hs.out x) := quotient.induction_on' x $ λ x, (setoid.ker_apply_mk_out' x).trans (hs.index_some _).symm /-- This lemma is analogous to `quotient.out_eq'`. -/ @[simp] lemma proj_out (x : hs.quotient) : hs.proj (hs.out x) = x := quotient.induction_on' x $ λ x, quotient.sound' $ hs.some_index x lemma class_of {x : α} : set_of (hs.setoid.rel x) = s (hs.index x) := set.ext $ λ y, eq_comm.trans hs.mem_iff_index_eq.symm lemma proj_fiber (x : hs.quotient) : hs.proj ⁻¹' {x} = s (hs.equiv_quotient.symm x) := quotient.induction_on' x $ λ x, begin ext y, simp only [set.mem_preimage, set.mem_singleton_iff, hs.mem_iff_index_eq], exact quotient.eq', end end indexed_partition
36c6f4159067768f94e4f78a87c86dfdc755af60
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/gamma.lean
a090be162a3f6c059aaddef0bb9770c4ba64b08d
[ "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
23,778
lean
/- Copyright (c) 2022 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import measure_theory.integral.exp_decay import analysis.calculus.parametric_integral import analysis.special_functions.integrals /-! # The Gamma function This file defines the `Γ` function (of a real or complex variable `s`). We define this by Euler's integral `Γ(s) = ∫ x in Ioi 0, exp (-x) * x ^ (s - 1)` in the range where this integral converges (i.e., for `0 < s` in the real case, and `0 < re s` in the complex case). We show that this integral satisfies `Γ(1) = 1` and `Γ(s + 1) = s * Γ(s)`; hence we can define `Γ(s)` for all `s` as the unique function satisfying this recurrence and agreeing with Euler's integral in the convergence range. In the complex case we also prove that the resulting function is holomorphic on `ℂ` away from the points `{-n : n ∈ ℤ}`. ## Tags Gamma -/ noncomputable theory open filter interval_integral set real measure_theory asymptotics open_locale topological_space lemma integral_exp_neg_Ioi : ∫ (x : ℝ) in Ioi 0, exp (-x) = 1 := begin refine tendsto_nhds_unique (interval_integral_tendsto_integral_Ioi _ _ tendsto_id) _, { simpa only [neg_mul, one_mul] using exp_neg_integrable_on_Ioi 0 zero_lt_one, }, { simpa using tendsto_exp_neg_at_top_nhds_0.const_sub 1, }, end namespace real /-- Asymptotic bound for the `Γ` function integrand. -/ lemma Gamma_integrand_is_o (s : ℝ) : (λ x:ℝ, exp (-x) * x ^ s) =o[at_top] (λ x:ℝ, exp (-(1/2) * x)) := begin refine is_o_of_tendsto (λ x hx, _) _, { exfalso, exact (exp_pos (-(1 / 2) * x)).ne' hx }, have : (λ (x:ℝ), exp (-x) * x ^ s / exp (-(1 / 2) * x)) = (λ (x:ℝ), exp ((1 / 2) * x) / x ^ s )⁻¹, { ext1 x, field_simp [exp_ne_zero, exp_neg, ← real.exp_add], left, ring }, rw this, exact (tendsto_exp_mul_div_rpow_at_top s (1 / 2) one_half_pos).inv_tendsto_at_top, end /-- Euler's integral for the `Γ` function (of a real variable `s`), defined as `∫ x in Ioi 0, exp (-x) * x ^ (s - 1)`. See `Gamma_integral_convergent` for a proof of the convergence of the integral for `0 < s`. -/ def Gamma_integral (s : ℝ) : ℝ := ∫ x in Ioi (0:ℝ), exp (-x) * x ^ (s - 1) /-- The integral defining the `Γ` function converges for positive real `s`. -/ lemma Gamma_integral_convergent {s : ℝ} (h : 0 < s) : integrable_on (λ x:ℝ, exp (-x) * x ^ (s - 1)) (Ioi 0) := begin rw [←Ioc_union_Ioi_eq_Ioi (@zero_le_one ℝ _ _ _ _), integrable_on_union], split, { rw ←integrable_on_Icc_iff_integrable_on_Ioc, refine integrable_on.continuous_on_mul continuous_on_id.neg.exp _ is_compact_Icc, refine (interval_integrable_iff_integrable_Icc_of_le zero_le_one).mp _, exact interval_integrable_rpow' (by linarith), }, { refine integrable_of_is_O_exp_neg one_half_pos _ (Gamma_integrand_is_o _ ).is_O, refine continuous_on_id.neg.exp.mul (continuous_on_id.rpow_const _), intros x hx, exact or.inl ((zero_lt_one : (0 : ℝ) < 1).trans_le hx).ne' } end lemma Gamma_integral_one : Gamma_integral 1 = 1 := by simpa only [Gamma_integral, sub_self, rpow_zero, mul_one] using integral_exp_neg_Ioi end real namespace complex /- Technical note: In defining the Gamma integrand exp (-x) * x ^ (s - 1) for s complex, we have to make a choice between ↑(real.exp (-x)), complex.exp (↑(-x)), and complex.exp (-↑x), all of which are equal but not definitionally so. We use the first of these throughout. -/ /-- The integral defining the `Γ` function converges for complex `s` with `0 < re s`. This is proved by reduction to the real case. -/ lemma Gamma_integral_convergent {s : ℂ} (hs : 0 < s.re) : integrable_on (λ x, (-x).exp * x ^ (s - 1) : ℝ → ℂ) (Ioi 0) := begin split, { refine continuous_on.ae_strongly_measurable _ measurable_set_Ioi, apply (continuous_of_real.comp continuous_neg.exp).continuous_on.mul, apply continuous_at.continuous_on, intros x hx, have : continuous_at (λ x:ℂ, x ^ (s - 1)) ↑x, { apply continuous_at_cpow_const, rw of_real_re, exact or.inl hx, }, exact continuous_at.comp this continuous_of_real.continuous_at }, { rw ←has_finite_integral_norm_iff, refine has_finite_integral.congr (real.Gamma_integral_convergent hs).2 _, refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ x hx, _)), dsimp only, rw [norm_eq_abs, map_mul, abs_of_nonneg $ le_of_lt $ exp_pos $ -x, abs_cpow_eq_rpow_re_of_pos hx _], simp } end /-- Euler's integral for the `Γ` function (of a complex variable `s`), defined as `∫ x in Ioi 0, exp (-x) * x ^ (s - 1)`. See `complex.Gamma_integral_convergent` for a proof of the convergence of the integral for `0 < re s`. -/ def Gamma_integral (s : ℂ) : ℂ := ∫ x in Ioi (0:ℝ), ↑(-x).exp * ↑x ^ (s - 1) lemma Gamma_integral_of_real (s : ℝ) : Gamma_integral ↑s = ↑(s.Gamma_integral) := begin rw [real.Gamma_integral, ←integral_of_real], refine set_integral_congr measurable_set_Ioi _, intros x hx, dsimp only, rw [of_real_mul, of_real_cpow (mem_Ioi.mp hx).le], simp, end lemma Gamma_integral_one : Gamma_integral 1 = 1 := begin rw [←of_real_one, Gamma_integral_of_real, of_real_inj], exact real.Gamma_integral_one, end end complex /-! Now we establish the recurrence relation `Γ(s + 1) = s * Γ(s)` using integration by parts. -/ namespace complex section Gamma_recurrence /-- The indefinite version of the `Γ` function, `Γ(s, X) = ∫ x ∈ 0..X, exp(-x) x ^ (s - 1)`. -/ def partial_Gamma (s : ℂ) (X : ℝ) : ℂ := ∫ x in 0..X, (-x).exp * x ^ (s - 1) lemma tendsto_partial_Gamma {s : ℂ} (hs: 0 < s.re) : tendsto (λ X:ℝ, partial_Gamma s X) at_top (𝓝 $ Gamma_integral s) := interval_integral_tendsto_integral_Ioi 0 (Gamma_integral_convergent hs) tendsto_id private lemma Gamma_integrand_interval_integrable (s : ℂ) {X : ℝ} (hs : 0 < s.re) (hX : 0 ≤ X): interval_integrable (λ x, (-x).exp * x ^ (s - 1) : ℝ → ℂ) volume 0 X := begin rw interval_integrable_iff_integrable_Ioc_of_le hX, exact integrable_on.mono_set (Gamma_integral_convergent hs) Ioc_subset_Ioi_self end private lemma Gamma_integrand_deriv_integrable_A {s : ℂ} (hs : 0 < s.re) {X : ℝ} (hX : 0 ≤ X): interval_integrable (λ x, -((-x).exp * x ^ s) : ℝ → ℂ) volume 0 X := begin convert (Gamma_integrand_interval_integrable (s+1) _ hX).neg, { ext1, simp only [add_sub_cancel, pi.neg_apply] }, { simp only [add_re, one_re], linarith,}, end private lemma Gamma_integrand_deriv_integrable_B {s : ℂ} (hs : 0 < s.re) {Y : ℝ} (hY : 0 ≤ Y) : interval_integrable (λ (x : ℝ), (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) volume 0 Y := begin have : (λ x, (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) = (λ x, s * ((-x).exp * x ^ (s - 1)) : ℝ → ℂ), { ext1, ring, }, rw [this, interval_integrable_iff_integrable_Ioc_of_le hY], split, { refine (continuous_on_const.mul _).ae_strongly_measurable measurable_set_Ioc, apply (continuous_of_real.comp continuous_neg.exp).continuous_on.mul, apply continuous_at.continuous_on, intros x hx, refine (_ : continuous_at (λ x:ℂ, x ^ (s - 1)) _).comp continuous_of_real.continuous_at, apply continuous_at_cpow_const, rw of_real_re, exact or.inl hx.1, }, rw ←has_finite_integral_norm_iff, simp_rw [norm_eq_abs, map_mul], refine (((real.Gamma_integral_convergent hs).mono_set Ioc_subset_Ioi_self).has_finite_integral.congr _).const_mul _, rw [eventually_eq, ae_restrict_iff'], { apply ae_of_all, intros x hx, rw [abs_of_nonneg (exp_pos _).le,abs_cpow_eq_rpow_re_of_pos hx.1], simp }, { exact measurable_set_Ioc}, end /-- The recurrence relation for the indefinite version of the `Γ` function. -/ lemma partial_Gamma_add_one {s : ℂ} (hs: 0 < s.re) {X : ℝ} (hX : 0 ≤ X) : partial_Gamma (s + 1) X = s * partial_Gamma s X - (-X).exp * X ^ s := begin rw [partial_Gamma, partial_Gamma, add_sub_cancel], have F_der_I: (∀ (x:ℝ), (x ∈ Ioo 0 X) → has_deriv_at (λ x, (-x).exp * x ^ s : ℝ → ℂ) ( -((-x).exp * x ^ s) + (-x).exp * (s * x ^ (s - 1))) x), { intros x hx, have d1 : has_deriv_at (λ (y: ℝ), (-y).exp) (-(-x).exp) x, { simpa using (has_deriv_at_neg x).exp }, have d1b : has_deriv_at (λ y, ↑(-y).exp : ℝ → ℂ) (↑-(-x).exp) x, { convert has_deriv_at.scomp x of_real_clm.has_deriv_at d1, simp, }, have d2: has_deriv_at (λ (y : ℝ), ↑y ^ s) (s * x ^ (s - 1)) x, { have t := @has_deriv_at.cpow_const _ _ _ s (has_deriv_at_id ↑x), simp only [id.def, of_real_re, of_real_im, ne.def, eq_self_iff_true, not_true, or_false, mul_one] at t, simpa using has_deriv_at.comp x (t hx.left) of_real_clm.has_deriv_at, }, simpa only [of_real_neg, neg_mul] using d1b.mul d2 }, have cont := (continuous_of_real.comp continuous_neg.exp).mul (continuous_of_real_cpow_const hs), have der_ible := (Gamma_integrand_deriv_integrable_A hs hX).add (Gamma_integrand_deriv_integrable_B hs hX), have int_eval := integral_eq_sub_of_has_deriv_at_of_le hX cont.continuous_on F_der_I der_ible, -- We are basically done here but manipulating the output into the right form is fiddly. apply_fun (λ x:ℂ, -x) at int_eval, rw [interval_integral.integral_add (Gamma_integrand_deriv_integrable_A hs hX) (Gamma_integrand_deriv_integrable_B hs hX), interval_integral.integral_neg, neg_add, neg_neg] at int_eval, replace int_eval := eq_sub_of_add_eq int_eval, rw [int_eval, sub_neg_eq_add, neg_sub, add_comm, add_sub], simp only [sub_left_inj, add_left_inj], have : (λ x, (-x).exp * (s * x ^ (s - 1)) : ℝ → ℂ) = (λ x, s * (-x).exp * x ^ (s - 1) : ℝ → ℂ), { ext1, ring,}, rw this, have t := @integral_const_mul (0:ℝ) X volume _ _ s (λ x:ℝ, (-x).exp * x ^ (s - 1)), dsimp at t, rw [←t, of_real_zero, zero_cpow], { rw [mul_zero, add_zero], congr', ext1, ring }, { contrapose! hs, rw [hs, zero_re] } end /-- The recurrence relation for the `Γ` integral. -/ theorem Gamma_integral_add_one {s : ℂ} (hs: 0 < s.re) : Gamma_integral (s + 1) = s * Gamma_integral s := begin suffices : tendsto (s+1).partial_Gamma at_top (𝓝 $ s * Gamma_integral s), { refine tendsto_nhds_unique _ this, apply tendsto_partial_Gamma, rw [add_re, one_re], linarith, }, have : (λ X:ℝ, s * partial_Gamma s X - X ^ s * (-X).exp) =ᶠ[at_top] (s+1).partial_Gamma, { apply eventually_eq_of_mem (Ici_mem_at_top (0:ℝ)), intros X hX, rw partial_Gamma_add_one hs (mem_Ici.mp hX), ring_nf, }, refine tendsto.congr' this _, suffices : tendsto (λ X, -X ^ s * (-X).exp : ℝ → ℂ) at_top (𝓝 0), { simpa using tendsto.add (tendsto.const_mul s (tendsto_partial_Gamma hs)) this }, rw tendsto_zero_iff_norm_tendsto_zero, have : (λ (e : ℝ), ‖-(e:ℂ) ^ s * (-e).exp‖ ) =ᶠ[at_top] (λ (e : ℝ), e ^ s.re * (-1 * e).exp ), { refine eventually_eq_of_mem (Ioi_mem_at_top 0) _, intros x hx, dsimp only, rw [norm_eq_abs, map_mul, abs.map_neg, abs_cpow_eq_rpow_re_of_pos hx, abs_of_nonneg (exp_pos(-x)).le, neg_mul, one_mul],}, exact (tendsto_congr' this).mpr (tendsto_rpow_mul_exp_neg_mul_at_top_nhds_0 _ _ zero_lt_one), end end Gamma_recurrence /-! Now we define `Γ(s)` on the whole complex plane, by recursion. -/ section Gamma_def /-- The `n`th function in this family is `Γ(s)` if `-n < s.re`, and junk otherwise. -/ noncomputable def Gamma_aux : ℕ → (ℂ → ℂ) | 0 := Gamma_integral | (n+1) := λ s:ℂ, (Gamma_aux n (s+1)) / s lemma Gamma_aux_recurrence1 (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) : Gamma_aux n s = Gamma_aux n (s+1) / s := begin induction n with n hn generalizing s, { simp only [nat.cast_zero, neg_lt_zero] at h1, dsimp only [Gamma_aux], rw Gamma_integral_add_one h1, rw [mul_comm, mul_div_cancel], contrapose! h1, rw h1, simp }, { dsimp only [Gamma_aux], have hh1 : -(s+1).re < n, { rw [nat.succ_eq_add_one, nat.cast_add, nat.cast_one] at h1, rw [add_re, one_re], linarith, }, rw ←(hn (s+1) hh1) } end lemma Gamma_aux_recurrence2 (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) : Gamma_aux n s = Gamma_aux (n+1) s := begin cases n, { simp only [nat.cast_zero, neg_lt_zero] at h1, dsimp only [Gamma_aux], rw [Gamma_integral_add_one h1, mul_div_cancel_left], rintro rfl, rw [zero_re] at h1, exact h1.false }, { dsimp only [Gamma_aux], have : (Gamma_aux n (s + 1 + 1)) / (s+1) = Gamma_aux n (s + 1), { have hh1 : -(s+1).re < n, { rw [nat.succ_eq_add_one, nat.cast_add, nat.cast_one] at h1, rw [add_re, one_re], linarith, }, rw Gamma_aux_recurrence1 (s+1) n hh1, }, rw this }, end /-- The `Γ` function (of a complex variable `s`). -/ @[pp_nodot] def Gamma (s : ℂ) : ℂ := Gamma_aux ⌊1 - s.re⌋₊ s lemma Gamma_eq_Gamma_aux (s : ℂ) (n : ℕ) (h1 : -s.re < ↑n) : Gamma s = Gamma_aux n s := begin have u : ∀ (k : ℕ), Gamma_aux (⌊1 - s.re⌋₊ + k) s = Gamma s, { intro k, induction k with k hk, { simp [Gamma],}, { rw [←hk, nat.succ_eq_add_one, ←add_assoc], refine (Gamma_aux_recurrence2 s (⌊1 - s.re⌋₊ + k) _).symm, rw nat.cast_add, have i0 := nat.sub_one_lt_floor (1 - s.re), simp only [sub_sub_cancel_left] at i0, refine lt_add_of_lt_of_nonneg i0 _, rw [←nat.cast_zero, nat.cast_le], exact nat.zero_le k, } }, convert (u $ n - ⌊1 - s.re⌋₊).symm, rw nat.add_sub_of_le, by_cases (0 ≤ 1 - s.re), { apply nat.le_of_lt_succ, exact_mod_cast lt_of_le_of_lt (nat.floor_le h) (by linarith : 1 - s.re < n + 1) }, { rw nat.floor_of_nonpos, linarith, linarith }, end /-- The recurrence relation for the `Γ` function. -/ theorem Gamma_add_one (s : ℂ) (h2 : s ≠ 0) : Gamma (s+1) = s * Gamma s := begin let n := ⌊1 - s.re⌋₊, have t1 : -s.re < n, { simpa only [sub_sub_cancel_left] using nat.sub_one_lt_floor (1 - s.re) }, have t2 : -(s+1).re < n, { rw [add_re, one_re], linarith, }, rw [Gamma_eq_Gamma_aux s n t1, Gamma_eq_Gamma_aux (s+1) n t2, Gamma_aux_recurrence1 s n t1], field_simp, ring, end theorem Gamma_eq_integral (s : ℂ) (hs : 0 < s.re) : Gamma s = Gamma_integral s := Gamma_eq_Gamma_aux s 0 (by { norm_cast, linarith }) theorem Gamma_nat_eq_factorial (n : ℕ) : Gamma (n+1) = nat.factorial n := begin induction n with n hn, { rw [nat.cast_zero, zero_add], rw Gamma_eq_integral, simpa using Gamma_integral_one, simp,}, rw (Gamma_add_one n.succ $ nat.cast_ne_zero.mpr $ nat.succ_ne_zero n), { simp only [nat.cast_succ, nat.factorial_succ, nat.cast_mul], congr, exact hn }, end end Gamma_def end complex /-! Now check that the `Γ` function is differentiable, wherever this makes sense. -/ section Gamma_has_deriv /-- Integrand for the derivative of the `Γ` function -/ def dGamma_integrand (s : ℂ) (x : ℝ) : ℂ := exp (-x) * log x * x ^ (s - 1) /-- Integrand for the absolute value of the derivative of the `Γ` function -/ def dGamma_integrand_real (s x : ℝ) : ℝ := |exp (-x) * log x * x ^ (s - 1)| lemma dGamma_integrand_is_o_at_top (s : ℝ) : (λ x : ℝ, exp (-x) * log x * x ^ (s - 1)) =o[at_top] (λ x, exp (-(1/2) * x)) := begin refine is_o_of_tendsto (λ x hx, _) _, { exfalso, exact (-(1/2) * x).exp_pos.ne' hx, }, have : eventually_eq at_top (λ (x : ℝ), exp (-x) * log x * x ^ (s - 1) / exp (-(1 / 2) * x)) (λ (x : ℝ), (λ z:ℝ, exp (1 / 2 * z) / z ^ s) x * (λ z:ℝ, z / log z) x)⁻¹, { refine eventually_of_mem (Ioi_mem_at_top 1) _, intros x hx, dsimp, replace hx := lt_trans zero_lt_one (mem_Ioi.mp hx), rw [real.exp_neg, neg_mul, real.exp_neg, rpow_sub hx], have : exp x = exp(x/2) * exp(x/2), { rw [←real.exp_add, add_halves], }, rw this, field_simp [hx.ne', exp_ne_zero (x/2)], ring, }, refine tendsto.congr' this.symm (tendsto.inv_tendsto_at_top _), apply tendsto.at_top_mul_at_top (tendsto_exp_mul_div_rpow_at_top s (1/2) one_half_pos), refine tendsto.congr' _ ((tendsto_exp_div_pow_at_top 1).comp tendsto_log_at_top), apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)), intros x hx, simp [exp_log hx], end /-- Absolute convergence of the integral which will give the derivative of the `Γ` function on `1 < re s`. -/ lemma dGamma_integral_abs_convergent (s : ℝ) (hs : 1 < s) : integrable_on (λ x:ℝ, ‖exp (-x) * log x * x ^ (s-1)‖) (Ioi 0) := begin rw [←Ioc_union_Ioi_eq_Ioi (@zero_le_one ℝ _ _ _ _), integrable_on_union], refine ⟨⟨_, _⟩, _⟩, { refine continuous_on.ae_strongly_measurable (continuous_on.mul _ _).norm measurable_set_Ioc, { refine (continuous_exp.comp continuous_neg).continuous_on.mul (continuous_on_log.mono _), simp, }, { apply continuous_on_id.rpow_const, intros x hx, right, linarith }, }, { apply has_finite_integral_of_bounded, swap, { exact 1 / (s - 1), }, refine (ae_restrict_iff' measurable_set_Ioc).mpr (ae_of_all _ (λ x hx, _)), rw [norm_norm, norm_eq_abs, mul_assoc, abs_mul, ←one_mul (1 / (s - 1))], refine mul_le_mul _ _ (abs_nonneg _) zero_le_one, { rw [abs_of_pos (exp_pos(-x)), exp_le_one_iff, neg_le, neg_zero], exact hx.1.le }, { exact (abs_log_mul_self_rpow_lt x (s-1) hx.1 hx.2 (sub_pos.mpr hs)).le }, }, { have := (dGamma_integrand_is_o_at_top s).is_O.norm_left, refine integrable_of_is_O_exp_neg one_half_pos (continuous_on.mul _ _).norm this, { refine (continuous_exp.comp continuous_neg).continuous_on.mul (continuous_on_log.mono _), simp, }, { apply continuous_at.continuous_on (λ x hx, _), apply continuous_at_id.rpow continuous_at_const, dsimp, right, linarith, }, } end /-- A uniform bound for the `s`-derivative of the `Γ` integrand for `s` in vertical strips. -/ lemma loc_unif_bound_dGamma_integrand {t : ℂ} {s1 s2 x : ℝ} (ht1 : s1 ≤ t.re) (ht2: t.re ≤ s2) (hx : 0 < x) : ‖dGamma_integrand t x‖ ≤ dGamma_integrand_real s1 x + dGamma_integrand_real s2 x := begin rcases le_or_lt 1 x with h|h, { -- case 1 ≤ x refine le_add_of_nonneg_of_le (abs_nonneg _) _, rw [dGamma_integrand, dGamma_integrand_real, complex.norm_eq_abs, map_mul, abs_mul, ←complex.of_real_mul, complex.abs_of_real], refine mul_le_mul_of_nonneg_left _ (abs_nonneg _), rw complex.abs_cpow_eq_rpow_re_of_pos hx, refine le_trans _ (le_abs_self _), apply rpow_le_rpow_of_exponent_le h, rw [complex.sub_re, complex.one_re], linarith, }, { refine le_add_of_le_of_nonneg _ (abs_nonneg _), rw [dGamma_integrand, dGamma_integrand_real, complex.norm_eq_abs, map_mul, abs_mul, ←complex.of_real_mul, complex.abs_of_real], refine mul_le_mul_of_nonneg_left _ (abs_nonneg _), rw complex.abs_cpow_eq_rpow_re_of_pos hx, refine le_trans _ (le_abs_self _), apply rpow_le_rpow_of_exponent_ge hx h.le, rw [complex.sub_re, complex.one_re], linarith, }, end namespace complex /-- The derivative of the `Γ` integral, at any `s ∈ ℂ` with `1 < re s`, is given by the integral of `exp (-x) * log x * x ^ (s - 1)` over `[0, ∞)`. -/ theorem has_deriv_at_Gamma_integral {s : ℂ} (hs : 1 < s.re) : (integrable_on (λ x, real.exp (-x) * real.log x * x ^ (s - 1) : ℝ → ℂ) (Ioi 0) volume) ∧ (has_deriv_at Gamma_integral (∫ x:ℝ in Ioi 0, real.exp (-x) * real.log x * x ^ (s - 1)) s) := begin let ε := (s.re - 1) / 2, let μ := volume.restrict (Ioi (0:ℝ)), let bound := (λ x:ℝ, dGamma_integrand_real (s.re - ε) x + dGamma_integrand_real (s.re + ε) x), have cont : ∀ (t : ℂ), continuous_on (λ x, real.exp (-x) * x ^ (t - 1) : ℝ → ℂ) (Ioi 0), { intro t, apply (continuous_of_real.comp continuous_neg.exp).continuous_on.mul, apply continuous_at.continuous_on, intros x hx, refine (continuous_at_cpow_const _).comp continuous_of_real.continuous_at, exact or.inl hx, }, have eps_pos: 0 < ε := div_pos (sub_pos.mpr hs) zero_lt_two, have hF_meas : ∀ᶠ (t : ℂ) in 𝓝 s, ae_strongly_measurable (λ x, real.exp(-x) * x ^ (t - 1) : ℝ → ℂ) μ, { apply eventually_of_forall, intro t, exact (cont t).ae_strongly_measurable measurable_set_Ioi, }, have hF'_meas : ae_strongly_measurable (dGamma_integrand s) μ, { refine continuous_on.ae_strongly_measurable _ measurable_set_Ioi, have : dGamma_integrand s = (λ x, real.exp (-x) * x ^ (s - 1) * real.log x : ℝ → ℂ), { ext1, simp only [dGamma_integrand], ring }, rw this, refine continuous_on.mul (cont s) (continuous_at.continuous_on _), exact λ x hx, continuous_of_real.continuous_at.comp (continuous_at_log (mem_Ioi.mp hx).ne'), }, have h_bound : ∀ᵐ (x : ℝ) ∂μ, ∀ (t : ℂ), t ∈ metric.ball s ε → ‖ dGamma_integrand t x ‖ ≤ bound x, { refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ x hx, _)), intros t ht, rw [metric.mem_ball, complex.dist_eq] at ht, replace ht := lt_of_le_of_lt (complex.abs_re_le_abs $ t - s ) ht, rw [complex.sub_re, @abs_sub_lt_iff ℝ _ t.re s.re ((s.re - 1) / 2) ] at ht, refine loc_unif_bound_dGamma_integrand _ _ hx, all_goals { simp only [ε], linarith } }, have bound_integrable : integrable bound μ, { apply integrable.add, { refine dGamma_integral_abs_convergent (s.re - ε) _, field_simp, rw one_lt_div, { linarith }, { exact zero_lt_two }, }, { refine dGamma_integral_abs_convergent (s.re + ε) _, linarith, }, }, have h_diff : ∀ᵐ (x : ℝ) ∂μ, ∀ (t : ℂ), t ∈ metric.ball s ε → has_deriv_at (λ u, real.exp (-x) * x ^ (u - 1) : ℂ → ℂ) (dGamma_integrand t x) t, { refine (ae_restrict_iff' measurable_set_Ioi).mpr (ae_of_all _ (λ x hx, _)), intros t ht, rw mem_Ioi at hx, simp only [dGamma_integrand], rw mul_assoc, apply has_deriv_at.const_mul, rw [of_real_log hx.le, mul_comm], have := ((has_deriv_at_id t).sub_const 1).const_cpow (or.inl (of_real_ne_zero.mpr hx.ne')), rwa mul_one at this }, exact (has_deriv_at_integral_of_dominated_loc_of_deriv_le eps_pos hF_meas (Gamma_integral_convergent (zero_lt_one.trans hs)) hF'_meas h_bound bound_integrable h_diff), end lemma differentiable_at_Gamma_aux (s : ℂ) (n : ℕ) (h1 : (1 - s.re) < n ) (h2 : ∀ m:ℕ, s + m ≠ 0) : differentiable_at ℂ (Gamma_aux n) s := begin induction n with n hn generalizing s, { refine (has_deriv_at_Gamma_integral _).2.differentiable_at, rw nat.cast_zero at h1, linarith }, { dsimp only [Gamma_aux], specialize hn (s + 1), have a : 1 - (s + 1).re < ↑n, { rw nat.cast_succ at h1, rw [complex.add_re, complex.one_re], linarith }, have b : ∀ m:ℕ, s + 1 + m ≠ 0, { intro m, have := h2 (1 + m), rwa [nat.cast_add, nat.cast_one, ←add_assoc] at this }, refine differentiable_at.div (differentiable_at.comp _ (hn a b) _) _ _, simp, simp, simpa using h2 0 } end theorem differentiable_at_Gamma (s : ℂ) (hs : ∀ m:ℕ, s + m ≠ 0) : differentiable_at ℂ Gamma s := begin let n := ⌊1 - s.re⌋₊ + 1, have hn : 1 - s.re < n := by exact_mod_cast nat.lt_floor_add_one (1 - s.re), apply (differentiable_at_Gamma_aux s n hn hs).congr_of_eventually_eq, let S := { t : ℂ | 1 - t.re < n }, have : S ∈ 𝓝 s, { rw mem_nhds_iff, use S, refine ⟨subset.rfl, _, hn⟩, have : S = re⁻¹' Ioi (1 - n : ℝ), { ext, rw [preimage,Ioi, mem_set_of_eq, mem_set_of_eq, mem_set_of_eq], exact sub_lt_comm }, rw this, refine continuous.is_open_preimage continuous_re _ is_open_Ioi, }, apply eventually_eq_of_mem this, intros t ht, rw mem_set_of_eq at ht, apply Gamma_eq_Gamma_aux, linarith, end end complex end Gamma_has_deriv
f578439f0e326ad9d56cdaaade97ec238d88e864
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/multiset/lattice.lean
1ed7e108374c89337d38bf800aec73d7efed633f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,153
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.finset_ops import data.multiset.fold /-! # Lattice operations on multisets -/ namespace multiset variables {α : Type*} /-! ### sup -/ section sup -- can be defined with just `[has_bot α]` where some lemmas hold without requiring `[order_bot α]` variables [semilattice_sup α] [order_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_coe (l : list α) : sup (l : multiset α) = l.foldr (⊔) ⊥ := rfl @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a ::ₘ s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : ({a} : multiset α).sup = a := sup_bot_eq @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 le_rfl _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) variables [decidable_eq α] @[simp] lemma sup_dedup (s : multiset α) : (dedup s).sup = s.sup := fold_dedup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_dedup, dedup_ext.2, sup_dedup, sup_cons]; simp lemma nodup_sup_iff {α : Type*} [decidable_eq α] {m : multiset (multiset α) } : m.sup.nodup ↔ ∀ (a : multiset α), a ∈ m → a.nodup := begin apply m.induction_on, { simp }, { intros a s h, simp [h] } end end sup /-! ### inf -/ section inf -- can be defined with just `[has_top α]` where some lemmas hold without requiring `[order_top α]` variables [semilattice_inf α] [order_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_coe (l : list α) : inf (l : multiset α) = l.foldr (⊓) ⊤ := rfl @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a ::ₘ s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : ({a} : multiset α).inf = a := inf_top_eq @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 le_rfl _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) variables [decidable_eq α] @[simp] lemma inf_dedup (s : multiset α) : (dedup s).inf = s.inf := fold_dedup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_dedup, dedup_ext.2, inf_dedup, inf_cons]; simp end inf end multiset
c0d0b6c1d242f58fbccf828343f92862e33cc966
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0401.lean
b63843db055ad39a42f0639b6bb2884366243c8b
[]
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
301
lean
open nat example : ∃ x : ℕ, x > 0 := have h : 1 > 0, from zero_lt_succ 0, exists.intro 1 h example (x : ℕ) (h : x > 0) : ∃ y, y < x := exists.intro 0 h example (x y z : ℕ) (hxy : x < y) (hyz : y < z) : ∃ w, x < w ∧ w < z := exists.intro y (and.intro hxy hyz) #check @exists.intro
67e034a0492e754185fdbf73db1fd1290ccb4f25
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/hott/arity.hlean
58ed580f158072d2e041466495d74a7d9e650c83
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,314
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.path Author: Floris van Doorn Theorems about functions with multiple arguments -/ variables {A U V W X Y Z : Type} {B : A → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {E : Πa b c, D a b c → Type} variables {a a' : A} {u u' : U} {v v' : V} {w w' : W} {x x' x'' : X} {y y' : Y} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} {d : D a b c} {d' : D a' b' c'} namespace eq /- Naming convention: The theorem which states how to construct an path between two function applications is api₀i₁...iₙ. Here i₀, ... iₙ are digits, n is the arity of the function(s), and iⱼ specifies the dimension of the path between the jᵗʰ argument (i₀ specifies the dimension of the path between the functions). A value iⱼ ≡ 0 means that the jᵗʰ arguments are definitionally equal The functions are non-dependent, except when the theorem name contains trailing zeroes (where the function is dependent only in the arguments where it doesn't result in any transports in the theorem statement). For the fully-dependent versions (except that the conclusion doesn't contain a transport) we write apDi₀i₁...iₙ. For versions where only some arguments depend on some other arguments, or for versions with transport in the conclusion (like apD), we don't have a consistent naming scheme (yet). We don't prove each theorem systematically, but prove only the ones which we actually need. -/ definition homotopy2 [reducible] (f g : Πa b, C a b) : Type := Πa b, f a b = g a b definition homotopy3 [reducible] (f g : Πa b c, D a b c) : Type := Πa b c, f a b c = g a b c definition homotopy4 [reducible] (f g : Πa b c d, E a b c d) : Type := Πa b c d, f a b c d = g a b c d notation f `∼2`:50 g := homotopy2 f g notation f `∼3`:50 g := homotopy3 f g definition ap011 (f : U → V → W) (Hu : u = u') (Hv : v = v') : f u v = f u' v' := eq.rec_on Hu (ap (f u) Hv) definition ap0111 (f : U → V → W → X) (Hu : u = u') (Hv : v = v') (Hw : w = w') : f u v w = f u' v' w' := eq.rec_on Hu (ap011 (f u) Hv Hw) definition ap01111 (f : U → V → W → X → Y) (Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') : f u v w x = f u' v' w' x' := eq.rec_on Hu (ap0111 (f u) Hv Hw Hx) definition ap010 (f : X → Πa, B a) (Hx : x = x') : f x ∼ f x' := λa, eq.rec_on Hx idp definition ap0100 (f : X → Πa b, C a b) (Hx : x = x') : f x ∼2 f x' := λa b, eq.rec_on Hx idp definition ap01000 (f : X → Πa b c, D a b c) (Hx : x = x') : f x ∼3 f x' := λa b c, eq.rec_on Hx idp definition apD011 (f : Πa, B a → Z) (Ha : a = a') (Hb : (Ha ▹ b) = b') : f a b = f a' b' := eq.rec_on Hb (eq.rec_on Ha idp) definition apD0111 (f : Πa b, C a b → Z) (Ha : a = a') (Hb : (Ha ▹ b) = b') (Hc : apD011 C Ha Hb ▹ c = c') : f a b c = f a' b' c' := eq.rec_on Hc (eq.rec_on Hb (eq.rec_on Ha idp)) definition apD01111 (f : Πa b c, D a b c → Z) (Ha : a = a') (Hb : (Ha ▹ b) = b') (Hc : apD011 C Ha Hb ▹ c = c') (Hd : apD0111 D Ha Hb Hc ▹ d = d') : f a b c d = f a' b' c' d' := eq.rec_on Hd (eq.rec_on Hc (eq.rec_on Hb (eq.rec_on Ha idp))) definition apD100 {f g : Πa b, C a b} (p : f = g) : f ∼2 g := λa b, apD10 (apD10 p a) b definition apD1000 {f g : Πa b c, D a b c} (p : f = g) : f ∼3 g := λa b c, apD100 (apD10 p a) b c /- some properties of these variants of ap -/ -- we only prove what is needed somewhere definition ap010_con (f : X → Πa, B a) (p : x = x') (q : x' = x'') : ap010 f (p ⬝ q) a = ap010 f p a ⬝ ap010 f q a := eq.rec_on q (eq.rec_on p idp) definition ap010_ap (f : X → Πa, B a) (g : Y → X) (p : y = y') : ap010 f (ap g p) a = ap010 (λy, f (g y)) p a := eq.rec_on p idp /- the following theorems are function extentionality for functions with multiple arguments -/ definition eq_of_homotopy2 {f g : Πa b, C a b} (H : f ∼2 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy (H a)) definition eq_of_homotopy3 {f g : Πa b c, D a b c} (H : f ∼3 g) : f = g := eq_of_homotopy (λa, eq_of_homotopy2 (H a)) definition eq_of_homotopy2_id (f : Πa b, C a b) : eq_of_homotopy2 (λa b, idpath (f a b)) = idpath f := begin apply concat, {apply (ap (λx, eq_of_homotopy x)), apply eq_of_homotopy, intro a, apply eq_of_homotopy_id}, apply eq_of_homotopy_id end definition eq_of_homotopy3_id (f : Πa b c, D a b c) : eq_of_homotopy3 (λa b c, idpath (f a b c)) = idpath f := begin apply concat, {apply (ap (λx, eq_of_homotopy x)), apply eq_of_homotopy, intro a, apply eq_of_homotopy2_id}, apply eq_of_homotopy_id end end eq open eq is_equiv namespace funext definition is_equiv_apD100 [instance] (f g : Πa b, C a b) : is_equiv (@apD100 A B C f g) := adjointify _ eq_of_homotopy2 begin intro H, esimp {apD100,eq_of_homotopy2, function.compose}, apply eq_of_homotopy, intro a, apply concat, apply (ap (λx, @apD10 _ (λb : B a, _) _ _ (x a))), apply (retr apD10), --TODO: remove implicit argument after #469 is closed apply (retr apD10) end begin intro p, cases p, apply eq_of_homotopy2_id end definition is_equiv_apD1000 [instance] (f g : Πa b c, D a b c) : is_equiv (@apD1000 A B C D f g) := adjointify _ eq_of_homotopy3 begin intro H, apply eq_of_homotopy, intro a, apply concat, {apply (ap (λx, @apD100 _ _ (λ(b : B a)(c : C a b), _) _ _ (x a))), apply (retr apD10)}, --TODO: remove implicit argument after #469 is closed apply (@retr _ _ apD100 !is_equiv_apD100) --is explicit argument needed here? end begin intro p, cases p, apply eq_of_homotopy3_id end end funext namespace eq open funext local attribute funext.is_equiv_apD100 [instance] protected definition homotopy2.rec_on {f g : Πa b, C a b} {P : (f ∼2 g) → Type} (p : f ∼2 g) (H : Π(q : f = g), P (apD100 q)) : P p := retr apD100 p ▹ H (eq_of_homotopy2 p) protected definition homotopy3.rec_on {f g : Πa b c, D a b c} {P : (f ∼3 g) → Type} (p : f ∼3 g) (H : Π(q : f = g), P (apD1000 q)) : P p := retr apD1000 p ▹ H (eq_of_homotopy3 p) definition apD10_ap (f : X → Πa, B a) (p : x = x') : apD10 (ap f p) = ap010 f p := eq.rec_on p idp definition eq_of_homotopy_ap010 (f : X → Πa, B a) (p : x = x') : eq_of_homotopy (ap010 f p) = ap f p := inv_eq_of_eq !apD10_ap⁻¹ definition ap_eq_ap_of_homotopy {f : X → Πa, B a} {p q : x = x'} (H : ap010 f p ∼ ap010 f q) : ap f p = ap f q := calc ap f p = eq_of_homotopy (ap010 f p) : eq_of_homotopy_ap010 ... = eq_of_homotopy (ap010 f q) : eq_of_homotopy H ... = ap f q : eq_of_homotopy_ap010 end eq
b17780cbd66a3242065b40d91b93c6aa305b447d
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0502/S0502.lean
d7a0d0603bb3dbf4973ba091da5262645975deb0
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
944
lean
import algebra.group_power tactic.norm_num algebra.big_operators theorem Q2 (n : ℕ) : n ≥ 2 → nat.pow 4 n > nat.pow 3 n + nat.pow 2 n := begin intro H_n_ge_2, cases n with n1, exfalso,revert H_n_ge_2, exact dec_trivial, cases n1 with n2, exfalso,revert H_n_ge_2, exact dec_trivial, clear H_n_ge_2, induction n2 with d Hd, exact dec_trivial, let e := nat.succ (nat.succ d), show nat.pow 4 e*4>nat.pow 3 e*3+nat.pow 2 e*2, change nat.pow 4 (nat.succ (nat.succ d)) > nat.pow 3 (nat.succ (nat.succ d)) + nat.pow 2 (nat.succ (nat.succ d)) with nat.pow 4 e>nat.pow 3 e+nat.pow 2 e at Hd, exact calc nat.pow 4 e * 4 > (nat.pow 3 e + nat.pow 2 e) * 4 : mul_lt_mul_of_pos_right Hd (dec_trivial) ... = nat.pow 3 e*4+nat.pow 2 e*4 : add_mul _ _ _ ... ≥ nat.pow 3 e*3+nat.pow 2 e*4 : add_le_add_right (nat.mul_le_mul_left _ (dec_trivial)) _ ... ≥ nat.pow 3 e*3+nat.pow 2 e*2 : add_le_add_left (nat.mul_le_mul_left _ (dec_trivial)) _, end
e55fdb7f3195c2f5353a6a451e33b7bf95448c55
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/algebra/module.lean
27934b72e413a0cd577aa5d531bdb3057141fe34
[ "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
41,779
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov -/ import topology.algebra.ring import topology.uniform_space.uniform_embedding import ring_theory.algebra import linear_algebra.projection /-! # Theory of topological modules and continuous linear maps. We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`, as extensions of the corresponding algebraic classes where the algebraic operations are continuous. We also define continuous linear maps, as linear maps between topological modules which are continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is denoted by `M →L[R] M₂`. Continuous linear equivalences are denoted by `M ≃L[R] M₂`. ## Implementation notes Topological vector spaces are defined as an `abbreviation` for topological modules, if the base ring is a field. This has as advantage that topological vector spaces are completely transparent for type class inference, which means that all instances for topological modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend topological vector spaces. The solution is to extend `topological_module` instead. -/ open filter open_locale topological_space big_operators universes u v w u' section prio set_option default_priority 100 -- see Note [default priority] /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, R will be a topological semiring and M a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (R : Type u) (M : Type v) [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] : Prop := (continuous_smul : continuous (λp : R × M, p.1 • p.2)) end prio section variables {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] lemma continuous_smul : continuous (λp:R×M, p.1 • p.2) := topological_semimodule.continuous_smul lemma continuous.smul {α : Type*} [topological_space α] {f : α → R} {g : α → M} (hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) := continuous_smul.comp (hf.prod_mk hg) lemma tendsto_smul {c : R} {x : M} : tendsto (λp:R×M, p.fst • p.snd) (𝓝 (c, x)) (𝓝 (c • x)) := continuous_smul.tendsto _ lemma filter.tendsto.smul {α : Type*} {l : filter α} {f : α → R} {g : α → M} {c : R} {x : M} (hf : tendsto f l (𝓝 c)) (hg : tendsto g l (𝓝 x)) : tendsto (λ a, f a • g a) l (𝓝 (c • x)) := tendsto_smul.comp (hf.prod_mk_nhds hg) end section prio set_option default_priority 100 -- see Note [default priority] /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a topological additive group, but this is not needed for the definition -/ class topological_module (R : Type u) (M : Type v) [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] extends topological_semimodule R M : Prop /-- A topological vector space is a topological module over a field. -/ abbreviation topological_vector_space (R : Type u) (M : Type v) [field R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] := topological_module R M end prio section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] /-- Scalar multiplication by a unit is a homeomorphism from a topological module onto itself. -/ protected def homeomorph.smul_of_unit (a : units R) : M ≃ₜ M := { to_fun := λ x, (a : R) • x, inv_fun := λ x, ((a⁻¹ : units R) : R) • x, right_inv := λ x, calc (a : R) • ((a⁻¹ : units R) : R) • x = x : by rw [smul_smul, units.mul_inv, one_smul], left_inv := λ x, calc ((a⁻¹ : units R) : R) • (a : R) • x = x : by rw [smul_smul, units.inv_mul, one_smul], continuous_to_fun := continuous_const.smul continuous_id, continuous_inv_fun := continuous_const.smul continuous_id } lemma is_open_map_smul_of_unit (a : units R) : is_open_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_open_map lemma is_closed_map_smul_of_unit (a : units R) : is_closed_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_closed_map /-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then `⊤` is the only submodule of `M` with a nonempty interior. This is the case, e.g., if `R` is a nondiscrete normed field. -/ lemma submodule.eq_top_of_nonempty_interior' [has_continuous_add M] [ne_bot (nhds_within (0:R) {x | is_unit x})] (s : submodule R M) (hs : (interior (s:set M)).nonempty) : s = ⊤ := begin rcases hs with ⟨y, hy⟩, refine (submodule.eq_top_iff'.2 $ λ x, _), rw [mem_interior_iff_mem_nhds] at hy, have : tendsto (λ c:R, y + c • x) (nhds_within 0 {x | is_unit x}) (𝓝 (y + (0:R) • x)), from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul tendsto_const_nhds), rw [zero_smul, add_zero] at this, rcases nonempty_of_mem_sets (inter_mem_sets (mem_map.1 (this hy)) self_mem_nhds_within) with ⟨_, hu, u, rfl⟩, have hy' : y ∈ ↑s := mem_of_nhds hy, exact (s.smul_mem_iff' _).1 ((s.add_mem_iff_right hy').1 hu) end end section variables {R : Type*} {M : Type*} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] /-- Scalar multiplication by a non-zero field element is a homeomorphism from a topological vector space onto itself. -/ protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : M ≃ₜ M := {.. homeomorph.smul_of_unit (units.mk0 a ha)} lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_open_map lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_closed_map end /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map (R : Type*) [semiring R] (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends linear_map R M M₂ := (cont : continuous to_fun . tactic.interactive.continuity') notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map R M M₂ /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ @[nolint has_inhabited_instance] structure continuous_linear_equiv (R : Type*) [semiring R] (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends linear_equiv R M M₂ := (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂ namespace continuous_linear_map section semiring /- Properties that hold for non-necessarily commutative semirings. -/ variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ /-- Coerce continuous linear maps to functions. -/ -- see Note [function coercion] instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨λ _, M → M₂, λ f, f⟩ @[simp] lemma coe_mk (f : M →ₗ[R] M₂) (h) : (mk f h : M →ₗ[R] M₂) = f := rfl @[simp] lemma coe_mk' (f : M →ₗ[R] M₂) (h) : (mk f h : M → M₂) = f := rfl @[continuity] protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2 theorem coe_injective : function.injective (coe : (M →L[R] M₂) → (M →ₗ[R] M₂)) := by { intros f g H, cases f, cases g, congr' 1, exact H } theorem coe_injective' ⦃f g : M →L[R] M₂⦄ (H : (f : M → M₂) = g) : f = g := coe_injective $ linear_map.coe_injective H @[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g := coe_injective' $ funext h theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : M) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _ @[simp, norm_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl /-- The continuous map that is constantly zero. -/ instance: has_zero (M →L[R] M₂) := ⟨⟨0, continuous_const⟩⟩ instance : inhabited (M →L[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] M₂) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[norm_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl section variables (R M) /-- the identity map as a continuous linear map. -/ def id : M →L[R] M := ⟨linear_map.id, continuous_id⟩ end instance : has_one (M →L[R] M) := ⟨id R M⟩ lemma id_apply : id R M x = x := rfl @[simp, norm_cast] lemma coe_id : (id R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma coe_id' : (id R M : M → M) = _root_.id := rfl @[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl section add variables [has_continuous_add M₂] instance : has_add (M →L[R] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, norm_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) + g := rfl @[norm_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl instance : add_comm_monoid (M →L[R] M₂) := by { refine {zero := 0, add := (+), ..}; intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm] } lemma sum_apply {ι : Type*} (t : finset ι) (f : ι → M →L[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := begin haveI : is_add_monoid_hom (λ (g : M →L[R] M₂), g b) := { map_add := λ f g, continuous_linear_map.add_apply f g b, map_zero := by simp }, exact (finset.sum_hom t (λ g : M →L[R] M₂, g b)).symm end end add /-- Composition of bounded linear maps. -/ def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ := ⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩ @[simp, norm_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl @[simp, norm_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl @[simp] theorem comp_id : f.comp (id R M) = f := ext $ λ x, rfl @[simp] theorem id_comp : (id R M₂).comp f = f := ext $ λ x, rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [has_continuous_add M₂] [has_continuous_add M₃] (g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [has_continuous_add M₃] (g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } theorem comp_assoc (h : M₃ →L[R] M₄) (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : (h.comp g).comp f = h.comp (g.comp f) := rfl instance : has_mul (M →L[R] M) := ⟨comp⟩ lemma mul_def (f g : M →L[R] M) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : M →L[R] M) : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (f g : M →L[R] M) (x : M) : (f * g) x = f (g x) := rfl /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ protected def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) := { cont := f₁.2.prod_mk f₂.2, ..f₁.to_linear_map.prod f₂.to_linear_map } @[simp, norm_cast] lemma coe_prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : (f₁.prod f₂ : M →ₗ[R] M₂ × M₃) = linear_map.prod f₁ f₂ := rfl @[simp, norm_cast] lemma prod_apply (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) (x : M) : f₁.prod f₂ x = (f₁ x, f₂ x) := rfl /-- Kernel of a continuous linear map. -/ def ker (f : M →L[R] M₂) : submodule R M := (f : M →ₗ[R] M₂).ker @[norm_cast] lemma ker_coe : (f : M →ₗ[R] M₂).ker = f.ker := rfl @[simp] lemma mem_ker {f : M →L[R] M₂} {x} : x ∈ f.ker ↔ f x = 0 := linear_map.mem_ker lemma is_closed_ker [t1_space M₂] : is_closed (f.ker : set M) := continuous_iff_is_closed.1 f.cont _ is_closed_singleton @[simp] lemma apply_ker (x : f.ker) : f x = 0 := mem_ker.1 x.2 lemma is_complete_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [semimodule R M'] [t1_space M₂] (f : M' →L[R] M₂) : is_complete (f.ker : set M') := f.is_closed_ker.is_complete instance complete_space_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [semimodule R M'] [t1_space M₂] (f : M' →L[R] M₂) : complete_space f.ker := f.is_closed_ker.complete_space_coe @[simp] lemma ker_prod (f : M →L[R] M₂) (g : M →L[R] M₃) : ker (f.prod g) = ker f ⊓ ker g := linear_map.ker_prod f g /-- Range of a continuous linear map. -/ def range (f : M →L[R] M₂) : submodule R M₂ := (f : M →ₗ[R] M₂).range lemma range_coe : (f.range : set M₂) = set.range f := linear_map.range_coe _ lemma mem_range {f : M →L[R] M₂} {y} : y ∈ f.range ↔ ∃ x, f x = y := linear_map.mem_range lemma range_prod_le (f : M →L[R] M₂) (g : M →L[R] M₃) : range (f.prod g) ≤ (range f).prod (range g) := (f : M →ₗ[R] M₂).range_prod_le g /-- Restrict codomain of a continuous linear map. -/ def cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : M →L[R] p := { cont := continuous_subtype_mk h f.continuous, to_linear_map := (f : M →ₗ[R] M₂).cod_restrict p h} @[norm_cast] lemma coe_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : (f.cod_restrict p h : M →ₗ[R] p) = (f : M →ₗ[R] M₂).cod_restrict p h := rfl @[simp] lemma coe_cod_restrict_apply (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) (x) : (f.cod_restrict p h x : M₂) = f x := rfl @[simp] lemma ker_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : ker (f.cod_restrict p h) = ker f := (f : M →ₗ[R] M₂).ker_cod_restrict p h /-- Embedding of a submodule into the ambient space as a continuous linear map. -/ def subtype_val (p : submodule R M) : p →L[R] M := { cont := continuous_subtype_val, to_linear_map := p.subtype } @[simp, norm_cast] lemma coe_subtype_val (p : submodule R M) : (subtype_val p : p →ₗ[R] M) = p.subtype := rfl @[simp, norm_cast] lemma subtype_val_apply (p : submodule R M) (x : p) : (subtype_val p : p → M) x = x := rfl variables (R M M₂) /-- `prod.fst` as a `continuous_linear_map`. -/ def fst : M × M₂ →L[R] M := { cont := continuous_fst, to_linear_map := linear_map.fst R M M₂ } /-- `prod.snd` as a `continuous_linear_map`. -/ def snd : M × M₂ →L[R] M₂ := { cont := continuous_snd, to_linear_map := linear_map.snd R M M₂ } variables {R M M₂} @[simp, norm_cast] lemma coe_fst : (fst R M M₂ : M × M₂ →ₗ[R] M) = linear_map.fst R M M₂ := rfl @[simp, norm_cast] lemma coe_fst' : (fst R M M₂ : M × M₂ → M) = prod.fst := rfl @[simp, norm_cast] lemma coe_snd : (snd R M M₂ : M × M₂ →ₗ[R] M₂) = linear_map.snd R M M₂ := rfl @[simp, norm_cast] lemma coe_snd' : (snd R M M₂ : M × M₂ → M₂) = prod.snd := rfl @[simp] lemma fst_prod_snd : (fst R M M₂).prod (snd R M M₂) = id R (M × M₂) := ext $ λ ⟨x, y⟩, rfl /-- `prod.map` of two continuous linear maps. -/ def prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : (M × M₃) →L[R] (M₂ × M₄) := (f₁.comp (fst R M M₃)).prod (f₂.comp (snd R M M₃)) @[simp, norm_cast] lemma coe_prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : (f₁.prod_map f₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = ((f₁ : M →ₗ[R] M₂).prod_map (f₂ : M₃ →ₗ[R] M₄)) := rfl @[simp, norm_cast] lemma coe_prod_map' (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : ⇑(f₁.prod_map f₂) = prod.map f₁ f₂ := rfl /-- The continuous linear map given by `(x, y) ↦ f₁ x + f₂ y`. -/ def coprod [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) : (M × M₂) →L[R] M₃ := ⟨linear_map.coprod f₁ f₂, (f₁.cont.comp continuous_fst).add (f₂.cont.comp continuous_snd)⟩ @[norm_cast, simp] lemma coe_coprod [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) : (f₁.coprod f₂ : (M × M₂) →ₗ[R] M₃) = linear_map.coprod f₁ f₂ := rfl @[simp] lemma coprod_apply [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) (x) : f₁.coprod f₂ x = f₁ x.1 + f₂ x.2 := rfl variables [topological_space R] [topological_semimodule R M₂] /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`) -/ def smul_right (c : M →L[R] R) (f : M₂) : M →L[R] M₂ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : M →L[R] R} {f : M₂} {x : M} : (smul_right c f : M → M₂) x = (c : M → R) x • f := rfl @[simp] lemma smul_right_one_one (c : R →L[R] M₂) : smul_right 1 ((c : R → M₂) 1) = c := by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R →L[R] R) f = smul_right 1 f' ↔ f = f' := ⟨λ h, have (smul_right (1 : R →L[R] R) f : R → M₂) 1 = (smul_right (1 : R →L[R] R) f' : R → M₂) 1, by rw h, by simp at this; assumption, by cc⟩ lemma smul_right_comp [topological_semimodule R R] {x : M₂} {c : R} : (smul_right 1 x : R →L[R] M₂).comp (smul_right 1 c : R →L[R] R) = smul_right 1 (c • x) := by { ext, simp [mul_smul] } end semiring section pi variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] [semimodule R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [semimodule R M₂] {ι : Type*} {φ : ι → Type*} [∀i, topological_space (φ i)] [∀i, add_comm_monoid (φ i)] [∀i, semimodule R (φ i)] /-- `pi` construction for continuous linear functions. From a family of continuous linear functions it produces a continuous linear function into a family of topological modules. -/ def pi (f : Πi, M →L[R] φ i) : M →L[R] (Πi, φ i) := ⟨linear_map.pi (λ i, (f i : M →ₗ[R] φ i)), continuous_pi (λ i, (f i).continuous)⟩ @[simp] lemma pi_apply (f : Πi, M →L[R] φ i) (c : M) (i : ι) : pi f c i = f i c := rfl lemma pi_eq_zero (f : Πi, M →L[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [ext_iff, pi_apply, function.funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M →L[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M →L[R] φ i) (g : M₂ →L[R] M) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of topological modules are continuous linear maps. -/ def proj (i : ι) : (Πi, φ i) →L[R] φ i := ⟨linear_map.proj i, continuous_apply _⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →L[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →L[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := linear_map.infi_ker_proj variables (R φ) /-- If `I` and `J` are complementary index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃L[R] (Πi:I, φ i) := ⟨ linear_map.infi_ker_proj_equiv R φ hd hu, continuous_pi (λ i, begin have := @continuous_subtype_coe _ _ (λ x, x ∈ (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i))), have := continuous.comp (by exact continuous_apply i) this, exact this end), continuous_subtype_mk _ (continuous_pi (λ i, begin dsimp, split_ifs; [apply continuous_apply, exact continuous_const] end)) ⟩ end pi section ring variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma sub_apply' (x : M) : ((f : M →ₗ[R] M₂) - g) x = f x - g x := rfl lemma range_prod_eq {f : M →L[R] M₂} {g : M →L[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (f.prod g) = (range f).prod (range g) := linear_map.range_prod_eq h section variables [topological_add_group M₂] instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, norm_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl @[norm_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl instance : add_comm_group (M →L[R] M₂) := by { refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm] } lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl @[simp, norm_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) - g := rfl @[simp, norm_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl end instance [topological_add_group M] : ring (M →L[R] M) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } lemma smul_right_one_pow [topological_space R] [topological_add_group R] [topological_semimodule R R] (c : R) (n : ℕ) : (smul_right 1 c : R →L[R] R)^n = smul_right 1 (c^n) := begin induction n with n ihn, { ext, simp }, { rw [pow_succ, ihn, mul_def, smul_right_comp, smul_eq_mul, pow_succ'] } end /-- Given a right inverse `f₂ : M₂ →L[R] M` to `f₁ : M →L[R] M₂`, `proj_ker_of_right_inverse f₁ f₂ h` is the projection `M →L[R] f₁.ker` along `f₂.range`. -/ def proj_ker_of_right_inverse [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M →L[R] f₁.ker := (id R M - f₂.comp f₁).cod_restrict f₁.ker $ λ x, by simp [h (f₁ x)] @[simp] lemma coe_proj_ker_of_right_inverse_apply [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (f₁.proj_ker_of_right_inverse f₂ h x : M) = x - f₂ (f₁ x) := rfl @[simp] lemma proj_ker_of_right_inverse_apply_idem [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : f₁.ker) : f₁.proj_ker_of_right_inverse f₂ h x = x := subtype.ext_iff_val.2 $ by simp @[simp] lemma proj_ker_of_right_inverse_comp_inv [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂) : f₁.proj_ker_of_right_inverse f₂ h (f₂ y) = 0 := subtype.ext_iff_val.2 $ by simp [h y] end ring section comm_ring variables {R : Type*} [comm_ring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] [topological_module R M₃] instance : has_scalar R (M →L[R] M₃) := ⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩ variables (c : R) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M) @[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl variable [topological_module R M₂] @[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, norm_cast] lemma coe_apply : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • (f : M →ₗ[R] M₂) := rfl @[norm_cast] lemma coe_apply' : (((c • f) : M →L[R] M₂) : M → M₂) = c • (f : M → M₂) := rfl @[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp } variable [topological_add_group M₂] instance : module R (M →L[R] M₂) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } instance : algebra R (M₂ →L[R] M₂) := algebra.of_semimodule' (λ c f, ext $ λ x, rfl) (λ c f, ext $ λ x, f.map_smul c x) end comm_ring end continuous_linear_map namespace continuous_linear_equiv section add_comm_monoid variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] M₂ := { cont := e.continuous_to_fun, ..e.to_linear_equiv.to_linear_map } /-- Coerce continuous linear equivs to continuous linear maps. -/ instance : has_coe (M ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩ /-- Coerce continuous linear equivs to maps. -/ -- see Note [function coercion] instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨λ _, M → M₂, λ f, f⟩ @[simp] theorem coe_def_rev (e : M ≃L[R] M₂) : e.to_continuous_linear_map = e := rfl @[simp] theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl @[norm_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl @[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g := begin cases f; cases g, simp only, ext x, induction h, refl end /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { ..e } -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero @[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y := (e : M →L[R] M₂).map_add x y @[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) := (e : M →L[R] M₂).map_smul c x @[simp] lemma map_eq_zero_iff (e : M ≃L[R] M₂) {x : M} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff attribute [continuity] continuous_linear_equiv.continuous_to_fun continuous_linear_equiv.continuous_inv_fun @[continuity] protected lemma continuous (e : M ≃L[R] M₂) : continuous (e : M → M₂) := e.continuous_to_fun protected lemma continuous_on (e : M ≃L[R] M₂) {s : set M} : continuous_on (e : M → M₂) s := e.continuous.continuous_on protected lemma continuous_at (e : M ≃L[R] M₂) {x : M} : continuous_at (e : M → M₂) x := e.continuous.continuous_at protected lemma continuous_within_at (e : M ≃L[R] M₂) {s : set M} {x : M} : continuous_within_at (e : M → M₂) s x := e.continuous.continuous_within_at lemma comp_continuous_on_iff {α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) (s : set α) : continuous_on (e ∘ f) s ↔ continuous_on f s := e.to_homeomorph.comp_continuous_on_iff _ _ lemma comp_continuous_iff {α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) : continuous (e ∘ f) ↔ continuous f := e.to_homeomorph.comp_continuous_iff _ /-- An extensionality lemma for `R ≃L[R] M`. -/ lemma ext₁ [topological_space R] {f g : R ≃L[R] M} (h : f 1 = g 1) : f = g := ext $ funext $ λ x, mul_one x ▸ by rw [← smul_eq_mul, map_smul, h, map_smul] section variables (R M) /-- The identity map as a continuous linear equivalence. -/ @[refl] protected def refl : M ≃L[R] M := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. linear_equiv.refl R M } end @[simp, norm_cast] lemma coe_refl : (continuous_linear_equiv.refl R M : M →L[R] M) = continuous_linear_map.id R M := rfl @[simp, norm_cast] lemma coe_refl' : (continuous_linear_equiv.refl R M : M → M) = id := rfl /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } @[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] M₃ := { continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun, continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun, .. e₁.to_linear_equiv.trans e₂.to_linear_equiv } @[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } /-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/ def prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) : (M × M₃) ≃L[R] (M₂ × M₄) := { continuous_to_fun := e.continuous_to_fun.prod_map e'.continuous_to_fun, continuous_inv_fun := e.continuous_inv_fun.prod_map e'.continuous_inv_fun, .. e.to_linear_equiv.prod e'.to_linear_equiv } @[simp, norm_cast] lemma prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (x) : e.prod e' x = (e x.1, e' x.2) := rfl @[simp, norm_cast] lemma coe_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) : (e.prod e' : (M × M₃) →L[R] (M₂ × M₄)) = (e : M →L[R] M₂).prod_map (e' : M₃ →L[R] M₄) := rfl theorem bijective (e : M ≃L[R] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective theorem injective (e : M ≃L[R] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective theorem surjective (e : M ≃L[R] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective @[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.6 c @[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.5 b @[simp] theorem coe_comp_coe_symm (e : M ≃L[R] M₂) : (e : M →L[R] M₂).comp (e.symm : M₂ →L[R] M) = continuous_linear_map.id R M₂ := continuous_linear_map.ext e.apply_symm_apply @[simp] theorem coe_symm_comp_coe (e : M ≃L[R] M₂) : (e.symm : M₂ →L[R] M).comp (e : M →L[R] M₂) = continuous_linear_map.id R M := continuous_linear_map.ext e.symm_apply_apply lemma symm_comp_self (e : M ≃L[R] M₂) : (e.symm : M₂ → M) ∘ (e : M → M₂) = id := by{ ext x, exact symm_apply_apply e x } lemma self_comp_symm (e : M ≃L[R] M₂) : (e : M → M₂) ∘ (e.symm : M₂ → M) = id := by{ ext x, exact apply_symm_apply e x } @[simp] lemma symm_comp_self' (e : M ≃L[R] M₂) : ((e.symm : M₂ →L[R] M) : M₂ → M) ∘ ((e : M →L[R] M₂) : M → M₂) = id := symm_comp_self e @[simp] lemma self_comp_symm' (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) ∘ ((e.symm : M₂ →L[R] M) : M₂ → M) = id := self_comp_symm e @[simp] theorem symm_symm (e : M ≃L[R] M₂) : e.symm.symm = e := by { ext x, refl } theorem symm_symm_apply (e : M ≃L[R] M₂) (x : M) : e.symm.symm x = e x := rfl lemma symm_apply_eq (e : M ≃L[R] M₂) {x y} : e.symm x = y ↔ x = e y := e.to_linear_equiv.symm_apply_eq lemma eq_symm_apply (e : M ≃L[R] M₂) {x y} : y = e.symm x ↔ e y = x := e.to_linear_equiv.eq_symm_apply /-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are inverse of each other. -/ def equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h₁ : function.left_inverse f₂ f₁) (h₂ : function.right_inverse f₂ f₁) : M ≃L[R] M₂ := { to_fun := f₁, continuous_to_fun := f₁.continuous, inv_fun := f₂, continuous_inv_fun := f₂.continuous, left_inv := h₁, right_inv := h₂, .. f₁ } @[simp] lemma equiv_of_inverse_apply (f₁ : M →L[R] M₂) (f₂ h₁ h₂ x) : equiv_of_inverse f₁ f₂ h₁ h₂ x = f₁ x := rfl @[simp] lemma symm_equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ h₁ h₂) : (equiv_of_inverse f₁ f₂ h₁ h₂).symm = equiv_of_inverse f₂ f₁ h₂ h₁ := rfl end add_comm_monoid section add_comm_group variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables [topological_add_group M₄] /-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ def skew_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) : (M × M₃) ≃L[R] M₂ × M₄ := { continuous_to_fun := (e.continuous_to_fun.comp continuous_fst).prod_mk ((e'.continuous_to_fun.comp continuous_snd).add $ f.continuous.comp continuous_fst), continuous_inv_fun := (e.continuous_inv_fun.comp continuous_fst).prod_mk (e'.continuous_inv_fun.comp $ continuous_snd.sub $ f.continuous.comp $ e.continuous_inv_fun.comp continuous_fst), .. e.to_linear_equiv.skew_prod e'.to_linear_equiv ↑f } @[simp] lemma skew_prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : e.skew_prod e' f x = (e x.1, e' x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : (e.skew_prod e' f).symm x = (e.symm x.1, e'.symm (x.2 - f (e.symm x.1))) := rfl end add_comm_group section ring variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] [semimodule R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [semimodule R M₂] @[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →L[R] M₂).map_sub x y @[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x section variables (R) [topological_space R] [topological_module R R] /-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `units R`. -/ def units_equiv_aut : units R ≃ (R ≃L[R] R) := { to_fun := λ u, equiv_of_inverse (continuous_linear_map.smul_right 1 ↑u) (continuous_linear_map.smul_right 1 ↑u⁻¹) (λ x, by simp) (λ x, by simp), inv_fun := λ e, ⟨e 1, e.symm 1, by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, symm_apply_apply], by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, apply_symm_apply]⟩, left_inv := λ u, units.ext $ by simp, right_inv := λ e, ext₁ $ by simp } variable {R} @[simp] lemma units_equiv_aut_apply (u : units R) (x : R) : units_equiv_aut R u x = x * u := rfl @[simp] lemma units_equiv_aut_apply_symm (u : units R) (x : R) : (units_equiv_aut R u).symm x = x * ↑u⁻¹ := rfl @[simp] lemma units_equiv_aut_symm_apply (e : R ≃L[R] R) : ↑((units_equiv_aut R).symm e) = e 1 := rfl end variables [topological_add_group M] open continuous_linear_map (id fst snd subtype_val mem_ker) /-- A pair of continuous linear maps such that `f₁ ∘ f₂ = id` generates a continuous linear equivalence `e` between `M` and `M₂ × f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`, `(e x).1 = f₁ x`, and `(e (f₂ y)).2 = 0`. The map is given by `e x = (f₁ x, x - f₂ (f₁ x))`. -/ def equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M ≃L[R] M₂ × f₁.ker := equiv_of_inverse (f₁.prod (f₁.proj_ker_of_right_inverse f₂ h)) (f₂.coprod (subtype_val f₁.ker)) (λ x, by simp) (λ ⟨x, y⟩, by simp [h x]) @[simp] lemma fst_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (equiv_of_right_inverse f₁ f₂ h x).1 = f₁ x := rfl @[simp] lemma snd_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : ((equiv_of_right_inverse f₁ f₂ h x).2 : M) = x - f₂ (f₁ x) := rfl @[simp] lemma equiv_of_right_inverse_symm_apply (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂ × f₁.ker) : (equiv_of_right_inverse f₁ f₂ h).symm y = f₂ y.1 + y.2 := rfl end ring end continuous_linear_equiv namespace submodule variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂] open continuous_linear_map /-- A submodule `p` is called *complemented* if there exists a continuous projection `M →ₗ[R] p`. -/ def closed_complemented (p : submodule R M) : Prop := ∃ f : M →L[R] p, ∀ x : p, f x = x lemma closed_complemented.has_closed_complement {p : submodule R M} [t1_space p] (h : closed_complemented p) : ∃ (q : submodule R M) (hq : is_closed (q : set M)), is_compl p q := exists.elim h $ λ f hf, ⟨f.ker, f.is_closed_ker, linear_map.is_compl_of_proj hf⟩ protected lemma closed_complemented.is_closed [topological_add_group M] [t1_space M] {p : submodule R M} (h : closed_complemented p) : is_closed (p : set M) := begin rcases h with ⟨f, hf⟩, have : ker (id R M - (subtype_val p).comp f) = p := linear_map.ker_id_sub_eq_of_proj hf, exact this ▸ (is_closed_ker _) end @[simp] lemma closed_complemented_bot : closed_complemented (⊥ : submodule R M) := ⟨0, λ x, by simp only [zero_apply, eq_zero_of_bot_submodule x]⟩ @[simp] lemma closed_complemented_top : closed_complemented (⊤ : submodule R M) := ⟨(id R M).cod_restrict ⊤ (λ x, trivial), λ x, subtype.ext_iff_val.2 $ by simp⟩ end submodule lemma continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : f₁.ker.closed_complemented := ⟨f₁.proj_ker_of_right_inverse f₂ h, f₁.proj_ker_of_right_inverse_apply_idem f₂ h⟩
3b566f9e37491cfdf2f86060c86e59190e84b084
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/star/basic.lean
0b2482caa873297ed7e548cc3a85c90a9fcc31ce
[ "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
17,301
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.apply_fun import algebra.field.opposite import algebra.field_power import algebra.ring.aut import group_theory.group_action.units import group_theory.group_action.opposite import algebra.ring.comp_typeclasses /-! # Star monoids, rings, and modules We introduce the basic algebraic notions of star monoids, star rings, and star modules. A star algebra is simply a star ring that is also a star module. These are implemented as "mixin" typeclasses, so to summon a star ring (for example) one needs to write `(R : Type) [ring R] [star_ring R]`. This avoids difficulties with diamond inheritance. We also define the class `star_ordered_ring R`, which says that the order on `R` respects the star operation, i.e. an element `r` is nonnegative iff there exists an `s` such that `r = star s * s`. For now we simply do not introduce notations, as different users are expected to feel strongly about the relative merits of `r^*`, `r†`, `rᘁ`, and so on. Our star rings are actually star semirings, but of course we can prove `star_neg : star (-r) = - star r` when the underlying semiring is a ring. ## TODO * In a Banach star algebra without a well-defined square root, the natural ordering is given by the positive cone which is the closure of the sums of elements `star r * r`. A weaker version of `star_ordered_ring` could be defined for this case. Note that the current definition has the advantage of not requiring a topology. -/ universes u v open mul_opposite /-- Notation typeclass (with no default notation!) for an algebraic structure with a star operation. -/ class has_star (R : Type u) := (star : R → R) variables {R : Type u} export has_star (star) /-- A star operation (e.g. complex conjugate). -/ add_decl_doc star /-- Typeclass for a star operation with is involutive. -/ class has_involutive_star (R : Type u) extends has_star R := (star_involutive : function.involutive star) export has_involutive_star (star_involutive) @[simp] lemma star_star [has_involutive_star R] (r : R) : star (star r) = r := star_involutive _ lemma star_injective [has_involutive_star R] : function.injective (star : R → R) := star_involutive.injective /-- `star` as an equivalence when it is involutive. -/ protected def equiv.star [has_involutive_star R] : equiv.perm R := star_involutive.to_perm _ lemma eq_star_of_eq_star [has_involutive_star R] {r s : R} (h : r = star s) : s = star r := by simp [h] lemma eq_star_iff_eq_star [has_involutive_star R] {r s : R} : r = star s ↔ s = star r := ⟨eq_star_of_eq_star, eq_star_of_eq_star⟩ lemma star_eq_iff_star_eq [has_involutive_star R] {r s : R} : star r = s ↔ star s = r := eq_comm.trans $ eq_star_iff_eq_star.trans eq_comm /-- Typeclass for a trivial star operation. This is mostly meant for `ℝ`. -/ class has_trivial_star (R : Type u) [has_star R] : Prop := (star_trivial : ∀ (r : R), star r = r) export has_trivial_star (star_trivial) attribute [simp] star_trivial /-- A `*`-semigroup is a semigroup `R` with an involutive operations `star` so `star (r * s) = star s * star r`. -/ class star_semigroup (R : Type u) [semigroup R] extends has_involutive_star R := (star_mul : ∀ r s : R, star (r * s) = star s * star r) export star_semigroup (star_mul) attribute [simp] star_mul /-- In a commutative ring, make `simp` prefer leaving the order unchanged. -/ @[simp] lemma star_mul' [comm_semigroup R] [star_semigroup R] (x y : R) : star (x * y) = star x * star y := (star_mul x y).trans (mul_comm _ _) /-- `star` as an `mul_equiv` from `R` to `Rᵐᵒᵖ` -/ @[simps apply] def star_mul_equiv [semigroup R] [star_semigroup R] : R ≃* Rᵐᵒᵖ := { to_fun := λ x, mul_opposite.op (star x), map_mul' := λ x y, (star_mul x y).symm ▸ (mul_opposite.op_mul _ _), ..(has_involutive_star.star_involutive.to_perm star).trans op_equiv} /-- `star` as a `mul_aut` for commutative `R`. -/ @[simps apply] def star_mul_aut [comm_semigroup R] [star_semigroup R] : mul_aut R := { to_fun := star, map_mul' := star_mul', ..(has_involutive_star.star_involutive.to_perm star) } variables (R) @[simp] lemma star_one [monoid R] [star_semigroup R] : star (1 : R) = 1 := op_injective $ (star_mul_equiv : R ≃* Rᵐᵒᵖ).map_one.trans (op_one _).symm variables {R} @[simp] lemma star_pow [monoid R] [star_semigroup R] (x : R) (n : ℕ) : star (x ^ n) = star x ^ n := op_injective $ ((star_mul_equiv : R ≃* Rᵐᵒᵖ).to_monoid_hom.map_pow x n).trans (op_pow (star x) n).symm @[simp] lemma star_inv [group R] [star_semigroup R] (x : R) : star (x⁻¹) = (star x)⁻¹ := op_injective $ ((star_mul_equiv : R ≃* Rᵐᵒᵖ).to_monoid_hom.map_inv x).trans (op_inv (star x)).symm @[simp] lemma star_zpow [group R] [star_semigroup R] (x : R) (z : ℤ) : star (x ^ z) = star x ^ z := op_injective $ ((star_mul_equiv : R ≃* Rᵐᵒᵖ).to_monoid_hom.map_zpow x z).trans (op_zpow (star x) z).symm /-- When multiplication is commutative, `star` preserves division. -/ @[simp] lemma star_div [comm_group R] [star_semigroup R] (x y : R) : star (x / y) = star x / star y := (star_mul_aut : R ≃* R).to_monoid_hom.map_div _ _ section open_locale big_operators @[simp] lemma star_prod [comm_monoid R] [star_semigroup R] {α : Type*} (s : finset α) (f : α → R): star (∏ x in s, f x) = ∏ x in s, star (f x) := (star_mul_aut : R ≃* R).map_prod _ _ end /-- Any commutative monoid admits the trivial `*`-structure. See note [reducible non-instances]. -/ @[reducible] def star_semigroup_of_comm {R : Type*} [comm_monoid R] : star_semigroup R := { star := id, star_involutive := λ x, rfl, star_mul := mul_comm } section local attribute [instance] star_semigroup_of_comm /-- Note that since `star_semigroup_of_comm` is reducible, `simp` can already prove this. --/ lemma star_id_of_comm {R : Type*} [comm_semiring R] {x : R} : star x = x := rfl end /-- A `*`-additive monoid `R` is an additive monoid with an involutive `star` operation which preserves addition. -/ class star_add_monoid (R : Type u) [add_monoid R] extends has_involutive_star R := (star_add : ∀ r s : R, star (r + s) = star r + star s) export star_add_monoid (star_add) attribute [simp] star_add /-- `star` as an `add_equiv` -/ @[simps apply] def star_add_equiv [add_monoid R] [star_add_monoid R] : R ≃+ R := { to_fun := star, map_add' := star_add, ..(has_involutive_star.star_involutive.to_perm star)} variables (R) @[simp] lemma star_zero [add_monoid R] [star_add_monoid R] : star (0 : R) = 0 := (star_add_equiv : R ≃+ R).map_zero variables {R} @[simp] lemma star_eq_zero [add_monoid R] [star_add_monoid R] {x : R} : star x = 0 ↔ x = 0 := star_add_equiv.map_eq_zero_iff lemma star_ne_zero [add_monoid R] [star_add_monoid R] {x : R} : star x ≠ 0 ↔ x ≠ 0 := star_eq_zero.not @[simp] lemma star_neg [add_group R] [star_add_monoid R] (r : R) : star (-r) = - star r := (star_add_equiv : R ≃+ R).map_neg _ @[simp] lemma star_sub [add_group R] [star_add_monoid R] (r s : R) : star (r - s) = star r - star s := (star_add_equiv : R ≃+ R).map_sub _ _ @[simp] lemma star_nsmul [add_monoid R] [star_add_monoid R] (x : R) (n : ℕ) : star (n • x) = n • star x := (star_add_equiv : R ≃+ R).to_add_monoid_hom.map_nsmul _ _ @[simp] lemma star_zsmul [add_group R] [star_add_monoid R] (x : R) (n : ℤ) : star (n • x) = n • star x := (star_add_equiv : R ≃+ R).to_add_monoid_hom.map_zsmul _ _ section open_locale big_operators @[simp] lemma star_sum [add_comm_monoid R] [star_add_monoid R] {α : Type*} (s : finset α) (f : α → R): star (∑ x in s, f x) = ∑ x in s, star (f x) := (star_add_equiv : R ≃+ R).map_sum _ _ end /-- A `*`-ring `R` is a (semi)ring with an involutive `star` operation which is additive which makes `R` with its multiplicative structure into a `*`-semigroup (i.e. `star (r * s) = star s * star r`). -/ class star_ring (R : Type u) [non_unital_semiring R] extends star_semigroup R := (star_add : ∀ r s : R, star (r + s) = star r + star s) @[priority 100] instance star_ring.to_star_add_monoid [non_unital_semiring R] [star_ring R] : star_add_monoid R := { star_add := star_ring.star_add } /-- `star` as an `ring_equiv` from `R` to `Rᵐᵒᵖ` -/ @[simps apply] def star_ring_equiv [non_unital_semiring R] [star_ring R] : R ≃+* Rᵐᵒᵖ := { to_fun := λ x, mul_opposite.op (star x), ..star_add_equiv.trans (mul_opposite.op_add_equiv : R ≃+ Rᵐᵒᵖ), ..star_mul_equiv } @[simp, norm_cast] lemma star_nat_cast [semiring R] [star_ring R] (n : ℕ) : star (n : R) = n := (congr_arg unop (map_nat_cast (star_ring_equiv : R ≃+* Rᵐᵒᵖ) n)).trans (unop_nat_cast _) @[simp, norm_cast] lemma star_int_cast [ring R] [star_ring R] (z : ℤ) : star (z : R) = z := (congr_arg unop ((star_ring_equiv : R ≃+* Rᵐᵒᵖ).to_ring_hom.map_int_cast z)).trans (unop_int_cast _) @[simp, norm_cast] lemma star_rat_cast [division_ring R] [char_zero R] [star_ring R] (r : ℚ) : star (r : R) = r := (congr_arg unop $ map_rat_cast (star_ring_equiv : R ≃+* Rᵐᵒᵖ) r).trans (unop_rat_cast _) /-- `star` as a ring automorphism, for commutative `R`. -/ @[simps apply] def star_ring_aut [comm_semiring R] [star_ring R] : ring_aut R := { to_fun := star, ..star_add_equiv, ..star_mul_aut } variables (R) /-- `star` as a ring endomorphism, for commutative `R`. This is used to denote complex conjugation, and is available under the notation `conj` in the locale `complex_conjugate`. Note that this is the preferred form (over `star_ring_aut`, available under the same hypotheses) because the notation `E →ₗ⋆[R] F` for an `R`-conjugate-linear map (short for `E →ₛₗ[star_ring_end R] F`) does not pretty-print if there is a coercion involved, as would be the case for `(↑star_ring_aut : R →* R)`. -/ def star_ring_end [comm_semiring R] [star_ring R] : R →+* R := @star_ring_aut R _ _ variables {R} localized "notation `conj` := star_ring_end _" in complex_conjugate /-- This is not a simp lemma, since we usually want simp to keep `star_ring_end` bundled. For example, for complex conjugation, we don't want simp to turn `conj x` into the bare function `star x` automatically since most lemmas are about `conj x`. -/ lemma star_ring_end_apply [comm_semiring R] [star_ring R] {x : R} : star_ring_end R x = star x := rfl @[simp] lemma star_ring_end_self_apply [comm_semiring R] [star_ring R] (x : R) : star_ring_end R (star_ring_end R x) = x := star_star x -- A more convenient name for complex conjugation alias star_ring_end_self_apply ← complex.conj_conj alias star_ring_end_self_apply ← is_R_or_C.conj_conj @[simp] lemma star_inv' [division_ring R] [star_ring R] (x : R) : star (x⁻¹) = (star x)⁻¹ := op_injective $ ((star_ring_equiv : R ≃+* Rᵐᵒᵖ).to_ring_hom.map_inv x).trans (op_inv (star x)).symm @[simp] lemma star_zpow₀ [division_ring R] [star_ring R] (x : R) (z : ℤ) : star (x ^ z) = star x ^ z := op_injective $ ((star_ring_equiv : R ≃+* Rᵐᵒᵖ).to_ring_hom.map_zpow x z).trans (op_zpow (star x) z).symm /-- When multiplication is commutative, `star` preserves division. -/ @[simp] lemma star_div' [field R] [star_ring R] (x y : R) : star (x / y) = star x / star y := (star_ring_end R).map_div _ _ @[simp] lemma star_bit0 [add_monoid R] [star_add_monoid R] (r : R) : star (bit0 r) = bit0 (star r) := by simp [bit0] @[simp] lemma star_bit1 [semiring R] [star_ring R] (r : R) : star (bit1 r) = bit1 (star r) := by simp [bit1] /-- Any commutative semiring admits the trivial `*`-structure. See note [reducible non-instances]. -/ @[reducible] def star_ring_of_comm {R : Type*} [comm_semiring R] : star_ring R := { star := id, star_add := λ x y, rfl, ..star_semigroup_of_comm } /-- An ordered `*`-ring is a ring which is both an `ordered_add_comm_group` and a `*`-ring, and `0 ≤ r ↔ ∃ s, r = star s * s`. -/ class star_ordered_ring (R : Type u) [non_unital_semiring R] [partial_order R] extends star_ring R := (add_le_add_left : ∀ a b : R, a ≤ b → ∀ c : R, c + a ≤ c + b) (nonneg_iff : ∀ r : R, 0 ≤ r ↔ ∃ s, r = star s * s) namespace star_ordered_ring variables [ring R] [partial_order R] [star_ordered_ring R] @[priority 100] -- see note [lower instance priority] instance : ordered_add_comm_group R := { ..show ring R, by apply_instance, ..show partial_order R, by apply_instance, ..show star_ordered_ring R, by apply_instance } end star_ordered_ring lemma star_mul_self_nonneg [non_unital_semiring R] [partial_order R] [star_ordered_ring R] {r : R} : 0 ≤ star r * r := (star_ordered_ring.nonneg_iff _).mpr ⟨r, rfl⟩ lemma star_mul_self_nonneg' [non_unital_semiring R] [partial_order R] [star_ordered_ring R] {r : R} : 0 ≤ r * star r := by { nth_rewrite_rhs 0 [←star_star r], exact star_mul_self_nonneg } /-- A star module `A` over a star ring `R` is a module which is a star add monoid, and the two star structures are compatible in the sense `star (r • a) = star r • star a`. Note that it is up to the user of this typeclass to enforce `[semiring R] [star_ring R] [add_comm_monoid A] [star_add_monoid A] [module R A]`, and that the statement only requires `[has_star R] [has_star A] [has_scalar R A]`. If used as `[comm_ring R] [star_ring R] [semiring A] [star_ring A] [algebra R A]`, this represents a star algebra. -/ class star_module (R : Type u) (A : Type v) [has_star R] [has_star A] [has_scalar R A] : Prop := (star_smul : ∀ (r : R) (a : A), star (r • a) = star r • star a) export star_module (star_smul) attribute [simp] star_smul /-- A commutative star monoid is a star module over itself via `monoid.to_mul_action`. -/ instance star_semigroup.to_star_module [comm_monoid R] [star_semigroup R] : star_module R R := ⟨star_mul'⟩ namespace ring_hom_inv_pair /-- Instance needed to define star-linear maps over a commutative star ring (ex: conjugate-linear maps when R = ℂ). -/ instance [comm_semiring R] [star_ring R] : ring_hom_inv_pair (star_ring_end R) (star_ring_end R) := ⟨ring_hom.ext star_star, ring_hom.ext star_star⟩ end ring_hom_inv_pair /-! ### Instances -/ namespace units variables [monoid R] [star_semigroup R] instance : star_semigroup Rˣ := { star := λ u, { val := star u, inv := star ↑u⁻¹, val_inv := (star_mul _ _).symm.trans $ (congr_arg star u.inv_val).trans $ star_one _, inv_val := (star_mul _ _).symm.trans $ (congr_arg star u.val_inv).trans $ star_one _ }, star_involutive := λ u, units.ext (star_involutive _), star_mul := λ u v, units.ext (star_mul _ _) } @[simp] lemma coe_star (u : Rˣ) : ↑(star u) = (star ↑u : R) := rfl @[simp] lemma coe_star_inv (u : Rˣ) : ↑(star u)⁻¹ = (star ↑u⁻¹ : R) := rfl instance {A : Type*} [has_star A] [has_scalar R A] [star_module R A] : star_module Rˣ A := ⟨λ u a, (star_smul ↑u a : _)⟩ end units lemma is_unit.star [monoid R] [star_semigroup R] {a : R} : is_unit a → is_unit (star a) | ⟨u, hu⟩ := ⟨star u, hu ▸ rfl⟩ @[simp] lemma is_unit_star [monoid R] [star_semigroup R] {a : R} : is_unit (star a) ↔ is_unit a := ⟨λ h, star_star a ▸ h.star, is_unit.star⟩ lemma ring.inverse_star [semiring R] [star_ring R] (a : R) : ring.inverse (star a) = star (ring.inverse a) := begin by_cases ha : is_unit a, { obtain ⟨u, rfl⟩ := ha, rw [ring.inverse_unit, ←units.coe_star, ring.inverse_unit, ←units.coe_star_inv], }, rw [ring.inverse_non_unit _ ha, ring.inverse_non_unit _ (mt is_unit_star.mp ha), star_zero], end instance invertible.star {R : Type*} [monoid R] [star_semigroup R] (r : R) [invertible r] : invertible (star r) := { inv_of := star (⅟r), inv_of_mul_self := by rw [←star_mul, mul_inv_of_self, star_one], mul_inv_of_self := by rw [←star_mul, inv_of_mul_self, star_one] } lemma star_inv_of {R : Type*} [monoid R] [star_semigroup R] (r : R) [invertible r] [invertible (star r)] : star (⅟r) = ⅟(star r) := by { letI := invertible.star r, convert (rfl : star (⅟r) = _) } namespace mul_opposite /-- The opposite type carries the same star operation. -/ instance [has_star R] : has_star (Rᵐᵒᵖ) := { star := λ r, op (star (r.unop)) } @[simp] lemma unop_star [has_star R] (r : Rᵐᵒᵖ) : unop (star r) = star (unop r) := rfl @[simp] lemma op_star [has_star R] (r : R) : op (star r) = star (op r) := rfl instance [has_involutive_star R] : has_involutive_star (Rᵐᵒᵖ) := { star_involutive := λ r, unop_injective (star_star r.unop) } instance [monoid R] [star_semigroup R] : star_semigroup (Rᵐᵒᵖ) := { star_mul := λ x y, unop_injective (star_mul y.unop x.unop) } instance [add_monoid R] [star_add_monoid R] : star_add_monoid (Rᵐᵒᵖ) := { star_add := λ x y, unop_injective (star_add x.unop y.unop) } instance [semiring R] [star_ring R] : star_ring (Rᵐᵒᵖ) := { .. mul_opposite.star_add_monoid } end mul_opposite /-- A commutative star monoid is a star module over its opposite via `monoid.to_opposite_mul_action`. -/ instance star_semigroup.to_opposite_star_module [comm_monoid R] [star_semigroup R] : star_module Rᵐᵒᵖ R := ⟨λ r s, star_mul' s r.unop⟩
73d17b53b0a3ad54cd6c4efdcc2965ebc495ee75
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/data/ordering.lean
4f5aa1f8d8792650b65346efc678ad8229676d71
[ "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
2,775
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.repr init.data.prod init.data.sum.basic universes u v inductive ordering | lt | eq | gt namespace ordering def swap : ordering → ordering | lt := gt | eq := eq | gt := lt def or_else : ordering → thunk ordering → ordering | lt _ := lt | eq f := f () | gt _ := gt theorem swap_swap : ∀ (o : ordering), o.swap.swap = o | lt := rfl | eq := rfl | gt := rfl end ordering open ordering instance : has_repr ordering := ⟨(λ s, match s with | ordering.lt := "lt" | ordering.eq := "eq" | ordering.gt := "gt" end)⟩ class has_ordering (α : Type u) := (cmp : α → α → ordering) def nat.cmp (a b : nat) : ordering := if a < b then ordering.lt else if a = b then ordering.eq else ordering.gt instance : has_ordering nat := ⟨nat.cmp⟩ instance (n) : has_ordering (fin n) := ⟨λ a b, nat.cmp a.1 b.1⟩ instance : has_ordering char := fin.has_ordering _ instance : has_ordering unsigned := fin.has_ordering _ def list.cmp {α : Type u} [has_ordering α] : list α → list α → ordering | [] [] := ordering.eq | [] (b::l') := ordering.lt | (a::l) [] := ordering.gt | (a::l) (b::l') := (has_ordering.cmp a b).or_else (list.cmp l l') instance {α : Type u} [has_ordering α] : has_ordering (list α) := ⟨list.cmp⟩ def string.cmp (s1 s2 : string) : ordering := list.cmp s1.to_list s2.to_list instance : has_ordering string := ⟨string.cmp⟩ section open prod variables {α : Type u} {β : Type v} [has_ordering α] [has_ordering β] def prod.cmp : α × β → α × β → ordering | (a₁, b₁) (a₂, b₂) := (has_ordering.cmp a₁ a₂).or_else (has_ordering.cmp b₁ b₂) instance {α : Type u} {β : Type v} [has_ordering α] [has_ordering β] : has_ordering (α × β) := ⟨prod.cmp⟩ end section open sum variables {α : Type u} {β : Type v} [has_ordering α] [has_ordering β] def sum.cmp : α ⊕ β → α ⊕ β → ordering | (inl a₁) (inl a₂) := has_ordering.cmp a₁ a₂ | (inr b₁) (inr b₂) := has_ordering.cmp b₁ b₂ | (inl a₁) (inr b₂) := lt | (inr b₁) (inl a₂) := gt instance {α : Type u} {β : Type v} [has_ordering α] [has_ordering β] : has_ordering (α ⊕ β) := ⟨sum.cmp⟩ end section open option variables {α : Type u} [has_ordering α] def option.cmp : option α → option α → ordering | (some a₁) (some a₂) := has_ordering.cmp a₁ a₂ | (some a₁) none := gt | none (some a₂) := lt | none none := eq instance {α : Type u} [has_ordering α] : has_ordering (option α) := ⟨option.cmp⟩ end
b99d692e8eeeb429b096f6fd82e745efbdac48fb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/ring.lean
4dcb10f74db63e0f1addc892faec9c9ff8deedaf
[ "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
32,558
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 tactic.norm_num import data.fin.basic /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (α : Type) : Type := reader_t cache tactic α /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : ℕ) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m ℕ := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. This version of `ring_m.run` uses an external atoms ref, so that subexpressions can be named across multiple `ring_m` calls. -/ meta def ring_m.run' (red : transparency) (atoms : ref (buffer expr)) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache α, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(ℕ), using_new_ref ic $ λ r, using_new_ref nc $ λ nr, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := using_new_ref mk_buffer $ λ atoms, ring_m.run' red atoms e m /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/ @[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α} (f : instance_cache → tactic (instance_cache × α)) : ring_m α := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `α`. -/ @[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `ℕ`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `ℕ` and `ℚ` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : ℚ) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr → expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr → bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr (λ _, expr → expr) := ⟨λ e, ⇑(e : expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr → string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr → tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ λ nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm (x ^ n)]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := ic_lift $ λ ic, do let n := c₁ + c₂, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ e₂ e c₁ c₂ n, return (ic, const e n, p) | he₁@(const e₁ c₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``zero_add [e₂], return (ic, he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂ c₂) := do c ← get_cache, if c₂ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek n₂.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0 0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₂.1 ek n₁.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0 0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ic_lift $ λ ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr × ℚ) : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic e₁ e₂ c₁ c₂, return (const e' (c₁ * c₂), p) | (const e₁ c₁) e₂ := if c₁ = 0 then do c ← get_cache, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ λ ic, ic.mk_app ``zero_mul [e₂], return (const α0 0, p) else if c₁ = 1 then do p ← ic_lift $ λ ic, ic.mk_app ``one_mul [e₂], return (e₂, p) else eval_const_mul (e₁, c₁) e₂ | e₁ he₂@(const e₂ c₂) := do p₁ ← ic_lift $ λ ic, ic.mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (haa, h₂) ← eval_horner aa x₁ n₂ (const α0 0), if b₂.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] theorem pow_succ {α} [comm_semiring α] (a n b c) (h₁ : (a:α) ^ n = b) (h₂ : b * a = c) : a ^ (n + 1) = c := by rw [← h₂, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], p ← ic_lift $ λ ic, ic.mk_app ``pow_zero [e], return (const α1 1, p) | e (_, 1) := do p ← ic_lift $ λ ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (e₂, m) := ic_lift $ λ ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic e₂, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ λ nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', h₂) ← eval_pow a m, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const α0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← nc_lift $ λ nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, e₂, tl, t, hl, p₂]) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], return (xadd' c (const α1 1) (e, i) (`(1), 1) (const α0 0), c.cs_app ``horner_atom [e]) /-- Evaluate `a` where `a` is an atom. -/ meta def eval_norm_atom (norm_atom : expr → tactic (expr × expr)) (e : expr) : ring_m (horner_expr × expr) := do o ← lift $ try_core (guard (e.get_app_args.length > 0) >> norm_atom e), match o with | none := eval_atom e | some (e', p) := do (e₂, p₂) ← eval_atom e', prod.mk e₂ <$> lift (mk_eq_trans p p₂) end lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := by rw [div_eq_mul_inv, h] /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval (norm_atom : expr → tactic (expr × expr)) : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%inst %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_neg.neg [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_sub [e₁, e₂, e', p], return (e', p')) (eval_norm_atom norm_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_norm_atom norm_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ic_lift $ λ ic, ic.mk_app ``div_inv_monoid.to_has_div [], lift $ is_def_eq inst inst')) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_inv.inv [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_div [e₁, e₂, e', p], return (e', p')) (eval_norm_atom norm_atom e) | e@`(@has_pow.pow _ _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ic_lift $ λ ic, ic.mk_app ``monoid.has_pow [], lift $ is_def_eq inst inst')) (do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat with | some k := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | _ := eval_norm_atom norm_atom e end) (eval_norm_atom norm_atom e) | e := match e.to_nat with | some n := (const e n).refl_conv | none := eval_norm_atom norm_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (atoms : ref (buffer expr)) (norm_atom : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := ring_m.run' red atoms e $ do (e', p) ← eval norm_atom e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := (sub_eq_add_neg a b).symm /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive [has_reflect, decidable_eq]] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. See `normalize`. This version takes a list of atoms to persist across multiple calls. * `atoms`: a mutable reference containing the atom set from the previous call * `red`: the reducibility setting to use when comparing atoms for defeq * `mode`: the normalization style (see `normalize_mode`) * `recursive`: if true, atoms will be reduced recursively using `normalize'` * `e`: the expression to normalize * `inner`: This should be set to `ff`. It is used internally to disable normalization at the top level when called from `eval` in order to prevent an infinite loop `eval' -> eval_atom -> normalize' -> eval'` when called on something that can't be simplified like `x`. -/ meta def normalize' (atoms : ref (buffer expr)) (red : transparency) (mode := normalize_mode.horner) (recursive := tt) : expr → opt_param _ ff → tactic (expr × expr) | e inner := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, trans_conv (λ e, do guard (mode ≠ normalize_mode.raw), (e', pr, _) ← simplify simp_lemmas.mk [] e, pure (e', pr)) (λ e, do a ← read_ref atoms, let norm_rec := if recursive then λ e, normalize' e tt else λ _, failed, (a, e', pr) ← ext_simplify_core a {} simp_lemmas.mk (λ _, failed) (λ a _ _ p e, do guard (inner → p.is_some), write_ref atoms a, (new_e, pr) ← eval' red atoms norm_rec e, (new_e, pr) ← match mode with | normalize_mode.raw := λ _, pure (new_e, pr) | normalize_mode.horner := trans_conv (λ _, pure (new_e, pr)) (λ e, do (e', prf, _) ← simplify lemmas [] e, pure (e', prf)) | normalize_mode.SOP := trans_conv (λ _, pure (new_e, pr)) $ trans_conv (λ e, do (e', prf, _) ← simplify lemmas [] e, pure (e', prf)) $ simp_bottom_up' (λ e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), a ← read_ref atoms, pure (a, new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, write_ref atoms a, pure (e', pr)) e /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (recursive := tt) (e : expr) : tactic (expr × expr) := using_new_ref mk_buffer $ λ atoms, normalize' atoms red mode recursive e /-- Configuration for `ring_nf`. * `recursive`: if true, atoms inside ring expressions will be reduced recursively -/ @[derive inhabited] structure ring_nf_cfg := (recursive := tt) end ring namespace interactive open tactic.ring setup_tactic_parser /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target >>= instantiate_mvars, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval (λ _, failed) e₁ <*> eval (λ _, failed) e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring_nf`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := pure ring.normalize_mode.horner | some `horner := pure ring.normalize_mode.horner | some `SOP := pure ring.normalize_mode.SOP | some `raw := pure ring.normalize_mode.raw | _ := failed end /-- Simplification tactic for expressions in the language of commutative (semi)rings, which rewrites all ring expressions into a normal form. When writing a normal form, `ring_nf SOP` will use sum-of-products form instead of horner form. `ring_nf!` will use a more aggressive reducibility setting to identify atoms. -/ meta def ring_nf (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) (cfg : ring_nf_cfg := {}) : tactic unit := do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← using_new_ref mk_buffer $ λ atoms, tactic.replace_at (normalize' atoms transp SOP cfg.recursive) ns loc.include_goal | fail "ring_nf failed to simplify", when loc.include_goal $ try tactic.reflexivity /-- Tactic for solving equations in the language of *commutative* (semi)rings. `ring!` will use a more aggressive reducibility setting to identify atoms. If the goal is not solvable, it falls back to rewriting all ring expressions into a normal form, with a suggestion to use `ring_nf` instead, if this is the intent. See also `ring1`, which is the same as `ring` but without the fallback behavior. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) : tactic unit := ring1 red <|> (ring_nf red normalize_mode.horner (loc.ns [none]) >> trace "Try this: ring_nf") add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [``ring, ``ring_nf, ``ring1], inherit_description_from := ``ring, tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize normalize_mode.horner) local postfix (name := parser.optional) `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring_nf (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) (cfg : ring.ring_nf_cfg := {}) : conv unit := let transp := if red.is_some then semireducible else reducible in replace_lhs (normalize transp SOP cfg.recursive) <|> fail "ring_nf failed to simplify" /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> (replace_lhs (normalize transp normalize_mode.horner) >> trace "Try this: ring_nf") <|> fail "ring failed to simplify" end conv.interactive
488e1c090f41bf9c05a5e33ffd5e6cdcfa38d534
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/upto.lean
e8996cd788fc8338eeec3167010a81da7b2865b8
[ "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,386
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.nat.order.basic /-! # `nat.upto` `nat.upto p`, with `p` a predicate on `ℕ`, is a subtype of elements `n : ℕ` such that no value (strictly) below `n` satisfies `p`. This type has the property that `>` is well-founded when `∃ i, p i`, which allows us to implement searches on `ℕ`, starting at `0` and with an unknown upper-bound. It is similar to the well founded relation constructed to define `nat.find` with the difference that, in `nat.upto p`, `p` does not need to be decidable. In fact, `nat.find` could be slightly altered to factor decidability out of its well founded relation and would then fulfill the same purpose as this file. -/ namespace nat /-- The subtype of natural numbers `i` which have the property that no `j` less than `i` satisfies `p`. This is an initial segment of the natural numbers, up to and including the first value satisfying `p`. We will be particularly interested in the case where there exists a value satisfying `p`, because in this case the `>` relation is well-founded. -/ @[reducible] def upto (p : ℕ → Prop) : Type := {i : ℕ // ∀ j < i, ¬ p j} namespace upto variable {p : ℕ → Prop} /-- Lift the "greater than" relation on natural numbers to `nat.upto`. -/ protected def gt (p) (x y : upto p) : Prop := x.1 > y.1 instance : has_lt (upto p) := ⟨λ x y, x.1 < y.1⟩ /-- The "greater than" relation on `upto p` is well founded if (and only if) there exists a value satisfying `p`. -/ protected lemma wf : (∃ x, p x) → well_founded (upto.gt p) | ⟨x, h⟩ := begin suffices : upto.gt p = measure (λ y : nat.upto p, x - y.val), { rw this, apply measure_wf }, ext ⟨a, ha⟩ ⟨b, _⟩, dsimp [measure, inv_image, upto.gt], rw tsub_lt_tsub_iff_left_of_le, exact le_of_not_lt (λ h', ha _ h' h), end /-- Zero is always a member of `nat.upto p` because it has no predecessors. -/ def zero : nat.upto p := ⟨0, λ j h, false.elim (nat.not_lt_zero _ h)⟩ /-- The successor of `n` is in `nat.upto p` provided that `n` doesn't satisfy `p`. -/ def succ (x : nat.upto p) (h : ¬ p x.val) : nat.upto p := ⟨x.val.succ, λ j h', begin rcases nat.lt_succ_iff_lt_or_eq.1 h' with h' | rfl; [exact x.2 _ h', exact h] end⟩ end upto end nat
081130e80d78c3998f638f1e6cb155b9581bac0d
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/topology/algebra/ordered.lean
1f1096a1a08c628333a22a1244fa379c5af03446
[ "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
117,668
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, Yury Kudryashov -/ import tactic.tfae import order.liminf_limsup import data.set.intervals.image_preimage import data.set.intervals.ord_connected import data.set.intervals.surj_on import topology.algebra.group import topology.extend_from_subset import order.filter.interval /-! # Theory of topology on ordered spaces ## Main definitions The order topology on an ordered space is the topology generated by all open intervals (or equivalently by those of the form `(-∞, a)` and `(b, +∞)`). We define it as `preorder.topology α`. However, we do *not* register it as an instance (as many existing ordered types already have topologies, which would be equal but not definitionally equal to `preorder.topology α`). Instead, we introduce a class `order_topology α`(which is a `Prop`, also known as a mixin) saying that on the type `α` having already a topological space structure and a preorder structure, the topological structure is equal to the order topology. We also introduce another (mixin) class `order_closed_topology α` saying that the set of points `(x, y)` with `x ≤ y` is closed in the product space. This is automatically satisfied on a linear order with the order topology. We prove many basic properties of such topologies. ## Main statements This file contains the proofs of the following facts. For exact requirements (`order_closed_topology` vs `order_topology`, `preorder` vs `partial_order` vs `linear_order` etc) see their statements. ### Open / closed sets * `is_open_lt` : if `f` and `g` are continuous functions, then `{x | f x < g x}` is open; * `is_open_Iio`, `is_open_Ioi`, `is_open_Ioo` : open intervals are open; * `is_closed_le` : if `f` and `g` are continuous functions, then `{x | f x ≤ g x}` is closed; * `is_closed_Iic`, `is_closed_Ici`, `is_closed_Icc` : closed intervals are closed; * `frontier_le_subset_eq`, `frontier_lt_subset_eq` : frontiers of both `{x | f x ≤ g x}` and `{x | f x < g x}` are included by `{x | f x = g x}`; * `exists_Ioc_subset_of_mem_nhds`, `exists_Ico_subset_of_mem_nhds` : if `x < y`, then any neighborhood of `x` includes an interval `[x, z)` for some `z ∈ (x, y]`, and any neighborhood of `y` includes an interval `(z, y]` for some `z ∈ [x, y)`. ### Convergence and inequalities * `le_of_tendsto_of_tendsto` : if `f` converges to `a`, `g` converges to `b`, and eventually `f x ≤ g x`, then `a ≤ b` * `le_of_tendsto`, `ge_of_tendsto` : if `f` converges to `a` and eventually `f x ≤ b` (resp., `b ≤ f x`), then `a ≤ b` (resp., `b ≤ a); we also provide primed versions that assume the inequalities to hold for all `x`. ### Min, max, `Sup` and `Inf` * `continuous.min`, `continuous.max`: pointwise `min`/`max` of two continuous functions is continuous. * `tendsto.min`, `tendsto.max` : if `f` tends to `a` and `g` tends to `b`, then their pointwise `min`/`max` tend to `min a b` and `max a b`, respectively. * `tendsto_of_tendsto_of_tendsto_of_le_of_le` : theorem known as squeeze theorem, sandwich theorem, theorem of Carabinieri, and two policemen (and a drunk) theorem; if `g` and `h` both converge to `a`, and eventually `g x ≤ f x ≤ h x`, then `f` converges to `a`. ### Connected sets and Intermediate Value Theorem * `is_preconnected_I??` : all intervals `I??` are preconnected, * `is_preconnected.intermediate_value`, `intermediate_value_univ` : Intermediate Value Theorem for connected sets and connected spaces, respectively; * `intermediate_value_Icc`, `intermediate_value_Icc'`: Intermediate Value Theorem for functions on closed intervals. ### Miscellaneous facts * `is_compact.exists_forall_le`, `is_compact.exists_forall_ge` : extreme value theorem, a continuous function on a compact set takes its minimum and maximum values. * `is_closed.Icc_subset_of_forall_mem_nhds_within` : “Continuous induction” principle; if `s ∩ [a, b]` is closed, `a ∈ s`, and for each `x ∈ [a, b) ∩ s` some of its right neighborhoods is included `s`, then `[a, b] ⊆ s`. * `is_closed.Icc_subset_of_forall_exists_gt`, `is_closed.mem_of_ge_of_forall_exists_gt` : two other versions of the “continuous induction” principle. ## Implementation We do _not_ register the order topology as an instance on a preorder (or even on a linear order). Indeed, on many such spaces, a topology has already been constructed in a different way (think of the discrete spaces `ℕ` or `ℤ`, or `ℝ` that could inherit a topology as the completion of `ℚ`), and is in general not defeq to the one generated by the intervals. We make it available as a definition `preorder.topology α` though, that can be registered as an instance when necessary, or for specific types. -/ open classical set filter topological_space open function (curry uncurry) open_locale topological_space classical filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- A topology on a set which is both a topological space and a preorder is _order-closed_ if the set of points `(x, y)` with `x ≤ y` is closed in the product space. We introduce this as a mixin. This property is satisfied for the order topology on a linear order, but it can be satisfied more generally, and suffices to derive many interesting properties relating order and topology. -/ class order_closed_topology (α : Type*) [topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed {p:α×α | p.1 ≤ p.2}) instance : Π [topological_space α], topological_space (order_dual α) := id section order_closed_topology section preorder variables [topological_space α] [preorder α] [t : order_closed_topology α] include t lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ t.is_closed_le' lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_Iic {a : α} : is_closed (Iic a) := is_closed_le' a lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id lemma is_closed_Ici {a : α} : is_closed (Ici a) := is_closed_ge' a instance : order_closed_topology (order_dual α) := ⟨continuous_swap _ (@order_closed_topology.is_closed_le' α _ _ _)⟩ lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed_inter is_closed_Ici is_closed_Iic @[simp] lemma closure_Icc (a b : α) : closure (Icc a b) = Icc a b := is_closed_Icc.closure_eq @[simp] lemma closure_Iic (a : α) : closure (Iic a) = Iic a := is_closed_Iic.closure_eq @[simp] lemma closure_Ici (a : α) : closure (Ici a) = Ici a := is_closed_Ici.closure_eq lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b] (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : f ≤ᶠ[b] g) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (𝓝 (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from t.is_closed_le'.mem_of_tendsto this h lemma le_of_tendsto_of_tendsto' {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b] (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : ∀ x, f x ≤ g x) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto hf hg (eventually_of_forall h) lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, f c ≤ b) : a ≤ b := le_of_tendsto_of_tendsto lim tendsto_const_nhds h lemma le_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, f c ≤ b) : a ≤ b := le_of_tendsto lim (eventually_of_forall h) lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, b ≤ f c) : b ≤ a := le_of_tendsto_of_tendsto tendsto_const_nhds lim h lemma ge_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, b ≤ f c) : b ≤ a := ge_of_tendsto lim (eventually_of_forall h) @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := (is_closed_le hf hg).closure_eq lemma closure_lt_subset_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b < g b} ⊆ {b | f b ≤ g b} := by { rw [←closure_le_eq hf hg], exact closure_mono (λ b, le_of_lt) } lemma continuous_within_at.closure_le [topological_space β] {f g : β → α} {s : set β} {x : β} (hx : x ∈ closure s) (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) (h : ∀ y ∈ s, f y ≤ g y) : f x ≤ g x := show (f x, g x) ∈ {p : α × α | p.1 ≤ p.2}, from order_closed_topology.is_closed_le'.closure_subset ((hf.prod hg).mem_closure hx h) /-- If `s` is a closed set and two functions `f` and `g` are continuous on `s`, then the set `{x ∈ s | f x ≤ g x}` is a closed set. -/ lemma is_closed.is_closed_le [topological_space β] {f g : β → α} {s : set β} (hs : is_closed s) (hf : continuous_on f s) (hg : continuous_on g s) : is_closed {x ∈ s | f x ≤ g x} := (hf.prod hg).preimage_closed_of_closed hs order_closed_topology.is_closed_le' omit t lemma nhds_within_Ici_ne_bot {a b : α} (H₂ : a ≤ b) : 𝓝[Ici a] b ≠ ⊥ := nhds_within_ne_bot_of_mem H₂ lemma nhds_within_Ici_self_ne_bot (a : α) : 𝓝[Ici a] a ≠ ⊥ := nhds_within_Ici_ne_bot (le_refl a) lemma nhds_within_Iic_ne_bot {a b : α} (H : a ≤ b) : 𝓝[Iic b] a ≠ ⊥ := nhds_within_ne_bot_of_mem H lemma nhds_within_Iic_self_ne_bot (a : α) : 𝓝[Iic a] a ≠ ⊥ := nhds_within_Iic_ne_bot (le_refl a) end preorder section partial_order variables [topological_space α] [partial_order α] [t : order_closed_topology α] include t private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} := by simp only [le_antisymm_iff]; exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst) @[priority 90] -- see Note [lower instance priority] instance order_closed_topology.to_t2_space : t2_space α := { t2 := have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq, assume a b h, let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in ⟨u, v, hu, hv, ha, hb, set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩, have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩, this rfl⟩ } end partial_order section linear_order variables [topological_space α] [linear_order α] [order_closed_topology α] lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf variables {a b : α} lemma is_open_Iio : is_open (Iio a) := is_open_lt continuous_id continuous_const lemma is_open_Ioi : is_open (Ioi a) := is_open_lt continuous_const continuous_id lemma is_open_Ioo : is_open (Ioo a b) := is_open_inter is_open_Ioi is_open_Iio @[simp] lemma interior_Ioi : interior (Ioi a) = Ioi a := is_open_Ioi.interior_eq @[simp] lemma interior_Iio : interior (Iio a) = Iio a := is_open_Iio.interior_eq @[simp] lemma interior_Ioo : interior (Ioo a b) = Ioo a b := is_open_Ioo.interior_eq /-- Intermediate value theorem for two functions: if `f` and `g` are two continuous functions on a preconnected space and `f a ≤ g a` and `g b ≤ f b`, then for some `x` we have `f x = g x`. -/ lemma intermediate_value_univ₂ {γ : Type*} [topological_space γ] [preconnected_space γ] {a b : γ} {f g : γ → α} (hf : continuous f) (hg : continuous g) (ha : f a ≤ g a) (hb : g b ≤ f b) : ∃ x, f x = g x := begin obtain ⟨x, h, hfg, hgf⟩ : (univ ∩ {x | f x ≤ g x ∧ g x ≤ f x}).nonempty, from is_preconnected_closed_iff.1 preconnected_space.is_preconnected_univ _ _ (is_closed_le hf hg) (is_closed_le hg hf) (λ x hx, le_total _ _) ⟨a, trivial, ha⟩ ⟨b, trivial, hb⟩, exact ⟨x, le_antisymm hfg hgf⟩ end /-- Intermediate value theorem for two functions: if `f` and `g` are two functions continuous on a preconnected set `s` and for some `a b ∈ s` we have `f a ≤ g a` and `g b ≤ f b`, then for some `x ∈ s` we have `f x = g x`. -/ lemma is_preconnected.intermediate_value₂ {γ : Type*} [topological_space γ] {s : set γ} (hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f g : γ → α} (hf : continuous_on f s) (hg : continuous_on g s) (ha' : f a ≤ g a) (hb' : g b ≤ f b) : ∃ x ∈ s, f x = g x := let ⟨x, hx⟩ := @intermediate_value_univ₂ α _ _ _ s _ (subtype.preconnected_space hs) ⟨a, ha⟩ ⟨b, hb⟩ _ _ (continuous_on_iff_continuous_restrict.1 hf) (continuous_on_iff_continuous_restrict.1 hg) ha' hb' in ⟨x, x.2, hx⟩ /-- Intermediate Value Theorem for continuous functions on connected sets. -/ lemma is_preconnected.intermediate_value {γ : Type*} [topological_space γ] {s : set γ} (hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f : γ → α} (hf : continuous_on f s) : Icc (f a) (f b) ⊆ f '' s := λ x hx, mem_image_iff_bex.2 $ hs.intermediate_value₂ ha hb hf continuous_on_const hx.1 hx.2 /-- Intermediate Value Theorem for continuous functions on connected spaces. -/ lemma intermediate_value_univ {γ : Type*} [topological_space γ] [preconnected_space γ] (a b : γ) {f : γ → α} (hf : continuous f) : Icc (f a) (f b) ⊆ range f := λ x hx, intermediate_value_univ₂ hf continuous_const hx.1 hx.2 /-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/ lemma is_preconnected.Icc_subset {s : set α} (hs : is_preconnected s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : Icc a b ⊆ s := by simpa only [image_id] using hs.intermediate_value ha hb continuous_on_id /-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/ lemma is_connected.Icc_subset {s : set α} (hs : is_connected s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : Icc a b ⊆ s := hs.2.Icc_subset ha hb /-- If preconnected set in a linear order space is unbounded below and above, then it is the whole space. -/ lemma is_preconnected.eq_univ_of_unbounded {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s) (ha : ¬bdd_above s) : s = univ := begin refine eq_univ_of_forall (λ x, _), obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := not_bdd_below_iff.1 hb x, obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x, exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ end /-! ### Neighborhoods to the left and to the right on an `order_closed_topology` Limits to the left and to the right of real functions are defined in terms of neighborhoods to the left and to the right, either open or closed, i.e., members of `𝓝[Ioi a] a` and `𝓝[Ici a] a` on the right, and similarly on the left. Here we simply prove that all right-neighborhoods of a point are equal, and we'll prove later other useful characterizations which require the stronger hypothesis `order_topology α` -/ /-! #### Right neighborhoods, point excluded -/ lemma Ioo_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ioo a c ∈ 𝓝[Ioi b] b := mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2, by rw [inter_comm, Ioi_inter_Iio]; exact Ioo_subset_Ioo_left H.1⟩ lemma Ioc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ioc a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ioc_self lemma Ico_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ico a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ico_self lemma Icc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Icc a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Icc_self @[simp] lemma nhds_within_Ioc_eq_nhds_within_Ioi {a b : α} (h : a < b) : 𝓝[Ioc a b] a = 𝓝[Ioi a] a := le_antisymm (nhds_within_mono _ Ioc_subset_Ioi_self) $ nhds_within_le_of_mem $ Ioc_mem_nhds_within_Ioi $ left_mem_Ico.2 h @[simp] lemma nhds_within_Ioo_eq_nhds_within_Ioi {a b : α} (h : a < b) : 𝓝[Ioo a b] a = 𝓝[Ioi a] a := le_antisymm (nhds_within_mono _ Ioo_subset_Ioi_self) $ nhds_within_le_of_mem $ Ioo_mem_nhds_within_Ioi $ left_mem_Ico.2 h @[simp] lemma continuous_within_at_Ioc_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioc a b) a ↔ continuous_within_at f (Ioi a) a := by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Ioi h] @[simp] lemma continuous_within_at_Ioo_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioo a b) a ↔ continuous_within_at f (Ioi a) a := by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Ioi h] /-! #### Left neighborhoods, point excluded -/ lemma Ioo_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ioo a c ∈ 𝓝[Iio b] b := by simpa only [dual_Ioo] using @Ioo_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩ lemma Ico_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ico a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ico_self lemma Ioc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ioc_self lemma Icc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Icc_self @[simp] lemma nhds_within_Ico_eq_nhds_within_Iio {a b : α} (h : a < b) : 𝓝[Ico a b] b = 𝓝[Iio b] b := by simpa only [dual_Ioc] using @nhds_within_Ioc_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h @[simp] lemma nhds_within_Ioo_eq_nhds_within_Iio {a b : α} (h : a < b) : 𝓝[Ioo a b] b = 𝓝[Iio b] b := by simpa only [dual_Ioo] using @nhds_within_Ioo_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h @[simp] lemma continuous_within_at_Ico_iff_Iio [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ico a b) b ↔ continuous_within_at f (Iio b) b := by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Iio h] @[simp] lemma continuous_within_at_Ioo_iff_Iio [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioo a b) b ↔ continuous_within_at f (Iio b) b := by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Iio h] /-! #### Right neighborhoods, point included -/ lemma Ioo_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[Ici b] b := mem_nhds_within_of_mem_nhds $ mem_nhds_sets is_open_Ioo H lemma Ioc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) : Ioc a c ∈ 𝓝[Ici b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ici H) Ioo_subset_Ioc_self lemma Ico_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) : Ico a c ∈ 𝓝[Ici b] b := mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2, by simp only [inter_comm, Ici_inter_Iio, Ico_subset_Ico_left H.1]⟩ lemma Icc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) : Icc a c ∈ 𝓝[Ici b] b := mem_sets_of_superset (Ico_mem_nhds_within_Ici H) Ico_subset_Icc_self @[simp] lemma nhds_within_Icc_eq_nhds_within_Ici {a b : α} (h : a < b) : 𝓝[Icc a b] a = 𝓝[Ici a] a := le_antisymm (nhds_within_mono _ Icc_subset_Ici_self) $ nhds_within_le_of_mem $ Icc_mem_nhds_within_Ici $ left_mem_Ico.2 h @[simp] lemma nhds_within_Ico_eq_nhds_within_Ici {a b : α} (h : a < b) : 𝓝[Ico a b] a = 𝓝[Ici a] a := le_antisymm (nhds_within_mono _ (λ x, and.left)) $ nhds_within_le_of_mem $ Ico_mem_nhds_within_Ici $ left_mem_Ico.2 h @[simp] lemma continuous_within_at_Icc_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Icc a b) a ↔ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Ici h] @[simp] lemma continuous_within_at_Ico_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ico a b) a ↔ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Ici h] /-! #### Left neighborhoods, point included -/ lemma Ioo_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[Iic b] b := mem_nhds_within_of_mem_nhds $ mem_nhds_sets is_open_Ioo H lemma Ico_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) : Ico a c ∈ 𝓝[Iic b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iic H) Ioo_subset_Ico_self lemma Ioc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[Iic b] b := by simpa only [dual_Ico] using @Ico_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩ lemma Icc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[Iic b] b := mem_sets_of_superset (Ioc_mem_nhds_within_Iic H) Ioc_subset_Icc_self @[simp] lemma nhds_within_Icc_eq_nhds_within_Iic {a b : α} (h : a < b) : 𝓝[Icc a b] b = 𝓝[Iic b] b := by simpa only [dual_Icc] using @nhds_within_Icc_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h @[simp] lemma nhds_within_Ioc_eq_nhds_within_Iic {a b : α} (h : a < b) : 𝓝[Ioc a b] b = 𝓝[Iic b] b := by simpa only [dual_Ico] using @nhds_within_Ico_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h @[simp] lemma continuous_within_at_Icc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Icc a b) b ↔ continuous_within_at f (Iic b) b := by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Iic h] @[simp] lemma continuous_within_at_Ioc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioc a b) b ↔ continuous_within_at f (Iic b) b := by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Iic h] end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [order_closed_topology α] {f g : β → α} section variables [topological_space β] (hf : continuous f) (hg : continuous g) include hf hg lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := begin rw [frontier_eq_closure_inter_closure, closure_le_eq hf hg], rintros b ⟨hb₁, hb₂⟩, refine le_antisymm hb₁ (closure_lt_subset_le hg hf _), convert hb₂ using 2, simp only [not_le.symm], refl end lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] @[continuity] lemma continuous.min : continuous (λb, min (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb, continuous_if this hf hg @[continuity] lemma continuous.max : continuous (λb, max (f b) (g b)) := @continuous.min (order_dual α) _ _ _ _ _ _ _ hf hg end lemma tendsto.max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) := show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (max a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_fst.max continuous_snd) _ end (hf.prod_mk hg) lemma tendsto.min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) := show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (𝓝 (min a₁ a₂)), from tendsto.comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_fst.min continuous_snd) _ end (hf.prod_mk hg) end decidable_linear_order end order_closed_topology /-- The order topology on an ordered type is the topology generated by open intervals. We register it on a preorder, but it is mostly interesting in linear orders, where it is also order-closed. We define it as a mixin. If you want to introduce the order topology on a preorder, use `preorder.topology`. -/ class order_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = Ioi a ∨ s = Iio a}) /-- (Order) topology on a partial order `α` generated by the subbase of open intervals `(a, ∞) = { x ∣ a < x }, (-∞ , b) = {x ∣ x < b}` for all `a, b` in `α`. We do not register it as an instance as many ordered sets are already endowed with the same topology, most often in a non-defeq way though. Register as a local instance when necessary. -/ def preorder.topology (α : Type*) [preorder α] : topological_space α := generate_from {s : set α | ∃ (a : α), s = {b : α | a < b} ∨ s = {b : α | b < a}} section order_topology instance {α : Type*} [topological_space α] [partial_order α] [order_topology α] : order_topology (order_dual α) := ⟨by convert @order_topology.topology_eq_generate_intervals α _ _ _; conv in (_ ∨ _) { rw or.comm }; refl⟩ section partial_order variables [topological_space α] [partial_order α] [t : order_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = Ioi a ∨ s = Iio a} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a < x := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a ≤ x := (𝓝 b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x < b := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b := (𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_order (a : α) : 𝓝 a = (⨅b ∈ Iio a, 𝓟 (Ioi b)) ⊓ (⨅b ∈ Ioi a, 𝓟 (Iio b)) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_order {f : β → α} {a : α} {x : filter β} : tendsto f x (𝓝 a) ↔ (∀ a' < a, ∀ᶠ b in x, a' < f b) ∧ (∀ a' > a, ∀ᶠ b in x, f b < a') := by simp [nhds_eq_order a, tendsto_inf, tendsto_infi, tendsto_principal] instance tendsto_Icc_class_nhds (a : α) : tendsto_Ixx_class Icc (𝓝 a) (𝓝 a) := begin simp only [nhds_eq_order, infi_subtype'], refine ((has_basis_infi_principal_finite _).inf (has_basis_infi_principal_finite _)).tendsto_Ixx_class (λ s hs, _), refine (ord_connected_bInter _).inter (ord_connected_bInter _); intros _ _, exacts [ord_connected_Ioi, ord_connected_Iio] end instance tendsto_Ico_class_nhds (a : α) : tendsto_Ixx_class Ico (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ioc_class_nhds (a : α) : tendsto_Ixx_class Ioc (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_class_nhds (a : α) : tendsto_Ixx_class Ioo (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Icc_self) instance tendsto_Ixx_nhds_within (a : α) {s t : set α} {Ixx} [tendsto_Ixx_class Ixx (𝓝 a) (𝓝 a)] [tendsto_Ixx_class Ixx (𝓟 s) (𝓟 t)]: tendsto_Ixx_class Ixx (𝓝[s] a) (𝓝[t] a) := filter.tendsto_Ixx_class_inf /-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold eventually for the filter. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le' {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : ∀ᶠ b in b, g b ≤ f b) (hfh : ∀ᶠ b in b, f b ≤ h b) : tendsto f b (𝓝 a) := tendsto_order.2 ⟨assume a' h', have ∀ᶠ b in b, a' < g b, from (tendsto_order.1 hg).left a' h', by filter_upwards [this, hgf] assume a, lt_of_lt_of_le, assume a' h', have ∀ᶠ b in b, h b < a', from (tendsto_order.1 hh).right a' h', by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩ /-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold everywhere. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : g ≤ f) (hfh : f ≤ h) : tendsto f b (𝓝 a) := tendsto_of_tendsto_of_tendsto_of_le_of_le' hg hh (eventually_of_forall hgf) (eventually_of_forall hfh) lemma nhds_order_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : 𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), 𝓟 (Ioo l u)) := calc 𝓝 a = (⨅b<a, 𝓟 {c | b < c}) ⊓ (⨅b>a, 𝓟 {c | c < b}) : nhds_eq_order a ... = (⨅b<a, 𝓟 {c | b < c} ⊓ (⨅b>a, 𝓟 {c | c < b})) : binfi_inf hl ... = (⨅l<a, (⨅u>a, 𝓟 {c | c < u} ⊓ 𝓟 {c | l < c})) : begin congr, funext x, congr, funext hx, rw [inf_comm], apply binfi_inf hu end ... = _ : by simp [inter_comm]; refl lemma tendsto_order_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → ∀ᶠ b in x, l < f b ∧ f b < u) : tendsto f x (𝓝 a) := by rw [nhds_order_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order theorem induced_order_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [order_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @order_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, nhds_eq_order (f a)], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap_sets.2 ⟨{x | f b < x}, mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap_sets.2 ⟨{x | x < f b}, mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } }, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, end theorem induced_order_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [order_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @order_topology _ (induced f ta) _ := induced_order_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) lemma nhds_top_order [topological_space α] [order_top α] [order_topology α] : 𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), 𝓟 (Ioi l)) := by simp [nhds_eq_order (⊤:α)] lemma nhds_bot_order [topological_space α] [order_bot α] [order_topology α] : 𝓝 (⊥:α) = (⨅l (h₂ : ⊥ < l), 𝓟 (Iio l)) := by simp [nhds_eq_order (⊥:α)] section linear_order variables [topological_space α] [linear_order α] [order_topology α] lemma exists_Ioc_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {l : α} (hl : l < a) : ∃ l' ∈ Ico l a, Ioc l' a ⊆ s := begin rw [nhds_eq_order a] at hs, rcases hs with ⟨t₁, ht₁, t₂, ht₂, hts⟩, -- First we show that `t₂` includes `(-∞, a]`, so it suffices to show `(l', ∞) ⊆ t₁` suffices : ∃ l' ∈ Ico l a, Ioi l' ⊆ t₁, { have A : 𝓟 (Iic a) ≤ ⨅ b ∈ Ioi a, 𝓟 (Iio b), from (le_infi $ λ b, le_infi $ λ hb, principal_mono.2 $ Iic_subset_Iio.2 hb), have B : t₁ ∩ Iic a ⊆ s, from subset.trans (inter_subset_inter_right _ (A ht₂)) hts, from this.imp (λ l', Exists.imp $ λ hl' hl x hx, B ⟨hl hx.1, hx.2⟩) }, clear hts ht₂ t₂, -- Now we find `l` such that `(l', ∞) ⊆ t₁` letI := classical.DLO α, rw [mem_binfi] at ht₁, { rcases ht₁ with ⟨b, hb, hb'⟩, exact ⟨max b l, ⟨le_max_right _ _, max_lt hb hl⟩, λ x hx, hb' $ Ioi_subset_Ioi (le_max_left _ _) hx⟩ }, { intros b hb b' hb', simp only [mem_Iio] at hb hb', use [max b b', max_lt hb hb'], simp [le_refl] }, exact ⟨l, hl⟩ end lemma exists_Ico_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {u : α} (hu : a < u) : ∃ u' ∈ Ioc a u, Ico a u' ⊆ s := begin convert @exists_Ioc_subset_of_mem_nhds' (order_dual α) _ _ _ _ _ hs _ hu, ext, rw [dual_Ico, dual_Ioc] end lemma exists_Ioc_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ l, l < a) : ∃ l < a, Ioc l a ⊆ s := let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ioc_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.2, hl.snd⟩ lemma exists_Ico_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ u, a < u) : ∃ u (_ : a < u), Ico a u ⊆ s := let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ico_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.1, hl.snd⟩ lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) : s ∈ 𝓝 a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) := let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in have 𝓝 a = (⨅p : {l // l < a} × {u // a < u}, 𝓟 (Ioo p.1.val p.2.val)), by simp [nhds_order_unbounded hu hl, infi_subtype, infi_prod], iff.intro (assume hs, by rw [this] at hs; from infi_sets_induct hs ⟨l, u, hl', hu', by simp⟩ begin intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩, simp [set.subset_def], intros s₁ s₂ hs₁ l' hl' u' hu' hs₂, letI := classical.DLO α, refine ⟨max l l', _, min u u', _⟩; simp [*, lt_min_iff, max_lt_iff] {contextual := tt} end (assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩)) (assume ⟨l, u, hl, hu, h⟩, by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂)) lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete a₁ a₂ with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end @[priority 100] -- see Note [lower instance priority] instance order_topology.to_order_closed_topology : order_closed_topology α := { is_closed_le' := is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } lemma order_topology.t2_space : t2_space α := by apply_instance @[priority 100] -- see Note [lower instance priority] instance order_topology.regular_space : regular_space α := { regular := assume s a hs ha, have hs' : sᶜ ∈ 𝓝 a, from mem_nhds_sets hs ha, have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ 𝓝[t] a = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := exists_Ioc_subset_of_mem_nhds hs' h in match dense_or_discrete l a with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _, assume c hcs hca, show c < b, from lt_of_not_ge $ assume hbc, h ⟨lt_of_lt_of_le hb₁ hbc, le_of_lt hca⟩ hcs, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $ assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $ assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩ end) (assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, nhds_within_empty _⟩), let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ 𝓝[t] a = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := exists_Ico_subset_of_mem_nhds hs' h in match dense_or_discrete a u with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _, assume c hcs hca, show c > b, from lt_of_not_ge $ assume hbc, h ⟨le_of_lt hca, lt_of_le_of_lt hbc hb₂⟩ hcs, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $ assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $ assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩ end) (assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, nhds_within_empty _⟩), let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in ⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o, assume x hx, have x ≠ a, from assume eq, ha $ eq ▸ hx, (ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx), by rw [nhds_within_union, ht₁a, ht₂a, bot_sup_eq]⟩, ..order_topology.t2_space } /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`, provided `a` is neither a bottom element nor a top element. -/ lemma mem_nhds_iff_exists_Ioo_subset' {a l' u' : α} {s : set α} (hl' : l' < a) (hu' : a < u') : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := begin split, { assume h, rcases exists_Ico_subset_of_mem_nhds' h hu' with ⟨u, au, hu⟩, rcases exists_Ioc_subset_of_mem_nhds' h hl' with ⟨l, la, hl⟩, refine ⟨l, u, ⟨la.2, au.1⟩, λx hx, _⟩, cases le_total a x with hax hax, { exact hu ⟨hax, hx.2⟩ }, { exact hl ⟨hx.1, hax⟩ } }, { rintros ⟨l, u, ha, h⟩, apply mem_sets_of_superset (mem_nhds_sets is_open_Ioo ha) h } end /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`. -/ lemma mem_nhds_iff_exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := let ⟨l', hl'⟩ := no_bot a in let ⟨u', hu'⟩ := no_top a in mem_nhds_iff_exists_Ioo_subset' hl' hu' lemma Iio_mem_nhds {a b : α} (h : a < b) : Iio b ∈ 𝓝 a := mem_nhds_sets is_open_Iio h lemma Ioi_mem_nhds {a b : α} (h : a < b) : Ioi a ∈ 𝓝 b := mem_nhds_sets is_open_Ioi h lemma Ioo_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioo a b ∈ 𝓝 x := mem_nhds_sets is_open_Ioo ⟨ha, hb⟩ lemma disjoint_nhds_at_top [no_top_order α] (x : α) : disjoint (𝓝 x) at_top := begin rw filter.disjoint_iff, cases no_top x with a ha, use [Iio a, Ici a, Iio_mem_nhds ha, mem_at_top a], rw [inter_comm, Ici_inter_Iio, Ico_self] end @[simp] lemma inf_nhds_at_top [no_top_order α] (x : α) : 𝓝 x ⊓ at_top = ⊥ := disjoint_iff.1 (disjoint_nhds_at_top x) lemma disjoint_nhds_at_bot [no_bot_order α] (x : α) : disjoint (𝓝 x) at_bot := @disjoint_nhds_at_top (order_dual α) _ _ _ _ x @[simp] lemma inf_nhds_at_bot [no_bot_order α] (x : α) : 𝓝 x ⊓ at_bot = ⊥ := @inf_nhds_at_top (order_dual α) _ _ _ _ x lemma not_tendsto_nhds_of_tendsto_at_top [no_top_order α] {F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_top) (x : α) : ¬ tendsto f F (𝓝 x) := hf.not_tendsto (disjoint_nhds_at_top x).symm lemma not_tendsto_at_top_of_tendsto_nhds [no_top_order α] {F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) : ¬ tendsto f F at_top := hf.not_tendsto (disjoint_nhds_at_top x) lemma not_tendsto_nhds_of_tendsto_at_bot [no_bot_order α] {F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_bot) (x : α) : ¬ tendsto f F (𝓝 x) := hf.not_tendsto (disjoint_nhds_at_bot x).symm lemma not_tendsto_at_bot_of_tendsto_nhds [no_bot_order α] {F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) : ¬ tendsto f F at_bot := hf.not_tendsto (disjoint_nhds_at_bot x) /-! ### Neighborhoods to the left and to the right on an `order_topology` We've seen some properties of left and right neighborhood of a point in an `order_closed_topology`. In an `order_topology`, such neighborhoods can be characterized as the sets containing suitable intervals to the right or to the left of `a`. We give now these characterizations. -/ -- NB: If you extend the list, append to the end please to avoid breaking the API /-- The following statements are equivalent: 0. `s` is a neighborhood of `a` within `(a, +∞)` 1. `s` is a neighborhood of `a` within `(a, b]` 2. `s` is a neighborhood of `a` within `(a, b)` 3. `s` includes `(a, u)` for some `u ∈ (a, b]` 4. `s` includes `(a, u)` for some `u > a` -/ lemma tfae_mem_nhds_within_Ioi {a b : α} (hab : a < b) (s : set α) : tfae [s ∈ 𝓝[Ioi a] a, -- 0 : `s` is a neighborhood of `a` within `(a, +∞)` s ∈ 𝓝[Ioc a b] a, -- 1 : `s` is a neighborhood of `a` within `(a, b]` s ∈ 𝓝[Ioo a b] a, -- 2 : `s` is a neighborhood of `a` within `(a, b)` ∃ u ∈ Ioc a b, Ioo a u ⊆ s, -- 3 : `s` includes `(a, u)` for some `u ∈ (a, b]` ∃ u ∈ Ioi a, Ioo a u ⊆ s] := -- 4 : `s` includes `(a, u)` for some `u > a` begin tfae_have : 1 ↔ 2, by rw [nhds_within_Ioc_eq_nhds_within_Ioi hab], tfae_have : 1 ↔ 3, by rw [nhds_within_Ioo_eq_nhds_within_Ioi hab], tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩, tfae_have : 5 → 1, { rintros ⟨u, hau, hu⟩, exact mem_sets_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_refl a, hau⟩) hu }, tfae_have : 1 → 4, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨hu ⟨le_of_lt hx.1, hx.2⟩, _⟩, exact hx.1 }, tfae_finish end lemma mem_nhds_within_Ioi_iff_exists_mem_Ioc_Ioo_subset {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioc a u', Ioo a u ⊆ s := (tfae_mem_nhds_within_Ioi hu' s).out 0 3 /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u < u'`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s := (tfae_mem_nhds_within_Ioi hu' s).out 0 4 /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset [no_top_order α] {a : α} {s : set α} : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s := let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ioi_iff_exists_Ioo_subset' hu' /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u]` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioc_subset [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioc a u ⊆ s := begin rw mem_nhds_within_Ioi_iff_exists_Ioo_subset, split, { rintros ⟨u, au, as⟩, rcases dense au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ioo_subset_Ioc_self as⟩ } end /-- The following statements are equivalent: 0. `s` is a neighborhood of `b` within `(-∞, b)` 1. `s` is a neighborhood of `b` within `[a, b)` 2. `s` is a neighborhood of `b` within `(a, b)` 3. `s` includes `(l, b)` for some `l ∈ [a, b)` 4. `s` includes `(l, b)` for some `l < b` -/ lemma tfae_mem_nhds_within_Iio {a b : α} (h : a < b) (s : set α) : tfae [s ∈ 𝓝[Iio b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b)` s ∈ 𝓝[Ico a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b)` s ∈ 𝓝[Ioo a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b)` ∃ l ∈ Ico a b, Ioo l b ⊆ s, -- 3 : `s` includes `(l, b)` for some `l ∈ [a, b)` ∃ l ∈ Iio b, Ioo l b ⊆ s] := -- 4 : `s` includes `(l, b)` for some `l < b` begin have := @tfae_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ h s, -- If we call `convert` here, it generates wrong equations, so we need to simplify first simp only [exists_prop] at this ⊢, rw [dual_Ioi, dual_Ioc, dual_Ioo] at this, convert this; ext l; rw [dual_Ioo] end lemma mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Ico l' a, Ioo l a ⊆ s := (tfae_mem_nhds_within_Iio hl' s).out 0 3 /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s := (tfae_mem_nhds_within_Iio hl' s).out 0 4 /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s := let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iio_iff_exists_Ioo_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `[l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ico_subset [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ico l a ⊆ s := begin convert @mem_nhds_within_Ioi_iff_exists_Ioc_subset (order_dual α) _ _ _ _ _ _ _, simp only [dual_Ioc], refl end /-- The following statements are equivalent: 0. `s` is a neighborhood of `a` within `[a, +∞)` 1. `s` is a neighborhood of `a` within `[a, b]` 2. `s` is a neighborhood of `a` within `[a, b)` 3. `s` includes `[a, u)` for some `u ∈ (a, b]` 4. `s` includes `[a, u)` for some `u > a` -/ lemma tfae_mem_nhds_within_Ici {a b : α} (hab : a < b) (s : set α) : tfae [s ∈ 𝓝[Ici a] a, -- 0 : `s` is a neighborhood of `a` within `[a, +∞)` s ∈ 𝓝[Icc a b] a, -- 1 : `s` is a neighborhood of `a` within `[a, b]` s ∈ 𝓝[Ico a b] a, -- 2 : `s` is a neighborhood of `a` within `[a, b)` ∃ u ∈ Ioc a b, Ico a u ⊆ s, -- 3 : `s` includes `[a, u)` for some `u ∈ (a, b]` ∃ u ∈ Ioi a, Ico a u ⊆ s] := -- 4 : `s` includes `[a, u)` for some `u > a` begin tfae_have : 1 ↔ 2, by rw [nhds_within_Icc_eq_nhds_within_Ici hab], tfae_have : 1 ↔ 3, by rw [nhds_within_Ico_eq_nhds_within_Ici hab], tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩, tfae_have : 5 → 1, { rintros ⟨u, hau, hu⟩, exact mem_sets_of_superset (Ico_mem_nhds_within_Ici ⟨le_refl a, hau⟩) hu }, tfae_have : 1 → 4, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨hu ⟨hx.1, hx.2⟩, _⟩, exact hx.1 }, tfae_finish end lemma mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioc a u', Ico a u ⊆ s := (tfae_mem_nhds_within_Ici hu' s).out 0 3 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u < u'`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s := (tfae_mem_nhds_within_Ici hu' s).out 0 4 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset [no_top_order α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s := let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ici_iff_exists_Ico_subset' hu' /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Icc_subset' [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Icc a u ⊆ s := begin rw mem_nhds_within_Ici_iff_exists_Ico_subset, split, { rintros ⟨u, au, as⟩, rcases dense au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ } end /-- The following statements are equivalent: 0. `s` is a neighborhood of `b` within `(-∞, b]` 1. `s` is a neighborhood of `b` within `[a, b]` 2. `s` is a neighborhood of `b` within `(a, b]` 3. `s` includes `(l, b]` for some `l ∈ [a, b)` 4. `s` includes `(l, b]` for some `l < b` -/ lemma tfae_mem_nhds_within_Iic {a b : α} (h : a < b) (s : set α) : tfae [s ∈ 𝓝[Iic b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b]` s ∈ 𝓝[Icc a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b]` s ∈ 𝓝[Ioc a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b]` ∃ l ∈ Ico a b, Ioc l b ⊆ s, -- 3 : `s` includes `(l, b]` for some `l ∈ [a, b)` ∃ l ∈ Iio b, Ioc l b ⊆ s] := -- 4 : `s` includes `(l, b]` for some `l < b` begin have := @tfae_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ h s, -- If we call `convert` here, it generates wrong equations, so we need to simplify first simp only [exists_prop] at this ⊢, rw [dual_Icc, dual_Ioc, dual_Ioi] at this, convert this; ext l; rw [dual_Ico] end lemma mem_nhds_within_Iic_iff_exists_mem_Ico_Ioc_subset {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Ico l' a, Ioc l a ⊆ s := (tfae_mem_nhds_within_Iic hl' s).out 0 3 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s := (tfae_mem_nhds_within_Iic hl' s).out 0 4 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s := let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iic_iff_exists_Ioc_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Icc_subset' [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Icc l a ⊆ s := begin convert @mem_nhds_within_Ici_iff_exists_Icc_subset' (order_dual α) _ _ _ _ _ _ _, simp_rw (show ∀ u : order_dual α, @Icc (order_dual α) _ a u = @Icc α _ u a, from λ u, dual_Icc), refl, end /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Icc_subset [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u, a < u ∧ Icc a u ⊆ s := begin rw mem_nhds_within_Ici_iff_exists_Ico_subset, split, { rintros ⟨u, au, as⟩, rcases dense au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ } end /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Icc_subset [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l, l < a ∧ Icc l a ⊆ s := begin rw mem_nhds_within_Iic_iff_exists_Ioc_subset, split, { rintros ⟨l, la, as⟩, rcases dense la with ⟨v, hv⟩, refine ⟨v, hv.2, λx hx, as ⟨lt_of_lt_of_le hv.1 hx.1, hx.2⟩⟩, }, { rintros ⟨l, la, as⟩, exact ⟨l, la, subset.trans Ioc_subset_Icc_self as⟩ } end section functions variables [topological_space β] [linear_order β] [order_topology β] /-- If `f : α → β` is strictly monotone and surjective, it is everywhere right-continuous. Superseded later in this file by `continuous_of_strict_mono_surjective` (same assumptions). -/ lemma continuous_right_of_strict_mono_surjective {f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) : continuous_within_at f (Ici a) a := begin have ha : a ∈ Ici a := left_mem_Ici, intros s hs, by_cases hfa_top : ∃ p, f a < p, { obtain ⟨q, hq, hqs⟩ : ∃ q ∈ Ioi (f a), Ico (f a) q ⊆ s := exists_Ico_subset_of_mem_nhds hs hfa_top, refine mem_sets_of_superset (mem_map.2 _) hqs, have h_surj_on := surj_on_Ici_of_monotone_surjective h_mono.monotone h_surj a, rcases h_surj_on (Ioi_subset_Ici_self hq) with ⟨x, hx, rfl⟩, rcases eq_or_lt_of_le hx with rfl|hax, { exact (lt_irrefl _ hq).elim }, refine mem_sets_of_superset (Ico_mem_nhds_within_Ici (left_mem_Ico.2 hax)) _, intros z hz, exact ⟨h_mono.monotone hz.1, h_mono hz.2⟩ }, { push_neg at hfa_top, have ha_top : ∀ x : α, x ≤ a := strict_mono.top_preimage_top h_mono hfa_top, rw [Ici_singleton_of_top ha_top, nhds_within_eq_map_subtype_coe (mem_singleton a), nhds_discrete {x : α // x ∈ {a}}], { exact mem_pure_sets.mpr (mem_of_nhds hs) }, { apply_instance } } end /-- If `f : α → β` is strictly monotone and surjective, it is everywhere left-continuous. Superseded later in this file by `continuous_of_strict_mono_surjective` (same assumptions). -/ lemma continuous_left_of_strict_mono_surjective {f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) : continuous_within_at f (Iic a) a := begin apply @continuous_right_of_strict_mono_surjective (order_dual α) (order_dual β), { exact λ x y hxy, h_mono hxy }, { simpa only [dual_Icc] } end end functions end linear_order section linear_ordered_ring variables [topological_space α] [linear_ordered_ring α] [order_topology α] variables {l : filter β} {f g : β → α} /- TODO The theorems in this section ought to be written in the context of linearly ordered (additive) commutative groups rather than linearly ordered rings; however, the former concept does not currently exist in mathlib. -/ /-- In a linearly ordered ring with the order topology, if `f` tends to `C` and `g` tends to `at_top` then `f + g` tends to `at_top`. -/ lemma tendsto_at_top_add_tendsto_left {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := begin obtain ⟨C', hC'⟩ : ∃ C', C' < C := no_bot C, refine tendsto_at_top_add_left_of_le' _ C' _ hg, rw tendsto_order at hf, exact (hf.1 C' hC').mp (eventually_of_forall (λ x hx, le_of_lt hx)) end /-- In a linearly ordered ring with the order topology, if `f` tends to `C` and `g` tends to `at_bot` then `f + g` tends to `at_bot`. -/ lemma tendsto_at_bot_add_tendsto_left {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := begin obtain ⟨C', hC'⟩ : ∃ C', C < C' := no_top C, refine tendsto_at_bot_add_left_of_ge' _ C' _ hg, rw tendsto_order at hf, exact (hf.2 C' hC').mp (eventually_of_forall (λ x hx, le_of_lt hx)) end /-- In a linearly ordered ring with the order topology, if `f` tends to `at_top` and `g` tends to `C` then `f + g` tends to `at_top`. -/ lemma tendsto_at_top_add_tendsto_right {C : α} (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, f x + g x) l at_top := begin convert tendsto_at_top_add_tendsto_left hg hf, ext, exact add_comm _ _, end /-- In a linearly ordered ring with the order topology, if `f` tends to `at_bot` and `g` tends to `C` then `f + g` tends to `at_bot`. -/ lemma tendsto_at_bot_add_tendsto_right {C : α} (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, f x + g x) l at_bot := begin convert tendsto_at_bot_add_tendsto_left hg hf, ext, exact add_comm _ _, end end linear_ordered_ring lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section topological_add_group variables [topological_space α] [ordered_add_comm_group α] [topological_add_group α] lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) := have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg, by rw [preimage_neg]; exact (subset.antisymm (image_closure_subset_closure_image continuous_neg) $ calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) : by rw [←image_comp, this, image_id] ... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) : monotone_image $ image_closure_subset_closure_image continuous_neg ... = _ : by rw [←image_comp, this, image_id]) end topological_add_group section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [order_topology α] [order_topology β] lemma is_lub.nhds_within_ne_bot {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : ne_bot (𝓝[s] a) := let ⟨a', ha'⟩ := hs in forall_sets_nonempty_iff_ne_bot.mp $ assume t ht, let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in by_cases (assume h : a = a', have a ∈ t₁, from mem_of_nhds ht₁, have a ∈ t₂, from ht₂ $ by rwa [h], ⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩) (assume : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left ‹a' ∈ s›) this.symm, let ⟨l, hl, hlt₁⟩ := exists_Ioc_subset_of_mem_nhds ht₁ ⟨a', this⟩ in have ∃a'∈s, l < a', from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a', have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩, have ¬ l < a, from not_lt.2 $ ha.right this, this ‹l < a›, let ⟨a', ha', ha'l⟩ := this in have a' ∈ t₁, from hlt₁ ⟨‹l < a'›, ha.left ha'⟩, ⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩) lemma is_glb.nhds_within_ne_bot : ∀ {a : α} {s : set α}, is_glb s a → s.nonempty → ne_bot (𝓝[s] a) := @is_lub.nhds_within_ne_bot (order_dual α) _ _ _ lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f) [ne_bot (f ⊓ 𝓝 a)] : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ 𝓝 a, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := nonempty_of_mem_sets this in have b < b, from lt_of_lt_of_le hxb $ hb hxs, lt_irrefl b this⟩ lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α}, a ∈ lower_bounds s → s ∈ f → ne_bot (f ⊓ 𝓝 a) → is_glb s a := @is_lub_of_mem_nhds (order_dual α) _ _ _ lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s.nonempty) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : is_lub (f '' s) b := have hnbot : ne_bot (𝓝[s] a), from ha.nhds_within_ne_bot hs, have ∀a'∈s, ¬ b < f a', from assume a' ha' h, have ∀ᶠ x in 𝓝 b, x < f a', from mem_nhds_sets (is_open_gt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a < f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left ha') h.symm, have {x | a' < x} ∈ 𝓝 a, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ 𝓝 a, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ 𝓝[s] a, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := hnbot.nonempty_of_mem this in have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁, lt_irrefl _ (lt_of_le_of_lt ha'x hxa')), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', by exactI (le_of_tendsto hb $ mem_inf_sets_of_right $ assume x hx, hb' $ mem_image_of_mem _ hx)) lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ f s a b (λ x hx y hy, hf y hy x hx) lemma is_glb_of_is_lub_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma is_lub_of_is_glb_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_lub (f '' s) b := @is_glb_of_is_glb_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : a ∈ closure s := by rw closure_eq_cluster_pts; exact ha.nhds_within_ne_bot hs lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s := by rw ←sc.closure_eq; exact mem_closure_of_is_lub ha hs lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : a ∈ closure s := by rw closure_eq_cluster_pts; exact ha.nhds_within_ne_bot hs lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s := by rw ←sc.closure_eq; exact mem_closure_of_is_glb ha hs /-- A compact set is bounded below -/ lemma is_compact.bdd_below {α : Type u} [topological_space α] [linear_order α] [order_closed_topology α] [nonempty α] {s : set α} (hs : is_compact s) : bdd_below s := begin by_contra H, letI := classical.DLO α, rcases hs.elim_finite_subcover_image (λ x (_ : x ∈ s), @is_open_Ioi _ _ _ _ x) _ with ⟨t, st, ft, ht⟩, { refine H (ft.bdd_below.imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC hx) (le_of_lt xy) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma is_compact.bdd_above {α : Type u} [topological_space α] [linear_order α] [order_topology α] : Π [nonempty α] {s : set α}, is_compact s → bdd_above s := @is_compact.bdd_below (order_dual α) _ _ _ end order_topology section linear_order variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α] /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`, unless `a` is a top element. -/ lemma closure_Ioi' {a b : α} (hab : a < b) : closure (Ioi a) = Ici a := begin apply subset.antisymm, { exact closure_minimal Ioi_subset_Ici_self is_closed_Ici }, { assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_glb is_glb_Ioi ⟨_, hab⟩ }, { exact subset_closure (lt_of_le_of_ne hx (ne.symm h)) } } end /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`. -/ @[simp] lemma closure_Ioi (a : α) [no_top_order α] : closure (Ioi a) = Ici a := let ⟨b, hb⟩ := no_top a in closure_Ioi' hb /-- The closure of the interval `(-∞, a)` is the closed interval `(-∞, a]`, unless `a` is a bottom element. -/ lemma closure_Iio' {a b : α} (hab : b < a) : closure (Iio a) = Iic a := begin apply subset.antisymm, { exact closure_minimal Iio_subset_Iic_self is_closed_Iic }, { assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_lub is_lub_Iio ⟨_, hab⟩ }, { apply subset_closure, by simpa [h] using lt_or_eq_of_le hx } } end /-- The closure of the interval `(-∞, a)` is the interval `(-∞, a]`. -/ @[simp] lemma closure_Iio (a : α) [no_bot_order α] : closure (Iio a) = Iic a := let ⟨b, hb⟩ := no_bot a in closure_Iio' hb /-- The closure of the open interval `(a, b)` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ioo {a b : α} (hab : a < b) : closure (Ioo a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ioo_subset_Icc_self is_closed_Icc }, { have hab' : (Ioo a b).nonempty, from nonempty_Ioo.2 hab, assume x hx, by_cases h : x = a, { rw h, exact mem_closure_of_is_glb (is_glb_Ioo hab) hab' }, by_cases h' : x = b, { rw h', refine mem_closure_of_is_lub (is_lub_Ioo hab) hab' }, exact subset_closure ⟨lt_of_le_of_ne hx.1 (ne.symm h), by simpa [h'] using lt_or_eq_of_le hx.2⟩ } end /-- The closure of the interval `(a, b]` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ioc {a b : α} (hab : a < b) : closure (Ioc a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ioc_subset_Icc_self is_closed_Icc }, { apply subset.trans _ (closure_mono Ioo_subset_Ioc_self), rw closure_Ioo hab } end /-- The closure of the interval `[a, b)` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ico {a b : α} (hab : a < b) : closure (Ico a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ico_subset_Icc_self is_closed_Icc }, { apply subset.trans _ (closure_mono Ioo_subset_Ico_self), rw closure_Ioo hab } end @[simp] lemma interior_Ici [no_bot_order α] {a : α} : interior (Ici a) = Ioi a := by rw [← compl_Iio, interior_compl, closure_Iio, compl_Iic] @[simp] lemma interior_Iic [no_top_order α] {a : α} : interior (Iic a) = Iio a := by rw [← compl_Ioi, interior_compl, closure_Ioi, compl_Ici] @[simp] lemma interior_Icc [no_bot_order α] [no_top_order α] {a b : α}: interior (Icc a b) = Ioo a b := by rw [← Ici_inter_Iic, interior_inter, interior_Ici, interior_Iic, Ioi_inter_Iio] @[simp] lemma interior_Ico [no_bot_order α] {a b : α} : interior (Ico a b) = Ioo a b := by rw [← Ici_inter_Iio, interior_inter, interior_Ici, interior_Iio, Ioi_inter_Iio] @[simp] lemma interior_Ioc [no_top_order α] {a b : α} : interior (Ioc a b) = Ioo a b := by rw [← Ioi_inter_Iic, interior_inter, interior_Ioi, interior_Iic, Ioi_inter_Iio] @[simp] lemma frontier_Ici [no_bot_order α] {a : α} : frontier (Ici a) = {a} := by simp [frontier] @[simp] lemma frontier_Iic [no_top_order α] {a : α} : frontier (Iic a) = {a} := by simp [frontier] @[simp] lemma frontier_Ioi [no_top_order α] {a : α} : frontier (Ioi a) = {a} := by simp [frontier] @[simp] lemma frontier_Iio [no_bot_order α] {a : α} : frontier (Iio a) = {a} := by simp [frontier] @[simp] lemma frontier_Icc [no_bot_order α] [no_top_order α] {a b : α} (h : a < b) : frontier (Icc a b) = {a, b} := by simp [frontier, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ioo {a b : α} (h : a < b) : frontier (Ioo a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ico [no_bot_order α] {a b : α} (h : a < b) : frontier (Ico a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ioc [no_top_order α] {a b : α} (h : a < b) : frontier (Ioc a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] lemma nhds_within_Ioi_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : a ≤ b) : ne_bot (𝓝[Ioi a] b) := mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Ioi' H₁], exact H₂ } lemma nhds_within_Ioi_ne_bot [no_top_order α] {a b : α} (H : a ≤ b) : ne_bot (𝓝[Ioi a] b) := let ⟨c, hc⟩ := no_top a in nhds_within_Ioi_ne_bot' hc H lemma nhds_within_Ioi_self_ne_bot' {a b : α} (H : a < b) : ne_bot (𝓝[Ioi a] a) := nhds_within_Ioi_ne_bot' H (le_refl a) @[instance] lemma nhds_within_Ioi_self_ne_bot [no_top_order α] (a : α) : ne_bot (𝓝[Ioi a] a) := nhds_within_Ioi_ne_bot (le_refl a) lemma nhds_within_Iio_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : b ≤ c) : ne_bot (𝓝[Iio c] b) := mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Iio' H₁], exact H₂ } lemma nhds_within_Iio_ne_bot [no_bot_order α] {a b : α} (H : a ≤ b) : ne_bot (𝓝[Iio b] a) := let ⟨c, hc⟩ := no_bot b in nhds_within_Iio_ne_bot' hc H lemma nhds_within_Iio_self_ne_bot' {a b : α} (H : a < b) : ne_bot (𝓝[Iio b] b) := nhds_within_Iio_ne_bot' H (le_refl b) @[instance] lemma nhds_within_Iio_self_ne_bot [no_bot_order α] (a : α) : ne_bot (𝓝[Iio a] a) := nhds_within_Iio_ne_bot (le_refl a) end linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [order_topology α] [complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_Sup _) hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_Inf _) hs lemma is_closed.Sup_mem {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_Sup _) hs hc lemma is_closed.Inf_mem {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_Inf _) hs hc /-- A monotone function continuous at the supremum of a nonempty set sends this supremum to the supremum of the image of this set. -/ lemma map_Sup_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (hs : s.nonempty) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub_of_is_lub_of_tendsto (is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Mf xy) (is_lub_Sup _) hs $ Cf.mono_left inf_le_left).Sup_eq.symm /-- A monotone function `s` sending `bot` to `bot` and continuous at the supremum of a set sends this supremum to the supremum of the image of this set. -/ lemma map_Sup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (fbot : f ⊥ = ⊥) : f (Sup s) = Sup (f '' s) := begin cases s.eq_empty_or_nonempty with h h, { simp [h, fbot] }, { exact map_Sup_of_continuous_at_of_monotone' Cf Mf h } end /-- A monotone function continuous at the indexed supremum over a nonempty `Sort` sends this indexed supremum to the indexed supremum of the composition. -/ lemma map_supr_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Mf : monotone f) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_Sup_of_continuous_at_of_monotone' Cf Mf (range_nonempty g), ← range_comp, supr] /-- If a monotone function sending `bot` to `bot` is continuous at the indexed supremum over a `Sort`, then it sends this indexed supremum to the indexed supremum of the composition. -/ lemma map_supr_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Mf : monotone f) (fbot : f ⊥ = ⊥) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_Sup_of_continuous_at_of_monotone Cf Mf fbot, ← range_comp, supr] /-- A monotone function continuous at the infimum of a nonempty set sends this infimum to the infimum of the image of this set. -/ lemma map_Inf_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := @map_Sup_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual hs /-- A monotone function `s` sending `top` to `top` and continuous at the infimum of a set sends this infimum to the infimum of the image of this set. -/ lemma map_Inf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (ftop : f ⊤ = ⊤) : f (Inf s) = Inf (f '' s) := @map_Sup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual ftop /-- A monotone function continuous at the indexed infimum over a nonempty `Sort` sends this indexed infimum to the indexed infimum of the composition. -/ lemma map_infi_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Mf : monotone f) : f (⨅ i, g i) = ⨅ i, f (g i) := @map_supr_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ ι _ f g Cf Mf.order_dual /-- If a monotone function sending `top` to `top` is continuous at the indexed infimum over a `Sort`, then it sends this indexed infimum to the indexed infimum of the composition. -/ lemma map_infi_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Mf : monotone f) (ftop : f ⊤ = ⊤) : f (infi g) = infi (f ∘ g) := @map_supr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ ι f g Cf Mf.order_dual ftop end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ] lemma cSup_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_cSup hs B) hs lemma cInf_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_cInf hs B) hs lemma is_closed.cSup_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc lemma is_closed.cInf_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc /-- If a monotone function is continuous at the supremum of a nonempty bounded above set `s`, then it sends this supremum to the supremum of the image of `s`. -/ lemma map_cSup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (ne : s.nonempty) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine ((is_lub_cSup (ne.image f) (Mf.map_bdd_above H)).unique _).symm, refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Mf xy) (is_lub_cSup ne H) ne _, exact Cf.mono_left inf_le_left end /-- If a monotone function is continuous at the indexed supremum of a bounded function on a nonempty `Sort`, then it sends this supremum to the supremum of the composition. -/ lemma map_csupr_of_continuous_at_of_monotone {f : α → β} {g : γ → α} (Cf : continuous_at f (⨆ i, g i)) (Mf : monotone f) (H : bdd_above (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_cSup_of_continuous_at_of_monotone Cf Mf (range_nonempty _) H, ← range_comp, supr] /-- If a monotone function is continuous at the infimum of a nonempty bounded below set `s`, then it sends this infimum to the infimum of the image of `s`. -/ lemma map_cInf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (ne : s.nonempty) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := @map_cSup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual ne H /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete linear order, under a boundedness assumption. -/ lemma map_cinfi_of_continuous_at_of_monotone {f : α → β} {g : γ → α} (Cf : continuous_at f (⨅ i, g i)) (Mf : monotone f) (H : bdd_below (range g)) : f (⨅ i, g i) = ⨅ i, f (g i) := @map_csupr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ _ _ _ _ Cf Mf.order_dual H /-- A bounded connected subset of a conditionally complete linear order includes the open interval `(Inf s, Sup s)`. -/ lemma is_connected.Ioo_cInf_cSup_subset {s : set α} (hs : is_connected s) (hb : bdd_below s) (ha : bdd_above s) : Ioo (Inf s) (Sup s) ⊆ s := λ x hx, let ⟨y, ys, hy⟩ := (is_glb_lt_iff (is_glb_cInf hs.nonempty hb)).1 hx.1 in let ⟨z, zs, hz⟩ := (lt_is_lub_iff (is_lub_cSup hs.nonempty ha)).1 hx.2 in hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ lemma eq_Icc_cInf_cSup_of_connected_bdd_closed {s : set α} (hc : is_connected s) (hb : bdd_below s) (ha : bdd_above s) (hcl : is_closed s) : s = Icc (Inf s) (Sup s) := subset.antisymm (subset_Icc_cInf_cSup hb ha) $ hc.Icc_subset (hcl.cInf_mem hc.nonempty hb) (hcl.cSup_mem hc.nonempty ha) lemma is_preconnected.Ioi_cInf_subset {s : set α} (hs : is_preconnected s) (hb : bdd_below s) (ha : ¬bdd_above s) : Ioi (Inf s) ⊆ s := begin have sne : s.nonempty := @nonempty_of_not_bdd_above α _ s ⟨Inf ∅⟩ ha, intros x hx, obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := (is_glb_lt_iff (is_glb_cInf sne hb)).1 hx, obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x, exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ end lemma is_preconnected.Iio_cSup_subset {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s) (ha : bdd_above s) : Iio (Sup s) ⊆ s := @is_preconnected.Ioi_cInf_subset (order_dual α) _ _ _ s hs ha hb /-- A preconnected set in a conditionally complete linear order is either one of the intervals `[Inf s, Sup s]`, `[Inf s, Sup s)`, `(Inf s, Sup s]`, `(Inf s, Sup s)`, `[Inf s, +∞)`, `(Inf s, +∞)`, `(-∞, Sup s]`, `(-∞, Sup s)`, `(-∞, +∞)`, or `∅`. The converse statement requires `α` to be densely ordererd. -/ lemma is_preconnected.mem_intervals {s : set α} (hs : is_preconnected s) : s ∈ ({Icc (Inf s) (Sup s), Ico (Inf s) (Sup s), Ioc (Inf s) (Sup s), Ioo (Inf s) (Sup s), Ici (Inf s), Ioi (Inf s), Iic (Sup s), Iio (Sup s), univ, ∅} : set (set α)) := begin rcases s.eq_empty_or_nonempty with rfl|hne, { apply_rules [or.inr, mem_singleton] }, have hs' : is_connected s := ⟨hne, hs⟩, by_cases hb : bdd_below s; by_cases ha : bdd_above s, { rcases mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset (hs'.Ioo_cInf_cSup_subset hb ha) (subset_Icc_cInf_cSup hb ha) with hs|hs|hs|hs, { exact (or.inl hs) }, { exact (or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inr $ or.inl hs) } }, { refine (or.inr $ or.inr $ or.inr $ or.inr _), cases mem_Ici_Ioi_of_subset_of_subset (hs.Ioi_cInf_subset hb ha) (λ x hx, cInf_le hb hx) with hs hs, { exact or.inl hs }, { exact or.inr (or.inl hs) } }, { iterate 6 { apply or.inr }, cases mem_Iic_Iio_of_subset_of_subset (hs.Iio_cSup_subset hb ha) (λ x hx, le_cSup ha hx) with hs hs, { exact or.inl hs }, { exact or.inr (or.inl hs) } }, { iterate 8 { apply or.inr }, exact or.inl (hs.eq_univ_of_unbounded hb ha) } end /-- A preconnected set is either one of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`, `Iic`, `Iio`, or `univ`, or `∅`. The converse statement requires `α` to be densely ordererd. Though one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of possible cases to improve readability. -/ lemma set_of_is_preconnected_subset_of_ordered : {s : set α | is_preconnected s} ⊆ -- bounded intervals (range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪ -- unbounded intervals and `univ` (range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) := begin intros s hs, rcases hs.mem_intervals with hs|hs|hs|hs|hs|hs|hs|hs|hs|hs, { exact (or.inl $ or.inl $ or.inl $ or.inl ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inl ⟨Inf s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inr ⟨Inf s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) }, { exact (or.inr $ or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inr hs) } end /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and the set `s ∩ [a, b)` has no maximal point, then `b ∈ s`. -/ lemma is_closed.mem_of_ge_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hab : a ≤ b) (hgt : ∀ x ∈ s ∩ Ico a b, (s ∩ Ioc x b).nonempty) : b ∈ s := begin let S := s ∩ Icc a b, replace ha : a ∈ S, from ⟨ha, left_mem_Icc.2 hab⟩, have Sbd : bdd_above S, from ⟨b, λ z hz, hz.2.2⟩, let c := Sup (s ∩ Icc a b), have c_mem : c ∈ S, from hs.cSup_mem ⟨_, ha⟩ Sbd, have c_le : c ≤ b, from cSup_le ⟨_, ha⟩ (λ x hx, hx.2.2), cases eq_or_lt_of_le c_le with hc hc, from hc ▸ c_mem.1, exfalso, rcases hgt c ⟨c_mem.1, c_mem.2.1, hc⟩ with ⟨x, xs, cx, xb⟩, exact not_lt_of_le (le_cSup Sbd ⟨xs, le_trans (le_cSup Sbd ha) (le_of_lt cx), xb⟩) cx end /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and for any `a ≤ x < y ≤ b`, `x ∈ s`, the set `s ∩ (x, y]` is not empty, then `[a, b] ⊆ s`. -/ lemma is_closed.Icc_subset_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, ∀ y ∈ Ioi x, (s ∩ Ioc x y).nonempty) : Icc a b ⊆ s := begin assume y hy, have : is_closed (s ∩ Icc a y), { suffices : s ∩ Icc a y = s ∩ Icc a b ∩ Icc a y, { rw this, exact is_closed_inter hs is_closed_Icc }, rw [inter_assoc], congr, exact (inter_eq_self_of_subset_right $ Icc_subset_Icc_right hy.2).symm }, exact is_closed.mem_of_ge_of_forall_exists_gt this ha hy.1 (λ x hx, hgt x ⟨hx.1, Ico_subset_Ico_right hy.2 hx.2⟩ y hx.2.2) end section densely_ordered variables [densely_ordered α] {a b : α} /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and for any `x ∈ s ∩ [a, b)` the set `s` includes some open neighborhood of `x` within `(x, +∞)`, then `[a, b] ⊆ s`. -/ lemma is_closed.Icc_subset_of_forall_mem_nhds_within {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, s ∈ 𝓝[Ioi x] x) : Icc a b ⊆ s := begin apply hs.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxs, hxab⟩ y hyxb, have : s ∩ Ioc x y ∈ 𝓝[Ioi x] x, from inter_mem_sets (hgt x ⟨hxs, hxab⟩) (Ioc_mem_nhds_within_Ioi ⟨le_refl _, hyxb⟩), exact (nhds_within_Ioi_self_ne_bot' hxab.2).nonempty_of_mem this end /-- A closed interval in a densely ordered conditionally complete linear order is preconnected. -/ lemma is_preconnected_Icc : is_preconnected (Icc a b) := is_preconnected_closed_iff.2 begin rintros s t hs ht hab ⟨x, hx⟩ ⟨y, hy⟩, wlog hxy : x ≤ y := le_total x y using [x y s t, y x t s], have xyab : Icc x y ⊆ Icc a b := Icc_subset_Icc hx.1.1 hy.1.2, by_contradiction hst, suffices : Icc x y ⊆ s, from hst ⟨y, xyab $ right_mem_Icc.2 hxy, this $ right_mem_Icc.2 hxy, hy.2⟩, apply (is_closed_inter hs is_closed_Icc).Icc_subset_of_forall_mem_nhds_within hx.2, rintros z ⟨zs, hz⟩, have zt : z ∈ tᶜ, from λ zt, hst ⟨z, xyab $ Ico_subset_Icc_self hz, zs, zt⟩, have : tᶜ ∩ Ioc z y ∈ 𝓝[Ioi z] z, { rw [← nhds_within_Ioc_eq_nhds_within_Ioi hz.2], exact mem_nhds_within.2 ⟨tᶜ, ht, zt, subset.refl _⟩}, apply mem_sets_of_superset this, have : Ioc z y ⊆ s ∪ t, from λ w hw, hab (xyab ⟨le_trans hz.1 (le_of_lt hw.1), hw.2⟩), exact λ w ⟨wt, wzy⟩, (this wzy).elim id (λ h, (wt h).elim) end lemma is_preconnected_interval : is_preconnected (interval a b) := is_preconnected_Icc lemma is_preconnected_iff_ord_connected {s : set α} : is_preconnected s ↔ ord_connected s := ⟨λ h x hx y hy, h.Icc_subset hx hy, λ h, is_preconnected_of_forall_pair $ λ x y hx hy, ⟨interval x y, h.interval_subset hx hy, left_mem_interval, right_mem_interval, is_preconnected_interval⟩⟩ alias is_preconnected_iff_ord_connected ↔ is_preconnected.ord_connected set.ord_connected.is_preconnected lemma is_preconnected_Ici : is_preconnected (Ici a) := ord_connected_Ici.is_preconnected lemma is_preconnected_Iic : is_preconnected (Iic a) := ord_connected_Iic.is_preconnected lemma is_preconnected_Iio : is_preconnected (Iio a) := ord_connected_Iio.is_preconnected lemma is_preconnected_Ioi : is_preconnected (Ioi a) := ord_connected_Ioi.is_preconnected lemma is_preconnected_Ioo : is_preconnected (Ioo a b) := ord_connected_Ioo.is_preconnected lemma is_preconnected_Ioc : is_preconnected (Ioc a b) := ord_connected_Ioc.is_preconnected lemma is_preconnected_Ico : is_preconnected (Ico a b) := ord_connected_Ico.is_preconnected @[priority 100] instance ordered_connected_space : preconnected_space α := ⟨ord_connected_univ.is_preconnected⟩ /-- In a dense conditionally complete linear order, the set of preconnected sets is exactly the set of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`, `Iic`, `Iio`, `(-∞, +∞)`, or `∅`. Though one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of possible cases to improve readability. -/ lemma set_of_is_preconnected_eq_of_ordered : {s : set α | is_preconnected s} = -- bounded intervals (range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪ -- unbounded intervals and `univ` (range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) := begin refine subset.antisymm set_of_is_preconnected_subset_of_ordered _, simp only [subset_def, -mem_range, forall_range_iff, uncurry, or_imp_distrib, forall_and_distrib, mem_union, mem_set_of_eq, insert_eq, mem_singleton_iff, forall_eq, forall_true_iff, and_true, is_preconnected_Icc, is_preconnected_Ico, is_preconnected_Ioc, is_preconnected_Ioo, is_preconnected_Ioi, is_preconnected_Iio, is_preconnected_Ici, is_preconnected_Iic, is_preconnected_univ, is_preconnected_empty], end /--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≤ t ≤ f b`.-/ lemma intermediate_value_Icc {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) : Icc (f a) (f b) ⊆ f '' (Icc a b) := is_preconnected_Icc.intermediate_value (left_mem_Icc.2 hab) (right_mem_Icc.2 hab) hf /--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≥ t ≥ f b`.-/ lemma intermediate_value_Icc' {a b : α} (hab : a ≤ b) {f : α → β} (hf : continuous_on f (Icc a b)) : Icc (f b) (f a) ⊆ f '' (Icc a b) := is_preconnected_Icc.intermediate_value (right_mem_Icc.2 hab) (left_mem_Icc.2 hab) hf /-- A continuous function which tendsto `at_top` `at_top` and to `at_bot` `at_bot` is surjective. -/ lemma surjective_of_continuous {f : α → β} (hf : continuous f) (h_top : tendsto f at_top at_top) (h_bot : tendsto f at_bot at_bot) : function.surjective f := begin intros p, obtain ⟨b, hb⟩ : ∃ b, p ≤ f b, { rcases ((tendsto_at_top_at_top _).mp h_top) p with ⟨b, hb⟩, exact ⟨b, hb b rfl.ge⟩ }, obtain ⟨a, hab, ha⟩ : ∃ a, a ≤ b ∧ f a ≤ p, { rcases ((tendsto_at_bot_at_bot _).mp h_bot) p with ⟨x, hx⟩, exact ⟨min x b, min_le_right x b, hx (min x b) (min_le_left x b)⟩ }, rcases intermediate_value_Icc hab hf.continuous_on ⟨ha, hb⟩ with ⟨x, _, hx⟩, exact ⟨x, hx⟩ end /-- A continuous function which tendsto `at_bot` `at_top` and to `at_top` `at_bot` is surjective. -/ lemma surjective_of_continuous' {f : α → β} (hf : continuous f) (h_top : tendsto f at_bot at_top) (h_bot : tendsto f at_top at_bot) : function.surjective f := @surjective_of_continuous (order_dual α) β _ _ _ _ _ _ _ _ hf h_top h_bot end densely_ordered lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Inf s ∈ s := hs.is_closed.cInf_mem ne_s hs.bdd_below lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Sup s ∈ s := @is_compact.Inf_mem (order_dual α) _ _ _ _ hs ne_s lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_glb s (Inf s) := is_glb_cInf ne_s hs.bdd_below lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_lub s (Sup s) := @is_compact.is_glb_Inf (order_dual α) _ _ _ _ hs ne_s lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_least s (Inf s) := ⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩ lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_greatest s (Sup s) := @is_compact.is_least_Inf (order_dual α) _ _ _ _ hs ne_s lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_least s x := ⟨_, hs.is_least_Inf ne_s⟩ lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_greatest s x := ⟨_, hs.is_greatest_Sup ne_s⟩ lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_glb s x := ⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩ lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_lub s x := ⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩ lemma is_compact.exists_Inf_image_eq {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) : ∃ x ∈ s, Inf (f '' s) = f x := let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f) in ⟨x, hxs, hx.symm⟩ /-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/ lemma is_compact.exists_forall_le {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) : ∃x∈s, ∀y∈s, f x ≤ f y := begin rcases hs.exists_Inf_image_eq ne_s hf with ⟨x, hxs, hx⟩, refine ⟨x, hxs, λ y hy, _⟩, rw ← hx, exact ((hs.image_of_continuous_on hf).is_glb_Inf (ne_s.image f)).1 (mem_image_of_mem _ hy) end /-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/ lemma is_compact.exists_forall_ge {α : Type u} [topological_space α]: ∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s → ∃x∈s, ∀y∈s, f y ≤ f x := @is_compact.exists_forall_le (order_dual β) _ _ _ _ _ lemma is_compact.exists_Sup_image_eq {α : Type u} [topological_space α]: ∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s → ∃ x ∈ s, Sup (f '' s) = f x := @is_compact.exists_Inf_image_eq (order_dual β) _ _ _ _ _ lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) : s = Icc (Inf s) (Sup s) := eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed end conditionally_complete_linear_order section liminf_limsup section order_closed_topology variables [semilattice_sup α] [topological_space α] [order_topology α] lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, eventually_of_forall h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma filter.tendsto.is_bounded_under_le {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u := (is_bounded_le_nhds a).mono h lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) := (is_bounded_le_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_ge {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u := h.is_bounded_under_le.is_cobounded_flip end order_closed_topology section order_closed_topology variables [semilattice_inf α] [topological_space α] [order_topology α] lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) := @is_bounded_le_nhds (order_dual α) _ _ _ a lemma filter.tendsto.is_bounded_under_ge {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u := (is_bounded_ge_nhds a).mono h lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) := (is_bounded_ge_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_le {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u := h.is_bounded_under_ge.is_cobounded_flip end order_closed_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : ∀ᶠ a in f, a < b := let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_cInf_lt h l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → b < f.Liminf → ∀ᶠ a in f, b < a := @lt_mem_sets_of_Limsup_lt (order_dual α) _ variables [topological_space α] [order_topology α] /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ 𝓝 a := tendsto_order.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a := cInf_intro (is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from match dense_or_discrete a b with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a := @Limsup_nhds (order_dual α) _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from (is_bounded_ge_nhds a).mono h, have hb_le : is_bounded (≤) f, from (is_bounded_le_nhds a).mono h, le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hb_le hb_ge ... ≤ (𝓝 a).Limsup : Limsup_le_Limsup_of_le h hb_ge.is_cobounded_flip (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) hb_le.is_cobounded_flip) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α} [ne_bot f], f ≤ 𝓝 a → f.Limsup = a := @Liminf_eq_of_le_nhds (order_dual α) _ _ _ end conditionally_complete_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [order_topology α] -- In complete_linear_order, the above theorems take a simpler form /-- If the liminf and the limsup of a function coincide, then the limit of the function exists and has the same value -/ theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α} (hinf : liminf f u = a) (hsup : limsup f u = a) : tendsto u f (𝓝 a) := le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot hsup hinf /-- If a number `a` is less than or equal to the `liminf` of a function `f` at some filter and is greater than or equal to the `limsup` of `f`, then `f` tends to `a` along this filter. -/ theorem tendsto_of_le_liminf_of_limsup_le {f : filter β} {u : β → α} {a : α} (hinf : a ≤ liminf f u) (hsup : limsup f u ≤ a) : tendsto u f (𝓝 a) := if hf : f = ⊥ then hf.symm ▸ tendsto_bot else by haveI : ne_bot f := hf; exact tendsto_of_liminf_eq_limsup (le_antisymm (le_trans liminf_le_limsup hsup) hinf) (le_antisymm hsup (le_trans hinf liminf_le_limsup)) /-- If a function has a limit, then its limsup coincides with its limit-/ theorem filter.tendsto.limsup_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : limsup f u = a := Limsup_eq_of_le_nhds h /-- If a function has a limit, then its liminf coincides with its limit-/ theorem filter.tendsto.liminf_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : liminf f u = a := Liminf_eq_of_le_nhds h end complete_linear_order end liminf_limsup end order_topology lemma order_topology_of_nhds_abs {α : Type*} [decidable_linear_ordered_add_comm_group α] [topological_space α] (h_nhds : ∀a:α, 𝓝 a = (⨅r>0, 𝓟 {b | abs (a - b) < r})) : order_topology α := order_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr begin simp [infi_and, topological_space.nhds_generate_from, h_nhds, le_infi_iff, -le_principal_iff, and_comm], refine ⟨λ s ha b hs, _, λ r hr, _⟩, { rcases hs with rfl | rfl, { refine infi_le_of_le (a - b) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _), have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc, exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) }, { refine infi_le_of_le (b - a) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _), have : abs (c - a) < b - a, {rw abs_sub; simpa using hc}, have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this, exact lt_of_add_lt_add_right this } }, { have h : {b | abs (a - b) < r} = {b | a - r < b} ∩ {b | b < a + r}, from set.ext (assume b, by simp [abs_lt, sub_lt, lt_sub_iff_add_lt, sub_lt_iff_lt_add']; cc), rw [h, ← inf_principal], apply le_inf _ _, { exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $ infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) }, { exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $ infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } } end lemma tendsto_at_top_supr_nat [topological_space α] [complete_linear_order α] [order_topology α] (f : ℕ → α) (hf : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) := tendsto_order.2 $ and.intro (assume a ha, let ⟨n, hn⟩ := lt_supr_iff.1 ha in mem_at_top_sets.2 ⟨n, assume i hi, lt_of_lt_of_le hn (hf hi)⟩) (assume a ha, univ_mem_sets' (assume n, lt_of_le_of_lt (le_supr _ n) ha)) lemma tendsto_at_top_infi_nat [topological_space α] [complete_linear_order α] [order_topology α] (f : ℕ → α) (hf : ∀{n m}, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 (⨅i, f i)) := @tendsto_at_top_supr_nat (order_dual α) _ _ _ _ @hf lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α] {f : ℕ → α} {a : α} (hf : monotone f) : tendsto f at_top (𝓝 a) → supr f = a := tendsto_nhds_unique (tendsto_at_top_supr_nat f hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α] {f : ℕ → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 a) → infi f = a := tendsto_nhds_unique (tendsto_at_top_infi_nat f hf) /-- $\lim_{x\to+\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_top_at_top [decidable_linear_ordered_add_comm_group α] : tendsto (abs : α → α) at_top at_top := tendsto_at_top_mono (λ n, le_abs_self _) tendsto_id local notation `|` x `|` := abs x lemma decidable_linear_ordered_add_comm_group.tendsto_nhds [decidable_linear_ordered_add_comm_group α] [topological_space α] [order_topology α] {β : Type*} (f : β → α) (x : filter β) (a : α) : filter.tendsto f x (nhds a) ↔ ∀ ε > (0 : α), ∀ᶠ b in x, |f b - a| < ε := begin rw (show _, from @tendsto_order α), -- does not work without `show` for some reason split, { rintros ⟨hyp_lt_a, hyp_gt_a⟩ ε ε_pos, suffices : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff], have set1 : {b : β | a - f b < ε} ∈ x, { have : {b : β | a - ε < f b} ∈ x, from hyp_lt_a (a - ε) (sub_lt_self a ε_pos), have : ∀ b, a - f b < ε ↔ a - ε < f b, by { intro _, exact sub_lt }, simpa only [this] }, have set2 : {b : β | f b - a < ε} ∈ x, { have : {b : β | a + ε > f b} ∈ x, from hyp_gt_a (a + ε) (lt_add_of_pos_right a ε_pos), have : ∀ b, f b - a < ε ↔ a + ε > f b, by { intro _, exact sub_lt_iff_lt_add' }, simpa only [this] }, exact (x.inter_sets set2 set1) }, { assume hyp_ε_pos, split, { assume a' a'_lt_a, let ε := a - a', have : {b : β | |f b - a| < ε} ∈ x, from hyp_ε_pos ε (sub_pos.elim_right a'_lt_a), have : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff] using this, have : {b : β | a - f b < ε} ∈ x, from x.sets_of_superset this (set.inter_subset_right _ _), have : ∀ b, a' < f b ↔ a - f b < ε, by {intro b, rw [sub_lt, sub_sub_self] }, simpa only [this] }, { assume a' a'_gt_a, let ε := a' - a, have : {b : β | |f b - a| < ε} ∈ x, from hyp_ε_pos ε (sub_pos.elim_right a'_gt_a), have : {b : β | f b - a < ε ∧ a - f b < ε} ∈ x, by simpa only [abs_sub_lt_iff] using this, have : {b : β | f b - a < ε} ∈ x, from x.sets_of_superset this (set.inter_subset_left _ _), have : ∀ b, f b < a' ↔ f b - a < ε, by { intro b, simp [lt_sub_iff_add_lt] }, simpa only [this] }} end /-! Here is a counter-example to a version of the following with `conditionally_complete_lattice α`. Take `α = [0, 1) → ℝ` with the natural lattice structure, `ι = ℕ`. Put `f n x = -x^n`. Then `⨆ n, f n = 0` while none of `f n` is strictly greater than the constant function `-0.5`. -/ lemma tendsto_at_top_csupr {ι α : Type*} [preorder ι] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) (hbdd : bdd_above $ range f) : tendsto f at_top (𝓝 (⨆i, f i)) := begin by_cases hi : nonempty ι, { resetI, rw tendsto_order, split, { intros a h, cases exists_lt_of_lt_csupr h with N hN, apply eventually.mono (mem_at_top N), exact λ i hi, lt_of_lt_of_le hN (h_mono hi) }, { exact λ a h, eventually_of_forall (λ n, lt_of_le_of_lt (le_csupr hbdd n) h) } }, { exact tendsto_of_not_nonempty hi } end lemma tendsto_at_top_supr {ι α : Type*} [preorder ι] [topological_space α] [complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) := tendsto_at_top_csupr h_mono (order_top.bdd_above _) 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 @[to_additive] lemma tendsto_inv_nhds_within_Ioi [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ioi a] a) (𝓝[Iio (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iio [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iio a] a) (𝓝[Ioi (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ioi (a⁻¹)] (a⁻¹)) (𝓝[Iio a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iio_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iio (a⁻¹)] (a⁻¹)) (𝓝[Ioi a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹) lemma nhds_left_sup_nhds_right (a : α) [topological_space α] [linear_order α] : nhds_within a (Iic a) ⊔ nhds_within a (Ici a) = 𝓝 a := by rw [← nhds_within_union, Iic_union_Ici, nhds_within_univ] lemma nhds_left'_sup_nhds_right (a : α) [topological_space α] [linear_order α] : nhds_within a (Iio a) ⊔ nhds_within a (Ici a) = 𝓝 a := by rw [← nhds_within_union, Iio_union_Ici, nhds_within_univ] lemma nhds_left_sup_nhds_right' (a : α) [topological_space α] [linear_order α] : nhds_within a (Iic a) ⊔ nhds_within a (Ioi a) = 𝓝 a := by rw [← nhds_within_union, Iic_union_Ioi, nhds_within_univ] lemma continuous_at_iff_continuous_left_right [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_at f a ↔ continuous_within_at f (Iic a) a ∧ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, continuous_at, ← tendsto_sup, nhds_left_sup_nhds_right] lemma continuous_on_Icc_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {la lb : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la)) (hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) : continuous_on (extend_from (Ioo a b) f) (Icc a b) := begin apply continuous_on_extend_from, { rw closure_Ioo hab, }, { intros x x_in, rcases mem_Ioo_or_eq_endpoints_of_mem_Icc x_in with rfl | rfl | h, { use la, simpa [hab] }, { use lb, simpa [hab] }, { use [f x, hf x h] } } end lemma eq_lim_at_left_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [t2_space β] {f : α → β} {a b : α} {la : β} (hab : a < b) (ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la)) : extend_from (Ioo a b) f a = la := begin apply extend_from_eq, { rw closure_Ioo hab, simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] }, { simpa [hab] } end lemma eq_lim_at_right_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [t2_space β] {f : α → β} {a b : α} {lb : β} (hab : a < b) (hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) : extend_from (Ioo a b) f b = lb := begin apply extend_from_eq, { rw closure_Ioo hab, simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] }, { simpa [hab] } end lemma continuous_on_Ico_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {la : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (ha : tendsto f (nhds_within a $ Ioi a) (𝓝 la)) : continuous_on (extend_from (Ioo a b) f) (Ico a b) := begin apply continuous_on_extend_from, { rw [closure_Ioo hab], exact Ico_subset_Icc_self, }, { intros x x_in, rcases mem_Ioo_or_eq_left_of_mem_Ico x_in with rfl | h, { use la, simpa [hab] }, { use [f x, hf x h] } } end lemma continuous_on_Ioc_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {lb : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (hb : tendsto f (nhds_within b $ Iio b) (𝓝 lb)) : continuous_on (extend_from (Ioo a b) f) (Ioc a b) := begin have := @continuous_on_Ico_extend_from_Ioo (order_dual α) _ _ _ _ _ _ _ f _ _ _ hab, erw [dual_Ico, dual_Ioi, dual_Ioo] at this, exact this hf hb end lemma continuous_within_at_Ioi_iff_Ici {α β : Type*} [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_within_at f (Ioi a) a ↔ continuous_within_at f (Ici a) a := begin split, { intros h s hs, specialize h hs, rw [mem_map, mem_nhds_within_iff_exists_mem_nhds_inter] at *, rcases h with ⟨u, huna, hu⟩, use [u, huna], { intros x hx, cases hx with hxu hx, by_cases h : x = a, { rw [h, mem_set_of_eq], exact mem_of_nhds hs, }, exact hu ⟨hxu, lt_of_le_of_ne hx (ne_comm.2 h)⟩ } }, { intros h, exact h.mono Ioi_subset_Ici_self } end lemma continuous_within_at_Iio_iff_Iic {α β : Type*} [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_within_at f (Iio a) a ↔ continuous_within_at f (Iic a) a := begin have := @continuous_within_at_Ioi_iff_Ici (order_dual α) _ _ _ _ _ f, erw [dual_Ici, dual_Ioi] at this, exact this, end lemma continuous_at_iff_continuous_left'_right' [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_at f a ↔ continuous_within_at f (Iio a) a ∧ continuous_within_at f (Ioi a) a := by rw [continuous_within_at_Ioi_iff_Ici, continuous_within_at_Iio_iff_Iic, continuous_at_iff_continuous_left_right] section homeomorphisms variables [topological_space α] [topological_space β] section linear_order variables [linear_order α] [order_topology α] variables [linear_order β] [order_topology β] /-- If `f : α → β` is strictly monotone and surjective, it is everywhere continuous. -/ lemma continuous_at_of_strict_mono_surjective {f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) (a : α) : continuous_at f a := continuous_at_iff_continuous_left_right.mpr ⟨continuous_left_of_strict_mono_surjective h_mono h_surj a, continuous_right_of_strict_mono_surjective h_mono h_surj a⟩ /-- If `f : α → β` is strictly monotone and surjective, it is continuous. -/ lemma continuous_of_strict_mono_surjective {f : α → β} (h_mono : strict_mono f) (h_surj : function.surjective f) : continuous f := continuous_iff_continuous_at.mpr (continuous_at_of_strict_mono_surjective h_mono h_surj) /-- If `f : α ≃ β` is strictly monotone, its inverse is continuous. -/ lemma continuous_inv_of_strict_mono_equiv (e : α ≃ β) (h_mono : strict_mono e.to_fun) : continuous e.inv_fun := begin have hinv_mono : strict_mono e.inv_fun, { intros x y hxy, rw [← h_mono.lt_iff_lt, e.right_inv, e.right_inv], exact hxy }, have hinv_surj : function.surjective e.inv_fun, { intros x, exact ⟨e.to_fun x, e.left_inv x⟩ }, exact continuous_of_strict_mono_surjective hinv_mono hinv_surj end /-- If `f : α → β` is strictly monotone and surjective, it is a homeomorphism. -/ noncomputable def homeomorph_of_strict_mono_surjective (f : α → β) (h_mono : strict_mono f) (h_surj : function.surjective f) : homeomorph α β := { to_equiv := equiv.of_bijective f ⟨strict_mono.injective h_mono, h_surj⟩, continuous_to_fun := continuous_of_strict_mono_surjective h_mono h_surj, continuous_inv_fun := continuous_inv_of_strict_mono_equiv (equiv.of_bijective f ⟨strict_mono.injective h_mono, h_surj⟩) h_mono } @[simp] lemma coe_homeomorph_of_strict_mono_surjective (f : α → β) (h_mono : strict_mono f) (h_surj : function.surjective f) : (homeomorph_of_strict_mono_surjective f h_mono h_surj : α → β) = f := rfl end linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [densely_ordered α] [order_topology α] variables [conditionally_complete_linear_order β] [order_topology β] /-- If `f : α → β` is strictly monotone and continuous, and tendsto `at_top` `at_top` and to `at_bot` `at_bot`, then it is a homeomorphism. -/ noncomputable def homeomorph_of_strict_mono_continuous (f : α → β) (h_mono : strict_mono f) (h_cont : continuous f) (h_top : tendsto f at_top at_top) (h_bot : tendsto f at_bot at_bot) : homeomorph α β := homeomorph_of_strict_mono_surjective f h_mono (surjective_of_continuous h_cont h_top h_bot) @[simp] lemma coe_homeomorph_of_strict_mono_continuous (f : α → β) (h_mono : strict_mono f) (h_cont : continuous f) (h_top : tendsto f at_top at_top) (h_bot : tendsto f at_bot at_bot) : (homeomorph_of_strict_mono_continuous f h_mono h_cont h_top h_bot : α → β) = f := rfl end conditionally_complete_linear_order end homeomorphisms
5b0900343d58e94a5a050a676656635164d89ce4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fin/tuple/monotone.lean
d5973fc02cc0393e49bd99646f098fb075821d76
[ "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
1,887
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import data.fin.vec_notation /-! # Monotone finite sequences In this file we prove `simp` lemmas that allow to simplify propositions like `monotone ![a, b, c]`. -/ open set fin matrix function variables {α : Type*} lemma lift_fun_vec_cons {n : ℕ} (r : α → α → Prop) [is_trans α r] {f : fin (n + 1) → α} {a : α} : ((<) ⇒ r) (vec_cons a f) (vec_cons a f) ↔ r a (f 0) ∧ ((<) ⇒ r) f f := by simp only [lift_fun_iff_succ r, forall_fin_succ, cons_val_succ, cons_val_zero, ← succ_cast_succ, cast_succ_zero] variables [preorder α] {n : ℕ} {f : fin (n + 1) → α} {a : α} @[simp] lemma strict_mono_vec_cons : strict_mono (vec_cons a f) ↔ a < f 0 ∧ strict_mono f := lift_fun_vec_cons (<) @[simp] lemma monotone_vec_cons : monotone (vec_cons a f) ↔ a ≤ f 0 ∧ monotone f := by simpa only [monotone_iff_forall_lt] using @lift_fun_vec_cons α n (≤) _ f a @[simp] lemma strict_anti_vec_cons : strict_anti (vec_cons a f) ↔ f 0 < a ∧ strict_anti f := lift_fun_vec_cons (>) @[simp] lemma antitone_vec_cons : antitone (vec_cons a f) ↔ f 0 ≤ a ∧ antitone f := @monotone_vec_cons αᵒᵈ _ _ _ _ lemma strict_mono.vec_cons (hf : strict_mono f) (ha : a < f 0) : strict_mono (vec_cons a f) := strict_mono_vec_cons.2 ⟨ha, hf⟩ lemma strict_anti.vec_cons (hf : strict_anti f) (ha : f 0 < a) : strict_anti (vec_cons a f) := strict_anti_vec_cons.2 ⟨ha, hf⟩ lemma monotone.vec_cons (hf : monotone f) (ha : a ≤ f 0) : monotone (vec_cons a f) := monotone_vec_cons.2 ⟨ha, hf⟩ lemma antitone.vec_cons (hf : antitone f) (ha : f 0 ≤ a) : antitone (vec_cons a f) := antitone_vec_cons.2 ⟨ha, hf⟩ example : monotone ![1, 2, 2, 3] := by simp [subsingleton.monotone]
e1449d95c9b7801c6e90d0fd955ee1d29e1e53f0
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/topology/continuous_map.lean
c35555b5be2ccec8817fefe19a0b10f6ccd9344b
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,676
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import topology.subset_properties import topology.tactic import topology.algebra.ordered /-! # Continuous bundled map In this file we define the type `continuous_map` of continuous bundled maps. -/ /-- Bundled continuous maps. -/ @[protect_proj] structure continuous_map (α : Type*) (β : Type*) [topological_space α] [topological_space β] := (to_fun : α → β) (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') notation `C(` α `, ` β `)` := continuous_map α β namespace continuous_map attribute [continuity] continuous_map.continuous_to_fun variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] instance : has_coe_to_fun (C(α, β)) := ⟨_, continuous_map.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : C(α, β)} : f.to_fun = (f : α → β) := rfl variables {α β} {f g : continuous_map α β} protected lemma continuous (f : C(α, β)) : continuous f := f.continuous_to_fun @[continuity] lemma coe_continuous : continuous (f : α → β) := f.continuous_to_fun @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H instance [inhabited β] : inhabited C(α, β) := ⟨{ to_fun := λ _, default _, }⟩ lemma coe_inj ⦃f g : C(α, β)⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[simp] lemma coe_mk (f : α → β) (h : continuous f) : ⇑(⟨f, h⟩ : continuous_map α β) = f := rfl section variables (α β) /-- The continuous functions from `α` to `β` are the same as the plain functions when `α` is discrete. -/ @[simps] def equiv_fn_of_discrete [discrete_topology α] : C(α, β) ≃ (α → β) := ⟨(λ f, f), (λ f, ⟨f, continuous_of_discrete_topology⟩), λ f, by { ext, refl, }, λ f, by { ext, refl, }⟩ end /-- The identity as a continuous map. -/ def id : C(α, α) := ⟨id⟩ @[simp] lemma id_coe : (id : α → α) = id := rfl lemma id_apply (a : α) : id a = a := rfl /-- The composition of continuous maps, as a continuous map. -/ def comp (f : C(β, γ)) (g : C(α, β)) : C(α, γ) := ⟨f ∘ g⟩ @[simp] lemma comp_coe (f : C(β, γ)) (g : C(α, β)) : (comp f g : α → γ) = f ∘ g := rfl lemma comp_apply (f : C(β, γ)) (g : C(α, β)) (a : α) : comp f g a = f (g a) := rfl /-- Constant map as a continuous map -/ def const (b : β) : C(α, β) := ⟨λ x, b⟩ @[simp] lemma const_coe (b : β) : (const b : α → β) = (λ x, b) := rfl lemma const_apply (b : β) (a : α) : const b a = b := rfl /-! We now set up the partial order and lattice structure (given by pointwise min and max) on continuous functions. -/ section lattice instance partial_order [partial_order β] : partial_order C(α, β) := partial_order.lift (λ f, f.to_fun) (by tidy) lemma le_def [partial_order β] {f g : C(α, β)} : f ≤ g ↔ ∀ a, f a ≤ g a := pi.le_def lemma lt_def [partial_order β] {f g : C(α, β)} : f < g ↔ (∀ a, f a ≤ g a) ∧ (∃ a, f a < g a) := pi.lt_def instance has_sup [linear_order β] [order_closed_topology β] : has_sup C(α, β) := { sup := λ f g, { to_fun := λ a, max (f a) (g a), } } @[simp] lemma sup_apply [linear_order β] [order_closed_topology β] (f g : C(α, β)) (a : α) : (f ⊔ g) a = max (f a) (g a) := rfl instance [linear_order β] [order_closed_topology β] : semilattice_sup C(α, β) := { le_sup_left := λ f g, le_def.mpr (by simp [le_refl]), le_sup_right := λ f g, le_def.mpr (by simp [le_refl]), sup_le := λ f₁ f₂ g w₁ w₂, le_def.mpr (λ a, by simp [le_def.mp w₁ a, le_def.mp w₂ a]), ..continuous_map.partial_order, ..continuous_map.has_sup, } instance has_inf [linear_order β] [order_closed_topology β] : has_inf C(α, β) := { inf := λ f g, { to_fun := λ a, min (f a) (g a), } } @[simp] lemma inf_apply [linear_order β] [order_closed_topology β] (f g : C(α, β)) (a : α) : (f ⊓ g) a = min (f a) (g a) := rfl instance [linear_order β] [order_closed_topology β] : semilattice_inf C(α, β) := { inf_le_left := λ f g, le_def.mpr (by simp [le_refl]), inf_le_right := λ f g, le_def.mpr (by simp [le_refl]), le_inf := λ f₁ f₂ g w₁ w₂, le_def.mpr (λ a, by simp [le_def.mp w₁ a, le_def.mp w₂ a]), ..continuous_map.partial_order, ..continuous_map.has_inf, } instance [linear_order β] [order_closed_topology β] : lattice C(α, β) := { ..continuous_map.semilattice_inf, ..continuous_map.semilattice_sup } end lattice end continuous_map
639d2cc0eaea54e71b58ceac0efe10c29d2c460b
618003631150032a5676f229d13a079ac875ff77
/src/topology/uniform_space/uniform_convergence.lean
51617d510def593c3c97ebda6abf359be1c6db43
[ "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
16,751
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 topology.uniform_space.basic /-! # Uniform convergence A sequence of functions `Fₙ` (with values in a metric space) converges uniformly on a set `s` to a function `f` if, for all `ε > 0`, for all large enough `n`, one has for all `y ∈ s` the inequality `dist (f y, Fₙ y) < ε`. Under uniform convergence, many properties of the `Fₙ` pass to the limit, most notably continuity. We prove this in the file, defining the notion of uniform convergence in the more general setting of uniform spaces, and with respect to an arbitrary indexing set endowed with a filter (instead of just `ℕ` with `at_top`). ## Main results Let `α` be a topological space, `β` a uniform space, `Fₙ` and `f` be functions from `α`to `β` (where the index `n` belongs to an indexing type `ι` endowed with a filter `p`). * `tendsto_uniformly_on F f p s`: the fact that `Fₙ` converges uniformly to `f` on `s`. This means that, for any entourage `u` of the diagonal, for large enough `n` (with respect to `p`), one has `(f y, Fₙ y) ∈ u` for all `y ∈ s`. * `tendsto_uniformly F f p`: same notion with `s = univ`. * `tendsto_uniformly_on.continuous_on`: a uniform limit on a set of functions which are continuous on this set is itself continuous on this set. * `tendsto_uniformly.continuous`: a uniform limit of continuous functions is continuous. * `tendsto_uniformly_on.tendsto_comp`: If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. * `tendsto_uniformly.tendsto_comp`: If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. We also define notions where the convergence is locally uniform, called `tendsto_locally_uniformly_on F f p s` and `tendsto_locally_uniformly F f p`. The previous theorems all have corresponding versions under locally uniform convergence. ## Implementation notes Most results hold under weaker assumptions of locally uniform approximation. In a first section, we prove the results under these weaker assumptions. Then, we derive the results on uniform convergence from them. ## Tags Uniform limit, uniform convergence, tends uniformly to -/ noncomputable theory open_locale topological_space classical uniformity open set filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-! ### Different notions of uniform convergence We define uniform convergence and locally uniform convergence, on a set or in the whole space. -/ variables {ι : Type*} [uniform_space β] {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α} /-- A sequence of functions `Fₙ` converges uniformly on a set `s` to a limiting function `f` with respect to the filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x ∈ s`. -/ def tendsto_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x ∈ s, (f x, F n x) ∈ u /-- A sequence of functions `Fₙ` converges uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x`. -/ def tendsto_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x, (f x, F n x) ∈ u lemma tendsto_uniformly_on_univ : tendsto_uniformly_on F f p univ ↔ tendsto_uniformly F f p := by simp [tendsto_uniformly_on, tendsto_uniformly] lemma tendsto_uniformly_on.mono {s' : set α} (h : tendsto_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_uniformly_on F f p s' := λ u hu, (h u hu).mono (λ n hn x hx, hn x (h' hx)) lemma tendsto_uniformly.tendsto_uniformly_on (h : tendsto_uniformly F f p) : tendsto_uniformly_on F f p s := (tendsto_uniformly_on_univ.2 h).mono (subset_univ s) /-- Composing on the right by a function preserves uniform convergence on a set -/ lemma tendsto_uniformly_on.comp (h : tendsto_uniformly_on F f p s) (g : γ → α) : tendsto_uniformly_on (λ n, F n ∘ g) (f ∘ g) p (g ⁻¹' s) := begin assume u hu, apply (h u hu).mono (λ n hn, _), exact λ x hx, hn _ hx end /-- Composing on the right by a function preserves uniform convergence -/ lemma tendsto_uniformly.comp (h : tendsto_uniformly F f p) (g : γ → α) : tendsto_uniformly (λ n, F n ∘ g) (f ∘ g) p := begin assume u hu, apply (h u hu).mono (λ n hn, _), exact λ x, hn _ end variable [topological_space α] /-- A sequence of functions `Fₙ` converges locally uniformly on a set `s` to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x ∈ s`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x` in `s`. -/ def tendsto_locally_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ u ∈ 𝓤 β, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u /-- A sequence of functions `Fₙ` converges locally uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x`. -/ def tendsto_locally_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ u ∈ 𝓤 β, ∀ (x : α), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u lemma tendsto_uniformly_on.tendsto_locally_uniformly_on (h : tendsto_uniformly_on F f p s) : tendsto_locally_uniformly_on F f p s := λ u hu x hx, ⟨s, self_mem_nhds_within, h u hu⟩ lemma tendsto_uniformly.tendsto_locally_uniformly (h : tendsto_uniformly F f p) : tendsto_locally_uniformly F f p := λ u hu x, ⟨univ, univ_mem_sets, by simpa using h u hu⟩ lemma tendsto_locally_uniformly_on.mono (h : tendsto_locally_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_locally_uniformly_on F f p s' := begin assume u hu x hx, rcases h u hu x (h' hx) with ⟨t, ht, H⟩, exact ⟨t, nhds_within_mono x h' ht, H.mono (λ n, id)⟩ end lemma tendsto_locally_uniformly_on_univ : tendsto_locally_uniformly_on F f p univ ↔ tendsto_locally_uniformly F f p := by simp [tendsto_locally_uniformly_on, tendsto_locally_uniformly, nhds_within_univ] lemma tendsto_locally_uniformly_on.comp [topological_space γ] {t : set γ} (h : tendsto_locally_uniformly_on F f p s) (g : γ → α) (hg : maps_to g t s) (cg : continuous_on g t) : tendsto_locally_uniformly_on (λ n, (F n) ∘ g) (f ∘ g) p t := begin assume u hu x hx, rcases h u hu (g x) (hg hx) with ⟨a, ha, H⟩, have : g⁻¹' a ∈ nhds_within x t := ((cg x hx).preimage_mem_nhds_within' (nhds_within_mono (g x) hg.image_subset ha)), exact ⟨g ⁻¹' a, this, H.mono (λ n hn y hy, hn _ hy)⟩ end lemma tendsto_locally_uniformly.comp [topological_space γ] (h : tendsto_locally_uniformly F f p) (g : γ → α) (cg : continuous g) : tendsto_locally_uniformly (λ n, (F n) ∘ g) (f ∘ g) p := begin rw ← tendsto_locally_uniformly_on_univ at h ⊢, rw continuous_iff_continuous_on_univ at cg, exact h.comp _ (maps_to_univ _ _) cg end /-! ### Uniform approximation In this section, we give lemmas ensuring that a function is continuous if it can be approximated uniformly by continuous functions. We give various versions, within a set or the whole space, at a single point or at all points, with locally uniform approximation or uniform approximation. All the statements are derived from a statement about locally uniform approximation within a set at a point, called `continuous_within_at_of_locally_uniform_approx_of_continuous_within_at`. -/ /-- A function which can be locally uniformly approximated by functions which are continuous within a set at a point is continuous within this set at this point. -/ lemma continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (hx : x ∈ s) (L : ∀ u ∈ 𝓤 β, ∃ t ∈ nhds_within x s, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_within_at (F n) s x) : continuous_within_at f s x := begin apply uniform.continuous_within_at_iff'_left.2 (λ u₀ hu₀, _), obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ := comp_mem_uniformity_sets hu₀, obtain ⟨u₂, h₂, hsymm, u₂₁⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), (∀{a b}, (a, b) ∈ u → (b, a) ∈ u) ∧ comp_rel u u ⊆ u₁ := comp_symm_of_uniformity h₁, rcases L u₂ h₂ with ⟨t, tx, n, ht⟩, have A : ∀ᶠ y in nhds_within x s, (f y, F n y) ∈ u₂ := eventually.mono tx ht, have B : ∀ᶠ y in nhds_within x s, (F n y, F n x) ∈ u₂ := uniform.continuous_within_at_iff'_left.1 (C n) h₂, have C : ∀ᶠ y in nhds_within x s, (f y, F n x) ∈ u₁ := (A.and B).mono (λ y hy, u₂₁ (prod_mk_mem_comp_rel hy.1 hy.2)), have : (F n x, f x) ∈ u₁ := u₂₁ (prod_mk_mem_comp_rel (refl_mem_uniformity h₂) (hsymm (A.self_of_nhds_within hx))), exact C.mono (λ y hy, u₁₀ (prod_mk_mem_comp_rel hy this)) end /-- A function which can be locally uniformly approximated by functions which are continuous at a point is continuous at this point. -/ lemma continuous_at_of_locally_uniform_approx_of_continuous_at (L : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_at (F n) x) : continuous_at f x := begin simp only [← continuous_within_at_univ] at C ⊢, apply continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (mem_univ _) _ C, simpa [nhds_within_univ] using L end /-- A function which can be locally uniformly approximated by functions which are continuous on a set is continuous on this set. -/ lemma continuous_on_of_locally_uniform_approx_of_continuous_on (L : ∀ (x ∈ s) (u ∈ 𝓤 β), ∃t ∈ nhds_within x s, ∃n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_on (F n) s) : continuous_on f s := λ x hx, continuous_within_at_of_locally_uniform_approx_of_continuous_within_at hx (L x hx) (λ n, C n x hx) /-- A function which can be uniformly approximated by functions which are continuous on a set is continuous on this set. -/ lemma continuous_on_of_uniform_approx_of_continuous_on (L : ∀ u ∈ 𝓤 β, ∃ n, ∀ y ∈ s, (f y, F n y) ∈ u) : (∀ n, continuous_on (F n) s) → continuous_on f s := continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, ⟨s, self_mem_nhds_within, L u hu⟩) /-- A function which can be locally uniformly approximated by continuous functions is continuous. -/ lemma continuous_of_locally_uniform_approx_of_continuous (L : ∀ (x : α), ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous (F n)) : continuous f := begin simp only [continuous_iff_continuous_on_univ] at ⊢ C, apply continuous_on_of_locally_uniform_approx_of_continuous_on _ C, simpa [nhds_within_univ] using L end /-- A function which can be uniformly approximated by continuous functions is continuous. -/ lemma continuous_of_uniform_approx_of_continuous (L : ∀ u ∈ 𝓤 β, ∃ N, ∀ y, (f y, F N y) ∈ u) : (∀ n, continuous (F n)) → continuous f := continuous_of_locally_uniform_approx_of_continuous $ λx u hu, ⟨univ, by simpa [filter.univ_mem_sets] using L u hu⟩ /-! ### Uniform limits From the previous statements on uniform approximation, we deduce continuity results for uniform limits. -/ /-- A locally uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ lemma tendsto_locally_uniformly_on.continuous_on (h : tendsto_locally_uniformly_on F f p s) (hc : ∀ n, continuous_on (F n) s) (hp : p ≠ ⊥) : continuous_on f s := begin apply continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, _) hc, rcases h u hu x hx with ⟨t, ht, H⟩, exact ⟨t, ht, H.exists hp⟩ end /-- A uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ lemma tendsto_uniformly_on.continuous_on (h : tendsto_uniformly_on F f p s) (hc : ∀ n, continuous_on (F n) s) (hp : p ≠ ⊥) : continuous_on f s := h.tendsto_locally_uniformly_on.continuous_on hc hp /-- A locally uniform limit of continuous functions is continuous. -/ lemma tendsto_locally_uniformly.continuous (h : tendsto_locally_uniformly F f p) (hc : ∀ n, continuous (F n)) (hp : p ≠ ⊥) : continuous f := begin apply continuous_of_locally_uniform_approx_of_continuous (λ x u hu, _) hc, rcases h u hu x with ⟨t, ht, H⟩, exact ⟨t, ht, H.exists hp⟩ end /-- A uniform limit of continuous functions is continuous. -/ lemma tendsto_uniformly.continuous (h : tendsto_uniformly F f p) (hc : ∀ n, continuous (F n)) (hp : p ≠ ⊥) : continuous f := h.tendsto_locally_uniformly.continuous hc hp /-! ### Composing limits under uniform convergence In general, if `Fₙ` converges pointwise to a function `f`, and `gₙ` tends to `x`, it is not true that `Fₙ gₙ` tends to `f x`. It is true however if the convergence of `Fₙ` to `f` is uniform. In this paragraph, we prove variations around this statement. -/ /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` within a set `s` to a function `f` which is continuous at `x` within `s `, and `gₙ` tends to `x` within `s`, then `Fₙ (gₙ)` tends to `f x`. -/ lemma tendsto_comp_of_locally_uniform_limit_within (h : continuous_within_at f s x) (hg : tendsto g p (nhds_within x s)) (hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := begin apply uniform.tendsto_nhds_right.2 (λ u₀ hu₀, _), obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ := comp_mem_uniformity_sets hu₀, rcases hunif u₁ h₁ with ⟨s, sx, hs⟩, have A : ∀ᶠ n in p, g n ∈ s := hg sx, have B : ∀ᶠ n in p, (f x, f (g n)) ∈ u₁ := hg (uniform.continuous_within_at_iff'_right.1 h h₁), refine ((hs.and A).and B).mono (λ y hy, _), rcases hy with ⟨⟨H1, H2⟩, H3⟩, exact u₁₀ (prod_mk_mem_comp_rel H3 (H1 _ H2)) end /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` to a function `f` which is continuous at `x`, and `gₙ` tends to `x`, then `Fₙ (gₙ)` tends to `f x`. -/ lemma tendsto_comp_of_locally_uniform_limit (h : continuous_at f x) (hg : tendsto g p (𝓝 x)) (hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := begin rw ← continuous_within_at_univ at h, rw ← nhds_within_univ at hunif hg, exact tendsto_comp_of_locally_uniform_limit_within h hg hunif end /-- If `Fₙ` tends locally uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s` and `x ∈ s`. -/ lemma tendsto_locally_uniformly_on.tendsto_comp (h : tendsto_locally_uniformly_on F f p s) (hf : continuous_within_at f s x) (hx : x ∈ s) (hg : tendsto g p (nhds_within x s)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, h u hu x hx) /-- If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. -/ lemma tendsto_uniformly_on.tendsto_comp (h : tendsto_uniformly_on F f p s) (hf : continuous_within_at f s x) (hg : tendsto g p (nhds_within x s)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, ⟨s, self_mem_nhds_within, h u hu⟩) /-- If `Fₙ` tends locally uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ lemma tendsto_locally_uniformly.tendsto_comp (h : tendsto_locally_uniformly F f p) (hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit hf hg (λ u hu, h u hu x) /-- If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ lemma tendsto_uniformly.tendsto_comp (h : tendsto_uniformly F f p) (hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := h.tendsto_locally_uniformly.tendsto_comp hf hg
72bd817355090e8970f7c459674a1e9f34098024
618003631150032a5676f229d13a079ac875ff77
/src/topology/subset_properties.lean
db7641c548ac8914001b0c5dbb54e7952567a0f7
[ "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
54,400
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, Yury Kudryashov -/ import topology.continuous_on /-! # Properties of subsets of topological spaces ## Main definitions `compact`, `is_clopen`, `is_irreducible`, `is_connected`, `is_totally_disconnected`, `is_totally_separated` TODO: write better docs ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible and connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible` and `is_preconnected` respectively. In other words, the only difference is whether the empty space counts as irreducible and/or connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical open_locale classical topological_space universes u v variables {α : Type u} {β : Type v} [topological_space α] /- compact sets -/ section compact /-- A set `s` is compact if for every filter `f` that contains `s`, every set of `f` also meets every neighborhood of some `a ∈ s`. -/ def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ 𝓝 a ≠ ⊥ lemma compact.inter_right {s t : set α} (hs : compact s) (ht : is_closed t) : compact (s ∩ t) := assume f hnf hstf, let ⟨a, hsa, (ha : f ⊓ 𝓝 a ≠ ⊥)⟩ := hs f hnf (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))) in have a ∈ t, from ht.mem_of_nhds_within_ne_bot $ ne_bot_of_le_ne_bot (by { rw inf_comm at ha, exact ha }) $ inf_le_inf_left _ (le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), ⟨a, ⟨hsa, this⟩, ha⟩ lemma compact.inter_left {s t : set α} (ht : compact t) (hs : is_closed s) : compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs lemma compact_diff {s t : set α} (hs : compact s) (ht : is_open t) : compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) lemma compact_of_is_closed_subset {s t : set α} (hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma compact.adherence_nhdset {s t : set α} {f : filter α} (hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, 𝓝 a ⊓ f ≠ ⊥ → a ∈ t) : t ∈ f := classical.by_cases mem_sets_of_eq_bot $ assume : f ⊓ principal (- t) ≠ ⊥, let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ 𝓝 a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha $ ne_bot_of_le_ne_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left, have (-t) ∩ t ∈ nhds_within a (-t), from inter_mem_nhds_within _ (mem_nhds_sets ht₁ this), have A : nhds_within a (-t) = ⊥, from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this, have nhds_within a (-t) ≠ ⊥, from ne_bot_of_le_ne_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right, absurd A this lemma compact_iff_ultrafilter_le_nhds {s : set α} : compact s ↔ (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ 𝓝 a) := ⟨assume hs : compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ 𝓝 a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ 𝓝 a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have ultrafilter_of f ⊓ 𝓝 a ≠ ⊥, by simp only [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, ne_bot_of_le_ne_bot this (inf_le_inf_right _ ultrafilter_of_le)⟩⟩ /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma compact.elim_finite_subcover {s : set α} {ι : Type v} (hs : compact s) (U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := classical.by_contradiction $ assume h, have h : ∀ t : finset ι, ¬ s ⊆ ⋃ i ∈ t, U i, from assume t ht, h ⟨t, ht⟩, let f : filter α := (⨅t:finset ι, principal (s - ⋃ i ∈ t, U i)), ⟨a, ha⟩ := (@ne_empty_iff_nonempty α s).1 (assume h', h ∅ $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_ne_bot_of_directed ⟨a⟩ (assume t₁ t₂, ⟨t₁ ∪ t₂, principal_mono.mpr $ diff_subset_diff_right $ bUnion_subset_bUnion_left $ finset.subset_union_left _ _, principal_mono.mpr $ diff_subset_diff_right $ bUnion_subset_bUnion_left $ finset.subset_union_right _ _⟩) (assume t, show principal (s \ _) ≠ ⊥, by simp only [ne.def, principal_eq_bot_iff, diff_eq_empty]; exact h _), have f ≤ principal s, from infi_le_of_le ∅ $ show principal (s \ _) ≤ principal s, from le_principal_iff.2 (diff_subset _ _), let ⟨a, ha, (h : f ⊓ 𝓝 a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this, ⟨_, ⟨i, rfl⟩, (ha : a ∈ U i)⟩ := hsU ha in have f ≤ principal (- U i), from infi_le_of_le {i} $ principal_mono.mpr $ show s - _ ⊆ - U i, by simp [diff_subset_iff], have is_closed (- U i), from is_open_compl_iff.mp $ by rw compl_compl; exact hUo i, have a ∈ - U i, from is_closed_iff_nhds.mp this _ $ ne_bot_of_le_ne_bot h $ le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- U i)›), this ‹a ∈ U i› /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : compact s) (Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, - Z i) hZc (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin apply hι.elim, intro i₀, let Z' := λ i, Z i ∩ Z i₀, suffices : (⋂ i, Z' i).nonempty, { exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this }, rw ← ne_empty_iff_nonempty, intro H, obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅, from (hZc i₀).elim_finite_subfamily_closed Z' (assume i, is_closed_inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]), obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i, { rcases directed.finset_le hι hZd t with ⟨i, hi⟩, rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩, use [i₁, hi₁₀], intros j hj, exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ }, suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty, { rw ← ne_empty_iff_nonempty at this, contradiction }, refine nonempty.mono _ (hZn i₁), exact subset_inter hi₁.left (subset_bInter hi₁.right) end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd, have hZd : directed (⊇) Z, from directed_of_mono Z Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i), compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma compact.elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α} (hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := begin rcases hs.elim_finite_subcover (λ i, c i.1 : b → set α) _ _ with ⟨d, hd⟩, refine ⟨↑(d.image subtype.val), _, finset.finite_to_set _, _⟩, { intros i hi, erw finset.mem_image at hi, rcases hi with ⟨s, hsd, rfl⟩, exact s.property }, { refine subset.trans hd _, rintros x ⟨_, ⟨s, rfl⟩, ⟨_, ⟨hsd, rfl⟩, H⟩⟩, refine ⟨c s.val, ⟨s.val, _⟩, H⟩, simp [finset.mem_image_of_mem subtype.val hsd] }, { rintro ⟨i, hi⟩, exact hc₁ i hi }, { refine subset.trans hc₂ _, rintros x ⟨_, ⟨i, rfl⟩, ⟨_, ⟨hib, rfl⟩, H⟩⟩, exact ⟨_, ⟨⟨i, hib⟩, rfl⟩, H⟩ }, end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_of_finite_subfamily_closed {s : set α} (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ 𝓝 x ≠ ⊥), have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥, by simpa only [not_exists, not_not, inf_comm], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ 𝓝 x ⊓ principal t₂, from (𝓝 x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have 𝓝 x ⊓ principal t₂ = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp only [closure_eq_nhds] at hx; exact hx t₂ ht₂ this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂i∈t, subtype.val i) ∈ f, from Inter_mem_sets t.finite_to_set $ assume i hi, i.2, have s ∩ (⋂i∈t, subtype.val i) ∈ f, from inter_mem_sets (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit), show false, from hxi this, hfn $ by rwa [empty_in_sets_eq_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_of_finite_subcover {s : set α} (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : compact s := compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, - Z i) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_iff_finite_subcover {s : set α} : compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_iff_finite_subfamily_closed {s : set α} : compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, compact_of_finite_subfamily_closed⟩ @[simp] lemma compact_empty : compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf @[simp] lemma compact_singleton {a : α} : compact ({a} : set α) := compact_of_finite_subcover $ assume ι U hUo hsU, let ⟨i, hai⟩ := (show ∃i : ι, a ∈ U i, from mem_Union.1 $ singleton_subset_iff.1 hsU) in ⟨{i}, singleton_subset_iff.2 (by simpa only [finset.bUnion_singleton])⟩ lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s) (hf : ∀i ∈ s, compact (f i)) : compact (⋃i ∈ s, f i) := compact_of_finite_subcover $ assume ι U hUo hsU, have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bind finset.univ finite_subcovers in have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bind.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma compact_Union {f : β → set α} [fintype β] (h : ∀i, compact (f i)) : compact (⋃i, f i) := by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i) lemma set.finite.compact {s : set α} (hs : finite s) : compact s := bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, compact_singleton) lemma compact.union {s t : set α} (hs : compact s) (ht : compact t) : compact (s ∪ t) := by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption) section tube_lemma variables [topological_space β] /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (continuous_swap n hn) (by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : compact (univ : set α)) lemma compact_univ [h : compact_space α] : compact (univ : set α) := h.compact_univ lemma cluster_point_of_compact [compact_space α] {f : filter α} (h : f ≠ ⊥) : ∃ x, f ⊓ 𝓝 x ≠ ⊥ := by simpa using compact_univ f h (by simpa using f.univ_sets) theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α] (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → (∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅)) : compact_space α := { compact_univ := begin apply compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.compact [compact_space α] {s : set α} (h : is_closed s) : compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) variables [topological_space β] lemma compact.image_of_continuous_on {s : set α} {f : α → β} (hs : compact s) (hf : continuous_on f s) : compact (f '' s) := begin intros l lne ls, have ne_bot : l.comap f ⊓ principal s ≠ ⊥, from comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), rcases hs (l.comap f ⊓ principal s) ne_bot inf_le_right with ⟨a, has, ha⟩, use [f a, mem_image_of_mem f has], rw [inf_assoc, @inf_comm _ _ _ (𝓝 a)] at ha, exact ne_bot_of_le_ne_bot (@@map_ne_bot f ha) (tendsto_comap.inf $ hf a has) end lemma compact.image {s : set α} {f : α → β} (hs : compact s) (hf : continuous f) : compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) : compact (range f) := by rw ← image_univ; exact compact_univ.image hf local notation `𝓟` := principal /-- If X is compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_nhds at hC ⊢, assume y (y_closure : 𝓝 y ⊓ 𝓟 (πY '' C) ≠ ⊥), have : map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ≠ ⊥, { suffices : map πY (comap πY (𝓝 y) ⊓ 𝓟 C) ≠ ⊥, from map_ne_bot (λ h, this $ by rw h ; exact map_bot ), calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal ... ≠ ⊥ : y_closure }, obtain ⟨x, hx⟩ : ∃ x, map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x ≠ ⊥, from cluster_point_of_compact this, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw ← filter.map_ne_bot_iff πX, calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... ≠ ⊥ : hx, end lemma embedding.compact_iff_compact_image {s : set α} {f : α → β} (hf : embedding f) : compact s ↔ compact (f '' s) := iff.intro (assume h, h.image hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ principal (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.inj end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap] end lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : compact s ↔ compact (subtype.val '' s) := embedding_subtype_val.compact_iff_compact_image lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.val_range]; refl lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s := compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ lemma compact.prod {s : set α} {t : set β} (hs : compact s) (ht : compact t) : compact (set.prod s t) := begin rw compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hf hfs, rw le_principal_iff at hfs, rcases hs (map prod.fst f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩, rcases ht (map prod.snd f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩, rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end /-- Finite topological spaces are compact. -/ @[priority 100] instance fintype.compact_space [fintype α] : compact_space α := { compact_univ := set.finite_univ.compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (compact_range continuous_inl).union (compact_range continuous_inr) end⟩ section tychonoff variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)] /-- Tychonoff's theorem -/ lemma compact_pi_infinite {s : Πi:ι, set (π i)} : (∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ 𝓝 a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets, from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩ end instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) := ⟨begin have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} := compact_pi_infinite (λi, compact_univ), have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp, rwa this at A, end⟩ end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ compact s) end compact section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩ theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen (-s) := ⟨hs.2, is_closed_compl_iff.2 hs.1⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen (-s) ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩ theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s-t) := is_clopen_inter hs (is_clopen_compl ht) end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3; substs y z; exact ⟨x, rfl, h2, h4⟩⟩ theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ lemma is_irreducible.closure {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := ⟨h.nonempty.closure, h.is_preirreducible.closure⟩ theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (zorn.chain.total hcc hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component is_irreducible_irreducible_component.is_preirreducible.closure subset_closure /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ [] : is_preirreducible (univ : set α)) section prio set_option default_priority 100 -- see Note [default priority] /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty [] : nonempty α) end prio attribute [instance, priority 50] irreducible_space.to_nonempty -- see Note [lower instance priority] theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← set.mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [set.inter_comm s u', ← u'_eq] at this, rw [set.inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← set.mem_preimage, apply set.mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {u,v} _ _, all_goals { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h (-t₁) (-t₂), simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₁, z₂} _ _, simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end end preirreducible section preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := s.nonempty ∧ is_preconnected s lemma is_connected.nonempty {s : set α} (h : is_connected s) : s.nonempty := h.1 lemma is_connected.is_preconnected {s : set α} (h : is_connected s) : is_preconnected s := h.2 theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) : is_preconnected s := λ _ _ hu hv _, H _ _ hu hv theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s := ⟨H.nonempty, H.is_preirreducible.is_preconnected⟩ theorem is_preconnected_empty : is_preconnected (∅ : set α) := is_preirreducible_empty.is_preconnected theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_irreducible_singleton.is_connected /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {s : set α} (x : α) (H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩, have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt }, wlog xu : x ∈ u := hs xs using [u v y z, v u z y], rcases H y ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {s : set α} (H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) := begin apply is_preconnected_of_forall x, rintros y ⟨s, sc, ys⟩, exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ end theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sUnion_pair s t ▸ is_preconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h); assumption) (by rintro r (rfl | rfl | h); assumption) theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := begin rcases H with ⟨x, hx⟩, refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩, exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Hs.is_preconnected Ht.is_preconnected end theorem is_preconnected.closure {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ theorem is_connected.closure {s : set α} (H : is_connected s) : is_connected (closure s) := ⟨H.nonempty.closure, H.is_preconnected.closure⟩ theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := begin -- Unfold/destruct definitions in hypotheses rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v', { rw [image_subset_iff, preimage_union] at huv, replace huv := subset_inter huv (subset.refl _), rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv, exact (subset_inter_iff.1 huv).1 }, -- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty, { refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm, exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] }, rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz, exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ end theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩ theorem is_preconnected_closed_iff {s : set α} : is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' → (s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty := ⟨begin rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xt' : x ∉ t', from (h' xs).elim (absurd xt) id, have yt : y ∉ t, from (h' ys).elim id (absurd yt'), have := ne_empty_iff_nonempty.2 (h (-t) (-t') (is_open_compl_iff.2 ht) (is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end, begin rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xv : x ∉ v, from (h' xs).elim (absurd xu) id, have yu : y ∉ u, from (h' ys).elim id (absurd yv), have := ne_empty_iff_nonempty.2 (h (-u) (-v) (is_closed_compl_iff.2 hu) (is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end⟩ /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_preconnected s ∧ x ∈ s } theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩ theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := ⟨⟨x, mem_connected_component⟩, is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left)⟩ theorem subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (subset_connected_component is_connected_connected_component.closure.is_preconnected (subset_closure mem_connected_component)) subset_closure theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := subset_connected_component is_irreducible_irreducible_component.is_connected.is_preconnected mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] : Prop := (is_preconnected_univ : is_preconnected (univ : set α)) section prio set_option default_priority 100 -- see Note [default priority] /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop := (to_nonempty : nonempty α) end prio attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority] @[priority 100] -- see Note [lower instance priority] instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := ⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩ @[priority 100] -- see Note [lower instance priority] instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := { to_nonempty := irreducible_space.to_nonempty α } theorem nonempty_inter [preconnected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preconnected_space.is_preconnected_univ α _ _ s t theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ -s ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2 (union_compl_self s) (ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) : preconnected_space s := { is_preconnected_univ := begin intros u v hu hv hs hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩, intros z hz, rcases hs (set.mem_univ ⟨z, hz⟩) with hzu|hzv, { left, assumption }, { right, assumption } end } lemma subtype.connected_space {s : set α} (h : is_connected s) : connected_space s := { is_preconnected_univ := (subtype.preconnected_space h.is_preconnected).is_preconnected_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ lemma is_preconnected_iff_subset_of_disjoint {s : set α} : is_preconnected s ↔ ∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := classical.or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := classical.or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ lemma is_connected_iff_sUnion_disjoint_open {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v) (hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U), ∃ u ∈ U, s ⊆ u := begin rw [is_connected, is_preconnected_iff_subset_of_disjoint], split; intro h, { intro U, apply finset.induction_on U, { rcases h.left, suffices : s ⊆ ∅ → false, { simpa }, intro, solve_by_elim }, { intros u U hu IH hs hU H, rw [finset.coe_insert, sUnion_insert] at H, cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU, { exact ⟨u, finset.mem_insert_self _ _, hsu⟩ }, { rcases IH _ _ hsU with ⟨v, hvU, hsv⟩, { exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ }, { intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sUnion, intros, solve_by_elim [finset.mem_insert_of_mem] }, { apply eq_empty_of_subset_empty, rintro x ⟨hxs, hxu, hxU⟩, rw mem_sUnion at hxU, rcases hxU with ⟨v, hvU, hxv⟩, rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl, { contradiction }, { exact ⟨x, hxs, hxu, hxv⟩ } } } }, { split, { rw ← ne_empty_iff_nonempty, by_contradiction hs, push_neg at hs, subst hs, simpa using h ∅ _ _ _; simp }, intros u v hu hv hs hsuv, rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩, { rw [finset.mem_insert, finset.mem_singleton] at ht, rcases ht with rfl|rfl; tauto }, { intros t₁ t₂ ht₁ ht₂ hst, rw ← ne_empty_iff_nonempty at hst, rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂, rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl, all_goals { refl <|> contradiction <|> skip }, rw inter_comm t₁ at hst, contradiction }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using hs } } end end preconnected section totally_disconnected /-- A set is called totally disconnected if all of its connected components are singletons. -/ def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_preconnected t → subsingleton t theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩ theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q, from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩ /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) end totally_disconnected section totally_separated /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $ assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in (ext_iff.1 huv r).1 hruv⟩ /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ [] : is_totally_separated (univ : set α)) @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ end totally_separated
a9323d8a3f9bee9e5172055c83d02a114f44ebfe
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/witt_vector/structure_polynomial.lean
884a059a1e176cbd02d70bfb1f6523f0d748d189
[]
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
13,892
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.matrix.notation import Mathlib.field_theory.mv_polynomial import Mathlib.field_theory.finite.polynomial import Mathlib.number_theory.basic import Mathlib.ring_theory.witt_vector.witt_polynomial import Mathlib.PostPort universes u_2 u_1 namespace Mathlib /-! # Witt structure polynomials In this file we prove the main theorem that makes the whole theory of Witt vectors work. Briefly, consider a polynomial `Φ : mv_polynomial idx ℤ` over the integers, with polynomials variables indexed by an arbitrary type `idx`. Then there exists a unique family of polynomials `φ : ℕ → mv_polynomial (idx × ℕ) Φ` such that for all `n : ℕ` we have (`witt_structure_int_exists_unique`) ``` bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℤ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. N.b.: As far as we know, these polynomials do not have a name in the literature, so we have decided to call them the “Witt structure polynomials”. See `witt_structure_int`. ## Special cases With the main result of this file in place, we apply it to certain special polynomials. For example, by taking `Φ = X tt + X ff` resp. `Φ = X tt * X ff` we obtain families of polynomials `witt_add` resp. `witt_mul` (with type `ℕ → mv_polynomial (bool × ℕ) ℤ`) that will be used in later files to define the addition and multiplication on the ring of Witt vectors. ## Outline of the proof The proof of `witt_structure_int_exists_unique` is rather technical, and takes up most of this file. We start by proving the analogous version for polynomials with rational coefficients, instead of integer coefficients. In this case, the solution is rather easy, since the Witt polynomials form a faithful change of coordinates in the polynomial ring `mv_polynomial ℕ ℚ`. We therefore obtain a family of polynomials `witt_structure_rat Φ` for every `Φ : mv_polynomial idx ℚ`. If `Φ` has integer coefficients, then the polynomials `witt_structure_rat Φ n` do so as well. Proving this claim is the essential core of this file, and culminates in `map_witt_structure_int`, which proves that upon mapping the coefficients of `witt_structure_int Φ n` from the integers to the rationals, one obtains `witt_structure_rat Φ n`. Ultimately, the proof of `map_witt_structure_int` relies on ``` dvd_sub_pow_of_dvd_sub {R : Type*} [comm_ring R] {p : ℕ} {a b : R} : (p : R) ∣ a - b → ∀ (k : ℕ), (p : R) ^ (k + 1) ∣ a ^ p ^ k - b ^ p ^ k ``` ## Main results * `witt_structure_rat Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` associated with `Φ : mv_polynomial idx ℚ` and satisfying the property explained above. * `witt_structure_rat_prop`: the proof that `witt_structure_rat` indeed satisfies the property. * `witt_structure_int Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℤ` associated with `Φ : mv_polynomial idx ℤ` and satisfying the property explained above. * `map_witt_structure_int`: the proof that the integral polynomials `with_structure_int Φ` are equal to `witt_structure_rat Φ` when mapped to polynomials with rational coefficients. * `witt_structure_int_prop`: the proof that `witt_structure_int` indeed satisfies the property. * Five families of polynomials that will be used to define the ring structure on the ring of Witt vectors: - `witt_vector.witt_zero` - `witt_vector.witt_one` - `witt_vector.witt_add` - `witt_vector.witt_mul` - `witt_vector.witt_neg` (We also define `witt_vector.witt_sub`, and later we will prove that it describes subtraction, which is defined as `λ a b, a + -b`. See `witt_vector.sub_coeff` for this proof.) -/ -- This lemma reduces a bundled morphism to a "mere" function, -- and consequently the simplifier cannot use a lot of powerful simp-lemmas. -- We disable this locally, and probably it should be disabled globally in mathlib. /-- `witt_structure_rat Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that ``` bind₁ (witt_structure_rat p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_rat Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_rat_prop` for this property, and `witt_structure_rat_exists_unique` for the fact that `witt_structure_rat` gives the unique family of polynomials with this property. These polynomials turn out to have integral coefficients, but it requires some effort to show this. See `witt_structure_int` for the version with integral coefficients, and `map_witt_structure_int` for the fact that it is equal to `witt_structure_rat` when mapped to polynomials over the rationals. -/ def witt_structure_rat (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (n : ℕ) : mv_polynomial (idx × ℕ) ℚ := coe_fn (mv_polynomial.bind₁ fun (k : ℕ) => coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℚ k)) Φ) (X_in_terms_of_W p ℚ n) theorem witt_structure_rat_prop (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (n : ℕ) : coe_fn (mv_polynomial.bind₁ (witt_structure_rat p Φ)) (witt_polynomial p ℚ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℚ n)) Φ := sorry theorem witt_structure_rat_exists_unique (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) : exists_unique fun (φ : ℕ → mv_polynomial (idx × ℕ) ℚ) => ∀ (n : ℕ), coe_fn (mv_polynomial.bind₁ φ) (witt_polynomial p ℚ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℚ n)) Φ := sorry theorem witt_structure_rat_rec_aux (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (n : ℕ) : witt_structure_rat p Φ n * coe_fn mv_polynomial.C (↑p ^ n) = coe_fn (mv_polynomial.bind₁ fun (b : idx) => coe_fn (mv_polynomial.rename fun (i : ℕ) => (b, i)) (witt_polynomial p ℚ n)) Φ - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * witt_structure_rat p Φ i ^ p ^ (n - i) := sorry /-- Write `witt_structure_rat p φ n` in terms of `witt_structure_rat p φ i` for `i < n`. -/ theorem witt_structure_rat_rec (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (n : ℕ) : witt_structure_rat p Φ n = coe_fn mv_polynomial.C (1 / ↑p ^ n) * (coe_fn (mv_polynomial.bind₁ fun (b : idx) => coe_fn (mv_polynomial.rename fun (i : ℕ) => (b, i)) (witt_polynomial p ℚ n)) Φ - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * witt_structure_rat p Φ i ^ p ^ (n - i)) := sorry /-- `witt_structure_int Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that ``` bind₁ (witt_structure_int p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_int Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_int_prop` for this property, and `witt_structure_int_exists_unique` for the fact that `witt_structure_int` gives the unique family of polynomials with this property. -/ def witt_structure_int (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) : mv_polynomial (idx × ℕ) ℤ := finsupp.map_range rat.num sorry (witt_structure_rat p (coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) Φ) n) theorem bind₁_rename_expand_witt_polynomial {p : ℕ} {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ (m : ℕ), m < n + 1 → coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) (witt_structure_int p Φ m) = witt_structure_rat p (coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) Φ) m) : coe_fn (mv_polynomial.bind₁ fun (b : idx) => coe_fn (mv_polynomial.rename fun (i : ℕ) => (b, i)) (coe_fn (mv_polynomial.expand p) (witt_polynomial p ℤ n))) Φ = coe_fn (mv_polynomial.bind₁ fun (i : ℕ) => coe_fn (mv_polynomial.expand p) (witt_structure_int p Φ i)) (witt_polynomial p ℤ n) := sorry theorem C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum {p : ℕ} {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ (m : ℕ), m < n → coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) (witt_structure_int p Φ m) = witt_structure_rat p (coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) Φ) m) : coe_fn mv_polynomial.C ↑(p ^ n) ∣ coe_fn (mv_polynomial.bind₁ fun (b : idx) => coe_fn (mv_polynomial.rename fun (i : ℕ) => (b, i)) (witt_polynomial p ℤ n)) Φ - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * witt_structure_int p Φ i ^ p ^ (n - i) := sorry @[simp] theorem map_witt_structure_int (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) : coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) (witt_structure_int p Φ n) = witt_structure_rat p (coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) Φ) n := sorry theorem witt_structure_int_prop (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) : coe_fn (mv_polynomial.bind₁ (witt_structure_int p Φ)) (witt_polynomial p ℤ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℤ n)) Φ := sorry theorem eq_witt_structure_int (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (φ : ℕ → mv_polynomial (idx × ℕ) ℤ) (h : ∀ (n : ℕ), coe_fn (mv_polynomial.bind₁ φ) (witt_polynomial p ℤ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℤ n)) Φ) : φ = witt_structure_int p Φ := sorry theorem witt_structure_int_exists_unique (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) : exists_unique fun (φ : ℕ → mv_polynomial (idx × ℕ) ℤ) => ∀ (n : ℕ), coe_fn (mv_polynomial.bind₁ φ) (witt_polynomial p ℤ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℤ n)) Φ := Exists.intro (witt_structure_int p Φ) { left := witt_structure_int_prop p Φ, right := eq_witt_structure_int p Φ } theorem witt_structure_prop (p : ℕ) {R : Type u_1} {idx : Type u_2} [comm_ring R] [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) : coe_fn (mv_polynomial.aeval fun (i : ℕ) => coe_fn (mv_polynomial.map (int.cast_ring_hom R)) (witt_structure_int p Φ i)) (witt_polynomial p ℤ n) = coe_fn (mv_polynomial.aeval fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p R n)) Φ := sorry theorem witt_structure_int_rename (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] {σ : Type u_1} (Φ : mv_polynomial idx ℤ) (f : idx → σ) (n : ℕ) : witt_structure_int p (coe_fn (mv_polynomial.rename f) Φ) n = coe_fn (mv_polynomial.rename (prod.map f id)) (witt_structure_int p Φ n) := sorry @[simp] theorem constant_coeff_witt_structure_rat_zero (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) : coe_fn mv_polynomial.constant_coeff (witt_structure_rat p Φ 0) = coe_fn mv_polynomial.constant_coeff Φ := sorry theorem constant_coeff_witt_structure_rat (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (h : coe_fn mv_polynomial.constant_coeff Φ = 0) (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_structure_rat p Φ n) = 0 := sorry @[simp] theorem constant_coeff_witt_structure_int_zero (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) : coe_fn mv_polynomial.constant_coeff (witt_structure_int p Φ 0) = coe_fn mv_polynomial.constant_coeff Φ := sorry theorem constant_coeff_witt_structure_int (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (h : coe_fn mv_polynomial.constant_coeff Φ = 0) (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_structure_int p Φ n) = 0 := sorry -- we could relax the fintype on `idx`, but then we need to cast from finset to set. -- for our applications `idx` is always finite. theorem witt_structure_rat_vars (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] [fintype idx] (Φ : mv_polynomial idx ℚ) (n : ℕ) : mv_polynomial.vars (witt_structure_rat p Φ n) ⊆ finset.product finset.univ (finset.range (n + 1)) := sorry -- we could relax the fintype on `idx`, but then we need to cast from finset to set. -- for our applications `idx` is always finite. theorem witt_structure_int_vars (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] [fintype idx] (Φ : mv_polynomial idx ℤ) (n : ℕ) : mv_polynomial.vars (witt_structure_int p Φ n) ⊆ finset.product finset.univ (finset.range (n + 1)) := sorry
b510e86f0d942c0d234da295f7c0ce4ab640ca6f
a6b711a4e8db20755026231f7ed529a9014b2b6d
/ZZ_IGNORE/RAW/type_and_set_theory.lean
8bfd74b96452641c4d85ba9b83b449dc3dccc676
[]
no_license
chaseboettner/cs-dm-1
b67d4a7e86f56bce59d2af115503769749d423b2
80b35f2957ffaa45b8b7a4479a3570a2d6eb4db0
refs/heads/master
1,585,367,603,488
1,536,235,675,000
1,536,235,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,792
lean
/- ** Logical Foundations of Mathematics ** -/ /- Modern mathematics is axiomatic. It's logical. It is "founded" on mutually consistent axioms and inference rules. There is however more than one way to establish the logical foundations of mathematics. The most widely used axiomatic foundation comprises a set of axioms that describes what it means to be a set, and everything else then builds on the concept of sets. The resulting theory is called "set theory." Set theory is the most widely accepted and used logical foundation for everyday mathematics. The natural numbers for example can be "formalized" as sets. Zero is represented by the empty set; one by the set that contains only the empty set; two by the set that contains that set; and so forth. The specific set theory foundation for ordinary mathematics is known as Zermelo-Frankl Set Theory with the Axiom of Choice (often abbreviated as ZFC). The axioms of ZFC capture our "naïve" view of sets as collections of elements. It took much time and great care, however, to craft a set of axioms that are not self-contradicting. The original formulation of set theory turned out to be inconsistent! (Does the set of all sets that do not contain themselves contain itself? If it does, then it doesn't, and if it doesn't then it does: a real inconsistency! In fact it was this problem that led mathematicians to a much more careful notion of what it means to be a set, as captured by the axioms of ZFC. As another example of an inconsistency, there's a word in the English language to describe words that describe themselves: autological. The antonym of autological is heterological. "Polysyllabic" is autological, but "palindrome" is heterological. Is the word "heterological" heterological? If the word doesn't describe itself, then it is, but then the word would describe itself. So, yeah, English is inconsistent in this sense.) The axioms of ZFC are somewhat technical; we will not explore them in this class. What you might want to remember is that if you want to prove even simple mathematical proposition in a precise, fully formal way using ZFC, it is a complex and messy affair. In fact, it's so messy that most mathematicians trade in rigorous but informal proofs. By informal proofs we mean mathematical arguments written in a stylized form of a natural language, such as English. For example, a proof of 0 = 0 and 1 = 1 might read like this: "To prove the proposition, which is a conjunction, we need proofs of the two parts. The first, 0 = 0, is proved by noting that equality is a reflexive relation, and 1 = 1 is proved similarly. Given that both conjuncts are so, then so is the overall conjunction. So it is shown (QED in latin)." Because machines aren't much good at figuring out what natural language text means with mathematical precision, it's nearly impossible today for computers to check that purported informal proofs are correct. Proof checking remains a demanding, mostly human, and social process. When a mathematician claims to have produced a proof of a theorem of potential significance, other experts come together (often as reviewers for journals to which mathematical purported proofs are generally submitted for review and publication) to see if they can find any errors in reasoning. They often do! Such human proof checking has in some cases proved to be nearly intractable. For example, in 2012, Shinichi Mochizuki, a reclusive Japanse mathematician, quietly posted to the web a 500-page "putative" proof of a major mathematical conjecture (proposition for which there is not yet a proof) in number theory and geometry. If correct, it could revolutionize mathematics. Yet the work is so complex and unusual that the mathematical community even to this day has still been unable even to comprehend the overall concept, not to mention checking every last detail for subtle errors. -/ /- HOMEWORK: Read this article. https://www.sciencealert.com/nightmarish-500-page-math-proof-even-experts-can-t-understand-about-published-shinichi-mochizuki -/ /- An alternative foundation for mathematics (in particular for what is called "constructive" mathematics) is available in what is called "type theory." It's basically a different (from ZFC) set of axioms and inference rules on which math can be based. Not surprisingly, types, rather than sets, are a fundamental building block of mathematics in type theory. Sets can be modeled, but they are not built in. From your high school math background, you probably already have a reasonable intuition for sets as collections of values. A type also defines a set of values, and each value in that set has that type. But whereas a value can be in many sets, in type theory a value has exactly one type. Whenever you see a value, or an expression that reduces to a value, in type theory, it thus makes sense to ask the question, what is its type? Every well formed expression and value in a type theory has exactly one type. In Lean, we can ask the type of an expression (including of a literal expression that directly denotes a value) by using the check command. Hover your mouse over the #check command. Note that ℕ is mathematical notation for "natural number", the type of non-negative integers. -/ -- The types of some literal expressions #check 0 #check "Hello" #check tt -- defining a binding of an identifier to a value def foo := 0 -- The type of a variable expression #check foo -- The types of some more complex expressions #check 1 + foo #check "Hello " ++ "Logic!" #check tt && ff /- Without getting into complicated details, it will suffice for now to say that proofs are much more tractable objects in type theory than in set theory. Type theory has thus emerged as an important framework for *automating* the handling of logic in both mathematics and computer science. For computer scientists, it is also the main foundation for functional programming, the theory of programming languages, and for formal verification of software correctness, which is vitally important when ultra-high levels of confidence in the correctness of code is required (e.g., for security). This very tool and language that you're using now, the Lean prover, is based on type theory. It's am example of what's known in the business as a proof assistant. But you can just think of it for now as a really cool tool in which you can write both programs and logic, and that can help you to construct "manageable" proofs. Through the magic of type checking it then *automatically* determines whether a proof is valid for a given proposition. This technology holds the promise of eventually changing the way that code is written and verified, and even the way that mathematics work. -/
b97861b1253d4b0eff92d12a78741316905c59f5
94096349332b0a0e223a22a3917c8f253cd39235
/src/game/world1/level2.lean
5d56394b7bd4d76c5b951e4b4654c7a74f16116f
[]
no_license
robertylewis/natural_number_game
26156e10ef7b45248549915cc4d1ab3d8c3afc85
b210c05cd627242f791db1ee3f365ee7829674c9
refs/heads/master
1,598,964,725,038
1,572,602,236,000
1,572,602,236,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,780
lean
import mynat.mul -- hide namespace mynat -- hide /- # World 1 : Tutorial world ## level 2: The rewrite (`rw`) tactic. The rewrite tactic is the way to "substitute in" the value of a variable. In general, if you have a hypothesis of the form `A = B`, and your goal mentions the left hand side `A` somewhere, then the `rewrite` tactic will replace the `A` in your goal with a `B`. Below is a theorem which cannot be proved using `refl` -- you need a rewrite first. Delete the sorry and take a look in the top right box at what we have. The variables $x$ and $y$ are natural numbers, and we have a proof `h` that $y = x + 7$. Our goal is to prove that $2y=2(x+7)$. This goal is obvious -- we just substitute in $y = x+7$ and we're done. In Lean, we do this substitution using the `rw` tactic. So start your proof with `rw h,` and then hit enter. **Don't forget the comma.** Did you see what happened to the goal? The goal doesn't close, but it *changes* from `⊢ 2 * y = 2 * (x + 7)` to `⊢ 2 * (x + 7) = 2 * (x + 7)`. We can just close this goal with `refl,` by writing it on the line after `rw h,`. Don't forget the comma, hit enter, and enjoy seeing the "Proof complete!" message in the top right window. The other reason you'll know you're done is that the bottom right window (the error window) becomes empty. -/ /- Lemma : no-side-bar If $x$ and $y$ are natural numbers, and $y=x+7$, then $2y=2(x+7)$. -/ lemma example2 (x y z : mynat) (h : y = x + 7) : 2 * y = 2 * (x + 7) := begin [less_leaky] rw h, refl end /- Tactic : rw The `rw` tactic is a way to do "substituting in". If `h : A = B` is a hypothesis (i.e., a proof of `A = B`) and your goal contains one or more `A`s, then `rw h` will change them all to `B`'s. If you want to change `B`s to `A`s instead, try `rw ←h` (get the arrow with `\l`). ### Example: If it looks like this in the top right hand box: ``` x y : mynat h : x = y + 3 ⊢ 1 + x = y + 4 ``` then `rw h,` will change the goal into `⊢ 1 + (y + 3) = y + 4`. Note of course that this goal is still far from solved. ### Example: You can rewrite a hypothesis as well. For example, if your local context looks like this: ``` x y : mynat h1 : x = y + 3 h2 : 2 * y = x ⊢ y = 3 ``` then `rw h1 at h2` will turn `h2` into `h2 : 2 * y = y + 3`. -/ /- ## Exploring your proof. Click on `refl,` and then use the arrow keys to move your cursor around the proof. Go up and down and note that the goal changes -- indeed you can inspect Lean's "state" at each line of the proof (the hypotheses, and the goal). Try to figure out the exact place where the goal changes. The comma tells Lean "I've finished writing this tactic now, please process it." Lean ignores newlines, but pays great attention to commas. -/ end mynat -- hide
5c3fb610fa9a21be54818e1873d2f94e75c17a8b
bb31430994044506fa42fd667e2d556327e18dfe
/src/order/prop_instances.lean
e27289e1d81534d314ae4a884ee558eb1eafd36d
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
2,807
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.disjoint import order.with_bot /-! # The order on `Prop` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Instances on `Prop` such as `distrib_lattice`, `bounded_order`, `linear_order`. -/ /-- Propositions form a distributive lattice. -/ instance Prop.distrib_lattice : distrib_lattice Prop := { sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := λ a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := λ a b c, or_and_distrib_left.2, ..Prop.partial_order } /-- Propositions form a bounded order. -/ instance Prop.bounded_order : bounded_order Prop := { top := true, le_top := λ a Ha, true.intro, bot := false, bot_le := @false.elim } lemma Prop.bot_eq_false : (⊥ : Prop) = false := rfl lemma Prop.top_eq_true : (⊤ : Prop) = true := rfl instance Prop.le_is_total : is_total Prop (≤) := ⟨λ p q, by { change (p → q) ∨ (q → p), tauto! }⟩ noncomputable instance Prop.linear_order : linear_order Prop := by classical; exact lattice.to_linear_order Prop @[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl @[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl namespace pi variables {ι : Type*} {α' : ι → Type*} [Π i, partial_order (α' i)] lemma disjoint_iff [Π i, order_bot (α' i)] {f g : Π i, α' i} : disjoint f g ↔ ∀ i, disjoint (f i) (g i) := begin split, { intros h i x hf hg, refine (update_le_iff.mp $ -- this line doesn't work h (update_le_iff.mpr ⟨hf, λ _ _, _⟩) (update_le_iff.mpr ⟨hg, λ _ _, _⟩)).1, { exact ⊥}, { exact bot_le }, { exact bot_le }, }, { intros h x hf hg i, apply h i (hf i) (hg i) }, end lemma codisjoint_iff [Π i, order_top (α' i)] {f g : Π i, α' i} : codisjoint f g ↔ ∀ i, codisjoint (f i) (g i) := @disjoint_iff _ (λ i, (α' i)ᵒᵈ) _ _ _ _ lemma is_compl_iff [Π i, bounded_order (α' i)] {f g : Π i, α' i} : is_compl f g ↔ ∀ i, is_compl (f i) (g i) := by simp_rw [is_compl_iff, disjoint_iff, codisjoint_iff, forall_and_distrib] end pi @[simp] lemma Prop.disjoint_iff {P Q : Prop} : disjoint P Q ↔ ¬(P ∧ Q) := disjoint_iff_inf_le @[simp] lemma Prop.codisjoint_iff {P Q : Prop} : codisjoint P Q ↔ P ∨ Q := codisjoint_iff_le_sup.trans $ forall_const _ @[simp] lemma Prop.is_compl_iff {P Q : Prop} : is_compl P Q ↔ ¬(P ↔ Q) := begin rw [is_compl_iff, Prop.disjoint_iff, Prop.codisjoint_iff, not_iff], tauto, end
2252179fa72e70702d6dbe6fcbccce7bbb26d704
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/init/ua.hlean
5ece71c4c665c968aa5e5faa40427c90e85b928d
[ "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
2,969
hlean
/- Copyright (c) 2014 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 Ported from Coq HoTT -/ prelude import .equiv open eq equiv is_equiv --Ensure that the types compared are in the same universe section universe variable l variables {A B : Type.{l}} definition is_equiv_cast_of_eq [constructor] (H : A = B) : is_equiv (cast H) := is_equiv_tr (λX, X) H definition equiv_of_eq [constructor] (H : A = B) : A ≃ B := equiv.mk _ (is_equiv_cast_of_eq H) definition equiv_of_eq_refl [reducible] [unfold_full] (A : Type) : equiv_of_eq (refl A) = equiv.refl := idp end axiom univalence (A B : Type) : is_equiv (@equiv_of_eq A B) attribute univalence [instance] -- This is the version of univalence axiom we will probably use most often definition ua [reducible] {A B : Type} : A ≃ B → A = B := equiv_of_eq⁻¹ definition eq_equiv_equiv (A B : Type) : (A = B) ≃ (A ≃ B) := equiv.mk equiv_of_eq _ definition equiv_of_eq_ua [reducible] {A B : Type} (f : A ≃ B) : equiv_of_eq (ua f) = f := right_inv equiv_of_eq f definition cast_ua_fn {A B : Type} (f : A ≃ B) : cast (ua f) = f := ap to_fun (equiv_of_eq_ua f) definition cast_ua {A B : Type} (f : A ≃ B) (a : A) : cast (ua f) a = f a := ap10 (cast_ua_fn f) a definition ua_equiv_of_eq [reducible] {A B : Type} (p : A = B) : ua (equiv_of_eq p) = p := left_inv equiv_of_eq p definition eq_of_equiv_lift {A B : Type} (f : A ≃ B) : A = lift B := ua (f ⬝e !equiv_lift) namespace equiv definition ua_refl (A : Type) : ua erfl = idpath A := eq_of_fn_eq_fn !eq_equiv_equiv (right_inv !eq_equiv_equiv erfl) -- One consequence of UA is that we can transport along equivalencies of types -- We can use this for calculation evironments protected definition transport_of_equiv [subst] (P : Type → Type) {A B : Type} (H : A ≃ B) : P A → P B := eq.transport P (ua H) -- we can "recurse" on equivalences, by replacing them by (equiv_of_eq _) definition rec_on_ua [recursor] {A B : Type} {P : A ≃ B → Type} (f : A ≃ B) (H : Π(q : A = B), P (equiv_of_eq q)) : P f := right_inv equiv_of_eq f ▸ H (ua f) -- a variant where we immediately recurse on the equality in the new goal definition rec_on_ua_idp [recursor] {A : Type} {P : Π{B}, A ≃ B → Type} {B : Type} (f : A ≃ B) (H : P equiv.refl) : P f := rec_on_ua f (λq, eq.rec_on q H) -- a variant where (equiv_of_eq (ua f)) will be replaced by f in the new goal definition rec_on_ua' {A B : Type} {P : A ≃ B → A = B → Type} (f : A ≃ B) (H : Π(q : A = B), P (equiv_of_eq q) q) : P f (ua f) := right_inv equiv_of_eq f ▸ H (ua f) -- a variant where we do both definition rec_on_ua_idp' {A : Type} {P : Π{B}, A ≃ B → A = B → Type} {B : Type} (f : A ≃ B) (H : P equiv.refl idp) : P f (ua f) := rec_on_ua' f (λq, eq.rec_on q H) end equiv
470baf43cf419201171d50a7dd6fcbdc7e59d7f1
6e41ee3ac9b96e8980a16295cc21f131e731884f
/tests/lean/run/e6.lean
167a4c5beebaccb2102b291cc8ae914f76c5ca93
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
635
lean
prelude precedence `+`:65 namespace nat constant nat : Type.{1} constant add : nat → nat → nat infixl + := add end nat namespace int open nat (nat) constant int : Type.{1} constant add : int → int → int infixl + := add constant of_nat : nat → int persistent attribute of_nat [coercion] end int open int open nat constants n m : nat constants i j : int check n + m check i + j check i + n check i + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n
24d4cc93dd34d40a6e65fcaa33d82f610ffd4f82
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/artinian.lean
dc54afeb8af1b9603f6fdf59a750f0e39a37b124
[ "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
17,603
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import linear_algebra.basic import linear_algebra.prod import linear_algebra.pi import data.set_like.fintype import linear_algebra.linear_independent import tactic.linarith import algebra.algebra.basic import ring_theory.noetherian import ring_theory.jacobson_ideal import ring_theory.nilpotent import ring_theory.nakayama /-! # Artinian rings and modules A module satisfying these equivalent conditions is said to be an *Artinian* R-module if every decreasing chain of submodules is eventually constant, or equivalently, if the relation `<` on submodules is well founded. A ring is an *Artinian ring* if it is Artinian as a module over itself. (Note that we do not assume yet that our rings are commutative, so perhaps this should be called "left Artinian". To avoid cumbersome names once we specialize to the commutative case, we don't make this explicit in the declaration names.) ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `is_artinian R M` is the proposition that `M` is a Artinian `R`-module. It is a class, implemented as the predicate that the `<` relation on submodules is well founded. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Artinian, artinian, Artinian ring, Artinian module, artinian ring, artinian module -/ open set open_locale big_operators pointwise /-- `is_artinian R M` is the proposition that `M` is an Artinian `R`-module, implemented as the well-foundedness of submodule inclusion. -/ class is_artinian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop := (well_founded_submodule_lt [] : well_founded ((<) : submodule R M → submodule R M → Prop)) section variables {R : Type*} {M : Type*} {P : Type*} {N : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] [add_comm_group N] variables [module R M] [module R P] [module R N] open is_artinian include R theorem is_artinian_of_injective (f : M →ₗ[R] P) (h : function.injective f) [is_artinian R P] : is_artinian R M := ⟨subrelation.wf (λ A B hAB, show A.map f < B.map f, from submodule.map_strict_mono_of_injective h hAB) (inv_image.wf (submodule.map f) (is_artinian.well_founded_submodule_lt R P))⟩ instance is_artinian_submodule' [is_artinian R M] (N : submodule R M) : is_artinian R N := is_artinian_of_injective N.subtype subtype.val_injective lemma is_artinian_of_le {s t : submodule R M} [ht : is_artinian R t] (h : s ≤ t) : is_artinian R s := is_artinian_of_injective (submodule.of_le h) (submodule.of_le_injective h) variable (M) theorem is_artinian_of_surjective (f : M →ₗ[R] P) (hf : function.surjective f) [is_artinian R M] : is_artinian R P := ⟨subrelation.wf (λ A B hAB, show A.comap f < B.comap f, from submodule.comap_strict_mono_of_surjective hf hAB) (inv_image.wf (submodule.comap f) (is_artinian.well_founded_submodule_lt _ _))⟩ variable {M} theorem is_artinian_of_linear_equiv (f : M ≃ₗ[R] P) [is_artinian R M] : is_artinian R P := is_artinian_of_surjective _ f.to_linear_map f.to_equiv.surjective theorem is_artinian_of_range_eq_ker [is_artinian R M] [is_artinian R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf : function.injective f) (hg : function.surjective g) (h : f.range = g.ker) : is_artinian R N := ⟨well_founded_lt_exact_sequence (is_artinian.well_founded_submodule_lt _ _) (is_artinian.well_founded_submodule_lt _ _) f.range (submodule.map f) (submodule.comap f) (submodule.comap g) (submodule.map g) (submodule.gci_map_comap hf) (submodule.gi_map_comap hg) (by simp [submodule.map_comap_eq, inf_comm]) (by simp [submodule.comap_map_eq, h])⟩ instance is_artinian_prod [is_artinian R M] [is_artinian R P] : is_artinian R (M × P) := is_artinian_of_range_eq_ker (linear_map.inl R M P) (linear_map.snd R M P) linear_map.inl_injective linear_map.snd_surjective (linear_map.range_inl R M P) @[instance, priority 100] lemma is_artinian_of_fintype [fintype M] : is_artinian R M := ⟨fintype.well_founded_of_trans_of_irrefl _⟩ local attribute [elab_as_eliminator] fintype.induction_empty_option instance is_artinian_pi {R ι : Type*} [fintype ι] : Π {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)], by exactI Π [Π i, module R (M i)], by exactI Π [∀ i, is_artinian R (M i)], is_artinian R (Π i, M i) := fintype.induction_empty_option (begin introsI α β e hα M _ _ _ _, exact is_artinian_of_linear_equiv (linear_equiv.Pi_congr_left R M e) end) (by { introsI M _ _ _ _, apply_instance }) (begin introsI α _ ih M _ _ _ _, exact is_artinian_of_linear_equiv (linear_equiv.pi_option_equiv_prod R).symm, end) ι /-- A version of `is_artinian_pi` for non-dependent functions. We need this instance because sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to prove that `ι → ℝ` is finite dimensional over `ℝ`). -/ instance is_artinian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι] [is_artinian R M] : is_artinian R (ι → M) := is_artinian_pi end open is_artinian submodule function section variables {R M : Type*} [ring R] [add_comm_group M] [module R M] theorem is_artinian_iff_well_founded : is_artinian R M ↔ well_founded ((<) : submodule R M → submodule R M → Prop) := ⟨λ h, h.1, is_artinian.mk⟩ variables {R M} lemma is_artinian.finite_of_linear_independent [nontrivial R] [is_artinian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_lt R M)).elim' _), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | n ≤ m} ⊆ s, { rintros n x ⟨y, hy₁, rfl⟩, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | b ≤ m}) ≤ span R ((coe ∘ f) '' {m | a ≤ m}), { assume a b, rw [span_le_span_iff hs (this b) (this a), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], simp only [set.mem_set_of_eq], exact ⟨λ hab x, le_trans hab, λ h, (h _ le_rfl)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | n ≤ m}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, begin intros a b, conv_rhs { rw [gt, lt_iff_le_not_le, this, this, ← lt_iff_le_not_le] }, simp end⟩ end /-- A module is Artinian iff every nonempty set of submodules has a minimal submodule among them. -/ theorem set_has_minimal_iff_artinian : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, I ≤ M' → I = M') ↔ is_artinian R M := by rw [is_artinian_iff_well_founded, well_founded.well_founded_iff_has_min'] theorem is_artinian.set_has_minimal [is_artinian R M] (a : set $ submodule R M) (ha : a.nonempty) : ∃ M' ∈ a, ∀ I ∈ a, I ≤ M' → I = M' := set_has_minimal_iff_artinian.mpr ‹_› a ha /-- A module is Artinian iff every decreasing chain of submodules stabilizes. -/ theorem monotone_stabilizes_iff_artinian : (∀ (f : ℕ →o (submodule R M)ᵒᵈ), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_artinian R M := by rw [is_artinian_iff_well_founded]; exact (well_founded.monotone_chain_condition (submodule R M)ᵒᵈ).symm theorem is_artinian.monotone_stabilizes [is_artinian R M] (f : ℕ →o (submodule R M)ᵒᵈ) : ∃ n, ∀ m, n ≤ m → f n = f m := monotone_stabilizes_iff_artinian.mpr ‹_› f /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_artinian.induction [is_artinian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J < I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_lt R M) I hgt /-- For any endomorphism of a Artinian module, there is some nontrivial iterate with disjoint kernel and range. -/ theorem is_artinian.exists_endomorphism_iterate_ker_sup_range_eq_top [I : is_artinian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊔ (f ^ n).range = ⊤ := begin obtain ⟨n, w⟩ := monotone_stabilizes_iff_artinian.mpr I (f.iterate_range.comp ⟨λ n, n+1, λ n m w, by linarith⟩), specialize w ((n + 1) + n) (by linarith), dsimp at w, refine ⟨n + 1, nat.succ_ne_zero _, _⟩, simp_rw [eq_top_iff', mem_sup], intro x, have : (f^(n + 1)) x ∈ (f ^ ((n + 1) + n + 1)).range, { rw ← w, exact mem_range_self _ }, rcases this with ⟨y, hy⟩, use x - (f ^ (n+1)) y, split, { rw [linear_map.mem_ker, linear_map.map_sub, ← hy, sub_eq_zero, pow_add], simp [iterate_add_apply], }, { use (f^ (n+1)) y, simp } end /-- Any injective endomorphism of an Artinian module is surjective. -/ theorem is_artinian.surjective_of_injective_endomorphism [is_artinian R M] (f : M →ₗ[R] M) (s : injective f) : surjective f := begin obtain ⟨n, ne, w⟩ := is_artinian.exists_endomorphism_iterate_ker_sup_range_eq_top f, rw [linear_map.ker_eq_bot.mpr (linear_map.iterate_injective s n), bot_sup_eq, linear_map.range_eq_top] at w, exact linear_map.surjective_of_iterate_surjective ne w, end /-- Any injective endomorphism of an Artinian module is bijective. -/ theorem is_artinian.bijective_of_injective_endomorphism [is_artinian R M] (f : M →ₗ[R] M) (s : injective f) : bijective f := ⟨s, is_artinian.surjective_of_injective_endomorphism f s⟩ /-- A sequence `f` of submodules of a artinian module, with the supremum `f (n+1)` and the infinum of `f 0`, ..., `f n` being ⊤, is eventually ⊤. -/ lemma is_artinian.disjoint_partial_infs_eventually_top [I : is_artinian R M] (f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups (order_dual.to_dual ∘ f) n) (order_dual.to_dual (f (n+1)))) : ∃ n : ℕ, ∀ m, n ≤ m → f m = ⊤ := begin -- A little off-by-one cleanup first: suffices t : ∃ n : ℕ, ∀ m, n ≤ m → order_dual.to_dual f (m+1) = ⊤, { obtain ⟨n, w⟩ := t, use n+1, rintros (_|m) p, { cases p, }, { apply w, exact nat.succ_le_succ_iff.mp p }, }, obtain ⟨n, w⟩ := monotone_stabilizes_iff_artinian.mpr I (partial_sups (order_dual.to_dual ∘ f)), exact ⟨n, (λ m p, eq_bot_of_disjoint_absorbs (h m) ((eq.symm (w (m + 1) (le_add_right p))).trans (w m p)))⟩ end universe w variables {N : Type w} [add_comm_group N] [module R N] -- TODO: Prove this for artinian modules -- /-- -- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial. -- -/ -- noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M] -- (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} := -- begin -- apply nonempty.some, -- obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i) -- (f.tailings_disjoint_tailing i), -- specialize w n (le_refl n), -- apply nonempty.intro, -- refine (f.tailing_linear_equiv i n).symm.trans _, -- rw w, -- exact submodule.bot_equiv_punit, -- end end /-- A ring is Artinian if it is Artinian as a module over itself. -/ class is_artinian_ring (R) [ring R] extends is_artinian R R : Prop theorem is_artinian_ring_iff {R} [ring R] : is_artinian_ring R ↔ is_artinian R R := ⟨λ h, h.1, @is_artinian_ring.mk _ _⟩ theorem ring.is_artinian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_artinian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); split; apply_instance theorem is_artinian_of_submodule_of_artinian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_artinian R M) : is_artinian R N := by apply_instance theorem is_artinian_of_quotient_of_artinian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_artinian R M) : is_artinian R (M ⧸ N) := is_artinian_of_surjective M (submodule.mkq N) (submodule.quotient.mk_surjective N) /-- If `M / S / R` is a scalar tower, and `M / R` is Artinian, then `M / S` is also Artinian. -/ theorem is_artinian_of_tower (R) {S M} [comm_ring R] [ring S] [add_comm_group M] [algebra R S] [module S M] [module R M] [is_scalar_tower R S M] (h : is_artinian R M) : is_artinian S M := begin rw is_artinian_iff_well_founded at h ⊢, refine (submodule.restrict_scalars_embedding R S M).well_founded h end theorem is_artinian_of_fg_of_artinian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_artinian_ring R] (hN : N.fg) : is_artinian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_artinian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_artinian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _) _ _ _ is_artinian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = 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 lemma is_artinian_of_fg_of_artinian' {R M} [ring R] [add_comm_group M] [module R M] [is_artinian_ring R] (h : (⊤ : submodule R M).fg) : is_artinian R M := have is_artinian R (⊤ : submodule R M), from is_artinian_of_fg_of_artinian _ h, by exactI is_artinian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a artinian ring, the submodule generated by finitely many vectors is artinian. -/ theorem is_artinian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_artinian_ring R] {A : set M} (hA : finite A) : is_artinian R (submodule.span R A) := is_artinian_of_fg_of_artinian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_artinian_ring_of_surjective (R) [ring R] (S) [ring S] (f : R →+* S) (hf : function.surjective f) [H : is_artinian_ring R] : is_artinian_ring S := begin rw [is_artinian_ring_iff, is_artinian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf) H, end instance is_artinian_ring_range {R} [ring R] {S} [ring S] (f : R →+* S) [is_artinian_ring R] : is_artinian_ring f.range := is_artinian_ring_of_surjective R f.range f.range_restrict f.range_restrict_surjective theorem is_artinian_ring_of_ring_equiv (R) [ring R] {S} [ring S] (f : R ≃+* S) [is_artinian_ring R] : is_artinian_ring S := is_artinian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace is_artinian_ring open is_artinian variables {R : Type*} [comm_ring R] [is_artinian_ring R] lemma is_nilpotent_jacobson_bot : is_nilpotent (ideal.jacobson (⊥ : ideal R)) := begin let Jac := ideal.jacobson (⊥ : ideal R), let f : ℕ →o (ideal R)ᵒᵈ := ⟨λ n, Jac ^ n, λ _ _ h, ideal.pow_le_pow h⟩, obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → Jac ^ n = Jac ^ m := is_artinian.monotone_stabilizes f, refine ⟨n, _⟩, let J : ideal R := annihilator (Jac ^ n), suffices : J = ⊤, { have hJ : J • Jac ^ n = ⊥ := annihilator_smul (Jac ^ n), simpa only [this, top_smul, ideal.zero_eq_bot] using hJ }, by_contradiction hJ, change J ≠ ⊤ at hJ, rcases is_artinian.set_has_minimal {J' : ideal R | J < J'} ⟨⊤, hJ.lt_top⟩ with ⟨J', hJJ' : J < J', hJ' : ∀ I, J < I → I ≤ J' → I = J'⟩, rcases set_like.exists_of_lt hJJ' with ⟨x, hxJ', hxJ⟩, obtain rfl : J ⊔ ideal.span {x} = J', { refine hJ' (J ⊔ ideal.span {x}) _ _, { rw set_like.lt_iff_le_and_exists, exact ⟨le_sup_left, ⟨x, mem_sup_right (mem_span_singleton_self x), hxJ⟩⟩ }, { exact (sup_le hJJ'.le (span_le.2 (singleton_subset_iff.2 hxJ'))) } }, have : J ⊔ Jac • ideal.span {x} ≤ J ⊔ ideal.span {x}, from sup_le_sup_left (smul_le.2 (λ _ _ _, submodule.smul_mem _ _)) _, have : Jac * ideal.span {x} ≤ J, --Need version 4 of Nakayamas lemma on Stacks { classical, by_contradiction H, refine H (smul_sup_le_of_le_smul_of_le_jacobson_bot (fg_span_singleton _) le_rfl (hJ' _ _ this).ge), exact lt_of_le_of_ne le_sup_left (λ h, H $ h.symm ▸ le_sup_right) }, have : ideal.span {x} * Jac ^ (n + 1) ≤ ⊥, calc ideal.span {x} * Jac ^ (n + 1) = ideal.span {x} * Jac * Jac ^ n : by rw [pow_succ, ← mul_assoc] ... ≤ J * Jac ^ n : mul_le_mul (by rwa mul_comm) le_rfl ... = ⊥ : by simp [J], refine hxJ (mem_annihilator.2 (λ y hy, (mem_bot R).1 _)), refine this (mul_mem_mul (mem_span_singleton_self x) _), rwa [← hn (n + 1) (nat.le_succ _)] end end is_artinian_ring
9159579a224eed8edf69f992aeb8c6a2683e8c7c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/affine_space/affine_equiv.lean
2e6f89d2306a32c16344e1b185dfcff45c7e2365
[ "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
13,927
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 an equivalence `e : P₁ ≃ P₂`, a linear equivalece `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_equiv := e, linear := e', .. affine_map.mk' e (e' : V₁ →ₗ[k] V₂) p h } @[simp] lemma coe_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl @[simp] lemma to_equiv_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : (mk' e e' p h).to_equiv = 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
57bcd77a6ebe65f2a33c38ba69f9ba6fe0bfb426
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/matchUnifyBug.lean
82aba9cf208dc4548e01252e06ed3ee6279f3bfe
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,078
lean
inductive Color where | Red | Black open Color inductive rbnode : Nat → Color → Type where | Leaf : rbnode 1 Black | R {h} (left : rbnode h Black) (value : Int) (right : rbnode h Black) : rbnode h Red | B {h cl cr} (left : rbnode h cl) (value : Int) (right : rbnode h cr) : rbnode (h+1) Black open rbnode inductive hiddenTree : Nat → Type | HR {h} (node : rbnode h Red) : hiddenTree h | HB {h} (node : rbnode (h+1) Black) : hiddenTree (h+1) open hiddenTree inductive almostNode : Nat → Type | LR {h cR} (left:rbnode h Red) (value:Int) (right:rbnode h cR) : almostNode h | RR {h cL} (left:rbnode h cL) (value:Int) (right:rbnode h Red) : almostNode h | V {h c} (node:rbnode h c) : almostNode h open almostNode def balanceRR {h c} (left : rbnode h c) (y : Int) (right : hiddenTree h) : almostNode h := match h, c, left, right with | _, _, left, HR c => RR left y c | n+1, _, R a x b, HB c => LR (R a x b) y c | _, _, B a x b, HB c => V (R (B a x b) y c) | _, _, Leaf, HB c => V (R Leaf y c)
78695fa117ac2af36c12d4dbc515d9884a277556
022215fec0be87ac6243b0f4fa3cc2939361d7d0
/src/category_theory/instances/Top/stalks.lean
51481c58e02b1beec20a2df2f16c14e3e3ed9d1d
[ "Apache-2.0" ]
permissive
PaulGustafson/mathlib
4aa7bc81ca971fdd7b6e50bf3a245fade2978391
c49ac06ff9fa1371e9b6050a121df618cfd3fb80
refs/heads/master
1,590,798,947,521
1,559,220,227,000
1,559,220,227,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,461
lean
-- Copyright (c) 2019 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.instances.Top.open_nhds import category_theory.instances.Top.presheaf import category_theory.limits.limits universes v u v' u' open category_theory open category_theory.instances open category_theory.instances.Top open category_theory.limits open topological_space variables {C : Type u} [𝒞 : category.{v+1} C] include 𝒞 variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace category_theory.instances.Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit (nbhds_inclusion x ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl variables (C) def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ), end -- Here are two other potential solutions, suggested by @fpvandoorn at -- https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240 -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], tidy, end @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor, pushforward], ext U, op_induction U, cases U, cases U_val, simp only [colim.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre, whisker_right.app, category.assoc], dsimp, simp only [category.id_comp, category_theory.functor.map_id], -- FIXME A simp lemma which unfortunately doesn't fire: rw [category_theory.functor.map_id], dsimp, simp, end end stalk_pushforward end category_theory.instances.Top.presheaf
92172275676db44b39cf359e66166d696200c9b3
18425d4bab0b5e4677ef791d0065e16639493248
/function/bijection.lean
8c4577d5671d6c1226a0088376d61c2514f7644e
[ "MIT" ]
permissive
tizmd/lean-finitary
5feb94a2474b55c0f23e4b61b9ac42403bf222f7
8958fdb3fa3d9fcc304e116fd339448875025e95
refs/heads/master
1,611,397,193,043
1,497,517,825,000
1,497,517,825,000
93,048,842
0
0
null
null
null
null
UTF-8
Lean
false
false
3,041
lean
universes u v open function class bijection {α : Sort u} {β : Sort v} (f : α → β) := (inv : β → α) (left_inverse_of_inv : left_inverse inv f) (right_inverse_of_inv : right_inverse inv f) namespace bijection variables {α : Sort u} {β : Sort v} {f : α → β} instance of_id : bijection (@id α) := ⟨ id, take a, rfl, take a, rfl⟩ instance inverse (iso_f : bijection f) : bijection (inv f) := ⟨f, right_inverse_of_inv f, left_inverse_of_inv f⟩ def injective_of_bijection (iso_f : bijection f) : injective f := injective_of_left_inverse (left_inverse_of_inv f) lemma eq_of_inv_of_bijection (iso₁ iso₂: bijection f) : iso₁.inv = iso₂.inv := begin apply funext, intro, apply injective_of_bijection, assumption, rw iso₁.right_inverse_of_inv, rw iso₂.right_inverse_of_inv end lemma bijection_of_iff {a b : Prop} (h : a ↔ b) : bijection (h.mp) := { inv := h.mpr, left_inverse_of_inv := take p, proof_irrel _ _, right_inverse_of_inv := take p, proof_irrel _ _ } private def has_right_inverse_of_bijection (iso_f : bijection f) : has_right_inverse f := ⟨ inv f , right_inverse_of_inv f⟩ def surjective_of_bijection (iso_f : bijection f) : surjective f := surjective_of_has_right_inverse (has_right_inverse_of_bijection iso_f) def bijective_of_bijection (iso_f : bijection f) : bijective f := ⟨ injective_of_bijection iso_f , surjective_of_bijection iso_f⟩ universe w variables {γ : Sort w} {g : β → γ} instance comp (iso_f : bijection f) (iso_g : bijection g) : bijection (g ∘ f) := ⟨ inv f ∘ inv g, begin intro a, simp [comp], repeat {rw [left_inverse_of_inv]} end, begin intro c, simp [comp], rw [right_inverse_of_inv f, right_inverse_of_inv g] end⟩ end bijection def has_bijection {α : Sort u}{β : Sort v} (f : α → β) := ∃ g : β → α, left_inverse g f ∧ right_inverse g f namespace has_bijection variables {α : Sort u}{β : Sort v} {f : α → β} def injective_of_has_bijection : has_bijection f → injective f := λ ex, exists.elim ex (λ g h, injective_of_left_inverse (and.left h)) def surjective_of_has_bijection : has_bijection f → surjective f := λ ex, exists.elim ex (λ g h, surjective_of_has_right_inverse (exists.intro g (and.right h))) def bijective_of_has_bijection : has_bijection f → bijective f := λ h, and.intro (injective_of_has_bijection h) (surjective_of_has_bijection h) def of_bijection [ins : bijection f] : has_bijection f := exists.intro ins.inv (and.intro ins.left_inverse_of_inv ins.right_inverse_of_inv) universe w variables {γ : Sort w} {g : β → γ} def trans : has_bijection f → has_bijection g → has_bijection (g ∘ f) := begin intros fH gH, cases fH with f_inv f_inv_h, cases gH with g_inv g_inv_h, apply (exists.intro (f_inv ∘ g_inv)), apply and.intro, { intro x, simp [comp], rw [g_inv_h.left, f_inv_h.left] }, { intro x, simp [comp], rw [f_inv_h.right, g_inv_h.right] } end end has_bijection
06974f587ea92c6943904f8d4641e7074a4d232b
ce89339993655da64b6ccb555c837ce6c10f9ef4
/zeptometer/topprover/37.lean
d23f2574dbe7deab8aa0207e4d3c1492cf043d1f
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
359
lean
inductive iszero : ℕ → Prop | iszero_0 : iszero 0 | iszero_S : ∀ n, iszero (nat.succ n) → iszero n example (n) : iszero n ↔ n = 0 := begin constructor, intro n_is_zero, induction n_is_zero, { refl }, { cases n_is_zero_ih, }, { intro n_is_zero, rw n_is_zero, apply iszero.iszero_0 } end
174911c6f27eab83b43cb7c01a67da9ba2e49b48
fc086f79b20cf002d6f34b023749998408e94fbf
/test/timing.lean
91526a6c80e30949a0070880e0759b4dd659b40e
[]
no_license
semorrison/lean-tidy
f039460136b898fb282f75efedd92f2d5c5d90f8
6c1d46de6cff05e1c2c4c9692af812bca3e13b6c
refs/heads/master
1,624,461,332,392
1,559,655,744,000
1,559,655,744,000
96,569,994
9
4
null
1,538,287,895,000
1,499,455,306,000
Lean
UTF-8
Lean
false
false
271
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import tidy.timing open tactic private lemma f : 1 = 1 := begin (time_tactic skip) >>= trace, simp end
03008a1a7980ffe07c82e4dcd0969884bd9b87da
6e8de6b43162bef473b4a0bd93b71db886df98ce
/src/pregeom/geometrize.lean
f3b9864557cdea78f3b7d0d9a86dcc37d510cd5e
[ "Unlicense" ]
permissive
adamtopaz/comb_geom
38ec6fde8d2543f56227ec50cdfb86cac6ac33c1
e16b629d6de3fbdea54a528755e7305dfb51e902
refs/heads/master
1,668,613,552,530
1,593,199,940,000
1,593,199,940,000
269,824,442
6
0
Unlicense
1,593,119,545,000
1,591,404,975,000
Lean
UTF-8
Lean
false
false
7,055
lean
import .basic import .pullback import .pushforward import data.finset /-! # Geometrization of a pregeometry In this file we construct a geometry from a pregeometry in the "standard way". We do this in four steps, as follows. Given a pregeometry `T`, we define: 1. The subtype of "regular elements" of `T`, denoted `reg T`. A "regular" element is an element which is not contained in the closure of `∅`. 2. We construct a pregeometry instance on `reg T`. 3. We construct the quotient of `reg T` by the equivalence relation `rel` defined as `rel x y ↔ cls x = cls y`. This quotient type is denoted `geom T`. 4. We construct a geometry structure on `geom T`. -/ set_option default_priority 100 open_locale classical namespace pregeom open has_cl variables (T : Type*) /-- The set of "regular elements" (see above). -/ def reg_set [has_cl T] := { t | t ∉ cl (∅ : set T) } /-- The subtype of regular elements (see above). -/ def reg [has_cl T] := subtype (reg_set T) namespace reg /-- A typeclass for regular elements of T. Mainly used to inhabited instance. -/ -- This is only here so that the linted is happy. Is this actually necessary? class has_reg_element extends has_cl T := (elem : T) (is_regular : elem ∉ cl (∅ : set T)) open has_reg_element instance [has_reg_element T] : inhabited (reg T) := ⟨⟨elem,is_regular⟩⟩ local notation `ι` := subtype.val instance has_cl_instance [has_cl T] : has_cl (reg T) := pregeom.pullback.has_cl_instance subtype.val /-- The relation used to define a geometry from a pregeomery. -/ protected def rel [has_cl T] : reg T → reg T → Prop := λ s t, cls s = cls t variable {T} protected theorem is_equiv [has_cl T] : equivalence (reg.rel T) := begin refine ⟨_,_,_⟩, { unfold reflexive reg.rel, intro x, refl, }, { unfold symmetric reg.rel, rintros x y hx, rwa hx, }, { unfold transitive reg.rel, intros x y z h1 h2, rwa [h1, h2], } end @[simp] lemma cl_reg_set_inter [pregeom T] {S : set T} : cl (reg_set T ∩ S) = cl S := begin ext, split, { intro h, have : reg_set T ∩ S ≤ S, by {intros x hx, cases hx, assumption}, exact monotone this h, }, { intro h, have : S ≤ cl (∅ : set T) ∪ (reg_set T ∩ S), { intros s hs, by_cases s ∈ cl (∅ : set T), { left, assumption }, { right, exact ⟨h,hs⟩, } }, replace h := monotone this h, rw cl_union_cl_empty at h, exact h, } end private lemma reg_lift_finset [has_cl T] {W : finset T} : ↑W ⊆ reg_set T → ∃ V : finset (reg T), finset.image ι V = W := begin refine finset.induction_on W _ _; intros, { use ∅, trivial, }, { have : ↑s ⊆ reg_set T, { intros x hx, apply a_3, simp [hx], }, rcases a_2 this with ⟨V,rfl⟩, have : a ∈ reg_set T, { apply a_3, simp, }, use insert ⟨a,this⟩ V, rwa finset.image_insert, } end instance pregeom_instance [pregeom T] : pregeom (reg T) := pregeom.pullback.pregeom_instance subtype.val @[simp] theorem regularity [has_cl T] : cl (∅ : set (reg T)) = ∅ := begin change subtype.val ⁻¹' _ = _, rw set.image_empty, ext, split; intro hx, { change x.val ∈ _ at hx, have := x.2, contradiction, }, { finish, } end end reg /-- The setoid used to construct `geom T` from `reg T`. -/ protected def setoid [has_cl T] : setoid (reg T) := ⟨reg.rel T, reg.is_equiv⟩ /-- The geometry associated to `T`. See above. -/ def geom [has_cl T] := quotient (pregeom.setoid T) namespace geom variable {T} /-- The canonical projection from `reg T` to `geom T`. -/ def to_geom [has_cl T] : reg T → geom T := quotient.mk' local notation `π` := to_geom instance [has_cl T] [inhabited (reg T)] : inhabited (geom T) := ⟨ π (default (reg T)) ⟩ /-- A variant of `to_geom`, but which takes a term of type `T` and a proof of "regularity" as inputs. -/ def to_geom_of_reg [has_cl T] {t : T} (h : t ∈ reg_set T) : geom T := π ⟨t,h⟩ theorem eq_iff [has_cl T] {u v : reg T} : π u = π v ↔ cls u = cls v := by simpa [to_geom] theorem eq_iff' [pregeom T] {u v : reg T} : π u = π v ↔ u ∈ cls v := begin rw eq_iff, split, { intro h, rw ←h, exact mem_cls, }, { intro h1, ext, split, { intro h2, unfold cls at h1, rw ←cls_le_iff_mem_cl at h1, exact h1 h2, }, { intro h2, replace h1 := exchange_cls h1 _, { unfold cls at h1, rw ←cls_le_iff_mem_cl at h1, exact h1 h2, }, { rw reg.regularity, tauto, } } } end theorem cls_le_pullback_of_mem [pregeom T] {t : reg T} {S : set (geom T) }: π t ∈ S ↔ cls t ≤ π ⁻¹' S := begin split; intro h, { intros u hu, change _ ∈ cls _ at hu, rw ←eq_iff' at hu, rwa ←hu at h, }, { suffices : t ∈ π ⁻¹' S, by exact this, apply h, exact mem_cls, } end lemma mem_cl_of_mem_mk_eq_mk [pregeom T] {x y : reg T} {S : set (reg T)} : x ∈ cl S → π x = π y → y ∈ cl S := begin intros hx h, suffices : cls y ≤ cl S, by exact this mem_cls, rw eq_iff at h, rw ←h, change _ ⊆ _, rw cls_le_iff_mem_cl, assumption, end lemma mem_cl_of_mk_eq_mk [pregeom T] {a b : reg T} {S : set (reg T)} : a ∈ S → π b = π a → b ∈ cl S := begin intros ha h, rw eq_iff' at h, replace ha : ({a} : set (reg T)) ≤ S, { rintros b ⟨rfl⟩, assumption, }, apply monotone ha, assumption, end instance has_cl_instance [has_cl T] : has_cl (geom T) := ⟨ λ S, π '' (cl (π ⁻¹' S)) ⟩ variable [pregeom T] @[simp] lemma pullback_insert {t : reg T} {S : set (geom T)} : π ⁻¹' insert (π t) S = cls t ∪ π ⁻¹' S := begin ext, split; intro hx, { change π x ∈ _ at hx, cases hx, { left, rwa eq_iff' at hx, }, { right, exact hx, } }, { change π x ∈ _, cases hx, { left, rwa eq_iff', }, { right, exact hx, } } end instance pregeom_instance : pregeom (geom T) := begin refine @pregeom.pushforward.pregeom_instance _ _ π _ _ (quot.exists_rep), intros s t ht, change π t ∈ _ at ht, rcases ht with ⟨z,⟨rfl⟩,h2⟩, change quotient.mk' _ = quotient.mk' _ at h2, rw quotient.eq' at h2, change cls s = cls t at h2, rw h2, exact mem_cls end lemma mem_cls_geom {x y : geom T} : x ∈ cls y → x = y := begin intro hx, rcases hx with ⟨z,hz,rfl⟩, rcases quot.exists_rep y with ⟨w,hw,rfl⟩, rw set.singleton_def at hz, change _ ∈ cl ( π ⁻¹' (insert (π w) _) ) at hz, rw pullback_insert at hz, change π z = π _, unfold cls at hz, rw pregeom.cl_cl_union_eq_cl_union at hz, simp only [insert_emptyc_eq, set.singleton_union, set.preimage_empty] at hz, rwa eq_iff', end instance geom_instance : geometry (geom T) := begin split, { intro x, ext y, split; intro hy, { apply mem_cls_geom, assumption, }, { change y = x at hy, rw hy, exact mem_cls, } }, { change π '' cl (∅ : set (reg T)) = _, rw reg.regularity, finish, } end end geom end pregeom
26cb4c21cc32f747acb8d02ee7024ddb95512856
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/data/char/classes.lean
7b29351e7ba7b2f462de63c0c9f53998553e48c4
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
1,618
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ prelude import .basic .lemmas init.meta init.data.int namespace char def is_whitespace (c : char) : Prop := c ∈ [' ', '\t', '\n'] def is_upper (c : char) : Prop := c.val ≥ 65 ∧ c.val ≤ 90 def is_lower (c : char) : Prop := c.val ≥ 97 ∧ c.val ≤ 122 def is_alpha (c : char) : Prop := c.is_upper ∨ c.is_lower def is_digit (c : char) : Prop := c.val ≥ 48 ∧ c.val ≤ 57 def is_alphanum (c : char) : Prop := c.is_alpha ∨ c.is_digit def is_punctuation (c : char) : Prop := c ∈ [' ', ',', '.', '?', '!', ';', '-', '\''] def to_lower (c : char) : char := let n := to_nat c in if n >= 65 ∧ n <= 90 then of_nat (n + 32) else c instance decidable_is_whitespace : decidable_pred is_whitespace := begin intro c, delta is_whitespace, apply_instance end instance decidable_is_upper : decidable_pred is_upper := begin intro c, delta is_upper, apply_instance end instance decidable_is_lower : decidable_pred is_lower := begin intro c, delta is_lower, apply_instance end instance decidable_is_alpha : decidable_pred is_alpha := begin intro c, delta is_alpha, apply_instance end instance decidable_is_digit : decidable_pred is_digit := begin intro c, delta is_digit, apply_instance end instance decidable_is_alphanum : decidable_pred is_alphanum := begin intro c, delta is_alphanum, apply_instance end instance decidable_is_punctuation : decidable_pred is_punctuation := begin intro c, delta is_punctuation, apply_instance end end char
66f767f1ada328c66909c4a18c51ce149bb77f04
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/category/Group/images.lean
25c2fdcdc2bd5cc18b4cabde1ba89a31b4834034
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
2,782
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Group /-! # The category of commutative additive groups has images. -/ open category_theory open category_theory.limits universe u namespace AddCommGroup -- Note that because `injective_of_mono` is currently only proved in `Type 0`, -- we restrict to the lowest universe here for now. variables {G H : AddCommGroup.{0}} (f : G ⟶ H) local attribute [ext] subtype.ext_val section -- implementation details of `has_image` for AddCommGroup; use the API, not these /-- the image of a morphism in AddCommGroup is just the bundling of `set.range f` -/ def image : AddCommGroup := AddCommGroup.of (set.range f) /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ H := f.range_subtype_val instance : mono (image.ι f) := concrete_category.mono_of_injective (image.ι f) subtype.val_injective /-- the corestriction map to the image -/ def factor_thru_image : G ⟶ image f := add_monoid_hom.range_factorization f lemma image.fac : factor_thru_image f ≫ image.ι f = f := by { ext, refl, } local attribute [simp] image.fac variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := { to_fun := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I), map_zero' := begin haveI := F'.m_mono, apply injective_of_mono F'.m, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, add_monoid_hom.map_zero], convert (classical.indefinite_description (λ y, f y = 0) _).2, end, map_add' := begin intros x y, haveI := F'.m_mono, apply injective_of_mono F'.m, rw [add_monoid_hom.map_add], change (F'.e ≫ F'.m) _ = (F'.e ≫ F'.m) _ + (F'.e ≫ F'.m) _, rw [F'.fac], rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, rw (classical.indefinite_description (λ z, f z = _) _).2, refl, end, } lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in AddCommGroup through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := factor_thru_image f } noncomputable instance : has_image f := { F := mono_factorisation f, is_image := { lift := image.lift, lift_fac' := image.lift_fac } } noncomputable instance : has_images.{0} AddCommGroup.{0} := { has_image := infer_instance } end AddCommGroup
7db3fa5978db6515ebcc4fbf2f4a61c141fce365
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20170116_POPL/super/listex.lean
0b289b65e2e81eef0620d27dcf2efaf9e4d9be93
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
1,629
lean
import tools.super open list -- These are the same examples we used to show backchaining. (see backchaining directory) -- Backchaining is a special case of resolution, so we can solve them using -- super as well. set_option trace.super true -- The first few cases can be handled by super's built-in support for data types -- and definition unfolding: -- when super sees a clause [a ∉ b :: bs], it will derive [a ≠ b] and [a ∉ bs]. example (a b c : nat) : a ∈ [b, c] ++ [b, a, b] := by super example (a b c : nat) : a ∈ [b, c] ++ [b, c, c] ++ [b, a, b] := by super example (a b c : nat) (l : list nat) : a ∈ l → a ∈ [b, c] ++ b::l := by super -- However super doesn't know anything about append, so it cannot figure out -- that append preserves membership: example (x : nat) (xs ys : list nat) : x ∈ xs → x ∈ xs ++ ys := by super -- So we need to tell super about append. (We also need to give it a few lemmas -- about membership and cons, otherwise it gets lost.) universe variable u lemma in_tail {α : Type u} {a : α} (b : α) {l : list α} : a ∈ l → a ∈ b::l := mem_cons_of_mem _ lemma in_head {α : Type u} (a : α) (l : list α) : a ∈ a::l := mem_cons_self _ _ lemma in_left {α : Type u} {a : α} {l : list α} (r : list α) : a ∈ l → a ∈ l ++ r := mem_append_left _ lemma in_right {α : Type u} {a : α} (l : list α) {r : list α} : a ∈ r → a ∈ l ++ r := mem_append_right _ example (a b c : nat) (l₁ l₂ : list nat) : a ∈ l₁ → a ∈ b::b::c::l₂ ++ b::c::l₁ ++ [c, c, b] := by super with in_left in_right in_head in_tail
2fb675861829d5a9ddffcc82d805b539a52b5025
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/pkg/prv/Prv.lean
7d4ffe350960870ada3da02ec5aa8e875409797a
[ "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
160
lean
import Prv.Foo #check { name := "leo", val := 15 : Foo } #check { name := "leo", val := 15 : Foo }.name #check { name := "leo", val := 15 : Foo }.val -- Error
dedf855970e48a6a7ec66ea1adabbdeec0dd1b62
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/equiv/list.lean
a78557c219daa0fa98a086d1af53b00f7466f48f
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,912
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.equiv.denumerable import data.finset.sort /-! # Equivalences involving `list`-like types This file defines some additional constructive equivalences using `encodable` and the pairing function on `ℕ`. -/ open nat list namespace encodable variables {α : Type*} section list variable [encodable α] /-- Explicit encoding function for `list α` -/ def encode_list : list α → ℕ | [] := 0 | (a::l) := succ (mkpair (encode a) (encode_list l)) /-- Explicit decoding function for `list α` -/ def decode_list : ℕ → option (list α) | 0 := some [] | (succ v) := match unpair v, unpair_right_le v with | (v₁, v₂), h := have v₂ < succ v, from lt_succ_of_le h, (::) <$> decode α v₁ <*> decode_list v₂ end /-- If `α` is encodable, then so is `list α`. This uses the `mkpair` and `unpair` functions from `data.nat.pairing`. -/ 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 [] := show decode_list 0 = some [], by rw decode_list @[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 $ (length_le_encode l).trans (right_le_mkpair _ _) end list section finset variables [encodable α] private def enle : α → α → Prop := encode ⁻¹'o (≤) private lemma enle.is_linear_order : is_linear_order α enle := (rel_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 /-- Explicit encoding function for `multiset α` -/ def encode_multiset (s : multiset α) : ℕ := encode (s.sort enle) /-- Explicit decoding function for `multiset α` -/ def decode_multiset (n : ℕ) : option (multiset α) := coe <$> decode (list α) n /-- If `α` is encodable, then so is `multiset α`. -/ instance multiset : encodable (multiset α) := ⟨encode_multiset, decode_multiset, λ s, by simp [encode_multiset, decode_multiset, encodek]⟩ end finset /-- A listable type with decidable equality is encodable. -/ 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 /-- A noncomputable way to arbitrarily choose an ordering on a finite type. It is not made into a global instance, since it involves an arbitrary choice. This can be locally made into an instance with `local attribute [instance] fintype.encodable`. -/ noncomputable def _root_.fintype.encodable (α : Type*) [fintype α] : encodable α := by { classical, exact (encodable.trunc_encodable_of_fintype α).out } /-- If `α` is encodable, then so is `vector α n`. -/ instance vector [encodable α] {n} : encodable (vector α n) := encodable.subtype /-- If `α` is encodable, then so is `fin n → α`. -/ 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) π) /-- If `α` is encodable, then so is `array n α`. -/ instance array [encodable α] {n} : encodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) /-- If `α` is encodable, then so is `finset α`. -/ 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*) [decidable_eq α] [fintype α] [encodable β] : trunc (encodable (α → β)) := (fintype.trunc_equiv_fin α).map $ λ f, encodable.of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr f (equiv.refl _) def fintype_pi (α : Type*) (π : α → Type*) [decidable_eq α] [fintype α] [∀ 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 α π) /-- The elements of a `fintype` as a sorted list. -/ def sorted_univ (α) [fintype α] [encodable α] : list α := finset.univ.sort (encodable.encode' α ⁻¹'o (≤)) theorem mem_sorted_univ {α} [fintype α] [encodable α] (x : α) : x ∈ sorted_univ α := (finset.mem_sort _).2 (finset.mem_univ _) theorem length_sorted_univ {α} [fintype α] [encodable α] : (sorted_univ α).length = fintype.card α := finset.length_sort _ theorem sorted_univ_nodup {α} [fintype α] [encodable α] : (sorted_univ α).nodup := finset.sort_nodup _ _ /-- An encodable `fintype` is equivalent to the same size `fin`. -/ def fintype_equiv_fin {α} [fintype α] [encodable α] : α ≃ fin (fintype.card α) := begin haveI : decidable_eq α := encodable.decidable_eq_of_encodable _, transitivity, { exact fintype.equiv_fin_of_forall_mem_list mem_sorted_univ (@sorted_univ_nodup α _ _) }, exact equiv.cast (congr_arg _ (@length_sorted_univ α _ _)) end /-- If `α` and `β` are encodable and `α` is a fintype, then `α → β` is encodable as well. -/ instance fintype_arrow_of_encodable {α β : Type*} [encodable α] [fintype α] [encodable β] : encodable (α → β) := of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr fintype_equiv_fin (equiv.refl _) 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 := by rw decode_list; exact ⟨_, rfl, rfl⟩ | (succ v) := begin cases e : unpair v with v₁ v₂, have h := unpair_right_le v, rw e at h, rcases have v₂ < succ v, from lt_succ_of_le h, denumerable_list_aux v₂ with ⟨a, h₁, h₂⟩, rw option.mem_def at h₁, use of_nat α v₁ :: a, simp [decode_list, e, h₂, h₁, encode_list, mkpair_unpair' e], end /-- If `α` is denumerable, then so is `list α`. -/ instance denumerable_list : denumerable (list α) := ⟨denumerable_list_aux⟩ @[simp] theorem list_of_nat_zero : of_nat (list α) 0 = [] := by rw [← @encode_list_nil α, of_nat_encode] @[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 /-- Outputs the list of differences of the input list, that is `lower [a₁, a₂, ...] n = [a₁ - n, a₂ - a₁, ...]` -/ def lower : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower l m /-- Outputs the list of partial sums of the input list, that is `raise [a₁, a₂, ...] n = [n + a₁, n + a₁ + a₂, ...]` -/ 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 rw [raise, lower, add_tsub_cancel_right, 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, tsub_add_cancel_of_le 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 _ _) /-- `raise l n` is an non-decreasing sequence. -/ 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 _ _) /-- If `α` is denumerable, then so is `multiset α`. Warning: this is *not* the same encoding as used in `encodable.multiset`. -/ 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 /-- Outputs the list of differences minus one of the input list, that is `lower' [a₁, a₂, a₃, ...] n = [a₁ - n, a₂ - a₁ - 1, a₃ - a₂ - 1, ...]`. -/ def lower' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower' l (m + 1) /-- Outputs the list of partial sums plus one of the input list, that is `raise [a₁, a₂, a₃, ...] n = [n + a₁, n + a₁ + a₂ + 1, n + a₁ + a₂ + a₃ + 2, ...]`. Adding one each time ensures the elements are distinct. -/ 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', add_tsub_cancel_right, 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', tsub_add_cancel_of_le 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 _)) /-- `raise' l n` is a strictly increasing sequence. -/ 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 _)) /-- Makes `raise' l n` into a finset. Elements are distinct thanks to `raise'_sorted`. -/ def raise'_finset (l : list ℕ) (n : ℕ) : finset ℕ := ⟨raise' l n, (raise'_sorted _ _).imp (@ne_of_lt _ _)⟩ /-- If `α` is denumerable, then so is `finset α`. Warning: this is *not* the same encoding as used in `encodable.finset`. -/ 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 /-- The type lists on unit is canonically equivalent to the natural numbers. -/ def list_unit_equiv : list unit ≃ ℕ := { to_fun := list.length, inv_fun := list.repeat (), left_inv := λ u, list.length_injective (by simp), right_inv := λ n, list.length_repeat () n } /-- `list ℕ` is equivalent to `ℕ`. -/ def list_nat_equiv_nat : list ℕ ≃ ℕ := denumerable.eqv _ /-- If `α` is equivalent to `ℕ`, then `list α` is equivalent to `α`. -/ 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
550341e1582df0d49a0e40d0cab952cc0468ff39
26ac254ecb57ffcb886ff709cf018390161a9225
/src/geometry/manifold/real_instances.lean
e6d96c1f92fc0bd9e386498a2add3d40104a60d8
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
15,755
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 geometry.manifold.smooth_manifold_with_corners import linear_algebra.finite_dimensional import analysis.normed_space.real_inner_product /-! # Constructing examples of manifolds over ℝ We introduce the necessary bits to be able to define manifolds modelled over `ℝ^n`, boundaryless or with boundary or with corners. As a concrete example, we construct explicitly the manifold with boundary structure on the real interval `[x, y]`. More specifically, we introduce * `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n)` for the model space used to define `n`-dimensional real manifolds with boundary * `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_quadrant n)` for the model space used to define `n`-dimensional real manifolds with corners ## Notations In the locale `manifold`, we introduce the notations * `𝓡 n` for the identity model with corners on `euclidean_space (fin n)` * `𝓡∂ n` for `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n)`. For instance, if a manifold `M` is boundaryless, smooth and modelled on `euclidean_space (fin m)`, and `N` is smooth with boundary modelled on `euclidean_half_space n`, and `f : M → N` is a smooth map, then the derivative of `f` can be written simply as `mfderiv (𝓡 m) (𝓡∂ n) f` (as to why the model with corners can not be implicit, see the discussion in `smooth_manifold_with_corners.lean`). ## Implementation notes The manifold structure on the interval `[x, y] = Icc x y` requires the assumption `x < y` as a typeclass. We provide it as `[fact (x < y)]`. -/ noncomputable theory open set open_locale manifold /-- The half-space in `ℝ^n`, used to model manifolds with boundary. We only define it when `1 ≤ n`, as the definition only makes sense in this case. -/ def euclidean_half_space (n : ℕ) [has_zero (fin n)] : Type := {x : euclidean_space (fin n) // 0 ≤ x 0} /-- The quadrant in `ℝ^n`, used to model manifolds with corners, made of all vectors with nonnegative coordinates. -/ def euclidean_quadrant (n : ℕ) : Type := {x : euclidean_space (fin n) // ∀i:fin n, 0 ≤ x i} section /- Register class instances for euclidean half-space and quadrant, that can not be noticed without the following reducibility attribute (which is only set in this section). -/ local attribute [reducible] euclidean_half_space euclidean_quadrant variable {n : ℕ} instance [has_zero (fin n)] : topological_space (euclidean_half_space n) := by apply_instance instance : topological_space (euclidean_quadrant n) := by apply_instance instance [has_zero (fin n)] : inhabited (euclidean_half_space n) := ⟨⟨0, le_refl _⟩⟩ instance : inhabited (euclidean_quadrant n) := ⟨⟨0, λ i, le_refl _⟩⟩ lemma range_half_space (n : ℕ) [has_zero (fin n)] : range (λx : euclidean_half_space n, x.val) = {y | 0 ≤ y 0} := by simp lemma range_quadrant (n : ℕ) : range (λx : euclidean_quadrant n, x.val) = {y | ∀i:fin n, 0 ≤ y i} := by simp end /-- Definition of the model with corners `(euclidean_space (fin n), euclidean_half_space n)`, used as a model for manifolds with boundary. In the locale `manifold`, use the shortcut `𝓡∂ n`. -/ def model_with_corners_euclidean_half_space (n : ℕ) [has_zero (fin n)] : model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n) := { to_fun := λx, x.val, inv_fun := λx, ⟨λi, if h : i = 0 then max (x i) 0 else x i, by simp [le_refl]⟩, source := univ, target := range (λx : euclidean_half_space n, x.val), map_source' := λx hx, by simpa only [subtype.range_val] using x.property, map_target' := λx hx, mem_univ _, left_inv' := λ⟨xval, xprop⟩ hx, begin rw subtype.mk_eq_mk, ext1 i, by_cases hi : i = 0, { rw hi, simp only [xprop, dif_pos, max_eq_left] }, { simp only [hi, dif_neg, not_false_iff] } end, right_inv' := λx hx, begin simp only [mem_set_of_eq, subtype.range_val_subtype] at hx, ext1 i, by_cases hi : i = 0, { rw hi, simp only [hx, dif_pos, max_eq_left] } , { simp only [hi, dif_neg, not_false_iff] } end, source_eq := rfl, unique_diff' := begin /- To check that the half-space has the unique differentiability property, we use the criterion `unique_diff_on_convex`: it suffices to check that it is convex and with nonempty interior. -/ rw range_half_space, apply unique_diff_on_convex, show convex {y : euclidean_space (fin n) | 0 ≤ y 0}, { assume x y hx hy a b ha hb hab, simpa only [add_zero] using add_le_add (mul_nonneg ha hx) (mul_nonneg hb hy) }, show (interior {y : euclidean_space (fin n) | 0 ≤ y 0}).nonempty, { use (λi, 1), rw mem_interior, refine ⟨(pi (univ : set (fin n)) (λi, (Ioi 0 : set ℝ))), _, is_open_set_pi finite_univ (λa ha, is_open_Ioi), _⟩, { assume x hx, simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi] at hx, exact le_of_lt (hx 0) }, { simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi], assume i, exact zero_lt_one } } end, continuous_to_fun := continuous_subtype_val, continuous_inv_fun := begin apply continuous_subtype_mk, apply continuous_pi, assume i, by_cases h : i = 0, { rw h, simp only [dif_pos], have : continuous (λx:ℝ, max x 0) := continuous_id.max continuous_const, exact this.comp (continuous_apply 0) }, { simp only [h, dif_neg, not_false_iff], exact continuous_apply i } end } /-- Definition of the model with corners `(euclidean_space (fin n), euclidean_quadrant n)`, used as a model for manifolds with corners -/ def model_with_corners_euclidean_quadrant (n : ℕ) : model_with_corners ℝ (euclidean_space (fin n)) (euclidean_quadrant n) := { to_fun := λx, x.val, inv_fun := λx, ⟨λi, max (x i) 0, λi, by simp only [le_refl, or_true, le_max_iff]⟩, source := univ, target := range (λx : euclidean_quadrant n, x.val), map_source' := λx hx, by simpa only [subtype.range_val] using x.property, map_target' := λx hx, mem_univ _, left_inv' := λ⟨xval, xprop⟩ hx, begin rw subtype.mk_eq_mk, ext1 i, simp only [xprop i, max_eq_left] end, right_inv' := λx hx, begin rw range_quadrant at hx, ext1 i, simp only [hx i, max_eq_left] end, source_eq := rfl, unique_diff' := begin /- To check that the quadrant has the unique differentiability property, we use the criterion `unique_diff_on_convex`: it suffices to check that it is convex and with nonempty interior. -/ rw range_quadrant, apply unique_diff_on_convex, show convex {y : euclidean_space (fin n) | ∀ (i : fin n), 0 ≤ y i}, { assume x y hx hy a b ha hb hab i, simpa only [add_zero] using add_le_add (mul_nonneg ha (hx i)) (mul_nonneg hb (hy i)) }, show (interior {y : euclidean_space (fin n) | ∀ (i : fin n), 0 ≤ y i}).nonempty, { use (λi, 1), rw mem_interior, refine ⟨(pi (univ : set (fin n)) (λi, (Ioi 0 : set ℝ))), _, is_open_set_pi finite_univ (λa ha, is_open_Ioi), _⟩, { assume x hx i, simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi] at hx, exact le_of_lt (hx i) }, { simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi], assume i, exact zero_lt_one } } end, continuous_to_fun := continuous_subtype_val, continuous_inv_fun := begin apply continuous_subtype_mk, apply continuous_pi, assume i, have : continuous (λx:ℝ, max x 0) := continuous.max continuous_id continuous_const, exact this.comp (continuous_apply i) end } localized "notation `𝓡 `n := model_with_corners_self ℝ (euclidean_space (fin n))" in manifold localized "notation `𝓡∂ `n := model_with_corners_euclidean_half_space n" in manifold /-- The left chart for the topological space `[x, y]`, defined on `[x,y)` and sending `x` to `0` in `euclidean_half_space 1`. -/ def Icc_left_chart (x y : ℝ) [fact (x < y)] : local_homeomorph (Icc x y) (euclidean_half_space 1) := { source := {z : Icc x y | z.val < y}, target := {z : euclidean_half_space 1 | z.val 0 < y - x}, to_fun := λ(z : Icc x y), ⟨λi, z.val - x, sub_nonneg.mpr z.property.1⟩, inv_fun := λz, ⟨min (z.val 0 + x) y, by simp [le_refl, z.prop, le_of_lt ‹x < y›]⟩, map_source' := by simp only [imp_self, sub_lt_sub_iff_right, mem_set_of_eq, forall_true_iff], map_target' := by { simp only [min_lt_iff, mem_set_of_eq], assume z hz, left, dsimp [-subtype.val_eq_coe] at hz, linarith }, left_inv' := begin rintros ⟨z, hz⟩ h'z, simp only [mem_set_of_eq, mem_Icc] at hz h'z, simp only [hz, min_eq_left, sub_add_cancel] end, right_inv' := begin rintros ⟨z, hz⟩ h'z, rw subtype.mk_eq_mk, funext, dsimp at hz h'z, have A : x + z 0 ≤ y, by linarith, rw subsingleton.elim i 0, simp only [A, add_comm, add_sub_cancel', min_eq_left], end, open_source := begin have : is_open {z : ℝ | z < y} := is_open_Iio, exact continuous_subtype_val _ this end, open_target := begin have : is_open {z : ℝ | z < y - x} := is_open_Iio, have : is_open {z : euclidean_space (fin 1) | z 0 < y - x} := @continuous_apply (fin 1) (λ _, ℝ) _ 0 _ this, exact continuous_subtype_val _ this end, continuous_to_fun := begin apply continuous.continuous_on, apply continuous_subtype_mk, have : continuous (λ (z : ℝ) (i : fin 1), z - x) := continuous.sub (continuous_pi $ λi, continuous_id) continuous_const, exact this.comp continuous_subtype_val, end, continuous_inv_fun := begin apply continuous.continuous_on, apply continuous_subtype_mk, have A : continuous (λ z : ℝ, min (z + x) y) := (continuous_id.add continuous_const).min continuous_const, have B : continuous (λz : euclidean_space (fin 1), z 0) := continuous_apply 0, exact (A.comp B).comp continuous_subtype_val end } /-- The right chart for the topological space `[x, y]`, defined on `(x,y]` and sending `y` to `0` in `euclidean_half_space 1`. -/ def Icc_right_chart (x y : ℝ) [fact (x < y)] : local_homeomorph (Icc x y) (euclidean_half_space 1) := { source := {z : Icc x y | x < z.val}, target := {z : euclidean_half_space 1 | z.val 0 < y - x}, to_fun := λ(z : Icc x y), ⟨λi, y - z.val, sub_nonneg.mpr z.property.2⟩, inv_fun := λz, ⟨max (y - z.val 0) x, by simp [le_refl, z.prop, le_of_lt ‹x < y›, sub_eq_add_neg]⟩, map_source' := by simp only [imp_self, mem_set_of_eq, sub_lt_sub_iff_left, forall_true_iff], map_target' := by { simp only [lt_max_iff, mem_set_of_eq], assume z hz, left, dsimp [-subtype.val_eq_coe] at hz, linarith }, left_inv' := begin rintros ⟨z, hz⟩ h'z, simp only [mem_set_of_eq, mem_Icc] at hz h'z, simp only [hz, sub_eq_add_neg, max_eq_left, add_add_neg_cancel'_right, neg_add_rev, neg_neg] end, right_inv' := begin rintros ⟨z, hz⟩ h'z, rw subtype.mk_eq_mk, funext, dsimp at hz h'z, have A : x ≤ y - z 0, by linarith, rw subsingleton.elim i 0, simp only [A, sub_sub_cancel, max_eq_left], end, open_source := begin have : is_open {z : ℝ | x < z} := is_open_Ioi, exact continuous_subtype_val _ this end, open_target := begin have : is_open {z : ℝ | z < y - x} := is_open_Iio, have : is_open {z : euclidean_space (fin 1) | z 0 < y - x} := @continuous_apply (fin 1) (λ _, ℝ) _ 0 _ this, exact continuous_subtype_val _ this end, continuous_to_fun := begin apply continuous.continuous_on, apply continuous_subtype_mk, have : continuous (λ (z : ℝ) (i : fin 1), y - z) := continuous_const.sub (continuous_pi (λi, continuous_id)), exact this.comp continuous_subtype_val, end, continuous_inv_fun := begin apply continuous.continuous_on, apply continuous_subtype_mk, have A : continuous (λ z : ℝ, max (y - z) x) := (continuous_const.sub continuous_id).max continuous_const, have B : continuous (λz : euclidean_space (fin 1), z 0) := continuous_apply 0, exact (A.comp B).comp continuous_subtype_val end } /-- Charted space structure on `[x, y]`, using only two charts taking values in `euclidean_half_space 1`. -/ instance Icc_manifold (x y : ℝ) [fact (x < y)] : charted_space (euclidean_half_space 1) (Icc x y) := { atlas := {Icc_left_chart x y, Icc_right_chart x y}, chart_at := λz, if z.val < y then Icc_left_chart x y else Icc_right_chart x y, mem_chart_source := λz, begin by_cases h' : z.val < y, { simp only [h', if_true], exact h' }, { simp only [h', if_false], apply lt_of_lt_of_le ‹x < y›, simpa only [not_lt] using h'} end, chart_mem_atlas := λz, by { by_cases h' : z.val < y; simp [h'] } } /-- The manifold structure on `[x, y]` is smooth. -/ instance Icc_smooth_manifold (x y : ℝ) [fact (x < y)] : smooth_manifold_with_corners (𝓡∂ 1) (Icc x y) := begin have M : times_cont_diff_on ℝ ∞ (λz : euclidean_space (fin 1), - z + (λi, y - x)) univ, { rw times_cont_diff_on_univ, exact times_cont_diff_id.neg.add times_cont_diff_const }, haveI : has_groupoid (Icc x y) (times_cont_diff_groupoid ∞ (𝓡∂ 1)) := begin apply has_groupoid_of_pregroupoid, assume e e' he he', simp only [atlas, mem_singleton_iff, mem_insert_iff] at he he', /- We need to check that any composition of two charts gives a `C^∞` function. Each chart can be either the left chart or the right chart, leaving 4 possibilities that we handle successively. -/ rcases he with rfl | rfl; rcases he' with rfl | rfl, { -- `e = left chart`, `e' = left chart` refine (mem_groupoid_of_pregroupoid.mpr _).1, exact symm_trans_mem_times_cont_diff_groupoid _ _ _ }, { -- `e = left chart`, `e' = right chart` apply M.congr_mono _ (subset_univ _), assume z hz, simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, dif_pos, lt_add_iff_pos_left, max_lt_iff, lt_min_iff, sub_pos, lt_max_iff, subtype.range_val] with mfld_simps at hz, have A : 0 ≤ z 0 := hz.2, have B : z 0 + x ≤ y, by { have := hz.1.1.1, linarith }, ext i, rw subsingleton.elim i 0, simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, A, B, pi_Lp.add_apply, dif_pos, min_eq_left, max_eq_left, pi_Lp.neg_apply] with mfld_simps, ring }, { -- `e = right chart`, `e' = left chart` apply M.congr_mono _ (subset_univ _), assume z hz, simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, dif_pos, max_lt_iff, sub_pos, subtype.range_val] with mfld_simps at hz, have A : 0 ≤ z 0 := hz.2, have B : x ≤ y - z 0, by { have := hz.1.1.1, dsimp at this, linarith }, ext i, rw subsingleton.elim i 0, simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, A, B, pi_Lp.add_apply, dif_pos, max_eq_left, pi_Lp.neg_apply] with mfld_simps, ring }, { -- `e = right chart`, `e' = right chart` refine (mem_groupoid_of_pregroupoid.mpr _).1, exact symm_trans_mem_times_cont_diff_groupoid _ _ _ } end, constructor end /- Register an instance of `0 < 1` to be able to use freely the manifold structure on `Icc 0 1`. -/ instance : fact ((0 : ℝ) < 1) := zero_lt_one
a1ab2f35c690f95b5e9a92a72cff5650bbe0d0fb
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/nat/cast.lean
972a4b3822453e3d2a906a09a13e1d557e87bf79
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
8,885
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.nat.basic import data.nat.cast.defs import algebra.group.pi import tactic.pi_instances /-! # Cast of natural numbers (additional theorems) This file proves additional properties about the *canonical* homomorphism from the natural numbers into an additive monoid with a one (`nat.cast`). ## Main declarations * `cast_add_monoid_hom`: `cast` bundled as an `add_monoid_hom`. * `cast_ring_hom`: `cast` bundled as a `ring_hom`. -/ namespace nat variables {α : Type*} /-- `coe : ℕ → α` as an `add_monoid_hom`. -/ def cast_add_monoid_hom (α : Type*) [add_monoid_with_one α] : ℕ →+ α := { to_fun := coe, map_add' := cast_add, map_zero' := cast_zero } @[simp] lemma coe_cast_add_monoid_hom [add_monoid_with_one α] : (cast_add_monoid_hom α : ℕ → α) = coe := rfl @[simp, norm_cast] theorem cast_mul [non_assoc_semiring α] (m n : ℕ) : ((m * n : ℕ) : α) = m * n := by induction n; simp [mul_succ, mul_add, *] /-- `coe : ℕ → α` as a `ring_hom` -/ def cast_ring_hom (α : Type*) [non_assoc_semiring α] : ℕ →+* α := { to_fun := coe, map_one' := cast_one, map_mul' := cast_mul, .. cast_add_monoid_hom α } @[simp] lemma coe_cast_ring_hom [non_assoc_semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl lemma cast_commute [non_assoc_semiring α] (n : ℕ) (x : α) : commute ↑n x := nat.rec_on n (by rw [cast_zero]; exact commute.zero_left x) $ λ n ihn, by rw [cast_succ]; exact ihn.add_left (commute.one_left x) lemma cast_comm [non_assoc_semiring α] (n : ℕ) (x : α) : (n : α) * x = x * n := (cast_commute n x).eq lemma commute_cast [non_assoc_semiring α] (x : α) (n : ℕ) : commute x n := (n.cast_commute x).symm section variables [ordered_semiring α] @[mono] theorem mono_cast : monotone (coe : ℕ → α) := monotone_nat_of_le_succ $ λ n, by rw [nat.cast_succ]; exact le_add_of_nonneg_right zero_le_one @[simp] theorem cast_nonneg (n : ℕ) : 0 ≤ (n : α) := @nat.cast_zero α _ ▸ mono_cast (nat.zero_le n) variable [nontrivial α] @[simp, norm_cast] theorem cast_le {m n : ℕ} : (m : α) ≤ n ↔ m ≤ n := strict_mono_cast.le_iff_le @[simp, norm_cast, mono] theorem cast_lt {m n : ℕ} : (m : α) < n ↔ m < n := strict_mono_cast.lt_iff_lt @[simp] theorem cast_pos {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] lemma cast_add_one_pos (n : ℕ) : 0 < (n : α) + 1 := add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one @[simp, norm_cast] theorem one_lt_cast {n : ℕ} : 1 < (n : α) ↔ 1 < n := by rw [← cast_one, cast_lt] @[simp, norm_cast] theorem one_le_cast {n : ℕ} : 1 ≤ (n : α) ↔ 1 ≤ n := by rw [← cast_one, cast_le] @[simp, norm_cast] theorem cast_lt_one {n : ℕ} : (n : α) < 1 ↔ n = 0 := by rw [← cast_one, cast_lt, lt_succ_iff, le_zero_iff] @[simp, norm_cast] theorem cast_le_one {n : ℕ} : (n : α) ≤ 1 ↔ n ≤ 1 := by rw [← cast_one, cast_le] end @[simp, norm_cast] theorem cast_min [linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := (@mono_cast α _).map_min @[simp, norm_cast] theorem cast_max [linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := (@mono_cast α _).map_max @[simp, norm_cast] theorem abs_cast [linear_ordered_ring α] (a : ℕ) : |(a : α)| = a := abs_of_nonneg (cast_nonneg a) lemma coe_nat_dvd [semiring α] {m n : ℕ} (h : m ∣ n) : (m : α) ∣ (n : α) := map_dvd (nat.cast_ring_hom α) h alias coe_nat_dvd ← _root_.has_dvd.dvd.nat_cast end nat namespace prod variables {α : Type*} {β : Type*} [add_monoid_with_one α] [add_monoid_with_one β] instance : add_monoid_with_one (α × β) := { nat_cast := λ n, (n, n), nat_cast_zero := congr_arg2 prod.mk nat.cast_zero nat.cast_zero, nat_cast_succ := λ n, congr_arg2 prod.mk (nat.cast_succ _) (nat.cast_succ _), .. prod.add_monoid, .. prod.has_one } @[simp] lemma fst_nat_cast (n : ℕ) : (n : α × β).fst = n := by induction n; simp * @[simp] lemma snd_nat_cast (n : ℕ) : (n : α × β).snd = n := by induction n; simp * end prod section add_monoid_hom_class variables {A B F : Type*} [add_monoid_with_one B] lemma ext_nat' [add_monoid A] [add_monoid_hom_class F ℕ A] (f g : F) (h : f 1 = g 1) : f = g := fun_like.ext f g $ begin apply nat.rec, { simp only [nat.nat_zero_eq_zero, map_zero] }, simp [nat.succ_eq_add_one, h] {contextual := tt} end @[ext] lemma add_monoid_hom.ext_nat [add_monoid A] : ∀ {f g : ℕ →+ A}, ∀ h : f 1 = g 1, f = g := ext_nat' variable [add_monoid_with_one A] -- these versions are primed so that the `ring_hom_class` versions aren't lemma eq_nat_cast' [add_monoid_hom_class F ℕ A] (f : F) (h1 : f 1 = 1) : ∀ n : ℕ, f n = n | 0 := by simp | (n+1) := by rw [map_add, h1, eq_nat_cast' n, nat.cast_add_one] lemma map_nat_cast' {A} [add_monoid_with_one A] [add_monoid_hom_class F A B] (f : F) (h : f 1 = 1) : ∀ (n : ℕ), f n = n | 0 := by simp | (n+1) := by rw [nat.cast_add, map_add, nat.cast_add, map_nat_cast', nat.cast_one, h, nat.cast_one] end add_monoid_hom_class section monoid_with_zero_hom_class variables {A F : Type*} [mul_zero_one_class A] /-- If two `monoid_with_zero_hom`s agree on the positive naturals they are equal. -/ theorem ext_nat'' [monoid_with_zero_hom_class F ℕ A] (f g : F) (h_pos : ∀ {n : ℕ}, 0 < n → f n = g n) : f = g := begin apply fun_like.ext, rintro (_|n), { simp }, exact h_pos n.succ_pos end @[ext] theorem monoid_with_zero_hom.ext_nat : ∀ {f g : ℕ →*₀ A}, (∀ {n : ℕ}, 0 < n → f n = g n) → f = g := ext_nat'' end monoid_with_zero_hom_class section ring_hom_class variables {R S F : Type*} [non_assoc_semiring R] [non_assoc_semiring S] @[simp] lemma eq_nat_cast [ring_hom_class F ℕ R] (f : F) : ∀ n, f n = n := eq_nat_cast' f $ map_one f @[simp] lemma map_nat_cast [ring_hom_class F R S] (f : F) : ∀ n : ℕ, f (n : R) = n := map_nat_cast' f $ map_one f lemma ext_nat [ring_hom_class F ℕ R] (f g : F) : f = g := ext_nat' f g $ by simp only [map_one] end ring_hom_class namespace ring_hom /-- This is primed to match `ring_hom.eq_int_cast'`. -/ lemma eq_nat_cast' {R} [non_assoc_semiring R] (f : ℕ →+* R) : f = nat.cast_ring_hom R := ring_hom.ext $ eq_nat_cast f end ring_hom @[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n := rfl @[simp] lemma nat.cast_ring_hom_nat : nat.cast_ring_hom ℕ = ring_hom.id ℕ := rfl @[simp] theorem nat.cast_with_bot (n : ℕ) : @coe ℕ (with_bot ℕ) (@coe_to_lift _ _ nat.cast_coe) n = n := rfl -- I don't think `ring_hom_class` is good here, because of the `subsingleton` TC slowness instance nat.unique_ring_hom {R : Type*} [non_assoc_semiring R] : unique (ℕ →+* R) := { default := nat.cast_ring_hom R, uniq := ring_hom.eq_nat_cast' } namespace mul_opposite variables {α : Type*} [add_monoid_with_one α] @[simp, norm_cast] lemma op_nat_cast (n : ℕ) : op (n : α) = n := rfl @[simp, norm_cast] lemma unop_nat_cast (n : ℕ) : unop (n : αᵐᵒᵖ) = n := rfl end mul_opposite namespace with_top variables {α : Type*} variables [add_monoid_with_one α] @[simp, norm_cast] lemma coe_nat : ∀ (n : ℕ), ((n : α) : with_top α) = n | 0 := rfl | (n+1) := by { push_cast, rw [coe_nat n] } @[simp] lemma nat_ne_top (n : nat) : (n : with_top α) ≠ ⊤ := by { rw [←coe_nat n], apply coe_ne_top } @[simp] lemma top_ne_nat (n : nat) : (⊤ : with_top α) ≠ n := by { rw [←coe_nat n], apply top_ne_coe } lemma add_one_le_of_lt {i n : with_top ℕ} (h : i < n) : i + 1 ≤ n := begin cases n, { exact le_top }, cases i, { exact (not_le_of_lt h le_top).elim }, exact with_top.coe_le_coe.2 (with_top.coe_lt_coe.1 h) end lemma one_le_iff_pos {n : with_top ℕ} : 1 ≤ n ↔ 0 < n := ⟨lt_of_lt_of_le (coe_lt_coe.mpr zero_lt_one), λ h, by simpa only [zero_add] using add_one_le_of_lt h⟩ @[elab_as_eliminator] lemma nat_induction {P : with_top ℕ → Prop} (a : with_top ℕ) (h0 : P 0) (hsuc : ∀n:ℕ, P n → P n.succ) (htop : (∀n : ℕ, P n) → P ⊤) : P a := begin have A : ∀n:ℕ, P n := λ n, nat.rec_on n h0 hsuc, cases a, { exact htop A }, { exact A a } end end with_top namespace pi variables {α : Type*} {β : α → Type*} [∀ a, has_nat_cast (β a)] instance : has_nat_cast (∀ a, β a) := by refine_struct { .. }; tactic.pi_instance_derive_field lemma nat_apply (n : ℕ) (a : α) : (n : ∀ a, β a) a = n := rfl @[simp] lemma coe_nat (n : ℕ) : (n : ∀ a, β a) = λ _, n := rfl end pi namespace pi variables {α : Type*} {β : α → Type*} [∀ a, add_monoid_with_one (β a)] instance : add_monoid_with_one (∀ a, β a) := by refine_struct { .. }; tactic.pi_instance_derive_field end pi
5ec0866efc6ef682ecb7158d25877730bb744283
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/eq23.lean
e1a44aafcee00c40ab5a3070d9d0567a0cae7bc4
[ "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
586
lean
open nat inductive tree (A : Type) := leaf : A → tree A, node : tree_list A → tree A with tree_list := nil : tree_list A, cons : tree A → tree_list A → tree_list A namespace tree_list definition len {A : Type} : tree_list A → nat, len (nil A) := 0, len (cons t l) := len l + 1 theorem len_nil {A : Type} : len (nil A) = 0 := rfl theorem len_cons {A : Type} (t : tree A) (l : tree_list A) : len (cons t l) = len l + 1 := rfl variables (A : Type) (t1 t2 t3 : tree A) example : len (cons t1 (cons t2 (cons t3 (nil A)))) = 3 := rfl print definition len end tree_list
8b304b98710e997f02f2e9970901651dfeaf6738
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Expr.lean
96029827b6bb6d66a0d3a9a658b244a9db2dd335
[ "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
36,868
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Level namespace Lean inductive Literal | natVal (val : Nat) | strVal (val : String) instance Literal.inhabited : Inhabited Literal := ⟨Literal.natVal 0⟩ def Literal.hash : Literal → USize | Literal.natVal v => hash v | Literal.strVal v => hash v instance Literal.hashable : Hashable Literal := ⟨Literal.hash⟩ def Literal.beq : Literal → Literal → Bool | Literal.natVal v₁, Literal.natVal v₂ => v₁ == v₂ | Literal.strVal v₁, Literal.strVal v₂ => v₁ == v₂ | _, _ => false instance Literal.hasBeq : HasBeq Literal := ⟨Literal.beq⟩ def Literal.lt : Literal → Literal → Bool | Literal.natVal _, Literal.strVal _ => true | Literal.natVal v₁, Literal.natVal v₂ => v₁ < v₂ | Literal.strVal v₁, Literal.strVal v₂ => v₁ < v₂ | _, _ => false instance Literal.hasLess : HasLess Literal := ⟨fun a b => a.lt b⟩ inductive BinderInfo | default | implicit | strictImplicit | instImplicit | auxDecl def BinderInfo.hash : BinderInfo → USize | BinderInfo.default => 947 | BinderInfo.implicit => 1019 | BinderInfo.strictImplicit => 1087 | BinderInfo.instImplicit => 1153 | BinderInfo.auxDecl => 1229 def BinderInfo.isExplicit : BinderInfo → Bool | BinderInfo.implicit => false | BinderInfo.strictImplicit => false | BinderInfo.instImplicit => false | _ => true instance BinderInfo.hashable : Hashable BinderInfo := ⟨BinderInfo.hash⟩ instance BinderInfo.inhabited : Inhabited BinderInfo := ⟨BinderInfo.default⟩ def BinderInfo.isInstImplicit : BinderInfo → Bool | BinderInfo.instImplicit => true | _ => false def BinderInfo.isAuxDecl : BinderInfo → Bool | BinderInfo.auxDecl => true | _ => false protected def BinderInfo.beq : BinderInfo → BinderInfo → Bool | BinderInfo.default, BinderInfo.default => true | BinderInfo.implicit, BinderInfo.implicit => true | BinderInfo.strictImplicit, BinderInfo.strictImplicit => true | BinderInfo.instImplicit, BinderInfo.instImplicit => true | BinderInfo.auxDecl, BinderInfo.auxDecl => true | _, _ => false instance BinderInfo.hasBeq : HasBeq BinderInfo := ⟨BinderInfo.beq⟩ abbrev MData := KVMap abbrev MData.empty : MData := {} /-- Cached hash code, cached results, and other data for `Expr`. hash : 32-bits hasFVar : 1-bit hasExprMVar : 1-bit hasLevelMVar : 1-bit hasLevelParam : 1-bit nonDepLet : 1-bit binderInfo : 3-bits looseBVarRange : 24-bits -/ def Expr.Data := UInt64 instance Expr.Data.inhabited : Inhabited Expr.Data := inferInstanceAs (Inhabited UInt64) def Expr.Data.hash (c : Expr.Data) : USize := c.toUInt32.toUSize instance Expr.Data.hasBeq : HasBeq Expr.Data := ⟨fun (a b : UInt64) => a == b⟩ def Expr.Data.looseBVarRange (c : Expr.Data) : UInt32 := (c.shiftRight 40).toUInt32 def Expr.Data.hasFVar (c : Expr.Data) : Bool := ((c.shiftRight 32).land 1) == 1 def Expr.Data.hasExprMVar (c : Expr.Data) : Bool := ((c.shiftRight 33).land 1) == 1 def Expr.Data.hasLevelMVar (c : Expr.Data) : Bool := ((c.shiftRight 34).land 1) == 1 def Expr.Data.hasLevelParam (c : Expr.Data) : Bool := ((c.shiftRight 35).land 1) == 1 def Expr.Data.nonDepLet (c : Expr.Data) : Bool := ((c.shiftRight 36).land 1) == 1 @[extern c inline "(uint8_t)((#1 << 24) >> 61)"] def Expr.Data.binderInfo (c : Expr.Data) : BinderInfo := let bi := (c.shiftLeft 24).shiftRight 61; if bi == 0 then BinderInfo.default else if bi == 1 then BinderInfo.implicit else if bi == 2 then BinderInfo.strictImplicit else if bi == 3 then BinderInfo.instImplicit else BinderInfo.auxDecl @[extern c inline "(uint64_t)#1"] def BinderInfo.toUInt64 : BinderInfo → UInt64 | BinderInfo.default => 0 | BinderInfo.implicit => 1 | BinderInfo.strictImplicit => 2 | BinderInfo.instImplicit => 3 | BinderInfo.auxDecl => 4 @[inline] private def Expr.mkDataCore (h : USize) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) (bi : BinderInfo) : Expr.Data := if looseBVarRange > Nat.pow 2 24 - 1 then panic! "bound variable index is too big" else let r : UInt64 := h.toUInt32.toUInt64 + hasFVar.toUInt64.shiftLeft 32 + hasExprMVar.toUInt64.shiftLeft 33 + hasLevelMVar.toUInt64.shiftLeft 34 + hasLevelParam.toUInt64.shiftLeft 35 + nonDepLet.toUInt64.shiftLeft 36 + bi.toUInt64.shiftLeft 37 + looseBVarRange.toUInt64.shiftLeft 40; r def Expr.mkData (h : USize) (looseBVarRange : Nat := 0) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool := false) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam false BinderInfo.default def Expr.mkDataForBinder (h : USize) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) (bi : BinderInfo) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam false bi def Expr.mkDataForLet (h : USize) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet BinderInfo.default open Expr abbrev MVarId := Name abbrev FVarId := Name /- We use the `E` suffix (short for `Expr`) to avoid collision with keywords. We considered using «...», but it is too inconvenient to use. -/ inductive Expr | bvar : Nat → Data → Expr -- bound variables | fvar : FVarId → Data → Expr -- free variables | mvar : MVarId → Data → Expr -- meta variables | sort : Level → Data → Expr -- Sort | const : Name → List Level → Data → Expr -- constants | app : Expr → Expr → Data → Expr -- application | lam : Name → Expr → Expr → Data → Expr -- lambda abstraction | forallE : Name → Expr → Expr → Data → Expr -- (dependent) arrow | letE : Name → Expr → Expr → Expr → Data → Expr -- let expressions | lit : Literal → Data → Expr -- literals | mdata : MData → Expr → Data → Expr -- metadata | proj : Name → Nat → Expr → Data → Expr -- projection -- IMPORTANT: the following constructor will be deleted | localE : Name → Name → Expr → Data → Expr -- Lean2 legacy. TODO: delete namespace Expr instance : Inhabited Expr := ⟨sort (arbitrary _) (arbitrary _)⟩ @[inline] def data : Expr → Data | bvar _ d => d | fvar _ d => d | mvar _ d => d | sort _ d => d | const _ _ d => d | app _ _ d => d | lam _ _ _ d => d | forallE _ _ _ d => d | letE _ _ _ _ d => d | lit _ d => d | mdata _ _ d => d | proj _ _ _ d => d | localE _ _ _ d => d def ctorName : Expr → String | bvar _ _ => "bvar" | fvar _ _ => "fvar" | mvar _ _ => "mvar" | sort _ _ => "sort" | const _ _ _ => "const" | app _ _ _ => "app" | lam _ _ _ _ => "lam" | forallE _ _ _ _ => "forallE" | letE _ _ _ _ _ => "letE" | lit _ _ => "lit" | mdata _ _ _ => "mdata" | proj _ _ _ _ => "proj" | localE _ _ _ _ => "localE" def hash (e : Expr) : USize := e.data.hash instance : Hashable Expr := ⟨Expr.hash⟩ def hasFVar (e : Expr) : Bool := e.data.hasFVar def hasExprMVar (e : Expr) : Bool := e.data.hasExprMVar def hasLevelMVar (e : Expr) : Bool := e.data.hasLevelMVar def hasMVar (e : Expr) : Bool := let d := e.data; d.hasExprMVar || d.hasLevelMVar def hasLevelParam (e : Expr) : Bool := e.data.hasLevelParam def looseBVarRange (e : Expr) : Nat := e.data.looseBVarRange.toNat def binderInfo (e : Expr) : BinderInfo := e.data.binderInfo @[export lean_expr_hash] def hashEx : Expr → USize := hash @[export lean_expr_has_fvar] def hasFVarEx : Expr → Bool := hasFVar @[export lean_expr_has_expr_mvar] def hasExprMVarEx : Expr → Bool := hasExprMVar @[export lean_expr_has_level_mvar] def hasLevelMVarEx : Expr → Bool := hasLevelMVar @[export lean_expr_has_mvar] def hasMVarEx : Expr → Bool := hasMVar @[export lean_expr_has_level_param] def hasLevelParamEx : Expr → Bool := hasLevelParam @[export lean_expr_loose_bvar_range] def looseBVarRangeEx (e : Expr) : UInt32 := e.data.looseBVarRange @[export lean_expr_binder_info] def binderInfoEx : Expr → BinderInfo := binderInfo end Expr def mkLit (l : Literal) : Expr := Expr.lit l $ mkData (mixHash 3 (hash l)) def mkNatLit (n : Nat) : Expr := mkLit (Literal.natVal n) def mkStrLit (s : String) : Expr := mkLit (Literal.strVal s) def mkConst (n : Name) (lvls : List Level := []) : Expr := Expr.const n lvls $ mkData (mixHash 5 $ mixHash (hash n) (hash lvls)) 0 false false (lvls.any Level.hasMVar) (lvls.any Level.hasParam) def Literal.type : Literal → Expr | Literal.natVal _ => mkConst `Nat | Literal.strVal _ => mkConst `String @[export lean_lit_type] def Literal.typeEx : Literal → Expr := Literal.type def mkBVar (idx : Nat) : Expr := Expr.bvar idx $ mkData (mixHash 7 $ hash idx) (idx+1) def mkSort (lvl : Level) : Expr := Expr.sort lvl $ mkData (mixHash 11 $ hash lvl) 0 false false lvl.hasMVar lvl.hasParam def mkFVar (fvarId : FVarId) : Expr := Expr.fvar fvarId $ mkData (mixHash 13 $ hash fvarId) 0 true def mkMVar (fvarId : MVarId) : Expr := Expr.mvar fvarId $ mkData (mixHash 17 $ hash fvarId) 0 false true def mkMData (d : MData) (e : Expr) : Expr := Expr.mdata d e $ mkData (mixHash 19 $ hash e) e.looseBVarRange e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam def mkProj (s : Name) (i : Nat) (e : Expr) : Expr := Expr.proj s i e $ mkData (mixHash 23 $ mixHash (hash s) $ mixHash (hash i) (hash e)) e.looseBVarRange e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam def mkApp (f a : Expr) : Expr := Expr.app f a $ mkData (mixHash 29 $ mixHash (hash f) (hash a)) (Nat.max f.looseBVarRange a.looseBVarRange) (f.hasFVar || a.hasFVar) (f.hasExprMVar || a.hasExprMVar) (f.hasLevelMVar || a.hasLevelMVar) (f.hasLevelParam || a.hasLevelParam) def mkLambda (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr := -- let x := x.eraseMacroScopes; Expr.lam x t b $ mkDataForBinder (mixHash 31 $ mixHash (hash t) (hash b)) (Nat.max t.looseBVarRange (b.looseBVarRange - 1)) (t.hasFVar || b.hasFVar) (t.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || b.hasLevelParam) bi def mkForall (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr := -- let x := x.eraseMacroScopes; Expr.forallE x t b $ mkDataForBinder (mixHash 37 $ mixHash (hash t) (hash b)) (Nat.max t.looseBVarRange (b.looseBVarRange - 1)) (t.hasFVar || b.hasFVar) (t.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || b.hasLevelParam) bi /- Return `Unit -> type` -/ def mkThunkType (type : Expr) : Expr := mkForall Name.anonymous BinderInfo.default (Lean.mkConst `Unit) type /- Return `fun (_ : Unit), e` -/ def mkThunk (type : Expr) : Expr := mkLambda `_ BinderInfo.default (Lean.mkConst `Unit) type def mkLet (x : Name) (t : Expr) (v : Expr) (b : Expr) (nonDep : Bool := false) : Expr := -- let x := x.eraseMacroScopes; Expr.letE x t v b $ mkDataForLet (mixHash 41 $ mixHash (hash t) $ mixHash (hash v) (hash b)) (Nat.max (Nat.max t.looseBVarRange v.looseBVarRange) (b.looseBVarRange - 1)) (t.hasFVar || v.hasFVar || b.hasFVar) (t.hasExprMVar || v.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || v.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || v.hasLevelParam || b.hasLevelParam) nonDep -- TODO: delete def mkLocal (x u : Name) (t : Expr) (bi : BinderInfo) : Expr := Expr.localE x u t $ mkDataForBinder (mixHash 43 $ hash t) t.looseBVarRange true t.hasExprMVar t.hasLevelMVar t.hasLevelParam bi @[export lean_expr_mk_bvar] def mkBVarEx : Nat → Expr := mkBVar @[export lean_expr_mk_fvar] def mkFVarEx : FVarId → Expr := mkFVar @[export lean_expr_mk_mvar] def mkMVarEx : MVarId → Expr := mkMVar @[export lean_expr_mk_sort] def mkSortEx : Level → Expr := mkSort @[export lean_expr_mk_const] def mkConstEx (c : Name) (lvls : List Level) : Expr := mkConst c lvls @[export lean_expr_mk_app] def mkAppEx : Expr → Expr → Expr := mkApp @[export lean_expr_mk_lambda] def mkLambdaEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkLambda n bi d b @[export lean_expr_mk_forall] def mkForallEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkForall n bi d b @[export lean_expr_mk_let] def mkLetEx (n : Name) (t v b : Expr) : Expr := mkLet n t v b @[export lean_expr_mk_lit] def mkLitEx : Literal → Expr := mkLit @[export lean_expr_mk_mdata] def mkMDataEx : MData → Expr → Expr := mkMData @[export lean_expr_mk_proj] def mkProjEx : Name → Nat → Expr → Expr := mkProj @[export lean_expr_mk_local] def mkLocalEx : Name → Name → Expr → BinderInfo → Expr := mkLocal def mkAppN (f : Expr) (args : Array Expr) : Expr := args.foldl mkApp f private partial def mkAppRangeAux (n : Nat) (args : Array Expr) : Nat → Expr → Expr | i, e => if i < n then mkAppRangeAux (i+1) (mkApp e (args.get! i)) else e /-- `mkAppRange f i j #[a_1, ..., a_i, ..., a_j, ... ]` ==> the expression `f a_i ... a_{j-1}` -/ def mkAppRange (f : Expr) (i j : Nat) (args : Array Expr) : Expr := mkAppRangeAux j args i f def mkAppRev (fn : Expr) (revArgs : Array Expr) : Expr := revArgs.foldr (fun a r => mkApp r a) fn namespace Expr -- TODO: implement it in Lean @[extern "lean_expr_dbg_to_string"] constant dbgToString (e : @& Expr) : String := arbitrary String @[extern "lean_expr_quick_lt"] constant quickLt (a : @& Expr) (b : @& Expr) : Bool := arbitrary _ @[extern "lean_expr_lt"] constant lt (a : @& Expr) (b : @& Expr) : Bool := arbitrary _ /- Return true iff `a` and `b` are alpha equivalent. Binder annotations are ignored. -/ @[extern "lean_expr_eqv"] constant eqv (a : @& Expr) (b : @& Expr) : Bool := arbitrary _ instance : HasBeq Expr := ⟨Expr.eqv⟩ /- Return true iff `a` and `b` are equal. Binder names and annotations are taking into account. -/ @[extern "lean_expr_equal"] constant equal (a : @& Expr) (b : @& Expr) : Bool := arbitrary _ def isSort : Expr → Bool | sort _ _ => true | _ => false def isBVar : Expr → Bool | bvar _ _ => true | _ => false def isMVar : Expr → Bool | mvar _ _ => true | _ => false def isFVar : Expr → Bool | fvar _ _ => true | _ => false def isApp : Expr → Bool | app _ _ _ => true | _ => false def isProj : Expr → Bool | proj _ _ _ _ => true | _ => false def isConst : Expr → Bool | const _ _ _ => true | _ => false def isConstOf : Expr → Name → Bool | const n _ _, m => n == m | _, _ => false def isForall : Expr → Bool | forallE _ _ _ _ => true | _ => false def isLambda : Expr → Bool | lam _ _ _ _ => true | _ => false def isBinding : Expr → Bool | lam _ _ _ _ => true | forallE _ _ _ _ => true | _ => false def isLet : Expr → Bool | letE _ _ _ _ _ => true | _ => false def isMData : Expr → Bool | mdata _ _ _ => true | _ => false def isLit : Expr → Bool | lit _ _ => true | _ => false def getAppFn : Expr → Expr | app f a _ => getAppFn f | e => e def getAppNumArgsAux : Expr → Nat → Nat | app f a _, n => getAppNumArgsAux f (n+1) | e, n => n def getAppNumArgs (e : Expr) : Nat := getAppNumArgsAux e 0 private def getAppArgsAux : Expr → Array Expr → Nat → Array Expr | app f a _, as, i => getAppArgsAux f (as.set! i a) (i-1) | _, as, _ => as @[inline] def getAppArgs (e : Expr) : Array Expr := let dummy := mkSort levelZero; let nargs := e.getAppNumArgs; getAppArgsAux e (mkArray nargs dummy) (nargs-1) private def getAppRevArgsAux : Expr → Array Expr → Array Expr | app f a _, as => getAppRevArgsAux f (as.push a) | _, as => as @[inline] def getAppRevArgs (e : Expr) : Array Expr := getAppRevArgsAux e (Array.mkEmpty e.getAppNumArgs) @[specialize] def withAppAux {α} (k : Expr → Array Expr → α) : Expr → Array Expr → Nat → α | app f a _, as, i => withAppAux f (as.set! i a) (i-1) | f, as, i => k f as @[inline] def withApp {α} (e : Expr) (k : Expr → Array Expr → α) : α := let dummy := mkSort levelZero; let nargs := e.getAppNumArgs; withAppAux k e (mkArray nargs dummy) (nargs-1) @[specialize] private def withAppRevAux {α} (k : Expr → Array Expr → α) : Expr → Array Expr → α | app f a _, as => withAppRevAux f (as.push a) | f, as => k f as @[inline] def withAppRev {α} (e : Expr) (k : Expr → Array Expr → α) : α := withAppRevAux k e (Array.mkEmpty e.getAppNumArgs) def getRevArgD : Expr → Nat → Expr → Expr | app f a _, 0, _ => a | app f _ _, i+1, v => getRevArgD f i v | _, _, v => v def getRevArg! : Expr → Nat → Expr | app f a _, 0 => a | app f _ _, i+1 => getRevArg! f i | _, _ => panic! "invalid index" @[inline] def getArg! (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr := getRevArg! e (n - i - 1) @[inline] def getArgD (e : Expr) (i : Nat) (v₀ : Expr) (n := e.getAppNumArgs) : Expr := getRevArgD e (n - i - 1) v₀ def isAppOf (e : Expr) (n : Name) : Bool := match e.getAppFn with | const c _ _ => c == n | _ => false def isAppOfArity : Expr → Name → Nat → Bool | const c _ _, n, 0 => c == n | app f _ _, n, a+1 => isAppOfArity f n a | _, _, _ => false def appFn! : Expr → Expr | app f _ _ => f | _ => panic! "application expected" def appArg! : Expr → Expr | app _ a _ => a | _ => panic! "application expected" def isNatLit : Expr → Bool | lit (Literal.natVal _) _ => true | _ => false def natLit? : Expr → Option Nat | lit (Literal.natVal v) _ => v | _ => none def isStringLit : Expr → Bool | lit (Literal.strVal _) _ => true | _ => false def isCharLit (e : Expr) : Bool := e.isAppOfArity `Char.ofNat 1 && e.appArg!.isNatLit def constName! : Expr → Name | const n _ _ => n | _ => panic! "constant expected" def constName? : Expr → Option Name | const n _ _ => some n | _ => none def constLevels! : Expr → List Level | const _ ls _ => ls | _ => panic! "constant expected" def bvarIdx! : Expr → Nat | bvar idx _ => idx | _ => panic! "bvar expected" def fvarId! : Expr → FVarId | fvar n _ => n | _ => panic! "fvar expected" def mvarId! : Expr → MVarId | mvar n _ => n | _ => panic! "mvar expected" def bindingName! : Expr → Name | forallE n _ _ _ => n | lam n _ _ _ => n | _ => panic! "binding expected" def bindingDomain! : Expr → Expr | forallE _ d _ _ => d | lam _ d _ _ => d | _ => panic! "binding expected" def bindingBody! : Expr → Expr | forallE _ _ b _ => b | lam _ _ b _ => b | _ => panic! "binding expected" def bindingInfo! : Expr → BinderInfo | forallE _ _ _ c => c.binderInfo | lam _ _ _ c => c.binderInfo | _ => panic! "binding expected" def letName! : Expr → Name | letE n _ _ _ _ => n | _ => panic! "let expression expected" def consumeMData : Expr → Expr | mdata _ e _ => consumeMData e | e => e def hasLooseBVars (e : Expr) : Bool := e.looseBVarRange > 0 @[extern "lean_expr_has_loose_bvar"] constant hasLooseBVar (e : @& Expr) (bvarIdx : @& Nat) : Bool := arbitrary _ /-- Return true if `e` contains the loose bound variable `bvarIdx` in an explicit parameter, or in the range if `tryRange == true`. -/ def hasLooseBVarInExplicitDomain : Expr → Nat → Bool → Bool | Expr.forallE _ d b c, bvarIdx, tryRange => (c.binderInfo.isExplicit && hasLooseBVar d bvarIdx) || hasLooseBVarInExplicitDomain b (bvarIdx+1) tryRange | e, bvarIdx, tryRange => tryRange && hasLooseBVar e bvarIdx /-- Lower the loose bound variables `>= s` in `e` by `d`. That is, a loose bound variable `bvar i`. `i >= s` is mapped into `bvar (i-d)`. Remark: if `s < d`, then result is `e` -/ @[extern "lean_expr_lower_loose_bvars"] constant lowerLooseBVars (e : @& Expr) (s d : @& Nat) : Expr := arbitrary _ /-- Lift loose bound variables `>= s` in `e` by `d`. -/ @[extern "lean_expr_lift_loose_bvars"] constant liftLooseBVars (e : @& Expr) (s d : @& Nat) : Expr := arbitrary _ /-- `inferImplicit e numParams considerRange` updates the first `numParams` parameter binder annotations of the `e` forall type. It marks any parameter with an explicit binder annotation if there is another explicit arguments that depends on it or the resulting type if `considerRange == true`. Remark: we use this function to infer the bind annotations of inductive datatype constructors, and structure projections. When the `{}` annotation is used in these commands, we set `considerRange == false`. -/ def inferImplicit : Expr → Nat → Bool → Expr | Expr.forallE n d b c, i+1, considerRange => let b := inferImplicit b i considerRange; let newInfo := if c.binderInfo.isExplicit && hasLooseBVarInExplicitDomain b 0 considerRange then BinderInfo.implicit else c.binderInfo; mkForall n newInfo d b | e, 0, _ => e | e, _, _ => e /-- Instantiate the loose bound variables in `e` using `subst`. That is, a loose `Expr.bvar i` is replaced with `subst[i]`. -/ @[extern "lean_expr_instantiate"] constant instantiate (e : @& Expr) (subst : @& Array Expr) : Expr := arbitrary _ @[extern "lean_expr_instantiate1"] constant instantiate1 (e : @& Expr) (subst : @& Expr) : Expr := arbitrary _ /-- Similar to instantiate, but `Expr.bvar i` is replaced with `subst[subst.size - i - 1]` -/ @[extern "lean_expr_instantiate_rev"] constant instantiateRev (e : @& Expr) (subst : @& Array Expr) : Expr := arbitrary _ /-- Similar to `instantiate`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`. Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/ @[extern "lean_expr_instantiate_range"] constant instantiateRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr := arbitrary _ /-- Similar to `instantiateRev`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`. Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/ @[extern "lean_expr_instantiate_rev_range"] constant instantiateRevRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr := arbitrary _ /-- Replace free variables `xs` with loose bound variables. -/ @[extern "lean_expr_abstract"] constant abstract (e : @& Expr) (xs : @& Array Expr) : Expr := arbitrary _ /-- Similar to `abstract`, but consider only the first `min n xs.size` entries in `xs`. -/ @[extern "lean_expr_abstract_range"] constant abstractRange (e : @& Expr) (n : @& Nat) (xs : @& Array Expr) : Expr := arbitrary _ /-- Replace occurrences of the free variable `fvar` in `e` with `v` -/ def replaceFVar (e : Expr) (fvar : Expr) (v : Expr) : Expr := (e.abstract #[fvar]).instantiate1 v /-- Replace occurrences of the free variable `fvarId` in `e` with `v` -/ def replaceFVarId (e : Expr) (fvarId : FVarId) (v : Expr) : Expr := replaceFVar e (mkFVar fvarId) v /-- Replace occurrences of the free variables `fvars` in `e` with `vs` -/ def replaceFVars (e : Expr) (fvars : Array Expr) (vs : Array Expr) : Expr := (e.abstract fvars).instantiateRev vs instance : HasToString Expr := ⟨Expr.dbgToString⟩ -- TODO: should not use dbgToString, but constructors. instance : HasRepr Expr := ⟨Expr.dbgToString⟩ def isAtomic : Expr → Bool | Expr.const _ _ _ => true | Expr.sort _ _ => true | Expr.bvar _ _ => true | Expr.lit _ _ => true | Expr.mvar _ _ => true | Expr.fvar _ _ => true | _ => false end Expr def mkAppB (f a b : Expr) := mkApp (mkApp f a) b def mkApp2 (f a b : Expr) := mkAppB f a b def mkApp3 (f a b c : Expr) := mkApp (mkAppB f a b) c def mkApp4 (f a b c d : Expr) := mkAppB (mkAppB f a b) c d def mkApp5 (f a b c d e : Expr) := mkApp (mkApp4 f a b c d) e def mkApp6 (f a b c d e₁ e₂ : Expr) := mkAppB (mkApp4 f a b c d) e₁ e₂ def mkApp7 (f a b c d e₁ e₂ e₃ : Expr) := mkApp3 (mkApp4 f a b c d) e₁ e₂ e₃ def mkApp8 (f a b c d e₁ e₂ e₃ e₄ : Expr) := mkApp4 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ def mkApp9 (f a b c d e₁ e₂ e₃ e₄ e₅ : Expr) := mkApp5 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ def mkApp10 (f a b c d e₁ e₂ e₃ e₄ e₅ e₆ : Expr) := mkApp6 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ e₆ def mkDecIsTrue (pred proof : Expr) := mkAppB (mkConst `Decidable.isTrue) pred proof def mkDecIsFalse (pred proof : Expr) := mkAppB (mkConst `Decidable.isFalse) pred proof open Std (HashMap HashSet PHashMap PHashSet) abbrev ExprMap (α : Type) := HashMap Expr α abbrev PersistentExprMap (α : Type) := PHashMap Expr α abbrev ExprSet := HashSet Expr abbrev PersistentExprSet := PHashSet Expr abbrev PExprSet := PersistentExprSet /- Auxiliary type for forcing `==` to be structural equality for `Expr` -/ structure ExprStructEq := (val : Expr) instance exprToExprStructEqOld : HasCoe Expr ExprStructEq := ⟨ExprStructEq.mk⟩ instance exprToExprStructEq : Coe Expr ExprStructEq := ⟨ExprStructEq.mk⟩ namespace ExprStructEq protected def beq : ExprStructEq → ExprStructEq → Bool | ⟨e₁⟩, ⟨e₂⟩ => Expr.equal e₁ e₂ protected def hash : ExprStructEq → USize | ⟨e⟩ => e.hash instance : Inhabited ExprStructEq := ⟨{ val := arbitrary _ }⟩ instance : HasBeq ExprStructEq := ⟨ExprStructEq.beq⟩ instance : Hashable ExprStructEq := ⟨ExprStructEq.hash⟩ instance : HasToString ExprStructEq := ⟨fun e => toString e.val⟩ instance : HasRepr ExprStructEq := ⟨fun e => repr e.val⟩ end ExprStructEq abbrev ExprStructMap (α : Type) := HashMap ExprStructEq α abbrev PersistentExprStructMap (α : Type) := PHashMap ExprStructEq α namespace Expr private partial def mkAppRevRangeAux (revArgs : Array Expr) (start : Nat) : Expr → Nat → Expr | b, i => if i == start then b else let i := i - 1; mkAppRevRangeAux (mkApp b (revArgs.get! i)) i /-- `mkAppRevRange f b e args == mkAppRev f (revArgs.extract b e)` -/ def mkAppRevRange (f : Expr) (beginIdx endIdx : Nat) (revArgs : Array Expr) : Expr := mkAppRevRangeAux revArgs beginIdx f endIdx private def betaRevAux (revArgs : Array Expr) (sz : Nat) : Expr → Nat → Expr | Expr.lam _ _ b _, i => if i + 1 < sz then betaRevAux b (i+1) else let n := sz - (i + 1); mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs | Expr.mdata _ b _, i => betaRevAux b i | b, i => let n := sz - i; mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs /-- If `f` is a lambda expression, than "beta-reduce" it using `revArgs`. This function is often used with `getAppRev` or `withAppRev`. Examples: - `betaRev (fun x y => t x y) #[]` ==> `fun x y => t x y` - `betaRev (fun x y => t x y) #[a]` ==> `fun y => t a y` - `betaRev (fun x y => t x y) #[a, b]` ==> t b a` - `betaRev (fun x y => t x y) #[a, b, c, d]` ==> t d c b a` Suppose `t` is `(fun x y => t x y) a b c d`, then `args := t.getAppRev` is `#[d, c, b, a]`, and `betaRev (fun x y => t x y) #[d, c, b, a]` is `t a b c d`. -/ def betaRev (f : Expr) (revArgs : Array Expr) : Expr := if revArgs.size == 0 then f else betaRevAux revArgs revArgs.size f 0 def isHeadBetaTargetFn : Expr → Bool | Expr.lam _ _ _ _ => true | Expr.mdata _ b _ => isHeadBetaTargetFn b | _ => false def headBeta (e : Expr) : Expr := let f := e.getAppFn; if f.isHeadBetaTargetFn then betaRev f e.getAppRevArgs else e def isHeadBetaTarget (e : Expr) : Bool := e.getAppFn.isHeadBetaTargetFn private def etaExpandedBody : Expr → Nat → Nat → Option Expr | app f (bvar j _) _, n+1, i => if j == i then etaExpandedBody f n (i+1) else none | _, n+1, _ => none | f, 0, _ => if f.hasLooseBVars then none else some f private def etaExpandedAux : Expr → Nat → Option Expr | lam _ _ b _, n => etaExpandedAux b (n+1) | e, n => etaExpandedBody e n 0 /-- If `e` is of the form `(fun x₁ ... xₙ => f x₁ ... xₙ)` and `f` does not contain `x₁`, ..., `xₙ`, then return `some f`. Otherwise, return `none`. It assumes `e` does not have loose bound variables. Remark: `ₙ` may be 0 -/ def etaExpanded? (e : Expr) : Option Expr := etaExpandedAux e 0 /-- Similar to `etaExpanded?`, but only succeeds if `ₙ ≥ 1`. -/ def etaExpandedStrict? : Expr → Option Expr | lam _ _ b _ => etaExpandedAux b 1 | _ => none def getOptParamDefault? (e : Expr) : Option Expr := if e.isAppOfArity `optParam 2 then some e.appArg! else none def getAutoParamTactic? (e : Expr) : Option Expr := if e.isAppOfArity `autoParam 2 then some e.appArg! else none def isOptParam (e : Expr) : Bool := e.isAppOfArity `optParam 2 def isAutoParam (e : Expr) : Bool := e.isAppOfArity `autoParam 2 @[specialize] private partial def hasAnyFVarAux (p : FVarId → Bool) : Expr → Bool | e => if !e.hasFVar then false else match e with | Expr.forallE _ d b _ => hasAnyFVarAux d || hasAnyFVarAux b | Expr.lam _ d b _ => hasAnyFVarAux d || hasAnyFVarAux b | Expr.mdata _ e _ => hasAnyFVarAux e | Expr.letE _ t v b _ => hasAnyFVarAux t || hasAnyFVarAux v || hasAnyFVarAux b | Expr.app f a _ => hasAnyFVarAux f || hasAnyFVarAux a | Expr.proj _ _ e _ => hasAnyFVarAux e | Expr.localE _ _ _ _ => unreachable! | e@(Expr.fvar fvarId _) => p fvarId | e => false /-- Return true iff `e` contains a free variable which statisfies `p`. -/ @[inline] def hasAnyFVar (e : Expr) (p : FVarId → Bool) : Bool := hasAnyFVarAux p e /- The update functions here are defined using C code. They will try to avoid allocating new values using pointer equality. The hypotheses `(h : e.is... = true)` are used to ensure Lean will not crash at runtime. The `update*!` functions are inlined and provide a convenient way of using the update proofs without providing proofs. Note that if they are used under a match-expression, the compiler will eliminate the double-match. -/ @[extern "lean_expr_update_app"] def updateApp (e : Expr) (newFn : Expr) (newArg : Expr) (h : e.isApp = true) : Expr := mkApp newFn newArg @[inline] def updateApp! (e : Expr) (newFn : Expr) (newArg : Expr) : Expr := match e with | app fn arg c => updateApp (app fn arg c) newFn newArg rfl | _ => panic! "application expected" @[extern "lean_expr_update_const"] def updateConst (e : Expr) (newLevels : List Level) (h : e.isConst = true) : Expr := mkConst e.constName! newLevels @[inline] def updateConst! (e : Expr) (newLevels : List Level) : Expr := match e with | const n ls c => updateConst (const n ls c) newLevels rfl | _ => panic! "constant expected" @[extern "lean_expr_update_sort"] def updateSort (e : Expr) (newLevel : Level) (h : e.isSort = true) : Expr := mkSort newLevel @[inline] def updateSort! (e : Expr) (newLevel : Level) : Expr := match e with | sort l c => updateSort (sort l c) newLevel rfl | _ => panic! "level expected" @[extern "lean_expr_update_proj"] def updateProj (e : Expr) (newExpr : Expr) (h : e.isProj = true) : Expr := match e with | proj s i _ _ => mkProj s i newExpr | _ => e -- unreachable because of `h` @[extern "lean_expr_update_mdata"] def updateMData (e : Expr) (newExpr : Expr) (h : e.isMData = true) : Expr := match e with | mdata d _ _ => mkMData d newExpr | _ => e -- unreachable because of `h` @[inline] def updateMData! (e : Expr) (newExpr : Expr) : Expr := match e with | mdata d e c => updateMData (mdata d e c) newExpr rfl | _ => panic! "mdata expected" @[inline] def updateProj! (e : Expr) (newExpr : Expr) : Expr := match e with | proj s i e c => updateProj (proj s i e c) newExpr rfl | _ => panic! "proj expected" @[extern "lean_expr_update_forall"] def updateForall (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isForall = true) : Expr := mkForall e.bindingName! newBinfo newDomain newBody @[inline] def updateForall! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr := match e with | forallE n d b c => updateForall (forallE n d b c) newBinfo newDomain newBody rfl | _ => panic! "forall expected" @[inline] def updateForallE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr := match e with | forallE n d b c => updateForall (forallE n d b c) c.binderInfo newDomain newBody rfl | _ => panic! "forall expected" @[extern "lean_expr_update_lambda"] def updateLambda (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isLambda = true) : Expr := mkLambda e.bindingName! newBinfo newDomain newBody @[inline] def updateLambda! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr := match e with | lam n d b c => updateLambda (lam n d b c) newBinfo newDomain newBody rfl | _ => panic! "lambda expected" @[inline] def updateLambdaE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr := match e with | lam n d b c => updateLambda (lam n d b c) c.binderInfo newDomain newBody rfl | _ => panic! "lambda expected" @[extern "lean_expr_update_let"] def updateLet (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) (h : e.isLet = true) : Expr := mkLet e.letName! newType newVal newBody @[inline] def updateLet! (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr := match e with | letE n t v b c => updateLet (letE n t v b c) newType newVal newBody rfl | _ => panic! "let expression expected" def updateFn : Expr → Expr → Expr | e@(app f a _), g => e.updateApp (updateFn f g) a rfl | _, g => g /- Instantiate level parameters -/ namespace InstantiateLevelParams @[inline] def visit (f : Expr → Expr) (e : Expr) : Expr := if e.hasLevelParam then f e else e @[specialize] partial def instantiate (s : Name → Option Level) : Expr → Expr | e@(lam n d b _) => e.updateLambdaE! (visit instantiate d) (visit instantiate b) | e@(forallE n d b _) => e.updateForallE! (visit instantiate d) (visit instantiate b) | e@(letE n t v b _) => e.updateLet! (visit instantiate t) (visit instantiate v) (visit instantiate b) | e@(app f a _) => e.updateApp (visit instantiate f) (visit instantiate a) rfl | e@(proj _ _ s _) => e.updateProj (visit instantiate s) rfl | e@(mdata _ b _) => e.updateMData (visit instantiate b) rfl | e@(const _ us _) => e.updateConst (us.map (fun u => u.instantiateParams s)) rfl | e@(sort u _) => e.updateSort (u.instantiateParams s) rfl | localE _ _ _ _ => unreachable! | e => e end InstantiateLevelParams @[inline] def instantiateLevelParamsCore (s : Name → Option Level) (e : Expr) : Expr := if e.hasLevelParam then InstantiateLevelParams.instantiate s e else e private def getParamSubst : List Name → List Level → Name → Option Level | p::ps, u::us, p' => if p == p' then some u else getParamSubst ps us p' | _, _, _ => none def instantiateLevelParams (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr := instantiateLevelParamsCore (getParamSubst paramNames lvls) e private partial def getParamSubstArray (ps : Array Name) (us : Array Level) (p' : Name) : Nat → Option Level | i => if h : i < ps.size then let p := ps.get ⟨i, h⟩; if h : i < us.size then let u := us.get ⟨i, h⟩; if p == p' then some u else getParamSubstArray (i+1) else none else none def instantiateLevelParamsArray (e : Expr) (paramNames : Array Name) (lvls : Array Level) : Expr := instantiateLevelParamsCore (fun p => getParamSubstArray paramNames lvls p 0) e end Expr def mkAnnotation (kind : Name) (e : Expr) : Expr := mkMData (KVMap.empty.insert kind (DataValue.ofBool true)) e def annotation? (kind : Name) (e : Expr) : Option Expr := match e with | Expr.mdata d b _ => if d.size == 1 && d.getBool kind false then some b else none | _ => none def mkFreshFVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m FVarId := mkFreshId def mkFreshMVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m FVarId := mkFreshId end Lean
0b7efe31babb437c4753cc7d82c29c0d129c2543
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Elab/Tactic/Induction.lean
e8e431d50fe18d34d0b9d75be8571c07cd913d76
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,026
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, Sebastian Ullrich -/ import Lean.Util.CollectFVars import Lean.Parser.Term import Lean.Meta.RecursorInfo import Lean.Meta.CollectMVars import Lean.Meta.Tactic.ElimInfo import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Cases import Lean.Meta.GeneralizeVars import Lean.Elab.App import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Generalize namespace Lean.Elab.Tactic open Meta /- Given an `inductionAlt` of the form ``` nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> termParser ``` -/ private def getAltName (alt : Syntax) : Name := -- alt[1] is of the form (("@"? ident) <|> "_") if alt[1].hasArgs then alt[1][1].getId.eraseMacroScopes else `_ private def altHasExplicitModifier (alt : Syntax) : Bool := alt[1].hasArgs && !alt[1][0].isNone private def getAltVarNames (alt : Syntax) : Array Name := alt[2].getArgs.map getNameOfIdent' private def getAltRHS (alt : Syntax) : Syntax := alt[4] private def getAltDArrow (alt : Syntax) : Syntax := alt[3] -- Return true if `stx` is a term occurring in the RHS of the induction/cases tactic def isHoleRHS (rhs : Syntax) : Bool := rhs.isOfKind ``Parser.Term.syntheticHole || rhs.isOfKind ``Parser.Term.hole def evalAlt (mvarId : MVarId) (alt : Syntax) (remainingGoals : Array MVarId) : TacticM (Array MVarId) := let rhs := getAltRHS alt withCaseRef (getAltDArrow alt) rhs do if isHoleRHS rhs then let gs' ← withMVarContext mvarId $ withRef rhs do let mvarDecl ← getMVarDecl mvarId let val ← elabTermEnsuringType rhs mvarDecl.type assignExprMVar mvarId val let gs' ← getMVarsNoDelayed val tagUntaggedGoals mvarDecl.userName `induction gs'.toList pure gs' return remainingGoals ++ gs' else setGoals [mvarId] closeUsingOrAdmit (withTacticInfoContext alt (evalTactic rhs)) return remainingGoals /- Helper method for creating an user-defined eliminator/recursor application. -/ namespace ElimApp structure Context where elimInfo : ElimInfo targets : Array Expr -- targets provided by the user structure State where argPos : Nat := 0 -- current argument position targetPos : Nat := 0 -- current target at targetsStx f : Expr fType : Expr alts : Array (Name × MVarId) := #[] insts : Array MVarId := #[] abbrev M := ReaderT Context $ StateRefT State TermElabM private def addNewArg (arg : Expr) : M Unit := modify fun s => { s with argPos := s.argPos+1, f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } /- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! private def getFType : M Expr := do let fType ← whnfForall (← get).fType modify fun s => { s with fType := fType } pure fType structure Result where elimApp : Expr alts : Array (Name × MVarId) := #[] others : Array MVarId := #[] /-- Construct the an eliminator/recursor application. `targets` contains the explicit and implicit targets for the eliminator. For example, the indices of builtin recursors are considered implicit targets. Remark: the method `addImplicitTargets` may be used to compute the sequence of implicit and explicit targets from the explicit ones. -/ partial def mkElimApp (elimName : Name) (elimInfo : ElimInfo) (targets : Array Expr) (tag : Name) : TermElabM Result := do let rec loop : M Unit := do match (← getFType) with | Expr.forallE binderName _ _ c => let ctx ← read let argPos := (← get).argPos if ctx.elimInfo.motivePos == argPos then let motive ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.syntheticOpaque addNewArg motive else if ctx.elimInfo.targetsPos.contains argPos then let s ← get let ctx ← read unless s.targetPos < ctx.targets.size do throwError "insufficient number of targets for '{elimName}'" let target := ctx.targets[s.targetPos] let expectedType ← getArgExpectedType let target ← Term.ensureHasType expectedType target modify fun s => { s with targetPos := s.targetPos + 1 } addNewArg target else match c.binderInfo with | BinderInfo.implicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | BinderInfo.strictImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) addNewArg arg | BinderInfo.instImplicit => let arg ← mkFreshExprMVar (← getArgExpectedType) (kind := MetavarKind.synthetic) (userName := appendTag tag binderName) modify fun s => { s with insts := s.insts.push arg.mvarId! } addNewArg arg | _ => let arg ← mkFreshExprSyntheticOpaqueMVar (← getArgExpectedType) (tag := appendTag tag binderName) let x ← getBindingName modify fun s => { s with alts := s.alts.push (x, arg.mvarId!) } addNewArg arg loop | _ => pure () let f ← Term.mkConst elimName let fType ← inferType f let (_, s) ← loop.run { elimInfo := elimInfo, targets := targets } |>.run { f := f, fType := fType } let mut others := #[] for mvarId in s.insts do try unless (← Term.synthesizeInstMVarCore mvarId) do setMVarKind mvarId MetavarKind.syntheticOpaque others := others.push mvarId catch _ => setMVarKind mvarId MetavarKind.syntheticOpaque others := others.push mvarId return { elimApp := (← instantiateMVars s.f), alts := s.alts, others := others } /- Given a goal `... targets ... |- C[targets]` associated with `mvarId`, assign `motiveArg := fun targets => C[targets]` -/ def setMotiveArg (mvarId : MVarId) (motiveArg : MVarId) (targets : Array FVarId) : MetaM Unit := do let type ← inferType (mkMVar mvarId) let motive ← mkLambdaFVars (targets.map mkFVar) type let motiverInferredType ← inferType motive let motiveType ← inferType (mkMVar motiveArg) unless (← isDefEqGuarded motiverInferredType motiveType) do throwError "type mismatch when assigning motive{indentExpr motive}\n{← mkHasTypeButIsExpectedMsg motiverInferredType motiveType}" assignExprMVar motiveArg motive private def getAltNumFields (elimInfo : ElimInfo) (altName : Name) : TermElabM Nat := do for altInfo in elimInfo.altsInfo do if altInfo.name == altName then return altInfo.numFields throwError "unknown alternative name '{altName}'" private def checkAltNames (alts : Array (Name × MVarId)) (altsSyntax : Array Syntax) : TacticM Unit := for altStx in altsSyntax do let altName := getAltName altStx if altName != `_ then unless alts.any fun (n, _) => n == altName do throwErrorAt altStx "invalid alternative name '{altName}'" def evalAlts (elimInfo : ElimInfo) (alts : Array (Name × MVarId)) (optPreTac : Syntax) (altsSyntax : Array Syntax) (initialInfo : Info) (numEqs : Nat := 0) (numGeneralized : Nat := 0) (toClear : Array FVarId := #[]) : TacticM Unit := do checkAltNames alts altsSyntax let hasAlts := altsSyntax.size > 0 if hasAlts then -- default to initial state outside of alts withInfoContext go initialInfo else go where go := do let hasAlts := altsSyntax.size > 0 let mut usedWildcard := false let mut subgoals := #[] -- when alternatives are not provided, we accumulate subgoals here let mut altsSyntax := altsSyntax for (altName, altMVarId) in alts do let numFields ← getAltNumFields elimInfo altName let mut isWildcard := false let altStx? ← match altsSyntax.findIdx? (fun alt => getAltName alt == altName) with | some idx => let altStx := altsSyntax[idx] altsSyntax := altsSyntax.eraseIdx idx pure (some altStx) | none => match altsSyntax.findIdx? (fun alt => getAltName alt == `_) with | some idx => isWildcard := true pure (some altsSyntax[idx]) | none => pure none match altStx? with | none => let mut (_, altMVarId) ← introN altMVarId numFields match (← Cases.unifyEqs numEqs altMVarId {}) with | none => pure () -- alternative is not reachable | some (altMVarId', _) => (_, altMVarId) ← introNP altMVarId' numGeneralized for fvarId in toClear do altMVarId ← tryClear altMVarId fvarId let altMVarIds ← applyPreTac altMVarId if !hasAlts then -- User did not provide alternatives using `|` subgoals := subgoals ++ altMVarIds.toArray else if altMVarIds.isEmpty then pure () else logError m!"alternative '{altName}' has not been provided" altMVarIds.forM fun mvarId => admitGoal mvarId | some altStx => (subgoals, usedWildcard) ← withRef altStx do let unusedAlt := if isWildcard then pure (#[], usedWildcard) else throwError "alternative '{altName}' is not needed" let altVarNames := getAltVarNames altStx if altVarNames.size > numFields then logError m!"too many variable names provided at alternative '{altName}', #{altVarNames.size} provided, but #{numFields} expected" let mut (_, altMVarId) ← introN altMVarId numFields altVarNames.toList (useNamesForExplicitOnly := !altHasExplicitModifier altStx) match (← Cases.unifyEqs numEqs altMVarId {}) with | none => unusedAlt | some (altMVarId', _) => (_, altMVarId) ← introNP altMVarId' numGeneralized for fvarId in toClear do altMVarId ← tryClear altMVarId fvarId let altMVarIds ← applyPreTac altMVarId if altMVarIds.isEmpty then unusedAlt else let mut subgoals := subgoals for altMVarId' in altMVarIds do subgoals ← evalAlt altMVarId' altStx subgoals pure (subgoals, usedWildcard || isWildcard) if usedWildcard then altsSyntax := altsSyntax.filter fun alt => getAltName alt != `_ unless altsSyntax.isEmpty do logErrorAt altsSyntax[0] "unused alternative" setGoals subgoals.toList applyPreTac (mvarId : MVarId) : TacticM (List MVarId) := if optPreTac.isNone then return [mvarId] else evalTacticAt optPreTac[0] mvarId end ElimApp /- Recall that ``` generalizingVars := optional (" generalizing " >> many1 ident) «induction» := leading_parser nonReservedSymbol "induction " >> majorPremise >> usingRec >> generalizingVars >> optional inductionAlts ``` `stx` is syntax for `induction`. -/ private def getUserGeneralizingFVarIds (stx : Syntax) : TacticM (Array FVarId) := withRef stx do let generalizingStx := stx[3] if generalizingStx.isNone then pure #[] else trace[Elab.induction] "{generalizingStx}" let vars := generalizingStx[1].getArgs getFVarIds vars -- process `generalizingVars` subterm of induction Syntax `stx`. private def generalizeVars (mvarId : MVarId) (stx : Syntax) (targets : Array Expr) : TacticM (Nat × MVarId) := withMVarContext mvarId do let userFVarIds ← getUserGeneralizingFVarIds stx let forbidden ← mkGeneralizationForbiddenSet targets let mut s ← getFVarSetToGeneralize targets forbidden for userFVarId in userFVarIds do if forbidden.contains userFVarId then throwError "variable cannot be generalized because target depends on it{indentExpr (mkFVar userFVarId)}" if s.contains userFVarId then throwError "unnecessary 'generalizing' argument, variable '{mkFVar userFVarId}' is generalized automatically" s := s.insert userFVarId let fvarIds ← sortFVars s let (fvarIds, mvarId') ← Meta.revert mvarId fvarIds return (fvarIds.size, mvarId') -- syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+) private def getAltsOfInductionAlts (inductionAlts : Syntax) : Array Syntax := inductionAlts[2].getArgs private def getAltsOfOptInductionAlts (optInductionAlts : Syntax) : Array Syntax := if optInductionAlts.isNone then #[] else getAltsOfInductionAlts optInductionAlts[0] private def getOptPreTacOfOptInductionAlts (optInductionAlts : Syntax) : Syntax := if optInductionAlts.isNone then mkNullNode else optInductionAlts[0][1] /- We may have at most one `| _ => ...` (wildcard alternative), and it must not set variable names. The idea is to make sure users do not write unstructured tactics. -/ private def checkAltsOfOptInductionAlts (optInductionAlts : Syntax) : TacticM Unit := unless optInductionAlts.isNone do let mut found := false for alt in getAltsOfInductionAlts optInductionAlts[0] do let n := getAltName alt if n == `_ then unless (getAltVarNames alt).isEmpty do throwErrorAt alt "wildcard alternative must not specify variable names" if found then throwErrorAt alt "more than one wildcard alternative '| _ => ...' used" found := true def getInductiveValFromMajor (major : Expr) : TacticM InductiveVal := liftMetaMAtMain fun mvarId => do let majorType ← inferType major let majorType ← whnf majorType matchConstInduct majorType.getAppFn (fun _ => Meta.throwTacticEx `induction mvarId m!"major premise type is not an inductive type {indentExpr majorType}") (fun val _ => pure val) -- `optElimId` is of the form `("using" ident)?` private def getElimNameInfo (optElimId : Syntax) (targets : Array Expr) (induction : Bool): TacticM (Name × ElimInfo) := do if optElimId.isNone then unless targets.size == 1 do throwError "eliminator must be provided when multiple targets are used (use 'using <eliminator-name>')" let indVal ← getInductiveValFromMajor targets[0] let elimName := if induction then mkRecName indVal.name else mkCasesOnName indVal.name pure (elimName, ← getElimInfo elimName) else let elimId := optElimId[1] let elimName ← withRef elimId do resolveGlobalConstNoOverloadWithInfo elimId pure (elimName, ← withRef elimId do getElimInfo elimName) private def generalizeTargets (exprs : Array Expr) : TacticM (Array Expr) := do if exprs.all (·.isFVar) then return exprs else liftMetaTacticAux fun mvarId => do let (fvarIds, mvarId) ← generalize mvarId (exprs.map fun expr => { expr }) return (fvarIds.map mkFVar, [mvarId]) @[builtinTactic Lean.Parser.Tactic.induction] def evalInduction : Tactic := fun stx => focus do let targets ← withMainContext <| stx[1].getSepArgs.mapM (elabTerm . none) let targets ← generalizeTargets targets let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := true) let mvarId ← getMainGoal -- save initial info before main goal is reassigned let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef) let tag ← getMVarTag mvarId withMVarContext mvarId do let targets ← addImplicitTargets elimInfo targets checkTargets targets let targetFVarIds := targets.map (·.fvarId!) let (n, mvarId) ← generalizeVars mvarId stx targets withMVarContext mvarId do let result ← withRef stx[1] do -- use target position as reference ElimApp.mkElimApp elimName elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let motiveType ← inferType elimArgs[elimInfo.motivePos] ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetFVarIds let optInductionAlts := stx[4] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts assignExprMVar mvarId result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numGeneralized := n) (toClear := targetFVarIds) appendGoals result.others.toList where checkTargets (targets : Array Expr) : MetaM Unit := do let mut foundFVars : FVarIdSet := {} for target in targets do unless target.isFVar do throwError "index in target's type is not a variable (consider using the `cases` tactic instead){indentExpr target}" if foundFVars.contains target.fvarId! then throwError "target (or one of its indices) occurs more than once{indentExpr target}" def elabCasesTargets (targets : Array Syntax) : TacticM (Array Expr) := withMainContext do let args ← targets.mapM fun target => do let hName? := if target[0].isNone then none else some target[0][0].getId let expr ← elabTerm target[1] none return { expr, hName? : GeneralizeArg } if args.all fun arg => arg.expr.isFVar && arg.hName?.isNone then return args.map (·.expr) else liftMetaTacticAux fun mvarId => do let (fvarIds, mvarId) ← generalize mvarId args return (fvarIds[:targets.size].toArray.map mkFVar, [mvarId]) builtin_initialize registerTraceClass `Elab.cases @[builtinTactic Lean.Parser.Tactic.cases] def evalCases : Tactic := fun stx => focus do -- leading_parser nonReservedSymbol "cases " >> sepBy1 (group majorPremise) ", " >> usingRec >> optInductionAlts let targets ← elabCasesTargets stx[1].getSepArgs let optInductionAlts := stx[3] let optPreTac := getOptPreTacOfOptInductionAlts optInductionAlts let alts := getAltsOfOptInductionAlts optInductionAlts let targetRef := stx[1] let (elimName, elimInfo) ← getElimNameInfo stx[2] targets (induction := false) let mvarId ← getMainGoal -- save initial info before main goal is reassigned let initInfo ← mkTacticInfo (← getMCtx) (← getUnsolvedGoals) (← getRef) let tag ← getMVarTag mvarId withMVarContext mvarId do let targets ← addImplicitTargets elimInfo targets let result ← withRef targetRef <| ElimApp.mkElimApp elimName elimInfo targets tag let elimArgs := result.elimApp.getAppArgs let targets ← elimInfo.targetsPos.mapM fun i => instantiateMVars elimArgs[i] let motiveType ← inferType elimArgs[elimInfo.motivePos] let mvarId ← generalizeTargetsEq mvarId motiveType targets let (targetsNew, mvarId) ← introN mvarId targets.size withMVarContext mvarId do ElimApp.setMotiveArg mvarId elimArgs[elimInfo.motivePos].mvarId! targetsNew assignExprMVar mvarId result.elimApp ElimApp.evalAlts elimInfo result.alts optPreTac alts initInfo (numEqs := targets.size) (toClear := targetsNew) end Lean.Elab.Tactic
29c37861ae9177860047fab73a2f12761867735e
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/data/nat/basic.lean
e4892e05a36919207b2215d242f9a4d7b0ec4420
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
62,855
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import algebra.ordered_ring import algebra.order_functions import init_.data.nat.lemmas /-! # Basic operations on the natural numbers This files has some basic lemmas about natural numbers, definition of the `choice` function, and extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers. * `decreasing_induction` : recursion growing downwards. * `strong_rec'` : recursion based on strong inequalities. -/ universes u v attribute [protected] nat.pow_zero nat.pow_succ instance : canonically_ordered_comm_semiring ℕ := { le_iff_exists_add := assume a b, ⟨assume h, let ⟨c, hc⟩ := nat.le.dest h in ⟨c, hc.symm⟩, assume ⟨c, hc⟩, hc.symm ▸ nat.le_add_right _ _⟩, zero_ne_one := ne_of_lt zero_lt_one, mul_eq_zero_iff := assume a b, iff.intro nat.eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}), bot := 0, bot_le := nat.zero_le, .. (infer_instance : ordered_add_comm_monoid ℕ), .. (infer_instance : linear_ordered_semiring ℕ), .. (infer_instance : comm_semiring ℕ) } namespace nat variables {m n k : ℕ} -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ_inj, congr_arg _⟩ theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ lemma zero_max {m : nat} : max 0 m = m := max_eq_right (zero_le _) theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := (lt_or_eq_of_le H).imp le_of_lt_succ id /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] theorem pos_iff_ne_zero : 0 < n ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem add_sub_eq_max (n m : ℕ) : n + (m - n) = max n m := by rw [add_comm, max_comm, sub_add_eq_max] theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := (nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $ by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by rw [add_comm, add_mul_mod_self_left, mul_mod_right]; exact dec_trivial) /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) /-- Recursion principle based on `<` applied to some natural number. -/ @[elab_as_eliminator] def strong_rec_on' {P : ℕ → Sort*} (n : ℕ) (h : ∀ n, (∀ m, m < n → P m) → P n) : P n := nat.strong_rec' h n theorem strong_rec_on_beta' {P : ℕ → Sort*} {h} {n : ℕ} : (strong_rec_on' n h : P n) = h n (λ m hmn, (strong_rec_on' m h : P m)) := by { simp only [strong_rec_on'], rw nat.strong_rec' } attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (decidable.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) /-- A version of `nat.div_lt_self` using successors, rather than additional hypotheses. -/ lemma div_lt_self' (n b : ℕ) : (n+1)/(b+2) < n+1 := nat.div_lt_self (nat.succ_pos n) (nat.succ_lt_succ (nat.succ_pos _)) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin revert x, refine nat.strong_rec' _ y, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { rw succ_mul, exact iff_of_false (not_succ_le_zero _) (not_le_of_lt $ lt_of_lt_of_le h (le_add_left _ _)) } }, { rw [div_eq_sub_div k0 h], cases x with x, { simp [zero_mul, zero_le] }, { rw [← add_one, nat.add_le_add_iff_le_right, succ_mul, IH _ (sub_lt_of_pos_le _ _ k0 h), add_le_to_le_sub _ h] } } end theorem div_mul_le_self' (m n : ℕ) : m / n * n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0, zero_le]) $ λ n0, (le_div_iff_mul_le' n0).1 (le_refl _) theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self' _ _) h lemma lt_of_div_lt_div {m n k : ℕ} (h : m / k < n / k) : m < n := by_contradiction $ λ h₁, absurd h (not_lt_of_ge (nat.div_le_div_right (not_lt.1 h₁))) protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_left_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_right_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc] else by conv {to_rhs, rw ← mod_add_div a (b * c)}; rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))] lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] /- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/ lemma triangle_succ (n : ℕ) : (n + 1) * ((n + 1) - 1) / 2 = n * (n - 1) / 2 + n := begin rw [← add_mul_div_left, mul_comm 2 n, ← mul_add, nat.add_sub_cancel, mul_comm], cases n; refl, apply zero_lt_succ end @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm /-- A natural number m divides the sum m + n if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number m divides the sum n + m if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_right_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_left_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := rfl | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1, add_assoc] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) /-- If `a` and `b` are equal mod `c`, `a - b` is zero mod `c`. -/ lemma sub_mod_eq_zero_of_mod_eq {a b c : ℕ} (h : a % c = b % c) : (a - b) % c = 0 := by rw [←nat.mod_add_div a c, ←nat.mod_add_div b c, ←h, ←nat.sub_sub, nat.add_sub_cancel_left, ←nat.mul_sub_left_distrib, nat.mul_mod_right] lemma dvd_sub_mod (k : ℕ) : n ∣ (k - (k % n)) := ⟨k / n, nat.sub_eq_of_eq_add (nat.mod_add_div k n).symm⟩ @[simp] theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℕ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] lemma mul_mod (a b n : ℕ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], by clear_aux_decl; finish⟩ lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_right_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm section facts -- Inject some simple facts into the typeclass system. -- This `fact` should not be confused with the factorial function `nat.fact`! instance succ_pos'' (n : ℕ) : _root_.fact (0 < n.succ) := n.succ_pos instance pos_of_one_lt (n : ℕ) [h : fact (1 < n)] : fact (0 < n) := lt_trans zero_lt_one h end facts instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /- partial subtraction -/ /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := begin dsimp, apply option.bind_eq_some.trans, simp [psub_eq_some, add_comm, add_left_comm, nat.succ_eq_add_one] end theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] /- pow -/ attribute [simp] nat.pow_zero nat.pow_one @[simp] lemma one_pow : ∀ n : ℕ, 1 ^ n = 1 | 0 := rfl | (k+1) := show 1^k * 1 = 1, by rw [mul_one, one_pow] theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, nat.pow_succ, mul_assoc] theorem pow_two (a : ℕ) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right theorem pow_dvd_pow_of_dvd {a b : ℕ} (h : a ∣ b) : ∀ n:ℕ, a^n ∣ b^n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul (pow_dvd_pow_of_dvd n) h theorem mul_pow (a b n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm] protected theorem pow_mul (a b n : ℕ) : n ^ (a * b) = (n ^ a) ^ b := by induction b; simp [*, nat.succ_eq_add_one, nat.pow_add, mul_add, mul_comm] theorem pow_pos {p : ℕ} (hp : 0 < p) : ∀ n : ℕ, 0 < p ^ n | 0 := by simp | (k+1) := mul_pos (pow_pos _) hp lemma pow_eq_mul_pow_sub (p : ℕ) {m n : ℕ} (h : m ≤ n) : p ^ m * p ^ (n - m) = p ^ n := by rw [←nat.pow_add, nat.add_sub_cancel' h] lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) := suffices p^n*1 < p^n*p, by simpa, nat.mul_lt_mul_of_pos_left h (nat.pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma lt_two_pow (n : ℕ) : n < 2^n := lt_pow_self dec_trivial n lemma one_le_pow (n m : ℕ) (h : 0 < m) : 1 ≤ m^n := one_pow n ▸ pow_le_pow_of_le_left h n lemma one_le_pow' (n m : ℕ) : 1 ≤ (m+1)^n := one_le_pow n (m+1) (succ_pos m) lemma one_le_two_pow (n : ℕ) : 1 ≤ 2^n := one_le_pow n 2 dec_trivial lemma one_lt_pow (n m : ℕ) (h₀ : 0 < n) (h₁ : 1 < m) : 1 < m^n := one_pow n ▸ pow_lt_pow_of_lt_left h₁ h₀ lemma one_lt_pow' (n m : ℕ) : 1 < (m+2)^(n+1) := one_lt_pow (n+1) (m+2) (succ_pos n) (nat.lt_of_sub_eq_succ rfl) lemma one_lt_two_pow (n : ℕ) (h₀ : 0 < n) : 1 < 2^n := one_lt_pow n 2 h₀ dec_trivial lemma one_lt_two_pow' (n : ℕ) : 1 < 2^(n+1) := one_lt_pow (n+1) 2 (succ_pos n) dec_trivial lemma pow_right_strict_mono {x : ℕ} (k : 2 ≤ x) : strict_mono (nat.pow x) := λ _ _, pow_lt_pow_of_lt_right k lemma pow_le_iff_le_right {x m n : ℕ} (k : 2 ≤ x) : x^m ≤ x^n ↔ m ≤ n := strict_mono.le_iff_le (pow_right_strict_mono k) lemma pow_lt_iff_lt_right {x m n : ℕ} (k : 2 ≤ x) : x^m < x^n ↔ m < n := strict_mono.lt_iff_lt (pow_right_strict_mono k) lemma pow_right_injective {x : ℕ} (k : 2 ≤ x) : function.injective (nat.pow x) := strict_mono.injective (pow_right_strict_mono k) lemma pow_dvd_pow_iff_pow_le_pow {k l : ℕ} : Π {x : ℕ} (w : 0 < x), x^k ∣ x^l ↔ x^k ≤ x^l | (x+1) w := begin split, { intro a, exact le_of_dvd (pow_pos (succ_pos x) l) a, }, { intro a, cases x with x, { simp only [one_pow], }, { have le := (pow_le_iff_le_right (le_add_left _ _)).mp a, use (x+2)^(l-k), rw [←nat.pow_add, add_comm k, nat.sub_add_cancel le], } } end /-- If `1 < x`, then `x^k` divides `x^l` if and only if `k` is at most `l`. -/ lemma pow_dvd_pow_iff_le_right {x k l : ℕ} (w : 1 < x) : x^k ∣ x^l ↔ k ≤ l := by rw [pow_dvd_pow_iff_pow_le_pow (lt_of_succ_lt w), pow_le_iff_le_right w] lemma pow_dvd_pow_iff_le_right' {b k l : ℕ} : (b+2)^k ∣ (b+2)^l ↔ k ≤ l := pow_dvd_pow_iff_le_right (nat.lt_of_sub_eq_succ rfl) lemma pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono (λ (x : ℕ), x^m) := λ _ _ h, pow_lt_pow_of_lt_left h k lemma pow_le_iff_le_left {m x y : ℕ} (k : 1 ≤ m) : x^m ≤ y^m ↔ x ≤ y := strict_mono.le_iff_le (pow_left_strict_mono k) lemma pow_lt_iff_lt_left {m x y : ℕ} (k : 1 ≤ m) : x^m < y^m ↔ x < y := strict_mono.lt_iff_lt (pow_left_strict_mono k) lemma pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective (λ (x : ℕ), x^m) := strict_mono.injective (pow_left_strict_mono k) lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have (succ p)^k * succ p ∣ 1 * succ p, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_right (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 < 1, by rwa [this] at hk, absurd this dec_trivial @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ /-- `fact n` is the factorial of `n`. -/ @[simp] def fact : nat → nat | 0 := 1 | (succ n) := succ n * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl theorem fact_pos : ∀ n, 0 < fact n | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : ∀ {m n}, 0 < m → m ≤ n → m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) lemma fact_mul_pow_le_fact : ∀ {m n : ℕ}, m.fact * m.succ ^ n ≤ (m + n).fact | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.fact_succ, mul_comm (nat.succ _), nat.pow_succ, ← mul_assoc]; exact mul_le_mul fact_mul_pow_le_fact (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_fact : monotone fact := λ n m, fact_le lemma fact_lt (h0 : 0 < n) : n.fact < m.fact ↔ n < m := begin split; intro h, { rw [← not_le], intro hmn, apply not_le_of_lt h (fact_le hmn) }, { have : ∀(n : ℕ), 0 < n → n.fact < n.succ.fact, { intros k hk, rw [fact_succ, succ_mul, lt_add_iff_pos_left], apply mul_pos hk (fact_pos k) }, induction h generalizing h0, { exact this _ h0, }, { refine lt_trans (h_ih h0) (this _ _), exact lt_trans h0 (lt_of_succ_le h_a) }} end lemma one_lt_fact : 1 < n.fact ↔ 1 < n := by { convert fact_lt _, refl, exact one_pos } lemma fact_eq_one : n.fact = 1 ↔ n ≤ 1 := begin split; intro h, { rw [← not_lt, ← one_lt_fact, h], apply lt_irrefl }, { cases h with h h, refl, cases h, refl } end lemma fact_inj (h0 : 1 < n.fact) : n.fact = m.fact ↔ n = m := begin split; intro h, { rcases lt_trichotomy n m with hnm|hnm|hnm, { exfalso, rw [← fact_lt, h] at hnm, exact lt_irrefl _ hnm, rw [one_lt_fact] at h0, exact lt_trans one_pos h0 }, { exact hnm }, { exfalso, rw [← fact_lt, h] at hnm, exact lt_irrefl _ hnm, rw [h, one_lt_fact] at h0, exact lt_trans one_pos h0 }}, { rw h } end /- choose -/ /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (k + 1) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose, add_comm] /-- `choose n 2` is the `n`-th triangle number. -/ lemma choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := begin induction n with n ih, simp, {rw triangle_succ n, simp [choose, ih], rw add_comm}, end lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_fact_mul_fact : ∀ {n k}, k ≤ n → choose n k * fact k * fact (n - k) = fact n | 0 _ hk := by simp [eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * fact (succ k) * fact (n - k) = succ k * fact n := by rw ← choose_mul_fact_mul_fact (le_of_succ_le_succ hk); simp [fact_succ, mul_comm, mul_left_comm], have h₁ : fact (n - k) = (n - k) * fact (n - succ k) := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), fact_succ], have h₂ : choose n (succ k) * fact (succ k) * ((n - k) * fact (n - succ k)) = (n - k) * fact n := by rw ← choose_mul_fact_mul_fact (le_of_lt_succ hk₁); simp [fact_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * fact n ≤ n * fact n := mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, ← add_one, add_mul, nat.mul_sub_right_distrib, fact_succ, ← nat.add_sub_assoc h₃, add_assoc, ← add_mul, nat.add_sub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, nat.sub_self] } end theorem choose_eq_fact_div_fact {n k : ℕ} (hk : k ≤ n) : choose n k = fact n / (fact k * fact (n - k)) := begin have : fact n = choose n k * (fact k * fact (n - k)) := by rw ← mul_assoc; exact (choose_mul_fact_mul_fact hk).symm, exact (nat.div_eq_of_eq_mul_left (mul_pos (fact_pos _) (fact_pos _)) this).symm end theorem fact_mul_fact_dvd_fact {n k : ℕ} (hk : k ≤ n) : fact k * fact (n - k) ∣ fact n := by rw [←choose_mul_fact_mul_fact hk, mul_assoc]; exact dvd_mul_left _ _ @[simp] lemma choose_symm {n k : ℕ} (hk : k ≤ n) : choose n (n-k) = choose n k := by rw [choose_eq_fact_div_fact hk, choose_eq_fact_div_fact (sub_le _ _), nat.sub_sub_self hk, mul_comm] lemma choose_symm_of_eq_add {n a b : ℕ} (h : n = a + b) : nat.choose n a = nat.choose n b := by { convert nat.choose_symm (nat.le_add_left _ _), rw nat.add_sub_cancel} lemma choose_symm_add {a b : ℕ} : choose (a+b) a = choose (a+b) b := choose_symm_of_eq_add rfl lemma choose_symm_half (m : ℕ) : choose (2 * m + 1) (m + 1) = choose (2 * m + 1) m := by { apply choose_symm_of_eq_add, rw [add_comm m 1, add_assoc 1 m m, add_comm (2 * m) 1, two_mul m] } lemma choose_succ_right_eq (n k : ℕ) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := begin have e : (n+1) * choose n k = choose n k * (k+1) + choose n (k+1) * (k+1), rw [← right_distrib, ← choose_succ_succ, succ_mul_choose_eq], rw [← nat.sub_eq_of_eq_add e, mul_comm, ← nat.mul_sub_left_distrib, nat.add_sub_add_right] end @[simp] lemma choose_succ_self_right : ∀ (n:ℕ), (n+1).choose n = n+1 | 0 := rfl | (n+1) := by rw [choose_succ_succ, choose_succ_self_right, choose_self] lemma choose_mul_succ_eq (n k : ℕ) : (n.choose k) * (n + 1) = ((n+1).choose k) * (n + 1 - k) := begin induction k with k ih, { simp }, by_cases hk : n < k + 1, { rw [choose_eq_zero_of_lt hk, sub_eq_zero_of_le hk, zero_mul, mul_zero] }, push_neg at hk, replace hk : k + 1 ≤ n + 1 := _root_.le_add_right hk, rw [choose_succ_succ], rw [add_mul, succ_sub_succ], rw [← choose_succ_right_eq], rw [← succ_sub_succ, nat.mul_sub_left_distrib], symmetry, apply nat.add_sub_cancel', exact mul_le_mul_left _ hk, end theorem units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ theorem add_units_eq_zero (u : add_units ℕ) : u = 0 := add_units.ext $ (nat.eq_zero_of_add_eq_zero u.val_neg).1 @[simp] protected theorem is_unit_iff {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_spec_and_le : ∀{b m}, m ≤ b → P m → P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b | 0 m hm hP := have m = 0, from le_antisymm hm (nat.zero_le _), show P 0 ∧ m ≤ 0, from this ▸ ⟨hP, le_refl _⟩ | (b + 1) m hm hP := begin by_cases h : P (b + 1), { simp [h, hm] }, { have : m ≠ b + 1 := assume this, h $ this ▸ hP, have : m ≤ b := (le_of_not_gt $ assume h : b + 1 ≤ m, this $ le_antisymm hm h), have : P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b := find_greatest_spec_and_le this hP, simp [h, this] } end lemma find_greatest_spec {b} : (∃m, m ≤ b ∧ P m) → P (nat.find_greatest P b) | ⟨m, hmb, hm⟩ := (find_greatest_spec_and_le hmb hm).1 lemma find_greatest_le : ∀ {b}, nat.find_greatest P b ≤ b | 0 := le_refl _ | (b + 1) := have nat.find_greatest P b ≤ b + 1, from le_trans find_greatest_le (nat.le_succ b), by by_cases P (b + 1); simp [h, this] lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := (find_greatest_spec_and_le hmb hm).2 lemma find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b} : (∃ m, m ≤ b ∧ P m) → ∀ k, nat.find_greatest P b < k ∧ k ≤ b → ¬ P k | ⟨m, hmb, hP⟩ k ⟨hk, hkb⟩ hPk := lt_irrefl k $ lt_of_le_of_lt (le_find_greatest hkb hPk) hk lemma find_greatest_eq_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b}, (∀ n ≤ b, ¬ P n) → nat.find_greatest P b = 0 | 0 h := find_greatest_zero | (n + 1) h := begin have := nat.find_greatest_of_not (h (n + 1) (le_refl _)), rw this, exact find_greatest_eq_zero (assume k hk, h k (le_trans hk $ nat.le_succ _)) end lemma find_greatest_of_ne_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b m}, nat.find_greatest P b = m → m ≠ 0 → P m | 0 m rfl h := by { have := @find_greatest_zero P _, contradiction } | (b + 1) m rfl h := decidable.by_cases (assume hb : P (b + 1), by { have := find_greatest_eq hb, rw this, exact hb }) (assume hb : ¬ P (b + 1), find_greatest_of_ne_zero (find_greatest_of_not hb).symm h) end find_greatest section div lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have hac : a ∣ c, from dvd_of_mul_right_dvd h, have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] /-- If a small natural number is divisible by a larger natural number, the small number is zero. -/ lemma eq_zero_of_dvd_of_lt {a b : ℕ} (w : a ∣ b) (h : b < a) : b = 0 := nat.eq_zero_of_dvd_of_div_eq_zero w ((nat.div_eq_zero_iff (lt_of_le_of_lt (zero_le b) h)).elim_right h) lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end end div lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ lemma with_bot.add_eq_zero_iff : ∀ {n m : with_bot ℕ}, n + m = 0 ↔ n = 0 ∧ m = 0 | none m := iff_of_false dec_trivial (λ h, absurd h.1 dec_trivial) | n none := iff_of_false (by cases n; exact dec_trivial) (λ h, absurd h.2 dec_trivial) | (some n) (some m) := show (n + m : with_bot ℕ) = (0 : ℕ) ↔ (n : with_bot ℕ) = (0 : ℕ) ∧ (m : with_bot ℕ) = (0 : ℕ), by rw [← with_bot.coe_add, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, add_eq_zero_iff' (nat.zero_le _) (nat.zero_le _)] lemma with_bot.add_eq_one_iff : ∀ {n m : with_bot ℕ}, n + m = 1 ↔ (n = 0 ∧ m = 1) ∨ (n = 1 ∧ m = 0) | none none := dec_trivial | none (some m) := dec_trivial | (some n) none := iff_of_false dec_trivial (λ h, h.elim (λ h, absurd h.2 dec_trivial) (λ h, absurd h.2 dec_trivial)) | (some n) (some 0) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp | (some n) (some (m + 1)) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp [nat.add_succ, nat.succ_inj', nat.succ_ne_zero] @[simp] lemma with_bot.coe_nonneg {n : ℕ} : 0 ≤ (n : with_bot ℕ) := by rw [← with_bot.coe_zero, with_bot.coe_le_coe]; exact nat.zero_le _ @[simp] lemma with_bot.lt_zero_iff (n : with_bot ℕ) : n < 0 ↔ n = ⊥ := option.cases_on n dec_trivial (λ n, iff_of_false (by simp [with_bot.some_eq_coe]) (λ h, option.no_confusion h)) -- induction /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } end nat
797379f9580a1a0484c66c9bd307eeede0943185
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/SortLocalDecls.lean
f51ce34e258a3b9e6caef3bfd2dc732bb5b74529
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,806
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic namespace Lean.Meta namespace SortLocalDecls structure Context where localDecls : NameMap LocalDecl := {} structure State where visited : NameSet := {} result : Array LocalDecl := #[] abbrev M := ReaderT Context $ StateRefT State MetaM mutual partial def visitExpr (e : Expr) : M Unit := do match e with | Expr.proj _ _ e _ => visitExpr e | Expr.forallE _ d b _ => visitExpr d; visitExpr b | Expr.lam _ d b _ => visitExpr d; visitExpr b | Expr.letE _ t v b _ => visitExpr t; visitExpr v; visitExpr b | Expr.app f a _ => visitExpr f; visitExpr a | Expr.mdata _ b _ => visitExpr b | Expr.mvar _ _ => let v ← instantiateMVars e; unless v.isMVar do visitExpr v | Expr.fvar fvarId _ => if let some localDecl := (← read).localDecls.find? fvarId.name then visitLocalDecl localDecl | _ => return () partial def visitLocalDecl (localDecl : LocalDecl) : M Unit := do unless (← get).visited.contains localDecl.fvarId.name do modify fun s => { s with visited := s.visited.insert localDecl.fvarId.name } visitExpr localDecl.type if let some val := localDecl.value? then visitExpr val modify fun s => { s with result := s.result.push localDecl } end end SortLocalDecls open SortLocalDecls in def sortLocalDecls (localDecls : Array LocalDecl) : MetaM (Array LocalDecl) := let aux : M (Array LocalDecl) := do localDecls.forM visitLocalDecl; return (← get).result aux.run { localDecls := localDecls.foldl (init := {}) fun s d => s.insert d.fvarId.name d } |>.run' {} end Lean.Meta
473f8923bb58e948dadb25211044ac2fe1510fc9
4767244035cdd124e1ce3d0c81128f8929df6163
/algebra/group.lean
bc4a8dc6432873a2a7601fcceff6ce8c6556f2a3
[ "Apache-2.0" ]
permissive
5HT/mathlib
b941fecacd31a9c5dd0abad58770084b8a1e56b1
40fa9ade2f5649569639608db5e621e5fad0cc02
refs/heads/master
1,586,978,681,358
1,546,681,764,000
1,546,681,764,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,050
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 Various multiplicative and additive structures. -/ import tactic.interactive data.option.defs section pending_1857 /- Transport multiplicative to additive -/ section transport open tactic @[user_attribute] meta def to_additive_attr : user_attribute (name_map name) name := { name := `to_additive, descr := "Transport multiplicative to additive", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do val ← to_additive_attr.get_param n, pure $ dict.insert n val) mk_name_map, []⟩, parser := lean.parser.ident, after_set := some $ λ src _ _, do env ← get_env, dict ← to_additive_attr.get_cache, tgt ← to_additive_attr.get_param src, (get_decl tgt >> skip) <|> transport_with_dict dict src tgt } end transport /- map operations -/ attribute [to_additive has_add.add] has_mul.mul attribute [to_additive has_zero.zero] has_one.one attribute [to_additive has_neg.neg] has_inv.inv attribute [to_additive has_add] has_mul attribute [to_additive has_zero] has_one attribute [to_additive has_neg] has_inv /- map constructors -/ attribute [to_additive has_add.mk] has_mul.mk attribute [to_additive has_zero.mk] has_one.mk attribute [to_additive has_neg.mk] has_inv.mk /- map structures -/ attribute [to_additive add_semigroup] semigroup attribute [to_additive add_semigroup.mk] semigroup.mk attribute [to_additive add_semigroup.to_has_add] semigroup.to_has_mul attribute [to_additive add_semigroup.add_assoc] semigroup.mul_assoc attribute [to_additive add_semigroup.add] semigroup.mul attribute [to_additive add_comm_semigroup] comm_semigroup attribute [to_additive add_comm_semigroup.mk] comm_semigroup.mk attribute [to_additive add_comm_semigroup.to_add_semigroup] comm_semigroup.to_semigroup attribute [to_additive add_comm_semigroup.add_comm] comm_semigroup.mul_comm attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup attribute [to_additive add_left_cancel_semigroup.mk] left_cancel_semigroup.mk attribute [to_additive add_left_cancel_semigroup.to_add_semigroup] left_cancel_semigroup.to_semigroup attribute [to_additive add_left_cancel_semigroup.add_left_cancel] left_cancel_semigroup.mul_left_cancel attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup attribute [to_additive add_right_cancel_semigroup.mk] right_cancel_semigroup.mk attribute [to_additive add_right_cancel_semigroup.to_add_semigroup] right_cancel_semigroup.to_semigroup attribute [to_additive add_right_cancel_semigroup.add_right_cancel] right_cancel_semigroup.mul_right_cancel attribute [to_additive add_monoid] monoid attribute [to_additive add_monoid.mk] monoid.mk attribute [to_additive add_monoid.to_has_zero] monoid.to_has_one attribute [to_additive add_monoid.to_add_semigroup] monoid.to_semigroup attribute [to_additive add_monoid.add] monoid.mul attribute [to_additive add_monoid.add_assoc] monoid.mul_assoc attribute [to_additive add_monoid.zero] monoid.one attribute [to_additive add_monoid.zero_add] monoid.one_mul attribute [to_additive add_monoid.add_zero] monoid.mul_one attribute [to_additive add_comm_monoid] comm_monoid attribute [to_additive add_comm_monoid.mk] comm_monoid.mk attribute [to_additive add_comm_monoid.to_add_monoid] comm_monoid.to_monoid attribute [to_additive add_comm_monoid.to_add_comm_semigroup] comm_monoid.to_comm_semigroup attribute [to_additive add_group] group attribute [to_additive add_group.mk] group.mk attribute [to_additive add_group.to_has_neg] group.to_has_inv attribute [to_additive add_group.to_add_monoid] group.to_monoid attribute [to_additive add_group.add_left_neg] group.mul_left_inv attribute [to_additive add_group.add] group.mul attribute [to_additive add_group.add_assoc] group.mul_assoc attribute [to_additive add_group.zero] group.one attribute [to_additive add_group.zero_add] group.one_mul attribute [to_additive add_group.add_zero] group.mul_one attribute [to_additive add_group.neg] group.inv attribute [to_additive add_comm_group] comm_group attribute [to_additive add_comm_group.mk] comm_group.mk attribute [to_additive add_comm_group.to_add_group] comm_group.to_group attribute [to_additive add_comm_group.to_add_comm_monoid] comm_group.to_comm_monoid /- map theorems -/ attribute [to_additive add_assoc] mul_assoc attribute [to_additive add_semigroup_to_is_associative] semigroup_to_is_associative attribute [to_additive add_comm] mul_comm attribute [to_additive add_comm_semigroup_to_is_commutative] comm_semigroup_to_is_commutative attribute [to_additive add_left_comm] mul_left_comm attribute [to_additive add_right_comm] mul_right_comm attribute [to_additive add_left_cancel] mul_left_cancel attribute [to_additive add_right_cancel] mul_right_cancel attribute [to_additive add_left_cancel_iff] mul_left_cancel_iff attribute [to_additive add_right_cancel_iff] mul_right_cancel_iff attribute [to_additive zero_add] one_mul attribute [to_additive add_zero] mul_one attribute [to_additive add_left_neg] mul_left_inv attribute [to_additive neg_add_self] inv_mul_self attribute [to_additive neg_add_cancel_left] inv_mul_cancel_left attribute [to_additive neg_add_cancel_right] inv_mul_cancel_right attribute [to_additive neg_eq_of_add_eq_zero] inv_eq_of_mul_eq_one attribute [to_additive neg_zero] one_inv attribute [to_additive neg_neg] inv_inv attribute [to_additive add_right_neg] mul_right_inv attribute [to_additive add_neg_self] mul_inv_self attribute [to_additive neg_inj] inv_inj attribute [to_additive add_group.add_left_cancel] group.mul_left_cancel attribute [to_additive add_group.add_right_cancel] group.mul_right_cancel attribute [to_additive add_group.to_left_cancel_add_semigroup] group.to_left_cancel_semigroup attribute [to_additive add_group.to_right_cancel_add_semigroup] group.to_right_cancel_semigroup attribute [to_additive add_neg_cancel_left] mul_inv_cancel_left attribute [to_additive add_neg_cancel_right] mul_inv_cancel_right attribute [to_additive neg_add_rev] mul_inv_rev attribute [to_additive eq_neg_of_eq_neg] eq_inv_of_eq_inv attribute [to_additive eq_neg_of_add_eq_zero] eq_inv_of_mul_eq_one attribute [to_additive eq_add_neg_of_add_eq] eq_mul_inv_of_mul_eq attribute [to_additive eq_neg_add_of_add_eq] eq_inv_mul_of_mul_eq attribute [to_additive neg_add_eq_of_eq_add] inv_mul_eq_of_eq_mul attribute [to_additive add_neg_eq_of_eq_add] mul_inv_eq_of_eq_mul attribute [to_additive eq_add_of_add_neg_eq] eq_mul_of_mul_inv_eq attribute [to_additive eq_add_of_neg_add_eq] eq_mul_of_inv_mul_eq attribute [to_additive add_eq_of_eq_neg_add] mul_eq_of_eq_inv_mul attribute [to_additive add_eq_of_eq_add_neg] mul_eq_of_eq_mul_inv attribute [to_additive neg_add] mul_inv end pending_1857 instance monoid_to_is_left_id {α : Type*} [monoid α] : is_left_id α (*) 1 := ⟨ monoid.one_mul ⟩ instance monoid_to_is_right_id {α : Type*} [monoid α] : is_right_id α (*) 1 := ⟨ monoid.mul_one ⟩ instance add_monoid_to_is_left_id {α : Type*} [add_monoid α] : is_left_id α (+) 0 := ⟨ add_monoid.zero_add ⟩ instance add_monoid_to_is_right_id {α : Type*} [add_monoid α] : is_right_id α (+) 0 := ⟨ add_monoid.add_zero ⟩ universes u v variables {α : Type u} {β : Type v} def additive (α : Type*) := α def multiplicative (α : Type*) := α instance [semigroup α] : add_semigroup (additive α) := { add := ((*) : α → α → α), add_assoc := @mul_assoc _ _ } instance [add_semigroup α] : semigroup (multiplicative α) := { mul := ((+) : α → α → α), mul_assoc := @add_assoc _ _ } instance [comm_semigroup α] : add_comm_semigroup (additive α) := { add_comm := @mul_comm _ _, ..additive.add_semigroup } instance [add_comm_semigroup α] : comm_semigroup (multiplicative α) := { mul_comm := @add_comm _ _, ..multiplicative.semigroup } instance [left_cancel_semigroup α] : add_left_cancel_semigroup (additive α) := { add_left_cancel := @mul_left_cancel _ _, ..additive.add_semigroup } instance [add_left_cancel_semigroup α] : left_cancel_semigroup (multiplicative α) := { mul_left_cancel := @add_left_cancel _ _, ..multiplicative.semigroup } instance [right_cancel_semigroup α] : add_right_cancel_semigroup (additive α) := { add_right_cancel := @mul_right_cancel _ _, ..additive.add_semigroup } instance [add_right_cancel_semigroup α] : right_cancel_semigroup (multiplicative α) := { mul_right_cancel := @add_right_cancel _ _, ..multiplicative.semigroup } @[simp, to_additive add_left_inj] theorem mul_left_inj [left_cancel_semigroup α] (a : α) {b c : α} : a * b = a * c ↔ b = c := ⟨mul_left_cancel, congr_arg _⟩ @[simp, to_additive add_right_inj] theorem mul_right_inj [right_cancel_semigroup α] (a : α) {b c : α} : b * a = c * a ↔ b = c := ⟨mul_right_cancel, congr_arg _⟩ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) namespace units variables [monoid α] {a b c : units α} instance : has_coe (units α) α := ⟨val⟩ @[extensionality] theorem ext : ∀ {a b : units α}, (a : α) = b → a = b | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := ⟨congr_arg _, ext⟩ instance [decidable_eq α] : decidable_eq (units α) | a b := decidable_of_iff' _ ext_iff protected def mul (u₁ u₂ : units α) : units α := ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, have u₁.val * (u₂.val * u₂.inv) * u₁.inv = 1, by rw [u₂.val_inv]; rw [mul_one, u₁.val_inv], by simpa only [mul_assoc], have u₂.inv * (u₁.inv * u₁.val) * u₂.val = 1, by rw [u₁.inv_val]; rw [mul_one, u₂.inv_val], by simpa only [mul_assoc]⟩ protected def inv' (u : units α) : units α := ⟨u.inv, u.val, u.inv_val, u.val_inv⟩ instance : has_mul (units α) := ⟨units.mul⟩ instance : has_one (units α) := ⟨⟨1, 1, mul_one 1, one_mul 1⟩⟩ instance : has_inv (units α) := ⟨units.inv'⟩ variables (a b) @[simp] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp] lemma coe_one : ((1 : units α) : α) = 1 := rfl lemma val_coe : (↑a : α) = a.val := rfl lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl @[simp] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[simp] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] instance : group (units α) := by refine {mul := (*), one := 1, inv := has_inv.inv, ..}; { intros, apply ext, simp only [coe_mul, coe_one, mul_assoc, one_mul, mul_one, inv_mul] } instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp] theorem mul_left_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp] theorem mul_right_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ end units theorem nat.units_eq_one (u : units ℕ) : u = 1 := units.ext $ nat.eq_one_of_dvd_one ⟨u.inv, u.val_inv.symm⟩ def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[to_additive with_zero] def with_one (α) := option α @[to_additive with_zero.has_coe_t] instance : has_coe_t α (with_one α) := ⟨some⟩ instance [semigroup α] : monoid (with_one α) := { one := none, mul := option.lift_or_get (*), mul_assoc := (option.lift_or_get_assoc _).1, one_mul := (option.lift_or_get_is_left_id _).1, mul_one := (option.lift_or_get_is_right_id _).1 } attribute [to_additive with_zero.add_monoid._proof_1] with_one.monoid._proof_1 attribute [to_additive with_zero.add_monoid._proof_2] with_one.monoid._proof_2 attribute [to_additive with_zero.add_monoid._proof_3] with_one.monoid._proof_3 attribute [to_additive with_zero.add_monoid] with_one.monoid instance [semigroup α] : mul_zero_class (with_zero α) := { zero := none, mul := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a * b)), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.add_monoid } instance [semigroup α] : semigroup (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup } instance [monoid α] : monoid (with_zero α) := { one := some 1, one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.semigroup } instance [comm_monoid α] : comm_monoid (with_zero α) := { ..with_zero.monoid, ..with_zero.comm_semigroup } instance [monoid α] : add_monoid (additive α) := { zero := (1 : α), zero_add := @one_mul _ _, add_zero := @mul_one _ _, ..additive.add_semigroup } instance [add_monoid α] : monoid (multiplicative α) := { one := (0 : α), one_mul := @zero_add _ _, mul_one := @add_zero _ _, ..multiplicative.semigroup } section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_right_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_right_inj _ theorem divp_eq_one (a : α) (u : units α) : a /ₚ u = 1 ↔ a = u := (units.mul_right_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } instance [add_comm_semigroup α] : add_comm_monoid (with_zero α) := { add_comm := (option.lift_or_get_comm _).1, ..with_zero.add_monoid } attribute [to_additive with_zero.add_comm_monoid] with_one.comm_monoid instance [comm_monoid α] : add_comm_monoid (additive α) := { add_comm := @mul_comm α _, ..additive.add_monoid } instance [add_comm_monoid α] : comm_monoid (multiplicative α) := { mul_comm := @add_comm α _, ..multiplicative.monoid } instance [group α] : add_group (additive α) := { neg := @has_inv.inv α _, add_left_neg := @mul_left_inv _ _, ..additive.add_monoid } instance [add_group α] : group (multiplicative α) := { inv := @has_neg.neg α _, mul_left_inv := @add_left_neg _ _, ..multiplicative.monoid } section group variables [group α] {a b c : α} instance : has_lift α (units α) := ⟨λ a, ⟨a, a⁻¹, mul_inv_self _, inv_mul_self _⟩⟩ @[simp, to_additive neg_inj'] theorem inv_inj' : a⁻¹ = b⁻¹ ↔ a = b := ⟨λ h, by rw [← inv_inv a, h, inv_inv], congr_arg _⟩ @[to_additive eq_of_neg_eq_neg] theorem eq_of_inv_eq_inv : a⁻¹ = b⁻¹ → a = b := inv_inj'.1 @[simp, to_additive add_self_iff_eq_zero] theorem mul_self_iff_eq_one : a * a = a ↔ a = 1 := by have := @mul_left_inj _ _ a a 1; rwa mul_one at this @[simp, to_additive neg_eq_zero] theorem inv_eq_one : a⁻¹ = 1 ↔ a = 1 := by rw [← @inv_inj' _ _ a 1, one_inv] @[simp, to_additive neg_ne_zero] theorem inv_ne_one : a⁻¹ ≠ 1 ↔ a ≠ 1 := not_congr inv_eq_one @[to_additive left_inverse_neg] theorem left_inverse_inv (α) [group α] : function.left_inverse (λ a : α, a⁻¹) (λ a, a⁻¹) := assume a, inv_inv a attribute [simp] mul_inv_cancel_left add_neg_cancel_left mul_inv_cancel_right add_neg_cancel_right @[to_additive eq_neg_iff_eq_neg] theorem eq_inv_iff_eq_inv : a = b⁻¹ ↔ b = a⁻¹ := ⟨eq_inv_of_eq_inv, eq_inv_of_eq_inv⟩ @[to_additive neg_eq_iff_neg_eq] theorem inv_eq_iff_inv_eq : a⁻¹ = b ↔ b⁻¹ = a := by rw [eq_comm, @eq_comm _ _ a, eq_inv_iff_eq_inv] @[to_additive add_eq_zero_iff_eq_neg] theorem mul_eq_one_iff_eq_inv : a * b = 1 ↔ a = b⁻¹ := by simpa [mul_left_inv, -mul_right_inj] using @mul_right_inj _ _ b a (b⁻¹) @[to_additive add_eq_zero_iff_neg_eq] 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 eq_neg_iff_add_eq_zero] theorem eq_inv_iff_mul_eq_one : a = b⁻¹ ↔ a * b = 1 := mul_eq_one_iff_eq_inv.symm @[to_additive neg_eq_iff_add_eq_zero] theorem inv_eq_iff_mul_eq_one : a⁻¹ = b ↔ a * b = 1 := mul_eq_one_iff_inv_eq.symm @[to_additive eq_add_neg_iff_add_eq] 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 eq_neg_add_iff_add_eq] 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 neg_add_eq_iff_eq_add] 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 add_neg_eq_iff_eq_add] 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 add_neg_eq_zero] theorem mul_inv_eq_one {a b : α} : a * b⁻¹ = 1 ↔ a = b := by rw [mul_eq_one_iff_eq_inv, inv_inv] @[to_additive neg_comm_of_comm] theorem inv_comm_of_comm {a b : α} (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm, rwa [inv_mul_cancel_left, mul_assoc, mul_inv_cancel_right] at this end end group instance [comm_group α] : add_comm_group (additive α) := { add_comm := @mul_comm α _, ..additive.add_group } instance [add_comm_group α] : comm_group (multiplicative α) := { mul_comm := @add_comm α _, ..multiplicative.group } section add_monoid variables [add_monoid α] {a b c : α} @[simp] lemma bit0_zero : bit0 (0 : α) = 0 := add_zero _ @[simp] lemma bit1_zero [has_one α] : bit1 (0 : α) = 1 := show 0+0+1=(1:α), by rw [zero_add, zero_add] end add_monoid section add_group variables [add_group α] {a b c : α} local attribute [simp] sub_eq_add_neg def sub_sub_cancel := @sub_sub_self @[simp] lemma sub_left_inj : a - b = a - c ↔ b = c := (add_left_inj _).trans neg_inj' @[simp] lemma sub_right_inj : b - a = c - a ↔ b = c := add_right_inj _ lemma sub_add_sub_cancel (a b c : α) : (a - b) + (b - c) = a - c := by rw [← add_sub_assoc, sub_add_cancel] lemma sub_sub_sub_cancel_right (a b c : α) : (a - c) - (b - c) = a - b := by rw [← neg_sub c b, sub_neg_eq_add, sub_add_sub_cancel] theorem sub_eq_zero : a - b = 0 ↔ a = b := ⟨eq_of_sub_eq_zero, λ h, by rw [h, sub_self]⟩ theorem sub_ne_zero : a - b ≠ 0 ↔ a ≠ b := not_congr sub_eq_zero theorem eq_sub_iff_add_eq : a = b - c ↔ a + c = b := eq_add_neg_iff_add_eq theorem sub_eq_iff_eq_add : a - b = c ↔ a = c + b := add_neg_eq_iff_eq_add theorem eq_iff_eq_of_sub_eq_sub {a b c d : α} (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 : α) : function.left_inverse (λ x, x - c) (λ x, x + c) := assume x, add_sub_cancel x c theorem left_inverse_add_left_sub (c : α) : function.left_inverse (λ x, x + c) (λ x, x - c) := assume x, sub_add_cancel x c theorem left_inverse_add_right_neg_add (c : α) : 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 : α) : function.left_inverse (λ x, - c + x) (λ x, c + x) := assume x, neg_add_cancel_left c x end add_group section add_comm_group variables [add_comm_group α] {a b c : α} lemma sub_eq_neg_add (a b : α) : a - b = -b + a := add_comm _ _ theorem neg_add' (a b : α) : -(a + b) = -a - b := neg_add a b lemma neg_sub_neg (a b : α) : -a - -b = b - a := by simp 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] lemma add_sub_cancel' (a b : α) : a + b - a = b := by rw [sub_eq_neg_add, neg_add_cancel_left] lemma add_sub_cancel'_right (a b : α) : a + (b - a) = b := by rw [← add_sub_assoc, add_sub_cancel'] lemma sub_right_comm (a b c : α) : a - b - c = a - c - b := add_right_comm _ _ _ lemma sub_add_sub_cancel' (a b c : α) : (a - b) + (c - a) = c - b := by rw add_comm; apply sub_add_sub_cancel lemma sub_sub_sub_cancel_left (a b c : α) : (c - a) - (c - b) = b - a := by rw [← neg_sub b c, sub_neg_eq_add, add_comm, sub_add_sub_cancel] end add_comm_group section is_conj variables [group α] [group β] def is_conj (a b : α) := ∃ c : α, c * a * c⁻¹ = b @[refl] lemma is_conj_refl (a : α) : is_conj a a := ⟨1, by rw [one_mul, one_inv, mul_one]⟩ @[symm] lemma is_conj_symm (a b : α) : is_conj a b → is_conj b a | ⟨c, hc⟩ := ⟨c⁻¹, by rw [← hc, mul_assoc, mul_inv_cancel_right, inv_mul_cancel_left]⟩ @[trans] lemma is_conj_trans (a b c : α) : is_conj a b → is_conj b c → is_conj a c | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, by rw [← hc₂, ← hc₁, mul_inv_rev]; simp only [mul_assoc]⟩ @[simp] lemma is_conj_iff_eq {α : Type*} [comm_group α] {a b : α} : is_conj a b ↔ a = b := ⟨λ ⟨c, hc⟩, by rw [← hc, mul_right_comm, mul_inv_self, one_mul], λ h, by rw h⟩ end is_conj class is_monoid_hom [monoid α] [monoid β] (f : α → β) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y}, f (x * y) = f x * f y) class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) : Prop := (map_zero : f 0 = 0) (map_add : ∀ {x y}, f (x + y) = f x + f y) attribute [to_additive is_add_monoid_hom] is_monoid_hom attribute [to_additive is_add_monoid_hom.map_add] is_monoid_hom.map_mul attribute [to_additive is_add_monoid_hom.mk] is_monoid_hom.mk namespace is_monoid_hom variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] @[to_additive is_add_monoid_hom.id] instance id : is_monoid_hom (@id α) := by refine {..}; intros; refl @[to_additive is_add_monoid_hom.id] instance comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] : is_monoid_hom (g ∘ f) := { map_mul := λ x y, show g _ = g _ * g _, by rw [map_mul f, map_mul g], map_one := show g _ = 1, by rw [map_one f, map_one g] } instance is_add_monoid_hom_mul_left {γ : Type*} [semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, x * y) := by refine_struct {..}; simp [mul_add] instance is_add_monoid_hom_mul_right {γ : Type*} [semiring γ] (x : γ) : is_add_monoid_hom (λ y : γ, y * x) := by refine_struct {..}; simp [add_mul] end is_monoid_hom -- TODO rename fields of is_group_hom: mul ↝ map_mul? /-- Predicate for group homomorphism. -/ class is_group_hom [group α] [group β] (f : α → β) : Prop := (mul : ∀ a b : α, f (a * b) = f a * f b) class is_add_group_hom [add_group α] [add_group β] (f : α → β) : Prop := (add : ∀ a b, f (a + b) = f a + f b) attribute [to_additive is_add_group_hom] is_group_hom attribute [to_additive is_add_group_hom.add] is_group_hom.mul attribute [to_additive is_add_group_hom.mk] is_group_hom.mk namespace is_group_hom variables [group α] [group β] (f : α → β) [is_group_hom f] @[to_additive is_add_group_hom.zero] theorem one : f 1 = 1 := mul_self_iff_eq_one.1 $ by rw [← mul f, one_mul] @[to_additive is_add_group_hom.neg] theorem inv (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← mul f, inv_mul_self, one f] @[to_additive is_add_group_hom.id] instance id : is_group_hom (@id α) := ⟨λ _ _, rfl⟩ @[to_additive is_add_group_hom.comp] instance comp {γ} [group γ] (g : β → γ) [is_group_hom g] : is_group_hom (g ∘ f) := ⟨λ x y, show g _ = g _ * g _, by rw [mul f, mul g]⟩ protected lemma is_conj (f : α → β) [is_group_hom f] {a b : α} : is_conj a b → is_conj (f a) (f b) | ⟨c, hc⟩ := ⟨f c, by rw [← is_group_hom.mul f, ← is_group_hom.inv f, ← is_group_hom.mul f, hc]⟩ @[to_additive is_add_group_hom.to_is_add_monoid_hom] lemma to_is_monoid_hom (f : α → β) [is_group_hom f] : is_monoid_hom f := ⟨is_group_hom.one f, is_group_hom.mul f⟩ attribute [instance] is_group_hom.to_is_monoid_hom is_add_group_hom.to_is_add_monoid_hom end is_group_hom @[to_additive is_add_group_hom_add] lemma is_group_hom_mul {α β} [group α] [comm_group β] (f g : α → β) [is_group_hom f] [is_group_hom g] : is_group_hom (λa, f a * g a) := ⟨assume a b, by simp only [is_group_hom.mul f, is_group_hom.mul g, mul_comm, mul_assoc, mul_left_comm]⟩ attribute [instance] is_group_hom_mul is_add_group_hom_add @[to_additive is_add_group_hom_neg] lemma is_group_hom_inv {α β} [group α] [comm_group β] (f : α → β) [is_group_hom f] : is_group_hom (λa, (f a)⁻¹) := ⟨assume a b, by rw [is_group_hom.mul f, mul_inv]⟩ attribute [instance] is_group_hom_inv is_add_group_hom_neg @[to_additive neg.is_add_group_hom] lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) := ⟨by simp [mul_inv_rev, mul_comm]⟩ attribute [instance] inv.is_group_hom neg.is_add_group_hom /-- Predicate for group anti-homomorphism, or a homomorphism into the opposite group. -/ class is_group_anti_hom {β : Type*} [group α] [group β] (f : α → β) : Prop := (mul : ∀ a b : α, f (a * b) = f b * f a) namespace is_group_anti_hom variables [group α] [group β] (f : α → β) [w : is_group_anti_hom f] include w theorem one : f 1 = 1 := mul_self_iff_eq_one.1 $ by rw [← mul f, one_mul] theorem inv (a : α) : f a⁻¹ = (f a)⁻¹ := eq_inv_of_mul_eq_one $ by rw [← mul f, mul_inv_self, one f] end is_group_anti_hom theorem inv_is_group_anti_hom [group α] : is_group_anti_hom (λ x : α, x⁻¹) := ⟨mul_inv_rev⟩ namespace is_add_group_hom variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] lemma sub (a b) : f (a - b) = f a - f b := calc f (a - b) = f (a + -b) : rfl ... = f a + f (-b) : add f _ _ ... = f a - f b : by simp[neg f] end is_add_group_hom lemma is_add_group_hom_sub {α β} [add_group α] [add_comm_group β] (f g : α → β) [is_add_group_hom f] [is_add_group_hom g] : is_add_group_hom (λa, f a - g a) := is_add_group_hom_add f (λa, - g a) attribute [instance] is_add_group_hom_sub namespace units variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] definition map : units α → units β := λ u, ⟨f u.val, f u.inv, by rw [← is_monoid_hom.map_mul f, u.val_inv, is_monoid_hom.map_one f], by rw [← is_monoid_hom.map_mul f, u.inv_val, is_monoid_hom.map_one f] ⟩ instance : is_group_hom (units.map f) := ⟨λ a b, by ext; exact is_monoid_hom.map_mul f ⟩ instance : is_monoid_hom (coe : units α → α) := ⟨by simp, by simp⟩ end units
01a1cc521ba37daaac7f2eed3b42cedffbf17c45
b29f946a2f0afd23ef86b9219116968babbb9f4f
/src/xenalib/M1P1.lean
6e8d0048fbde747562d76d6507d4303cc07da021
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M1P1-lean
58be7394fded719d95e45e6b10e1ecf2ed3c7c4c
3723468cc50f8bebd00a9811caf25224a578de17
refs/heads/master
1,587,063,867,779
1,572,727,164,000
1,572,727,164,000
165,845,802
14
4
Apache-2.0
1,549,730,698,000
1,547,554,675,000
Lean
UTF-8
Lean
false
false
619
lean
import tactic.linarith data.real.basic local notation `|` x `|` := abs x lemma zero_of_abs_lt_all (x : ℝ) (h : ∀ ε > 0, |x| < ε) : x = 0 := eq_zero_of_abs_eq_zero $ eq_of_le_of_forall_le_of_dense (abs_nonneg x) $ λ ε ε_pos, le_of_lt (h ε ε_pos) -- The next few things should be hidden @[user_attribute] meta def ineq_rules : user_attribute := { name := `ineq_rules, descr := "lemmas usable to prove inequalities" } attribute [ineq_rules] add_lt_add le_max_left le_max_right meta def obvious_ineq := `[linarith <|> apply_rules ineq_rules] run_cmd add_interactive [`obvious_ineq] -- end of scary things
81a3835eceda080738414af725c2bb01a8e23218
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/NFM2022/nfm15.lean
46e493c70d37f560a4e1543c22efa1039f4bd826
[ "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
702
lean
/- intro tactic variants -/ example (p q : α → Prop) : (∃ x, p x ∧ q x) → ∃ x, q x ∧ p x := by intro h match h with | Exists.intro w (And.intro hp hq) => exact Exists.intro w (And.intro hq hp) example (p q : α → Prop) : (∃ x, p x ∧ q x) → ∃ x, q x ∧ p x := by intro (Exists.intro _ (And.intro hp hq)) exact Exists.intro _ (And.intro hq hp) example (p q : α → Prop) : (∃ x, p x ∧ q x) → ∃ x, q x ∧ p x := by intro ⟨_, hp, hq⟩ exact ⟨_, hq, hp⟩ example (α : Type) (p q : α → Prop) : (∃ x, p x ∨ q x) → ∃ x, q x ∨ p x := by intro | ⟨_, .inl h⟩ => exact ⟨_, .inr h⟩ | ⟨_, .inr h⟩ => exact ⟨_, .inl h⟩
d80da5de05ff143e353716aaa56e5815bdcc88d7
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/util/prod.lean
c6eab8909af7b44a85c923a57de24ee66a1461cf
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
427
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. def prod.eq {α : Type*} {β : Type*} : Π {x y : prod α β}, x.fst = y.fst → x.snd = y.snd → x = y | ⟨_, _⟩ ⟨_, _⟩ rfl rfl := rfl def pprod.eq {α : Sort*} {β : Sort*} : Π {x y : pprod α β}, x.fst = y.fst → x.snd = y.snd → x = y | ⟨_, _⟩ ⟨_, _⟩ rfl rfl := rfl
e7d7f231c8449888b4d0e3b5c3f4d26b3801e7c0
137c667471a40116a7afd7261f030b30180468c2
/src/analysis/normed_space/basic.lean
2a1d595f8a6ee418c30899e3e53178483af04ff7
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
85,857
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.punit_instances import topology.instances.nnreal import topology.algebra.module import topology.algebra.algebra import topology.algebra.group_completion import topology.metric_space.completion import topology.algebra.ordered.liminf_limsup import topology.sequences /-! # Normed spaces Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory of `semi_normed_group` and we specialize to `normed_group` at the end. -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators nnreal ennreal uniformity /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥` e `∥` := norm e /-- A seminormed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a pseudometric space structure. -/ class semi_normed_group (α : Type*) extends has_norm α, add_comm_group α, pseudo_metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- A normed group is a seminormed group. -/ @[priority 100] -- see Note [lower instance priority] instance normed_group.to_semi_normed_group [β : normed_group α] : semi_normed_group α := { ..β } /-- Construct a seminormed group from a translation invariant pseudodistance -/ def semi_normed_group.of_add_dist [has_norm α] [add_comm_group α] [pseudo_metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : semi_normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a seminormed group from a translation invariant pseudodistance -/ def semi_normed_group.of_add_dist' [has_norm α] [add_comm_group α] [pseudo_metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : semi_normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A seminormed group can be built from a seminorm that satisfies algebraic properties. This is formalised in this structure. -/ structure semi_normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_zero : ∥(0 : α)∥ = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- Constructing a seminormed group from core properties of a seminorm, i.e., registering the pseudodistance and the pseudometric space structure from the seminorm properties. -/ noncomputable def semi_normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : semi_normed_group.core α) : semi_normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, by simp [C.norm_zero], dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } instance : normed_group punit := { norm := function.const _ 0, dist_eq := λ _ _, rfl, } @[simp] lemma punit.norm_eq_zero (r : punit) : ∥r∥ = 0 := rfl instance : normed_group ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl } lemma real.norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl section semi_normed_group variables [semi_normed_group α] [semi_normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := semi_normed_group.dist_eq _ _ lemma dist_eq_norm' (g h : α) : dist g h = ∥h - g∥ := by rw [dist_comm, dist_eq_norm] @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] @[simp] lemma dist_zero_left : dist (0:α) = norm := funext $ λ g, by rw [dist_comm, dist_zero_right] lemma tendsto_norm_cocompact_at_top [proper_space α] : tendsto norm (cocompact α) at_top := by simpa only [dist_zero_right] using tendsto_dist_right_cocompact_at_top (0:α) lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := by simpa only [sub_eq_add_neg] using dist_add_right _ _ _ /-- **Triangle inequality** for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [sub_eq_add_neg, dist_neg_neg] using dist_add_add_le g₁ (-g₂) h₁ (-h₂) lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := by rw [← dist_zero_right, dist_self] @[nontriviality] lemma norm_of_subsingleton [subsingleton α] (x : α) : ∥x∥ = 0 := by rw [subsingleton.elim x 0, norm_zero] lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥∑ b in s, f b∥ ≤ ∑ b in s, n b := le_trans (norm_sum_le s f) (finset.sum_le_sum h) lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_le_insert (u v : α) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ := calc ∥v∥ = ∥u - (u - v)∥ : by abel ... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _ lemma norm_le_insert' (u v : α) : ∥u∥ ≤ ∥v∥ + ∥u - v∥ := by { rw norm_sub_rev, exact norm_le_insert v u } lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma mem_ball_iff_norm {g h : α} {r : ℝ} : h ∈ ball g r ↔ ∥h - g∥ < r := by rw [mem_ball, dist_eq_norm] lemma add_mem_ball_iff_norm {g h : α} {r : ℝ} : g + h ∈ ball g r ↔ ∥h∥ < r := by rw [mem_ball_iff_norm, add_sub_cancel'] lemma mem_ball_iff_norm' {g h : α} {r : ℝ} : h ∈ ball g r ↔ ∥g - h∥ < r := by rw [mem_ball', dist_eq_norm] @[simp] lemma mem_ball_0_iff {ε : ℝ} {x : α} : x ∈ ball (0 : α) ε ↔ ∥x∥ < ε := by rw [mem_ball, dist_zero_right] lemma mem_closed_ball_iff_norm {g h : α} {r : ℝ} : h ∈ closed_ball g r ↔ ∥h - g∥ ≤ r := by rw [mem_closed_ball, dist_eq_norm] lemma add_mem_closed_ball_iff_norm {g h : α} {r : ℝ} : g + h ∈ closed_ball g r ↔ ∥h∥ ≤ r := by rw [mem_closed_ball_iff_norm, add_sub_cancel'] lemma mem_closed_ball_iff_norm' {g h : α} {r : ℝ} : h ∈ closed_ball g r ↔ ∥g - h∥ ≤ r := by rw [mem_closed_ball', dist_eq_norm] lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_le_norm_add_const_of_dist_le {a b : α} {c : ℝ} (h : dist a b ≤ c) : ∥a∥ ≤ ∥b∥ + c := norm_le_of_mem_closed_ball h lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_norm_add_const_of_dist_lt {a b : α} {c : ℝ} (h : dist a b < c) : ∥a∥ < ∥b∥ + c := norm_lt_of_mem_ball h lemma bounded_iff_forall_norm_le {s : set α} : bounded s ↔ ∃ C, ∀ x ∈ s, ∥x∥ ≤ C := begin rw bounded_iff_subset_ball (0 : α), exact exists_congr (λ r, by simp [(⊆), set.subset]), end @[simp] lemma mem_sphere_iff_norm (v w : α) (r : ℝ) : w ∈ sphere v r ↔ ∥w - v∥ = r := by simp [dist_eq_norm] @[simp] lemma mem_sphere_zero_iff_norm {w : α} {r : ℝ} : w ∈ sphere (0:α) r ↔ ∥w∥ = r := by simp [dist_eq_norm] @[simp] lemma norm_eq_of_mem_sphere {r : ℝ} (x : sphere (0:α) r) : ∥(x:α)∥ = r := mem_sphere_zero_iff_norm.mp x.2 lemma ne_zero_of_norm_pos {g : α} : 0 < ∥ g ∥ → g ≠ 0 := begin intros hpos hzero, rw [hzero, norm_zero] at hpos, exact lt_irrefl 0 hpos, end lemma nonzero_of_mem_sphere {r : ℝ} (hr : 0 < r) (x : sphere (0:α) r) : (x:α) ≠ 0 := begin refine ne_zero_of_norm_pos _, rwa norm_eq_of_mem_sphere x, end lemma nonzero_of_mem_unit_sphere (x : sphere (0:α) 1) : (x:α) ≠ 0 := by { apply nonzero_of_mem_sphere, norm_num } /-- We equip the sphere, in a seminormed group, with a formal operation of negation, namely the antipodal map. -/ instance {r : ℝ} : has_neg (sphere (0:α) r) := { neg := λ w, ⟨-↑w, by simp⟩ } @[simp] lemma coe_neg_sphere {r : ℝ} (v : sphere (0:α) r) : (((-v) : sphere _ _) : α) = - (v:α) := rfl namespace isometric /-- Addition `y ↦ y + x` as an `isometry`. -/ protected def add_right (x : α) : α ≃ᵢ α := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_right _ _ _, .. equiv.add_right x } @[simp] lemma add_right_to_equiv (x : α) : (isometric.add_right x).to_equiv = equiv.add_right x := rfl @[simp] lemma coe_add_right (x : α) : (isometric.add_right x : α → α) = λ y, y + x := rfl lemma add_right_apply (x y : α) : (isometric.add_right x : α → α) y = y + x := rfl @[simp] lemma add_right_symm (x : α) : (isometric.add_right x).symm = isometric.add_right (-x) := ext $ λ y, rfl /-- Addition `y ↦ x + y` as an `isometry`. -/ protected def add_left (x : α) : α ≃ᵢ α := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_left _ _ _, to_equiv := equiv.add_left x } @[simp] lemma add_left_to_equiv (x : α) : (isometric.add_left x).to_equiv = equiv.add_left x := rfl @[simp] lemma coe_add_left (x : α) : ⇑(isometric.add_left x) = (+) x := rfl @[simp] lemma add_left_symm (x : α) : (isometric.add_left x).symm = isometric.add_left (-x) := ext $ λ y, rfl variable (α) /-- Negation `x ↦ -x` as an `isometry`. -/ protected def neg : α ≃ᵢ α := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ x y, dist_neg_neg _ _, to_equiv := equiv.neg α } variable {α} @[simp] lemma neg_symm : (isometric.neg α).symm = isometric.neg α := rfl @[simp] lemma neg_to_equiv : (isometric.neg α).to_equiv = equiv.neg α := rfl @[simp] lemma coe_neg : ⇑(isometric.neg α) = has_neg.neg := rfl end isometric theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] lemma normed_group.tendsto_nhds_nhds {f : α → β} {x : α} {y : β} : tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε := by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm] lemma normed_group.cauchy_seq_iff {u : ℕ → α} : cauchy_seq u ↔ ∀ ε > 0, ∃ N, ∀ m n, N ≤ m → N ≤ n → ∥u m - u n∥ < ε := by simp [metric.cauchy_seq_iff, dist_eq_norm] lemma cauchy_seq.add {u v : ℕ → α} (hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (u + v) := begin rw normed_group.cauchy_seq_iff at *, intros ε ε_pos, rcases hu (ε/2) (half_pos ε_pos) with ⟨Nu, hNu⟩, rcases hv (ε/2) (half_pos ε_pos) with ⟨Nv, hNv⟩, use max Nu Nv, intros m n hm hn, replace hm := max_le_iff.mp hm, replace hn := max_le_iff.mp hn, calc ∥(u + v) m - (u + v) n∥ = ∥u m + v m - (u n + v n)∥ : rfl ... = ∥(u m - u n) + (v m - v n)∥ : by abel ... ≤ ∥u m - u n∥ + ∥v m - v n∥ : norm_add_le _ _ ... < ε : by linarith only [hNu m n hm.1 hn.1, hNv m n hm.2 hn.2] end open finset lemma cauchy_seq_sum_of_eventually_eq {u v : ℕ → α} {N : ℕ} (huv : ∀ n ≥ N, u n = v n) (hv : cauchy_seq (λ n, ∑ k in range (n+1), v k)) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin let d : ℕ → α := λ n, ∑ k in range (n + 1), (u k - v k), rw show (λ n, ∑ k in range (n + 1), u k) = d + (λ n, ∑ k in range (n + 1), v k), by { ext n, simp [d] }, have : ∀ n ≥ N, d n = d N, { intros n hn, dsimp [d], rw eventually_constant_sum _ hn, intros m hm, simp [huv m hm] }, exact (tendsto_at_top_of_eventually_const this).cauchy_seq.add hv end /-- A homomorphism `f` of seminormed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of (semi)normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.lipschitz_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (real.to_nnreal C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma lipschitz_on_with_iff_norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} : lipschitz_on_with C f s ↔ ∀ (x ∈ s) (y ∈ s), ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm] lemma lipschitz_on_with.norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} (h : lipschitz_on_with C f s) {x y : α} (x_in : x ∈ s) (y_in : y ∈ s) : ∥f x - f y∥ ≤ C * ∥x - y∥ := lipschitz_on_with_iff_norm_sub_le.mp h x x_in y y_in /-- A homomorphism `f` of seminormed groups is continuous, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.continuous_of_bound (f : α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous lemma is_compact.exists_bound_of_continuous_on {γ : Type*} [topological_space γ] {s : set γ} (hs : is_compact s) {f : γ → α} (hf : continuous_on f s) : ∃ C, ∀ x ∈ s, ∥f x∥ ≤ C := begin have : bounded (f '' s) := (hs.image_of_continuous_on hf).bounded, rcases bounded_iff_forall_norm_le.1 this with ⟨C, hC⟩, exact ⟨C, λ x hx, hC _ (set.mem_image_of_mem _ hx)⟩, end lemma add_monoid_hom.isometry_iff_norm (f : α →+ β) : isometry f ↔ ∀ x, ∥f x∥ = ∥x∥ := begin simp only [isometry_emetric_iff_metric, dist_eq_norm, ← f.map_sub], refine ⟨λ h x, _, λ h x y, h _⟩, simpa using h x 0 end lemma add_monoid_hom.isometry_of_norm (f : α →+ β) (hf : ∀ x, ∥f x∥ = ∥x∥) : isometry f := f.isometry_iff_norm.2 hf lemma controlled_sum_of_mem_closure {s : add_subgroup α} {g : α} (hg : g ∈ closure (s : set α)) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ v : ℕ → α, tendsto (λ n, ∑ i in range (n+1), v i) at_top (𝓝 g) ∧ (∀ n, v n ∈ s) ∧ ∥v 0 - g∥ < b 0 ∧ ∀ n > 0, ∥v n∥ < b n := begin obtain ⟨u : ℕ → α, u_in : ∀ n, u n ∈ s, lim_u : tendsto u at_top (𝓝 g)⟩ := mem_closure_iff_seq_limit.mp hg, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ∀ n ≥ n₀, ∥u n - g∥ < b 0, { have : {x | ∥x - g∥ < b 0} ∈ 𝓝 g, { simp_rw ← dist_eq_norm, exact metric.ball_mem_nhds _ (b_pos _) }, exact filter.tendsto_at_top'.mp lim_u _ this }, set z : ℕ → α := λ n, u (n + n₀), have lim_z : tendsto z at_top (𝓝 g) := lim_u.comp (tendsto_add_at_top_nat n₀), have mem_𝓤 : ∀ n, {p : α × α | ∥p.1 - p.2∥ < b (n + 1)} ∈ 𝓤 α := λ n, by simpa [← dist_eq_norm] using metric.dist_mem_uniformity (b_pos $ n+1), obtain ⟨φ : ℕ → ℕ, φ_extr : strict_mono φ, hφ : ∀ n, ∥z (φ $ n + 1) - z (φ n)∥ < b (n + 1)⟩ := lim_z.cauchy_seq.subseq_mem mem_𝓤, set w : ℕ → α := z ∘ φ, have hw : tendsto w at_top (𝓝 g), from lim_z.comp φ_extr.tendsto_at_top, set v : ℕ → α := λ i, if i = 0 then w 0 else w i - w (i - 1), refine ⟨v, tendsto.congr (finset.eq_sum_range_sub' w) hw , _, hn₀ _ (n₀.le_add_left _), _⟩, { rintro ⟨⟩, { change w 0 ∈ s, apply u_in }, { apply s.sub_mem ; apply u_in }, }, { intros l hl, obtain ⟨k, rfl⟩ : ∃ k, l = k+1, exact nat.exists_eq_succ_of_ne_zero (ne_of_gt hl), apply hφ }, end lemma controlled_sum_of_mem_closure_range {j : α →+ β} {h : β} (Hh : h ∈ (closure $ (j.range : set β))) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ g : ℕ → α, tendsto (λ n, ∑ i in range (n+1), j (g i)) at_top (𝓝 h) ∧ ∥j (g 0) - h∥ < b 0 ∧ ∀ n > 0, ∥j (g n)∥ < b n := begin rcases controlled_sum_of_mem_closure Hh b_pos with ⟨v, sum_v, v_in, hv₀, hv_pos⟩, choose g hg using v_in, change ∀ (n : ℕ), j (g n) = v n at hg, refine ⟨g, by simpa [← hg] using sum_v, by simpa [hg 0] using hv₀, λ n hn, by simpa [hg] using hv_pos n hn⟩ end section nnnorm /-- Auxiliary class, endowing a type `α` with a function `nnnorm : α → ℝ≥0`. -/ class has_nnnorm (α : Type*) := (nnnorm : α → ℝ≥0) export has_nnnorm (nnnorm) notation `∥`e`∥₊` := nnnorm e @[priority 100] -- see Note [lower instance priority] instance semi_normed_group.to_has_nnnorm : has_nnnorm α := ⟨λ a, ⟨norm a, norm_nonneg a⟩⟩ @[simp, norm_cast] lemma coe_nnnorm (a : α) : (∥a∥₊ : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = ∥a - b∥₊ := nnreal.eq $ dist_eq_norm _ _ @[simp] lemma nnnorm_zero : ∥(0 : α)∥₊ = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : ∥g + h∥₊ ≤ ∥g∥₊ + ∥h∥₊ := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : ∥-g∥₊ = ∥g∥₊ := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist ∥g∥₊ ∥h∥₊ ≤ ∥g - h∥₊ := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (∥x∥₊ : ℝ≥0∞) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (∥x - y∥₊ : ℝ≥0∞) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (∥x∥₊ : ℝ≥0∞) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma mem_emetric_ball_0_iff {x : β} {r : ℝ≥0∞} : x ∈ emetric.ball (0 : β) r ↔ ↑∥x∥₊ < r := by rw [emetric.mem_ball, edist_eq_coe_nnnorm] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥₊ ≤ ∑ a in s, ∥f a∥₊ := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le end nnnorm lemma lipschitz_with.neg {α : Type*} [pseudo_emetric_space α] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma lipschitz_with.add {α : Type*} [pseudo_emetric_space α] {Kf : ℝ≥0} {f : α → β} (hf : lipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.sub {α : Type*} [pseudo_emetric_space α] {Kf : ℝ≥0} {f : α → β} (hf : lipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [pseudo_metric_space α] {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], rw le_div_iff (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end lemma antilipschitz_with.add_sub_lipschitz_with {α : Type*} [pseudo_metric_space α] {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg (g - f)) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ g := by simpa only [pi.sub_apply, add_sub_cancel'_right] using hf.add_lipschitz_with hg hK /-- A subgroup of a seminormed group is also a seminormed group, with the restriction of the norm. -/ instance add_subgroup.semi_normed_group {E : Type*} [semi_normed_group E] (s : add_subgroup E) : semi_normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. -/ @[simp] lemma coe_norm_subgroup {E : Type*} [semi_normed_group E] {s : add_subgroup E} (x : s) : ∥x∥ = ∥(x:E)∥ := rfl /-- A submodule of a seminormed group is also a seminormed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.semi_normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : semi_normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `E` is equal to its norm in `s`. See note [implicit instance arguments]. -/ @[simp, norm_cast] lemma submodule.norm_coe {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) : ∥(x : E)∥ = ∥x∥ := rfl @[simp] lemma submodule.norm_mk {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : E) (hx : x ∈ s) : ∥(⟨x, hx⟩ : s)∥ = ∥x∥ := rfl /-- seminormed group instance on the product of two seminormed groups, using the sup norm. -/ instance prod.semi_normed_group : semi_normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma prod.semi_norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnsemi_norm_def (x : α × β) : ∥x∥₊ = max (∥x.1∥₊) (∥x.2∥₊) := by { have := x.semi_norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma semi_norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma semi_norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma semi_norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- seminormed group instance on the product of finitely many seminormed groups, using the sup norm. -/ instance pi.semi_normed_group {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] : semi_normed_group (Πi, π i) := { norm := λf, ((finset.sup finset.univ (λ b, ∥f b∥₊) : ℝ≥0) : ℝ), dist_eq := assume x y, congr_arg (coe : ℝ≥0 → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = ∥x a - y a∥₊, from nndist_eq_nnnorm _ _ } /-- The seminorm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_semi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] /-- The seminorm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_semi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma semi_norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_semi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i @[simp] lemma pi_semi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnsemi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥₊ = ∥a∥₊ := nnreal.eq $ pi_semi_norm_const a lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥f e - b∥) a (𝓝 0) := by { convert tendsto_iff_dist_tendsto_zero, simp [dist_eq_norm] } lemma is_bounded_under_of_tendsto {l : filter ι} {f : ι → α} {c : α} (h : filter.tendsto f l (𝓝 c)) : is_bounded_under (≤) l (λ x, ∥f x∥) := ⟨∥c∥ + 1, @tendsto.eventually ι α f _ _ (λ k, ∥k∥ ≤ ∥c∥ + 1) h (filter.eventually_iff_exists_mem.mpr ⟨metric.closed_ball c 1, metric.closed_ball_mem_nhds c zero_lt_one, λ y hy, norm_le_norm_add_const_of_dist_le hy⟩)⟩ lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥f e∥) a (𝓝 0) := by { rw [tendsto_iff_norm_tendsto_zero], simp only [sub_zero] } /-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `g` which tends to `0`, then `f` tends to `0`. In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.ordered`, the `'` version is phrased using "eventually" and the non-`'` version is phrased absolutely. -/ lemma squeeze_zero_norm' {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ᶠ n in t₀, ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := tendsto_zero_iff_norm_tendsto_zero.mpr (squeeze_zero' (eventually_of_forall (λ n, norm_nonneg _)) h h') /-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which tends to `0`, then `f` tends to `0`. -/ lemma squeeze_zero_norm {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ (n:γ), ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero_norm' (eventually_of_forall h) h' lemma tendsto_norm_sub_self (x : α) : tendsto (λ g : α, ∥g - x∥) (𝓝 x) (𝓝 0) := by simpa [dist_eq_norm] using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (x:α)) (𝓝 x) _) lemma tendsto_norm {x : α} : tendsto (λg : α, ∥g∥) (𝓝 x) (𝓝 ∥x∥) := by simpa using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (0:α)) _ _) lemma tendsto_norm_zero : tendsto (λg : α, ∥g∥) (𝓝 0) (𝓝 0) := by simpa using tendsto_norm_sub_self (0:α) @[continuity] lemma continuous_norm : continuous (λg:α, ∥g∥) := by simpa using continuous_id.dist (continuous_const : continuous (λ g, (0:α))) @[continuity] lemma continuous_nnnorm : continuous (λ (a : α), ∥a∥₊) := continuous_subtype_mk _ continuous_norm lemma lipschitz_with_one_norm : lipschitz_with 1 (norm : α → ℝ) := by simpa only [dist_zero_left] using lipschitz_with.dist_right (0 : α) lemma uniform_continuous_norm : uniform_continuous (norm : α → ℝ) := lipschitz_with_one_norm.uniform_continuous lemma uniform_continuous_nnnorm : uniform_continuous (λ (a : α), ∥a∥₊) := uniform_continuous_subtype_mk uniform_continuous_norm _ section variables {l : filter γ} {f : γ → α} {a : α} lemma filter.tendsto.norm {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto_norm.comp h lemma filter.tendsto.nnnorm (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥₊) l (𝓝 (∥a∥₊)) := tendsto.comp continuous_nnnorm.continuous_at h end section variables [topological_space γ] {f : γ → α} {s : set γ} {a : γ} {b : α} lemma continuous.norm (h : continuous f) : continuous (λ x, ∥f x∥) := continuous_norm.comp h lemma continuous.nnnorm (h : continuous f) : continuous (λ x, ∥f x∥₊) := continuous_nnnorm.comp h lemma continuous_at.norm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥) a := h.norm lemma continuous_at.nnnorm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥₊) a := h.nnnorm lemma continuous_within_at.norm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥) s a := h.norm lemma continuous_within_at.nnnorm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥₊) s a := h.nnnorm lemma continuous_on.norm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥) s := λ x hx, (h x hx).norm lemma continuous_on.nnnorm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥₊) s := λ x hx, (h x hx).nnnorm end /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end /-- A seminormed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group α := ⟨(lipschitz_with.prod_fst.sub lipschitz_with.prod_snd).uniform_continuous⟩ @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : has_continuous_add α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference lemma nat.norm_cast_le [has_one α] : ∀ n : ℕ, ∥(n : α)∥ ≤ n * ∥(1 : α)∥ | 0 := by simp | (n + 1) := by { rw [n.cast_succ, n.cast_succ, add_mul, one_mul], exact norm_add_le_of_le (nat.norm_cast_le n) le_rfl } lemma semi_normed_group.mem_closure_iff {s : set α} {x : α} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, ∥x - y∥ < ε := by simp [metric.mem_closure_iff, dist_eq_norm] lemma norm_le_zero_iff' [separated_space α] {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := begin have : g = 0 ↔ g ∈ closure ({0} : set α), by simpa only [separated_space.out, mem_id_rel, sub_zero] using group_separation_rel g (0 : α), rw [this, semi_normed_group.mem_closure_iff], simp [forall_lt_iff_le'] end lemma norm_eq_zero_iff' [separated_space α] {g : α} : ∥g∥ = 0 ↔ g = 0 := begin conv_rhs { rw ← norm_le_zero_iff' }, split ; intro h, { rw h }, { exact le_antisymm h (norm_nonneg g) } end lemma norm_pos_iff' [separated_space α] {g : α} : 0 < ∥g∥ ↔ g ≠ 0 := begin rw lt_iff_le_and_ne, simp only [norm_nonneg, true_and], rw [ne_comm], exact not_iff_not_of_iff (norm_eq_zero_iff'), end end semi_normed_group section normed_group /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- The `semi_normed_group.core` induced by a `normed_group.core`. -/ lemma normed_group.core.to_semi_normed_group.core {α : Type*} [add_comm_group α] [has_norm α] (C : normed_group.core α) : semi_normed_group.core α := { norm_zero := (C.norm_eq_zero_iff 0).2 rfl, triangle := C.triangle, norm_neg := C.norm_neg } /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { eq_of_dist_eq_zero := λ x y h, begin rw [dist_eq_norm] at h, exact sub_eq_zero.mp ((C.norm_eq_zero_iff _).1 h) end ..semi_normed_group.of_core α (normed_group.core.to_semi_normed_group.core C) } variables [normed_group α] [normed_group β] @[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos @[simp] lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw [← dist_zero_right], exact dist_le_zero } lemma eq_of_norm_sub_le_zero {g h : α} (a : ∥g - h∥ ≤ 0) : g = h := by rwa [← sub_eq_zero, ← norm_le_zero_iff] lemma eq_of_norm_sub_eq_zero {u v : α} (h : ∥u - v∥ = 0) : u = v := begin apply eq_of_dist_eq_zero, rwa dist_eq_norm end lemma norm_sub_eq_zero_iff {u v : α} : ∥u - v∥ = 0 ↔ u = v := begin convert dist_eq_zero, rwa dist_eq_norm end @[simp] lemma nnnorm_eq_zero {a : α} : ∥a∥₊ = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] /-- A subgroup of a normed group is also a normed group, with the restriction of the norm. -/ instance add_subgroup.normed_group {E : Type*} [normed_group E] (s : add_subgroup E) : normed_group s := { ..add_subgroup.semi_normed_group s } /-- A submodule of a normed group is also a normed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { ..submodule.semi_normed_group s } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { ..prod.semi_normed_group } lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnnorm_def (x : α × β) : ∥x∥₊ = max (∥x.1∥₊) (∥x.2∥₊) := by { have := x.norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { ..pi.semi_normed_group } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] /-- The norm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i @[simp] lemma pi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnnorm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥₊ = ∥a∥₊ := nnreal.eq $ pi_norm_const a lemma tendsto_norm_nhds_within_zero : tendsto (norm : α → ℝ) (𝓝[{0}ᶜ] 0) (𝓝[set.Ioi 0] 0) := (continuous_norm.tendsto' (0 : α) 0 norm_zero).inf $ tendsto_principal_principal.2 $ λ x, norm_pos_iff.2 end normed_group section semi_normed_ring /-- A seminormed ring is a ring endowed with a seminorm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class semi_normed_ring (α : Type*) extends has_norm α, ring α, pseudo_metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A normed ring is a seminormed ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_semi_normed_ring [β : normed_ring α] : semi_normed_ring α := { ..β } /-- A seminormed commutative ring is a commutative ring endowed with a seminorm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class semi_normed_comm_ring (α : Type*) extends semi_normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A normed commutative ring is a commutative ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_comm_ring (α : Type*) extends normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A normed commutative ring is a seminormed commutative ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_comm_ring.to_semi_normed_comm_ring [β : normed_comm_ring α] : semi_normed_comm_ring α := { ..β } instance : normed_comm_ring punit := { norm_mul := λ _ _, by simp, ..punit.normed_group, ..punit.comm_ring, } /-- A mixin class with the axiom `∥1∥ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this axiom. -/ class norm_one_class (α : Type*) [has_norm α] [has_one α] : Prop := (norm_one : ∥(1:α)∥ = 1) export norm_one_class (norm_one) attribute [simp] norm_one @[simp] lemma nnnorm_one [semi_normed_group α] [has_one α] [norm_one_class α] : ∥(1 : α)∥₊ = 1 := nnreal.eq norm_one @[priority 100] -- see Note [lower instance priority] instance semi_normed_comm_ring.to_comm_ring [β : semi_normed_comm_ring α] : comm_ring α := { ..β } @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } @[priority 100] -- see Note [lower instance priority] instance semi_normed_ring.to_semi_normed_group [β : semi_normed_ring α] : semi_normed_group α := { ..β } instance prod.norm_one_class [normed_group α] [has_one α] [norm_one_class α] [normed_group β] [has_one β] [norm_one_class β] : norm_one_class (α × β) := ⟨by simp [prod.norm_def]⟩ variables [semi_normed_ring α] lemma norm_mul_le (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := semi_normed_ring.norm_mul _ _ /-- A subalgebra of a seminormed ring is also a seminormed ring, with the restriction of the norm. See note [implicit instance arguments]. -/ instance subalgebra.semi_normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜} {E : Type*} [semi_normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : semi_normed_ring s := { norm_mul := λ a b, norm_mul_le a.1 b.1, ..s.to_submodule.semi_normed_group } /-- A subalgebra of a normed ring is also a normed ring, with the restriction of the norm. See note [implicit instance arguments]. -/ instance subalgebra.normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜} {E : Type*} [normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : normed_ring s := { ..s.semi_normed_ring } lemma list.norm_prod_le' : ∀ {l : list α}, l ≠ [] → ∥l.prod∥ ≤ (l.map norm).prod | [] h := (h rfl).elim | [a] _ := by simp | (a :: b :: l) _ := begin rw [list.map_cons, list.prod_cons, @list.prod_cons _ _ _ ∥a∥], refine le_trans (norm_mul_le _ _) (mul_le_mul_of_nonneg_left _ (norm_nonneg _)), exact list.norm_prod_le' (list.cons_ne_nil b l) end lemma list.norm_prod_le [norm_one_class α] : ∀ l : list α, ∥l.prod∥ ≤ (l.map norm).prod | [] := by simp | (a::l) := list.norm_prod_le' (list.cons_ne_nil a l) lemma finset.norm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty) (f : ι → α) : ∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ := begin rcases s with ⟨⟨l⟩, hl⟩, have : l.map f ≠ [], by simpa using hs, simpa using list.norm_prod_le' this end lemma finset.norm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι) (f : ι → α) : ∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ := begin rcases s with ⟨⟨l⟩, hl⟩, simpa using (l.map f).norm_prod_le end /-- If `α` is a seminormed ring, then `∥a^n∥≤ ∥a∥^n` for `n > 0`. See also `norm_pow_le`. -/ lemma norm_pow_le' (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := by { rw [pow_succ _ (n+1), pow_succ _ (n+1)], exact le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le' (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) } /-- If `α` is a seminormed ring with `∥1∥=1`, then `∥a^n∥≤ ∥a∥^n`. See also `norm_pow_le'`. -/ lemma norm_pow_le [norm_one_class α] (a : α) : ∀ (n : ℕ), ∥a^n∥ ≤ ∥a∥^n | 0 := by simp | (n+1) := norm_pow_le' a n.zero_lt_succ lemma eventually_norm_pow_le (a : α) : ∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n := eventually_at_top.mpr ⟨1, λ b h, norm_pow_le' a (nat.succ_le_iff.mp h)⟩ /-- In a seminormed ring, the left-multiplication `add_monoid_hom` is bounded. -/ lemma mul_left_bound (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ := norm_mul_le x /-- In a seminormed ring, the right-multiplication `add_monoid_hom` is bounded. -/ lemma mul_right_bound (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ := λ y, by {rw mul_comm, convert norm_mul_le y x} /-- Seminormed ring structure on the product of two seminormed rings, using the sup norm. -/ instance prod.semi_normed_ring [semi_normed_ring β] : semi_normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp [max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.semi_normed_group } end semi_normed_ring section normed_ring variables [normed_ring α] lemma units.norm_pos [nontrivial α] (x : units α) : 0 < ∥(x:α)∥ := norm_pos_iff.mpr (units.ne_zero x) /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring β] : normed_ring (α × β) := { norm_mul := norm_mul_le, ..prod.semi_normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance semi_normed_ring_top_monoid [semi_normed_ring α] : has_continuous_mul α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ begin have : ∀ e : α × α, ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥, { intro e, calc ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1 * (e.2 - x.2) + (e.1 - x.1) * x.2∥ : by rw [mul_sub, sub_mul, sub_add_sub_cancel] ... ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥ : norm_add_le_of_le (norm_mul_le _ _) (norm_mul_le _ _) }, refine squeeze_zero (λ e, norm_nonneg _) this _, convert ((continuous_fst.tendsto x).norm.mul ((continuous_snd.tendsto x).sub tendsto_const_nhds).norm).add (((continuous_fst.tendsto x).sub tendsto_const_nhds).norm.mul _), show tendsto _ _ _, from tendsto_const_nhds, simp end ⟩ /-- A seminormed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance semi_normed_top_ring [semi_normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply tendsto_norm_sub_self ⟩ /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) namespace normed_field section normed_field variables [normed_field α] @[simp] lemma norm_mul (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b @[priority 100] -- see Note [lower instance priority] instance to_normed_comm_ring : normed_comm_ring α := { norm_mul := λ a b, (norm_mul a b).le, ..‹normed_field α› } @[priority 900] instance to_norm_one_class : norm_one_class α := ⟨mul_left_cancel' (mt norm_eq_zero.1 (@one_ne_zero α _ _)) $ by rw [← norm_mul, mul_one, mul_one]⟩ @[simp] lemma nnnorm_mul (a b : α) : ∥a * b∥₊ = ∥a∥₊ * ∥b∥₊ := nnreal.eq $ norm_mul a b /-- `norm` as a `monoid_hom`. -/ @[simps] def norm_hom : monoid_with_zero_hom α ℝ := ⟨norm, norm_zero, norm_one, norm_mul⟩ /-- `nnnorm` as a `monoid_hom`. -/ @[simps] def nnnorm_hom : monoid_with_zero_hom α ℝ≥0 := ⟨nnnorm, nnnorm_zero, nnnorm_one, nnnorm_mul⟩ @[simp] lemma norm_pow (a : α) : ∀ (n : ℕ), ∥a ^ n∥ = ∥a∥ ^ n := (norm_hom.to_monoid_hom : α →* ℝ).map_pow a @[simp] lemma nnnorm_pow (a : α) (n : ℕ) : ∥a ^ n∥₊ = ∥a∥₊ ^ n := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_pow a n @[simp] lemma norm_prod (s : finset β) (f : β → α) : ∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ := (norm_hom.to_monoid_hom : α →* ℝ).map_prod f s @[simp] lemma nnnorm_prod (s : finset β) (f : β → α) : ∥∏ b in s, f b∥₊ = ∏ b in s, ∥f b∥₊ := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_prod f s @[simp] lemma norm_div (a b : α) : ∥a / b∥ = ∥a∥ / ∥b∥ := (norm_hom : monoid_with_zero_hom α ℝ).map_div a b @[simp] lemma nnnorm_div (a b : α) : ∥a / b∥₊ = ∥a∥₊ / ∥b∥₊ := (nnnorm_hom : monoid_with_zero_hom α ℝ≥0).map_div a b @[simp] lemma norm_inv (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := (norm_hom : monoid_with_zero_hom α ℝ).map_inv' a @[simp] lemma nnnorm_inv (a : α) : ∥a⁻¹∥₊ = ∥a∥₊⁻¹ := nnreal.eq $ by simp @[simp] lemma norm_fpow : ∀ (a : α) (n : ℤ), ∥a^n∥ = ∥a∥^n := (norm_hom : monoid_with_zero_hom α ℝ).map_fpow @[simp] lemma nnnorm_fpow : ∀ (a : α) (n : ℤ), ∥a ^ n∥₊ = ∥a∥₊ ^ n := (nnnorm_hom : monoid_with_zero_hom α ℝ≥0).map_fpow @[priority 100] -- see Note [lower instance priority] instance : has_continuous_inv' α := begin refine ⟨λ r r0, tendsto_iff_norm_tendsto_zero.2 _⟩, have r0' : 0 < ∥r∥ := norm_pos_iff.2 r0, rcases exists_between r0' with ⟨ε, ε0, εr⟩, have : ∀ᶠ e in 𝓝 r, ∥e⁻¹ - r⁻¹∥ ≤ ∥r - e∥ / ∥r∥ / ε, { filter_upwards [(is_open_lt continuous_const continuous_norm).eventually_mem εr], intros e he, have e0 : e ≠ 0 := norm_pos_iff.1 (ε0.trans he), calc ∥e⁻¹ - r⁻¹∥ = ∥r - e∥ / ∥r∥ / ∥e∥ : by field_simp [mul_comm] ... ≤ ∥r - e∥ / ∥r∥ / ε : div_le_div_of_le_left (div_nonneg (norm_nonneg _) (norm_nonneg _)) ε0 he.le }, refine squeeze_zero' (eventually_of_forall $ λ _, norm_nonneg _) this _, refine (continuous_const.sub continuous_id).norm.div_const.div_const.tendsto' _ _ _, simp end end normed_field variables (α) [nondiscrete_normed_field α] lemma exists_one_lt_norm : ∃x : α, 1 < ∥x∥ := ‹nondiscrete_normed_field α›.non_trivial lemma exists_norm_lt_one : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], rintro rfl, rw norm_zero at hy, exact lt_asymm zero_lt_one hy }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ variable {α} @[instance] lemma punctured_nhds_ne_bot (x : α) : ne_bot (𝓝[{x}ᶜ] x) := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end @[instance] lemma nhds_within_is_unit_ne_bot : ne_bot (𝓝[{x : α | is_unit x}] 0) := by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α) end normed_field instance : normed_field ℝ := { norm_mul' := abs_mul, .. real.normed_group } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } namespace real lemma norm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥ = x := abs_of_nonneg hx @[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg @[simp] lemma nnnorm_coe_nat (n : ℕ) : ∥(n : ℝ)∥₊ = n := nnreal.eq $ by simp @[simp] lemma norm_two : ∥(2 : ℝ)∥ = 2 := abs_of_pos (@zero_lt_two ℝ _ _) @[simp] lemma nnnorm_two : ∥(2 : ℝ)∥₊ = 2 := nnreal.eq $ by simp lemma nnnorm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥₊ = ⟨x, hx⟩ := nnreal.eq $ norm_of_nonneg hx lemma ennnorm_eq_of_real {x : ℝ} (hx : 0 ≤ x) : (∥x∥₊ : ℝ≥0∞) = ennreal.of_real x := by { rw [← of_real_norm_eq_coe_nnnorm, norm_of_nonneg hx] } end real namespace nnreal open_locale nnreal @[simp] lemma norm_eq (x : ℝ≥0) : ∥(x : ℝ)∥ = x := by rw [real.norm_eq_abs, x.abs_eq] @[simp] lemma nnnorm_eq (x : ℝ≥0) : ∥(x : ℝ)∥₊ = x := nnreal.eq $ real.norm_of_nonneg x.2 end nnreal @[simp] lemma norm_norm [semi_normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := real.norm_of_nonneg (norm_nonneg _) @[simp] lemma nnnorm_norm [semi_normed_group α] (a : α) : ∥∥a∥∥₊ = ∥a∥₊ := by simpa [real.nnnorm_of_nonneg (norm_nonneg a)] /-- A restatement of `metric_space.tendsto_at_top` in terms of the norm. -/ lemma normed_group.tendsto_at_top [nonempty α] [semilattice_sup α] {β : Type*} [semi_normed_group β] {f : α → β} {b : β} : tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N ≤ n → ∥f n - b∥ < ε := (at_top_basis.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm]) /-- A variant of `normed_group.tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ lemma normed_group.tendsto_at_top' [nonempty α] [semilattice_sup α] [no_top_order α] {β : Type*} [semi_normed_group β] {f : α → β} {b : β} : tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N < n → ∥f n - b∥ < ε := (at_top_basis_Ioi.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm]) instance : normed_comm_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub], mul_comm := mul_comm } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl lemma int.norm_eq_abs (n : ℤ) : ∥n∥ = abs n := rfl lemma nnreal.coe_nat_abs (n : ℤ) : (n.nat_abs : ℝ≥0) = ∥n∥₊ := nnreal.eq $ calc ((n.nat_abs : ℝ≥0) : ℝ) = (n.nat_abs : ℤ) : by simp only [int.cast_coe_nat, nnreal.coe_nat_cast] ... = abs n : by simp only [← int.abs_eq_nat_abs, int.cast_abs] ... = ∥n∥ : rfl instance : norm_one_class ℤ := ⟨by simp [← int.norm_cast_real]⟩ instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast -- Now that we've installed the norm on `ℤ`, -- we can state some lemmas about `nsmul` and `gsmul`. section variables [semi_normed_group α] lemma norm_nsmul_le (n : ℕ) (a : α) : ∥n • a∥ ≤ n * ∥a∥ := begin induction n with n ih, { simp only [norm_zero, nat.cast_zero, zero_mul, zero_smul] }, simp only [nat.succ_eq_add_one, add_smul, add_mul, one_mul, nat.cast_add, nat.cast_one, one_nsmul], exact norm_add_le_of_le ih le_rfl end lemma norm_gsmul_le (n : ℤ) (a : α) : ∥n • a∥ ≤ ∥n∥ * ∥a∥ := begin induction n with n n, { simp only [int.of_nat_eq_coe, gsmul_coe_nat], convert norm_nsmul_le n a, exact nat.abs_cast n }, { simp only [int.neg_succ_of_nat_coe, neg_smul, norm_neg, gsmul_coe_nat], convert norm_nsmul_le n.succ a, exact nat.abs_cast n.succ, } end lemma nnnorm_nsmul_le (n : ℕ) (a : α) : ∥n • a∥₊ ≤ n * ∥a∥₊ := by simpa only [←nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_nat_cast] using norm_nsmul_le n a lemma nnnorm_gsmul_le (n : ℤ) (a : α) : ∥n • a∥₊ ≤ ∥n∥₊ * ∥a∥₊ := by simpa only [←nnreal.coe_le_coe, nnreal.coe_mul] using norm_gsmul_le n a end section semi_normed_space section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[semi_normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A seminormed space over a normed field is a vector space endowed with a seminorm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class semi_normed_space (α : Type*) (β : Type*) [normed_field α] [semi_normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) /-- A normed space is a seminormed space. -/ @[priority 100] -- see Note [lower instance priority] instance normed_space.to_semi_normed_space [normed_field α] [normed_group β] [γ : normed_space α β] : semi_normed_space α β := { ..γ } end prio variables [normed_field α] [semi_normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) } lemma norm_smul [semi_normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin by_cases h : s = 0, { simp [h] }, { refine le_antisymm (semi_normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : mul_le_mul_of_nonneg_left (semi_normed_space.norm_smul_le _ _) (norm_nonneg _) ... = ∥s • x∥ : by rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel (mt norm_eq_zero.1 h), one_mul] } end @[simp] lemma abs_norm_eq_norm (z : β) : abs ∥z∥ = ∥z∥ := (abs_eq (norm_nonneg z)).mpr (or.inl rfl) lemma dist_smul [semi_normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [semi_normed_space α β] (s : α) (x : β) : ∥s • x∥₊ = ∥s∥₊ * ∥x∥₊ := nnreal.eq $ norm_smul s x lemma nndist_smul [semi_normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = ∥s∥₊ * nndist x y := nnreal.eq $ dist_smul s x y lemma norm_smul_of_nonneg [semi_normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} [semi_normed_group E] [semi_normed_space α E] variables {F : Type*} [semi_normed_group F] [semi_normed_space α F] @[priority 100] -- see Note [lower instance priority] instance semi_normed_space.has_continuous_smul : has_continuous_smul α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end theorem eventually_nhds_norm_smul_sub_lt (c : α) (x : E) {ε : ℝ} (h : 0 < ε) : ∀ᶠ y in 𝓝 x, ∥c • (y - x)∥ < ε := have tendsto (λ y, ∥c • (y - x)∥) (𝓝 x) (𝓝 0), from (continuous_const.smul (continuous_id.sub continuous_const)).norm.tendsto' _ _ (by simp), this.eventually (gt_mem_nhds h) theorem closure_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_lt_one ℝ _ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, apply mul_lt_mul'; assumption } end theorem frontier_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (closed_ball x r) = ball x r := begin refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem frontier_closed_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] variables (α) lemma ne_neg_of_mem_sphere [char_zero α] {r : ℝ} (hr : 0 < r) (x : sphere (0:E) r) : x ≠ - x := λ h, nonzero_of_mem_sphere hr x (eq_zero_of_eq_neg α (by { conv_lhs {rw h}, simp })) lemma ne_neg_of_mem_unit_sphere [char_zero α] (x : sphere (0:E) 1) : x ≠ - x := ne_neg_of_mem_sphere α (by norm_num) x variables {α} open normed_field /-- The product of two seminormed spaces is a seminormed space, with the sup norm. -/ instance prod.semi_normed_space : semi_normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.semi_norm_def, norm_smul, mul_max_of_nonneg], ..prod.normed_group, ..prod.module } /-- The product of finitely many seminormed spaces is a seminormed space, with the sup norm. -/ instance pi.semi_normed_space {E : ι → Type*} [fintype ι] [∀i, semi_normed_group (E i)] [∀i, semi_normed_space α (E i)] : semi_normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), ∥a • f b∥₊)) : ℝ) = ∥a∥₊ * ↑(finset.sup finset.univ (λ (b : ι), ∥f b∥₊)), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a seminormed space is also a normed space, with the restriction of the norm. -/ instance submodule.semi_normed_space {𝕜 R : Type*} [has_scalar 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [semi_normed_group E] [semi_normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : semi_normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } /-- If there is a scalar `c` with `∥c∥>1`, then any element of with norm different from `0` can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell_semi_normed {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : ∥x∥ ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos ((ne.symm hx).le_iff_lt.1 (norm_nonneg x)) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ < ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_fpow], exact (div_lt_iff εpos).1 (hn.2) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), gpow_one, mul_inv_rev', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), gpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end end semi_normed_space section normed_space variables [normed_field α] variables {E : Type*} [normed_group E] [normed_space α E] variables {F : Type*} [normed_group F] [normed_space α F] open normed_field theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] }, { suffices : x ∉ interior {x}, { rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff], intros y hy, obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy), exact this hy }, rw [← set.mem_compl_iff, ← closure_compl], rcases exists_ne (0 : E) with ⟨z, hz⟩, suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E), by simpa only [zero_smul, add_zero] using this, have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi], refine (continuous_const.add (continuous_id.smul continuous_const)).continuous_within_at.mem_closure this _, intros c hc, simp [smul_eq_zero, hz, ne_of_gt hc] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] variables {α} /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := rescale_to_shell_semi_normed hc εpos (ne_of_lt (norm_pos_iff.2 hx)).symm /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { ..prod.semi_normed_space } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { ..pi.semi_normed_space } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 R : Type*} [has_scalar 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [normed_group E] [normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : normed_space 𝕜 s := { ..submodule.semi_normed_space s } end normed_space section normed_algebra /-- A seminormed algebra `𝕜'` over `𝕜` is an algebra endowed with a seminorm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class semi_normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) /-- A normed algebra is a seminormed algebra. -/ @[priority 100] -- see Note [lower instance priority] instance normed_algebra.to_semi_normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : semi_normed_algebra 𝕜 𝕜' := { norm_algebra_map_eq := normed_algebra.norm_algebra_map_eq } @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [h : semi_normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := semi_normed_algebra.norm_algebra_map_eq _ /-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/ lemma algebra_map_isometry (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [semi_normed_algebra 𝕜 𝕜'] : isometry (algebra_map 𝕜 𝕜') := begin refine isometry_emetric_iff_metric.2 (λx y, _), rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map_eq], end variables (𝕜 : Type*) [normed_field 𝕜] variables (𝕜' : Type*) [semi_normed_ring 𝕜'] @[priority 100] instance semi_normed_algebra.to_semi_normed_space [h : semi_normed_algebra 𝕜 𝕜'] : semi_normed_space 𝕜 𝕜' := { norm_smul_le := λ s x, calc ∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl } ... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : semi_normed_ring.norm_mul _ _ ... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq, ..h } @[priority 100] instance normed_algebra.to_normed_space (𝕜 : Type*) [normed_field 𝕜] (𝕜' : Type*) [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := { norm_smul_le := semi_normed_space.norm_smul_le, ..h } instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { norm_algebra_map_eq := by simp, .. algebra.id 𝕜} variables (𝕜') [semi_normed_algebra 𝕜 𝕜'] include 𝕜 lemma normed_algebra.norm_one : ∥(1:𝕜')∥ = 1 := by simpa using (norm_algebra_map_eq 𝕜' (1:𝕜)) lemma normed_algebra.norm_one_class : norm_one_class 𝕜' := ⟨normed_algebra.norm_one 𝕜 𝕜'⟩ lemma normed_algebra.zero_ne_one : (0:𝕜') ≠ 1 := begin refine (ne_zero_of_norm_pos _).symm, rw normed_algebra.norm_one 𝕜 𝕜', norm_num, end lemma normed_algebra.nontrivial : nontrivial 𝕜' := ⟨⟨0, 1, normed_algebra.zero_ne_one 𝕜 𝕜'⟩⟩ end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [normed_group E] [normed_space 𝕜' E] (F : Type*) [semi_normed_group F] [semi_normed_space 𝕜' F] /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` instead. `𝕜`-seminormed space structure induced by a `𝕜'`-seminormed space structure when `𝕜'` is a seminormed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `module.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def semi_normed_space.restrict_scalars : semi_normed_space 𝕜 F := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..restrict_scalars.module 𝕜 𝕜' F } /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` instead. `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `module.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..restrict_scalars.module 𝕜 𝕜' E } instance {𝕜 : Type*} {𝕜' : Type*} {F : Type*} [I : semi_normed_group F] : semi_normed_group (restrict_scalars 𝕜 𝕜' F) := I instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] : normed_group (restrict_scalars 𝕜 𝕜' E) := I instance module.restrict_scalars.semi_normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {F : Type*} [normed_field 𝕜'] [semi_normed_group F] [I : semi_normed_space 𝕜' F] : semi_normed_space 𝕜' (restrict_scalars 𝕜 𝕜' F) := I instance module.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I instance : semi_normed_space 𝕜 (restrict_scalars 𝕜 𝕜' F) := (semi_normed_space.restrict_scalars 𝕜 𝕜' F : semi_normed_space 𝕜 F) instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := (normed_space.restrict_scalars 𝕜 𝕜' E : normed_space 𝕜 E) end restrict_scalars section summable open_locale classical open finset filter variables [semi_normed_group α] [semi_normed_group β] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := begin rw [cauchy_seq_finset_iff_vanishing, nhds_basis_ball.forall_iff], { simp only [ball_0_eq, set.mem_set_of_eq] }, { rintros s t hst ⟨s', hs'⟩, exact ⟨s', λ t' ht', hst $ hs' _ ht'⟩ } end lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥∑ i in t, g i∥ < ε := hs t ht, have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, ∑ a in s, f a) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : γ → finset ι} {p : filter γ} [ne_bot p] (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf tendsto_finset_range h⟩ /-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded [complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } lemma has_sum.norm_le_of_bounded {f : ι → α} {g : ι → ℝ} {a : α} {b : ℝ} (hf : has_sum f a) (hg : has_sum g b) (h : ∀ i, ∥f i∥ ≤ g i) : ∥a∥ ≤ b := le_of_tendsto_of_tendsto' hf.norm hg $ λ s, norm_sum_le_of_le _ $ λ i hi, h i /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥∑' i, f i∥ ≤ ∑' i, g i`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_norm_bounded {f : ι → α} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a) (h : ∀ i, ∥f i∥ ≤ g i) : ∥∑' i : ι, f i∥ ≤ a := begin by_cases hf : summable f, { exact hf.has_sum.norm_le_of_bounded hg h }, { rw [tsum_eq_zero_of_not_summable hf, norm_zero], exact ge_of_tendsto' hg (λ s, sum_nonneg $ λ i hi, (norm_nonneg _).trans (h i)) } end /-- If `∑' i, ∥f i∥` is summable, then `∥∑' i, f i∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥∑' i, f i∥ ≤ ∑' i, ∥f i∥ := tsum_of_norm_bounded hf.has_sum $ λ i, le_rfl /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `nnnorm (f i) ≤ g i`, then `nnnorm (∑' i, f i) ≤ ∑' i, g i`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_nnnorm_bounded {f : ι → α} {g : ι → ℝ≥0} {a : ℝ≥0} (hg : has_sum g a) (h : ∀ i, nnnorm (f i) ≤ g i) : nnnorm (∑' i : ι, f i) ≤ a := begin simp only [← nnreal.coe_le_coe, ← nnreal.has_sum_coe, coe_nnnorm] at *, exact tsum_of_norm_bounded hg h end /-- If `∑' i, nnnorm (f i)` is summable, then `nnnorm (∑' i, f i) ≤ ∑' i, nnnorm (f i)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma nnnorm_tsum_le {f : ι → α} (hf : summable (λi, nnnorm (f i))) : nnnorm (∑' i, f i) ≤ ∑' i, nnnorm (f i) := tsum_of_nnnorm_bounded hf.has_sum (λ i, le_rfl) variable [complete_space α] /-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded_eventually {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : summable f := begin replace h := mem_cofinite.1 h, refine h.summable_compl_iff.mp _, refine summable_of_norm_bounded _ (h.summable_compl_iff.mpr hg) _, rintros ⟨a, h'⟩, simpa using h' end lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → ℝ≥0) (hg : summable g) (h : ∀i, ∥f i∥₊ ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λ a, ∥f a∥₊)) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable namespace uniform_space namespace completion variables (V : Type*) instance [uniform_space V] [has_norm V] : has_norm (completion V) := { norm := completion.extension has_norm.norm } @[simp] lemma norm_coe {V} [semi_normed_group V] (v : V) : ∥(v : completion V)∥ = ∥v∥ := completion.extension_coe uniform_continuous_norm v instance [semi_normed_group V] : normed_group (completion V) := { dist_eq := begin intros x y, apply completion.induction_on₂ x y; clear x y, { refine is_closed_eq (completion.uniform_continuous_extension₂ _).continuous _, exact continuous.comp completion.continuous_extension continuous_sub }, { intros x y, rw [← completion.coe_sub, norm_coe, metric.completion.dist_eq, dist_eq_norm] } end, .. (show add_comm_group (completion V), by apply_instance), .. (show metric_space (completion V), by apply_instance) } end completion end uniform_space
d6c62c5bb68996a1b30bafc1b13273bb02f9f0af
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.15.lean
58546623931ffd671a5ce74c7d07363221743197
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
73
lean
import standard definition pr1 [reducible] (A : Type) (a b : A) : A := a
c21edcc0e3a6419761d65213b1aa15a5e185fe0f
c777c32c8e484e195053731103c5e52af26a25d1
/src/field_theory/ax_grothendieck.lean
7cec7336d2e9faea04dd1e9dbd81247b6a05ddb2
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
3,106
lean
/- Copyright (c) 2023 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.mv_polynomial.basic import ring_theory.algebraic import data.fintype.card /-! # Ax-Grothendieck for algebraic extensions of `zmod p` This file proves that if `R` is an algebraic extension of a finite field, then any injective polynomial map `R^n -> R^n` is also surjective. This proof is required for the true Ax-Grothendieck theorem, which proves the same result for any algebraically closed field of characteristic zero. ## TODO The proof of the theorem for characteristic zero is not in mathlib, but it is at https://github.com/Jlh18/ModelTheoryInLean8 -/ noncomputable theory open mv_polynomial finset function /-- Any injective polynomial map over an algebraic extension of a finite field is surjective. -/ lemma ax_grothendieck_of_locally_finite {ι K R : Type*} [field K] [finite K] [comm_ring R] [finite ι] [algebra K R] (alg : algebra.is_algebraic K R) (ps : ι → mv_polynomial ι R) (hinj : injective (λ v i, eval v (ps i))) : surjective (λ v i, eval v (ps i)) := begin have is_int : ∀ x : R, is_integral K x, from λ x, is_algebraic_iff_is_integral.1 (alg x), classical, intros v, casesI nonempty_fintype ι, /- `s` is the set of all coefficients of the polynomial, as well as all of the coordinates of `v`, the point I am trying to find the preimage of. -/ let s : finset R := finset.bUnion (univ : finset ι) (λ i, (ps i).support.image (λ x, coeff x (ps i))) ∪ (univ : finset ι).image v, have hv : ∀ i, v i ∈ algebra.adjoin K (s : set R), from λ j, algebra.subset_adjoin (mem_union_right _ (mem_image.2 ⟨j, mem_univ _, rfl⟩)), have hs₁ : ∀ (i : ι) (k : ι →₀ ℕ), k ∈ (ps i).support → coeff k (ps i) ∈ algebra.adjoin K (s : set R), from λ i k hk, algebra.subset_adjoin (mem_union_left _ (mem_bUnion.2 ⟨i, mem_univ _, mem_image_of_mem _ hk⟩)), have hs : ∀ i, mv_polynomial.eval v (ps i) ∈ algebra.adjoin K (s : set R), from λ i, eval_mem (hs₁ _) hv, letI := is_noetherian_adjoin_finset s (λ x _, is_int x), letI := module.is_noetherian.finite K (algebra.adjoin K (s : set R)), letI : finite (algebra.adjoin K (s : set R)) := finite_dimensional.finite_of_finite K (algebra.adjoin K (s : set R)), /- The restriction of the polynomial map, `ps`, to the subalgebra generated by `s` -/ let res : (ι → algebra.adjoin K (s : set R)) → (ι → algebra.adjoin K (s : set R)) := λ x i, ⟨eval (λ j : ι, (x j : R)) (ps i), eval_mem (hs₁ _) (λ i, (x i).2)⟩, have hres_inj : injective res, { intros x y hxy, ext i, simp only [res, subtype.ext_iff, funext_iff] at hxy, exact congr_fun (hinj (funext hxy)) i }, have hres_surj : surjective res, from finite.injective_iff_surjective.1 hres_inj, cases hres_surj (λ i, ⟨v i, hv i⟩) with w hw, use λ i, w i, simpa only [res, subtype.ext_iff, funext_iff] using hw, end
916be6aa5d741ab9bd984bffd1bc57f81f7786f4
26ac254ecb57ffcb886ff709cf018390161a9225
/test/library_search/basic.lean
469581490b4d3ea86a347efa56019924b5c15411
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
4,755
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.suggest -- No other imports, for fast testing /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true /- For debugging purposes, we can display the list of lemmas: -/ -- set_option trace.suggest true namespace test.library_search -- Check that `library_search` fails if there are no goals. example : true := begin trivial, success_if_fail { library_search }, end -- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't -- even needed. example (P : Prop) (p : P) : P := by library_search example (P : Prop) (p : P) (np : ¬P) : false := by library_search example (X : Type) (P : Prop) (x : X) (h : Π x : X, x = x → P) : P := by library_search example (α : Prop) : α → α := by library_search -- says: `exact id` example (p : Prop) [decidable p] : (¬¬p) → p := by library_search -- says: `exact not_not.mp` example (a b : Prop) (h : a ∧ b) : a := by library_search -- says: `exact h.left` example (P Q : Prop) [decidable P] [decidable Q]: (¬ Q → ¬ P) → (P → Q) := by library_search -- says: `exact not_imp_not.mp` example (a b : ℕ) : a + b = b + a := by library_search -- says: `exact add_comm a b` example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- says: `exact nat.mul_sub_left_distrib n m k` example (n m k : ℕ) : n * m - n * k = n * (m - k) := by library_search -- says: `exact eq.symm (nat.mul_sub_left_distrib n m k)` example {α : Type} (x y : α) : x = y ↔ y = x := by library_search -- says: `exact eq_comm` example (a b : ℕ) (ha : 0 < a) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` section synonym -- Synonym `>` for `<` in another part of the goal example (a b : ℕ) (ha : a > 0) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : a ≤ b := by library_search -- says: `exact nat.le_of_dvd w h` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : b ≥ a := by library_search -- says: `exact nat.le_of_dvd w h` -- A lemma with head symbol `¬` can be used to prove `¬ p` or `⊥` example (a : ℕ) : ¬ (a < 0) := by library_search -- says `exact not_lt_bot` example (a : ℕ) (h : a < 0) : false := by library_search -- says `exact not_lt_bot h` -- An inductive type hides the constructor's arguments enough -- so that `library_search` doesn't accidentally close the goal. inductive P : ℕ → Prop | gt_in_head {n : ℕ} : n < 0 → P n -- This lemma with `>` as its head symbol should also be found for goals with head symbol `<`. lemma lemma_with_gt_in_head (a : ℕ) (h : P a) : 0 > a := by { cases h, assumption } -- This lemma with `false` as its head symbols should also be found for goals with head symbol `¬`. lemma lemma_with_false_in_head (a b : ℕ) (h1 : a < b) (h2 : P a) : false := by { apply nat.not_lt_zero, cases h2, assumption } example (a : ℕ) (h : P a) : 0 > a := by library_search -- says `exact lemma_with_gt_in_head a h` example (a : ℕ) (h : P a) : a < 0 := by library_search -- says `exact lemma_with_gt_in_head a h` example (a b : ℕ) (h1 : a < b) (h2 : P a) : false := by library_search -- says `exact lemma_with_false_in_head a b h1 h2` example (a b : ℕ) (h1 : a < b) : ¬ (P a) := by library_search! -- says `exact lemma_with_false_in_head a b h1` end synonym -- We even find `iff` results: example : ∀ P : Prop, ¬(P ↔ ¬P) := by library_search! -- says: `λ (a : Prop), (iff_not_self a).mp` example {a b c : ℕ} (h₁ : a ∣ c) (h₂ : a ∣ b + c) : a ∣ b := by library_search -- says `exact (nat.dvd_add_left h₁).mp h₂` -- Checking examples from issue #2220 example {α : Sort*} (h : empty) : α := by library_search example {α : Type*} (h : empty) : α := by library_search def map_from_sum {A B C : Type} (f : A → C) (g : B → C) : (A ⊕ B) → C := by library_search -- Test that we can provide custom `apply` tactics, -- e.g. to change how aggressively we unfold definitions in trying to apply lemmas. lemma bind_singleton {α β} (x : α) (f : α → list β) : list.bind [x] f = f x := begin success_if_fail { library_search { apply := λ e, tactic.apply e { md := tactic.transparency.reducible } }, }, library_search!, end constant f : ℕ → ℕ axiom F (a b : ℕ) : f a ≤ f b ↔ a ≤ b example (a b : ℕ) (h : a ≤ b) : f a ≤ f b := by library_search -- Test #3432 theorem nonzero_gt_one (n : ℕ) : ¬ n = 0 → n ≥ 1 := by library_search! -- `exact nat.pos_of_ne_zero` end test.library_search
905dec26bd2b956d30f1b3255ad82cb2ad36eac1
367134ba5a65885e863bdc4507601606690974c1
/src/data/list/nodup.lean
ec6d0989c2caccfb9b8de3921df539136b3c10ab
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
12,240
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.list.pairwise import data.list.forall2 /-! # Lists with no duplicates `list.nodup` is defined in `data/list/defs`. In this file we prove various properties of this predicate. -/ universes u v open nat function variables {α : Type u} {β : Type v} namespace list @[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] protected lemma pairwise.nodup {l : list α} {r : α → α → Prop} [is_irrefl α r] (h : pairwise r l) : nodup l := h.imp $ λ a b, ne_of_irrefl 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_append_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 (left_inverse.injective (λ 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)⟩ lemma nodup.map_update [decidable_eq α] {l : list α} (hl : l.nodup) (f : α → β) (x : α) (y : β) : l.map (function.update f x y) = if x ∈ l then (l.map f).update_nth (l.index_of x) y else l.map f := begin induction l with hd tl ihl, { simp }, rw [nodup_cons] at hl, simp only [mem_cons_iff, map, ihl hl.2], by_cases H : hd = x, { subst hd, simp [update_nth, hl.1] }, { simp [ne.symm H, H, update_nth, ← apply_ite (cons (f hd))] } end end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x
3bc7b90a8f26ffe79db82f899e02cb50a0dd2381
7007bb645068e0b6b859aab9da7cf5c1c79e98be
/library/init/meta/widget/interactive_expr.lean
43c965641e202c0fbaafcf5256110717b8a0c674
[ "Apache-2.0" ]
permissive
EdAyers/lean
7d3fb852380bc386545ebc119b7d03c128c3ce1c
be72c8dc527a062e243a408480f487a55b06cb0a
refs/heads/master
1,624,443,179,694
1,592,837,958,000
1,592,837,958,000
154,972,348
0
0
Apache-2.0
1,557,768,267,000
1,540,649,772,000
C++
UTF-8
Lean
false
false
10,089
lean
/- Copyright (c) E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ prelude import init.meta.widget.basic import init.meta.widget.tactic_component import init.meta.tagged_format import init.data.punit import init.meta.mk_dec_eq_instance meta def subexpr := (expr × expr.address) namespace widget open tagged_format open html attr namespace interactive_expression /-- eformat but without any of the formatting stuff like highlighting, groups etc. -/ meta inductive sf : Type | tag_expr : expr.address → expr → sf → sf | compose : sf → sf → sf | of_string : string → sf private meta def to_simple : eformat → sf | (tag ⟨ea,e⟩ m) := sf.tag_expr ea e $ to_simple m | (group m) := to_simple m | (nest i m) := to_simple m | (highlight i m) := to_simple m | (of_format f) := sf.of_string $ format.to_string f | (compose x y) := sf.compose (to_simple x) (to_simple y) private meta def sf.flatten : sf → sf | (sf.tag_expr e ea m) := (sf.tag_expr e ea $ sf.flatten m) | (sf.compose x y) := match (sf.flatten x), (sf.flatten y) with | (sf.of_string sx), (sf.of_string sy) := sf.of_string (sx ++ sy) | (sf.of_string sx), (sf.compose (sf.of_string sy) z) := sf.compose (sf.of_string (sx ++ sy)) z | (sf.compose x (sf.of_string sy)), (sf.of_string sz) := sf.compose x (sf.of_string (sy ++ sz)) | (sf.compose x (sf.of_string sy1)), (sf.compose (sf.of_string sy2) z) := sf.compose x (sf.compose (sf.of_string (sy1 ++ sy2)) z) | x, y := sf.compose x y end | (sf.of_string s) := sf.of_string s meta inductive action (γ : Type) | on_mouse_enter : subexpr → action | on_mouse_leave_all : action | on_click : subexpr → action | on_tooltip_action : γ → action | on_close_tooltip : action meta def view {γ} (tooltip_component : tc subexpr (action γ)) (click_address : option expr.address) (select_address : option expr.address) : subexpr → sf → tactic (list (html (action γ))) | ⟨ce, current_address⟩ (sf.tag_expr ea e m) := do let new_address := current_address ++ ea, let select_attrs : list (attr (action γ)) := if some new_address = select_address then [className "highlight"] else [], click_attrs : list (attr (action γ)) ← if some new_address = click_address then do content ← tc.to_html tooltip_component (e, new_address), pure [tooltip $ h "div" [] [ h "button" [cn "fr pointer ba br3", on_click (λ _, action.on_close_tooltip)] ["x"], content ]] else pure [], let as := [className "expr-boundary", key (ea)] ++ select_attrs ++ click_attrs, inner ← view (e,new_address) m, pure [h "span" as inner] | ca (sf.compose x y) := pure (++) <*> view ca x <*> view ca y | ca (sf.of_string s) := pure [h "span" [ on_mouse_enter (λ _, action.on_mouse_enter ca), on_click (λ _, action.on_click ca), key s ] [html.of_string s]] /-- Make an interactive expression. -/ meta def mk {γ} (tooltip : tc subexpr γ) : tc expr γ := let tooltip_comp := component.with_props_eq (λ (x y : tactic_state × expr × expr.address), x.2.2 = y.2.2) $ component.map_action (action.on_tooltip_action) tooltip in tc.mk_simple (action γ) (option subexpr × option subexpr) (λ e, pure $ (none, none)) (λ e ⟨ca, sa⟩ act, pure $ match act with | (action.on_mouse_enter ⟨e, ea⟩) := ((ca, some (e, ea)), none) | (action.on_mouse_leave_all) := ((ca, none), none) | (action.on_click ⟨e, ea⟩) := if some (e,ea) = ca then ((none, sa), none) else ((some (e, ea), sa), none) | (action.on_tooltip_action g) := ((none, sa), some g) | (action.on_close_tooltip) := ((none, sa), none) end ) (λ e ⟨ca, sa⟩, do ts ← tactic.read, let m : sf := sf.flatten $ to_simple $ tactic_state.pp_tagged ts e, let m : sf := sf.tag_expr [] e m, -- [hack] in pp.cpp I forgot to add an expr-boundary for the root expression. v ← view tooltip_comp (prod.snd <$> ca) (prod.snd <$> sa) ⟨e, []⟩ m, pure $ [ h "span" [ className "expr", key e.hash, on_mouse_leave (λ _, action.on_mouse_leave_all) ] $ v ] ) /-- Render the implicit arguments for an expression in fancy, little pills. -/ meta def implicit_arg_list (tooltip : tc subexpr empty) (e : expr) : tactic $ html empty := do fn ← (mk tooltip) $ expr.get_app_fn e, args ← list.mmap (mk tooltip) $ expr.get_app_args e, pure $ h "div" [] ( (h "span" [className "bg-blue br3 ma1 ph2 white"] [fn]) :: list.map (λ a, h "span" [className "bg-gray br3 ma1 ph2 white"] [a]) args ) meta def type_tooltip : tc subexpr empty := tc.stateless (λ ⟨e,ea⟩, do y ← tactic.infer_type e, y_comp ← mk type_tooltip y, implicit_args ← implicit_arg_list type_tooltip e, pure [ h "div" [] [ h "div" [] [y_comp], h "hr" [] [], implicit_args ] ] ) end interactive_expression @[derive decidable_eq] meta inductive filter_type | none | no_instances | only_props meta def filter_local : filter_type → expr → tactic bool | (filter_type.none) e := pure tt | (filter_type.no_instances) e := do t ← tactic.infer_type e, bnot <$> tactic.is_class t | (filter_type.only_props) e := do t ← tactic.infer_type e, tactic.is_prop t meta def filter_component : component filter_type filter_type := component.stateless (λ lf, [ h "label" [] ["filter: "], select [ ⟨filter_type.none, "0", ["no filter"]⟩, ⟨filter_type.no_instances, "1", ["no instances"]⟩, ⟨filter_type.only_props, "2", ["only props"]⟩ ] lf ] ) meta def html.of_name {α : Type} : name → html α | n := html.of_string $ name.to_string n open tactic meta def show_type_component : tc expr empty := tc.stateless (λ x, do y ← infer_type x, y_comp ← interactive_expression.mk interactive_expression.type_tooltip $ y, pure y_comp ) /-- A group of local constants in the context that should be rendered as one line. -/ @[derive decidable_eq] meta structure local_collection := (key : string) (locals : list expr) (type : expr) /-- Group consecutive locals according to whether they have the same type -/ meta def to_local_collection : list local_collection → list expr → tactic (list local_collection) | acc [] := pure $ list.map (λ lc : local_collection, {locals := lc.locals.reverse, ..lc}) $ list.reverse $ acc | acc (l::ls) := do l_type ← infer_type l, (do (⟨k,ns,t⟩::acc) ← pure acc, is_def_eq t l_type, to_local_collection (⟨k,l::ns,t⟩::acc) ls) <|> (to_local_collection (⟨to_string $ expr.local_uniq_name $ l, [l], l_type⟩::acc) ls) /-- Component that displays the main (first) goal. -/ meta def tactic_view_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc filter_type γ := tc.stateless $ λ ft, do g@(expr.mvar u_n pp_n y) ← main_goal, set_goals [g], lcs ← local_context, lcs ← list.mfilter (filter_local ft) lcs, lcs ← to_local_collection [] lcs, lchs ← lcs.mmap (λ lc, do lh ← local_c lc, ns ← pure $ lc.locals.map (λ n, h "span" [cn "goal-hyp b ml2"] [html.of_name $ expr.local_pp_name n]), pure $ h "li" [key lc.key] (ns ++ [" : ", h "span" [cn "goal-hyp-type"] [lh]])), t_comp ← target_c g, pure $ h "ul" [key g.hash, className "list pl0 font-code"] $ lchs ++ [ h "li" [key u_n] [ h "span" [cn "goal-vdash b"] ["⊢ "], t_comp ]] meta inductive tactic_view_action (γ : Type) | out (a:γ): tactic_view_action | filter (f: filter_type): tactic_view_action /-- Component that displays all goals, together with the `$n goals` message. -/ meta def tactic_view_component {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.mk_simple (tactic_view_action γ) (filter_type) (λ _, pure $ filter_type.none) (λ ⟨⟩ ft a, match a with | (tactic_view_action.out a) := pure (ft, some a) | (tactic_view_action.filter ft) := pure (ft, none) end) (λ ⟨⟩ ft, do gs ← get_goals, hs ← gs.mmap (λ g, do set_goals [g], flip tc.to_html ft $ tactic_view_goal local_c target_c), set_goals gs, let goal_message := if gs.length = 0 then "goals accomplished" else if gs.length = 1 then "1 goal" else to_string gs.length ++ " goals", let goal_message : html γ := h "strong" [cn "goal-goals"] [goal_message], let goals : html γ := h "ul" [className "list pl0"] $ list.map_with_index (λ i x, let border_cn := if i < hs.length then "ba bl-0 bt-0 br-0 b--dotted b--black-30" else "" in h "li" [className $ "lh-copy " ++ border_cn, key i] [x]) $ (goal_message :: hs), pure [ h "div" [className "fr"] [html.of_component ft $ component.map_action tactic_view_action.filter filter_component], html.map_action tactic_view_action.out goals ]) /-- Component that displays the term-mode goal. -/ meta def tactic_view_term_goal {γ} (local_c : tc local_collection γ) (target_c : tc expr γ) : tc unit γ := tc.stateless $ λ _, do goal ← flip tc.to_html (filter_type.none) $ tactic_view_goal local_c target_c, pure [h "ul" [className "list pl0"] [ h "li" [className "lh-copy"] [h "strong" [cn "goal-goals"] ["expected type:"]], h "li" [className "lh-copy"] [goal]]] meta def show_local_collection_component : tc local_collection empty := tc.stateless (λ lc, do (l::_) ← pure lc.locals, c ← show_type_component l, pure [c] ) meta def tactic_render : tc unit string := component.ignore_action $ tactic_view_component show_local_collection_component show_type_component meta def tactic_state_widget : component tactic_state string := tc.to_component tactic_render /-- Widget used to display term-proof goals. -/ meta def term_goal_widget : component tactic_state string := (tactic_view_term_goal show_local_collection_component show_type_component).to_component end widget
5f44eda505e67e22c88e5cc9159ab15b3c40f720
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/subsemigroup/membership.lean
90d4d0e144b89cb2980f2e9f8fad7d797bb8b8fe
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,991
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import group_theory.subsemigroup.basic /-! # Subsemigroups: membership criteria > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove various facts about membership in a subsemigroup. The intent is to mimic `group_theory/submonoid/membership`, but currently this file is mostly a stub and only provides rudimentary support. * `mem_supr_of_directed`, `coe_supr_of_directed`, `mem_Sup_of_directed_on`, `coe_Sup_of_directed_on`: the supremum of a directed collection of subsemigroup is their union. ## TODO * Define the `free_semigroup` generated by a set. This might require some rather substantial additions to low-level API. For example, developing the subtype of nonempty lists, then defining a product on nonempty lists, powers where the exponent is a positive natural, et cetera. Another option would be to define the `free_semigroup` as the subsemigroup (pushed to be a semigroup) of the `free_monoid` consisting of non-identity elements. ## Tags subsemigroup -/ variables {ι : Sort*} {M A B : Type*} section non_assoc variables [has_mul M] open set namespace subsemigroup -- TODO: this section can be generalized to `[mul_mem_class B M] [complete_lattice B]` -- such that `complete_lattice.le` coincides with `set_like.le` @[to_additive] lemma mem_supr_of_directed {S : ι → subsemigroup M} (hS : directed (≤) S) {x : M} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, suffices : x ∈ closure (⋃ i, (S i : set M)) → ∃ i, x ∈ S i, by simpa only [closure_Union, closure_eq (S _)] using this, refine (λ hx, closure_induction hx (λ y hy, mem_Union.mp hy) _), { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hS i j with ⟨k, hki, hkj⟩, exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ } end @[to_additive] lemma coe_supr_of_directed {S : ι → subsemigroup M} (hS : directed (≤) S) : ((⨆ i, S i : subsemigroup M) : set M) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {S : set (subsemigroup M)} (hS : directed_on (≤) S) {x : M} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := by simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] @[to_additive] lemma coe_Sup_of_directed_on {S : set (subsemigroup M)} (hS : directed_on (≤) S) : (↑(Sup S) : set M) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on hS] @[to_additive] lemma mem_sup_left {S T : subsemigroup M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subsemigroup M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mul_mem_sup {S T : subsemigroup M} {x y : M} (hx : x ∈ S) (hy : y ∈ T) : x * y ∈ S ⊔ T := mul_mem (mem_sup_left hx) (mem_sup_right hy) @[to_additive] lemma mem_supr_of_mem {S : ι → subsemigroup M} (i : ι) : ∀ {x : M}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subsemigroup M)} {s : subsemigroup M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs /-- An induction principle for elements of `⨆ i, S i`. If `C` holds all elements of `S i` for all `i`, and is preserved under multiplication, then it holds for all elements of the supremum of `S`. -/ @[elab_as_eliminator, to_additive /-" An induction principle for elements of `⨆ i, S i`. If `C` holds all elements of `S i` for all `i`, and is preserved under addition, then it holds for all elements of the supremum of `S`. "-/] lemma supr_induction (S : ι → subsemigroup M) {C : M → Prop} {x : M} (hx : x ∈ ⨆ i, S i) (hp : ∀ i (x ∈ S i), C x) (hmul : ∀ x y, C x → C y → C (x * y)) : C x := begin rw supr_eq_closure at hx, refine closure_induction hx (λ x hx, _) hmul, obtain ⟨i, hi⟩ := set.mem_Union.mp hx, exact hp _ _ hi, end /-- A dependent version of `subsemigroup.supr_induction`. -/ @[elab_as_eliminator, to_additive /-"A dependent version of `add_subsemigroup.supr_induction`. "-/] lemma supr_induction' (S : ι → subsemigroup M) {C : Π x, (x ∈ ⨆ i, S i) → Prop} (hp : ∀ i (x ∈ S i), C x (mem_supr_of_mem i ‹_›)) (hmul : ∀ x y hx hy, C x hx → C y hy → C (x * y) (mul_mem ‹_› ‹_›)) {x : M} (hx : x ∈ ⨆ i, S i) : C x hx := begin refine exists.elim _ (λ (hx : x ∈ ⨆ i, S i) (hc : C x hx), hc), refine supr_induction S hx (λ i x hx, _) (λ x y, _), { exact ⟨_, hp _ _ hx⟩ }, { rintro ⟨_, Cx⟩ ⟨_, Cy⟩, exact ⟨_, hmul _ _ _ _ Cx Cy⟩ }, end end subsemigroup end non_assoc
5a5da4eded35707b6504828820592d30ad03f9ff
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/finite_measure.lean
3efd56a6070fefd63589e64bbf5e857c48b26fb9
[ "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
33,306
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import topology.continuous_function.bounded import topology.algebra.module.weak_dual import measure_theory.integral.bochner /-! # Finite measures > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the type of finite measures on a given measurable space. When the underlying space has a topology and the measurable space structure (sigma algebra) is finer than the Borel sigma algebra, then the type of finite measures is equipped with the topology of weak convergence of measures. The topology of weak convergence is the coarsest topology w.r.t. which for every bounded continuous `ℝ≥0`-valued function `f`, the integration of `f` against the measure is continuous. ## Main definitions The main definitions are * the type `measure_theory.finite_measure Ω` with the topology of weak convergence; * `measure_theory.finite_measure.to_weak_dual_bcnn : finite_measure Ω → (weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0))` allowing to interpret a finite measure as a continuous linear functional on the space of bounded continuous nonnegative functions on `Ω`. This is used for the definition of the topology of weak convergence. ## Main results * Finite measures `μ` on `Ω` give rise to continuous linear functionals on the space of bounded continuous nonnegative functions on `Ω` via integration: `measure_theory.finite_measure.to_weak_dual_bcnn : finite_measure Ω → (weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0))` * `measure_theory.finite_measure.tendsto_iff_forall_integral_tendsto`: Convergence of finite measures is characterized by the convergence of integrals of all bounded continuous functions. This shows that the chosen definition of topology coincides with the common textbook definition of weak convergence of measures. A similar characterization by the convergence of integrals (in the `measure_theory.lintegral` sense) of all bounded continuous nonnegative functions is `measure_theory.finite_measure.tendsto_iff_forall_lintegral_tendsto`. ## Implementation notes The topology of weak convergence of finite Borel measures is defined using a mapping from `measure_theory.finite_measure Ω` to `weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0)`, inheriting the topology from the latter. The implementation of `measure_theory.finite_measure Ω` and is directly as a subtype of `measure_theory.measure Ω`, and the coercion to a function is the composition `ennreal.to_nnreal` and the coercion to function of `measure_theory.measure Ω`. Another alternative would have been to use a bijection with `measure_theory.vector_measure Ω ℝ≥0` as an intermediate step. Some considerations: * Potential advantages of using the `nnreal`-valued vector measure alternative: * The coercion to function would avoid need to compose with `ennreal.to_nnreal`, the `nnreal`-valued API could be more directly available. * Potential drawbacks of the vector measure alternative: * The coercion to function would lose monotonicity, as non-measurable sets would be defined to have measure 0. * No integration theory directly. E.g., the topology definition requires `measure_theory.lintegral` w.r.t. a coercion to `measure_theory.measure Ω` in any case. ## References * [Billingsley, *Convergence of probability measures*][billingsley1999] ## Tags weak convergence of measures, finite measure -/ noncomputable theory open measure_theory open set open filter open bounded_continuous_function open_locale topology ennreal nnreal bounded_continuous_function namespace measure_theory namespace finite_measure section finite_measure /-! ### Finite measures In this section we define the `Type` of `finite_measure Ω`, when `Ω` is a measurable space. Finite measures on `Ω` are a module over `ℝ≥0`. If `Ω` is moreover a topological space and the sigma algebra on `Ω` is finer than the Borel sigma algebra (i.e. `[opens_measurable_space Ω]`), then `finite_measure Ω` is equipped with the topology of weak convergence of measures. This is implemented by defining a pairing of finite measures `μ` on `Ω` with continuous bounded nonnegative functions `f : Ω →ᵇ ℝ≥0` via integration, and using the associated weak topology (essentially the weak-star topology on the dual of `Ω →ᵇ ℝ≥0`). -/ variables {Ω : Type*} [measurable_space Ω] /-- Finite measures are defined as the subtype of measures that have the property of being finite measures (i.e., their total mass is finite). -/ def _root_.measure_theory.finite_measure (Ω : Type*) [measurable_space Ω] : Type* := {μ : measure Ω // is_finite_measure μ} /-- A finite measure can be interpreted as a measure. -/ instance : has_coe (finite_measure Ω) (measure_theory.measure Ω) := coe_subtype instance is_finite_measure (μ : finite_measure Ω) : is_finite_measure (μ : measure Ω) := μ.prop instance : has_coe_to_fun (finite_measure Ω) (λ _, set Ω → ℝ≥0) := ⟨λ μ s, (μ s).to_nnreal⟩ lemma coe_fn_eq_to_nnreal_coe_fn_to_measure (ν : finite_measure Ω) : (ν : set Ω → ℝ≥0) = λ s, ((ν : measure Ω) s).to_nnreal := rfl @[simp] lemma ennreal_coe_fn_eq_coe_fn_to_measure (ν : finite_measure Ω) (s : set Ω) : (ν s : ℝ≥0∞) = (ν : measure Ω) s := ennreal.coe_to_nnreal (measure_lt_top ↑ν s).ne @[simp] lemma val_eq_to_measure (ν : finite_measure Ω) : ν.val = (ν : measure Ω) := rfl lemma coe_injective : function.injective (coe : finite_measure Ω → measure Ω) := subtype.coe_injective lemma apply_mono (μ : finite_measure Ω) {s₁ s₂ : set Ω} (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := begin change ((μ : measure Ω) s₁).to_nnreal ≤ ((μ : measure Ω) s₂).to_nnreal, have key : (μ : measure Ω) s₁ ≤ (μ : measure Ω) s₂ := (μ : measure Ω).mono h, apply (ennreal.to_nnreal_le_to_nnreal (measure_ne_top _ s₁) (measure_ne_top _ s₂)).mpr key, end /-- The (total) mass of a finite measure `μ` is `μ univ`, i.e., the cast to `nnreal` of `(μ : measure Ω) univ`. -/ def mass (μ : finite_measure Ω) : ℝ≥0 := μ univ @[simp] lemma ennreal_mass {μ : finite_measure Ω} : (μ.mass : ℝ≥0∞) = (μ : measure Ω) univ := ennreal_coe_fn_eq_coe_fn_to_measure μ set.univ instance has_zero : has_zero (finite_measure Ω) := { zero := ⟨0, measure_theory.is_finite_measure_zero⟩ } @[simp] lemma zero.mass : (0 : finite_measure Ω).mass = 0 := rfl @[simp] lemma mass_zero_iff (μ : finite_measure Ω) : μ.mass = 0 ↔ μ = 0 := begin refine ⟨λ μ_mass, _, (λ hμ, by simp only [hμ, zero.mass])⟩, ext1, apply measure.measure_univ_eq_zero.mp, rwa [← ennreal_mass, ennreal.coe_eq_zero], end lemma mass_nonzero_iff (μ : finite_measure Ω) : μ.mass ≠ 0 ↔ μ ≠ 0 := begin rw not_iff_not, exact finite_measure.mass_zero_iff μ, end @[ext] lemma eq_of_forall_measure_apply_eq (μ ν : finite_measure Ω) (h : ∀ (s : set Ω), measurable_set s → (μ : measure Ω) s = (ν : measure Ω) s) : μ = ν := by { ext1, ext1 s s_mble, exact h s s_mble, } lemma eq_of_forall_apply_eq (μ ν : finite_measure Ω) (h : ∀ (s : set Ω), measurable_set s → μ s = ν s) : μ = ν := begin ext1 s s_mble, simpa [ennreal_coe_fn_eq_coe_fn_to_measure] using congr_arg (coe : ℝ≥0 → ℝ≥0∞) (h s s_mble), end instance : inhabited (finite_measure Ω) := ⟨0⟩ instance : has_add (finite_measure Ω) := { add := λ μ ν, ⟨μ + ν, measure_theory.is_finite_measure_add⟩ } variables {R : Type*} [has_smul R ℝ≥0] [has_smul R ℝ≥0∞] [is_scalar_tower R ℝ≥0 ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] instance : has_smul R (finite_measure Ω) := { smul := λ (c : R) μ, ⟨c • μ, measure_theory.is_finite_measure_smul_of_nnreal_tower⟩, } @[simp, norm_cast] lemma coe_zero : (coe : finite_measure Ω → measure Ω) 0 = 0 := rfl @[simp, norm_cast] lemma coe_add (μ ν : finite_measure Ω) : ↑(μ + ν) = (↑μ + ↑ν : measure Ω) := rfl @[simp, norm_cast] lemma coe_smul (c : R) (μ : finite_measure Ω) : ↑(c • μ) = (c • ↑μ : measure Ω) := rfl @[simp, norm_cast] lemma coe_fn_zero : (⇑(0 : finite_measure Ω) : set Ω → ℝ≥0) = (0 : set Ω → ℝ≥0) := by { funext, refl, } @[simp, norm_cast] lemma coe_fn_add (μ ν : finite_measure Ω) : (⇑(μ + ν) : set Ω → ℝ≥0) = (⇑μ + ⇑ν : set Ω → ℝ≥0) := by { funext, simp [← ennreal.coe_eq_coe], } @[simp, norm_cast] lemma coe_fn_smul [is_scalar_tower R ℝ≥0 ℝ≥0] (c : R) (μ : finite_measure Ω) : (⇑(c • μ) : set Ω → ℝ≥0) = c • (⇑μ : set Ω → ℝ≥0) := by { funext, simp [← ennreal.coe_eq_coe, ennreal.coe_smul], } instance : add_comm_monoid (finite_measure Ω) := coe_injective.add_comm_monoid coe coe_zero coe_add (λ _ _, coe_smul _ _) /-- Coercion is an `add_monoid_hom`. -/ @[simps] def coe_add_monoid_hom : finite_measure Ω →+ measure Ω := { to_fun := coe, map_zero' := coe_zero, map_add' := coe_add } instance {Ω : Type*} [measurable_space Ω] : module ℝ≥0 (finite_measure Ω) := function.injective.module _ coe_add_monoid_hom coe_injective coe_smul @[simp] lemma coe_fn_smul_apply [is_scalar_tower R ℝ≥0 ℝ≥0] (c : R) (μ : finite_measure Ω) (s : set Ω) : (c • μ) s = c • (μ s) := by { simp only [coe_fn_smul, pi.smul_apply], } /-- Restrict a finite measure μ to a set A. -/ def restrict (μ : finite_measure Ω) (A : set Ω) : finite_measure Ω := { val := (μ : measure Ω).restrict A, property := measure_theory.is_finite_measure_restrict μ A, } lemma restrict_measure_eq (μ : finite_measure Ω) (A : set Ω) : (μ.restrict A : measure Ω) = (μ : measure Ω).restrict A := rfl lemma restrict_apply_measure (μ : finite_measure Ω) (A : set Ω) {s : set Ω} (s_mble : measurable_set s) : (μ.restrict A : measure Ω) s = (μ : measure Ω) (s ∩ A) := measure.restrict_apply s_mble lemma restrict_apply (μ : finite_measure Ω) (A : set Ω) {s : set Ω} (s_mble : measurable_set s) : (μ.restrict A) s = μ (s ∩ A) := begin apply congr_arg ennreal.to_nnreal, exact measure.restrict_apply s_mble, end lemma restrict_mass (μ : finite_measure Ω) (A : set Ω) : (μ.restrict A).mass = μ A := by simp only [mass, restrict_apply μ A measurable_set.univ, univ_inter] lemma restrict_eq_zero_iff (μ : finite_measure Ω) (A : set Ω) : μ.restrict A = 0 ↔ μ A = 0 := by rw [← mass_zero_iff, restrict_mass] lemma restrict_nonzero_iff (μ : finite_measure Ω) (A : set Ω) : μ.restrict A ≠ 0 ↔ μ A ≠ 0 := by rw [← mass_nonzero_iff, restrict_mass] variables [topological_space Ω] /-- The pairing of a finite (Borel) measure `μ` with a nonnegative bounded continuous function is obtained by (Lebesgue) integrating the (test) function against the measure. This is `finite_measure.test_against_nn`. -/ def test_against_nn (μ : finite_measure Ω) (f : Ω →ᵇ ℝ≥0) : ℝ≥0 := (∫⁻ ω, f ω ∂(μ : measure Ω)).to_nnreal lemma _root_.bounded_continuous_function.nnreal.to_ennreal_comp_measurable {Ω : Type*} [topological_space Ω] [measurable_space Ω] [opens_measurable_space Ω] (f : Ω →ᵇ ℝ≥0) : measurable (λ ω, (f ω : ℝ≥0∞)) := measurable_coe_nnreal_ennreal.comp f.continuous.measurable lemma _root_.measure_theory.lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ≥0) : ∫⁻ ω, f ω ∂μ < ∞ := begin apply is_finite_measure.lintegral_lt_top_of_bounded_to_ennreal, use nndist f 0, intros x, have key := bounded_continuous_function.nnreal.upper_bound f x, rw ennreal.coe_le_coe, have eq : nndist f 0 = ⟨dist f 0, dist_nonneg⟩, { ext, simp only [real.coe_to_nnreal', max_eq_left_iff, subtype.coe_mk, coe_nndist], }, rwa eq at key, end @[simp] lemma test_against_nn_coe_eq {μ : finite_measure Ω} {f : Ω →ᵇ ℝ≥0} : (μ.test_against_nn f : ℝ≥0∞) = ∫⁻ ω, f ω ∂(μ : measure Ω) := ennreal.coe_to_nnreal (lintegral_lt_top_of_bounded_continuous_to_nnreal _ f).ne lemma test_against_nn_const (μ : finite_measure Ω) (c : ℝ≥0) : μ.test_against_nn (bounded_continuous_function.const Ω c) = c * μ.mass := by simp [← ennreal.coe_eq_coe] lemma test_against_nn_mono (μ : finite_measure Ω) {f g : Ω →ᵇ ℝ≥0} (f_le_g : (f : Ω → ℝ≥0) ≤ g) : μ.test_against_nn f ≤ μ.test_against_nn g := begin simp only [←ennreal.coe_le_coe, test_against_nn_coe_eq], exact lintegral_mono (λ ω, ennreal.coe_mono (f_le_g ω)), end @[simp] lemma test_against_nn_zero (μ : finite_measure Ω) : μ.test_against_nn 0 = 0 := by simpa only [zero_mul] using μ.test_against_nn_const 0 @[simp] lemma test_against_nn_one (μ : finite_measure Ω) : μ.test_against_nn 1 = μ.mass := begin simp only [test_against_nn, coe_one, pi.one_apply, ennreal.coe_one, lintegral_one], refl, end @[simp] lemma zero.test_against_nn_apply (f : Ω →ᵇ ℝ≥0) : (0 : finite_measure Ω).test_against_nn f = 0 := by simp only [test_against_nn, coe_zero, lintegral_zero_measure, ennreal.zero_to_nnreal] lemma zero.test_against_nn : (0 : finite_measure Ω).test_against_nn = 0 := by { funext, simp only [zero.test_against_nn_apply, pi.zero_apply], } @[simp] lemma smul_test_against_nn_apply (c : ℝ≥0) (μ : finite_measure Ω) (f : Ω →ᵇ ℝ≥0) : (c • μ).test_against_nn f = c • (μ.test_against_nn f) := by simp only [test_against_nn, coe_smul, smul_eq_mul, ← ennreal.smul_to_nnreal, ennreal.smul_def, lintegral_smul_measure] variables [opens_measurable_space Ω] lemma test_against_nn_add (μ : finite_measure Ω) (f₁ f₂ : Ω →ᵇ ℝ≥0) : μ.test_against_nn (f₁ + f₂) = μ.test_against_nn f₁ + μ.test_against_nn f₂ := begin simp only [←ennreal.coe_eq_coe, bounded_continuous_function.coe_add, ennreal.coe_add, pi.add_apply, test_against_nn_coe_eq], exact lintegral_add_left (bounded_continuous_function.nnreal.to_ennreal_comp_measurable _) _ end lemma test_against_nn_smul [is_scalar_tower R ℝ≥0 ℝ≥0] [pseudo_metric_space R] [has_zero R] [has_bounded_smul R ℝ≥0] (μ : finite_measure Ω) (c : R) (f : Ω →ᵇ ℝ≥0) : μ.test_against_nn (c • f) = c • μ.test_against_nn f := begin simp only [←ennreal.coe_eq_coe, bounded_continuous_function.coe_smul, test_against_nn_coe_eq, ennreal.coe_smul], simp_rw [←smul_one_smul ℝ≥0∞ c (f _ : ℝ≥0∞), ←smul_one_smul ℝ≥0∞ c (lintegral _ _ : ℝ≥0∞), smul_eq_mul], exact @lintegral_const_mul _ _ (μ : measure Ω) (c • 1) _ (bounded_continuous_function.nnreal.to_ennreal_comp_measurable f), end lemma test_against_nn_lipschitz_estimate (μ : finite_measure Ω) (f g : Ω →ᵇ ℝ≥0) : μ.test_against_nn f ≤ μ.test_against_nn g + (nndist f g) * μ.mass := begin simp only [←μ.test_against_nn_const (nndist f g), ←test_against_nn_add, ←ennreal.coe_le_coe, bounded_continuous_function.coe_add, const_apply, ennreal.coe_add, pi.add_apply, coe_nnreal_ennreal_nndist, test_against_nn_coe_eq], apply lintegral_mono, have le_dist : ∀ ω, dist (f ω) (g ω) ≤ nndist f g := bounded_continuous_function.dist_coe_le_dist, intros ω, have le' : f ω ≤ g ω + nndist f g, { apply (nnreal.le_add_nndist (f ω) (g ω)).trans, rw add_le_add_iff_left, exact dist_le_coe.mp (le_dist ω), }, have le : (f ω : ℝ≥0∞) ≤ (g ω : ℝ≥0∞) + (nndist f g), by { rw ←ennreal.coe_add, exact ennreal.coe_mono le', }, rwa [coe_nnreal_ennreal_nndist] at le, end lemma test_against_nn_lipschitz (μ : finite_measure Ω) : lipschitz_with μ.mass (λ (f : Ω →ᵇ ℝ≥0), μ.test_against_nn f) := begin rw lipschitz_with_iff_dist_le_mul, intros f₁ f₂, suffices : abs (μ.test_against_nn f₁ - μ.test_against_nn f₂ : ℝ) ≤ μ.mass * (dist f₁ f₂), { rwa nnreal.dist_eq, }, apply abs_le.mpr, split, { have key' := μ.test_against_nn_lipschitz_estimate f₂ f₁, rw mul_comm at key', suffices : ↑(μ.test_against_nn f₂) ≤ ↑(μ.test_against_nn f₁) + ↑(μ.mass) * dist f₁ f₂, { linarith, }, have key := nnreal.coe_mono key', rwa [nnreal.coe_add, nnreal.coe_mul, nndist_comm] at key, }, { have key' := μ.test_against_nn_lipschitz_estimate f₁ f₂, rw mul_comm at key', suffices : ↑(μ.test_against_nn f₁) ≤ ↑(μ.test_against_nn f₂) + ↑(μ.mass) * dist f₁ f₂, { linarith, }, have key := nnreal.coe_mono key', rwa [nnreal.coe_add, nnreal.coe_mul] at key, }, end /-- Finite measures yield elements of the `weak_dual` of bounded continuous nonnegative functions via `measure_theory.finite_measure.test_against_nn`, i.e., integration. -/ def to_weak_dual_bcnn (μ : finite_measure Ω) : weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0) := { to_fun := λ f, μ.test_against_nn f, map_add' := test_against_nn_add μ, map_smul' := test_against_nn_smul μ, cont := μ.test_against_nn_lipschitz.continuous, } @[simp] lemma coe_to_weak_dual_bcnn (μ : finite_measure Ω) : ⇑μ.to_weak_dual_bcnn = μ.test_against_nn := rfl @[simp] lemma to_weak_dual_bcnn_apply (μ : finite_measure Ω) (f : Ω →ᵇ ℝ≥0) : μ.to_weak_dual_bcnn f = (∫⁻ x, f x ∂(μ : measure Ω)).to_nnreal := rfl /-- The topology of weak convergence on `measure_theory.finite_measure Ω` is inherited (induced) from the weak-* topology on `weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0)` via the function `measure_theory.finite_measure.to_weak_dual_bcnn`. -/ instance : topological_space (finite_measure Ω) := topological_space.induced to_weak_dual_bcnn infer_instance lemma to_weak_dual_bcnn_continuous : continuous (@to_weak_dual_bcnn Ω _ _ _) := continuous_induced_dom /- Integration of (nonnegative bounded continuous) test functions against finite Borel measures depends continuously on the measure. -/ lemma continuous_test_against_nn_eval (f : Ω →ᵇ ℝ≥0) : continuous (λ (μ : finite_measure Ω), μ.test_against_nn f) := (by apply (weak_bilin.eval_continuous _ _).comp to_weak_dual_bcnn_continuous : continuous ((λ φ : weak_dual ℝ≥0 (Ω →ᵇ ℝ≥0), φ f) ∘ to_weak_dual_bcnn)) /-- The total mass of a finite measure depends continuously on the measure. -/ lemma continuous_mass : continuous (λ (μ : finite_measure Ω), μ.mass) := by { simp_rw ←test_against_nn_one, exact continuous_test_against_nn_eval 1, } /-- Convergence of finite measures implies the convergence of their total masses. -/ lemma _root_.filter.tendsto.mass {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} (h : tendsto μs F (𝓝 μ)) : tendsto (λ i, (μs i).mass) F (𝓝 μ.mass) := (continuous_mass.tendsto μ).comp h lemma tendsto_iff_weak_star_tendsto {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} : tendsto μs F (𝓝 μ) ↔ tendsto (λ i, (μs(i)).to_weak_dual_bcnn) F (𝓝 μ.to_weak_dual_bcnn) := inducing.tendsto_nhds_iff ⟨rfl⟩ theorem tendsto_iff_forall_to_weak_dual_bcnn_tendsto {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} : tendsto μs F (𝓝 μ) ↔ ∀ (f : Ω →ᵇ ℝ≥0), tendsto (λ i, (μs i).to_weak_dual_bcnn f) F (𝓝 (μ.to_weak_dual_bcnn f)) := by { rw [tendsto_iff_weak_star_tendsto, tendsto_iff_forall_eval_tendsto_top_dual_pairing], refl, } theorem tendsto_iff_forall_test_against_nn_tendsto {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} : tendsto μs F (𝓝 μ) ↔ ∀ (f : Ω →ᵇ ℝ≥0), tendsto (λ i, (μs i).test_against_nn f) F (𝓝 (μ.test_against_nn f)) := by { rw finite_measure.tendsto_iff_forall_to_weak_dual_bcnn_tendsto, refl, } /-- If the total masses of finite measures tend to zero, then the measures tend to zero. This formulation concerns the associated functionals on bounded continuous nonnegative test functions. See `finite_measure.tendsto_zero_of_tendsto_zero_mass` for a formulation stating the weak convergence of measures. -/ lemma tendsto_zero_test_against_nn_of_tendsto_zero_mass {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} (mass_lim : tendsto (λ i, (μs i).mass) F (𝓝 0)) (f : Ω →ᵇ ℝ≥0) : tendsto (λ i, (μs i).test_against_nn f) F (𝓝 0) := begin apply tendsto_iff_dist_tendsto_zero.mpr, have obs := λ i, (μs i).test_against_nn_lipschitz_estimate f 0, simp_rw [test_against_nn_zero, zero_add] at obs, simp_rw (show ∀ i, dist ((μs i).test_against_nn f) 0 = (μs i).test_against_nn f, by simp only [dist_nndist, nnreal.nndist_zero_eq_val', eq_self_iff_true, implies_true_iff]), refine squeeze_zero (λ i, nnreal.coe_nonneg _) obs _, simp_rw nnreal.coe_mul, have lim_pair : tendsto (λ i, (⟨nndist f 0, (μs i).mass⟩ : ℝ × ℝ)) F (𝓝 (⟨nndist f 0, 0⟩)), { refine (prod.tendsto_iff _ _).mpr ⟨tendsto_const_nhds, _⟩, exact (nnreal.continuous_coe.tendsto 0).comp mass_lim, }, have key := tendsto_mul.comp lim_pair, rwa mul_zero at key, end /-- If the total masses of finite measures tend to zero, then the measures tend to zero. -/ lemma tendsto_zero_of_tendsto_zero_mass {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} (mass_lim : tendsto (λ i, (μs i).mass) F (𝓝 0)) : tendsto μs F (𝓝 0) := begin rw tendsto_iff_forall_test_against_nn_tendsto, intro f, convert tendsto_zero_test_against_nn_of_tendsto_zero_mass mass_lim f, rw [zero.test_against_nn_apply], end /-- A characterization of weak convergence in terms of integrals of bounded continuous nonnegative functions. -/ theorem tendsto_iff_forall_lintegral_tendsto {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} : tendsto μs F (𝓝 μ) ↔ ∀ (f : Ω →ᵇ ℝ≥0), tendsto (λ i, (∫⁻ x, (f x) ∂(μs(i) : measure Ω))) F (𝓝 ((∫⁻ x, (f x) ∂(μ : measure Ω)))) := begin rw tendsto_iff_forall_to_weak_dual_bcnn_tendsto, simp_rw [to_weak_dual_bcnn_apply _ _, ←test_against_nn_coe_eq, ennreal.tendsto_coe, ennreal.to_nnreal_coe], end end finite_measure -- section section finite_measure_bounded_convergence /-! ### Bounded convergence results for finite measures This section is about bounded convergence theorems for finite measures. -/ variables {Ω : Type*} [measurable_space Ω] [topological_space Ω] [opens_measurable_space Ω] /-- A bounded convergence theorem for a finite measure: If bounded continuous non-negative functions are uniformly bounded by a constant and tend to a limit, then their integrals against the finite measure tend to the integral of the limit. This formulation assumes: * the functions tend to a limit along a countably generated filter; * the limit is in the almost everywhere sense; * boundedness holds almost everywhere; * integration is `measure_theory.lintegral`, i.e., the functions and their integrals are `ℝ≥0∞`-valued. -/ lemma tendsto_lintegral_nn_filter_of_le_const {ι : Type*} {L : filter ι} [L.is_countably_generated] (μ : measure Ω) [is_finite_measure μ] {fs : ι → (Ω →ᵇ ℝ≥0)} {c : ℝ≥0} (fs_le_const : ∀ᶠ i in L, ∀ᵐ (ω : Ω) ∂μ, fs i ω ≤ c) {f : Ω → ℝ≥0} (fs_lim : ∀ᵐ (ω : Ω) ∂μ, tendsto (λ i, fs i ω) L (𝓝 (f ω))) : tendsto (λ i, (∫⁻ ω, fs i ω ∂μ)) L (𝓝 (∫⁻ ω, (f ω) ∂μ)) := begin simpa only using tendsto_lintegral_filter_of_dominated_convergence (λ _, c) (eventually_of_forall ((λ i, (ennreal.continuous_coe.comp (fs i).continuous).measurable))) _ ((@lintegral_const_lt_top _ _ μ _ _ (@ennreal.coe_ne_top c)).ne) _, { simpa only [ennreal.coe_le_coe] using fs_le_const, }, { simpa only [ennreal.tendsto_coe] using fs_lim, }, end /-- A bounded convergence theorem for a finite measure: If a sequence of bounded continuous non-negative functions are uniformly bounded by a constant and tend pointwise to a limit, then their integrals (`measure_theory.lintegral`) against the finite measure tend to the integral of the limit. A related result with more general assumptions is `measure_theory.finite_measure.tendsto_lintegral_nn_filter_of_le_const`. -/ lemma tendsto_lintegral_nn_of_le_const (μ : finite_measure Ω) {fs : ℕ → (Ω →ᵇ ℝ≥0)} {c : ℝ≥0} (fs_le_const : ∀ n ω, fs n ω ≤ c) {f : Ω → ℝ≥0} (fs_lim : ∀ ω, tendsto (λ n, fs n ω) at_top (𝓝 (f ω))) : tendsto (λ n, (∫⁻ ω, fs n ω ∂(μ : measure Ω))) at_top (𝓝 (∫⁻ ω, (f ω) ∂(μ : measure Ω))) := tendsto_lintegral_nn_filter_of_le_const μ (eventually_of_forall (λ n, eventually_of_forall (fs_le_const n))) (eventually_of_forall fs_lim) /-- A bounded convergence theorem for a finite measure: If bounded continuous non-negative functions are uniformly bounded by a constant and tend to a limit, then their integrals against the finite measure tend to the integral of the limit. This formulation assumes: * the functions tend to a limit along a countably generated filter; * the limit is in the almost everywhere sense; * boundedness holds almost everywhere; * integration is the pairing against non-negative continuous test functions (`measure_theory.finite_measure.test_against_nn`). A related result using `measure_theory.lintegral` for integration is `measure_theory.finite_measure.tendsto_lintegral_nn_filter_of_le_const`. -/ lemma tendsto_test_against_nn_filter_of_le_const {ι : Type*} {L : filter ι} [L.is_countably_generated] {μ : finite_measure Ω} {fs : ι → (Ω →ᵇ ℝ≥0)} {c : ℝ≥0} (fs_le_const : ∀ᶠ i in L, ∀ᵐ (ω : Ω) ∂(μ : measure Ω), fs i ω ≤ c) {f : Ω →ᵇ ℝ≥0} (fs_lim : ∀ᵐ (ω : Ω) ∂(μ : measure Ω), tendsto (λ i, fs i ω) L (𝓝 (f ω))) : tendsto (λ i, μ.test_against_nn (fs i)) L (𝓝 (μ.test_against_nn f)) := begin apply (ennreal.tendsto_to_nnreal (lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) f).ne).comp, exact tendsto_lintegral_nn_filter_of_le_const μ fs_le_const fs_lim, end /-- A bounded convergence theorem for a finite measure: If a sequence of bounded continuous non-negative functions are uniformly bounded by a constant and tend pointwise to a limit, then their integrals (`measure_theory.finite_measure.test_against_nn`) against the finite measure tend to the integral of the limit. Related results: * `measure_theory.finite_measure.tendsto_test_against_nn_filter_of_le_const`: more general assumptions * `measure_theory.finite_measure.tendsto_lintegral_nn_of_le_const`: using `measure_theory.lintegral` for integration. -/ lemma tendsto_test_against_nn_of_le_const {μ : finite_measure Ω} {fs : ℕ → (Ω →ᵇ ℝ≥0)} {c : ℝ≥0} (fs_le_const : ∀ n ω, fs n ω ≤ c) {f : Ω →ᵇ ℝ≥0} (fs_lim : ∀ ω, tendsto (λ n, fs n ω) at_top (𝓝 (f ω))) : tendsto (λ n, μ.test_against_nn (fs n)) at_top (𝓝 (μ.test_against_nn f)) := tendsto_test_against_nn_filter_of_le_const (eventually_of_forall (λ n, eventually_of_forall (fs_le_const n))) (eventually_of_forall fs_lim) end finite_measure_bounded_convergence -- section section finite_measure_convergence_by_bounded_continuous_functions /-! ### Weak convergence of finite measures with bounded continuous real-valued functions In this section we characterize the weak convergence of finite measures by the usual (defining) condition that the integrals of all bounded continuous real-valued functions converge. -/ variables {Ω : Type*} [measurable_space Ω] [topological_space Ω] [opens_measurable_space Ω] lemma integrable_of_bounded_continuous_to_nnreal (μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ≥0) : integrable ((coe : ℝ≥0 → ℝ) ∘ ⇑f) μ := begin refine ⟨(nnreal.continuous_coe.comp f.continuous).measurable.ae_strongly_measurable, _⟩, simp only [has_finite_integral, nnreal.nnnorm_eq], exact lintegral_lt_top_of_bounded_continuous_to_nnreal _ f, end lemma integrable_of_bounded_continuous_to_real (μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ) : integrable ⇑f μ := begin refine ⟨f.continuous.measurable.ae_strongly_measurable, _⟩, have aux : (coe : ℝ≥0 → ℝ) ∘ ⇑f.nnnorm = (λ x, ‖f x‖), { ext ω, simp only [function.comp_app, bounded_continuous_function.nnnorm_coe_fun_eq, coe_nnnorm], }, apply (has_finite_integral_iff_norm ⇑f).mpr, rw ← of_real_integral_eq_lintegral_of_real, { exact ennreal.of_real_lt_top, }, { exact aux ▸ integrable_of_bounded_continuous_to_nnreal μ f.nnnorm, }, { exact eventually_of_forall (λ ω, norm_nonneg (f ω)), }, end lemma _root_.bounded_continuous_function.integral_eq_integral_nnreal_part_sub (μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ) : ∫ ω, f ω ∂μ = ∫ ω, f.nnreal_part ω ∂μ - ∫ ω, (-f).nnreal_part ω ∂μ := by simp only [f.self_eq_nnreal_part_sub_nnreal_part_neg, pi.sub_apply, integral_sub, integrable_of_bounded_continuous_to_nnreal] lemma lintegral_lt_top_of_bounded_continuous_to_real {Ω : Type*} [measurable_space Ω] [topological_space Ω] (μ : measure Ω) [is_finite_measure μ] (f : Ω →ᵇ ℝ) : ∫⁻ ω, ennreal.of_real (f ω) ∂μ < ∞ := lintegral_lt_top_of_bounded_continuous_to_nnreal _ f.nnreal_part theorem tendsto_of_forall_integral_tendsto {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} (h : (∀ (f : Ω →ᵇ ℝ), tendsto (λ i, (∫ x, (f x) ∂(μs i : measure Ω))) F (𝓝 ((∫ x, (f x) ∂(μ : measure Ω)))))) : tendsto μs F (𝓝 μ) := begin apply (@tendsto_iff_forall_lintegral_tendsto Ω _ _ _ γ F μs μ).mpr, intro f, have key := @ennreal.tendsto_to_real_iff _ F _ (λ i, (lintegral_lt_top_of_bounded_continuous_to_nnreal (μs i : measure Ω) f).ne) _ (lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) f).ne, simp only [ennreal.of_real_coe_nnreal] at key, apply key.mp, have lip : lipschitz_with 1 (coe : ℝ≥0 → ℝ), from isometry_subtype_coe.lipschitz, set f₀ := bounded_continuous_function.comp _ lip f with def_f₀, have f₀_eq : ⇑f₀ = (coe : ℝ≥0 → ℝ) ∘ ⇑f, by refl, have f₀_nn : 0 ≤ ⇑f₀, from λ _, by simp only [f₀_eq, pi.zero_apply, nnreal.zero_le_coe], have f₀_ae_nn : 0 ≤ᵐ[(μ : measure Ω)] ⇑f₀, from eventually_of_forall f₀_nn, have f₀_ae_nns : ∀ i, 0 ≤ᵐ[(μs i : measure Ω)] ⇑f₀, from λ i, eventually_of_forall f₀_nn, have aux := integral_eq_lintegral_of_nonneg_ae f₀_ae_nn f₀.continuous.measurable.ae_strongly_measurable, have auxs := λ i, integral_eq_lintegral_of_nonneg_ae (f₀_ae_nns i) f₀.continuous.measurable.ae_strongly_measurable, simp only [f₀_eq, ennreal.of_real_coe_nnreal] at aux auxs, simpa only [←aux, ←auxs] using h f₀, end lemma _root_.bounded_continuous_function.nnreal.to_real_lintegral_eq_integral (f : Ω →ᵇ ℝ≥0) (μ : measure Ω) : (∫⁻ x, (f x : ℝ≥0∞) ∂μ).to_real = (∫ x, f x ∂μ) := begin rw integral_eq_lintegral_of_nonneg_ae _ (nnreal.continuous_coe.comp f.continuous).measurable.ae_strongly_measurable, { simp only [ennreal.of_real_coe_nnreal], }, { apply eventually_of_forall, simp only [pi.zero_apply, nnreal.zero_le_coe, implies_true_iff], }, end /-- A characterization of weak convergence in terms of integrals of bounded continuous real-valued functions. -/ theorem tendsto_iff_forall_integral_tendsto {γ : Type*} {F : filter γ} {μs : γ → finite_measure Ω} {μ : finite_measure Ω} : tendsto μs F (𝓝 μ) ↔ ∀ (f : Ω →ᵇ ℝ), tendsto (λ i, (∫ x, (f x) ∂(μs i : measure Ω))) F (𝓝 ((∫ x, (f x) ∂(μ : measure Ω)))) := begin refine ⟨_, tendsto_of_forall_integral_tendsto⟩, rw tendsto_iff_forall_lintegral_tendsto, intros h f, simp_rw bounded_continuous_function.integral_eq_integral_nnreal_part_sub, set f_pos := f.nnreal_part with def_f_pos, set f_neg := (-f).nnreal_part with def_f_neg, have tends_pos := (ennreal.tendsto_to_real ((lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) f_pos).ne)).comp (h f_pos), have tends_neg := (ennreal.tendsto_to_real ((lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure Ω) f_neg).ne)).comp (h f_neg), have aux : ∀ (g : Ω →ᵇ ℝ≥0), ennreal.to_real ∘ (λ (i : γ), ∫⁻ (x : Ω), ↑(g x) ∂(μs i : measure Ω)) = λ (i : γ), (∫⁻ (x : Ω), ↑(g x) ∂(μs i : measure Ω)).to_real, from λ _, rfl, simp_rw [aux, bounded_continuous_function.nnreal.to_real_lintegral_eq_integral] at tends_pos tends_neg, exact tendsto.sub tends_pos tends_neg, end end finite_measure_convergence_by_bounded_continuous_functions -- section end finite_measure -- namespace end measure_theory -- namespace
6e67e8671a8b2777be5cea0b5157fe170b1f255f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/succ_pred/linear_locally_finite.lean
39db9c91883a89af54f9943c3cb2d5326977c0dc
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
17,520
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import order.locally_finite import order.succ_pred.basic import order.hom.basic import data.countable.basic import logic.encodable.basic /-! # Linear locally finite orders We prove that a `linear_order` which is a `locally_finite_order` also verifies * `succ_order` * `pred_order` * `is_succ_archimedean` * `is_pred_archimedean` * `countable` Furthermore, we show that there is an `order_iso` between such an order and a subset of `ℤ`. ## Main definitions * `to_Z i0 i`: in a linear order on which we can define predecessors and successors and which is succ-archimedean, we can assign a unique integer `to_Z i0 i` to each element `i : ι` while respecting the order, starting from `to_Z i0 i0 = 0`. ## Main results Instances about linear locally finite orders: * `linear_locally_finite_order.succ_order`: a linear locally finite order has a successor function. * `linear_locally_finite_order.pred_order`: a linear locally finite order has a predecessor function. * `linear_locally_finite_order.is_succ_archimedean`: a linear locally finite order is succ-archimedean. * `linear_order.pred_archimedean_of_succ_archimedean`: a succ-archimedean linear order is also pred-archimedean. * `countable_of_linear_succ_pred_arch` : a succ-archimedean linear order is countable. About `to_Z`: * `order_iso_range_to_Z_of_linear_succ_pred_arch`: `to_Z` defines an `order_iso` between `ι` and its range. * `order_iso_nat_of_linear_succ_pred_arch`: if the order has a bot but no top, `to_Z` defines an `order_iso` between `ι` and `ℕ`. * `order_iso_int_of_linear_succ_pred_arch`: if the order has neither bot nor top, `to_Z` defines an `order_iso` between `ι` and `ℤ`. * `order_iso_range_of_linear_succ_pred_arch`: if the order has both a bot and a top, `to_Z` gives an `order_iso` between `ι` and `finset.range ((to_Z ⊥ ⊤).to_nat + 1)`. -/ open order variables {ι : Type*} [linear_order ι] namespace linear_locally_finite_order /-- Successor in a linear order. This defines a true successor only when `i` is isolated from above, i.e. when `i` is not the greatest lower bound of `(i, ∞)`. -/ noncomputable def succ_fn (i : ι) : ι := (exists_glb_Ioi i).some lemma succ_fn_spec (i : ι) : is_glb (set.Ioi i) (succ_fn i) := (exists_glb_Ioi i).some_spec lemma le_succ_fn (i : ι) : i ≤ succ_fn i := by { rw [le_is_glb_iff (succ_fn_spec i), mem_lower_bounds], exact λ x hx, (le_of_lt hx), } lemma is_glb_Ioc_of_is_glb_Ioi {i j k : ι} (hij_lt : i < j) (h : is_glb (set.Ioi i) k) : is_glb (set.Ioc i j) k := begin simp_rw [is_glb, is_greatest, mem_upper_bounds, mem_lower_bounds] at h ⊢, refine ⟨λ x hx, h.1 x hx.1, λ x hx, h.2 x _⟩, intros y hy, cases le_or_lt y j with h_le h_lt, { exact hx y ⟨hy, h_le⟩, }, { exact le_trans (hx j ⟨hij_lt, le_rfl⟩) h_lt.le, }, end lemma is_max_of_succ_fn_le [locally_finite_order ι] (i : ι) (hi : succ_fn i ≤ i) : is_max i := begin refine λ j hij, not_lt.mp (λ hij_lt, _), have h_succ_fn_eq : succ_fn i = i := le_antisymm hi (le_succ_fn i), have h_glb : is_glb (finset.Ioc i j : set ι) i, { rw finset.coe_Ioc, have h := succ_fn_spec i, rw h_succ_fn_eq at h, exact is_glb_Ioc_of_is_glb_Ioi hij_lt h, }, have hi_mem : i ∈ finset.Ioc i j, { refine finset.is_glb_mem _ h_glb _, exact ⟨_, finset.mem_Ioc.mpr ⟨hij_lt, le_rfl⟩⟩, }, rw finset.mem_Ioc at hi_mem, exact lt_irrefl i hi_mem.1, end lemma succ_fn_le_of_lt (i j : ι) (hij : i < j) : succ_fn i ≤ j := by { have h := succ_fn_spec i, rw [is_glb, is_greatest, mem_lower_bounds] at h, exact h.1 j hij, } lemma le_of_lt_succ_fn (j i : ι) (hij : j < succ_fn i) : j ≤ i := begin rw lt_is_glb_iff (succ_fn_spec i) at hij, obtain ⟨k, hk_lb, hk⟩ := hij, rw mem_lower_bounds at hk_lb, exact not_lt.mp (λ hi_lt_j, not_le.mpr hk (hk_lb j hi_lt_j)), end @[priority 100] noncomputable instance [locally_finite_order ι] : succ_order ι := { succ := succ_fn, le_succ := le_succ_fn, max_of_succ_le := is_max_of_succ_fn_le, succ_le_of_lt := succ_fn_le_of_lt, le_of_lt_succ := le_of_lt_succ_fn, } @[priority 100] noncomputable instance [locally_finite_order ι] : pred_order ι := @order_dual.pred_order ιᵒᵈ _ _ end linear_locally_finite_order @[priority 100] instance linear_locally_finite_order.is_succ_archimedean [locally_finite_order ι] : is_succ_archimedean ι := { exists_succ_iterate_of_le := λ i j hij, begin rw le_iff_lt_or_eq at hij, cases hij, swap, { refine ⟨0, _⟩, simpa only [function.iterate_zero, id.def] using hij, }, by_contra h, push_neg at h, have h_lt : ∀ n, succ^[n] i < j, { intro n, induction n with n hn, { simpa only [function.iterate_zero, id.def] using hij, }, { refine lt_of_le_of_ne _ (h _), rw [function.iterate_succ', function.comp_app], exact succ_le_of_lt hn, }, }, have h_mem : ∀ n, succ^[n] i ∈ finset.Icc i j, from λ n, finset.mem_Icc.mpr ⟨le_succ_iterate n i, (h_lt n).le⟩, obtain ⟨n, m, hnm, h_eq⟩ : ∃ n m, n < m ∧ (succ^[n] i = (succ^[m] i)), { let f : ℕ → finset.Icc i j := λ n, ⟨succ^[n] i, h_mem n⟩, obtain ⟨n, m, hnm_ne, hfnm⟩ : ∃ n m, n ≠ m ∧ f n = f m, from finite.exists_ne_map_eq_of_infinite f, have hnm_eq : (succ^[n] i) = (succ^[m] i), { simpa only [subtype.mk_eq_mk] using hfnm, }, cases le_total n m with h_le h_le, { exact ⟨n, m, lt_of_le_of_ne h_le hnm_ne, hnm_eq⟩, }, { exact ⟨m, n, lt_of_le_of_ne h_le hnm_ne.symm, hnm_eq.symm ⟩, }, }, have h_max : is_max (succ^[n] i) := is_max_iterate_succ_of_eq_of_ne h_eq hnm.ne, exact not_le.mpr (h_lt n) (h_max (h_lt n).le), end } @[priority 100] instance linear_order.pred_archimedean_of_succ_archimedean [succ_order ι] [pred_order ι] [is_succ_archimedean ι] : is_pred_archimedean ι := { exists_pred_iterate_of_le := λ i j hij, begin have h_exists := exists_succ_iterate_of_le hij, obtain ⟨n, hn_eq, hn_lt_ne⟩ : ∃ n, (succ^[n] i = j) ∧ (∀ m < n, succ^[m] i ≠ j), from ⟨nat.find h_exists, nat.find_spec h_exists, λ m hmn, nat.find_min h_exists hmn⟩, refine ⟨n, _⟩, rw ← hn_eq, induction n with n hn, { simp only [function.iterate_zero, id.def], }, { rw pred_succ_iterate_of_not_is_max, rw [nat.succ_sub_succ_eq_sub, tsub_zero], suffices : (succ^[n] i) < (succ^[n.succ] i), from not_is_max_of_lt this, refine lt_of_le_of_ne _ _, { rw function.iterate_succ', exact le_succ _, }, { rw hn_eq, exact hn_lt_ne _ (nat.lt_succ_self n), }, }, end } section to_Z variables [succ_order ι] [is_succ_archimedean ι] [pred_order ι] {i0 i : ι} /-- `to_Z` numbers elements of `ι` according to their order, starting from `i0`. We prove in `order_iso_range_to_Z_of_linear_succ_pred_arch` that this defines an `order_iso` between `ι` and the range of `to_Z`. -/ def to_Z (i0 i : ι) : ℤ := dite (i0 ≤ i) (λ hi, nat.find (exists_succ_iterate_of_le hi)) (λ hi, - nat.find (exists_pred_iterate_of_le (not_le.mp hi).le)) lemma to_Z_of_ge (hi : i0 ≤ i) : to_Z i0 i = nat.find (exists_succ_iterate_of_le hi) := dif_pos hi lemma to_Z_of_lt (hi : i < i0) : to_Z i0 i = - nat.find (exists_pred_iterate_of_le hi.le) := dif_neg (not_le.mpr hi) @[simp] lemma to_Z_of_eq : to_Z i0 i0 = 0 := begin rw to_Z_of_ge le_rfl, norm_cast, refine le_antisymm (nat.find_le _) (zero_le _), rw [function.iterate_zero, id.def], end lemma iterate_succ_to_Z (i : ι) (hi : i0 ≤ i) : succ^[(to_Z i0 i).to_nat] i0 = i := by { rw [to_Z_of_ge hi, int.to_nat_coe_nat], exact nat.find_spec (exists_succ_iterate_of_le hi), } lemma iterate_pred_to_Z (i : ι) (hi : i < i0) : pred^[(- to_Z i0 i).to_nat] i0 = i := begin rw [to_Z_of_lt hi, neg_neg, int.to_nat_coe_nat], exact nat.find_spec (exists_pred_iterate_of_le hi.le), end lemma to_Z_nonneg (hi : i0 ≤ i) : 0 ≤ to_Z i0 i := by { rw to_Z_of_ge hi, exact nat.cast_nonneg _, } lemma to_Z_neg (hi : i < i0) : to_Z i0 i < 0 := begin refine lt_of_le_of_ne _ _, { rw [to_Z_of_lt hi, neg_nonpos], exact nat.cast_nonneg _, }, { by_contra, have h_eq := iterate_pred_to_Z i hi, rw [← h_eq, h] at hi, simpa only [neg_zero, int.to_nat_zero, function.iterate_zero, id.def, lt_self_iff_false] using hi, }, end lemma to_Z_iterate_succ_le (n : ℕ) : to_Z i0 (succ^[n] i0) ≤ n := begin rw to_Z_of_ge (le_succ_iterate _ _), norm_cast, exact nat.find_min' (exists_succ_iterate_of_le _) rfl, end lemma to_Z_iterate_pred_ge (n : ℕ) : -(n : ℤ) ≤ to_Z i0 (pred^[n] i0) := begin cases le_or_lt i0 (pred^[n] i0) with h h, { have h_eq : (pred^[n] i0) = i0 := le_antisymm (pred_iterate_le _ _) h, rw [h_eq, to_Z_of_eq], simp only [right.neg_nonpos_iff, nat.cast_nonneg],}, { rw [to_Z_of_lt h, neg_le_neg_iff], norm_cast, exact nat.find_min' (exists_pred_iterate_of_le _) rfl, }, end lemma to_Z_iterate_succ_of_not_is_max (n : ℕ) (hn : ¬ is_max (succ^[n] i0)) : to_Z i0 (succ^[n] i0) = n := begin let m := (to_Z i0 (succ^[n] i0)).to_nat, have h_eq : (succ^[m] i0) = (succ^[n] i0) := iterate_succ_to_Z _ (le_succ_iterate _ _), by_cases hmn : m = n, { nth_rewrite 1 ← hmn, simp_rw [m], rw [int.to_nat_eq_max, to_Z_of_ge (le_succ_iterate _ _), max_eq_left], exact nat.cast_nonneg _, }, suffices : is_max (succ^[n] i0), from absurd this hn, exact is_max_iterate_succ_of_eq_of_ne h_eq.symm (ne.symm hmn), end lemma to_Z_iterate_pred_of_not_is_min (n : ℕ) (hn : ¬ is_min (pred^[n] i0)) : to_Z i0 (pred^[n] i0) = -n := begin cases n, { simp only [function.iterate_zero, id.def, to_Z_of_eq, nat.cast_zero, neg_zero], }, have : (pred^[n.succ] i0) < i0, { refine lt_of_le_of_ne (pred_iterate_le _ _) (λ h_pred_iterate_eq, hn _), have h_pred_eq_pred : (pred^[n.succ] i0) = (pred^[0] i0), { rwa [function.iterate_zero, id.def], }, exact is_min_iterate_pred_of_eq_of_ne h_pred_eq_pred (nat.succ_ne_zero n), }, let m := (- to_Z i0 (pred^[n.succ] i0)).to_nat, have h_eq : (pred^[m] i0) = (pred^[n.succ] i0) := iterate_pred_to_Z _ this, by_cases hmn : m = n.succ, { nth_rewrite 1 ← hmn, simp_rw [m], rw [int.to_nat_eq_max, to_Z_of_lt this, max_eq_left, neg_neg], rw neg_neg, exact nat.cast_nonneg _, }, { suffices : is_min (pred^[n.succ] i0), from absurd this hn, exact is_min_iterate_pred_of_eq_of_ne h_eq.symm (ne.symm hmn), }, end lemma le_of_to_Z_le {j : ι} (h_le : to_Z i0 i ≤ to_Z i0 j) : i ≤ j := begin cases le_or_lt i0 i with hi hi; cases le_or_lt i0 j with hj hj, { rw [← iterate_succ_to_Z i hi, ← iterate_succ_to_Z j hj], exact monotone.monotone_iterate_of_le_map succ_mono (le_succ _) (int.to_nat_le_to_nat h_le), }, { exact absurd ((to_Z_neg hj).trans_le (to_Z_nonneg hi)) (not_lt.mpr h_le), }, { exact hi.le.trans hj, }, { rw [← iterate_pred_to_Z i hi, ← iterate_pred_to_Z j hj], refine monotone.antitone_iterate_of_map_le pred_mono (pred_le _) (int.to_nat_le_to_nat _), exact neg_le_neg h_le, }, end lemma to_Z_mono {i j : ι} (h_le : i ≤ j) : to_Z i0 i ≤ to_Z i0 j := begin by_cases hi_max : is_max i, { rw le_antisymm h_le (hi_max h_le), }, by_cases hj_min : is_min j, { rw le_antisymm h_le (hj_min h_le), }, cases le_or_lt i0 i with hi hi; cases le_or_lt i0 j with hj hj, { let m := nat.find (exists_succ_iterate_of_le h_le), have hm : (succ^[m] i = j) := nat.find_spec (exists_succ_iterate_of_le h_le), have hj_eq : j = (succ^[(to_Z i0 i).to_nat + m] i0), { rw [← hm, add_comm], nth_rewrite 0 ← iterate_succ_to_Z i hi, rw function.iterate_add, }, by_contra h, push_neg at h, by_cases hm0 : m = 0, { rw [hm0, function.iterate_zero, id.def] at hm, rw hm at h, exact lt_irrefl _ h, }, refine hi_max (max_of_succ_le (le_trans _ (@le_of_to_Z_le _ _ _ _ _ i0 _ _ _))), { exact j, }, { have h_succ_le : (succ^[(to_Z i0 i).to_nat + 1] i0) ≤ j, { rw hj_eq, refine monotone.monotone_iterate_of_le_map succ_mono (le_succ i0) (add_le_add_left _ _), exact nat.one_le_iff_ne_zero.mpr hm0, }, rwa [function.iterate_succ', function.comp_app, iterate_succ_to_Z i hi] at h_succ_le, }, { exact h.le, }, }, { exact absurd h_le (not_le.mpr (hj.trans_le hi)), }, { exact (to_Z_neg hi).le.trans (to_Z_nonneg hj), }, { let m := nat.find (exists_pred_iterate_of_le h_le), have hm : (pred^[m] j = i) := nat.find_spec (exists_pred_iterate_of_le h_le), have hj_eq : i = (pred^[(-to_Z i0 j).to_nat + m] i0), { rw [← hm, add_comm], nth_rewrite 0 ← iterate_pred_to_Z j hj, rw function.iterate_add, }, by_contra h, push_neg at h, by_cases hm0 : m = 0, { rw [hm0, function.iterate_zero, id.def] at hm, rw hm at h, exact lt_irrefl _ h, }, refine hj_min (min_of_le_pred _), refine (@le_of_to_Z_le _ _ _ _ _ i0 _ _ _).trans _, { exact i, }, { exact h.le, }, { have h_le_pred : i ≤ (pred^[(-to_Z i0 j).to_nat + 1] i0), { rw hj_eq, refine monotone.antitone_iterate_of_map_le pred_mono (pred_le i0) (add_le_add_left _ _), exact nat.one_le_iff_ne_zero.mpr hm0, }, rwa [function.iterate_succ', function.comp_app, iterate_pred_to_Z j hj] at h_le_pred, }, }, end lemma to_Z_le_iff (i j : ι) : to_Z i0 i ≤ to_Z i0 j ↔ i ≤ j := ⟨le_of_to_Z_le, to_Z_mono⟩ lemma to_Z_iterate_succ [no_max_order ι] (n : ℕ) : to_Z i0 (succ^[n] i0) = n := to_Z_iterate_succ_of_not_is_max n (not_is_max _) lemma to_Z_iterate_pred [no_min_order ι] (n : ℕ) : to_Z i0 (pred^[n] i0) = -n := to_Z_iterate_pred_of_not_is_min n (not_is_min _) lemma injective_to_Z : function.injective (to_Z i0) := λ i j hij, le_antisymm (le_of_to_Z_le hij.le) (le_of_to_Z_le hij.symm.le) end to_Z section order_iso variables [succ_order ι] [pred_order ι] [is_succ_archimedean ι] /-- `to_Z` defines an `order_iso` between `ι` and its range. -/ noncomputable def order_iso_range_to_Z_of_linear_succ_pred_arch [hι : nonempty ι] : ι ≃o set.range (to_Z hι.some) := { to_equiv := equiv.of_injective _ injective_to_Z, map_rel_iff' := to_Z_le_iff, } @[priority 100] instance countable_of_linear_succ_pred_arch : countable ι := begin casesI is_empty_or_nonempty ι with _ hι, { apply_instance, }, { exact countable.of_equiv _ (order_iso_range_to_Z_of_linear_succ_pred_arch).symm.to_equiv, }, end /-- If the order has neither bot nor top, `to_Z` defines an `order_iso` between `ι` and `ℤ`. -/ noncomputable def order_iso_int_of_linear_succ_pred_arch [no_max_order ι] [no_min_order ι] [hι : nonempty ι] : ι ≃o ℤ := { to_fun := to_Z hι.some, inv_fun := λ n, if 0 ≤ n then (succ^[n.to_nat] hι.some) else (pred^[(-n).to_nat] hι.some), left_inv := λ i, begin cases le_or_lt hι.some i with hi hi, { have h_nonneg : 0 ≤ to_Z hι.some i := to_Z_nonneg hi, simp_rw if_pos h_nonneg, exact iterate_succ_to_Z i hi, }, { have h_neg : to_Z hι.some i < 0 := to_Z_neg hi, simp_rw if_neg (not_le.mpr h_neg), exact iterate_pred_to_Z i hi, }, end, right_inv := λ n, begin cases le_or_lt 0 n with hn hn, { simp_rw if_pos hn, rw to_Z_iterate_succ, exact int.to_nat_of_nonneg hn, }, { simp_rw if_neg (not_le.mpr hn), rw to_Z_iterate_pred, simp only [hn.le, int.to_nat_of_nonneg, right.nonneg_neg_iff, neg_neg], }, end, map_rel_iff' := to_Z_le_iff, } /-- If the order has a bot but no top, `to_Z` defines an `order_iso` between `ι` and `ℕ`. -/ def order_iso_nat_of_linear_succ_pred_arch [no_max_order ι] [order_bot ι] : ι ≃o ℕ := { to_fun := λ i, (to_Z ⊥ i).to_nat, inv_fun := λ n, succ^[n] ⊥, left_inv := λ i, by { simp_rw if_pos (to_Z_nonneg bot_le), exact iterate_succ_to_Z i bot_le, }, right_inv := λ n, begin simp_rw if_pos bot_le, rw to_Z_iterate_succ, exact int.to_nat_coe_nat n, end, map_rel_iff' := λ i j, begin simp only [equiv.coe_fn_mk, int.to_nat_le], rw [← @to_Z_le_iff ι _ _ _ _ ⊥, int.to_nat_of_nonneg (to_Z_nonneg bot_le)], end, } /-- If the order has both a bot and a top, `to_Z` gives an `order_iso` between `ι` and `finset.range n` for some `n`. -/ def order_iso_range_of_linear_succ_pred_arch [order_bot ι] [order_top ι] : ι ≃o finset.range ((to_Z ⊥ (⊤ : ι)).to_nat + 1) := { to_fun := λ i, ⟨(to_Z ⊥ i).to_nat, finset.mem_range_succ_iff.mpr (int.to_nat_le_to_nat ((to_Z_le_iff _ _).mpr le_top))⟩, inv_fun := λ n, succ^[n] ⊥, left_inv := λ i, iterate_succ_to_Z i bot_le, right_inv := λ n, begin ext1, simp only [subtype.coe_mk], refine le_antisymm _ _, { rw int.to_nat_le, exact (to_Z_iterate_succ_le _), }, by_cases hn_max : is_max (succ^[↑n] (⊥ : ι)), { rw [← is_top_iff_is_max, is_top_iff_eq_top] at hn_max, rw hn_max, exact nat.lt_succ_iff.mp (finset.mem_range.mp n.prop), }, { rw to_Z_iterate_succ_of_not_is_max _ hn_max, simp only [int.to_nat_coe_nat], }, end, map_rel_iff' := λ i j, begin simp only [equiv.coe_fn_mk, subtype.mk_le_mk, int.to_nat_le], rw [← @to_Z_le_iff ι _ _ _ _ ⊥, int.to_nat_of_nonneg (to_Z_nonneg bot_le)], end, } end order_iso
ab0f929a1428c84fad8bfbddba083f37a3ec1a0b
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/inClassNotes/type_library/list_test.lean
85fd16332f2f5666be583fedf82bcd10cfa6947e
[]
no_license
liuxin-James/complogic-s21
0d55b76dbe25024473d31d98b5b83655c365f811
13e03e0114626643b44015c654151fb651603486
refs/heads/master
1,681,109,264,463
1,618,848,261,000
1,618,848,261,000
337,599,491
0
0
null
1,613,141,619,000
1,612,925,555,000
null
UTF-8
Lean
false
false
10,463
lean
import .list namespace hidden -- list is polymorphic #check list nat -- nat lives in Type #check list bool -- bool lives in Type #check list Type -- Type lives in Type 1 #check list (Type 1) -- Type 1 lives in Type 2 /- Some lists of nats -/ #eval list.nil -- can't infer α #eval @list.nil nat -- can't infer α #eval (list.nil : list nat) /- Top-down (outside-in) refinement -/ def lnat0 : list nat := list.nil def lnat1 : list nat := list.cons (1) (list.cons (2) list.nil ) def lstr1 : list string := list.cons ("1") (list.cons ("2") (list.nil) ) /- cons / \ "hi" cons / \ "ho" ... -/ -- FUNCTIONS def head { α : Type } : list α → option α | list.nil := none | (list.cons h t) := some h #reduce head lnat1 def tail { α : Type } : list α → option (list α) | list.nil := none | (list.cons h t) := some t -- recursive definition of length (by cases) -- strucute recursion can guarantees to teminate def length {α : Type} : list α → nat | list.nil := 0 | (list.cons h t) := (length t) + 1 -- length in context def append {α : Type} : list α → list α → list α | list.nil m := m | (list.cons h t) m := list.cons h (append t m) -- h :: append t m #eval append lnat0 lnat1 def pure {α : Type} : α → list α | a := list.cons a list.nil def reverse {α : Type} : list α → list α | list.nil := list.nil | (list.cons h t) := append(reverse t) (pure h) #eval reverse lnat1 #eval reverse (list.cons 1 (list.cons 2 list.nil)) end hidden /- From here on, we use Lean's identical definition of the list type, but we gain the benefit of additional notation. -/ /- NOTATION -/ #eval list.cons "hi" (list.cons "ho" list.nil) #eval ["hi", "ho"] #eval list.cons "hi" ["ho"] #eval "hi"::["ho"] #eval let s : string := let a := ["hi","ho"] in (match a with | list.nil := "oops" | (h::t) := h end) in s ++ "!" -- more examples #eval [1,2,3,4,5] #eval 1::[2,3,4,5] #eval 1::2::3::4::5::list.nil def head { α : Type } : list α → option α | list.nil := none | (h::t) := some h def tail { α : Type } : list α → option (list α) | list.nil := none | (h::t) := some t -- recursive definition of length (by cases) def length {α : Type} : list α → nat | list.nil := 0 | (h::t) := (_) + 1 -- length in context #eval list.append ["Hi","Ho"] ["!"] #eval ["Hi","Ho"] ++ ["!"] #check @pure list #eval (pure 5 : list nat) #eval (pure 5 : option nat) -- whoa (later) def reverse {α : Type} : list α → list α | [] := [] | (h::t) := (reverse t)++[h] -- use nice notation here universe u /- HIGHER ORDER FUNCTIONS -/ /- Suppose we want to map a list of strings to a list of bools, where each bool is tt if the length of the corresponding string is even, and false otherwise. -/ def strlist := ["Hello", "There", "Lean"] def map_ev_string_bool : list string → list bool | list.nil := list.nil | (h::t) := (h.length%2=0)::(map_ev_string_bool t) #eval map_ev_string_bool strlist def map_odd_string_bool : list string → list bool | list.nil := list.nil | (h::t) := (h.length%2=1)::_ def map_string_bang_string : list string → list string | list.nil := list.nil | (h::t) := (h++"!")::(map_string_bang_string t) #eval map_string_bang_string strlist /- Dimensions of variation? -- argument list element type, α -- result list element type, β -- function used to transform α → β -/ def map_list {α β : Type u} : (α → β) → list α → list β | f list.nil := list.nil | f (h::t) := (f h)::(map_list f t) #eval map_list (λ (s : string), s.length) (strlist) #eval map_list (λ (s : string), (s.length%2=0:bool)) (strlist) def exclafy : list string → list string := map_list (λ (s : string), s++"!") -- arg #eval exclafy ["Whoa","That","Is","COOL"] /- Define reduce, or fold, over a list. Let's start with an example. Suppose we're given a list of strings and we want to know if they are all of even length. What we need is a function, allEvenLength : list string → bool, that returns tt iff all strings in the list have even length. Let's do an informal case analysis: First we consider the case where the given list of strings, l, is not empty. In this case it has the form (h::t), with (h : string) and (t : list string). And in this case, every string in the list will have even length iff (1) h is of even length *AND* every string in the tail, t, of l, also has even length. Now consider the case where l is nil. What Boolean value do we return? One might guess false ... incorrectly. Suppose our function returned false (ff) for the empty list. Consider a case where l = ["Hi"]. That is, the list, l = (list.cons "Hi" list.nil). The list is non-empty, so the first rule applies: return the AND of two Boolean values: one for "Hi" and one for the rest of the list. For "Hi" we will get true, as "Hi" has even length, so our result will have to be (tt ∧ X), where X is the result for the rest of the list. But here the rest of the list is empty. So what *must* R, the result for the empty list, be for the function to return the right result, tt (as all strings in the list are even length)? Clearly the answer must be true (tt). What would happen if it were ff? So now we have our algorithm! -/ -- first a predicate function def isEvenStr (s : string) : bool := (s.length % 2 = 0) def allEvenStr : list string → bool | list.nil := tt | (h::t) := band (isEvenStr h) (allEvenStr t) #eval allEvenStr [] #eval allEvenStr ["Hi"] #eval allEvenStr ["Hi!"] #eval allEvenStr ["Hi","There!"] #eval allEvenStr ["Hi","Ho!"] /- Now suppose we want to know if there is *at least* one string of even length in any given list of strings. Again we do a case analysis. There is at least one even-length string in a non-empty list, l = h::t, iff h is of even length OR there is at least one even-lenght string in the rest of the list. Now suppose t is the empty string. What result must be returned for the function to work. Consider the case where l = ["Hi!"] = (cons "Hi" nil). The correct answer here is (ff ∨ X), with the ff because "Hi!" is not of even length, and X is the answer for the empty list. To get the correct answer, it must be that X = ff. So now again we have our algorithm. -/ /- The key idea both here and in the preceding example is that the answer for the empty list must leave the result for the preceding elements unchanged. The result must be the *identity element* for the Boolean operator being used to combine the values for the head and rest of the list. The identity element for Boolean and is tt, and for Boolean or it is ff. ∀ (b : bool), b ∧ tt = b ∀ (b : bool), b ∨ ff = b We can see these propositions are true by case analysis. Case 1: b = tt. In this case b ∧ tt = tt and b = tt so b ∧ t = b. Exercise: Finish up. -/ def someEvenStr : list string → bool | list.nil := ff | (h::t) := bor (isEvenStr h) (someEvenStr t) #eval someEvenStr [] #eval someEvenStr ["Hi"] #eval someEvenStr ["Hi!"] #eval someEvenStr ["Hello","Lean"] #eval someEvenStr ["Hello","Lean!"] /- Now a key observation: Our two functions are very similar, varying in only a few dimensions. Let's factor dimensions of variation into parameter to generalize our definition. First, we want to be able to operte on lists of values of any type, not just strings. Let call the list element type α. Second, in general, we want to reduce a list (l : list α) to a value of some other type, let's call it β, just as in our examples we reduced lists of values of type α = string to a final result of type β = bool. Third, we need a function to compute the answer for a non-empty list (h::t) where (1) (h : α), (2) the result for the rest of the list is of type β, and (3) the final combined result is of type β. The type of this reducing function is thus α → β → β. Finally, we need a result value for the empty list. This value obviously has to be of type β. Those are our parameters! Given: { α : Type u} { β : Type u} ( f : α → β → β ) ( id : β) ( l : list α) Compute result : β -/ -- By case analysis on the list l def fold { α : Type u} { β : Type u} : ( α → β → β ) → β → list α → β | f id list.nil := id | f id (h::t) := f h (fold f id t) -- allEven def allStrCombine : string → bool → bool | s b := band (isEvenStr s) b def allEvenStr' (l : list string) : bool := fold allStrCombine tt l def someStrCombine : string → bool → bool | s b := bor (isEvenStr s) b def someEvenStr' (l : list string) : bool := fold someStrCombine ff l #eval allEvenStr' [] #eval allEvenStr' ["Hi"] #eval allEvenStr' ["Hi!"] #eval allEvenStr' ["Hi","There!"] #eval allEvenStr' ["Hi","Ho!"] #eval someEvenStr [] #eval someEvenStr' ["Hi"] #eval someEvenStr' ["Hi!"] #eval someEvenStr' ["Hello","Lean"] #eval someEvenStr' ["Hello","Lean!"] #eval fold nat.add 0 [10,9,8,7,6,5,4,3,2,1] #eval fold nat.mul 1 [10,9,8,7,6,5,4,3,2,1] #eval fold string.append "" ["Hello, ", "Lean. ", "We ", "love ", "you!"] /- Given a predicate function on the type of element in a list, return the sublist of elements for which predicate is true. Define filter by case analysis with one case a base case and the other case using "structural recursion" on list argument. An opportunity to introduces if/then/else expression in Lean. -/ def filter' {α : Type u} : (α → bool) → list α → list α | f list.nil := list.nil | f (h::t) := if (f h) then h::(filter' f t) else (filter' f t) /- Take opportunity to introduce let bindings. Binds name to result of evaluation, then evaluates expr in context of that additional binding. -/ def filter {α : Type u} : (α → bool) → list α → list α | f list.nil := list.nil | f (h::t) := let restOfResult := (filter f t) in if (f h) then h::restOfResult else restOfResult def isEven (n : nat) : bool := n%2 = 0 #eval filter isEven [] #eval filter isEven [0,1,2,3,5,6,7,9,10] /- Note: the body of a let can use another let. That is, let bindings can be chained. let x := 1 in let y := 2+3 in let z := 3*4 in x + y + z To what value does this expression reduce? -/
b67d4c9cb1cc5f0d50d6dbd49b7a24bd217bc7d6
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/list/basic.lean
427fe3b39d16282346ab2942edad8fc15679516d
[ "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
155,352
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import deprecated.group import data.nat.basic import order.rel_classes import algebra.order_functions /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head 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 ⟩ 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_injective {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_injective 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 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⟩ theorem mem_map_of_injective {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 _⟩ lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[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] /-! ### length -/ 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 ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end lemma length_injective [subsingleton α] : injective (length : list α → ℕ) := length_injective_iff.mpr $ by apply_instance /-! ### set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] := by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] } /-! ### 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))) 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_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_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 append_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 _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end 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⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl @[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: 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 @[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_right {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_left {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_right' {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_left' {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_right h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_left_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 /-! ### 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]] /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /-! ### 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 _ _ _ @[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x := append_nil (f x) /-! ### concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by 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 simp /-! ### 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 α) := left_inverse.injective 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)⟩ /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[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 /-! ### is_nil -/ lemma is_nil_iff_eq_nil {l : list α} : l.is_nil ↔ l = [] := list.cases_on l (by simp [is_nil]) (by simp [is_nil]) /-! ### 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₁ theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l | [] h := absurd rfl h | [a] h := or.inl rfl | (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) } /-! ### last' -/ @[simp] theorem last'_is_none : ∀ {l : list α}, (last' l).is_none ↔ l = [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_none (b::l)] @[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_some (b::l)] theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h | [] x hx := false.elim $ by simpa using hx | [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩ | (a::b::l) x hx := begin rw last' at hx, rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩, use cons_ne_nil _ _, rwa [last_cons] end theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l := let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _ theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l | [] a ha := (option.not_mem_none a ha).elim | [a] _ rfl := rfl | (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] } theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget | [] := by simp [ilast, arbitrary] | [a] := rfl | [a, b] := rfl | [a, b, c] := rfl | (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)] @[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α), last' (l₁ ++ a :: l₂) = last' (a :: l₂) | [] a l₂ := rfl | [b] a l₂ := rfl | (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons] theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []), last' (l₁ ++ l₂) = last' l₂ | [] hl₂ := by contradiction | (b::l₂) _ := last'_append_cons l₁ b l₂ /-! ### head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l | [] h := (option.not_mem_none _ h).elim | (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl } @[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 : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l | [] a h := by contradiction | (b::l) a h := by { simp at h, simp [h] } theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l | [] h := by contradiction | (a::l) h := rfl theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := cons_head'_tail (head_mem_head' h) @[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := 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_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_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 sublist.append_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 sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact ih.append_right [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff] using h.reverse, λ h, h.append_right l⟩ theorem sublist.append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (hl.append_right _).trans ((append_sublist_append_left _).2 hr) theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset 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 _ (sublist.subset s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, h.subset (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 $ s.subset 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, priority 990] 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, priority 980] 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_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (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_len_le 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 /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[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 _ _ /-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as `hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make such a rewrite, with `rw (nth_le_of_eq h)`. -/ lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) : nth_le L i hi = nth_le L' i (h ▸ hi) := by { congr, exact h} @[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_zero [inhabited α] {L : list α} (h : 0 < L.length) : L.nth_le 0 h = L.head := by { cases L, cases h, simp, } 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 _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) : (list.repeat a n).nth_le m h = 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] lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[ext] 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_len_le h₁, nth_len_le], 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 eq_cons_of_length_one {l : list α} (h : l.length = 1) : l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] := begin refine ext_le (by convert h) (λ n h₁ h₂, _), simp only [nth_le_singleton], congr, exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂) end 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] @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] 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₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /-! ### map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl 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₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end 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 (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op 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 @[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /-! ### 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 /-! ### 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_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → 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_le (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 theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m) | n 0 := by simp | 0 m := by simp | (succ n) (succ m) := by simp [min_succ_succ, take_repeat] lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } 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)] /-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first `i` elements of `l₂` to `l₁`. -/ lemma take_append {l₁ l₂ : list α} (i : ℕ) : take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self] end /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) : nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) := by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ } /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) : nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) := by { simp at hi, rw nth_le_take L _ hi.1 } @[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_length (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)] /-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements up to `i` in `l₂`. -/ lemma drop_append {l₁ l₂ : list α} (i : ℕ) : drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, drop, l₁_ih] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) : nth_le L (i + j) h = nth_le (L.drop i) j begin have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h, rw (take_append_drop i L).symm at h, simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h end := begin have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)], rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right]; simp [A] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) : nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) := by rw nth_le_drop @[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 ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } 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 /- scanl -/ lemma length_scanl {β : Type*} {f : α → β → α} : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] /- 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 /-! ### prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[to_additive] theorem prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] 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] 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] 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]] @[to_additive] theorem prod_eq_foldr : l.prod = foldr (*) 1 l := list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α → β) [is_monoid_hom f] : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, (is_monoid_hom.map_one f).symm], exact l.foldl_hom _ _ _ 1 (is_monoid_hom.map_mul f) } -- `to_additive` chokes on the next few lemmas, so we do them by hand below @[simp] lemma prod_take_mul_prod_drop : ∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], } @[simp] lemma prod_take_succ : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], } /-- A list with product not one must have positive length. -/ lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } end monoid @[simp] lemma sum_take_add_sum_drop [add_monoid α] : ∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], } @[simp] lemma sum_take_succ [add_monoid α] : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], } lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length) (h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' := begin apply ext_le h (λ i h₁ h₂, _), have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁), rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this, exact add_left_cancel this end lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) : monotone (λ i, (L.take i).sum) := begin apply monotone_of_monotone_nat (λ n, _), by_cases h : n < L.length, { rw sum_take_succ _ _ h, exact le_add_right (le_refl _) }, { push_neg at h, simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] } end /-- A list with sum not zero must have positive length. -/ lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } /-- If all elements in a list are bounded below by `1`, then the length of the list is bounded by the sum of the elements. -/ lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum := begin induction L with j L IH h, { simp }, rw [sum_cons, length, add_comm], exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi))) end -- Now we tie those lemmas back to their multiplicative versions. attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one /-- A list with positive sum must have positive length. -/ -- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications. lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) : 0 < L.length := length_pos_of_sum_ne_zero L (ne_of_gt h) @[simp, to_additive] 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]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[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] lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end -- Several lemmas about sum/head/tail for `list ℕ`. -- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`. -- We'd like to state this as `L.head * L.tail.prod = L.prod`, -- but because `L.head` relies on an inhabited instances and -- returns a garbage value for the empty list, this is not possible. -- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`, -- and below, restate the lemma just for `ℕ`. @[to_additive] lemma head_mul_tail_prod' [monoid α] (L : list α) : (L.nth 0).get_or_else 1 * L.tail.prod = L.prod := by { cases L, { simp, refl, }, { simp, }, } lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum := by { cases L, { simp, refl, }, { simp, }, } lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L) lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head := by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel] section variables {G : Type*} [comm_group G] attribute [to_additive] alternating_prod @[simp, to_additive] lemma alternating_prod_nil : alternating_prod ([] : list G) = 1 := rfl @[simp, to_additive] lemma alternating_prod_singleton (g : G) : alternating_prod [g] = g := rfl @[simp, to_additive alternating_sum_cons_cons'] lemma alternating_prod_cons_cons (g h : G) (l : list G) : alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) : alternating_sum (g :: h :: l) = g - h + alternating_sum l := rfl 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]] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end /-! ### lexicographic ordering -/ /-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which `[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`. The definition is given for any relation `r`, not only strict orders. -/ 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⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. 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 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 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 sublist.map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := filter_map_eq_map f ▸ s.filter_map _ /-! ### 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 := (filter_sublist l).subset 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₂ := filter_map_eq_filter p ▸ s.filter_map _ 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, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } 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 theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] 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⟩ theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append 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] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp 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_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_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 tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix theorem tail_subset (l : list α) : tail l ⊆ l := (sublist_of_suffix (tail_suffix l)).subset 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, priority 1100] 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, nat.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_injective 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 -/ /-- Auxiliary function to construct the list of all sublists of a given length. Given an integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/ 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) /-- The list of all sublists of a list `l` that are of length `n`. For instance, for `l = [0, 1, 2, 3]` and `n = 2`, one gets `[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/ 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 (sublists_len_sublist_sublists' _ _).append ((sublists_len_sublist_sublists' _ _).map _) 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 IH.append ((IHn s).map _) } 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 ((sublists_len_sublist_sublists' _ _).subset h), length_of_sublists_len h⟩, λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self 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, priority 980] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] 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) 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 : α} {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 : α} {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 := (erasep_sublist l).subset theorem 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, priority 980] 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 := (erase_sublist a l).subset theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact 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₁ := (diff_sublist _ _).subset 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 sublist.diff_right : ∀ {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, (h.erase _).diff_right] 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 (h.erase b) end diff /-! ### 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) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end /-! ### 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 /-! ### disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ 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 disjoint_nil_right (l : list α) : disjoint l [] := by rw disjoint_comm; exact disjoint_nil_left _ @[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp, priority 1100] 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 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 -- A jumble of lost lemmas: theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_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 end list @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm namespace list @[to_additive] theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) : (L.map (g ∘ f)).prod = g ((L.map f).prod) := by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm} theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, r * f b)).sum = r * (L.map f).sum := sum_map_hom L f $ add_monoid_hom.mul_left r theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, f b * r)).sum = (L.map f).sum * r := sum_map_hom L f $ add_monoid_hom.mul_right r end list
ec870a479f8c997c4f7bc7eabf2294a6c5798f12
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/explode_widget_auto.lean
2fb28f5ece2dd00e5ddb5dae1a3a32d23809ec0d
[]
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
651
lean
/- Copyright (c) 2020 Minchao Wu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Minchao Wu -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.explode import Mathlib.tactic.interactive_expr import Mathlib.PostPort namespace Mathlib /-! # `#explode_widget` command Render a widget that displays an `#explode` proof, providing more interactivity such as jumping to definitions and exploding constants occurring in the exploded proofs. -/ namespace tactic namespace explode_widget /-- Redefine some of the style attributes for better formatting. -/ end Mathlib
111cb27056c875556a3c11e037f063b02ede8103
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/convex/simplicial_complex/basic.lean
20a7e59aa8b218ab6b97af1f6d88537efb88c162
[ "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
9,765
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.topology import tactic.by_contra /-! # Simplicial complexes In this file, we define simplicial complexes in `𝕜`-modules. A simplicial complex is a collection of simplices closed by inclusion (of vertices) and intersection (of underlying sets). We model them by a downward-closed set of affine independent finite sets whose convex hulls "glue nicely", each finite set and its convex hull corresponding respectively to the vertices and the underlying set of a simplex. ## Main declarations * `simplicial_complex 𝕜 E`: A simplicial complex in the `𝕜`-module `E`. * `simplicial_complex.vertices`: The zero dimensional faces of a simplicial complex. * `simplicial_complex.facets`: The maximal faces of a simplicial complex. ## Notation `s ∈ K` means that `s` is a face of `K`. `K ≤ L` means that the faces of `K` are faces of `L`. ## Implementation notes "glue nicely" usually means that the intersection of two faces (as sets in the ambient space) is a face. Given that we store the vertices, not the faces, this would be a bit awkward to spell. Instead, `simplicial_complex.inter_subset_convex_hull` is an equivalent condition which works on the vertices. ## TODO Simplicial complexes can be generalized to affine spaces once `convex_hull` has been ported. -/ open finset set variables (𝕜 E : Type*) {ι : Type*} [ordered_ring 𝕜] [add_comm_group E] [module 𝕜 E] namespace geometry /-- A simplicial complex in a `𝕜`-module is a collection of simplices which glue nicely together. Note that the textbook meaning of "glue nicely" is given in `geometry.simplicial_complex.disjoint_or_exists_inter_eq_convex_hull`. It is mostly useless, as `geometry.simplicial_complex.convex_hull_inter_convex_hull` is enough for all purposes. -/ -- TODO: update to new binder order? not sure what binder order is correct for `down_closed`. @[ext] structure simplicial_complex := (faces : set (finset E)) (not_empty_mem : ∅ ∉ faces) (indep : ∀ {s}, s ∈ faces → affine_independent 𝕜 (coe : (s : set E) → E)) (down_closed : ∀ {s t}, s ∈ faces → t ⊆ s → t ≠ ∅ → t ∈ faces) (inter_subset_convex_hull : ∀ {s t}, s ∈ faces → t ∈ faces → convex_hull 𝕜 ↑s ∩ convex_hull 𝕜 ↑t ⊆ convex_hull 𝕜 (s ∩ t : set E)) namespace simplicial_complex variables {𝕜 E} {K : simplicial_complex 𝕜 E} {s t : finset E} {x : E} /-- A `finset` belongs to a `simplicial_complex` if it's a face of it. -/ instance : has_mem (finset E) (simplicial_complex 𝕜 E) := ⟨λ s K, s ∈ K.faces⟩ /-- The underlying space of a simplicial complex is the union of its faces. -/ def space (K : simplicial_complex 𝕜 E) : set E := ⋃ s ∈ K.faces, convex_hull 𝕜 (s : set E) lemma mem_space_iff : x ∈ K.space ↔ ∃ s ∈ K.faces, x ∈ convex_hull 𝕜 (s : set E) := mem_Union₂ lemma convex_hull_subset_space (hs : s ∈ K.faces) : convex_hull 𝕜 ↑s ⊆ K.space := subset_bUnion_of_mem hs protected lemma subset_space (hs : s ∈ K.faces) : (s : set E) ⊆ K.space := (subset_convex_hull 𝕜 _).trans $ convex_hull_subset_space hs lemma convex_hull_inter_convex_hull (hs : s ∈ K.faces) (ht : t ∈ K.faces) : convex_hull 𝕜 ↑s ∩ convex_hull 𝕜 ↑t = convex_hull 𝕜 (s ∩ t : set E) := (K.inter_subset_convex_hull hs ht).antisymm $ subset_inter (convex_hull_mono $ set.inter_subset_left _ _) $ convex_hull_mono $ set.inter_subset_right _ _ /-- The conclusion is the usual meaning of "glue nicely" in textbooks. It turns out to be quite unusable, as it's about faces as sets in space rather than simplices. Further, additional structure on `𝕜` means the only choice of `u` is `s ∩ t` (but it's hard to prove). -/ lemma disjoint_or_exists_inter_eq_convex_hull (hs : s ∈ K.faces) (ht : t ∈ K.faces) : disjoint (convex_hull 𝕜 (s : set E)) (convex_hull 𝕜 ↑t) ∨ ∃ u ∈ K.faces, convex_hull 𝕜 (s : set E) ∩ convex_hull 𝕜 ↑t = convex_hull 𝕜 ↑u := begin classical, by_contra' h, refine h.2 (s ∩ t) (K.down_closed hs (inter_subset_left _ _) $ λ hst, h.1 $ (K.inter_subset_convex_hull hs ht).trans _) _, { rw [←coe_inter, hst, coe_empty, convex_hull_empty], refl }, { rw [coe_inter, convex_hull_inter_convex_hull hs ht] } end /-- Construct a simplicial complex by removing the empty face for you. -/ @[simps] def of_erase (faces : set (finset E)) (indep : ∀ s ∈ faces, affine_independent 𝕜 (coe : (s : set E) → E)) (down_closed : ∀ s ∈ faces, ∀ t ⊆ s, t ∈ faces) (inter_subset_convex_hull : ∀ s t ∈ faces, convex_hull 𝕜 ↑s ∩ convex_hull 𝕜 ↑t ⊆ convex_hull 𝕜 (s ∩ t : set E)) : simplicial_complex 𝕜 E := { faces := faces \ {∅}, not_empty_mem := λ h, h.2 (mem_singleton _), indep := λ s hs, indep _ hs.1, down_closed := λ s t hs hts ht, ⟨down_closed _ hs.1 _ hts, ht⟩, inter_subset_convex_hull := λ s t hs ht, inter_subset_convex_hull _ hs.1 _ ht.1 } /-- Construct a simplicial complex as a subset of a given simplicial complex. -/ @[simps] def of_subcomplex (K : simplicial_complex 𝕜 E) (faces : set (finset E)) (subset : faces ⊆ K.faces) (down_closed : ∀ {s t}, s ∈ faces → t ⊆ s → t ∈ faces) : simplicial_complex 𝕜 E := { faces := faces, not_empty_mem := λ h, K.not_empty_mem (subset h), indep := λ s hs, K.indep (subset hs), down_closed := λ s t hs hts _, down_closed hs hts, inter_subset_convex_hull := λ s t hs ht, K.inter_subset_convex_hull (subset hs) (subset ht) } /-! ### Vertices -/ /-- The vertices of a simplicial complex are its zero dimensional faces. -/ def vertices (K : simplicial_complex 𝕜 E) : set E := {x | {x} ∈ K.faces} lemma mem_vertices : x ∈ K.vertices ↔ {x} ∈ K.faces := iff.rfl lemma vertices_eq : K.vertices = ⋃ k ∈ K.faces, (k : set E) := begin ext x, refine ⟨λ h, mem_bUnion h $ mem_coe.2 $ mem_singleton_self x, λ h, _⟩, obtain ⟨s, hs, hx⟩ := mem_Union₂.1 h, exact K.down_closed hs (finset.singleton_subset_iff.2 $ mem_coe.1 hx) (singleton_ne_empty _), end lemma vertices_subset_space : K.vertices ⊆ K.space := vertices_eq.subset.trans $ Union₂_mono $ λ x hx, subset_convex_hull 𝕜 x lemma vertex_mem_convex_hull_iff (hx : x ∈ K.vertices) (hs : s ∈ K.faces) : x ∈ convex_hull 𝕜 (s : set E) ↔ x ∈ s := begin refine ⟨λ h, _, λ h, subset_convex_hull _ _ h⟩, classical, have h := K.inter_subset_convex_hull hx hs ⟨by simp, h⟩, by_contra H, rwa [←coe_inter, finset.disjoint_iff_inter_eq_empty.1 (finset.disjoint_singleton_right.2 H).symm, coe_empty, convex_hull_empty] at h, end /-- A face is a subset of another one iff its vertices are. -/ lemma face_subset_face_iff (hs : s ∈ K.faces) (ht : t ∈ K.faces) : convex_hull 𝕜 (s : set E) ⊆ convex_hull 𝕜 ↑t ↔ s ⊆ t := ⟨λ h x hxs, (vertex_mem_convex_hull_iff (K.down_closed hs (finset.singleton_subset_iff.2 hxs) $ singleton_ne_empty _) ht).1 (h (subset_convex_hull 𝕜 ↑s hxs)), convex_hull_mono⟩ /-! ### Facets -/ /-- A facet of a simplicial complex is a maximal face. -/ def facets (K : simplicial_complex 𝕜 E) : set (finset E) := {s ∈ K.faces | ∀ ⦃t⦄, t ∈ K.faces → s ⊆ t → s = t} lemma mem_facets : s ∈ K.facets ↔ s ∈ K.faces ∧ ∀ t ∈ K.faces, s ⊆ t → s = t := mem_sep_iff lemma facets_subset : K.facets ⊆ K.faces := λ s hs, hs.1 lemma not_facet_iff_subface (hs : s ∈ K.faces) : (s ∉ K.facets ↔ ∃ t, t ∈ K.faces ∧ s ⊂ t) := begin refine ⟨λ (hs' : ¬ (_ ∧ _)), _, _⟩, { push_neg at hs', obtain ⟨t, ht⟩ := hs' hs, exact ⟨t, ht.1, ⟨ht.2.1, (λ hts, ht.2.2 (subset.antisymm ht.2.1 hts))⟩⟩ }, { rintro ⟨t, ht⟩ ⟨hs, hs'⟩, have := hs' ht.1 ht.2.1, rw this at ht, exact ht.2.2 (subset.refl t) } -- `has_ssubset.ssubset.ne` would be handy here end /-! ### The semilattice of simplicial complexes `K ≤ L` means that `K.faces ⊆ L.faces`. -/ variables (𝕜 E) /-- The complex consisting of only the faces present in both of its arguments. -/ instance : has_inf (simplicial_complex 𝕜 E) := ⟨λ K L, { faces := K.faces ∩ L.faces, not_empty_mem := λ h, K.not_empty_mem (set.inter_subset_left _ _ h), indep := λ s hs, K.indep hs.1, down_closed := λ s t hs hst ht, ⟨K.down_closed hs.1 hst ht, L.down_closed hs.2 hst ht⟩, inter_subset_convex_hull := λ s t hs ht, K.inter_subset_convex_hull hs.1 ht.1 }⟩ instance : semilattice_inf (simplicial_complex 𝕜 E) := { inf := (⊓), inf_le_left := λ K L s hs, hs.1, inf_le_right := λ K L s hs, hs.2, le_inf := λ K L M hKL hKM s hs, ⟨hKL hs, hKM hs⟩, .. (partial_order.lift faces $ λ x y, ext _ _) } instance : has_bot (simplicial_complex 𝕜 E) := ⟨{ faces := ∅, not_empty_mem := set.not_mem_empty ∅, indep := λ s hs, (set.not_mem_empty _ hs).elim, down_closed := λ s _ hs, (set.not_mem_empty _ hs).elim, inter_subset_convex_hull := λ s _ hs, (set.not_mem_empty _ hs).elim }⟩ instance : order_bot (simplicial_complex 𝕜 E) := { bot_le := λ K, set.empty_subset _, .. simplicial_complex.has_bot 𝕜 E } instance : inhabited (simplicial_complex 𝕜 E) := ⟨⊥⟩ variables {𝕜 E} lemma faces_bot : (⊥ : simplicial_complex 𝕜 E).faces = ∅ := rfl lemma space_bot : (⊥ : simplicial_complex 𝕜 E).space = ∅ := set.bUnion_empty _ lemma facets_bot : (⊥ : simplicial_complex 𝕜 E).facets = ∅ := eq_empty_of_subset_empty facets_subset end simplicial_complex end geometry
f4fc7b2e66cb87130f6158d02964a61ba34f124a
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/data/nat/sub.lean
42c66d7974dc06a3be56513befa58e80b3bd2112
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
6,270
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad Subtraction on the natural numbers, as well as min, max, and distance. -/ namespace nat /- interaction with inequalities -/ protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) protected theorem sub_eq_of_eq_add {n m k : ℕ} (h : k = n + m) : k - n = m := begin rw [h, nat.add_sub_cancel_left] end protected theorem lt_of_sub_pos {m n : ℕ} (h : n - m > 0) : m < n := lt_of_not_ge (assume : m ≥ n, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right {n m k : ℕ} (h : n - k < m - k) : n < m := lt_of_not_ge (assume : m ≤ n, have m - k ≤ n - k, from nat.sub_le_sub_right this _, not_le_of_gt h this) protected theorem lt_of_sub_lt_sub_left {n m k : ℕ} (h : n - m < n - k) : k < m := lt_of_not_ge (assume : m ≤ k, have n - k ≤ n - m, from nat.sub_le_sub_left _ this, not_le_of_gt h this) protected theorem sub_lt_self {m n : ℕ} (h₁ : m > 0) (h₂ : n > 0) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_of_add_le {m n k : ℕ} (h : m + k ≤ n) : m ≤ n - k := calc m = m + k - k : by rw nat.add_sub_cancel ... ≤ n - k : nat.sub_le_sub_right h k protected theorem lt_sub_of_add_lt {m n k : ℕ} (h : m + k < n) : m < n - k := lt_of_succ_le (nat.le_sub_of_add_le (calc succ m + k = succ (m + k) : by rw succ_add ... ≤ n : succ_le_of_lt h)) protected theorem add_lt_of_lt_sub {m n k : ℕ} (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem sub_lt_of_lt_add {k n m : nat} (h₁ : k < n + m) (h₂ : n ≤ k) : k - n < m := have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub h₂) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this /- distance -/ definition dist (n m : ℕ) := (n - m) + (m - n) theorem dist.def (n m : ℕ) : dist n m = (n - m) + (m - n) := rfl @[simp] theorem dist_comm (n m : ℕ) : dist n m = dist m n := by simp [dist.def] @[simp] theorem dist_self (n : ℕ) : dist n n = 0 := by simp [dist.def, nat.sub_self] theorem eq_of_dist_eq_zero {n m : ℕ} (h : dist n m = 0) : n = m := have n - m = 0, from eq_zero_of_add_eq_zero_right h, have n ≤ m, from nat.le_of_sub_eq_zero this, have m - n = 0, from eq_zero_of_add_eq_zero_left h, have m ≤ n, from nat.le_of_sub_eq_zero this, le_antisymm ‹n ≤ m› ‹m ≤ n› theorem dist_eq_zero {n m : ℕ} (h : n = m) : dist n m = 0 := begin rw [h, dist_self] end theorem dist_eq_sub_of_le {n m : ℕ} (h : n ≤ m) : dist n m = m - n := begin rw [dist.def, sub_eq_zero_of_le h, zero_add] end theorem dist_eq_sub_of_ge {n m : ℕ} (h : n ≥ m) : dist n m = n - m := begin rw [dist_comm], apply dist_eq_sub_of_le h end theorem dist_zero_right (n : ℕ) : dist n 0 = n := eq.trans (dist_eq_sub_of_ge (zero_le n)) (nat.sub_zero n) theorem dist_zero_left (n : ℕ) : dist 0 n = n := eq.trans (dist_eq_sub_of_le (zero_le n)) (nat.sub_zero n) theorem dist_add_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m := calc dist (n + k) (m + k) = ((n + k) - (m + k)) + ((m + k)-(n + k)) : rfl ... = (n - m) + ((m + k) - (n + k)) : by rw nat.add_sub_add_right ... = (n - m) + (m - n) : by rw nat.add_sub_add_right theorem dist_add_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m := begin rw [add_comm k n, add_comm k m], apply dist_add_add_right end theorem dist_eq_intro {n m k l : ℕ} (h : n + m = k + l) : dist n k = dist l m := calc dist n k = dist (n + m) (k + m) : by rw dist_add_add_right ... = dist (k + l) (k + m) : by rw h ... = dist l m : by rw dist_add_add_left protected theorem sub_lt_sub_add_sub (n m k : ℕ) : n - k ≤ (n - m) + (m - k) := or.elim (le_total k m) (assume : k ≤ m, begin rw ←nat.add_sub_assoc this, apply nat.sub_le_sub_right, apply nat.le_sub_add end) (assume : k ≥ m, begin rw [sub_eq_zero_of_le this, add_zero], apply nat.sub_le_sub_left, exact this end) theorem dist.triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k := have dist n m + dist m k = (n - m) + (m - k) + ((k - m) + (m - n)), by simp [dist.def], begin rw [this, dist.def], apply add_le_add, repeat { apply nat.sub_lt_sub_add_sub } end theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k := by rw [dist.def, dist.def, right_distrib, nat.mul_sub_right_distrib, nat.mul_sub_right_distrib] theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m := by rw [mul_comm k n, mul_comm k m, dist_mul_right, mul_comm] -- TODO(Jeremy): do when we have max and minx --lemma dist_eq_max_sub_min {i j : nat} : dist i j = (max i j) - min i j := --sorry /- or.elim (lt_or_ge i j) (assume : i < j, by rw [max_eq_right_of_lt this, min_eq_left_of_lt this, dist_eq_sub_of_lt this]) (assume : i ≥ j, by rw [max_eq_left this , min_eq_right this, dist_eq_sub_of_ge this]) -/ lemma dist_succ_succ {i j : nat} : dist (succ i) (succ j) = dist i j := by simp [dist.def, succ_sub_succ] lemma dist_pos_of_ne {i j : nat} : i ≠ j → dist i j > 0 := assume hne, nat.lt_by_cases (assume : i < j, begin rw [dist_eq_sub_of_le (le_of_lt this)], apply nat.sub_pos_of_lt this end) (assume : i = j, by contradiction) (assume : i > j, begin rw [dist_eq_sub_of_ge (le_of_lt this)], apply nat.sub_pos_of_lt this end) end nat
576308f29dccebd7cd695f62b8e5bf51bc20b83e
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Lean/Syntax.lean
d57f633c22286bda3d353c01f424569fd28e685f
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,096
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Data.Name import Lean.Data.Format namespace Lean def SourceInfo.updateTrailing (trailing : Substring) : SourceInfo → SourceInfo | SourceInfo.original leading pos _ endPos => SourceInfo.original leading pos trailing endPos | info => info /- Syntax AST -/ inductive IsNode : Syntax → Prop where | mk (kind : SyntaxNodeKind) (args : Array Syntax) : IsNode (Syntax.node kind args) def SyntaxNode : Type := {s : Syntax // IsNode s } def unreachIsNodeMissing {β} (h : IsNode Syntax.missing) : β := False.elim (nomatch h) def unreachIsNodeAtom {β} {info val} (h : IsNode (Syntax.atom info val)) : β := False.elim (nomatch h) def unreachIsNodeIdent {β info rawVal val preresolved} (h : IsNode (Syntax.ident info rawVal val preresolved)) : β := False.elim (nomatch h) namespace SyntaxNode @[inline] def getKind (n : SyntaxNode) : SyntaxNodeKind := match n with | ⟨Syntax.node k args, _⟩ => k | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom .., h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident .., h⟩ => unreachIsNodeIdent h @[inline] def withArgs {β} (n : SyntaxNode) (fn : Array Syntax → β) : β := match n with | ⟨Syntax.node _ args, _⟩ => fn args | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h @[inline] def getNumArgs (n : SyntaxNode) : Nat := withArgs n $ fun args => args.size @[inline] def getArg (n : SyntaxNode) (i : Nat) : Syntax := withArgs n $ fun args => args.get! i @[inline] def getArgs (n : SyntaxNode) : Array Syntax := withArgs n $ fun args => args @[inline] def modifyArgs (n : SyntaxNode) (fn : Array Syntax → Array Syntax) : Syntax := match n with | ⟨Syntax.node kind args, _⟩ => Syntax.node kind (fn args) | ⟨Syntax.missing, h⟩ => unreachIsNodeMissing h | ⟨Syntax.atom _ _, h⟩ => unreachIsNodeAtom h | ⟨Syntax.ident _ _ _ _, h⟩ => unreachIsNodeIdent h end SyntaxNode namespace Syntax def getAtomVal! : Syntax → String | atom _ val => val | _ => panic! "getAtomVal!: not an atom" def setAtomVal : Syntax → String → Syntax | atom info _, v => (atom info v) | stx, _ => stx @[inline] def ifNode {β} (stx : Syntax) (hyes : SyntaxNode → β) (hno : Unit → β) : β := match stx with | Syntax.node k args => hyes ⟨Syntax.node k args, IsNode.mk k args⟩ | _ => hno () @[inline] def ifNodeKind {β} (stx : Syntax) (kind : SyntaxNodeKind) (hyes : SyntaxNode → β) (hno : Unit → β) : β := match stx with | Syntax.node k args => if k == kind then hyes ⟨Syntax.node k args, IsNode.mk k args⟩ else hno () | _ => hno () def asNode : Syntax → SyntaxNode | Syntax.node kind args => ⟨Syntax.node kind args, IsNode.mk kind args⟩ | _ => ⟨Syntax.node nullKind #[], IsNode.mk nullKind #[]⟩ def getIdAt (stx : Syntax) (i : Nat) : Name := (stx.getArg i).getId @[inline] def modifyArgs (stx : Syntax) (fn : Array Syntax → Array Syntax) : Syntax := match stx with | node k args => node k (fn args) | stx => stx @[inline] def modifyArg (stx : Syntax) (i : Nat) (fn : Syntax → Syntax) : Syntax := match stx with | node k args => node k (args.modify i fn) | stx => stx @[specialize] partial def replaceM {m : Type → Type} [Monad m] (fn : Syntax → m (Option Syntax)) : Syntax → m (Syntax) | stx@(node kind args) => do match (← fn stx) with | some stx => return stx | none => return node kind (← args.mapM (replaceM fn)) | stx => do let o ← fn stx return o.getD stx @[specialize] partial def rewriteBottomUpM {m : Type → Type} [Monad m] (fn : Syntax → m (Syntax)) : Syntax → m (Syntax) | node kind args => do let args ← args.mapM (rewriteBottomUpM fn) fn (node kind args) | stx => fn stx @[inline] def rewriteBottomUp (fn : Syntax → Syntax) (stx : Syntax) : Syntax := Id.run $ stx.rewriteBottomUpM fn private def updateInfo : SourceInfo → String.Pos → String.Pos → SourceInfo | SourceInfo.original lead pos trail endPos, leadStart, trailStop => SourceInfo.original { lead with startPos := leadStart } pos { trail with stopPos := trailStop } endPos | info, _, _ => info private def chooseNiceTrailStop (trail : Substring) : String.Pos := trail.startPos + trail.posOf '\n' /- Remark: the State `String.Pos` is the `SourceInfo.trailing.stopPos` of the previous token, or the beginning of the String. -/ @[inline] private def updateLeadingAux : Syntax → StateM String.Pos (Option Syntax) | atom info@(SourceInfo.original lead _ trail _) val => do let trailStop := chooseNiceTrailStop trail let newInfo := updateInfo info (← get) trailStop set trailStop pure $ some (atom newInfo val) | ident info@(SourceInfo.original lead _ trail _) rawVal val pre => do let trailStop := chooseNiceTrailStop trail let newInfo := updateInfo info (← get) trailStop set trailStop pure $ some (ident newInfo rawVal val pre) | _ => pure none /-- Set `SourceInfo.leading` according to the trailing stop of the preceding token. The result is a round-tripping syntax tree IF, in the input syntax tree, * all leading stops, atom contents, and trailing starts are correct * trailing stops are between the trailing start and the next leading stop. Remark: after parsing, all `SourceInfo.leading` fields are empty. The `Syntax` argument is the output produced by the parser for `source`. This function "fixes" the `source.leading` field. Additionally, we try to choose "nicer" splits between leading and trailing stops according to some heuristics so that e.g. comments are associated to the (intuitively) correct token. Note that the `SourceInfo.trailing` fields must be correct. The implementation of this Function relies on this property. -/ def updateLeading : Syntax → Syntax := fun stx => (replaceM updateLeadingAux stx).run' 0 partial def updateTrailing (trailing : Substring) : Syntax → Syntax | Syntax.atom info val => Syntax.atom (info.updateTrailing trailing) val | Syntax.ident info rawVal val pre => Syntax.ident (info.updateTrailing trailing) rawVal val pre | n@(Syntax.node k args) => if args.size == 0 then n else let i := args.size - 1 let last := updateTrailing trailing args[i] let args := args.set! i last; Syntax.node k args | s => s partial def getTailWithPos : Syntax → Option Syntax | stx@(atom info _) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node _ args => args.findSomeRev? getTailWithPos | _ => none open SourceInfo in /-- Split an `ident` into its dot-separated components while preserving source info. Macro scopes are first erased. For example, `` `foo.bla.boo._@._hyg.4 `` ↦ `` [`foo, `bla, `boo] ``. If `nFields` is set, we take that many fields from the end and keep the remaining components as one name. For example, `` `foo.bla.boo `` with `(nFields := 1)` ↦ `` [`foo.bla, `boo] ``. -/ def identComponents (stx : Syntax) (nFields? : Option Nat := none) : List Syntax := match stx with | ident (SourceInfo.original lead pos trail _) rawStr val _ => let val := val.eraseMacroScopes -- With original info, we assume that `rawStr` represents `val`. let nameComps := nameComps val nFields? let rawComps := splitNameLit rawStr let rawComps := if let some nFields := nFields? then let nPrefix := rawComps.length - nFields let prefixSz := rawComps.take nPrefix |>.foldl (init := 0) fun acc (ss : Substring) => acc + ss.bsize + 1 let prefixSz := prefixSz - 1 -- The last component has no dot rawStr.extract 0 prefixSz :: rawComps.drop nPrefix else rawComps assert! nameComps.length == rawComps.length nameComps.zip rawComps |>.map fun (id, ss) => let off := ss.startPos - rawStr.startPos let lead := if off == 0 then lead else "".toSubstring let trail := if ss.stopPos == rawStr.stopPos then trail else "".toSubstring let info := original lead (pos + off) trail (pos + off + ss.bsize) ident info ss id [] | ident si _ val _ => let val := val.eraseMacroScopes /- With non-original info: - `rawStr` can take all kinds of forms so we only use `val`. - there is no source extent to offset, so we pass it as-is. -/ nameComps val nFields? |>.map fun n => ident si n.toString.toSubstring n [] | _ => unreachable! where nameComps (n : Name) (nFields? : Option Nat) : List Name := if let some nFields := nFields? then let nameComps := n.components let nPrefix := nameComps.length - nFields let namePrefix := nameComps.take nPrefix |>.foldl (init := Name.anonymous) fun acc n => acc ++ n namePrefix :: nameComps.drop nPrefix else n.components structure TopDown where firstChoiceOnly : Bool stx : Syntax /-- `for _ in stx.topDown` iterates through each node and leaf in `stx` top-down, left-to-right. If `firstChoiceOnly` is `true`, only visit the first argument of each choice node. -/ def topDown (stx : Syntax) (firstChoiceOnly := false) : TopDown := ⟨firstChoiceOnly, stx⟩ partial instance : ForIn m TopDown Syntax where forIn := fun ⟨firstChoiceOnly, stx⟩ init f => do let rec @[specialize] loop stx b [Inhabited (typeOf% b)] := do match (← f stx b) with | ForInStep.yield b' => let mut b := b' if let Syntax.node k args := stx then if firstChoiceOnly && k == choiceKind then return ← loop args[0] b else for arg in args do match (← loop arg b) with | ForInStep.yield b' => b := b' | ForInStep.done b' => return ForInStep.done b' return ForInStep.yield b | ForInStep.done b => return ForInStep.done b match (← @loop stx init ⟨init⟩) with | ForInStep.yield b => return b | ForInStep.done b => return b partial def reprint (stx : Syntax) : Option String := OptionM.run do let mut s := "" for stx in stx.topDown (firstChoiceOnly := true) do match stx with | atom info val => s := s ++ reprintLeaf info val | ident info rawVal _ _ => s := s ++ reprintLeaf info rawVal.toString | node kind args => if kind == choiceKind then -- this visit the first arg twice, but that should hardly be a problem -- given that choice nodes are quite rare and small let s0 ← reprint args[0] for arg in args[1:] do let s' ← reprint arg guard (s0 == s') | _ => pure () return s where reprintLeaf (info : SourceInfo) (val : String) : String := match info with | SourceInfo.original lead _ trail _ => s!"{lead}{val}{trail}" -- no source info => add gracious amounts of whitespace to definitely separate tokens -- Note that the proper pretty printer does not use this function. -- The parser as well always produces source info, so round-tripping is still -- guaranteed. | _ => s!" {val} " def hasMissing (stx : Syntax) : Bool := do for stx in stx.topDown do if stx.isMissing then return true return false /-- Represents a cursor into a syntax tree that can be read, written, and advanced down/up/left/right. Indices are allowed to be out-of-bound, in which case `cur` is `Syntax.missing`. If the `Traverser` is used linearly, updates are linear in the `Syntax` object as well. -/ structure Traverser where cur : Syntax parents : Array Syntax idxs : Array Nat namespace Traverser def fromSyntax (stx : Syntax) : Traverser := ⟨stx, #[], #[]⟩ def setCur (t : Traverser) (stx : Syntax) : Traverser := { t with cur := stx } /-- Advance to the `idx`-th child of the current node. -/ def down (t : Traverser) (idx : Nat) : Traverser := if idx < t.cur.getNumArgs then { cur := t.cur.getArg idx, parents := t.parents.push $ t.cur.setArg idx arbitrary, idxs := t.idxs.push idx } else { cur := Syntax.missing, parents := t.parents.push t.cur, idxs := t.idxs.push idx } /-- Advance to the parent of the current node, if any. -/ def up (t : Traverser) : Traverser := if t.parents.size > 0 then let cur := if t.idxs.back < t.parents.back.getNumArgs then t.parents.back.setArg t.idxs.back t.cur else t.parents.back { cur := cur, parents := t.parents.pop, idxs := t.idxs.pop } else t /-- Advance to the left sibling of the current node, if any. -/ def left (t : Traverser) : Traverser := if t.parents.size > 0 then t.up.down (t.idxs.back - 1) else t /-- Advance to the right sibling of the current node, if any. -/ def right (t : Traverser) : Traverser := if t.parents.size > 0 then t.up.down (t.idxs.back + 1) else t end Traverser /-- Monad class that gives read/write access to a `Traverser`. -/ class MonadTraverser (m : Type → Type) where st : MonadState Traverser m namespace MonadTraverser variable {m : Type → Type} [Monad m] [t : MonadTraverser m] def getCur : m Syntax := Traverser.cur <$> t.st.get def setCur (stx : Syntax) : m Unit := @modify _ _ t.st (fun t => t.setCur stx) def goDown (idx : Nat) : m Unit := @modify _ _ t.st (fun t => t.down idx) def goUp : m Unit := @modify _ _ t.st (fun t => t.up) def goLeft : m Unit := @modify _ _ t.st (fun t => t.left) def goRight : m Unit := @modify _ _ t.st (fun t => t.right) def getIdx : m Nat := do let st ← t.st.get st.idxs.back?.getD 0 end MonadTraverser end Syntax namespace SyntaxNode @[inline] def getIdAt (n : SyntaxNode) (i : Nat) : Name := (n.getArg i).getId end SyntaxNode def mkListNode (args : Array Syntax) : Syntax := Syntax.node nullKind args namespace Syntax -- quotation node kinds are formed from a unique quotation name plus "quot" def isQuot : Syntax → Bool | Syntax.node (Name.str _ "quot" _) _ => true | Syntax.node `Lean.Parser.Term.dynamicQuot _ => true | _ => false def getQuotContent (stx : Syntax) : Syntax := if stx.isOfKind `Lean.Parser.Term.dynamicQuot then stx[3] else stx[1] -- antiquotation node kinds are formed from the original node kind (if any) plus "antiquot" def isAntiquot : Syntax → Bool | Syntax.node (Name.str _ "antiquot" _) _ => true | _ => false def mkAntiquotNode (term : Syntax) (nesting := 0) (name : Option String := none) (kind := Name.anonymous) : Syntax := let nesting := mkNullNode (mkArray nesting (mkAtom "$")) let term := match term.isIdent with | true => term | false => mkNode `antiquotNestedExpr #[mkAtom "(", term, mkAtom ")"] let name := match name with | some name => mkNode `antiquotName #[mkAtom ":", mkAtom name] | none => mkNullNode mkNode (kind ++ `antiquot) #[mkAtom "$", nesting, term, name] -- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. Also works for antiquotation splices. def isEscapedAntiquot (stx : Syntax) : Bool := !stx[1].getArgs.isEmpty -- Also works for antiquotation splices. def unescapeAntiquot (stx : Syntax) : Syntax := if isAntiquot stx then stx.setArg 1 $ mkNullNode stx[1].getArgs.pop else stx -- Also works for token antiquotations. def getAntiquotTerm (stx : Syntax) : Syntax := let e := if stx.isAntiquot then stx[2] else stx[3] if e.isIdent then e else -- `e` is from `"(" >> termParser >> ")"` e[1] def antiquotKind? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot" _) args => if args[3].isOfKind `antiquotName then some k else -- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`) some Name.anonymous | _ => none -- An "antiquotation splice" is something like `$[...]?` or `$[...]*`. def antiquotSpliceKind? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot_scope" _) args => some k | _ => none def isAntiquotSplice (stx : Syntax) : Bool := antiquotSpliceKind? stx |>.isSome def getAntiquotSpliceContents (stx : Syntax) : Array Syntax := stx[3].getArgs -- `$[..],*` or `$x,*` ~> `,*` def getAntiquotSpliceSuffix (stx : Syntax) : Syntax := if stx.isAntiquotSplice then stx[5] else stx[1] def mkAntiquotSpliceNode (kind : SyntaxNodeKind) (contents : Array Syntax) (suffix : String) (nesting := 0) : Syntax := let nesting := mkNullNode (mkArray nesting (mkAtom "$")) mkNode (kind ++ `antiquot_splice) #[mkAtom "$", nesting, mkAtom "[", mkNullNode contents, mkAtom "]", mkAtom suffix] -- `$x,*` etc. def antiquotSuffixSplice? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot_suffix_splice" _) args => some k | _ => none def isAntiquotSuffixSplice (stx : Syntax) : Bool := antiquotSuffixSplice? stx |>.isSome -- `$x` in the example above def getAntiquotSuffixSpliceInner (stx : Syntax) : Syntax := stx[0] def mkAntiquotSuffixSpliceNode (kind : SyntaxNodeKind) (inner : Syntax) (suffix : String) : Syntax := mkNode (kind ++ `antiquot_suffix_splice) #[inner, mkAtom suffix] def isTokenAntiquot (stx : Syntax) : Bool := stx.isOfKind `token_antiquot def isAnyAntiquot (stx : Syntax) : Bool := stx.isAntiquot || stx.isAntiquotSplice || stx.isAntiquotSuffixSplice || stx.isTokenAntiquot end Syntax end Lean
a2c9e2d89f6b2bc9f2b2752ab2e8416667435e50
6c7d3318f9e137ff78c170e5986abe531d316cd1
/inClassNotes/02_polymorphicTypes.lean
0f99e140accd6d05e533a7edc0a0ac11cc4f8699
[]
no_license
sethfertig/complogic-s21
3a2c1d90cbb4a9292a8afbe78f46797193f4293f
efb63424d873def3945a04238327b2551af67500
refs/heads/master
1,677,812,457,719
1,613,059,434,000
1,613,059,434,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,457
lean
namespace hidden /- Inductive, aka algebraic, data types - sum types - product types and case analysis - parametrically polymorphic - sum of product types and destructuring -/ /- SUM TYPES A value of such a type is "one of these OR one of those OR one of something else." SUM means OR in this sense. -/ inductive romanNumeral : Type | I : romanNumeral | II : romanNumeral | III : romanNumeral | IV : romanNumeral | V : romanNumeral -- The empty data type inductive empty : Type -- Look Ma, no terms ("uninhabited") def x : empty := _ def funny : empty → empty | e := e -- The unit data type inductive unit : Type -- A type with one value (void) | star : unit -- The bool data type inductive bool : Type -- Two values | tt : bool | ff -- leave type to be inferred -- An inductive type with seven values inductive day : Type | sun | mon | tue | wed | thu | fri | sat open day /- CASE ANALYSIS We generally define functions that consume values of sum types by case analysis. To know what to return, we need to know what form of value we got as an argument. -/ def next_day : day → day | sun := mon | mon := tue | tue := wed | wed := thu | thu := fri | fri := sat | sat := sun /- The left side of a case is usually called a pattern. Argument values are matched to patterns in the order in which patterns are using a "unification" algorithm (more on that later). Function evaluation finds the first pattern that matches and return the result obtained by evaluating the expression on the right hand side of that pattern-matching rule. -/ #reduce next_day sun #reduce next_day sat /- The _ character can be used to match any value. All functions in Lean must be total. We often use _ to cover all other cases no covered explicitly so far. -/ def isWeekday : day → bool | sat := bool.ff | sun := bool.ff | _ := bool.tt /- PRODUCT TYPES (records, structures) -/ /- A product type has one constructor that takes and bundles up values of zero or more other types into records, or structures. In a value of a product type there a value for the first field of an object AND a value for the secon AND a value for the third, etc. PRODUCT in this sense means AND. -/ /- Note: The empty type can be viewed as also a product type with zero fields. -/ /- We now define a product type with one field. To understand such type definitions you need to understand that a constructor, C, is like a function, with zero or more arguments, the only thing it does is to package up its arguments into a term, (C a₀ ... aₙ). A value of our box type can thus be visualized as a box (term) with a single value, the argument to box.mk, inside. As usual there are several syntactic variants for defining inductive types. -/ inductive box_nat' : Type | mk (val : ℕ) -- : box_nat' inductive box_nat'' : Type | mk : ℕ → box_nat'' structure box_nat''' : Type := mk :: (val : ℕ) structure box_nat := -- readable (val : ℕ) -- Let's create such a value def aBox := box_nat.mk 3 -- What does the resulting term look like? #reduce aBox /- Given a box, we "destructure" it using "pattern matching" to get at the values that were used in its construction: in this case to access the ℕ inside a box. Here we see a more interesting form of unification. The key ideas are (1) the algorithm determines whether a pattern matches, (2) it binds names to parts of the object being matched accordingly. -/ def unbox_nat : box_nat → ℕ -- box_nat.mk 3 -- pattern matching, unification | (box_nat.mk n) := n #eval unbox_nat aBox /- When you use the "structure" syntax, Lean generates a projection (accessor) function for each field automatically. -/ #eval box_nat.val aBox #eval aBox.val -- Preferred notation /- Polymorphic types -/ /- We immediately see the same problem as with functions: the need for a many variants varying only in the type of value "contained in the box". The solution is analogous: make our type polymorphic by having it take a type-valued parameter and by making the value it contains of the type that is the value of that parameter. -/ structure box (α : Type) : Type := (val : α) def nat_box : box nat := box.mk 3 def bool_box : box bool := box.mk bool.tt #check nat_box #check box def str_box : box string:= box.mk "Hello, Lean!" def bool_box' := box.mk bool.tt #eval nat_box.val #eval str_box.val #eval bool_box.val def fun_box : box (nat → nat) := box.mk (nat.succ) #check nat.succ #eval nat.succ 4 /- Polymorphic product types with two fields -- the type of ordered pairs -- and two type parameters accordingly. -/ structure prod (α β : Type) : Type := (fst : α) (snd : β) -- Self-test: What's the type of prod? -- "Introduce" some pairs def pair1 := prod.mk 4 "Hi" #check pair1 #check prod #eval prod.fst pair1 #eval prod.snd pair1 #eval pair1.fst #eval pair1.snd def pair2 := prod.mk "Bye" tt -- "Eliminate" some pairs #eval pair1.fst #eval pair1.snd #eval pair2.fst #eval pair2.snd #check prod structure phythagorean_triple : Type := (a : ℕ) (b : ℕ) (c : ℕ) (cert: a*a + b*b = c*c) def py_tri : phythagorean_triple := phythagorean_triple.mk 3 4 5 rfl #reduce py_tri.cert -- construct proof that 25 = 25 def py_tri_bad : phythagorean_triple := phythagorean_triple.mk 3 4 6 rfl -- can't construct proof that 25 = 36 -- Try that in mere Haskell. No way! end hidden
ff0c6e72209837694e4e16ac541c6033cb462e9f
367134ba5a65885e863bdc4507601606690974c1
/src/order/filter/cofinite.lean
b76cfd963457e51986e9622297c5326c8e25562d
[ "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
3,942
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import order.filter.at_top_bot /-! # The cofinite filter In this file we define `cofinite`: the filter of sets with finite complement and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`. ## TODO Define filters for other cardinalities of the complement. -/ open set open_locale classical variables {α : Type*} namespace filter /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite sᶜ}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite sᶜ) (st: s ⊆ t), hs.subset $ compl_subset_compl.2 st, inter_sets := assume s t (hs : finite sᶜ) (ht : finite (tᶜ)), by simp only [compl_inter, finite.union, ht, hs, mem_set_of_eq] } @[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite sᶜ := iff.rfl @[simp] lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in cofinite, p x) ↔ finite {x | ¬p x} := iff.rfl instance cofinite_ne_bot [infinite α] : ne_bot (@cofinite α) := ⟨mt empty_in_sets_eq_bot.mpr $ by { simp only [mem_cofinite, compl_empty], exact infinite_univ }⟩ lemma frequently_cofinite_iff_infinite {p : α → Prop} : (∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} := by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not, set.infinite] /-- The coproduct of the cofinite filters on two types is the cofinite filter on their product. -/ lemma coprod_cofinite {β : Type*} : (cofinite : filter α).coprod (cofinite : filter β) = cofinite := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap_sets, mem_cofinite], split, { rintro ⟨⟨A, hAf, hAS⟩, B, hBf, hBS⟩, rw [← compl_subset_compl, ← preimage_compl] at hAS hBS, exact (hAf.prod hBf).subset (subset_inter hAS hBS) }, { intro hS, refine ⟨⟨(prod.fst '' Sᶜ)ᶜ, _, _⟩, ⟨(prod.snd '' Sᶜ)ᶜ, _, _⟩⟩, { simpa using hS.image prod.fst }, { simpa [compl_subset_comm] using subset_preimage_image prod.fst Sᶜ }, { simpa using hS.image prod.snd }, { simpa [compl_subset_comm] using subset_preimage_image prod.snd Sᶜ } }, end end filter open filter lemma set.finite.compl_mem_cofinite {s : set α} (hs : s.finite) : sᶜ ∈ (@cofinite α) := mem_cofinite.2 $ (compl_compl s).symm ▸ hs lemma set.finite.eventually_cofinite_nmem {s : set α} (hs : s.finite) : ∀ᶠ x in cofinite, x ∉ s := hs.compl_mem_cofinite lemma finset.eventually_cofinite_nmem (s : finset α) : ∀ᶠ x in cofinite, x ∉ s := s.finite_to_set.eventually_cofinite_nmem lemma set.infinite_iff_frequently_cofinite {s : set α} : set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) := frequently_cofinite_iff_infinite.symm lemma filter.eventually_cofinite_ne (x : α) : ∀ᶠ a in cofinite, a ≠ x := (set.finite_singleton x).eventually_cofinite_nmem /-- For natural numbers the filters `cofinite` and `at_top` coincide. -/ lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top := begin ext s, simp only [mem_cofinite, mem_at_top_sets], split, { assume hs, use (hs.to_finset.sup id) + 1, assume b hb, by_contradiction hbs, have := hs.to_finset.subset_range_sup_succ (hs.mem_to_finset.2 hbs), exact not_lt_of_le hb (finset.mem_range.1 this) }, { rintros ⟨N, hN⟩, apply (finite_lt_nat N).subset, assume n hn, change n < N, exact lt_of_not_ge (λ hn', hn $ hN n hn') } end lemma nat.frequently_at_top_iff_infinite {p : ℕ → Prop} : (∃ᶠ n in at_top, p n) ↔ set.infinite {n | p n} := by simp only [← nat.cofinite_eq_at_top, frequently_cofinite_iff_infinite]
7cf9a306868d33fc79ba37ede4bcc354708e93aa
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Elab/Tactic/Rewrite.lean
8d0c2436ebd07d22329f7755888a77cfb826def4
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,409
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.Tactic.Rewrite import Lean.Meta.Tactic.Replace import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Location namespace Lean.Elab.Tactic open Meta @[builtinMacro Lean.Parser.Tactic.rewriteSeq] def expandRewriteTactic : Macro := fun stx => let seq := stx[1][1].getSepArgs let loc := stx[2] return mkNullNode <| seq.map fun rwRule => Syntax.node ``Parser.Tactic.rewrite #[mkAtomFrom rwRule "rewrite ", rwRule, loc] @[builtinMacro Lean.Parser.Tactic.erewriteSeq] def expandERewriteTactic : Macro := fun stx => let seq := stx[1][1].getSepArgs let loc := stx[2] return mkNullNode <| seq.map fun rwRule => Syntax.node ``Parser.Tactic.erewrite #[mkAtomFrom rwRule "erewrite ", rwRule, loc] def rewriteTarget (stx : Syntax) (symm : Bool) (mode : TransparencyMode) : TacticM Unit := do let (g, gs) ← getMainGoal withMVarContext g do let e ← elabTerm stx none true let target ← instantiateMVars (← getMVarDecl g).type let r ← rewrite g target e symm (mode := mode) let g' ← replaceTargetEq g r.eNew r.eqProof setGoals (g' :: r.mvarIds ++ gs) def rewriteLocalDeclFVarId (stx : Syntax) (symm : Bool) (fvarId : FVarId) (mode : TransparencyMode) : TacticM Unit := do let (g, gs) ← getMainGoal withMVarContext g do let e ← elabTerm stx none true let localDecl ← getLocalDecl fvarId let rwResult ← rewrite g localDecl.type e symm (mode := mode) let replaceResult ← replaceLocalDecl g fvarId rwResult.eNew rwResult.eqProof setGoals (replaceResult.mvarId :: rwResult.mvarIds ++ gs) def rewriteLocalDecl (stx : Syntax) (symm : Bool) (userName : Name) (mode : TransparencyMode) : TacticM Unit := withMainMVarContext do let localDecl ← getLocalDeclFromUserName userName rewriteLocalDeclFVarId stx symm localDecl.fvarId mode def rewriteAll (stx : Syntax) (symm : Bool) (mode : TransparencyMode) : TacticM Unit := do let worked ← «try» $ rewriteTarget stx symm mode withMainMVarContext do let mut worked := worked -- We must traverse backwards because `replaceLocalDecl` uses the revert/intro idiom for fvarId in (← getLCtx).getFVarIds.reverse do worked := worked || (← «try» $ rewriteLocalDeclFVarId stx symm fvarId mode) unless worked do let (mvarId, _) ← getMainGoal throwTacticEx `rewrite mvarId "did not find instance of the pattern in the current goal" def evalRewriteCore (mode : TransparencyMode) : Tactic := fun stx => do let rule := stx[1] let symm := !rule[0].isNone let term := rule[1] let loc := expandOptLocation stx[2] match loc with | Location.target => rewriteTarget term symm mode | Location.localDecls userNames => userNames.forM (rewriteLocalDecl term symm · mode) | Location.wildcard => rewriteAll term symm mode /- ``` def rwRule := parser! optional (unicodeSymbol "←" "<-") >> termParser def «rewrite» := parser! "rewrite" >> rwRule >> optional location ``` -/ @[builtinTactic Lean.Parser.Tactic.rewrite] def evalRewrite : Tactic := evalRewriteCore TransparencyMode.instances @[builtinTactic Lean.Parser.Tactic.erewrite] def evalERewrite : Tactic := evalRewriteCore TransparencyMode.default end Lean.Elab.Tactic
4f6a56bfcbf6dda80a13ff7b5ff5b65963d67e08
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/normed_space/bounded_linear_maps.lean
9a980a1eab7fde345b911869240ccfa3ae49b1ed
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
24,596
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import analysis.normed_space.multilinear import analysis.normed_space.units import analysis.asymptotics.asymptotics /-! # Bounded linear maps This file defines a class stating that a map between normed vector spaces is (bi)linear and continuous. Instead of asking for continuity, the definition takes the equivalent condition (because the space is normed) that `∥f x∥` is bounded by a multiple of `∥x∥`. Hence the "bounded" in the name refers to `∥f x∥/∥x∥` rather than `∥f x∥` itself. ## Main definitions * `is_bounded_linear_map`: Class stating that a map `f : E → F` is linear and has `∥f x∥` bounded by a multiple of `∥x∥`. * `is_bounded_bilinear_map`: Class stating that a map `f : E × F → G` is bilinear and continuous, but through the simpler to provide statement that `∥f (x, y)∥` is bounded by a multiple of `∥x∥ * ∥y∥` * `is_bounded_bilinear_map.linear_deriv`: Derivative of a continuous bilinear map as a linear map. * `is_bounded_bilinear_map.deriv`: Derivative of a continuous bilinear map as a continuous linear map. The proof that it is indeed the derivative is `is_bounded_bilinear_map.has_fderiv_at` in `analysis.calculus.fderiv`. ## Main theorems * `is_bounded_bilinear_map.continuous`: A bounded bilinear map is continuous. * `continuous_linear_equiv.is_open`: The continuous linear equivalences are an open subset of the set of continuous linear maps between a pair of Banach spaces. Placed in this file because its proof uses `is_bounded_bilinear_map.continuous`. ## Notes The main use of this file is `is_bounded_bilinear_map`. The file `analysis.normed_space.multilinear` already expounds the theory of multilinear maps, but the `2`-variables case is sufficiently simpler to currently deserve its own treatment. `is_bounded_linear_map` is effectively an unbundled version of `continuous_linear_map` (defined in `topology.algebra.module.basic`, theory over normed spaces developed in `analysis.normed_space.operator_norm`), albeit the name disparity. A bundled `continuous_linear_map` is to be preferred over a `is_bounded_linear_map` hypothesis. Historical artifact, really. -/ noncomputable theory open_locale classical big_operators topological_space open filter (tendsto) metric variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] /-- A function `f` satisfies `is_bounded_linear_map 𝕜 f` if it is linear and satisfies the inequality `∥f x∥ ≤ M * ∥x∥` for some positive constant `M`. -/ structure is_bounded_linear_map (𝕜 : Type*) [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E → F) extends is_linear_map 𝕜 f : Prop := (bound : ∃ M, 0 < M ∧ ∀ x : E, ∥f x∥ ≤ M * ∥x∥) lemma is_linear_map.with_bound {f : E → F} (hf : is_linear_map 𝕜 f) (M : ℝ) (h : ∀ x : E, ∥f x∥ ≤ M * ∥x∥) : is_bounded_linear_map 𝕜 f := ⟨ hf, classical.by_cases (assume : M ≤ 0, ⟨1, zero_lt_one, λ x, (h x).trans $ mul_le_mul_of_nonneg_right (this.trans zero_le_one) (norm_nonneg x)⟩) (assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩ /-- A continuous linear map satisfies `is_bounded_linear_map` -/ lemma continuous_linear_map.is_bounded_linear_map (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 f := { bound := f.bound, ..f.to_linear_map.is_linear } namespace is_bounded_linear_map /-- Construct a linear map from a function `f` satisfying `is_bounded_linear_map 𝕜 f`. -/ def to_linear_map (f : E → F) (h : is_bounded_linear_map 𝕜 f) : E →ₗ[𝕜] F := (is_linear_map.mk' _ h.to_is_linear_map) /-- Construct a continuous linear map from is_bounded_linear_map -/ def to_continuous_linear_map {f : E → F} (hf : is_bounded_linear_map 𝕜 f) : E →L[𝕜] F := { cont := let ⟨C, Cpos, hC⟩ := hf.bound in (to_linear_map f hf).continuous_of_bound C hC, ..to_linear_map f hf} lemma zero : is_bounded_linear_map 𝕜 (λ (x:E), (0:F)) := (0 : E →ₗ[𝕜] F).is_linear.with_bound 0 $ by simp [le_refl] lemma id : is_bounded_linear_map 𝕜 (λ (x:E), x) := linear_map.id.is_linear.with_bound 1 $ by simp [le_refl] lemma fst : is_bounded_linear_map 𝕜 (λ x : E × F, x.1) := begin refine (linear_map.fst 𝕜 E F).is_linear.with_bound 1 (λ x, _), rw one_mul, exact le_max_left _ _ end lemma snd : is_bounded_linear_map 𝕜 (λ x : E × F, x.2) := begin refine (linear_map.snd 𝕜 E F).is_linear.with_bound 1 (λ x, _), rw one_mul, exact le_max_right _ _ end variables {f g : E → F} lemma smul (c : 𝕜) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (c • f) := let ⟨hlf, M, hMp, hM⟩ := hf in (c • hlf.mk' f).is_linear.with_bound (∥c∥ * M) $ λ x, calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x) ... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (hM _) (norm_nonneg _) ... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm lemma neg (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ e, -f e) := begin rw show (λ e, -f e) = (λ e, (-1 : 𝕜) • f e), { funext, simp }, exact smul (-1) hf end lemma add (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e + g e) := let ⟨hlf, Mf, hMfp, hMf⟩ := hf in let ⟨hlg, Mg, hMgp, hMg⟩ := hg in (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ λ x, calc ∥f x + g x∥ ≤ Mf * ∥x∥ + Mg * ∥x∥ : norm_add_le_of_le (hMf x) (hMg x) ... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul lemma sub (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e - g e) := by simpa [sub_eq_add_neg] using add hf (neg hg) lemma comp {g : F → G} (hg : is_bounded_linear_map 𝕜 g) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (g ∘ f) := (hg.to_continuous_linear_map.comp hf.to_continuous_linear_map).is_bounded_linear_map protected lemma tendsto (x : E) (hf : is_bounded_linear_map 𝕜 f) : tendsto f (𝓝 x) (𝓝 (f x)) := let ⟨hf, M, hMp, hM⟩ := hf in tendsto_iff_norm_tendsto_zero.2 $ squeeze_zero (λ e, norm_nonneg _) (λ e, calc ∥f e - f x∥ = ∥hf.mk' f (e - x)∥ : by rw (hf.mk' _).map_sub e x; refl ... ≤ M * ∥e - x∥ : hM (e - x)) (suffices tendsto (λ (e : E), M * ∥e - x∥) (𝓝 x) (𝓝 (M * 0)), by simpa, tendsto_const_nhds.mul (tendsto_norm_sub_self _)) lemma continuous (hf : is_bounded_linear_map 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λ _, hf.tendsto _ lemma lim_zero_bounded_linear_map (hf : is_bounded_linear_map 𝕜 f) : tendsto f (𝓝 0) (𝓝 0) := (hf.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 hf.continuous 0 section open asymptotics filter theorem is_O_id {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := h.bound in is_O.of_bound _ (mem_of_superset univ_mem (λ x _, hM x)) theorem is_O_comp {E : Type*} {g : F → G} (hg : is_bounded_linear_map 𝕜 g) {f : E → F} (l : filter E) : is_O (λ x', g (f x')) f l := (hg.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := is_O_comp h l end end is_bounded_linear_map section variables {ι : Type*} [decidable_eq ι] [fintype ι] /-- Taking the cartesian product of two continuous multilinear maps is a bounded linear operation. -/ lemma is_bounded_linear_map_prod_multilinear {E : ι → Type*} [∀ i, normed_group (E i)] [∀ i, normed_space 𝕜 (E i)] : is_bounded_linear_map 𝕜 (λ p : (continuous_multilinear_map 𝕜 E F) × (continuous_multilinear_map 𝕜 E G), p.1.prod p.2) := { map_add := λ p₁ p₂, by { ext1 m, refl }, map_smul := λ c p, by { ext1 m, refl }, bound := ⟨1, zero_lt_one, λ p, begin rw one_mul, apply continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λ m, _), rw [continuous_multilinear_map.prod_apply, norm_prod_le_iff], split, { exact (p.1.le_op_norm m).trans (mul_le_mul_of_nonneg_right (norm_fst_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) }, { exact (p.2.le_op_norm m).trans (mul_le_mul_of_nonneg_right (norm_snd_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) }, end⟩ } /-- Given a fixed continuous linear map `g`, associating to a continuous multilinear map `f` the continuous multilinear map `f (g m₁, ..., g mₙ)` is a bounded linear operation. -/ lemma is_bounded_linear_map_continuous_multilinear_map_comp_linear (g : G →L[𝕜] E) : is_bounded_linear_map 𝕜 (λ f : continuous_multilinear_map 𝕜 (λ (i : ι), E) F, f.comp_continuous_linear_map (λ _, g)) := begin refine is_linear_map.with_bound ⟨λ f₁ f₂, by { ext m, refl }, λ c f, by { ext m, refl }⟩ (∥g∥ ^ (fintype.card ι)) (λ f, _), apply continuous_multilinear_map.op_norm_le_bound _ _ (λ m, _), { apply_rules [mul_nonneg, pow_nonneg, norm_nonneg] }, calc ∥f (g ∘ m)∥ ≤ ∥f∥ * ∏ i, ∥g (m i)∥ : f.le_op_norm _ ... ≤ ∥f∥ * ∏ i, (∥g∥ * ∥m i∥) : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), exact finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, g.le_op_norm _) end ... = ∥g∥ ^ fintype.card ι * ∥f∥ * ∏ i, ∥m i∥ : by { simp [finset.prod_mul_distrib, finset.card_univ], ring } end end section bilinear_map variable (𝕜) /-- A map `f : E × F → G` satisfies `is_bounded_bilinear_map 𝕜 f` if it is bilinear and continuous. -/ structure is_bounded_bilinear_map (f : E × F → G) : Prop := (add_left : ∀ (x₁ x₂ : E) (y : F), f (x₁ + x₂, y) = f (x₁, y) + f (x₂, y)) (smul_left : ∀ (c : 𝕜) (x : E) (y : F), f (c • x, y) = c • f (x, y)) (add_right : ∀ (x : E) (y₁ y₂ : F), f (x, y₁ + y₂) = f (x, y₁) + f (x, y₂)) (smul_right : ∀ (c : 𝕜) (x : E) (y : F), f (x, c • y) = c • f (x,y)) (bound : ∃ C > 0, ∀ (x : E) (y : F), ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥) variable {𝕜} variable {f : E × F → G} lemma continuous_linear_map.is_bounded_bilinear_map (f : E →L[𝕜] F →L[𝕜] G) : is_bounded_bilinear_map 𝕜 (λ x : E × F, f x.1 x.2) := { add_left := λ x₁ x₂ y, by rw [f.map_add, continuous_linear_map.add_apply], smul_left := λ c x y, by rw [f.map_smul _, continuous_linear_map.smul_apply], add_right := λ x, (f x).map_add, smul_right := λ c x y, (f x).map_smul c y, bound := ⟨max ∥f∥ 1, zero_lt_one.trans_le (le_max_right _ _), λ x y, (f.le_op_norm₂ x y).trans $ by apply_rules [mul_le_mul_of_nonneg_right, norm_nonneg, le_max_left]⟩ } protected lemma is_bounded_bilinear_map.is_O (h : is_bounded_bilinear_map 𝕜 f) : asymptotics.is_O f (λ p : E × F, ∥p.1∥ * ∥p.2∥) ⊤ := let ⟨C, Cpos, hC⟩ := h.bound in asymptotics.is_O.of_bound _ $ filter.eventually_of_forall $ λ ⟨x, y⟩, by simpa [mul_assoc] using hC x y lemma is_bounded_bilinear_map.is_O_comp {α : Type*} (H : is_bounded_bilinear_map 𝕜 f) {g : α → E} {h : α → F} {l : filter α} : asymptotics.is_O (λ x, f (g x, h x)) (λ x, ∥g x∥ * ∥h x∥) l := H.is_O.comp_tendsto le_top protected lemma is_bounded_bilinear_map.is_O' (h : is_bounded_bilinear_map 𝕜 f) : asymptotics.is_O f (λ p : E × F, ∥p∥ * ∥p∥) ⊤ := h.is_O.trans (asymptotics.is_O_fst_prod'.norm_norm.mul asymptotics.is_O_snd_prod'.norm_norm) lemma is_bounded_bilinear_map.map_sub_left (h : is_bounded_bilinear_map 𝕜 f) {x y : E} {z : F} : f (x - y, z) = f (x, z) - f(y, z) := calc f (x - y, z) = f (x + (-1 : 𝕜) • y, z) : by simp [sub_eq_add_neg] ... = f (x, z) + (-1 : 𝕜) • f (y, z) : by simp only [h.add_left, h.smul_left] ... = f (x, z) - f (y, z) : by simp [sub_eq_add_neg] lemma is_bounded_bilinear_map.map_sub_right (h : is_bounded_bilinear_map 𝕜 f) {x : E} {y z : F} : f (x, y - z) = f (x, y) - f (x, z) := calc f (x, y - z) = f (x, y + (-1 : 𝕜) • z) : by simp [sub_eq_add_neg] ... = f (x, y) + (-1 : 𝕜) • f (x, z) : by simp only [h.add_right, h.smul_right] ... = f (x, y) - f (x, z) : by simp [sub_eq_add_neg] lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 f) : continuous f := begin have one_ne : (1:ℝ) ≠ 0 := by simp, obtain ⟨C, (Cpos : 0 < C), hC⟩ := h.bound, rw continuous_iff_continuous_at, intros x, have H : ∀ (a:E) (b:F), ∥f (a, b)∥ ≤ C * ∥∥a∥ * ∥b∥∥, { intros a b, simpa [mul_assoc] using hC a b }, have h₁ : asymptotics.is_o (λ e : E × F, f (e.1 - x.1, e.2)) (λ e, (1:ℝ)) (𝓝 x), { refine (asymptotics.is_O_of_le' (𝓝 x) (λ e, H (e.1 - x.1) e.2)).trans_is_o _, rw asymptotics.is_o_const_iff one_ne, convert ((continuous_fst.sub continuous_const).norm.mul continuous_snd.norm).continuous_at, { simp }, apply_instance }, have h₂ : asymptotics.is_o (λ e : E × F, f (x.1, e.2 - x.2)) (λ e, (1:ℝ)) (𝓝 x), { refine (asymptotics.is_O_of_le' (𝓝 x) (λ e, H x.1 (e.2 - x.2))).trans_is_o _, rw asymptotics.is_o_const_iff one_ne, convert (continuous_const.mul (continuous_snd.sub continuous_const).norm).continuous_at, { simp }, apply_instance }, have := h₁.add h₂, rw asymptotics.is_o_const_iff one_ne at this, change tendsto _ _ _, convert this.add_const (f x), { ext e, simp [h.map_sub_left, h.map_sub_right], }, { simp } end lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 f) {e₂ : F} : continuous (λe₁, f (e₁, e₂)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 f) {e₁ : E} : continuous (λe₂, f (e₁, e₂)) := h.continuous.comp (continuous_const.prod_mk continuous_id) lemma is_bounded_bilinear_map.is_bounded_linear_map_left (h : is_bounded_bilinear_map 𝕜 f) (y : F) : is_bounded_linear_map 𝕜 (λ x, f (x, y)) := { map_add := λ x x', h.add_left _ _ _, map_smul := λ c x, h.smul_left _ _ _, bound := begin rcases h.bound with ⟨C, C_pos, hC⟩, refine ⟨C * (∥y∥ + 1), mul_pos C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ x, _⟩, have : ∥y∥ ≤ ∥y∥ + 1, by simp [zero_le_one], calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y ... ≤ C * ∥x∥ * (∥y∥ + 1) : by apply_rules [norm_nonneg, mul_le_mul_of_nonneg_left, le_of_lt C_pos, mul_nonneg] ... = C * (∥y∥ + 1) * ∥x∥ : by ring end } lemma is_bounded_bilinear_map.is_bounded_linear_map_right (h : is_bounded_bilinear_map 𝕜 f) (x : E) : is_bounded_linear_map 𝕜 (λ y, f (x, y)) := { map_add := λ y y', h.add_right _ _ _, map_smul := λ c y, h.smul_right _ _ _, bound := begin rcases h.bound with ⟨C, C_pos, hC⟩, refine ⟨C * (∥x∥ + 1), mul_pos C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ y, _⟩, have : ∥x∥ ≤ ∥x∥ + 1, by simp [zero_le_one], calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y ... ≤ C * (∥x∥ + 1) * ∥y∥ : by apply_rules [mul_le_mul_of_nonneg_right, norm_nonneg, mul_le_mul_of_nonneg_left, le_of_lt C_pos] end } lemma is_bounded_bilinear_map_smul {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜' × E), p.1 • p.2) := { add_left := add_smul, smul_left := λ c x y, by simp [smul_assoc], add_right := smul_add, smul_right := λ c x y, by simp [smul_assoc, smul_algebra_smul_comm], bound := ⟨1, zero_lt_one, λ x y, by simp [norm_smul] ⟩ } lemma is_bounded_bilinear_map_mul : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := by simp_rw ← smul_eq_mul; exact is_bounded_bilinear_map_smul lemma is_bounded_bilinear_map_comp : is_bounded_bilinear_map 𝕜 (λ (p : (E →L[𝕜] F) × (F →L[𝕜] G)), p.2.comp p.1) := { add_left := λ x₁ x₂ y, begin ext z, change y (x₁ z + x₂ z) = y (x₁ z) + y (x₂ z), rw y.map_add end, smul_left := λ c x y, begin ext z, change y (c • (x z)) = c • y (x z), rw continuous_linear_map.map_smul end, add_right := λ x y₁ y₂, rfl, smul_right := λ c x y, rfl, bound := ⟨1, zero_lt_one, λ x y, calc ∥continuous_linear_map.comp ((x, y).snd) ((x, y).fst)∥ ≤ ∥y∥ * ∥x∥ : continuous_linear_map.op_norm_comp_le _ _ ... = 1 * ∥x∥ * ∥ y∥ : by ring ⟩ } lemma continuous_linear_map.is_bounded_linear_map_comp_left (g : F →L[𝕜] G) : is_bounded_linear_map 𝕜 (λ (f : E →L[𝕜] F), continuous_linear_map.comp g f) := is_bounded_bilinear_map_comp.is_bounded_linear_map_left _ lemma continuous_linear_map.is_bounded_linear_map_comp_right (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 (λ (g : F →L[𝕜] G), continuous_linear_map.comp g f) := is_bounded_bilinear_map_comp.is_bounded_linear_map_right _ lemma is_bounded_bilinear_map_apply : is_bounded_bilinear_map 𝕜 (λ p : (E →L[𝕜] F) × E, p.1 p.2) := { add_left := by simp, smul_left := by simp, add_right := by simp, smul_right := by simp, bound := ⟨1, zero_lt_one, by simp [continuous_linear_map.le_op_norm]⟩ } /-- The function `continuous_linear_map.smul_right`, associating to a continuous linear map `f : E → 𝕜` and a scalar `c : F` the tensor product `f ⊗ c` as a continuous linear map from `E` to `F`, is a bounded bilinear map. -/ lemma is_bounded_bilinear_map_smul_right : is_bounded_bilinear_map 𝕜 (λ p, (continuous_linear_map.smul_right : (E →L[𝕜] 𝕜) → F → (E →L[𝕜] F)) p.1 p.2) := { add_left := λ m₁ m₂ f, by { ext z, simp [add_smul] }, smul_left := λ c m f, by { ext z, simp [mul_smul] }, add_right := λ m f₁ f₂, by { ext z, simp [smul_add] }, smul_right := λ c m f, by { ext z, simp [smul_smul, mul_comm] }, bound := ⟨1, zero_lt_one, λ m f, by simp⟩ } /-- The composition of a continuous linear map with a continuous multilinear map is a bounded bilinear operation. -/ lemma is_bounded_bilinear_map_comp_multilinear {ι : Type*} {E : ι → Type*} [decidable_eq ι] [fintype ι] [∀ i, normed_group (E i)] [∀ i, normed_space 𝕜 (E i)] : is_bounded_bilinear_map 𝕜 (λ p : (F →L[𝕜] G) × (continuous_multilinear_map 𝕜 E F), p.1.comp_continuous_multilinear_map p.2) := { add_left := λ g₁ g₂ f, by { ext m, refl }, smul_left := λ c g f, by { ext m, refl }, add_right := λ g f₁ f₂, by { ext m, simp }, smul_right := λ c g f, by { ext m, simp }, bound := ⟨1, zero_lt_one, λ g f, begin apply continuous_multilinear_map.op_norm_le_bound _ _ (λ m, _), { apply_rules [mul_nonneg, zero_le_one, norm_nonneg] }, calc ∥g (f m)∥ ≤ ∥g∥ * ∥f m∥ : g.le_op_norm _ ... ≤ ∥g∥ * (∥f∥ * ∏ i, ∥m i∥) : mul_le_mul_of_nonneg_left (f.le_op_norm _) (norm_nonneg _) ... = 1 * ∥g∥ * ∥f∥ * ∏ i, ∥m i∥ : by ring end⟩ } /-- Definition of the derivative of a bilinear map `f`, given at a point `p` by `q ↦ f(p.1, q.2) + f(q.1, p.2)` as in the standard formula for the derivative of a product. We define this function here as a linear map `E × F →ₗ[𝕜] G`, then `is_bounded_bilinear_map.deriv` strengthens it to a continuous linear map `E × F →L[𝕜] G`. ``. -/ def is_bounded_bilinear_map.linear_deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : E × F →ₗ[𝕜] G := { to_fun := λ q, f (p.1, q.2) + f (q.1, p.2), map_add' := λ q₁ q₂, begin change f (p.1, q₁.2 + q₂.2) + f (q₁.1 + q₂.1, p.2) = f (p.1, q₁.2) + f (q₁.1, p.2) + (f (p.1, q₂.2) + f (q₂.1, p.2)), simp [h.add_left, h.add_right], abel end, map_smul' := λ c q, begin change f (p.1, c • q.2) + f (c • q.1, p.2) = c • (f (p.1, q.2) + f (q.1, p.2)), simp [h.smul_left, h.smul_right, smul_add] end } /-- The derivative of a bounded bilinear map at a point `p : E × F`, as a continuous linear map from `E × F` to `G`. The statement that this is indeed the derivative of `f` is `is_bounded_bilinear_map.has_fderiv_at` in `analysis.calculus.fderiv`. -/ def is_bounded_bilinear_map.deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : E × F →L[𝕜] G := (h.linear_deriv p).mk_continuous_of_exists_bound $ begin rcases h.bound with ⟨C, Cpos, hC⟩, refine ⟨C * ∥p.1∥ + C * ∥p.2∥, λ q, _⟩, calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _) ... ≤ C * ∥p.1∥ * ∥q∥ + C * ∥q∥ * ∥p.2∥ : begin apply add_le_add, exact mul_le_mul_of_nonneg_left (le_max_right _ _) (mul_nonneg (le_of_lt Cpos) (norm_nonneg _)), apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), exact mul_le_mul_of_nonneg_left (le_max_left _ _) (le_of_lt Cpos), end ... = (C * ∥p.1∥ + C * ∥p.2∥) * ∥q∥ : by ring end @[simp] lemma is_bounded_bilinear_map_deriv_coe (h : is_bounded_bilinear_map 𝕜 f) (p q : E × F) : h.deriv p q = f (p.1, q.2) + f (q.1, p.2) := rfl variables (𝕜) /-- The function `lmul_left_right : 𝕜' × 𝕜' → (𝕜' →L[𝕜] 𝕜')` is a bounded bilinear map. -/ lemma continuous_linear_map.lmul_left_right_is_bounded_bilinear (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : is_bounded_bilinear_map 𝕜 (λ p : 𝕜' × 𝕜', continuous_linear_map.lmul_left_right 𝕜 𝕜' p.1 p.2) := (continuous_linear_map.lmul_left_right 𝕜 𝕜').is_bounded_bilinear_map variables {𝕜} /-- Given a bounded bilinear map `f`, the map associating to a point `p` the derivative of `f` at `p` is itself a bounded linear map. -/ lemma is_bounded_bilinear_map.is_bounded_linear_map_deriv (h : is_bounded_bilinear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ p : E × F, h.deriv p) := begin rcases h.bound with ⟨C, Cpos : 0 < C, hC⟩, refine is_linear_map.with_bound ⟨λ p₁ p₂, _, λ c p, _⟩ (C + C) (λ p, _), { ext; simp [h.add_left, h.add_right]; abel }, { ext; simp [h.smul_left, h.smul_right, smul_add] }, { refine continuous_linear_map.op_norm_le_bound _ (mul_nonneg (add_nonneg Cpos.le Cpos.le) (norm_nonneg _)) (λ q, _), calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _) ... ≤ C * ∥p∥ * ∥q∥ + C * ∥q∥ * ∥p∥ : by apply_rules [add_le_add, mul_le_mul, norm_nonneg, Cpos.le, le_refl, le_max_left, le_max_right, mul_nonneg] ... = (C + C) * ∥p∥ * ∥q∥ : by ring }, end end bilinear_map namespace continuous_linear_equiv open set /-! ### The set of continuous linear equivalences between two Banach spaces is open In this section we establish that the set of continuous linear equivalences between two Banach spaces is an open subset of the space of linear maps between them. -/ protected lemma is_open [complete_space E] : is_open (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) := begin rw [is_open_iff_mem_nhds, forall_range_iff], refine λ e, is_open.mem_nhds _ (mem_range_self _), let O : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : F →L[𝕜] E).comp f, have h_O : continuous O := is_bounded_bilinear_map_comp.continuous_left, convert units.is_open.preimage h_O using 1, ext f', split, { rintros ⟨e', rfl⟩, exact ⟨(e'.trans e.symm).to_unit, rfl⟩ }, { rintros ⟨w, hw⟩, use (units_equiv 𝕜 E w).trans e, ext x, simp [coe_fn_coe_base' w, hw] } end protected lemma nhds [complete_space E] (e : E ≃L[𝕜] F) : (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) ∈ 𝓝 (e : E →L[𝕜] F) := is_open.mem_nhds continuous_linear_equiv.is_open (by simp) end continuous_linear_equiv
8e3a969b80b1637dbb3938b5bf78025f1db13fe7
03338d7688221ff94beea53202aeb7371a960c3b
/src/action.lean
beb4bd334ade7d31028e6c6ca7b0e3f75146f691
[]
no_license
dwarn/nielsen-schreier-lean
6edd2ae9fdc93e2c6b4dfe35c0fb55e36d6ab5ca
99fb30c0bf321c651edbb7524101604cf0242ea1
refs/heads/master
1,617,993,640,671
1,584,787,300,000
1,584,787,300,000
248,867,596
3
0
null
null
null
null
UTF-8
Lean
false
false
26,885
lean
import group_theory.free_group group_theory.group_action logic.relation noncomputable theory open free_group mul_action classical local attribute [instance] prop_decidable section parameters {α : Type} @[reducible] private def G := free_group α parameters (Q : Type) [mul_action G Q] (r : Q) (trans_act : orbit G r = set.univ) @[simp] lemma nil_is_id : (mk [] : G) = 1 := rfl lemma id_is_id (x : Q) : (mk [] : G) • x = x := by simp lemma invinv (a : α) (b : bool) : mk [(a,b)] * mk [(a,!b)] = 1 := mul_inv_self _ @[simp] lemma inv_is_inv (x : Q) (a : α) (b : bool) : mk [(a,b)] • mk [(a,!b)] • x = x := by {rw [smul_smul, invinv _ _], simp} @[simp] lemma is_inv_inv (x : Q) (a : α) (b : bool) : mk [(a,!b)] • mk [(a,b)] • x = x := begin have h : mk [(a,!b)] • mk [(a,!!b)] • x = x, exact inv_is_inv x a (!b), rwa bnot_bnot at h, end lemma cons_smul (p : α × bool) (l : list (α × bool)) (x : Q) : mk [p] • mk l • x = (mk (p::l):G) • x := by {rwa smul_smul, refl} inductive edge (s : Q) : Q → Type | intro (p : α × bool) : edge (mk [p] • s) variables {s t : Q} @[simp] def proj : Π {s t}, edge s t → α × bool | _ _ ⟨_, p⟩ := p def change_end {s t t'} (h : t = t') : edge s t → edge s t' := λ p, eq.rec p h @[simp] lemma change_proj : Π {s t t'} (h : t = t') (e : edge s t), proj (change_end h e) = proj e | _ _ _ rfl _ := rfl @[reducible] def pbnot {β : Type} : β × bool → β × bool | (a, b) := (a, !b) lemma pbnot_pbnot : ∀ p : α × bool, pbnot (pbnot p) = p | (a, b) := by simp @[reducible] def rev : Π {s t}, edge s t → edge t s | _ _ ⟨s, (a,b)⟩ := change_end (is_inv_inv s a b) ⟨mk [(a,b)] • s, (a,!b)⟩ @[simp] lemma rev_proj : Π {s t} (e : edge s t), proj (rev e) = pbnot (proj e) | _ _ ⟨s, (a,b)⟩ := by {rw change_proj, refl} lemma edge_hext : Π {s t t'} {e : edge s t} {e' : edge s t'} (h : proj e = proj e'), e == e' | _ _ _ ⟨_, _⟩ ⟨_, _⟩ rfl := heq.rfl lemma edge_ext {s t} {e e' : edge s t} (h : proj e = proj e') : e = e' := eq_of_heq $ edge_hext h @[simp] lemma rev_rev : Π {s t} (e : edge s t), rev (rev e) = e | _ _ ⟨s, (a,b)⟩ := by {apply edge_ext, simp} inductive path : Q → Q → Type | nil (s : Q) : path s s | cons {s t t' : Q} (p : path s t) (e : edge t t') : path s t' instance e_to_p {s t : Q} : has_coe (edge s t) (path s t) := ⟨λ e, path.cons (path.nil _) e⟩ def path_length : Π {s t : Q} (p : path s t), ℕ | _ _ (path.nil _) := 0 | _ _ (path.cons p _) := path_length p + 1 @[simp] def pconcat : Π {a b c : Q}, path a b → path b c → path a c | _ _ _ p (path.nil _) := p | _ _ _ p (path.cons q e) := path.cons (pconcat p q) e @[simp] def prev : Π {a b : Q}, path a b → path b a | _ _ (path.nil _) := path.nil _ | _ _ (path.cons q e) := pconcat ↑(rev e) (prev q) @[simp] def pmul : Π {a b : Q}, path a b → G | _ _ (path.nil _) := 1 | _ _ (path.cons q e) := mk [proj e] * pmul q @[simp] lemma pconcat_mul : ∀ {a b c : Q} (p : path a b) (q : path b c), pmul (pconcat p q) = pmul q * pmul p | _ _ _ _ (path.nil _) := by simp | _ _ _ _ (path.cons _ _) := by {simp, rw [pconcat_mul, mul_assoc]} @[simp] lemma pmul_smul : ∀ {a b : Q} (p : path a b), pmul p • a = b | _ _ (path.nil _) := by simp | s _ (path.cons p ⟨t, x⟩) := by {simp, rw [←smul_smul, pmul_smul]} @[simp] def path_from_list (s : Q) : Π (l : list (α × bool)), Σ t, path s t | [] := ⟨s, path.nil s⟩ | (p :: l) := ⟨_, path.cons (path_from_list l).2 ⟨_, p⟩⟩ lemma pfl_cons (s : Q) (l : list (α × bool)) (p : α × bool) : (path_from_list s (p::l)).2 = path.cons (path_from_list s l).2 ⟨_, p⟩ := rfl lemma pfl_cons' (s : Q) (l : list (α × bool)) (p : α × bool) : path_from_list s (p::l) = ⟨_, path.cons (path_from_list s l).2 ⟨_, p⟩⟩ := rfl @[simp] lemma pfl_concat : Π (s : Q) (l : list (α × bool)) (l' : list (α × bool)), path_from_list s (l' ++ l) = ⟨_, pconcat (path_from_list s l).2 (path_from_list _ l').2⟩ | s l [] := sigma.eq rfl rfl | s l (p::l') := begin have hh : (p::l') ++ l = p::(l'++l), from rfl, rw [hh, pfl_cons', pfl_concat, pfl_cons], simp, end lemma pfl_end (s : Q) : Π (l : list (α × bool)), (path_from_list s l).1 = mk l • s | [] := by simp | (p :: l) := by {simp, rw pfl_end, apply cons_smul} @[reducible] def list_from_path : Π {s t : Q} (p : path s t), list (α × bool) | _ _ (path.nil _) := [] | _ _ (path.cons p e) := (proj e) :: list_from_path p lemma lfp_cons {s t t' : Q} {p : path s t} {e : edge t t'} : list_from_path (path.cons p e) = (proj e) :: list_from_path p := rfl lemma path_cons_ext : Π {s t t' : Q} (p : path s t) (e : edge t t'), (⟨mk [proj e] • t, path.cons p ⟨t, proj e⟩⟩ : Σ x, path s x) = ⟨t', path.cons p e⟩ | s _ _ p ⟨t, a⟩ := rfl lemma path_from_path : Π {s t : Q} (p : path s t), path_from_list s (list_from_path p) = ⟨t, p⟩ | _ _ (path.nil _) := by simp | s t' (path.cons p (e:edge t _)) := begin have h : list_from_path (path.cons p e) = (proj e) :: list_from_path p, from rfl, rw [h, pfl_cons', path_from_path], exact path_cons_ext p e, end lemma list_from_list (s : Q) : Π (l : list (α × bool)), list_from_path (path_from_list s l).2 = l | [] := rfl | (x::l) := begin rw pfl_cons, rw lfp_cons, simp, apply list_from_list, end lemma pmul_list : Π {a b : Q} (p : path a b), pmul p = mk (list_from_path p) | _ _ (path.nil _) := by simp | _ _ (path.cons _ _) := by {simp, rw pmul_list, simp} @[simp] lemma path_length_nil {s : Q} : path_length (path.nil s) = 0 := rfl @[simp] lemma path_length_cons {s t t' : Q} (p : path s t) (e : edge t t') : path_length (path.cons p e) = path_length p + 1 := rfl lemma path_length_zero : Π {s t : Q} (p : path s t), path_length p = 0 → t = s | _ _ (path.nil _) _ := rfl | s t (path.cons p e) h := begin exfalso, rw path_length_cons at h, exact (nat.succ_ne_zero _) h end def dist_ub (t : Q) (n : ℕ) : Prop := ∃ p : path r t, path_length p = n lemma dist_ub_from_path {t : Q} (p : path r t) : dist_ub t (path_length p) := ⟨p, rfl⟩ include trans_act lemma connected (x : Q) : nonempty (path r x) := begin have hx : x ∈ orbit G r, rw trans_act, trivial, cases hx with g hg, simp at hg, induction g with l, apply nonempty.intro, rw ←hg, have p : path r (mk l • r), rw ←pfl_end, exact (path_from_list r l).2, exact p, simp, end lemma dist_is_bounded (t : Q) : ∃ n : ℕ, dist_ub t n := begin cases (connected t) with p, use path_length p, exact dist_ub_from_path p end def dist (t : Q) : ℕ := nat.find $ dist_is_bounded t lemma dist_is_attained (t : Q) : ∃ p : path r t, path_length p = dist t := nat.find_spec $ dist_is_bounded t lemma dist_is_dist (t : Q) (p : path r t) : dist t ≤ path_length p := nat.find_min' _ $ dist_ub_from_path p lemma dist_zero_iff {t : Q} : dist t = 0 ↔ t = r := begin split, intro h, cases dist_is_attained t with p hp, rw h at hp, exact path_length_zero p hp, intro h, rw h, rw le_antisymm_iff, split, exact dist_is_dist r (path.nil r), simp, end @[simp] lemma dist_root : dist r = 0 := dist_zero_iff.mpr rfl def inbhd (x : Q) : Type := Σ y : Q, edge y x def onbhd (x : Q) : Type := Σ y : Q, edge x y lemma dist_is_lipschitz (x : Q) (q : onbhd x) : dist q.1 ≤ dist x + 1 := begin cases dist_is_attained x with p hp, rw ←hp, exact dist_is_dist q.1 (path.cons p q.2), end lemma ex_closer_nbr (x : Q) (hx : x ≠ r) : ∃ p : inbhd x, dist x = dist p.1 + 1 := begin cases dist_is_attained x with p hp, cases p with p e, exfalso, apply hx, refl, use p_t, use p_e, rw le_antisymm_iff, split, exact dist_is_lipschitz p_t ⟨x, p_e⟩, rw ←hp, simp, exact dist_is_dist _ _ end def my_closer_nbr (x : Q) (hx : x ≠ r) : {p : inbhd x // dist x = dist p.1 + 1} := subtype_of_exists $ ex_closer_nbr x hx def nb (t : Q) (hn : t ≠ r) : Q := (my_closer_nbr t hn).1.1 def nb_is_nb (t : Q) (hn : t ≠ r) : dist t = dist (nb t hn) + 1 := (my_closer_nbr t hn).2 def nb_edge (t : Q) (hn : t ≠ r) : edge (nb t hn) t := (my_closer_nbr t hn).1.2 section bar universe v @[simp] def rec_aux {P : ℕ → Sort v} (f : Π n, (Π m, n = m+1 → P m) → P n) : Π n, P n | 0 := f 0 (λ m h, false.elim $ nat.succ_ne_zero m h.symm) | (n+1) := f (n+1) (λ m h, eq.rec (rec_aux n) (nat.succ_inj h)) end bar section tree_recursion universe u parameters {pt : Q → Sort u} (ptr : pt r) (pt_succ : Π t (hn : t ≠ r), pt (nb t hn) → pt t) @[simp] def helper (n) (f : Π m : ℕ, n = m+1 → (Π x, dist x = m → pt x)) (t) (h : dist t = n) : pt t := dite (t=r) (λ hr, eq.rec ptr hr.symm) $ λ hnr, pt_succ t hnr (f (dist $ nb t hnr) (eq.rec (nb_is_nb t hnr) h) _ rfl) def tree_recursion (t : Q) : pt t := rec_aux helper (dist t) t rfl lemma my_ext {t : Q} : Π n (h : dist t = n), rec_aux helper n t h = rec_aux helper (dist t) t rfl | _ rfl := rfl lemma recursion_at_root : tree_recursion r = ptr := begin have hh : tree_recursion r = rec_aux helper 0 r dist_root, exact (my_ext 0 dist_root).symm, rw hh, simp, end lemma recursion_away (t : Q) (h : t ≠ r) : tree_recursion t = pt_succ t h (tree_recursion (nb t h)) := begin have hh : tree_recursion t = rec_aux helper (dist (nb t h) + 1) t (nb_is_nb t h), exact (my_ext _ (nb_is_nb t h)).symm, rw hh, simp, apply dif_neg, end end tree_recursion def tree_path : Π t, path r t := tree_recursion (path.nil r) (λ t hn p, path.cons p (nb_edge t hn)) def is_in_dir_tree {s t : Q} (e : edge s t) : Prop := ∃ (hn : t ≠ r), (my_closer_nbr t hn).1 = ⟨s, e⟩ def is_in_tree {s t : Q} (e : edge s t) : Prop := is_in_dir_tree e ∨ is_in_dir_tree (rev e) lemma is_in_tree_unfold {s t : Q} (e : edge s t) : is_in_tree e ↔ is_in_dir_tree e ∨ is_in_dir_tree (rev e) := by refl lemma is_in_tree_rev {s t : Q} {e : edge s t} : is_in_tree (rev e) ↔ is_in_tree e := by {repeat {rw is_in_tree_unfold}, simp, tauto} lemma not_in_tree_rev {s t : Q} {e : edge s t} : ¬is_in_tree (rev e) ↔ ¬is_in_tree e := by {rw is_in_tree_rev} def R : Type := {p : Σ s t, edge s t // ¬is_in_tree p.2.2 ∧ (proj p.2.2).2} def to_s (x : R) : Q := x.1.1 def to_t (x : R) : Q := x.1.2.1 def to_edge (x : R) : edge (to_s x) (to_t x) := x.1.2.2 def rmk (s t : Q) (e : edge s t) (h : ¬ is_in_tree e) (hh : (proj e).2) : R := ⟨⟨s, t, e⟩, h, hh⟩ def rmk_ext : Π {s t : Q} {e e' : edge s t} {h : ¬is_in_tree e} {hh : (proj e).2} {h' : ¬is_in_tree e'} {hh' : (proj e').2} (he : e = e'), rmk s t e h hh = rmk s t e' h' hh' | _ _ _ _ _ _ _ _ rfl := rfl lemma rev_ori : Π {s t} {e : edge s t}, (proj (rev e)).2 ↔ ¬(proj e).2 | _ _ ⟨s, (a,tt)⟩ := by simp | _ _ ⟨s, (a,ff)⟩ := by simp def from_edge {s t : Q} (e : edge s t) (h : ¬is_in_tree e) : R × bool := dite (proj e).2 (λ hh, (rmk s t e h hh, tt)) (λ hh, (rmk t s (rev e) (not_in_tree_rev.mpr h) (rev_ori.mpr hh), ff)) lemma from_edge_unfold {s t : Q} (e : edge s t) (h : ¬is_in_tree e) : from_edge e h = dite (proj e).2 (λ hh, (rmk s t e h hh, tt)) (λ hh, (rmk t s (rev e) (not_in_tree_rev.mpr h) (rev_ori.mpr hh), ff)) := rfl lemma r_from_r : Π x : R, from_edge (to_edge x) x.2.1 = (x, tt) | ⟨⟨s, ⟨t, e⟩⟩, ⟨h, hh⟩⟩ := begin rw [from_edge_unfold, dif_pos], refl, assumption, end lemma from_edge_rev : Π {s t : Q} (e : edge s t) (h : ¬ is_in_tree e) (h' : ¬ is_in_tree (rev e)), from_edge (rev e) h' = pbnot (from_edge e h) | _ _ ⟨s, (a,tt)⟩ h h' := begin repeat {rw from_edge_unfold}, rw [dif_neg, dif_pos, rmk_ext (rev_rev _)], refl, simp, simp, end | _ _ ⟨s, (a,ff)⟩ h h' := by {repeat {rw from_edge_unfold}, rw [dif_pos, dif_neg], refl, simp} def from_edge_maybe {s t} (e : edge s t) : list (R × bool) := dite (is_in_tree e) (λ _, []) (list.ret ∘ from_edge e) lemma fem_unfold {s t} {e : edge s t} : from_edge_maybe e = dite (is_in_tree e) (λ _, []) (λ h, [from_edge e h]) := rfl def to_loop (x : R) : path r r := pconcat (path.cons (tree_path (to_s x)) (to_edge x)) $ prev $ tree_path (to_t x) def F := free_group R @[simp] private def H := stabilizer G r instance H_is_subgroup : is_subgroup H := mul_action.is_subgroup r @[simp] noncomputable def plist : Π {a b : Q}, path a b → list (R × bool) | _ _ (path.nil _) := [] | _ _ (path.cons p e) := from_edge_maybe e ++ plist p lemma plist_wd : Π {s s' : Q} (h : s = s') (l : list (α × bool)), plist (path_from_list s l).snd = plist (path_from_list s' l).snd | _ _ rfl _ := rfl lemma plist_concat : Π {a b c : Q} (p : path a b) (p' : path b c), plist (pconcat p p') = plist p' ++ plist p | a _ _ p (path.nil b) := by simp | a b c' p (path.cons p' e) := by {simp, rw plist_concat} lemma tree_path_root : tree_path r = path.nil r := recursion_at_root _ _ lemma tree_path_away {x : Q} (hn : x ≠ r) : tree_path x = path.cons (tree_path (nb x hn)) (nb_edge x hn) := recursion_away _ _ _ _ @[reducible] def rlist : Q → list (α × bool) → list (R × bool) := λ s l, plist (path_from_list s l).2 @[simp] lemma rlist_concat (s : Q) (l l' : list (α × bool)) : rlist s (l' ++ l) = rlist (mk l • s) l' ++ rlist s l := begin have h : rlist s (l' ++ l) = plist (path_from_list s (l' ++ l)).2, from rfl, rw [h, pfl_concat], simp, rw [plist_concat, plist_wd (pfl_end s l) l'], end @[simp] def rmul : Q → list (α × bool) → F := λ s l, mk (rlist s l) lemma concat_to_mul {l l' : list (R × bool)} : mk (l++l') = mk l * mk l' := rfl lemma rlist_singleton {t : Q} {p : α × bool} : rlist t [p] = plist (path.cons (path.nil t) (edge.intro t p)) := rfl lemma plist_singleton {s t : Q} {e : edge s t} : plist (path.cons (path.nil s) e) = from_edge_maybe e := by simp lemma change_fem : Π {s t t'} {e : edge s t} (h : t = t'), from_edge_maybe e = from_edge_maybe (change_end h e) | _ _ _ _ rfl := rfl lemma plist_tp : Π {x : Q}, plist (tree_path x) = [] := tree_recursion (by {rw tree_path_root, simp}) begin intros x hn h, rw tree_path_away hn, simp, split, rw fem_unfold, rw dif_pos, apply or.inl, use hn, exact sigma.eq rfl rfl, assumption, end lemma plist_rev_tp : Π {x : Q}, plist (prev $ tree_path x) = [] := tree_recursion (by {rw tree_path_root, simp}) begin intros x hn h, rw tree_path_away hn, simp, rw plist_concat, simp, split, assumption, have p : ↑(rev (nb_edge x hn)) = path.cons (path.nil _) (rev (nb_edge x hn)), refl, rw p, rw plist_singleton, rw fem_unfold, rw dif_pos, apply or.inr, rw rev_rev, use hn, exact sigma.eq rfl rfl, end lemma pbnot_inv {β : Type} : Π (p : β × bool), mk [pbnot p] * mk [p] = 1 | (a, b) := inv_mul_self $ mk [(a,b)] lemma inv_pbnot {β : Type} : Π (p : β × bool), mk [p] * mk [pbnot p] = 1 | (a, b) := mul_inv_self $ mk [(a,b)] lemma red_smul : ∀ {s l l'}, red.step l l' → rmul s l = rmul s l' | s _ _ (@red.step.bnot _ L1 L2 a b) := begin simp, have h : (mk ((a,b)::(a,!b)::L2) : G) = mk L2, from quot.sound (@red.step.bnot _ [] L2 a b), rw h, suffices g : mk (rlist s ((a,b)::(a,!b)::L2)) = mk (rlist s L2), by {repeat {rw concat_to_mul}, cc}, have h : (((a,b)::(a,!b)::L2):list(α×bool)) = [(a,b)] ++ [(a,!b)] ++ L2, from rfl, rw h, repeat {rw rlist_concat}, repeat {rw concat_to_mul}, set t := mk L2 • s, suffices g : mk (rlist (mk [(a,!b)] • t) [(a,b)]) * mk (rlist t [(a,!b)]) = 1, by {rw g, simp}, repeat {rw rlist_singleton}, repeat {rw plist_singleton}, set e := edge.intro t (a,!b), have h : from_edge_maybe (edge.intro (mk [(a,!b)] • t) (a,!!b)) = from_edge_maybe (rev e), apply change_fem, rw bnot_bnot at h, rw h, repeat {rw fem_unfold}, cases (em $ is_in_tree e) with pos neg, rw [dif_pos, dif_pos], simp, assumption, rwa is_in_tree_rev, rw [dif_neg, dif_neg, from_edge_rev], apply pbnot_inv, assumption, rwa is_in_tree_rev, end instance f_is_group : group F := free_group.group def f_of_g : G → F := quot.lift (rmul r) (@red_smul r) def f_of_h : H → F := f_of_g ∘ coe def h_of_f : F → H := to_group $ λ a, ⟨pmul (to_loop a), by simp⟩ lemma f_of_g.mk (l : list (α × bool)) : f_of_g (mk l) = rmul r l := rfl lemma f_of_h_mul : ∀ (x : G) (y : H), f_of_g (x*y) = f_of_g x * f_of_g y | x ⟨y, h⟩ := begin induction x with l, induction y with l', simp, simp at h, repeat {rw f_of_g.mk}, simp, rw h, simp, simp, end instance f_of_h.is_hom : is_group_hom f_of_h := {map_mul := λ x y, f_of_h_mul x y} instance h_of_f.is_hom : is_group_hom h_of_f := to_group.is_group_hom lemma coe_mul {a b : H} : ↑(a*b) = (↑a * ↑b:G) := rfl lemma pmul_tp_change : Π {s t : Q} {e : edge s t} (h : is_in_dir_tree e), mk [proj e] * pmul (tree_path s) = pmul (tree_path t) | s t e ⟨hn, he⟩ := begin have p : s = (my_closer_nbr t hn).1.1, rw he, have q : proj e = proj ((my_closer_nbr t hn).1.2), rw he, rw q, rw p, suffices g : mk [proj (nb_edge t hn)] * pmul (tree_path (nb t hn)) = pmul (tree_path t), exact g, rw tree_path_away hn, simp, end lemma pmul_prev : Π {s t} (p : path s t), pmul (prev p) = (pmul p)⁻¹ | _ _ (path.nil s) := by simp | s t' (path.cons p (e:edge t _)) := begin simp, rw pmul_prev, simp, have h : ↑(rev e) = path.cons (path.nil t') (rev e), from rfl, rw h, simp, cases proj e with a b, refl, end lemma h_of_f.from_edge {s t} {e : edge s t} (hn : ¬is_in_tree e) (h : (proj e).2) : ↑(h_of_f (mk [from_edge e hn])) = (pmul (tree_path t))⁻¹ * mk [proj e] * pmul (tree_path s) := begin rw from_edge_unfold, rw dif_pos h, have p : ∀ x, h_of_f x = to_group (λ a, ⟨pmul (to_loop a), by simp⟩) x, intro x, refl, rw p, have q : mk [(rmk s t e hn h, tt)] = of (rmk s t e hn h), from rfl, rw q, rw to_group.of, simp, have p' : to_loop (rmk s t e hn h) = pconcat (path.cons (tree_path s) e) (prev (tree_path t)), refl, rw p', simp, rw mul_assoc, simp, apply pmul_prev, exact r, -- TODO: where does this goal come from??? end lemma pbnot_is_inv {β : Type} : Π (p : β × bool), mk [pbnot p] = (mk [p])⁻¹ | (x, b) := rfl lemma coe_inv {x : H} : (↑x⁻¹ : G) = (↑x)⁻¹ := rfl lemma h_of_f.from_edge' {s t} {e : edge s t} (hn : ¬is_in_tree e) (h : ¬(proj e).2) : ↑(h_of_f (mk [from_edge e hn])) = (pmul (tree_path t))⁻¹ * mk [proj e] * pmul (tree_path s) := begin have p : from_edge e hn = pbnot (from_edge (rev e) (not_in_tree_rev.mpr hn)), rw from_edge_unfold, rw from_edge_unfold, rw [dif_neg, dif_pos], refl, assumption, rw p, rw pbnot_is_inv, rw is_group_hom.map_inv h_of_f, have q : ↥(proj $ rev e).2, rw rev_ori, assumption, rw coe_inv, rw h_of_f.from_edge, repeat {rw mul_inv_rev}, repeat {rw mul_assoc}, rw mul_left_inj, rw inv_inv, rw mul_right_inj, rw rev_proj, rw pbnot_is_inv, simp, assumption, end lemma g_of_p : Π {s t} {p : path s t}, pmul p = pmul (tree_path t) * h_of_f (mk $ plist p) * (pmul (tree_path s))⁻¹ | _ _ (path.nil s) := begin have h : plist (path.nil s) = [], from rfl, rw h, have h' : h_of_f (mk []) = 1, from rfl, rw h', simp, end | s t' (path.cons p (e:edge t _)) := begin simp, rw g_of_p, rw ←mul_assoc, simp, have h : mk (from_edge_maybe e ++ plist p) = mk (from_edge_maybe e) * mk (plist p), from rfl, rw h, rw is_mul_hom.map_mul h_of_f, rw coe_mul, repeat {rw ←mul_assoc}, simp, cases (em $ is_in_tree e) with pos neg, rw [fem_unfold, dif_pos pos], have h' : h_of_f (mk []) = 1, from rfl, rw h', simp, cases pos with a b, exact pmul_tp_change a, rw ←pmul_tp_change b, rw ←mul_assoc, simp, exact inv_pbnot _, rw [fem_unfold, dif_neg neg], cases (em (proj e).2) with x y, rw h_of_f.from_edge neg x, repeat {rw ←mul_assoc}, simp, rw h_of_f.from_edge' neg y, repeat {rw ←mul_assoc}, simp, end instance f_of_f_is_hom : is_group_hom (f_of_h ∘ h_of_f) := is_group_hom.comp _ _ lemma f_of_f (f : F) : f_of_h (h_of_f f) = f := begin suffices g : f_of_h (h_of_f f) = to_group of f, rw g, exact to_group.of_eq _, apply to_group.unique (f_of_h ∘ h_of_f), intro x, simp, have p : h_of_f (of x) = ⟨pmul (to_loop x), by simp⟩, from to_group.of, rw p, have p : f_of_h ⟨pmul (to_loop x), by simp⟩ = f_of_g (pmul (to_loop x)), from rfl, rw [p, pmul_list, f_of_g.mk], have p : rmul r (list_from_path (to_loop x)) = mk (plist (path_from_list r (list_from_path (to_loop x))).2), refl, rw [p, path_from_path], simp, have p : to_loop x = pconcat (path.cons (tree_path (to_s x)) (to_edge x)) (prev $ tree_path (to_t x)), refl, rw [p, plist_concat, plist_rev_tp], simp, rw plist_tp, simp, rw [fem_unfold, dif_neg, r_from_r], refl, exact r, end lemma h_of_h : ∀ h : H, h_of_f (f_of_h h) = h | ⟨x, hh⟩ := begin induction x with l, have p : f_of_h = f_of_g ∘ coe, from rfl, rw p, rw subtype.ext, simp, rw f_of_g.mk, have h : rmul r l = mk (plist (path_from_list r l).2), refl, rw h, have q : mk l = mk (list_from_path (path_from_list r l).2), rw list_from_list r l, rw q, set pp := (path_from_list r l).2 with hpp, rw ←pmul_list, rw g_of_p, have h' : pmul (tree_path (path_from_list r l).1) = pmul (tree_path $ mk l • r), rw pfl_end r l, rw h', have hh' : mk l • r = r, from hh, rw hh', repeat {rw tree_path_root}, simp, refl, exact r, simp, -- TODO: ??? end def isom : stabilizer G r ≃* free_group R := ⟨f_of_h, h_of_f, h_of_h, f_of_f, is_mul_hom.map_mul _⟩ @[simp] def rhs_of_lhs : Q × α ⊕ unit → Q ⊕ R | (sum.inl (s, a)) := dite (is_in_tree ⟨s, (a,tt)⟩) (λ _, sum.inl $ ite (is_in_dir_tree ⟨s, (a,tt)⟩) (of a • s) s) (λ hn, sum.inr $ (from_edge ⟨s, (a,tt)⟩ hn).1) | (sum.inr ()) := sum.inl r @[simp] def lhs_of_rhs : Q ⊕ R → Q × α ⊕ unit | (sum.inl s) := dite (s = r) (λ _, sum.inr ()) (λ hn, sum.inl (ite (proj $ nb_edge s hn).2 (nb s hn) s, (proj $ nb_edge s hn).1)) | (sum.inr ⟨⟨_, _, s, (a,b)⟩, _⟩) := sum.inl (s, a) def lhs_of_lhs : ∀ x, lhs_of_rhs (rhs_of_lhs x) = x | (sum.inl (s,a)) := dite (is_in_tree ⟨s, (a,tt)⟩) begin intro pos, simp, rw dif_pos pos, simp, set e := edge.intro s (a,tt), cases (em $ is_in_dir_tree e) with vr rv, rw if_pos vr, cases vr with hn he, have p : mk [(a,tt)] = of a, from rfl, rw p at hn, rw dif_neg hn, rw sum.inl.inj_iff, set t := (my_closer_nbr (of a • s) hn).val, have hne : nb_edge (of a • s) hn_1 = t.2, from rfl, repeat {rw hne}, have hnb : nb (of a • s) hn_1 = t.1, from rfl, have hv : t = ⟨s, e⟩, from he, have hp : proj t.2 = proj (⟨s, e⟩:inbhd (of a • s)).2, exact congr_arg (λ x : inbhd (of a • s), proj x.2) hv, repeat {rw hp}, simp, rw hnb, rw hv, rw if_neg rv, have h : is_in_dir_tree (rev e), cases pos with le ri, exact false.elim (rv le), assumption, cases h with hn he, rw dif_neg hn, rw sum.inl.inj_iff, set t := (my_closer_nbr s hn).val, have hne : nb_edge s hn = t.2, from rfl, repeat {rw hne}, have hnb : nb s hn = t.1, from rfl, have hv : t = ⟨of a • s, rev e⟩, from he, have hp : proj t.2 = proj (⟨of a • s, rev e⟩ : inbhd s).2, exact congr_arg (λ x : inbhd s, proj x.2) hv, repeat {rw hp}, simp, end begin intro neg, simp, rw dif_neg neg, rw from_edge_unfold, rw dif_pos, swap, simp, simp, have h : rmk s (mk [(a,tt)] • s) ⟨s, (a,tt)⟩ neg (by simp) = ⟨⟨s, of a • s, s, (a,tt)⟩, neg, (by simp)⟩, refl, rw h, refl, end | (sum.inr ()) := by simp def end_is_end : Π {s t} (e : edge s t), mk [proj e] • s = t | _ _ ⟨_, _⟩ := rfl def change_is_in_dir_tree : Π {s t t'} {e : edge s t} (h : t = t'), is_in_dir_tree (change_end h e) ↔ is_in_dir_tree e | _ _ _ _ rfl := by refl def change_is_in_tree : Π {s t t'} {e : edge s t} (h : t = t'), is_in_tree (change_end h e) ↔ is_in_tree e | _ _ _ _ rfl := by refl lemma nb.unique : Π {s s'} {h : s ≠ r} {h' : s' ≠ r} (he : s = s'), nb s h = nb s' h' | _ _ _ _ rfl := rfl def not_in_2_cycle (s) : Prop := ∀ (h : s ≠ r) (h' : nb s h ≠ r), s ≠ nb (nb s h) h' lemma no_2_cycle : ∀ (s) (h : s ≠ r) (h' : nb s h ≠ r), s ≠ nb (nb s h) h' := @tree_recursion not_in_2_cycle (λ h, false.elim (h rfl)) begin intros t hn f hn' h' he, rw he at hn, apply f h' hn, apply nb.unique, cc, end def rhs_of_rhs : ∀ x, rhs_of_lhs (lhs_of_rhs x) = x | (sum.inl s) := dite (s = r) (λ h, eq.rec (by simp) h.symm) begin intro hn, simp, rw dif_neg hn, cases (em $ (proj (nb_edge s hn)).2) with le ri, rw if_pos le, simp, have h : ((proj $ nb_edge s hn).1, tt) = proj (nb_edge s hn), ext, refl, simp, symmetry, assumption, rw h, set t := proj (nb_edge s hn), have p : mk [t] • (nb s hn) = s, exact end_is_end _, have he : edge.intro (nb s hn) t = change_end p.symm (nb_edge s hn), apply edge_ext, simp, have hd : is_in_dir_tree (edge.intro (nb s hn) t), rw he, rw change_is_in_dir_tree, use hn, exact sigma.eq rfl rfl, have ht : is_in_tree (edge.intro (nb s hn) t), exact or.inl hd, rw dif_pos ht, rw sum.inl.inj_iff, rw if_pos hd, rw ←h at p, exact p, rw if_neg ri, simp, have hp : ((proj $ nb_edge s hn).1, tt) = proj (rev $ nb_edge s hn), rw rev_proj, ext, have ha : ∀ x, (pbnot x).1 = x.1, intro x, cases x with a b, refl, rw ha, simp, symmetry, have ha : ∀ x, (pbnot x).2 = !x.2, intro x, cases x with a b, refl, rw ha, simp, exact bool_eq_false ri, have hm : mk [proj $ rev $ nb_edge s hn] • s = nb s hn, exact end_is_end _, rw hp, rw dif_pos, rw sum.inl.inj_iff, rw if_neg, intro h, cases h with hn' hh, have hs : nb (mk [proj $ rev $ nb_edge s hn] • s) hn' = s, exact congr_arg _ hh, rw nb.unique hm at hs, swap, rw ←hm, assumption, apply no_2_cycle s, exact hs.symm, have he : edge.intro s (proj $ rev $ nb_edge s hn) = change_end hm.symm (rev $ nb_edge s hn), apply edge_ext, simp, rw he, rw change_is_in_tree, rw is_in_tree_rev, apply or.inl, use hn, exact sigma.eq rfl rfl, end | (sum.inr ⟨⟨_, _, s, (a, b)⟩, h, hh⟩) := begin simp, have hh' : b = tt, from hh, rw hh' at h, have h' : ¬is_in_tree ⟨s, (a, tt)⟩, from h, rw dif_neg h', rw sum.inr.inj_iff, rw from_edge_unfold, rw dif_pos, swap, simp, rw subtype.ext, simp, rw hh', refl, end def index_equiv : Q × α ⊕ unit ≃ Q ⊕ R := ⟨rhs_of_lhs, lhs_of_rhs, lhs_of_lhs, rhs_of_rhs⟩ end
3ff725d6fb5c5f8bb4088f59b69177dfeeaa58c8
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/print.lean
95d491db708774740615c43c68d05f1b62b1d29e
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
254
lean
import data.num logic data.prod data.nat data.int algebra.category.basic open num prod int nat category print instances inhabited print raw 3+2 print options print coercions Category print "-----------" print coercions print "-----------" print classes
614ee15874217a31c615bb1a404cfce8d9ad3a9b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/convex/integral.lean
cabfade17b69ca3ca7412cadf588f8e522c487d1
[ "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
7,796
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 analysis.convex.function import measure_theory.integral.set_integral /-! # Jensen's inequality for integrals In this file we prove four theorems: * `convex.smul_integral_mem`: if `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`: `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. * `convex.integral_mem`: if `μ` is a probability measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the expected value of `f` belongs to `s`: `∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this lemma. * `convex_on.map_smul_integral_le`: Convex Jensen's inequality: If a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the average value of `f` is less than or equal to the average value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex_on.map_sum_le` for a finite sum version of this lemma. * `convex_on.map_integral_le`: Convex Jensen's inequality: If a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the expected value of `f` is less than or equal to the expected value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex_on.map_sum_le` for a finite sum version of this lemma. ## Tags convex, integral, center mass, Jensen's inequality -/ open measure_theory set filter open_locale topological_space big_operators variables {α E : Type*} [measurable_space α] {μ : measure α} [normed_group E] [normed_space ℝ E] [complete_space E] [topological_space.second_countable_topology E] [measurable_space E] [borel_space E] private lemma convex.smul_integral_mem_of_measurable [is_finite_measure μ] {s : set E} (hs : convex ℝ s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hfm : measurable f) : (μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s := begin unfreezingI { rcases eq_empty_or_nonempty s with rfl|⟨y₀, h₀⟩ }, { refine (hμ _).elim, simpa using hfs }, rw ← hsc.closure_eq at hfs, have hc : integrable (λ _, y₀) μ := integrable_const _, set F : ℕ → simple_func α E := simple_func.approx_on f hfm s y₀ h₀, have : tendsto (λ n, (F n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ), { simp only [simple_func.integral_eq_integral _ (simple_func.integrable_approx_on hfm hfi h₀ hc _)], exact tendsto_integral_of_L1 _ hfi (eventually_of_forall $ simple_func.integrable_approx_on hfm hfi h₀ hc) (simple_func.tendsto_approx_on_L1_nnnorm hfm h₀ hfs (hfi.sub hc).2) }, refine hsc.mem_of_tendsto (tendsto_const_nhds.smul this) (eventually_of_forall $ λ n, _), have : ∑ y in (F n).range, (μ ((F n) ⁻¹' {y})).to_real = (μ univ).to_real, by rw [← (F n).sum_range_measure_preimage_singleton, @ennreal.to_real_sum _ _ (λ y, μ ((F n) ⁻¹' {y})) (λ _ _, (measure_ne_top _ _))], rw [← this, simple_func.integral], refine hs.center_mass_mem (λ _ _, ennreal.to_real_nonneg) _ _, { rw [this, ennreal.to_real_pos_iff, pos_iff_ne_zero, ne.def, measure.measure_univ_eq_zero], exact ⟨hμ, measure_ne_top _ _⟩ }, { simp only [simple_func.mem_range], rintros _ ⟨x, rfl⟩, exact simple_func.approx_on_mem hfm h₀ n x } end /-- If `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`: `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version of this lemma. -/ lemma convex.smul_integral_mem [is_finite_measure μ] {s : set E} (hs : convex ℝ s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : (μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s := begin have : ∀ᵐ (x : α) ∂μ, hfi.ae_measurable.mk f x ∈ s, { filter_upwards [hfs, hfi.ae_measurable.ae_eq_mk], assume a ha h, rwa ← h }, convert convex.smul_integral_mem_of_measurable hs hsc hμ this (hfi.congr hfi.ae_measurable.ae_eq_mk) (hfi.ae_measurable.measurable_mk) using 2, apply integral_congr_ae, exact hfi.ae_measurable.ae_eq_mk end /-- If `μ` is a probability measure on `α`, `s` is a convex closed set in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the expected value of `f` belongs to `s`: `∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this lemma. -/ lemma convex.integral_mem [is_probability_measure μ] {s : set E} (hs : convex ℝ s) (hsc : is_closed s) {f : α → E} (hf : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) : ∫ x, f x ∂μ ∈ s := by simpa [measure_univ] using hs.smul_integral_mem hsc (is_probability_measure.ne_zero μ) hf hfi /-- Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the average value of `f` is less than or equal to the average value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_center_mass_le` for a finite sum version of this lemma. -/ lemma convex_on.map_smul_integral_le [is_finite_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : g ((μ univ).to_real⁻¹ • ∫ x, f x ∂μ) ≤ (μ univ).to_real⁻¹ • ∫ x, g (f x) ∂μ := begin set t := {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2}, have ht_conv : convex ℝ t := hg.convex_epigraph, have ht_closed : is_closed t := (hsc.preimage continuous_fst).is_closed_le (hgc.comp continuous_on_fst (subset.refl _)) continuous_on_snd, have ht_mem : ∀ᵐ x ∂μ, (f x, g (f x)) ∈ t := hfs.mono (λ x hx, ⟨hx, le_rfl⟩), simpa [integral_pair hfi hgi] using (ht_conv.smul_integral_mem ht_closed hμ ht_mem (hfi.prod_mk hgi)).2 end /-- Convex **Jensen's inequality**: if a function `g : E → ℝ` is convex and continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to `s`, then the value of `g` at the expected value of `f` is less than or equal to the expected value of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex_on.map_center_mass_le` for a finite sum version of this lemma. -/ lemma convex_on.map_integral_le [is_probability_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on ℝ s g) (hgc : continuous_on g s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) : g (∫ x, f x ∂μ) ≤ ∫ x, g (f x) ∂μ := by simpa [measure_univ] using hg.map_smul_integral_le hgc hsc (is_probability_measure.ne_zero μ) hfs hfi hgi
19443366a8aad7187dbc6c16fe02488a235453d0
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/list/rotate.lean
deca75582c79c683d7a180e483bf8f9a14232e00
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,591
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.list.basic universes u variables {α : Type u} open nat namespace list 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; simp [rotate] @[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] end list
7c7d4f3fa3961fbd04b08631f8d82e8b1f1c472b
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Scopes.lean
59db0a88c0ca3d6c72afdecd0c27e57ac4351599
[ "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
3,707
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Environment namespace Lean namespace TODELETE /- Scope management TODO: delete after we delete parser implemented in C++. We have decided to store scope information at ElabState -/ structure ScopeManagerState := (allNamespaces : NameSet := {}) /- Stack of namespaces for each each open namespace and section -/ (namespaces : List Name := []) /- Stack of namespace/section headers -/ (headers : List Name := []) (isNamespace : List Bool := []) namespace ScopeManagerState instance : Inhabited ScopeManagerState := ⟨{}⟩ def saveNamespace (s : ScopeManagerState) (n : Name) : ScopeManagerState := { s with allNamespaces := s.allNamespaces.insert n } end ScopeManagerState def regScopeManagerExtension : IO (SimplePersistentEnvExtension Name ScopeManagerState) := registerSimplePersistentEnvExtension { name := `scopes, addImportedFn := fun as => mkStateFromImportedEntries ScopeManagerState.saveNamespace {} as, addEntryFn := fun s n => { s with allNamespaces := s.allNamespaces.insert n }, } @[init regScopeManagerExtension] constant scopeManagerExt : SimplePersistentEnvExtension Name ScopeManagerState := arbitrary _ @[export lean_get_namespaces] def getNamespaces (env : Environment) : List Name := (scopeManagerExt.getState env).namespaces def getNamespaceSet (env : Environment) : NameSet := (scopeManagerExt.getState env).allNamespaces @[export lean_is_namespace] def isNamespace (env : Environment) (n : Name) : Bool := (getNamespaceSet env).contains n @[export lean_in_section] def inSection (env : Environment) : Bool := match (scopeManagerExt.getState env).isNamespace with | (b::_) => !b | _ => false @[export lean_has_open_scopes] def hasOpenScopes (env : Environment) : Bool := !(getNamespaces env).isEmpty @[export lean_get_namespace] def getNamespace (env : Environment) : Name := match getNamespaces env with | (n::_) => n | _ => Name.anonymous @[export lean_get_scope_header] def getScopeHeader (env : Environment) : Name := match (scopeManagerExt.getState env).headers with | (n::_) => n | _ => Name.anonymous @[export lean_to_valid_namespace] def toValidNamespace (env : Environment) (n : Name) : Option Name := let s := scopeManagerExt.getState env; if s.allNamespaces.contains n then some n else s.namespaces.foldl (fun r ns => match r with | some _ => r | none => let c := ns ++ n; if s.allNamespaces.contains c then some c else none) none def registerNamespaceAux (env : Environment) (n : Name) : Environment := if (getNamespaceSet env).contains n then env else scopeManagerExt.addEntry env n @[export lean_register_namespace] def registerNamespace : Environment → Name → Environment | env, n@(Name.str p _ _) => registerNamespace (registerNamespaceAux env n) p | env, _ => env def pushScopeCore (env : Environment) (header : Name) (isNamespace : Bool) : Environment := let ns := getNamespace env; let newNs := if isNamespace then ns ++ header else ns; let env := registerNamespaceAux env newNs; let env := scopeManagerExt.modifyState env $ fun s => { s with headers := header :: s.headers, namespaces := newNs :: s.namespaces, isNamespace := isNamespace :: s.isNamespace }; env def popScopeCore (env : Environment) : Environment := if (getNamespaces env).isEmpty then env else scopeManagerExt.modifyState env $ fun s => { s with headers := s.headers.tail!, namespaces := s.namespaces.tail!, isNamespace := s.isNamespace.tail! } end TODELETE end Lean
5080dc54f7ff37e3787d02dead772b8007e79019
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/meta/simp_tactic.lean
f654fd0f691d1211fc445cf7612cd36f5ce8b190
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,208
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences init.meta.quote open tactic meta constant simp_lemmas : Type meta constant simp_lemmas.mk : simp_lemmas meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas meta constant simp_lemmas.mk_default_core : transparency → tactic simp_lemmas meta constant simp_lemmas.add_core : transparency → simp_lemmas → expr → tactic simp_lemmas meta constant simp_lemmas.add_simp_core : transparency → simp_lemmas → name → tactic simp_lemmas meta constant simp_lemmas.add_congr_core : transparency → simp_lemmas → name → tactic simp_lemmas meta def simp_lemmas.mk_default : tactic simp_lemmas := simp_lemmas.mk_default_core reducible meta def simp_lemmas.add : simp_lemmas → expr → tactic simp_lemmas := simp_lemmas.add_core reducible meta def simp_lemmas.add_simp : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_simp_core reducible meta def simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_congr_core reducible meta def simp_lemmas.append : simp_lemmas → list expr → tactic simp_lemmas | sls [] := return sls | sls (l::ls) := do new_sls ← simp_lemmas.add sls l, simp_lemmas.append new_sls ls /- (simp_lemmas.rewrite_core m s prove R e) apply a simplification lemma from 's' - 'prove' is used to discharge proof obligations. - 'R' is the equivalence relation being used (e.g., 'eq', 'iff') - 'e' is the expression to be "simplified" Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite_core : transparency → simp_lemmas → tactic unit → name → expr → tactic (expr × expr) meta def simp_lemmas.rewrite : simp_lemmas → tactic unit → name → expr → tactic (expr × expr) := simp_lemmas.rewrite_core reducible /- (simp_lemmas.drewrite s e) tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite_core : transparency → simp_lemmas → expr → tactic expr meta def simp_lemmas.drewrite : simp_lemmas → expr → tactic expr := simp_lemmas.drewrite_core reducible /- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. -/ meta constant simp_lemmas.dsimplify_core (max_steps : nat) (visit_instances : bool) : simp_lemmas → expr → tactic expr meta constant is_valid_simp_lemma_cnst : transparency → name → tactic bool meta constant is_valid_simp_lemma : transparency → expr → tactic bool def default_max_steps := 10000000 meta def simp_lemmas.dsimplify : simp_lemmas → expr → tactic expr := simp_lemmas.dsimplify_core default_max_steps ff meta constant simp_lemmas.pp : simp_lemmas → tactic format namespace tactic /- (get_eqn_lemmas_for deps d) returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta constant get_eqn_lemmas_for : bool → name → tactic (list name) meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (max_steps : nat) /- If visit_instances = ff, then instance implicit arguments are not visited, but tactic will canonize them. -/ (visit_instances : bool) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) : expr → tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () default_max_steps ff (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta constant dunfold_expr_core : transparency → expr → tactic expr meta def dunfold_expr : expr → tactic expr := dunfold_expr_core reducible meta constant unfold_projection_core : transparency → expr → tactic expr meta def unfold_projection : expr → tactic expr := unfold_projection_core reducible meta def dunfold_occs_core (m : transparency) (max_steps : nat) (occs : occurrences) (cs : list name) (e : expr) : tactic expr := let unfold (c : nat) (e : expr) : tactic (nat × expr × bool) := do guard (cs^.any e^.is_app_of), new_e ← dunfold_expr_core m e, if occs^.contains c then return (c+1, new_e, tt) else return (c+1, e, tt) in do (c, new_e) ← dsimplify_core 1 max_steps tt unfold (λ c e, failed) e, return new_e meta def dunfold_core (m : transparency) (max_steps : nat) (cs : list name) (e : expr) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (cs^.any e^.is_app_of), new_e ← dunfold_expr_core m e, return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () max_steps tt (λ c e, failed) unfold e, return new_e meta def dunfold : list name → tactic unit := λ cs, target >>= dunfold_core reducible default_max_steps cs >>= change meta def dunfold_occs_of (occs : list nat) (c : name) : tactic unit := target >>= dunfold_occs_core reducible default_max_steps (occurrences.pos occs) [c] >>= change meta def dunfold_core_at (occs : occurrences) (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← dunfold_occs_core reducible default_max_steps occs cs d, change $ expr.pi n bi new_d b, intron num_reverted meta def dunfold_at (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← dunfold_core reducible default_max_steps cs d, change $ expr.pi n bi new_d b, intron num_reverted structure delta_config := (max_steps := default_max_steps) (visit_instances := tt) private meta def is_delta_target (e : expr) (cs : list name) : bool := cs^.any (λ c, if e^.is_app_of c then tt /- Exact match -/ else let f := e^.get_app_fn in /- f is an auxiliary constant generated when compiling c -/ f^.is_constant && f^.const_name^.is_internal && (f^.const_name^.get_prefix = c)) /- Delta reduce the given constant names -/ meta def delta_core (cfg : delta_config) (cs : list name) (e : expr) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (is_delta_target e cs), (expr.const f_name f_lvls) ← return e^.get_app_fn, env ← get_env, decl ← env^.get f_name, new_f ← decl^.instantiate_value_univ_params f_lvls, new_e ← head_beta (expr.mk_app new_f e^.get_app_args), return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () cfg^.max_steps cfg^.visit_instances (λ c e, failed) unfold e, return new_e meta def delta (cs : list name) : tactic unit := target >>= delta_core {} cs >>= change meta def delta_at (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← delta_core {} cs d, change $ expr.pi n bi new_d b, intron num_reverted structure simp_config := (max_steps : nat := default_max_steps) (contextual : bool := ff) (lift_eq : bool := tt) (canonize_instances : bool := tt) (canonize_proofs : bool := ff) (use_axioms : bool := tt) (zeta : bool := tt) meta constant simplify_core (c : simp_config) (s : simp_lemmas) (r : name) : expr → tactic (expr × expr) meta constant ext_simplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (c : simp_config) /- Congruence and simplification lemmas. Remark: the simplification lemmas at not applied automatically like in the simplify_core tactic. the caller must use them at pre/post. -/ (s : simp_lemmas) /- Tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user state. -/ (prove : α → tactic α) /- (pre a S r s p e) is invoked before visiting the children of subterm 'e', 'r' is the simplification relation being used, 's' is the updated set of lemmas if 'contextual' is tt, 'p' is the "parent" expression (if there is one). if it succeeds the result is (new_a, new_e, new_pr, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression s.t. 'e r new_e' - 'new_pr' is a proof for 'e r new_e', If it is none, the proof is assumed to be by reflexivity - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- (post a r s p e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a r s p e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- simplification relation -/ (r : name) : expr → tactic (α × expr × expr) meta def simplify (S : simp_lemmas) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := do e_type ← infer_type e >>= whnf, simplify_core cfg S `eq e meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do assert `htarget new_target, swap, ht ← get_local `htarget, mk_eq_mpr pr ht >>= exact meta def simplify_goal (S : simp_lemmas) (cfg : simp_config := {}) : tactic unit := do t ← target, (new_t, pr) ← simplify S t cfg, replace_target new_t pr meta def simp (cfg : simp_config := {}) : tactic unit := do S ← simp_lemmas.mk_default, simplify_goal S cfg >> try triv >> try (reflexivity reducible) meta def simp_using (hs : list expr) (cfg : simp_config := {}) : tactic unit := do S ← simp_lemmas.mk_default, S ← S^.append hs, simplify_goal S cfg >> try triv meta def dsimp_core (s : simp_lemmas) : tactic unit := target >>= s^.dsimplify >>= change meta def dsimp : tactic unit := simp_lemmas.mk_default >>= dsimp_core meta def dsimp_at_core (s : simp_lemmas) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, h_simp ← s^.dsimplify d, change $ expr.pi n bi h_simp b, intron num_reverted meta def dsimp_at (h : expr) : tactic unit := do s ← simp_lemmas.mk_default, dsimp_at_core s h private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end private meta def collect_simps : list expr → tactic (list expr) | [] := return [] | (h :: hs) := do result ← collect_simps hs, htype ← infer_type h >>= whnf, if is_equation htype then return (h :: result) else do pr ← is_prop htype, return $ if pr then (h :: result) else result meta def collect_ctx_simps : tactic (list expr) := local_context >>= collect_simps /-- Simplify target using all hypotheses in the local context. -/ meta def simp_using_hs (cfg : simp_config := {}) : tactic unit := do es ← collect_ctx_simps, simp_using es cfg meta def simph (cfg : simp_config := {}) := simp_using_hs cfg meta def intro1_aux : bool → list name → tactic expr | ff _ := intro1 | tt (n::ns) := intro n | _ _ := failed meta def simp_intro_aux (cfg : simp_config) (updt : bool) : simp_lemmas → bool → list name → tactic simp_lemmas | S tt [] := try (simplify_goal S cfg) >> return S | S use_ns ns := do t ← target, if t^.is_napp_of `not 1 then intro1_aux use_ns ns >> simp_intro_aux S use_ns ns^.tail else if t^.is_arrow then do { d ← return t^.binding_domain, (new_d, h_d_eq_new_d) ← simplify S d cfg, h_d ← intro1_aux use_ns ns, h_new_d ← mk_eq_mp h_d_eq_new_d h_d, assertv_core h_d^.local_pp_name new_d h_new_d, h_new ← intro1, new_S ← if updt && is_equation new_d then S^.add h_new else return S, clear h_d, simp_intro_aux new_S use_ns ns } <|> -- failed to simplify... we just introduce and continue (intro1_aux use_ns ns >> simp_intro_aux S use_ns ns^.tail) else if t^.is_pi || t^.is_let then intro1_aux use_ns ns >> simp_intro_aux S use_ns ns^.tail else do new_t ← whnf t reducible, if new_t^.is_pi then change new_t >> simp_intro_aux S use_ns ns else try (simplify_goal S cfg) >> mcond (expr.is_pi <$> target) (simp_intro_aux S use_ns ns) (if use_ns ∧ ¬ns^.empty then failed else return S) meta def simp_intros_using (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ simp_intro_aux cfg ff s ff [] meta def simph_intros_using (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ do s ← collect_ctx_simps >>= s^.append, simp_intro_aux cfg tt s ff [] meta def simp_intro_lst_using (ns : list name) (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ simp_intro_aux cfg ff s tt ns meta def simph_intro_lst_using (ns : list name) (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ do s ← collect_ctx_simps >>= s^.append, simp_intro_aux cfg tt s tt ns meta def simp_at (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic unit := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, S ← simp_lemmas.mk_default, S ← S^.append extra_lemmas, (new_htype, heq) ← simplify S htype cfg, assert (expr.local_pp_name h) new_htype, mk_eq_mp heq h >>= exact, try $ clear h meta def simp_at_using_hs (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic unit := do hs ← collect_ctx_simps, simp_at h (list.filter (≠ h) hs ++ extra_lemmas) cfg meta def simph_at (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic unit := simp_at_using_hs h extra_lemmas cfg meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← S^.add_simp n, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) : command := do let t := ```(caching_user_attribute simp_lemmas), v ← to_expr ``({name := %%(quote attr_name), descr := "simplifier attribute", mk_cache := λ ns, do {tactic.to_simp_lemmas simp_lemmas.mk ns}, dependencies := [`reducibility] } : caching_user_attribute simp_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute simp_lemmas) cnst, caching_user_attribute.get_cache attr meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S^.join S') R meta def join_user_simp_lemmas : list name → tactic simp_lemmas | [] := simp_lemmas.mk_default | attr_names := join_user_simp_lemmas_core simp_lemmas.mk attr_names /- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral, and pr is a proof that the input argument is equal to n. -/ meta constant norm_num : expr → tactic (expr × expr) meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) (λ _ _ _ _ _, failed) `eq e meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg, replace_target new_target pr meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) `eq e meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg, replace_target new_target pr end tactic export tactic (mk_simp_attr)
b329d7edd3fc3e46e4fd7642bb87642f0f7ef5ed
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/rat/order.lean
a328433fd2dbf30165e9a4471502e29e88526efe
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
9,515
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 := show rat.nonneg _ ↔ _, by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos' b0 d0, mul_comm] using @sub_nonneg _ _ (b * c) (a * d) 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 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 : lattice.distrib_lattice ℚ := by apply_instance instance : lattice.lattice ℚ := by apply_instance instance : lattice.semilattice_inf ℚ := by apply_instance instance : lattice.semilattice_sup ℚ := by apply_instance instance : lattice.has_inf ℚ := by apply_instance instance : lattice.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, add_lt_add_left := assume a b ab c, lt_of_not_ge $ λ ba, not_le_of_lt ab $ rat.add_le_add_left.1 ba, mul_nonneg := @rat.mul_nonneg, 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.discrete_field, ..rat.decidable_linear_order } /- 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_comm_group ℚ := by apply_instance instance : ordered_comm_group ℚ := by apply_instance instance : ordered_cancel_comm_monoid ℚ := by apply_instance instance : ordered_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 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
7e9b5a31e94d361ede3d5cd260b45e649cbd2656
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/logic/function/basic.lean
d702206c5bcb161ca359df28bca7234b88fca63c
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
21,776
lean
/- Copyright (c) 2016 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 logic.basic import data.option.defs /-! # Miscellaneous function constructions and lemmas -/ universes u v w namespace function section variables {α β γ : Sort*} {f : α → β} /-- Evaluate a function at an argument. Useful if you want to talk about the partially applied `function.eval x : (Π x, β x) → β x`. -/ @[reducible] def eval {β : α → Sort*} (x : α) (f : Π x, β x) : β x := f x @[simp] lemma eval_apply {β : α → Sort*} (x : α) (f : Π x, β x) : eval x f = f x := rfl lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl lemma const_def {y : β} : (λ x : α, y) = const α y := rfl @[simp] lemma const_apply {y : β} {x : α} : const α y x = y := rfl @[simp] lemma const_comp {f : α → β} {c : γ} : const β c ∘ f = const α c := rfl @[simp] lemma comp_const {f : β → γ} {b : β} : f ∘ const α b = const α (f b) := rfl lemma id_def : @id α = λ x, x := rfl lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a} (hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' := begin subst hα, have : ∀a, f a == f' a, { intro a, exact h a a (heq.refl a) }, have : β = β', { funext a, exact type_eq_of_heq (this a) }, subst this, apply heq_of_eq, funext a, exact eq_of_heq (this a) end lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := iff.intro (assume h a, h ▸ rfl) funext @[simp] theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ theorem injective.eq_iff' (I : injective f) {a b : α} {c : β} (h : f b = c) : f a = c ↔ a = b := h ▸ I.eq_iff lemma injective.ne (hf : injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ := mt (assume h, hf h) lemma injective.ne_iff (hf : injective f) {x y : α} : f x ≠ f y ↔ x ≠ y := ⟨mt $ congr_arg f, hf.ne⟩ lemma injective.ne_iff' (hf : injective f) {x y : α} {z : β} (h : f y = z) : f x ≠ z ↔ x ≠ y := h ▸ hf.ne_iff /-- If the co-domain `β` of an injective function `f : α → β` has decidable equality, then the domain `α` also has decidable equality. -/ def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α := λ a b, decidable_of_iff _ I.eq_iff lemma injective.of_comp {g : γ → α} (I : injective (f ∘ g)) : injective g := λ x y h, I $ show f (g x) = f (g y), from congr_arg f h lemma surjective.of_comp {g : γ → α} (S : surjective (f ∘ g)) : surjective f := λ y, let ⟨x, h⟩ := S y in ⟨g x, h⟩ instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*) [Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp) | f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm theorem surjective.forall {f : α → β} (hf : surjective f) {p : β → Prop} : (∀ y, p y) ↔ ∀ x, p (f x) := ⟨λ h x, h (f x), λ h y, let ⟨x, hx⟩ := hf y in hx ▸ h x⟩ theorem surjective.forall₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∀ y₁ y₂, p y₁ y₂) ↔ ∀ x₁ x₂, p (f x₁) (f x₂) := hf.forall.trans $ forall_congr $ λ x, hf.forall theorem surjective.forall₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∀ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∀ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.forall.trans $ forall_congr $ λ x, hf.forall₂ theorem surjective.exists {f : α → β} (hf : surjective f) {p : β → Prop} : (∃ y, p y) ↔ ∃ x, p (f x) := ⟨λ ⟨y, hy⟩, let ⟨x, hx⟩ := hf y in ⟨x, hx.symm ▸ hy⟩, λ ⟨x, hx⟩, ⟨f x, hx⟩⟩ theorem surjective.exists₂ {f : α → β} (hf : surjective f) {p : β → β → Prop} : (∃ y₁ y₂, p y₁ y₂) ↔ ∃ x₁ x₂, p (f x₁) (f x₂) := hf.exists.trans $ exists_congr $ λ x, hf.exists theorem surjective.exists₃ {f : α → β} (hf : surjective f) {p : β → β → β → Prop} : (∃ y₁ y₂ y₃, p y₁ y₂ y₃) ↔ ∃ x₁ x₂ x₃, p (f x₁) (f x₂) (f x₃) := hf.exists.trans $ exists_congr $ λ x, hf.exists₂ /-- Cantor's diagonal argument implies that there are no surjective functions from `α` to `set α`. -/ theorem cantor_surjective {α} (f : α → set α) : ¬ function.surjective f | h := let ⟨D, e⟩ := h (λ a, ¬ f a a) in (iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D) /-- Cantor's diagonal argument implies that there are no injective functions from `set α` to `α`. -/ theorem cantor_injective {α : Type*} (f : (set α) → α) : ¬ function.injective f | i := cantor_surjective (λ a b, ∀ U, a = f U → U b) $ right_inverse.surjective (λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩) /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem left_inverse_iff_comp {f : α → β} {g : β → α} : left_inverse f g ↔ f ∘ g = id := ⟨left_inverse.comp_eq_id, congr_fun⟩ theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem right_inverse_iff_comp {f : α → β} {g : β → α} : right_inverse f g ↔ g ∘ f = id := ⟨right_inverse.comp_eq_id, congr_fun⟩ theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf theorem left_inverse.right_inverse {f : α → β} {g : β → α} (h : left_inverse g f) : right_inverse f g := h theorem right_inverse.left_inverse {f : α → β} {g : β → α} (h : right_inverse g f) : left_inverse f g := h theorem left_inverse.surjective {f : α → β} {g : β → α} (h : left_inverse f g) : surjective f := h.right_inverse.surjective theorem right_inverse.injective {f : α → β} {g : β → α} (h : right_inverse f g) : injective f := h.left_inverse.injective theorem left_inverse.eq_right_inverse {f : α → β} {g₁ g₂ : β → α} (h₁ : left_inverse g₁ f) (h₂ : right_inverse g₂ f) : g₁ = g₂ := calc g₁ = g₁ ∘ f ∘ g₂ : by rw [h₂.comp_eq_id, comp.right_id] ... = g₂ : by rw [← comp.assoc, h₁.comp_eq_id, comp.left_id] local attribute [instance, priority 10] classical.prop_decidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a b := ⟨λ h, if h' : ∃ a, f a = b then begin rw [partial_inv, dif_pos h'] at h, injection h with h, subst h, apply classical.some_spec h' end else by rw [partial_inv, dif_neg h'] at h; contradiction, λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variables {α : Type u} [n : nonempty α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β} include n local attribute [instance, priority 10] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice n theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀ (x ∈ s) (y ∈ s), f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice n := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = classical.choice n := by refine inv_fun_on_neg (mt _ h); exact assume ⟨a, _, ha⟩, ⟨a, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := (left_inverse_inv_fun hf).surjective lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf end inv_fun section inv_fun variables {α : Type u} [i : nonempty α] {β : Sort v} {f : α → β} include i lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, has_left_inverse.injective⟩ end inv_fun section surj_inv variables {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, has_right_inverse.surjective⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩, ⟨gl.injective, gr.surjective⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := (right_inverse_surj_inv h).injective end surj_inv section update variables {α : Sort u} {β : α → Sort v} {α' : Sort w} [decidable_eq α] [decidable_eq α'] /-- Replacing the value of a function at a given point by a given value. -/ def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then eq.rec v h.symm else f a /-- On non-dependent functions, `function.update` can be expressed as an `ite` -/ lemma update_apply {β : Sort*} (f : α → β) (a' : α) (b : β) (a : α) : update f a' b a = if a = a' then b else f a := begin dunfold update, congr, funext, rw eq_rec_constant, end @[simp] lemma update_same (a : α) (v : β a) (f : Πa, β a) : update f a v a = v := dif_pos rfl lemma update_injective (f : Πa, β a) (a' : α) : injective (update f a') := λ v v' h, have _ := congr_fun h a', by rwa [update_same, update_same] at this @[simp] lemma update_noteq {a a' : α} (h : a ≠ a') (v : β a') (f : Πa, β a) : update f a' v a = f a := dif_neg h lemma forall_update_iff (f : Π a, β a) {a : α} {b : β a} (p : Π a, β a → Prop) : (∀ x, p x (update f a b x)) ↔ p a b ∧ ∀ x ≠ a, p x (f x) := calc (∀ x, p x (update f a b x)) ↔ ∀ x, (x = a ∨ x ≠ a) → p x (update f a b x) : by simp only [ne.def, classical.em, forall_prop_of_true] ... ↔ p a b ∧ ∀ x ≠ a, p x (f x) : by simp [or_imp_distrib, forall_and_distrib] { contextual := tt } lemma update_eq_iff {a : α} {b : β a} {f g : Π a, β a} : update f a b = g ↔ b = g a ∧ ∀ x ≠ a, f x = g x := funext_iff.trans $ forall_update_iff _ (λ x y, y = g x) lemma eq_update_iff {a : α} {b : β a} {f g : Π a, β a} : g = update f a b ↔ g a = b ∧ ∀ x ≠ a, g x = f x := funext_iff.trans $ forall_update_iff _ (λ x y, g x = y) @[simp] lemma update_eq_self (a : α) (f : Πa, β a) : update f a (f a) = f := update_eq_iff.2 ⟨rfl, λ _ _, rfl⟩ lemma update_comp {β : Sort v} (f : α → β) {g : α' → α} (hg : injective g) (a : α') (v : β) : (update f (g a) v) ∘ g = update (f ∘ g) a v := eq_update_iff.2 ⟨update_same _ _ _, λ x hx, update_noteq (hg.ne hx) _ _⟩ lemma apply_update {ι : Sort*} [decidable_eq ι] {α β : ι → Sort*} (f : Π i, α i → β i) (g : Π i, α i) (i : ι) (v : α i) (j : ι) : f j (update g i v j) = update (λ k, f k (g k)) i (f i v) j := begin by_cases h : j = i, { subst j, simp }, { simp [h] } end lemma comp_update {α' : Sort*} {β : Sort*} (f : α' → β) (g : α → α') (i : α) (v : α') : f ∘ (update g i v) = update (f ∘ g) i (f v) := funext $ apply_update _ _ _ _ theorem update_comm {α} [decidable_eq α] {β : α → Sort*} {a b : α} (h : a ≠ b) (v : β a) (w : β b) (f : Πa, β a) : update (update f a v) b w = update (update f b w) a v := begin funext c, simp only [update], by_cases h₁ : c = b; by_cases h₂ : c = a; try {simp [h₁, h₂]}, cases h (h₂.symm.trans h₁), end @[simp] theorem update_idem {α} [decidable_eq α] {β : α → Sort*} {a : α} (v w : β a) (f : Πa, β a) : update (update f a v) a w = update f a w := by {funext b, by_cases b = a; simp [update, h]} end update section extend noncomputable theory local attribute [instance, priority 10] classical.prop_decidable variables {α β γ : Type*} {f : α → β} /-- `extend f g e'` extends a function `g : α → γ` along a function `f : α → β` to a function `β → γ`, by using the values of `g` on the range of `f` and the values of an auxiliary function `e' : β → γ` elsewhere. Mostly useful when `f` is injective. -/ def extend (f : α → β) (g : α → γ) (e' : β → γ) : β → γ := λ b, if h : ∃ a, f a = b then g (classical.some h) else e' b lemma extend_def (f : α → β) (g : α → γ) (e' : β → γ) (b : β) : extend f g e' b = if h : ∃ a, f a = b then g (classical.some h) else e' b := rfl @[simp] lemma extend_apply (hf : injective f) (g : α → γ) (e' : β → γ) (a : α) : extend f g e' (f a) = g a := begin simp only [extend_def, dif_pos, exists_apply_eq_apply], exact congr_arg g (hf $ classical.some_spec (exists_apply_eq_apply f a)) end @[simp] lemma extend_comp (hf : injective f) (g : α → γ) (e' : β → γ) : extend f g e' ∘ f = g := funext $ λ a, extend_apply hf g e' a end extend lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) := rfl @[simp] lemma uncurry_apply_pair {α β γ} (f : α → β → γ) (x : α) (y : β) : uncurry f (x, y) = f x y := rfl @[simp] lemma curry_apply {α β γ} (f : α × β → γ) (x : α) (y : β) : curry f x y = f (x, y) := rfl section bicomp variables {α β γ δ ε : Type*} /-- Compose a binary function `f` with a pair of unary functions `g` and `h`. If both arguments of `f` have the same type and `g = h`, then `bicompl f g g = f on g`. -/ def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) := f (g a) (h b) /-- Compose an unary function `f` with a binary function `g`. -/ def bicompr (f : γ → δ) (g : α → β → γ) (a b) := f (g a b) -- Suggested local notation: local notation f `∘₂` g := bicompr f g lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) : uncurry (g ∘₂ f) = (g ∘ uncurry f) := rfl lemma uncurry_bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) : uncurry (bicompl f g h) = (uncurry f) ∘ (prod.map g h) := rfl end bicomp section uncurry variables {α β γ δ : Type*} /-- Records a way to turn an element of `α` into a function from `β` to `γ`. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps. -/ class has_uncurry (α : Type*) (β : out_param Type*) (γ : out_param Type*) := (uncurry : α → (β → γ)) /-- Uncurrying operator. The most generic use is to recursively uncurry. For instance `f : α → β → γ → δ` will be turned into `↿f : α × β × γ → δ`. One can also add instances for bundled maps.-/ add_decl_doc has_uncurry.uncurry notation `↿`:max x:max := has_uncurry.uncurry x instance has_uncurry_base : has_uncurry (α → β) α β := ⟨id⟩ instance has_uncurry_induction [has_uncurry β γ δ] : has_uncurry (α → β) (α × γ) δ := ⟨λ f p, ↿(f p.1) p.2⟩ end uncurry /-- A function is involutive, if `f ∘ f = id`. -/ def involutive {α} (f : α → α) : Prop := ∀ x, f (f x) = x lemma involutive_iff_iter_2_eq_id {α} {f : α → α} : involutive f ↔ (f^[2] = id) := funext_iff.symm namespace involutive variables {α : Sort u} {f : α → α} (h : involutive f) include h @[simp] lemma comp_self : f ∘ f = id := funext h protected lemma left_inverse : left_inverse f f := h protected lemma right_inverse : right_inverse f f := h protected lemma injective : injective f := h.left_inverse.injective protected lemma surjective : surjective f := λ x, ⟨f x, h x⟩ protected lemma bijective : bijective f := ⟨h.injective, h.surjective⟩ /-- Involuting an `ite` of an involuted value `x : α` negates the `Prop` condition in the `ite`. -/ protected lemma ite_not (P : Prop) [decidable P] (x : α) : f (ite P x (f x)) = ite (¬ P) x (f x) := by rw [apply_ite f, h, ite_not] end involutive /-- The property of a binary function `f : α → β → γ` being injective. Mathematically this should be thought of as the corresponding function `α × β → γ` being injective. -/ @[reducible] def injective2 {α β γ} (f : α → β → γ) : Prop := ∀ ⦃a₁ a₂ b₁ b₂⦄, f a₁ b₁ = f a₂ b₂ → a₁ = a₂ ∧ b₁ = b₂ namespace injective2 variables {α β γ : Type*} (f : α → β → γ) protected lemma left (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : a₁ = a₂ := (hf h).1 protected lemma right (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ (h : f a₁ b₁ = f a₂ b₂) : b₁ = b₂ := (hf h).2 lemma eq_iff (hf : injective2 f) ⦃a₁ a₂ b₁ b₂⦄ : f a₁ b₁ = f a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ h, hf h, λ⟨h1, h2⟩, congr_arg2 f h1 h2⟩ end injective2 section sometimes local attribute [instance, priority 10] classical.prop_decidable /-- `sometimes f` evaluates to some value of `f`, if it exists. This function is especially interesting in the case where `α` is a proposition, in which case `f` is necessarily a constant function, so that `sometimes f = f a` for all `a`. -/ noncomputable def sometimes {α β} [nonempty β] (f : α → β) : β := if h : nonempty α then f (classical.choice h) else classical.choice ‹_› theorem sometimes_eq {p : Prop} {α} [nonempty α] (f : p → α) (a : p) : sometimes f = f a := dif_pos ⟨a⟩ theorem sometimes_spec {p : Prop} {α} [nonempty α] (P : α → Prop) (f : p → α) (a : p) (h : P (f a)) : P (sometimes f) := by rwa sometimes_eq end sometimes end function /-- `s.piecewise f g` is the function equal to `f` on the set `s`, and to `g` on its complement. -/ def set.piecewise {α : Type u} {β : α → Sort v} (s : set α) (f g : Πi, β i) [∀j, decidable (j ∈ s)] : Πi, β i := λi, if i ∈ s then f i else g i
631bcc789585b7b2f82e7155c3b060fba0b66194
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/field/basic.lean
814b4696d87dc4ac1ef4c43c671da5a7a22f34c5
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,277
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import algebra.field.defs import algebra.group_with_zero.units.lemmas import algebra.hom.ring import algebra.ring.commute /-! # Lemmas about division (semi)rings and (semi)fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open function order_dual set set_option old_structure_cmd true universe u variables {α β K : Type*} section division_semiring variables [division_semiring α] {a b c d : α} lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := by simp_rw [div_eq_mul_inv, add_mul] @[field_simps] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c := (add_div _ _ _).symm lemma same_add_div (h : b ≠ 0) : (b + a) / b = 1 + a / b := by rw [←div_self h, add_div] lemma div_add_same (h : b ≠ 0) : (a + b) / b = a / b + 1 := by rw [←div_self h, add_div] lemma one_add_div (h : b ≠ 0 ) : 1 + a / b = (b + a) / b := (same_add_div h).symm lemma div_add_one (h : b ≠ 0) : a / b + 1 = (a + b) / b := (div_add_same h).symm lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b := by rw [mul_add, one_div_mul_cancel ha, add_mul, one_mul, mul_assoc, mul_one_div_cancel hb, mul_one, add_comm] lemma add_div_eq_mul_add_div (a b : α) (hc : c ≠ 0) : a + b / c = (a * c + b) / c := (eq_div_iff_mul_eq hc).2 $ by rw [right_distrib, (div_mul_cancel _ hc)] @[field_simps] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by rw [add_div, mul_div_cancel _ hc] @[field_simps] lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] protected lemma commute.div_add_div (hbc : commute b c) (hbd : commute b d) (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := by rw [add_div, mul_div_mul_right _ b hd, hbc.eq, hbd.eq, mul_div_mul_right c d hb] protected lemma commute.one_div_add_one_div (hab : commute a b) (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := by rw [(commute.one_right a).div_add_div hab ha hb, one_mul, mul_one, add_comm] protected lemma commute.inv_add_inv (hab : commute a b) (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, hab.one_div_add_one_div ha hb] end division_semiring section division_monoid variables [division_monoid K] [has_distrib_neg K] {a b : K} lemma one_div_neg_one_eq_neg_one : (1:K) / (-1) = -1 := have (-1) * (-1) = (1:K), by rw [neg_mul_neg, one_mul], eq.symm (eq_one_div_of_mul_eq_one_right this) lemma one_div_neg_eq_neg_one_div (a : K) : 1 / (- a) = - (1 / a) := calc 1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul ... = (1 / a) * (1 / (- 1)) : by rw one_div_mul_one_div_rev ... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one ... = - (1 / a) : by rw [mul_neg, mul_one] lemma div_neg_eq_neg_div (a b : K) : b / (- a) = - (b / a) := calc b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def] ... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div ... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg ... = - (b / a) : by rw mul_one_div lemma neg_div (a b : K) : (-b) / a = - (b / a) := by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul] @[field_simps] lemma neg_div' (a b : K) : - (b / a) = (-b) / a := by simp [neg_div] lemma neg_div_neg_eq (a b : K) : (-a) / (-b) = a / b := by rw [div_neg_eq_neg_div, neg_div, neg_neg] lemma neg_inv : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma div_neg (a : K) : a / -b = -(a / b) := by rw [← div_neg_eq_neg_div] lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rw neg_inv end division_monoid section division_ring variables [division_ring K] {a b c d : K} @[simp] lemma div_neg_self {a : K} (h : a ≠ 0) : a / -a = -1 := by rw [div_neg_eq_neg_div, div_self h] @[simp] lemma neg_div_self {a : K} (h : a ≠ 0) : (-a) / a = -1 := by rw [neg_div, div_self h] lemma div_sub_div_same (a b c : K) : (a / c) - (b / c) = (a - b) / c := by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg] lemma same_sub_div {a b : K} (h : b ≠ 0) : (b - a) / b = 1 - a / b := by simpa only [← @div_self _ _ b h] using (div_sub_div_same b a b).symm lemma one_sub_div {a b : K} (h : b ≠ 0) : 1 - a / b = (b - a) / b := (same_sub_div h).symm lemma div_sub_same {a b : K} (h : b ≠ 0) : (a - b) / b = a / b - 1 := by simpa only [← @div_self _ _ b h] using (div_sub_div_same a b b).symm lemma div_sub_one {a b : K} (h : b ≠ 0) : a / b - 1 = (a - b) / b := (div_sub_same h).symm lemma sub_div (a b c : K) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm /-- See `inv_sub_inv` for the more convenient version when `K` is commutative. -/ lemma inv_sub_inv' {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = a⁻¹ * (b - a) * b⁻¹ := by rw [mul_sub, sub_mul, mul_inv_cancel_right₀ hb, inv_mul_cancel ha, one_mul] lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : (1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b := by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib, one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one] @[priority 100] -- see Note [lower instance priority] instance division_ring.is_domain : is_domain K := no_zero_divisors.to_is_domain _ protected lemma commute.div_sub_div (hbc : commute b c) (hbd : commute b d) (hb : b ≠ 0) (hd : d ≠ 0) : a / b - c / d = (a * d - b * c) / (b * d) := by simpa only [mul_neg, neg_div, ←sub_eq_add_neg] using hbc.neg_right.div_add_div hbd hb hd protected lemma commute.inv_sub_inv (hab : commute a b) (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by simp only [inv_eq_one_div, (commute.one_right a).div_sub_div hab ha hb, one_mul, mul_one] end division_ring section semifield variables [semifield α] {a b c d : α} lemma div_add_div (a : α) (c : α) (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) := (commute.all b _).div_add_div (commute.all _ _) hb hd lemma one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) := (commute.all a _).one_div_add_one_div ha hb lemma inv_add_inv (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := (commute.all a _).inv_add_inv ha hb end semifield section field variable [field K] local attribute [simp] mul_assoc mul_comm mul_left_comm @[field_simps] lemma div_sub_div (a : K) {b : K} (c : K) {d : K} (hb : b ≠ 0) (hd : d ≠ 0) : (a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) := (commute.all b _).div_sub_div (commute.all _ _) hb hd lemma inv_sub_inv {a b : K} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := (commute.all a _).inv_sub_inv ha hb @[field_simps] lemma sub_div' (a b c : K) (hc : c ≠ 0) : b - a / c = (b * c - a) / c := by simpa using div_sub_div b a one_ne_zero hc @[field_simps] lemma div_sub' (a b c : K) (hc : c ≠ 0) : a / c - b = (a - c * b) / c := by simpa using div_sub_div a b hc one_ne_zero @[priority 100] -- see Note [lower instance priority] instance field.is_domain : is_domain K := { ..division_ring.is_domain } end field namespace ring_hom protected lemma injective [division_ring α] [semiring β] [nontrivial β] (f : α →+* β) : injective f := (injective_iff_map_eq_zero f).2 $ λ x, (map_eq_zero f).1 end ring_hom section noncomputable_defs variables {R : Type*} [nontrivial R] /-- Constructs a `division_ring` structure on a `ring` consisting only of units and 0. -/ noncomputable def division_ring_of_is_unit_or_eq_zero [hR : ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : division_ring R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } /-- Constructs a `field` structure on a `comm_ring` consisting only of units and 0. See note [reducible non-instances]. -/ @[reducible] noncomputable def field_of_is_unit_or_eq_zero [hR : comm_ring R] (h : ∀ (a : R), is_unit a ∨ a = 0) : field R := { .. (group_with_zero_of_is_unit_or_eq_zero h), .. hR } end noncomputable_defs /-- Pullback a `division_semiring` along an injective function. -/ @[reducible] -- See note [reducible non-instances] protected def function.injective.division_semiring [division_semiring β] [has_zero α] [has_mul α] [has_add α] [has_one α] [has_inv α] [has_div α] [has_smul ℕ α] [has_pow α ℕ] [has_pow α ℤ] [has_nat_cast α] (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) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : division_semiring α := { .. hf.group_with_zero f zero one mul inv div npow zpow, .. hf.semiring f zero one add mul nsmul npow nat_cast } /-- Pullback a `division_ring` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.division_ring [division_ring K] {K'} [has_zero K'] [has_one K'] [has_add K'] [has_mul K'] [has_neg K'] [has_sub K'] [has_inv K'] [has_div K'] [has_smul ℕ K'] [has_smul ℤ K'] [has_smul ℚ K'] [has_pow K' ℕ] [has_pow K' ℤ] [has_nat_cast K'] [has_int_cast K'] [has_rat_cast K'] (f : K' → K) (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) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (qsmul : ∀ x (n : ℚ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) (rat_cast : ∀ n : ℚ, f n = n) : division_ring K' := { rat_cast := coe, rat_cast_mk := λ a b h1 h2, hf (by erw [rat_cast, mul, inv, int_cast, nat_cast]; exact division_ring.rat_cast_mk a b h1 h2), qsmul := (•), qsmul_eq_mul' := λ a x, hf (by erw [qsmul, mul, rat.smul_def, rat_cast]), .. hf.group_with_zero f zero one mul inv div npow zpow, .. hf.ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast } /-- Pullback a `field` along an injective function. -/ @[reducible] -- See note [reducible non-instances] protected def function.injective.semifield [semifield β] [has_zero α] [has_mul α] [has_add α] [has_one α] [has_inv α] [has_div α] [has_smul ℕ α] [has_pow α ℕ] [has_pow α ℤ] [has_nat_cast α] (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) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) : semifield α := { .. hf.comm_group_with_zero f zero one mul inv div npow zpow, .. hf.comm_semiring f zero one add mul nsmul npow nat_cast } /-- Pullback a `field` along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.field [field K] {K'} [has_zero K'] [has_mul K'] [has_add K'] [has_neg K'] [has_sub K'] [has_one K'] [has_inv K'] [has_div K'] [has_smul ℕ K'] [has_smul ℤ K'] [has_smul ℚ K'] [has_pow K' ℕ] [has_pow K' ℤ] [has_nat_cast K'] [has_int_cast K'] [has_rat_cast K'] (f : K' → K) (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) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (qsmul : ∀ x (n : ℚ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) (rat_cast : ∀ n : ℚ, f n = n) : field K' := { rat_cast := coe, rat_cast_mk := λ a b h1 h2, hf (by erw [rat_cast, mul, inv, int_cast, nat_cast]; exact division_ring.rat_cast_mk a b h1 h2), qsmul := (•), qsmul_eq_mul' := λ a x, hf (by erw [qsmul, mul, rat.smul_def, rat_cast]), .. hf.comm_group_with_zero f zero one mul inv div npow zpow, .. hf.comm_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast } /-! ### Order dual -/ instance [h : has_rat_cast α] : has_rat_cast αᵒᵈ := h instance [h : division_semiring α] : division_semiring αᵒᵈ := h instance [h : division_ring α] : division_ring αᵒᵈ := h instance [h : semifield α] : semifield αᵒᵈ := h instance [h : field α] : field αᵒᵈ := h @[simp] lemma to_dual_rat_cast [has_rat_cast α] (n : ℚ) : to_dual (n : α) = n := rfl @[simp] lemma of_dual_rat_cast [has_rat_cast α] (n : ℚ) : (of_dual n : α) = n := rfl /-! ### Lexicographic order -/ instance [h : has_rat_cast α] : has_rat_cast (lex α) := h instance [h : division_semiring α] : division_semiring (lex α) := h instance [h : division_ring α] : division_ring (lex α) := h instance [h : semifield α] : semifield (lex α) := h instance [h : field α] : field (lex α) := h @[simp] lemma to_lex_rat_cast [has_rat_cast α] (n : ℚ) : to_lex (n : α) = n := rfl @[simp] lemma of_lex_rat_cast [has_rat_cast α] (n : ℚ) : (of_lex n : α) = n := rfl
25a30cd0e4f5105f9d6bd277a28b220a0871dad7
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/set/basic.lean
08af3259a3f2e0249e16bdcd031d7145f5ec7bf0
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
77,623
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 -/ import order.symm_diff import logic.function.iterate /-! # Basic properties of sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements have type `X` are thus defined as `set X := X → Prop`. Note that this function need not be decidable. The definition is in the core library. This file provides some basic definitions related to sets and functions not present in the core library, as well as extra lemmas for functions in the core library (empty set, univ, union, intersection, insert, singleton, set-theoretic difference, complement, and powerset). Note that a set is a term, not a type. There is a coercion from `set α` to `Type*` sending `s` to the corresponding subtype `↥s`. See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean. ## Main definitions Notation used here: - `f : α → β` is a function, - `s : set α` and `s₁ s₂ : set α` are subsets of `α` - `t : set β` is a subset of `β`. Definitions in the file: * `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the fact that `s` has an element (see the Implementation Notes). * `subsingleton s : Prop` : the predicate saying that `s` has at most one element. * `nontrivial s : Prop` : the predicate saying that `s` has at least two distinct elements. * `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`. ## Notation * `sᶜ` for the complement of `s` ## Implementation notes * `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that the `s.nonempty` dot notation can be used. * For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`. ## Tags set, sets, subset, subsets, union, intersection, insert, singleton, complement, powerset -/ /-! ### Set coercion to a type -/ open function universes u v w x namespace set variables {α : Type*} {s t : set α} instance : has_le (set α) := ⟨λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t⟩ instance : has_subset (set α) := ⟨(≤)⟩ instance {α : Type*} : boolean_algebra (set α) := { sup := λ s t, {x | x ∈ s ∨ x ∈ t}, le := (≤), lt := λ s t, s ⊆ t ∧ ¬t ⊆ s, inf := λ s t, {x | x ∈ s ∧ x ∈ t}, bot := ∅, compl := λ s, {x | x ∉ s}, top := univ, sdiff := λ s t, {x | x ∈ s ∧ x ∉ t}, .. (infer_instance : boolean_algebra (α → Prop)) } instance : has_ssubset (set α) := ⟨(<)⟩ instance : has_union (set α) := ⟨(⊔)⟩ instance : has_inter (set α) := ⟨(⊓)⟩ @[simp] lemma top_eq_univ : (⊤ : set α) = univ := rfl @[simp] lemma bot_eq_empty : (⊥ : set α) = ∅ := rfl @[simp] lemma sup_eq_union : ((⊔) : set α → set α → set α) = (∪) := rfl @[simp] lemma inf_eq_inter : ((⊓) : set α → set α → set α) = (∩) := rfl @[simp] lemma le_eq_subset : ((≤) : set α → set α → Prop) = (⊆) := rfl @[simp] lemma lt_eq_ssubset : ((<) : set α → set α → Prop) = (⊂) := rfl lemma le_iff_subset : s ≤ t ↔ s ⊆ t := iff.rfl lemma lt_iff_ssubset : s < t ↔ s ⊂ t := iff.rfl alias le_iff_subset ↔ _root_.has_le.le.subset _root_.has_subset.subset.le alias lt_iff_ssubset ↔ _root_.has_lt.lt.ssubset _root_.has_ssubset.ssubset.lt /-- Coercion from a set to the corresponding subtype. -/ instance {α : Type u} : has_coe_to_sort (set α) (Type u) := ⟨λ s, {x // x ∈ s}⟩ instance pi_set_coe.can_lift (ι : Type u) (α : Π i : ι, Type v) [ne : Π i, nonempty (α i)] (s : set ι) : can_lift (Π i : s, α i) (Π i, α i) (λ f i, f i) (λ _, true) := pi_subtype.can_lift ι α s instance pi_set_coe.can_lift' (ι : Type u) (α : Type v) [ne : nonempty α] (s : set ι) : can_lift (s → α) (ι → α) (λ f i, f i) (λ _, true) := pi_set_coe.can_lift ι (λ _, α) s end set section set_coe variables {α : Type u} theorem set.coe_eq_subtype (s : set α) : ↥s = {x // x ∈ s} := rfl @[simp] theorem set.coe_set_of (p : α → Prop) : ↥{x | p x} = {x // p x} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} : (∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x x.2) := (@set_coe.exists _ _ $ λ x, p x.1 x.2).symm theorem set_coe.forall' {s : set α} {p : Π x, x ∈ s → Prop} : (∀ x (h : x ∈ s), p x h) ↔ (∀ x : s, p x x.2) := (@set_coe.forall _ _ $ λ x, p x.1 x.2).symm @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : ↥s = ↥t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe /-- See also `subtype.prop` -/ lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop /-- Duplicate of `eq.subset'`, which currently has elaboration problems. -/ lemma eq.subset {α} {s t : set α} : s = t → s ⊆ t := eq.subset' namespace set variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a b : α} {s s₁ s₂ t t₁ t₂ u : set α} instance : inhabited (set α) := ⟨∅⟩ @[ext] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx lemma forall_in_swap {p : α → β → Prop} : (∀ (a ∈ s) b, p a b) ↔ ∀ b (a ∈ s), p a b := by tauto /-! ### Lemmas about `mem` and `set_of` -/ lemma mem_set_of {a : α} {p : α → Prop} : a ∈ {x | p x} ↔ p a := iff.rfl /-- If `h : a ∈ {x | p x}` then `h.out : p x`. These are definitionally equal, but this can nevertheless be useful for various reasons, e.g. to apply further projection notation or in an argument to `simp`. -/ lemma _root_.has_mem.mem.out {p : α → Prop} {a : α} (h : a ∈ {x | p x}) : p a := h theorem nmem_set_of_iff {a : α} {p : α → Prop} : a ∉ {x | p x} ↔ ¬ p a := iff.rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem set_of_set {s : set α} : set_of s = s := rfl lemma set_of_app_iff {p : α → Prop} {x : α} : {x | p x} x ↔ p x := iff.rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl lemma set_of_bijective : bijective (set_of : (α → Prop) → set α) := bijective_id @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl lemma set_of_and {p q : α → Prop} : {a | p a ∧ q a} = {a | p a} ∩ {a | q a} := rfl lemma set_of_or {p q : α → Prop} : {a | p a ∨ q a} = {a | p a} ∪ {a | q a} := rfl /-! ### Subset and strict subset relations -/ instance : is_refl (set α) (⊆) := has_le.le.is_refl instance : is_trans (set α) (⊆) := has_le.le.is_trans instance : is_antisymm (set α) (⊆) := has_le.le.is_antisymm instance : is_irrefl (set α) (⊂) := has_lt.lt.is_irrefl instance : is_trans (set α) (⊂) := has_lt.lt.is_trans instance : is_asymm (set α) (⊂) := has_lt.lt.is_asymm instance : is_nonstrict_strict_order (set α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? lemma subset_def : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl lemma ssubset_def : s ⊂ t = (s ⊆ t ∧ ¬ t ⊆ s) := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := λ x h, bc $ ab h @[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := set.ext $ λ x, ⟨@h₁ _, @h₂ _⟩ theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, ⟨e.subset, e.symm.subset⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alternative name theorem eq_of_subset_of_subset {a b : set α} : a ⊆ b → b ⊆ a → a = b := subset.antisymm theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ := @h _ theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s := mt $ mem_of_subset_of_mem h theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp only [subset_def, not_forall] /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ protected theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := eq_or_lt_of_le h lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := not_subset.1 h.2 protected lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne (set α) _ s t lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s := ⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩ protected lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂.1 hs₂s₃, λ hs₃s₁, hs₁s₂.2 (subset.trans hs₂s₃ hs₃s₁)⟩ protected lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : set α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := ⟨subset.trans hs₁s₂ hs₂s₃.1, λ hs₃s₁, hs₂s₃.2 (subset.trans hs₃s₁ hs₁s₂)⟩ theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := id @[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := not_not /-! ### Non-empty sets -/ /-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s @[simp] lemma nonempty_coe_sort {s : set α} : nonempty ↥s ↔ s.nonempty := nonempty_subtype alias nonempty_coe_sort ↔ _ nonempty.coe_sort lemma nonempty_def : s.nonempty ↔ ∃ x, x ∈ s := iff.rfl lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩ theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅) | ⟨x, hx⟩ hs := hs hx /-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/ protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht lemma nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).nonempty := let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩ lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := nonempty_of_not_subset ht.2 lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr @[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right lemma inter_nonempty : (s ∩ t).nonempty ↔ ∃ x, x ∈ s ∧ x ∈ t := iff.rfl lemma inter_nonempty_iff_exists_left : (s ∩ t).nonempty ↔ ∃ x ∈ s, x ∈ t := by simp_rw [inter_nonempty, exists_prop] lemma inter_nonempty_iff_exists_right : (s ∩ t).nonempty ↔ ∃ x ∈ t, x ∈ s := by simp_rw [inter_nonempty, exists_prop, and_comm] lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty := ⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩ @[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty | ⟨x⟩ := ⟨x, trivial⟩ lemma nonempty.to_subtype : s.nonempty → nonempty s := nonempty_subtype.2 lemma nonempty.to_type : s.nonempty → nonempty α := λ ⟨x, hx⟩, ⟨x⟩ instance [nonempty α] : nonempty (set.univ : set α) := set.univ_nonempty.to_subtype lemma nonempty_of_nonempty_subtype [nonempty s] : s.nonempty := nonempty_subtype.mp ‹_› /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_iff_false (x : α) : x ∈ (∅ : set α) ↔ false := iff.rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s. theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := (subset.antisymm_iff.trans $ and_iff_left (empty_subset _)).symm theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := subset_empty_iff.symm lemma eq_empty_of_forall_not_mem (h : ∀ x, x ∉ s) : s = ∅ := subset_empty_iff.1 h theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem eq_empty_of_is_empty [is_empty α] (s : set α) : s = ∅ := eq_empty_of_subset_empty $ λ x hx, is_empty_elim x /-- There is exactly one set of a type that is empty. -/ instance unique_empty [is_empty α] : unique (set α) := { default := ∅, uniq := eq_empty_of_is_empty } /-- See also `set.nonempty_iff_ne_empty`. -/ lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ := by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists] /-- See also `set.not_nonempty_iff_eq_empty`. -/ lemma nonempty_iff_ne_empty : s.nonempty ↔ s ≠ ∅ := not_nonempty_iff_eq_empty.not_right alias nonempty_iff_ne_empty ↔ nonempty.ne_empty _ @[simp] lemma not_nonempty_empty : ¬(∅ : set α).nonempty := λ ⟨x, hx⟩, hx @[simp] lemma is_empty_coe_sort {s : set α} : is_empty ↥s ↔ s = ∅ := not_iff_not.1 $ by simpa using nonempty_iff_ne_empty lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty := or_iff_not_imp_left.2 nonempty_iff_ne_empty.2 theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := iff_true_intro $ λ x, false.elim instance (α : Type u) : is_empty.{u+1} (∅ : set α) := ⟨λ x, x.2⟩ @[simp] lemma empty_ssubset : ∅ ⊂ s ↔ s.nonempty := (@bot_lt_iff_ne_bot (set α) _ _ _).trans nonempty_iff_ne_empty.symm alias empty_ssubset ↔ _ nonempty.empty_ssubset /-! ### Universal set. In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ @[simp] theorem set_of_true : {x : α | true} = univ := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial @[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ is_empty α := eq_empty_iff_forall_not_mem.trans ⟨λ H, ⟨λ x, H x trivial⟩, λ H x _, @is_empty.false α H x⟩ theorem empty_ne_univ [nonempty α] : (∅ : set α) ≠ univ := λ e, not_is_empty_of_nonempty α $ univ_eq_empty_iff.1 e.symm @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := @top_le_iff _ _ _ s alias univ_subset_iff ↔ eq_univ_of_univ_subset _ theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := univ_subset_iff.symm.trans $ forall_congr $ λ x, imp_iff_right trivial theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma nonempty.eq_univ [subsingleton α] : s.nonempty → s = univ := by { rintro ⟨x, hx⟩, refine eq_univ_of_forall (λ y, by rwa subsingleton.elim y x) } lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ := eq_univ_of_univ_subset $ hs ▸ h lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ lemma ne_univ_iff_exists_not_mem {α : Type*} (s : set α) : s ≠ univ ↔ ∃ a, a ∉ s := by rw [←not_forall, ←eq_univ_iff_forall] lemma not_subset_iff_exists_mem_not_mem {α : Type*} {s t : set α} : ¬ s ⊆ t ↔ ∃ x, x ∈ s ∧ x ∉ t := by simp [subset_def] lemma univ_unique [unique α] : @set.univ α = {default} := set.ext $ λ x, iff_of_true trivial $ subsingleton.elim x default lemma ssubset_univ_iff : s ⊂ univ ↔ s ≠ univ := lt_top_iff_ne_top instance nontrivial_of_nonempty [nonempty α] : nontrivial (set α) := ⟨⟨∅, univ, empty_ne_univ⟩⟩ /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ @[simp] theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ (x ∈ a ∨ x ∈ b) := iff.rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext $ λ x, or_self _ @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext $ λ x, or_false _ @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext $ λ x, false_or _ theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext $ λ x, or.comm theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext $ λ x, or.assoc instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ x, or.left_comm theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, or.right_comm @[simp] theorem union_eq_left_iff_subset {s t : set α} : s ∪ t = s ↔ t ⊆ s := sup_eq_left @[simp] theorem union_eq_right_iff_subset {s t : set α} : s ∪ t = t ↔ s ⊆ t := sup_eq_right theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := union_eq_right_iff_subset.mpr h theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := union_eq_left_iff_subset.mpr h @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x, or.rec (@sr _) (@tr _) @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (forall_congr (by exact λ x, or_imp_distrib)).trans forall_and_distrib theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := λ x, or.imp (@h₁ _) (@h₂ _) theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h subset.rfl theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union subset.rfl h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) lemma union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ⊔ u := sup_congr_left ht hu lemma union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u := sup_congr_right hs ht lemma union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t := sup_eq_sup_iff_left lemma union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u := sup_eq_sup_iff_right @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := by simp only [← subset_empty_iff]; exact union_subset_iff @[simp] lemma union_univ {s : set α} : s ∪ univ = univ := sup_top_eq @[simp] lemma univ_union {s : set α} : univ ∪ s = univ := top_sup_eq /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl @[simp] theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ (x ∈ a ∧ x ∈ b) := iff.rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext $ λ x, and_self _ @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext $ λ x, and_false _ @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext $ λ x, false_and _ theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext $ λ x, and.comm theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext $ λ x, and.assoc instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ x, and.left_comm theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ x, and.right_comm @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x, and.left @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x, and.right theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x h, ⟨rs h, rt h⟩ @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := (forall_congr (by exact λ x, imp_and_distrib)).trans forall_and_distrib @[simp] theorem inter_eq_left_iff_subset {s t : set α} : s ∩ t = s ↔ s ⊆ t := inf_eq_left @[simp] theorem inter_eq_right_iff_subset {s t : set α} : s ∩ t = t ↔ t ⊆ s := inf_eq_right theorem inter_eq_self_of_subset_left {s t : set α} : s ⊆ t → s ∩ t = s := inter_eq_left_iff_subset.mpr theorem inter_eq_self_of_subset_right {s t : set α} : t ⊆ s → s ∩ t = t := inter_eq_right_iff_subset.mpr lemma inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u := inf_congr_left ht hu lemma inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u := inf_congr_right hs ht lemma inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u := inf_eq_inf_iff_left lemma inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t := inf_eq_inf_iff_right @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := inf_top_eq @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := top_inf_eq theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := λ x, and.imp (@h₁ _) (@h₂ _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter H subset.rfl theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := inter_subset_inter subset.rfl H theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := inter_eq_self_of_subset_right $ subset_union_left _ _ theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := inter_eq_self_of_subset_right $ subset_union_right _ _ lemma inter_set_of_eq_sep (s : set α) (p : α → Prop) : s ∩ {a | p a} = {a ∈ s | p a} := rfl lemma set_of_inter_eq_sep (p : α → Prop) (s : set α) : {a | p a} ∩ s = {a ∈ s | p a} := inter_comm _ _ /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_union_distrib_left (s t u : set α) : s ∪ (t ∪ u) = (s ∪ t) ∪ (s ∪ u) := sup_sup_distrib_left _ _ _ lemma union_union_distrib_right (s t u : set α) : (s ∪ t) ∪ u = (s ∪ u) ∪ (t ∪ u) := sup_sup_distrib_right _ _ _ lemma inter_inter_distrib_left (s t u : set α) : s ∩ (t ∩ u) = (s ∩ t) ∩ (s ∩ u) := inf_inf_distrib_left _ _ _ lemma inter_inter_distrib_right (s t u : set α) : (s ∩ t) ∩ u = (s ∩ u) ∩ (t ∩ u) := inf_inf_distrib_right _ _ _ lemma union_union_union_comm (s t u v : set α) : (s ∪ t) ∪ (u ∪ v) = (s ∪ u) ∪ (t ∪ v) := sup_sup_sup_comm _ _ _ _ lemma inter_inter_inter_comm (s t u v : set α) : (s ∩ t) ∩ (u ∩ v) = (s ∩ u) ∩ (t ∩ v) := inf_inf_inf_comm _ _ _ _ /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := λ y, or.inr theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id lemma mem_of_mem_insert_of_ne : b ∈ insert a s → b ≠ a → b ∈ s := or.resolve_left lemma eq_of_not_mem_of_mem_insert : b ∈ insert a s → b ∉ s → b = a := or.resolve_right @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ x = a ∨ x ∈ s := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := ext $ λ x, or_iff_right_of_imp $ λ e, e.symm ▸ h lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} : a ∉ s → s ≠ insert a t := mt $ λ e, e.symm ▸ mem_insert _ _ @[simp] lemma insert_eq_self : insert a s = s ↔ a ∈ s := ⟨λ h, h ▸ mem_insert _ _, insert_eq_of_mem⟩ lemma insert_ne_self : insert a s ≠ s ↔ a ∉ s := insert_eq_self.not theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp only [subset_def, or_imp_distrib, forall_and_distrib, forall_eq, mem_insert_iff] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := λ x, or.imp_right (@h _) theorem insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t := begin refine ⟨λ h x hx, _, insert_subset_insert⟩, rcases h (subset_insert _ _ hx) with (rfl|hxt), exacts [(ha hx).elim, hxt] end theorem subset_insert_iff_of_not_mem (ha : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t := forall₂_congr $ λ b hb, or_iff_right $ ne_of_mem_of_not_mem hb ha theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := begin simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset], simp only [exists_prop, and_comm] end theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff_insert.2 ⟨a, h, subset.rfl⟩ theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, or.left_comm @[simp] lemma insert_idem (a : α) (s : set α) : insert a (insert a s) = insert a s := insert_eq_of_mem $ mem_insert _ _ theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ λ x, or.assoc @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ λ x, or.left_comm @[simp] theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ instance (a : α) (s : set α) : nonempty (insert a s : set α) := (insert_nonempty a s).to_subtype lemma insert_inter_distrib (a : α) (s t : set α) : insert a (s ∩ t) = insert a s ∩ insert a t := ext $ λ y, or_and_distrib_left lemma insert_union_distrib (a : α) (s t : set α) : insert a (s ∪ t) = insert a s ∪ insert a t := ext $ λ _, or_or_distrib_left _ _ _ lemma insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b := ⟨λ h, eq_of_not_mem_of_mem_insert (h.subst $ mem_insert a s) ha, congr_arg _⟩ -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ insert a s → P x) (x) (h : x ∈ s) : P x := H _ (or.inr h) theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (H : ∀ x, x ∈ s → P x) (ha : P a) (x) (h : x ∈ insert a s) : P x := h.elim (λ e, e.symm ▸ ha) (H _) theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} : (∃ x ∈ insert a s, P x) ↔ P a ∨ (∃ x ∈ s, P x) := bex_or_left_distrib.trans $ or_congr_left' bex_eq_left theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := ball_or_left_distrib.trans $ and_congr_left' forall_eq /-! ### Lemmas about singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := (insert_emptyc_eq _).symm @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := iff.rfl @[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := rfl @[simp] lemma set_of_eq_eq_singleton' {a : α} : {x | a = x} = {a} := ext $ λ x, eq_comm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := @rfl _ _ theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := h @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := ext_iff.trans eq_iff_eq_cancel_left lemma singleton_injective : injective (singleton : α → set α) := λ _ _, singleton_eq_singleton_iff.mp theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := H theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := rfl @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := ⟨a, rfl⟩ @[simp] lemma singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := (singleton_nonempty _).ne_empty @[simp] lemma empty_ssubset_singleton : (∅ : set α) ⊂ {a} := (singleton_nonempty _).empty_ssubset @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := forall_eq lemma singleton_subset_singleton : ({a} : set α) ⊆ {b} ↔ a = b := by simp theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := rfl @[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl @[simp] theorem union_singleton : s ∪ {a} = insert a s := union_comm _ _ @[simp] theorem singleton_inter_nonempty : ({a} ∩ s).nonempty ↔ a ∈ s := by simp only [set.nonempty, mem_inter_iff, mem_singleton_iff, exists_eq_left] @[simp] theorem inter_singleton_nonempty : (s ∩ {a}).nonempty ↔ a ∈ s := by rw [inter_comm, singleton_inter_nonempty] @[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := not_nonempty_iff_eq_empty.symm.trans singleton_inter_nonempty.not @[simp] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty := nonempty_iff_ne_empty.symm instance unique_singleton (a : α) : unique ↥({a} : set α) := ⟨⟨⟨a, mem_singleton a⟩⟩, λ ⟨x, h⟩, subtype.eq h⟩ lemma eq_singleton_iff_unique_mem : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := subset.antisymm_iff.trans $ and.comm.trans $ and_congr_left' singleton_subset_iff lemma eq_singleton_iff_nonempty_unique_mem : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := eq_singleton_iff_unique_mem.trans $ and_congr_left $ λ H, ⟨λ h', ⟨_, h'⟩, λ ⟨x, h⟩, H x h ▸ h⟩ -- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS. @[simp] lemma default_coe_singleton (x : α) : (default : ({x} : set α)) = ⟨x, rfl⟩ := rfl /-! ### Lemmas about pairs -/ @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := union_self _ theorem pair_comm (a b : α) : ({a, b} : set α) = {b, a} := union_comm _ _ lemma pair_eq_pair_iff {x y z w : α} : ({x, y} : set α) = {z, w} ↔ x = z ∧ y = w ∨ x = w ∧ y = z := begin simp only [set.subset.antisymm_iff, set.insert_subset, set.mem_insert_iff, set.mem_singleton_iff, set.singleton_subset_iff], split, { tauto! }, { rintro (⟨rfl,rfl⟩|⟨rfl,rfl⟩); simp } end /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ section sep variables {p q : α → Prop} {x : α} theorem mem_sep (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem sep_mem_eq : {x ∈ s | x ∈ t} = s ∩ t := rfl @[simp] theorem mem_sep_iff : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem sep_ext_iff : {x ∈ s | p x} = {x ∈ s | q x} ↔ ∀ x ∈ s, (p x ↔ q x) := by simp_rw [ext_iff, mem_sep_iff, and.congr_right_iff] theorem sep_eq_of_subset (h : s ⊆ t) : {x ∈ t | x ∈ s} = s := inter_eq_self_of_subset_right h @[simp] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := λ x, and.left @[simp] lemma sep_eq_self_iff_mem_true : {x ∈ s | p x} = s ↔ ∀ x ∈ s, p x := by simp_rw [ext_iff, mem_sep_iff, and_iff_left_iff_imp] @[simp] lemma sep_eq_empty_iff_mem_false : {x ∈ s | p x} = ∅ ↔ ∀ x ∈ s, ¬ p x := by simp_rw [ext_iff, mem_sep_iff, mem_empty_iff_false, iff_false, not_and] @[simp] lemma sep_true : {x ∈ s | true} = s := inter_univ s @[simp] lemma sep_false : {x ∈ s | false} = ∅ := inter_empty s @[simp] lemma sep_empty (p : α → Prop) : {x ∈ (∅ : set α) | p x} = ∅ := empty_inter p @[simp] lemma sep_univ : {x ∈ (univ : set α) | p x} = {x | p x} := univ_inter p @[simp] lemma sep_union : {x ∈ s ∪ t | p x} = {x ∈ s | p x} ∪ {x ∈ t | p x} := union_inter_distrib_right @[simp] lemma sep_inter : {x ∈ s ∩ t | p x} = {x ∈ s | p x} ∩ {x ∈ t | p x} := inter_inter_distrib_right s t p @[simp] lemma sep_and : {x ∈ s | p x ∧ q x} = {x ∈ s | p x} ∩ {x ∈ s | q x} := inter_inter_distrib_left s p q @[simp] lemma sep_or : {x ∈ s | p x ∨ q x} = {x ∈ s | p x} ∪ {x ∈ s | q x} := inter_union_distrib_left @[simp] lemma sep_set_of : {x ∈ {y | p y} | q x} = {x | p x ∧ q x} := rfl end sep @[simp] lemma subset_singleton_iff {α : Type*} {s : set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x := iff.rfl lemma subset_singleton_iff_eq {s : set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} := begin obtain (rfl | hs) := s.eq_empty_or_nonempty, use ⟨λ _, or.inl rfl, λ _, empty_subset _⟩, simp [eq_singleton_iff_nonempty_unique_mem, hs, hs.ne_empty], end lemma nonempty.subset_singleton_iff (h : s.nonempty) : s ⊆ {a} ↔ s = {a} := subset_singleton_iff_eq.trans $ or_iff_right h.ne_empty lemma ssubset_singleton_iff {s : set α} {x : α} : s ⊂ {x} ↔ s = ∅ := begin rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_distrib_right, and_not_self, or_false, and_iff_left_iff_imp], exact λ h, ne_of_eq_of_ne h (singleton_ne_empty _).symm, end lemma eq_empty_of_ssubset_singleton {s : set α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### Disjointness -/ protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := disjoint_iff_inf_le theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff lemma _root_.disjoint.inter_eq : disjoint s t → s ∩ t = ∅ := disjoint.eq_bot lemma disjoint_left : disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t := disjoint_iff_inf_le.trans $ forall_congr $ λ _, not_and lemma disjoint_right : disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] lemma not_disjoint_iff : ¬disjoint s t ↔ ∃ x, x ∈ s ∧ x ∈ t := set.disjoint_iff.not.trans $ not_forall.trans $ exists_congr $ λ x, not_not lemma not_disjoint_iff_nonempty_inter : ¬disjoint s t ↔ (s ∩ t).nonempty := not_disjoint_iff alias not_disjoint_iff_nonempty_inter ↔ _ nonempty.not_disjoint lemma disjoint_or_nonempty_inter (s t : set α) : disjoint s t ∨ (s ∩ t).nonempty := (em _).imp_right not_disjoint_iff_nonempty_inter.mp lemma disjoint_iff_forall_ne : disjoint s t ↔ ∀ (x ∈ s) (y ∈ t), x ≠ y := by simp only [ne.def, disjoint_left, @imp_not_comm _ (_ = _), forall_eq'] lemma _root_.disjoint.ne_of_mem (h : disjoint s t) {x y} (hx : x ∈ s) (hy : y ∈ t) : x ≠ y := disjoint_iff_forall_ne.mp h x hx y hy lemma disjoint_of_subset_left (hs : s₁ ⊆ s₂) (h : disjoint s₂ t) : disjoint s₁ t := h.mono_left hs lemma disjoint_of_subset_right (ht : t₁ ⊆ t₂) (h : disjoint s t₂) : disjoint s t₁ := h.mono_right ht lemma disjoint_of_subset (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (h : disjoint s₂ t₂) : disjoint s₁ t₁ := h.mono hs ht @[simp] lemma disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := disjoint_sup_left @[simp] lemma disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := disjoint_sup_right @[simp] lemma disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right @[simp] lemma empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left @[simp] lemma univ_disjoint : disjoint univ s ↔ s = ∅ := top_disjoint @[simp] lemma disjoint_univ : disjoint s univ ↔ s = ∅ := disjoint_top lemma disjoint_sdiff_left : disjoint (t \ s) s := disjoint_sdiff_self_left lemma disjoint_sdiff_right : disjoint s (t \ s) := disjoint_sdiff_self_right lemma diff_union_diff_cancel (hts : t ⊆ s) (hut : u ⊆ t) : s \ t ∪ t \ u = s \ u := sdiff_sup_sdiff_cancel hts hut lemma diff_diff_eq_sdiff_union (h : u ⊆ s) : s \ (t \ u) = s \ t ∪ u := sdiff_sdiff_eq_sdiff_sup h @[simp] lemma disjoint_singleton_left : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl @[simp] lemma disjoint_singleton_right : disjoint s {a} ↔ a ∉ s := disjoint.comm.trans disjoint_singleton_left @[simp] lemma disjoint_singleton : disjoint ({a} : set α) {b} ↔ a ≠ b := by rw [disjoint_singleton_left, mem_singleton_iff] lemma subset_diff : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := le_iff_subset.symm.trans le_sdiff lemma inter_diff_distrib_left (s t u : set α) : s ∩ (t \ u) = (s ∩ t) \ (s ∩ u) := inf_sdiff_distrib_left _ _ _ lemma inter_diff_distrib_right (s t u : set α) : s \ t ∩ u = (s ∩ u) \ (t ∩ u) := inf_sdiff_distrib_right _ _ _ /-! ### Lemmas about complement -/ lemma compl_def (s : set α) : sᶜ = {x | x ∉ s} := rfl theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h lemma compl_set_of {α} (p : α → Prop) : {a | p a}ᶜ = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h @[simp] theorem mem_compl_iff (s : set α) (x : α) : x ∈ sᶜ ↔ (x ∉ s) := iff.rfl lemma not_mem_compl_iff {x : α} : x ∉ sᶜ ↔ x ∈ s := not_not @[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ := compl_inf_eq_bot @[simp] theorem compl_empty : (∅ : set α)ᶜ = univ := compl_bot @[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ := compl_top @[simp] lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ := compl_eq_bot @[simp] lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ := compl_eq_top lemma compl_ne_univ : sᶜ ≠ univ ↔ s.nonempty := compl_univ_iff.not.trans nonempty_iff_ne_empty.symm lemma nonempty_compl : sᶜ.nonempty ↔ s ≠ univ := (ne_univ_iff_exists_not_mem s).symm lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a := iff.rfl lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} := rfl @[simp] lemma compl_ne_eq_singleton (a : α) : ({x | x ≠ a} : set α)ᶜ = {a} := compl_compl _ theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ := ext $ λ x, or_iff_not_and_not theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ := ext $ λ x, and_iff_not_or_not @[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ := eq_univ_iff_forall.2 $ λ x, em _ @[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self] lemma compl_subset_comm : sᶜ ⊆ t ↔ tᶜ ⊆ s := @compl_le_iff_compl_le _ s _ _ lemma subset_compl_comm : s ⊆ tᶜ ↔ t ⊆ sᶜ := @le_compl_iff_le_compl _ _ _ t @[simp] lemma compl_subset_compl : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le (set α) _ _ _ lemma subset_compl_iff_disjoint_left : s ⊆ tᶜ ↔ disjoint t s := @le_compl_iff_disjoint_left (set α) _ _ _ lemma subset_compl_iff_disjoint_right : s ⊆ tᶜ ↔ disjoint s t := @le_compl_iff_disjoint_right (set α) _ _ _ lemma disjoint_compl_left_iff_subset : disjoint sᶜ t ↔ t ⊆ s := disjoint_compl_left_iff lemma disjoint_compl_right_iff_subset : disjoint s tᶜ ↔ s ⊆ t := disjoint_compl_right_iff alias subset_compl_iff_disjoint_right ↔ _ _root_.disjoint.subset_compl_right alias subset_compl_iff_disjoint_left ↔ _ _root_.disjoint.subset_compl_left alias disjoint_compl_left_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_left alias disjoint_compl_right_iff_subset ↔ _ _root_.has_subset.subset.disjoint_compl_right theorem subset_union_compl_iff_inter_subset {s t u : set α} : s ⊆ t ∪ uᶜ ↔ s ∩ u ⊆ t := (@is_compl_compl _ u _).le_sup_right_iff_inf_left_le theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, or_iff_not_imp_left @[simp] lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s := subset_compl_comm.trans singleton_subset_iff theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c := forall_congr $ λ x, and_imp.trans $ imp_congr_right $ λ _, imp_iff_not_or lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t := (not_subset.trans $ exists_congr $ by exact λ x, by simp [mem_compl]).symm /-! ### Lemmas about set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ tᶜ := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ lemma not_mem_diff_of_mem {s t : set α} {x : α} (hx : x ∈ t) : x ∉ s \ t := λ h, h.2 hx theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem diff_eq_compl_inter {s t : set α} : s \ t = tᶜ ∩ s := by rw [diff_eq, inter_comm] theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := inter_compl_nonempty_iff theorem diff_subset (s t : set α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le theorem union_diff_cancel' {s t u : set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ (u \ s) = u := sup_sdiff_cancel' h₁ h₂ theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := sup_sdiff_cancel_right h theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := disjoint.sup_sdiff_cancel_left $ disjoint_iff_inf_le.2 h theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := disjoint.sup_sdiff_cancel_right $ disjoint_iff_inf_le.2 h @[simp] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := sup_sdiff_left_self @[simp] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := sup_sdiff_right_self theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := sup_sdiff theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inf_sdiff_assoc @[simp] theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := inf_sdiff_self_right @[simp] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := sup_inf_sdiff s t @[simp] lemma diff_union_inter (s t : set α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] theorem inter_union_compl (s t : set α) : (s ∩ t) ∪ (s ∩ tᶜ) = s := inter_union_diff _ _ theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂, from sdiff_le_sdiff theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := sdiff_le_sdiff_right ‹s₁ ≤ s₂› theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := sdiff_le_sdiff_left ‹t ≤ u› theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s := top_sdiff.symm @[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ := bot_sdiff theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := sdiff_bot @[simp] lemma diff_univ (s : set α) : s \ univ = ∅ := diff_eq_empty.2 (subset_univ s) theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := sdiff_sdiff_left -- the following statement contains parentheses to help the reader lemma diff_diff_comm {s t u : set α} : (s \ t) \ u = (s \ u) \ t := sdiff_sdiff_comm lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := show s \ t ≤ u ↔ s ≤ t ∪ u, from sdiff_le_iff lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t := show s ≤ (s \ t) ∪ t, from le_sdiff_sup lemma diff_union_of_subset {s t : set α} (h : t ⊆ s) : (s \ t) ∪ t = s := subset.antisymm (union_subset (diff_subset _ _) h) (subset_diff_union _ _) @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} := subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := show s \ t ≤ u ↔ s \ u ≤ t, from sdiff_le_comm lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := sdiff_inf lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) := sdiff_sup.symm lemma diff_compl : s \ tᶜ = s ∩ t := sdiff_compl lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) := sdiff_sdiff_right' @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := by { ext, split; simp [or_imp_distrib, h] {contextual := tt} } theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := begin classical, ext x, by_cases h' : x ∈ t, { have : x ≠ a, { assume H, rw H at h', exact h h' }, simp [h, h', this] }, { simp [h, h'] } end lemma insert_diff_self_of_not_mem {a : α} {s : set α} (h : a ∉ s) : insert a s \ {a} = s := by { ext, simp [and_iff_left_of_imp (λ hx : x ∈ s, show x ≠ a, from λ hxa, h $ hxa ▸ hx)] } @[simp] lemma insert_diff_eq_singleton {a : α} {s : set α} (h : a ∉ s) : insert a s \ s = {a} := begin ext, rw [set.mem_diff, set.mem_insert_iff, set.mem_singleton_iff, or_and_distrib_right, and_not_self, or_false, and_iff_left_iff_imp], rintro rfl, exact h, end lemma inter_insert_of_mem (h : a ∈ s) : s ∩ insert a t = insert a (s ∩ t) := by rw [insert_inter_distrib, insert_eq_of_mem h] lemma insert_inter_of_mem (h : a ∈ t) : insert a s ∩ t = insert a (s ∩ t) := by rw [insert_inter_distrib, insert_eq_of_mem h] lemma inter_insert_of_not_mem (h : a ∉ s) : s ∩ insert a t = s ∩ t := ext $ λ x, and_congr_right $ λ hx, or_iff_right $ ne_of_mem_of_not_mem hx h lemma insert_inter_of_not_mem (h : a ∉ t) : insert a s ∩ t = s ∩ t := ext $ λ x, and_congr_left $ λ hx, or_iff_right $ ne_of_mem_of_not_mem hx h @[simp] lemma union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := sup_sdiff_self _ _ @[simp] lemma diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := sdiff_sup_self _ _ @[simp] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := inf_sdiff_self_left @[simp] theorem diff_inter_self_eq_diff {s t : set α} : s \ (t ∩ s) = s \ t := sdiff_inf_self_right _ _ @[simp] theorem diff_self_inter {s t : set α} : s \ (s ∩ t) = s \ t := sdiff_inf_self_left _ _ @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := sdiff_eq_self_iff_disjoint.2 $ by simp [h] @[simp] lemma diff_singleton_ssubset {s : set α} {a : α} : s \ {a} ⊂ s ↔ a ∈ s := sdiff_le.lt_iff_ne.trans $ sdiff_eq_left.not.trans $ by simp @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] lemma insert_diff_singleton_comm (hab : a ≠ b) (s : set α) : insert a (s \ {b}) = insert a s \ {b} := by simp_rw [←union_singleton, union_diff_distrib, diff_singleton_eq_self (mem_singleton_iff.not.2 hab.symm)] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := sdiff_self lemma diff_diff_right_self (s t : set α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s := sdiff_sdiff_eq_self h lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) := iff.rfl lemma mem_diff_singleton_empty {t : set (set α)} : s ∈ t \ {∅} ↔ s ∈ t ∧ s.nonempty := mem_diff_singleton.trans $ and_congr_right' nonempty_iff_ne_empty.symm lemma union_eq_diff_union_diff_union_inter (s t : set α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf /-! ### Symmetric difference -/ lemma mem_symm_diff : a ∈ s ∆ t ↔ a ∈ s ∧ a ∉ t ∨ a ∈ t ∧ a ∉ s := iff.rfl protected lemma symm_diff_def (s t : set α) : s ∆ t = s \ t ∪ t \ s := rfl lemma symm_diff_subset_union : s ∆ t ⊆ s ∪ t := @symm_diff_le_sup (set α) _ _ _ @[simp] lemma symm_diff_eq_empty : s ∆ t = ∅ ↔ s = t := symm_diff_eq_bot @[simp] lemma symm_diff_nonempty : (s ∆ t).nonempty ↔ s ≠ t := nonempty_iff_ne_empty.trans symm_diff_eq_empty.not lemma inter_symm_diff_distrib_left (s t u : set α) : s ∩ t ∆ u = (s ∩ t) ∆ (s ∩ u) := inf_symm_diff_distrib_left _ _ _ lemma inter_symm_diff_distrib_right (s t u : set α) : s ∆ t ∩ u = (s ∩ u) ∆ (t ∩ u) := inf_symm_diff_distrib_right _ _ _ lemma subset_symm_diff_union_symm_diff_left (h : disjoint s t) : u ⊆ s ∆ u ∪ t ∆ u := h.le_symm_diff_sup_symm_diff_left lemma subset_symm_diff_union_symm_diff_right (h : disjoint t u) : s ⊆ s ∆ t ∪ s ∆ u := h.le_symm_diff_sup_symm_diff_right /-! ### Powerset -/ /-- `𝒫 s = set.powerset s` is the set of all subsets of `s`. -/ def powerset (s : set α) : set (set α) := {t | t ⊆ s} prefix `𝒫`:100 := powerset theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ 𝒫 s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ 𝒫 s) : x ⊆ s := h @[simp] theorem mem_powerset_iff (x s : set α) : x ∈ 𝒫 s ↔ x ⊆ s := iff.rfl theorem powerset_inter (s t : set α) : 𝒫 (s ∩ t) = 𝒫 s ∩ 𝒫 t := ext $ λ u, subset_inter_iff @[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t := ⟨λ h, h (subset.refl s), λ h u hu, subset.trans hu h⟩ theorem monotone_powerset : monotone (powerset : set α → set (set α)) := λ s t, powerset_mono.2 @[simp] theorem powerset_nonempty : (𝒫 s).nonempty := ⟨∅, empty_subset s⟩ @[simp] theorem powerset_empty : 𝒫 (∅ : set α) = {∅} := ext $ λ s, subset_empty_iff @[simp] theorem powerset_univ : 𝒫 (univ : set α) = univ := eq_univ_of_forall subset_univ /-- The powerset of a singleton contains only `∅` and the singleton itself. -/ theorem powerset_singleton (x : α) : 𝒫 ({x} : set α) = {∅, {x}} := by { ext y, rw [mem_powerset_iff, subset_singleton_iff_eq, mem_insert_iff, mem_singleton_iff] } /-! ### Sets defined as an if-then-else -/ lemma mem_dite_univ_right (p : Prop) [decidable p] (t : p → set α) (x : α) : (x ∈ if h : p then t h else univ) ↔ (∀ h : p, x ∈ t h) := by split_ifs; simp [h] @[simp] lemma mem_ite_univ_right (p : Prop) [decidable p] (t : set α) (x : α) : x ∈ ite p t set.univ ↔ (p → x ∈ t) := mem_dite_univ_right p (λ _, t) x lemma mem_dite_univ_left (p : Prop) [decidable p] (t : ¬ p → set α) (x : α) : (x ∈ if h : p then univ else t h) ↔ (∀ h : ¬ p, x ∈ t h) := by split_ifs; simp [h] @[simp] lemma mem_ite_univ_left (p : Prop) [decidable p] (t : set α) (x : α) : x ∈ ite p set.univ t ↔ (¬ p → x ∈ t) := mem_dite_univ_left p (λ _, t) x lemma mem_dite_empty_right (p : Prop) [decidable p] (t : p → set α) (x : α) : (x ∈ if h : p then t h else ∅) ↔ (∃ h : p, x ∈ t h) := by split_ifs; simp [h] @[simp] lemma mem_ite_empty_right (p : Prop) [decidable p] (t : set α) (x : α) : x ∈ ite p t ∅ ↔ p ∧ x ∈ t := by split_ifs; simp [h] lemma mem_dite_empty_left (p : Prop) [decidable p] (t : ¬ p → set α) (x : α) : (x ∈ if h : p then ∅ else t h) ↔ (∃ h : ¬ p, x ∈ t h) := by split_ifs; simp [h] @[simp] lemma mem_ite_empty_left (p : Prop) [decidable p] (t : set α) (x : α) : x ∈ ite p ∅ t ↔ ¬ p ∧ x ∈ t := by split_ifs; simp [h] /-! ### If-then-else for sets -/ /-- `ite` for sets: `set.ite t s s' ∩ t = s ∩ t`, `set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`. Defined as `s ∩ t ∪ s' \ t`. -/ protected def ite (t s s' : set α) : set α := s ∩ t ∪ s' \ t @[simp] lemma ite_inter_self (t s s' : set α) : t.ite s s' ∩ t = s ∩ t := by rw [set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty] @[simp] lemma ite_compl (t s s' : set α) : tᶜ.ite s s' = t.ite s' s := by rw [set.ite, set.ite, diff_compl, union_comm, diff_eq] @[simp] lemma ite_inter_compl_self (t s s' : set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ := by rw [← ite_compl, ite_inter_self] @[simp] lemma ite_diff_self (t s s' : set α) : t.ite s s' \ t = s' \ t := ite_inter_compl_self t s s' @[simp] lemma ite_same (t s : set α) : t.ite s s = s := inter_union_diff _ _ @[simp] lemma ite_left (s t : set α) : s.ite s t = s ∪ t := by simp [set.ite] @[simp] lemma ite_right (s t : set α) : s.ite t s = t ∩ s := by simp [set.ite] @[simp] lemma ite_empty (s s' : set α) : set.ite ∅ s s' = s' := by simp [set.ite] @[simp] lemma ite_univ (s s' : set α) : set.ite univ s s' = s := by simp [set.ite] @[simp] lemma ite_empty_left (t s : set α) : t.ite ∅ s = s \ t := by simp [set.ite] @[simp] lemma ite_empty_right (t s : set α) : t.ite s ∅ = s ∩ t := by simp [set.ite] lemma ite_mono (t : set α) {s₁ s₁' s₂ s₂' : set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') : t.ite s₁ s₁' ⊆ t.ite s₂ s₂' := union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h') lemma ite_subset_union (t s s' : set α) : t.ite s s' ⊆ s ∪ s' := union_subset_union (inter_subset_left _ _) (diff_subset _ _) lemma inter_subset_ite (t s s' : set α) : s ∩ s' ⊆ t.ite s s' := ite_same t (s ∩ s') ▸ ite_mono _ (inter_subset_left _ _) (inter_subset_right _ _) lemma ite_inter_inter (t s₁ s₂ s₁' s₂' : set α) : t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' := by { ext x, simp only [set.ite, set.mem_inter_iff, set.mem_diff, set.mem_union], itauto } lemma ite_inter (t s₁ s₂ s : set α) : t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s := by rw [ite_inter_inter, ite_same] lemma ite_inter_of_inter_eq (t : set α) {s₁ s₂ s : set α} (h : s₁ ∩ s = s₂ ∩ s) : t.ite s₁ s₂ ∩ s = s₁ ∩ s := by rw [← ite_inter, ← h, ite_same] lemma subset_ite {t s s' u : set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' := begin simp only [subset_def, ← forall_and_distrib], refine forall_congr (λ x, _), by_cases hx : x ∈ t; simp [*, set.ite] end /-! ### Subsingleton -/ /-- A set `s` is a `subsingleton` if it has at most one element. -/ protected def subsingleton (s : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y lemma subsingleton.anti (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton := λ x hx y hy, ht (hst hx) (hst hy) lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) : s = {x} := ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩ @[simp] lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim @[simp] lemma subsingleton_singleton {a} : ({a} : set α).subsingleton := λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl lemma subsingleton_of_subset_singleton (h : s ⊆ {a}) : s.subsingleton := subsingleton_singleton.anti h lemma subsingleton_of_forall_eq (a : α) (h : ∀ b ∈ s, b = a) : s.subsingleton := λ b hb c hc, (h _ hb).trans (h _ hc).symm lemma subsingleton_iff_singleton {x} (hx : x ∈ s) : s.subsingleton ↔ s = {x} := ⟨λ h, h.eq_singleton_of_mem hx, λ h,h.symm ▸ subsingleton_singleton⟩ lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) : s = ∅ ∨ ∃ x, s = {x} := s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩) lemma subsingleton.induction_on {p : set α → Prop} (hs : s.subsingleton) (he : p ∅) (h₁ : ∀ x, p {x}) : p s := by { rcases hs.eq_empty_or_singleton with rfl|⟨x, rfl⟩, exacts [he, h₁ _] } lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton := λ x hx y hy, subsingleton.elim x y lemma subsingleton_of_univ_subsingleton (h : (univ : set α).subsingleton) : subsingleton α := ⟨λ a b, h (mem_univ a) (mem_univ b)⟩ @[simp] lemma subsingleton_univ_iff : (univ : set α).subsingleton ↔ subsingleton α := ⟨subsingleton_of_univ_subsingleton, λ h, @subsingleton_univ _ h⟩ lemma subsingleton_of_subsingleton [subsingleton α] {s : set α} : set.subsingleton s := subsingleton_univ.anti (subset_univ s) lemma subsingleton_is_top (α : Type*) [partial_order α] : set.subsingleton {x : α | is_top x} := λ x hx y hy, hx.is_max.eq_of_le (hy x) lemma subsingleton_is_bot (α : Type*) [partial_order α] : set.subsingleton {x : α | is_bot x} := λ x hx y hy, hx.is_min.eq_of_ge (hy x) lemma exists_eq_singleton_iff_nonempty_subsingleton : (∃ a : α, s = {a}) ↔ s.nonempty ∧ s.subsingleton := begin refine ⟨_, λ h, _⟩, { rintros ⟨a, rfl⟩, exact ⟨singleton_nonempty a, subsingleton_singleton⟩ }, { exact h.2.eq_empty_or_singleton.resolve_left h.1.ne_empty }, end /-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/ @[simp, norm_cast] lemma subsingleton_coe (s : set α) : subsingleton s ↔ s.subsingleton := begin split, { refine λ h, (λ a ha b hb, _), exact set_coe.ext_iff.2 (@subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) }, { exact λ h, subsingleton.intro (λ a b, set_coe.ext (h a.property b.property)) } end lemma subsingleton.coe_sort {s : set α} : s.subsingleton → subsingleton s := s.subsingleton_coe.2 /-- The `coe_sort` of a set `s` in a subsingleton type is a subsingleton. For the corresponding result for `subtype`, see `subtype.subsingleton`. -/ instance subsingleton_coe_of_subsingleton [subsingleton α] {s : set α} : subsingleton s := by { rw [s.subsingleton_coe], exact subsingleton_of_subsingleton } /-! ### Nontrivial -/ /-- A set `s` is `nontrivial` if it has at least two distinct elements. -/ protected def nontrivial (s : set α) : Prop := ∃ x y ∈ s, x ≠ y lemma nontrivial_of_mem_mem_ne {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : s.nontrivial := ⟨x, hx, y, hy, hxy⟩ /-- Extract witnesses from s.nontrivial. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the classical.choice axiom. -/ protected noncomputable def nontrivial.some (hs : s.nontrivial) : α × α := (hs.some, hs.some_spec.some_spec.some) protected lemma nontrivial.some_fst_mem (hs : s.nontrivial) : hs.some.fst ∈ s := hs.some_spec.some protected lemma nontrivial.some_snd_mem (hs : s.nontrivial) : hs.some.snd ∈ s := hs.some_spec.some_spec.some_spec.some protected lemma nontrivial.some_fst_ne_some_snd (hs : s.nontrivial) : hs.some.fst ≠ hs.some.snd := hs.some_spec.some_spec.some_spec.some_spec lemma nontrivial.mono (hs : s.nontrivial) (hst : s ⊆ t) : t.nontrivial := let ⟨x, hx, y, hy, hxy⟩ := hs in ⟨x, hst hx, y, hst hy, hxy⟩ lemma nontrivial_pair {x y} (hxy : x ≠ y) : ({x, y} : set α).nontrivial := ⟨x, mem_insert _ _, y, mem_insert_of_mem _ (mem_singleton _), hxy⟩ lemma nontrivial_of_pair_subset {x y} (hxy : x ≠ y) (h : {x, y} ⊆ s) : s.nontrivial := (nontrivial_pair hxy).mono h lemma nontrivial.pair_subset (hs : s.nontrivial) : ∃ x y (hab : x ≠ y), {x, y} ⊆ s := let ⟨x, hx, y, hy, hxy⟩ := hs in ⟨x, y, hxy, insert_subset.2 ⟨hx, (singleton_subset_iff.2 hy)⟩⟩ lemma nontrivial_iff_pair_subset : s.nontrivial ↔ ∃ x y (hxy : x ≠ y), {x, y} ⊆ s := ⟨nontrivial.pair_subset, λ H, let ⟨x, y, hxy, h⟩ := H in nontrivial_of_pair_subset hxy h⟩ lemma nontrivial_of_exists_ne {x} (hx : x ∈ s) (h : ∃ y ∈ s, y ≠ x) : s.nontrivial := let ⟨y, hy, hyx⟩ := h in ⟨y, hy, x, hx, hyx⟩ lemma nontrivial.exists_ne (hs : s.nontrivial) (z) : ∃ x ∈ s, x ≠ z := begin by_contra H, push_neg at H, rcases hs with ⟨x, hx, y, hy, hxy⟩, rw [H x hx, H y hy] at hxy, exact hxy rfl end lemma nontrivial_iff_exists_ne {x} (hx : x ∈ s) : s.nontrivial ↔ ∃ y ∈ s, y ≠ x := ⟨λ H, H.exists_ne _, nontrivial_of_exists_ne hx⟩ lemma nontrivial_of_lt [preorder α] {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x < y) : s.nontrivial := ⟨x, hx, y, hy, ne_of_lt hxy⟩ lemma nontrivial_of_exists_lt [preorder α] (H : ∃ x y ∈ s, x < y) : s.nontrivial := let ⟨x, hx, y, hy, hxy⟩ := H in nontrivial_of_lt hx hy hxy lemma nontrivial.exists_lt [linear_order α] (hs : s.nontrivial) : ∃ x y ∈ s, x < y := let ⟨x, hx, y, hy, hxy⟩ := hs in or.elim (lt_or_gt_of_ne hxy) (λ H, ⟨x, hx, y, hy, H⟩) (λ H, ⟨y, hy, x, hx, H⟩) lemma nontrivial_iff_exists_lt [linear_order α] : s.nontrivial ↔ ∃ x y ∈ s, x < y := ⟨nontrivial.exists_lt, nontrivial_of_exists_lt⟩ protected lemma nontrivial.nonempty (hs : s.nontrivial) : s.nonempty := let ⟨x, hx, _⟩ := hs in ⟨x, hx⟩ protected lemma nontrivial.ne_empty (hs : s.nontrivial) : s ≠ ∅ := hs.nonempty.ne_empty lemma nontrivial.not_subset_empty (hs : s.nontrivial) : ¬ s ⊆ ∅ := hs.nonempty.not_subset_empty @[simp] lemma not_nontrivial_empty : ¬ (∅ : set α).nontrivial := λ h, h.ne_empty rfl @[simp] lemma not_nontrivial_singleton {x} : ¬ ({x} : set α).nontrivial := λ H, begin rw nontrivial_iff_exists_ne (mem_singleton x) at H, exact let ⟨y, hy, hya⟩ := H in hya (mem_singleton_iff.1 hy) end lemma nontrivial.ne_singleton {x} (hs : s.nontrivial) : s ≠ {x} := λ H, by { rw H at hs, exact not_nontrivial_singleton hs } lemma nontrivial.not_subset_singleton {x} (hs : s.nontrivial) : ¬ s ⊆ {x} := (not_congr subset_singleton_iff_eq).2 (not_or hs.ne_empty hs.ne_singleton) lemma nontrivial_univ [nontrivial α] : (univ : set α).nontrivial := let ⟨x, y, hxy⟩ := exists_pair_ne α in ⟨x, mem_univ _, y, mem_univ _, hxy⟩ lemma nontrivial_of_univ_nontrivial (h : (univ : set α).nontrivial) : nontrivial α := let ⟨x, _, y, _, hxy⟩ := h in ⟨⟨x, y, hxy⟩⟩ @[simp] lemma nontrivial_univ_iff : (univ : set α).nontrivial ↔ nontrivial α := ⟨nontrivial_of_univ_nontrivial, λ h, @nontrivial_univ _ h⟩ lemma nontrivial_of_nontrivial (hs : s.nontrivial) : nontrivial α := let ⟨x, _, y, _, hxy⟩ := hs in ⟨⟨x, y, hxy⟩⟩ /-- `s`, coerced to a type, is a nontrivial type if and only if `s` is a nontrivial set. -/ @[simp, norm_cast] lemma nontrivial_coe_sort {s : set α} : nontrivial s ↔ s.nontrivial := by simp_rw [← nontrivial_univ_iff, set.nontrivial, mem_univ, exists_true_left, set_coe.exists, subtype.mk_eq_mk] alias nontrivial_coe_sort ↔ _ nontrivial.coe_sort /-- A type with a set `s` whose `coe_sort` is a nontrivial type is nontrivial. For the corresponding result for `subtype`, see `subtype.nontrivial_iff_exists_ne`. -/ lemma nontrivial_of_nontrivial_coe (hs : nontrivial s) : nontrivial α := nontrivial_of_nontrivial $ nontrivial_coe_sort.1 hs theorem nontrivial_mono {α : Type*} {s t : set α} (hst : s ⊆ t) (hs : nontrivial s) : nontrivial t := nontrivial.coe_sort $ (nontrivial_coe_sort.1 hs).mono hst @[simp] lemma not_subsingleton_iff : ¬ s.subsingleton ↔ s.nontrivial := by simp_rw [set.subsingleton, set.nontrivial, not_forall] @[simp] lemma not_nontrivial_iff : ¬ s.nontrivial ↔ s.subsingleton := iff.not_left not_subsingleton_iff.symm alias not_nontrivial_iff ↔ _ subsingleton.not_nontrivial alias not_subsingleton_iff ↔ _ nontrivial.not_subsingleton protected lemma subsingleton_or_nontrivial (s : set α) : s.subsingleton ∨ s.nontrivial := by simp [or_iff_not_imp_right] lemma eq_singleton_or_nontrivial (ha : a ∈ s) : s = {a} ∨ s.nontrivial := by { rw ←subsingleton_iff_singleton ha, exact s.subsingleton_or_nontrivial } lemma nontrivial_iff_ne_singleton (ha : a ∈ s) : s.nontrivial ↔ s ≠ {a} := ⟨nontrivial.ne_singleton, (eq_singleton_or_nontrivial ha).resolve_left⟩ lemma nonempty.exists_eq_singleton_or_nontrivial : s.nonempty → (∃ a, s = {a}) ∨ s.nontrivial := λ ⟨a, ha⟩, (eq_singleton_or_nontrivial ha).imp_left $ exists.intro a theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section preorder variables [preorder α] [preorder β] {f : α → β} lemma monotone_on_iff_monotone : monotone_on f s ↔ monotone (λ a : s, f a) := by simp [monotone, monotone_on] lemma antitone_on_iff_antitone : antitone_on f s ↔ antitone (λ a : s, f a) := by simp [antitone, antitone_on] lemma strict_mono_on_iff_strict_mono : strict_mono_on f s ↔ strict_mono (λ a : s, f a) := by simp [strict_mono, strict_mono_on] lemma strict_anti_on_iff_strict_anti : strict_anti_on f s ↔ strict_anti (λ a : s, f a) := by simp [strict_anti, strict_anti_on] variables (f) /-! ### Monotonicity on singletons -/ protected lemma subsingleton.monotone_on (h : s.subsingleton) : monotone_on f s := λ a ha b hb _, (congr_arg _ (h ha hb)).le protected lemma subsingleton.antitone_on (h : s.subsingleton) : antitone_on f s := λ a ha b hb _, (congr_arg _ (h hb ha)).le protected lemma subsingleton.strict_mono_on (h : s.subsingleton) : strict_mono_on f s := λ a ha b hb hlt, (hlt.ne (h ha hb)).elim protected lemma subsingleton.strict_anti_on (h : s.subsingleton) : strict_anti_on f s := λ a ha b hb hlt, (hlt.ne (h ha hb)).elim @[simp] lemma monotone_on_singleton : monotone_on f {a} := subsingleton_singleton.monotone_on f @[simp] lemma antitone_on_singleton : antitone_on f {a} := subsingleton_singleton.antitone_on f @[simp] lemma strict_mono_on_singleton : strict_mono_on f {a} := subsingleton_singleton.strict_mono_on f @[simp] lemma strict_anti_on_singleton : strict_anti_on f {a} := subsingleton_singleton.strict_anti_on f end preorder section linear_order variables [linear_order α] [linear_order β] {f : α → β} /-- A function between linear orders which is neither monotone nor antitone makes a dent upright or downright. -/ lemma not_monotone_on_not_antitone_on_iff_exists_le_le : ¬ monotone_on f s ∧ ¬ antitone_on f s ↔ ∃ a b c ∈ s, a ≤ b ∧ b ≤ c ∧ (f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) := by simp [monotone_on_iff_monotone, antitone_on_iff_antitone, and_assoc, exists_and_distrib_left, not_monotone_not_antitone_iff_exists_le_le, @and.left_comm (_ ∈ s)] /-- A function between linear orders which is neither monotone nor antitone makes a dent upright or downright. -/ lemma not_monotone_on_not_antitone_on_iff_exists_lt_lt : ¬ monotone_on f s ∧ ¬ antitone_on f s ↔ ∃ a b c ∈ s, a < b ∧ b < c ∧ (f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) := by simp [monotone_on_iff_monotone, antitone_on_iff_antitone, and_assoc, exists_and_distrib_left, not_monotone_not_antitone_iff_exists_lt_lt, @and.left_comm (_ ∈ s)] end linear_order end set open set namespace function variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β} lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f) (h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty := by rw [nonempty_iff_ne_empty, ← h2, nonempty_iff_ne_empty, hf.ne_iff] end function open function namespace set /-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/ section inclusion variables {α : Type*} {s t u : set α} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self (x : s) : inclusion subset.rfl x = x := by { cases x, refl } lemma inclusion_eq_id (h : s ⊆ s) : inclusion h = id := funext inclusion_self @[simp] lemma inclusion_mk {h : s ⊆ t} (a : α) (ha : a ∈ s) : inclusion h ⟨a, ha⟩ = ⟨a, h ha⟩ := rfl lemma inclusion_right (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) : inclusion h ⟨x, m⟩ = x := by { cases x, refl } @[simp] lemma inclusion_inclusion (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (hst.trans htu) x := by { cases x, refl } @[simp] lemma inclusion_comp_inclusion {α} {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) : inclusion htu ∘ inclusion hst = inclusion (hst.trans htu) := funext (inclusion_inclusion hst htu) @[simp] lemma coe_inclusion (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) := rfl lemma inclusion_injective (h : s ⊆ t) : injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1 lemma eq_of_inclusion_surjective {s t : set α} {h : s ⊆ t} (h_surj : function.surjective (inclusion h)) : s = t := begin refine set.subset.antisymm h (λ x hx, _), obtain ⟨y, hy⟩ := h_surj ⟨x, hx⟩, exact mem_of_eq_of_mem (congr_arg coe hy).symm y.prop, end end inclusion end set namespace subsingleton variables {α : Type*} [subsingleton α] lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ := λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx @[elab_as_eliminator] lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1 lemma mem_iff_nonempty {α : Type*} [subsingleton α] {s : set α} {x : α} : x ∈ s ↔ s.nonempty := ⟨λ hx, ⟨x, hx⟩, λ ⟨y, hy⟩, subsingleton.elim y x ▸ hy⟩ end subsingleton /-! ### Decidability instances for sets -/ namespace set variables {α : Type u} (s t : set α) (a : α) instance decidable_sdiff [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s \ t) := (by apply_instance : decidable (a ∈ s ∧ a ∉ t)) instance decidable_inter [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∩ t) := (by apply_instance : decidable (a ∈ s ∧ a ∈ t)) instance decidable_union [decidable (a ∈ s)] [decidable (a ∈ t)] : decidable (a ∈ s ∪ t) := (by apply_instance : decidable (a ∈ s ∨ a ∈ t)) instance decidable_compl [decidable (a ∈ s)] : decidable (a ∈ sᶜ) := (by apply_instance : decidable (a ∉ s)) instance decidable_emptyset : decidable_pred (∈ (∅ : set α)) := λ _, decidable.is_false (by simp) instance decidable_univ : decidable_pred (∈ (set.univ : set α)) := λ _, decidable.is_true (by simp) instance decidable_set_of (p : α → Prop) [decidable (p a)] : decidable (a ∈ {a | p a}) := by assumption end set /-! ### Monotone lemmas for sets -/ section monotone variables {α β : Type*} theorem monotone.inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∩ g x) := hf.inf hg theorem monotone_on.inter [preorder β] {f g : β → set α} {s : set β} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ∩ g x) s := hf.inf hg theorem antitone.inter [preorder β] {f g : β → set α} (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ∩ g x) := hf.inf hg theorem antitone_on.inter [preorder β] {f g : β → set α} {s : set β} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ∩ g x) s := hf.inf hg theorem monotone.union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λ x, f x ∪ g x) := hf.sup hg theorem monotone_on.union [preorder β] {f g : β → set α} {s : set β} (hf : monotone_on f s) (hg : monotone_on g s) : monotone_on (λ x, f x ∪ g x) s := hf.sup hg theorem antitone.union [preorder β] {f g : β → set α} (hf : antitone f) (hg : antitone g) : antitone (λ x, f x ∪ g x) := hf.sup hg theorem antitone_on.union [preorder β] {f g : β → set α} {s : set β} (hf : antitone_on f s) (hg : antitone_on g s) : antitone_on (λ x, f x ∪ g x) s := hf.sup hg namespace set theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀ b, monotone (λ a, p a b)) : monotone (λ a, {b | p a b}) := λ a a' h b, hp b h theorem antitone_set_of [preorder α] {p : α → β → Prop} (hp : ∀ b, antitone (λ a, p a b)) : antitone (λ a, {b | p a b}) := λ a a' h b, hp b h /-- Quantifying over a set is antitone in the set -/ lemma antitone_bforall {P : α → Prop} : antitone (λ s : set α, ∀ x ∈ s, P x) := λ s t hst h x hx, h x $ hst hx end set end monotone /-! ### Disjoint sets -/ variables {α β : Type*} {s t u : set α} {f : α → β} namespace disjoint theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u := hs.sup_left ht theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) := ht.sup_right hu lemma inter_left (u : set α) (h : disjoint s t) : disjoint (s ∩ u) t := h.inf_left u lemma inter_left' (u : set α) (h : disjoint s t) : disjoint (u ∩ s) t := h.inf_left' _ lemma inter_right (u : set α) (h : disjoint s t) : disjoint s (t ∩ u) := h.inf_right _ lemma inter_right' (u : set α) (h : disjoint s t) : disjoint s (u ∩ t) := h.inf_right' _ lemma subset_left_of_subset_union (h : s ⊆ t ∪ u) (hac : disjoint s u) : s ⊆ t := hac.left_le_of_le_sup_right h lemma subset_right_of_subset_union (h : s ⊆ t ∪ u) (hab : disjoint s t) : s ⊆ u := hab.left_le_of_le_sup_left h end disjoint
8336d091d0fc60ce48bbc5a131c0ee5a8251f334
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/unreachable_cases.lean
66d49b92454c7b1fc26ee8035626bc573e2de195
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
558
lean
open nat prod inductive ifin : ℕ → Type -- inductively defined fin-type | fz : Π n, ifin (succ n) | fs : Π {n}, ifin n → ifin (succ n) open ifin definition foo {N : Type} : Π{n : ℕ}, N → ifin n → (N × ifin n) | (succ k) n (fz .k) := sorry | (succ k) n (fs x) := sorry definition bar {N : Type} : Π{n : ℕ}, (N × ifin n) → (N × ifin n) | (succ k) (n, fz .k) := sorry | (succ k) (n, fs x) := sorry definition bar2 {N : Type} : Π{n : ℕ}, (N × ifin n) → (N × ifin n) | (succ k) (n, fz .k) := sorry | (succ k) (n, fs x) := sorry
6a104f28c853104e164f314ef5fbb347c93492c7
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Init/Core.lean
63a238332ea9e4e26c88a11f44f2814e65fdbad9
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,727
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude import Init.Prelude import Init.Notation universes u v w def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b /- Remark: thunks have an efficient implementation in the runtime. -/ structure Thunk (α : Type u) : Type u := (fn : Unit → α) attribute [extern "lean_mk_thunk"] Thunk.mk @[noinline, extern "lean_thunk_pure"] protected def Thunk.pure {α : Type u} (a : α) : Thunk α := ⟨fun _ => a⟩ @[noinline, extern "lean_thunk_get_own"] protected def Thunk.get {α : Type u} (x : @& Thunk α) : α := x.fn () @[noinline, extern "lean_thunk_map"] protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ @[noinline, extern "lean_thunk_bind"] protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : Eq a b) (m : motive a) : motive b := Eq.ndrec m h structure Iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) infix:20 " <-> " => Iff infix:20 " ↔ " => Iff /- Eq basic support -/ theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ inductive Sum (α : Type u) (β : Type v) := | inl (val : α) : Sum α β | inr (val : β) : Sum α β inductive PSum (α : Sort u) (β : Sort v) := | inl (val : α) : PSum α β | inr (val : β) : PSum α β structure Sigma {α : Type u} (β : α → Type v) := mk :: (fst : α) (snd : β fst) attribute [unbox] Sigma structure PSigma {α : Sort u} (β : α → Sort v) := mk :: (fst : α) (snd : β fst) inductive Exists {α : Sort u} (p : α → Prop) : Prop := | intro (w : α) (h : p w) : Exists p /- Auxiliary type used to compile `for x in xs` notation. -/ inductive ForInStep (α : Type u) := | done : α → ForInStep α | yield : α → ForInStep α /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPRBC (α β σ : Type u) := | «pure» : α → σ → DoResultPRBC α β σ | «return» : β → σ → DoResultPRBC α β σ | «break» : σ → DoResultPRBC α β σ | «continue» : σ → DoResultPRBC α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPR (α β σ : Type u) := | «pure» : α → σ → DoResultPR α β σ | «return» : β → σ → DoResultPR α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultBC (σ : Type u) := | «break» : σ → DoResultBC σ | «continue» : σ → DoResultBC σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultSBC (α σ : Type u) := | «pureReturn» : α → σ → DoResultSBC α σ | «break» : σ → DoResultSBC α σ | «continue» : σ → DoResultSBC α σ class HasEquiv (α : Sort u) := (Equiv : α → α → Prop) infix:50 " ≈ " => HasEquiv.Equiv class EmptyCollection (α : Type u) := (emptyCollection : α) /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u := pure :: (get : α) attribute [extern "lean_task_pure"] Task.pure attribute [extern "lean_task_get_own"] Task.get namespace Task /-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/ abbrev Priority := Nat def Priority.default : Priority := 0 -- see `LEAN_MAX_PRIO` def Priority.max : Priority := 8 /-- Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread. This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more non-dedicated workers than the number of cores to reduce context switches. -/ def Priority.dedicated : Priority := 9 @[noinline, extern "lean_task_spawn"] protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α := ⟨fn ()⟩ @[noinline, extern "lean_task_map"] protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β := ⟨f x.get⟩ @[noinline, extern "lean_task_bind"] protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β := ⟨(f x.get).get⟩ end Task /- Some type that is not a scalar value in our runtime. -/ structure NonScalar := (val : Nat) /- Some type that is not a scalar value in our runtime and is universe polymorphic. -/ inductive PNonScalar : Type u := | mk (v : Nat) : PNonScalar theorem natAddZero (n : Nat) : n + 0 = n := rfl theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl /- Boolean operators -/ @[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool := !(a == b) infix:50 " != " => bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun hp => h₂ (h₁ hp) def trivial : True := ⟨⟩ theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun ha => h₂ (h₁ ha) theorem notFalse : ¬False := id -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl @[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β := h ▸ a @[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α := h ▸ b theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := h₁ ▸ h₂ theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : ∀ x, β x} (h : f = g) (a : α) : f a = g a := h ▸ rfl theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) infix:50 " ≠ " => Ne section Ne variable {α : Sort u} variables {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := fun h₁ => h (h₁.symm) theorem falseOfNe : a ≠ a → False := Ne.irrefl theorem neFalseOfSelf : p → p ≠ False := fun (hp : p) (h : p = False) => h ▸ hp theorem neTrueOfNot : ¬p → p ≠ True := fun (hnp : ¬p) (h : p = True) => have ¬True from h ▸ hnp this trivial theorem trueNeFalse : ¬True = False := neFalseOfSelf trivial end Ne section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : a ≅ b) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : motive a) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b := eqOfHEq h₁ ▸ h₂ theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b := HEq.ndrecOn h₁ h₂ theorem HEq.symm (h : a ≅ b) : b ≅ a := HEq.ndrecOn (motive := fun x => x ≅ a) h (HEq.refl a) theorem heqOfEq (h : a = a') : a ≅ a' := Eq.subst h (HEq.refl a) theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c := HEq.subst h₂ h₁ theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' := HEq.trans h₁ (heqOfEq h₂) theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := HEq.trans (heqOfEq h₁) h₂ def typeEqOfHEq (h : a ≅ b) : α = β := HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (Eq.refl α) end theorem eqRecHEq {α : Sort u} {φ : α → Sort v} : {a a' : α} → (h : a = a') → (p : φ a) → (Eq.recOn (motive := fun x _ => φ x) h p) ≅ p | a, _, rfl, p => HEq.refl p theorem heqOfEqRecEq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : a ≅ b := by subst h₁ apply heqOfEq exact h₂ done theorem castHEq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a | α, _, rfl, a => HEq.refl a variables {a b c d : Prop} theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (fun h => h) (fun h => h) theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (fun ha => Iff.mp h₂ (Iff.mp h₁ ha)) (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.mpr h) (Iff.mp h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := h₂ h₁.1 h₁.2 /- Decidable -/ theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true := match h with | isTrue h => rfl | isFalse h => False.elim <| h ⟨⟩ theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false := match h with | isFalse h => rfl | isTrue h => False.elim h /-- Similar to `decide`, but uses an explicit instance -/ @[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool := @decide p d theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true := @decideEqTrue _ d h theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p := @ofDecideEqTrue _ d h theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p := @ofDecideEqFalse _ d h instance : Decidable True := isTrue trivial instance : Decidable False := isFalse notFalse namespace Decidable variables {p q : Prop} @[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match dec with | isTrue h => h1 h | isFalse h => h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p := byCases id (fun np => False.elim (h np)) theorem ofNotNot [Decidable p] : ¬ ¬ p → p := fun hnn => byContradiction (fun hn => absurd hn hnn) theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (fun h => match d₁, d₂ with | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h | _, isFalse h₂ => Or.inr h₂ | isFalse h₁, _ => Or.inl h₁) (fun (h) ⟨hp, hq⟩ => match h with | Or.inl h => h hp | Or.inr h => h hq) end Decidable section variables {p q : Prop} @[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse fun hq => absurd (Iff.mpr h hq) hp @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := h ▸ hp end @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun h => hq) else isFalse (fun h => absurd (h hp) hq) else isTrue (fun h => absurd h hp) instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩ else isFalse fun h => hq (h.1 hp) else if hq : q then isFalse fun h => hp (h.2 hq) else isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩ /- if-then-else expression theorems -/ theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e := match h with | (isTrue hc) => rfl | (isFalse hnc) => rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | (isTrue hc) => dT | (isFalse hc) => dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | (isTrue hc) => dT hc | (isFalse hc) => dE hc /- Inhabited -/ instance : Inhabited Prop where default := True instance : Inhabited Bool where default := false instance : Inhabited True where default := trivial instance : Inhabited NonScalar where default := ⟨arbitrary⟩ instance : Inhabited PNonScalar.{u} where default := ⟨arbitrary⟩ instance {α} [Inhabited α] : Inhabited (ForInStep α) where default := ForInStep.done (arbitrary) class inductive Nonempty (α : Sort u) : Prop := | intro (val : α) : Nonempty α protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := h₂ h₁.1 instance {α : Sort u} [Inhabited α] : Nonempty α where val := arbitrary theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, h⟩ => ⟨w⟩ /- Subsingleton -/ class inductive Subsingleton (α : Sort u) : Prop := | intro (h : (a b : α) → a = b) : Subsingleton α protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b := match h with | intro h => h protected def Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : a ≅ b := by subst h₂ apply heqOfEq apply Subsingleton.elim instance (p : Prop) : Subsingleton p := ⟨fun a b => proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro fun | (isTrue t₁) => fun | (isTrue t₂) => proofIrrel t₁ t₂ ▸ rfl | (isFalse f₂) => absurd t₁ f₂ | (isFalse f₁) => fun | (isTrue t₂) => absurd t₂ f₁ | (isFalse f₂) => proofIrrel f₁ f₂ ▸ rfl theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)] : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h₂ h₁) := match h with | (isTrue h) => h₃ h | (isFalse h) => h₄ h structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop := (refl : ∀ x, r x x) (symm : ∀ {x y}, r x y → r y x) (trans : ∀ {x y z}, r x y → r y z → r x z) def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop := False def Subrelation {α : Sort u} (q r : α → α → Prop) := ∀ {x y}, q x y → r x y def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop := | base : ∀ a b, r a b → TC r a b | trans : ∀ a b c, TC r a b → TC r b c → TC r a c /- Subtype -/ namespace Subtype def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x) | ⟨a, h⟩ => ⟨a, h⟩ variables {α : Type u} {p : α → Prop} protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨x, h1⟩, ⟨_, _⟩, rfl => rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by cases a exact rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where default := ⟨a, h⟩ instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := fun ⟨a, h₁⟩ ⟨b, h₂⟩ => if h : a = b then isTrue (by subst h; exact rfl) else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h)) end Subtype /- Sum -/ section variables {α : Type u} {β : Type v} instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) where default := Sum.inl arbitrary instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) where default := Sum.inr arbitrary instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b => match a, b with | (Sum.inl a), (Sum.inl b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inr b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inl b) => isFalse (fun h => Sum.noConfusion h) | (Sum.inl a), (Sum.inr b) => isFalse (fun h => Sum.noConfusion h) end /- Product -/ section variables {α : Type u} {β : Type v} instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where default := (arbitrary, arbitrary) instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := fun ⟨a, b⟩ ⟨a', b'⟩ => match (decEq a a') with | (isTrue e₁) => match (decEq b b') with | (isTrue e₂) => isTrue (e₁ ▸ e₂ ▸ rfl) | (isFalse n₂) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₂' n₂)) | (isFalse n₁) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₁' n₁)) instance [BEq α] [BEq β] : BEq (α × β) where beq := fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => a₁ == a₂ && b₁ == b₂ instance [HasLess α] [HasLess β] : HasLess (α × β) where Less s t := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2) instance prodHasDecidableLt [HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β] [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)] : (s t : α × β) → Decidable (s < t) := fun t s => inferInstanceAs (Decidable (_ ∨ _)) theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl end def Prod.map.{u₁, u₂, v₁, v₂} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) => (f a, g b) /- Dependent products -/ theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x) | ⟨x, hx⟩ => ⟨x, hx⟩ protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} (h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by subst h₁ subst h₂ exact rfl /- Universe polymorphic unit -/ theorem punitEq (a b : PUnit) : a = b := by cases a; cases b; exact rfl theorem punitEqPUnit (a : PUnit) : a = () := punitEq a () instance : Subsingleton PUnit := Subsingleton.intro punitEq instance : Inhabited PUnit where default := ⟨⟩ instance : DecidableEq PUnit := fun a b => isTrue (punitEq a b) /- Setoid -/ class Setoid (α : Sort u) := (r : α → α → Prop) (iseqv {} : Equivalence r) instance {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variables {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := (Setoid.iseqv α).refl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := (Setoid.iseqv α).symm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := (Setoid.iseqv α).trans hab hbc end Setoid /- Propositional extensionality -/ axiom propext {a b : Prop} : (a ↔ b) → a = b /- Quotients -/ -- Iff can now be used to do substitutions in a calculation theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : (a b : α) → r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (p : (a : α) → motive (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a := rfl protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β := lift f c q protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (q : Quot r) (h : (a : α) → motive (Quot.mk r a)) : motive q := ind h q theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) := Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {motive : Quot r → Sort v} @[reducible, macroInline] protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : (a b : α) → r a b → Quot.indep f a = Quot.indep f b := fun a b e => PSigma.eta (sound e) (h a b e) protected theorem liftIndepPr1 (f : (a : α) → motive (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by induction q using Quot.ind exact rfl protected abbrev rec (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : motive q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) protected abbrev recOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : motive q := Quot.rec f h q protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quot.mk r a))] (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) : motive q := by induction q using Quot.rec apply f apply Subsingleton.elim protected abbrev hrecOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (c : (a b : α) → (p : r a b) → f a ≅ f b) : motive q := Quot.recOn q f fun a b p => eqOfHEq <| have p₁ : Eq.ndrec (f a) (sound p) ≅ f a := eqRecHEq (sound p) (f a) HEq.trans p₁ (c a b p) end end Quot def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b := Quot.sound protected abbrev lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β := Quot.lift f protected theorem ind {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk a)) → (q : Quot Setoid.r) → motive q := Quot.ind protected abbrev liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β := Quot.liftOn q f c protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} (q : Quotient s) (h : (a : α) → motive (Quotient.mk a)) : motive q := Quot.inductionOn q h theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) := Quot.existsRep q section variable {α : Sort u} variable [s : Setoid α] variable {motive : Quotient s → Sort v} @[inline] protected def rec (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) (q : Quotient s) : motive q := Quot.rec f h q protected abbrev recOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) : motive q := Quot.recOn q f h protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quotient.mk a))] (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) : motive q := Quot.recOnSubsingleton (h := h) q f protected abbrev hrecOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (c : (a b : α) → (p : a ≈ b) → f a ≅ f b) : motive q := Quot.hrecOn q f c end section universes uA uB uC variables {α : Sort uA} {β : Sort uB} {φ : Sort uC} variables [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev lift₂ (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := by apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁ intros induction q₂ using Quotient.ind apply c; assumption; apply Setoid.refl protected abbrev liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) : φ := Quotient.lift₂ f c q₁ q₂ protected theorem ind₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₃ [s₃ : Setoid φ] {motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c)) : motive q₁ q₂ q₃ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind induction q₃ using Quotient.ind apply h end section Exact variable {α : Sort u} private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (fun a₁ a₂ => a₁ ≈ a₂) (fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ => propext (Iff.intro (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl [s : Setoid α] (q : Quotient s) : rel q q := Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a) private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := fun h => Eq.ndrecOn h (rel.refl q₁) theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b := fun h => eqImpRel h end Exact section universes uA uB uC variables {α : Sort uA} {β : Sort uB} variables [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev recOnSubsingleton₂ {motive : Quotient s₁ → Quotient s₂ → Sort uC} [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quot.recOnSubsingleton induction q₂ using Quot.recOnSubsingleton intro a; apply s induction q₂ using Quot.recOnSubsingleton intro a; apply s apply g end end Quotient section variable {α : Type u} variable (r : α → α → Prop) instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) := fun (q₁ q₂ : Quotient s) => Quotient.recOnSubsingleton₂ (motive := fun a b => Decidable (a = b)) q₁ q₂ (fun a₁ a₂ => match (d a₁ a₂) with | (isTrue h₁) => isTrue (Quotient.sound h₁) | (isFalse h₂) => isFalse (fun h => absurd (Quotient.exact h) h₂)) /- Function extensionality -/ namespace Function variables {α : Sort u} {β : α → Sort v} def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f := fun x => rfl protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ := fun h x => Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ := fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := { refl := Equiv.refl, symm := Equiv.symm, trans := Equiv.trans } end Function section open Quotient variables {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient <| funSetoid α β) (x : α) : β x := Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun f₁ f₂ h => h x) theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) apply congrArg apply Quotient.sound exact h end instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) := ⟨fun f₁ f₂ => funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))⟩ /- Squash -/ def Squash (α : Type u) := Quot (fun (a b : α) => True) def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q := Quot.ind h @[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β := Quot.lift f (fun a b _ => Subsingleton.elim _ _) s instance {α} : Subsingleton (Squash α) := ⟨fun a b => Squash.ind (motive := fun a => a = b) (fun a => Squash.ind (motive := fun b => Squash.mk a = b) (fun b => show Quot.mk _ a = Quot.mk _ b by apply Quot.sound; exact trivial) b) a⟩ namespace Lean /- Kernel reduction hints -/ /-- When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`. The kernel will not use the interpreter if `c` is not a constant. This feature is useful for performing proofs by reflection. Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with `Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your developement using external checkers. Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations. If an extern function is executed, then the trusted code base will also include the implementation of the associated foreign function. -/ constant reduceBool (b : Bool) : Bool := b /-- Similar to `Lean.reduceBool` for closed `Nat` terms. Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`. The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression. We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/ constant reduceNat (n : Nat) : Nat := n axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b end Lean
d942db6d4bbe5efc2b9a19babf06ddf356ac0c2a
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Data/Lsp/Diagnostics.lean
0e42e756966a1a57d16075357820120aba98b23c
[ "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
5,080
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic import Lean.Data.Lsp.Utf16 import Lean.Message /-! Definitions and functionality for emitting diagnostic information such as errors, warnings and #command outputs from the LSP server. -/ namespace Lean namespace Lsp open Json inductive DiagnosticSeverity | error | warning | information | hint instance DiagnosticSeverity.hasFromJson : HasFromJson DiagnosticSeverity := ⟨fun j => match j.getNat? with | some 1 => DiagnosticSeverity.error | some 2 => DiagnosticSeverity.warning | some 3 => DiagnosticSeverity.information | some 4 => DiagnosticSeverity.hint | _ => none⟩ instance DiagnosticSeverity.hasToJson : HasToJson DiagnosticSeverity := ⟨fun o => match o with | DiagnosticSeverity.error => (1 : Nat) | DiagnosticSeverity.warning => (2 : Nat) | DiagnosticSeverity.information => (3 : Nat) | DiagnosticSeverity.hint => (4 : Nat)⟩ inductive DiagnosticCode | int (i : Int) | string (s : String) instance DiagnosticCode.hasFromJson : HasFromJson DiagnosticCode := ⟨fun j => match j with | num (i : Int) => DiagnosticCode.int i | str s => DiagnosticCode.string s | _ => none⟩ instance DiagnosticCode.hasToJson : HasToJson DiagnosticCode := ⟨fun o => match o with | DiagnosticCode.int i => i | DiagnosticCode.string s => s⟩ inductive DiagnosticTag | unnecessary | deprecated instance DiagnosticTag.hasFromJson : HasFromJson DiagnosticTag := ⟨fun j => match j.getNat? with | some 1 => DiagnosticTag.unnecessary | some 2 => DiagnosticTag.deprecated | _ => none⟩ instance DiagnosticTag.hasToJson : HasToJson DiagnosticTag := ⟨fun o => match o with | DiagnosticTag.unnecessary => (1 : Nat) | DiagnosticTag.deprecated => (2 : Nat)⟩ structure DiagnosticRelatedInformation := (location : Location) (message : String) instance DiagnosticRelatedInformation.hasFromJson : HasFromJson DiagnosticRelatedInformation := ⟨fun j => do location ← j.getObjValAs? Location "location"; message ← j.getObjValAs? String "message"; pure ⟨location, message⟩⟩ instance DiagnosticRelatedInformation.hasToJson : HasToJson DiagnosticRelatedInformation := ⟨fun o => mkObj [ ⟨"location", toJson o.location⟩, ⟨"message", o.message⟩]⟩ structure Diagnostic := (range : Range) (severity? : Option DiagnosticSeverity := none) (code? : Option DiagnosticCode := none) (source? : Option String := none) (message : String) (tags? : Option (Array DiagnosticTag) := none) (relatedInformation? : Option (Array DiagnosticRelatedInformation) := none) instance Diagnostic.hasFromJson : HasFromJson Diagnostic := ⟨fun j => do range ← j.getObjValAs? Range "range"; let severity? := j.getObjValAs? DiagnosticSeverity "severity"; let code? := j.getObjValAs? DiagnosticCode "code"; let source? := j.getObjValAs? String "source"; message ← j.getObjValAs? String "message"; let tags? := j.getObjValAs? (Array DiagnosticTag) "tags"; let relatedInformation? := j.getObjValAs? (Array DiagnosticRelatedInformation) "relatedInformation"; pure ⟨range, severity?, code?, source?, message, tags?, relatedInformation?⟩⟩ instance Diagnostic.hasToJson : HasToJson Diagnostic := ⟨fun o => mkObj $ opt "severity" o.severity? ++ opt "code" o.code? ++ opt "source" o.source? ++ opt "tags" o.tags? ++ opt "relatedInformation" o.relatedInformation? ++ [ ⟨"range", toJson o.range⟩, ⟨"message", o.message⟩]⟩ structure PublishDiagnosticsParams := (uri : DocumentUri) (version? : Option Int := none) (diagnostics: Array Diagnostic) instance PublishDiagnosticsParams.hasFromJson : HasFromJson PublishDiagnosticsParams := ⟨fun j => do uri ← j.getObjValAs? DocumentUri "uri"; let version? := j.getObjValAs? Int "version"; diagnostics ← j.getObjValAs? (Array Diagnostic) "diagnostics"; pure ⟨uri, version?, diagnostics⟩⟩ instance PublishDiagnosticsParams.hasToJson : HasToJson PublishDiagnosticsParams := ⟨fun o => mkObj $ opt "version" o.version? ++ [ ⟨"uri", toJson o.uri⟩, ⟨"diagnostics", toJson o.diagnostics⟩]⟩ /-- Transform a Lean Message concerning the given text into an LSP Diagnostic. -/ def msgToDiagnostic (text : FileMap) (m : Message) : IO Diagnostic := do let low : Lsp.Position := text.leanPosToLspPos m.pos; let high : Lsp.Position := match m.endPos with | some endPos => text.leanPosToLspPos endPos | none => low; let range : Range := ⟨low, high⟩; let severity := match m.severity with | MessageSeverity.information => DiagnosticSeverity.information | MessageSeverity.warning => DiagnosticSeverity.warning | MessageSeverity.error => DiagnosticSeverity.error; let source := "Lean 4 server"; message ← m.data.toString; pure { range := range, severity? := severity, source? := source, message := message, } end Lsp end Lean
19f6678d3a607c3d485e5ba4ddca846f101652e2
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex27.lean
01dcfaf46ad8c000259f1e68ad63b2deae544f9e
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
219
lean
variables A B : Type variable a : A variable b : B check @id -- Π {A : Type u_1}, A → A check @id A -- A → A check @id B -- B → B check @id A a -- A check @id B b -- B check id check id a
fac6b60a532bd1132dd1094999fba4c9523686f5
7cef822f3b952965621309e88eadf618da0c8ae9
/src/field_theory/mv_polynomial.lean
9c4f6df95e4ce460dbbeb18e066bd50b1f386f89
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
9,389
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Multivariate functions of the form `α^n → α` are isomorphic to multivariate polynomials in `n` variables. -/ import linear_algebra.finsupp_vector_space field_theory.finite data.mv_polynomial noncomputable theory open_locale classical open lattice set linear_map submodule namespace mv_polynomial universes u v variables {σ : Type u} {α : Type v} instance [discrete_field α] : vector_space α (mv_polynomial σ α) := finsupp.vector_space _ _ section variables (σ α) [discrete_field α] (m : ℕ) def restrict_total_degree : submodule α (mv_polynomial σ α) := finsupp.supported _ _ {n | n.sum (λn e, e) ≤ m } lemma mem_restrict_total_degree (p : mv_polynomial σ α) : p ∈ restrict_total_degree σ α m ↔ p.total_degree ≤ m := begin rw [total_degree, finset.sup_le_iff], refl end end section variables (σ α) def restrict_degree (m : ℕ) [discrete_field α] : submodule α (mv_polynomial σ α) := finsupp.supported _ _ {n | ∀i, n i ≤ m } end lemma mem_restrict_degree [discrete_field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) := begin rw [restrict_degree, finsupp.mem_supported], refl end lemma mem_restrict_degree_iff_sup [discrete_field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ ∀i, p.degrees.count i ≤ n := begin simp only [mem_restrict_degree, degrees, multiset.count_sup, finsupp.count_to_multiset, finset.sup_le_iff], exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩ end lemma map_range_eq_map {β : Type*} [comm_ring α] [comm_ring β] (p : mv_polynomial σ α) (f : α → β) [is_semiring_hom f]: finsupp.map_range f (is_semiring_hom.map_zero f) p = p.map f := begin rw [← finsupp.sum_single p, finsupp.sum, finsupp.map_range_finset_sum, ← finset.sum_hom (map f)], { refine finset.sum_congr rfl (assume n _, _), rw [finsupp.map_range_single, ← monomial, ← monomial, map_monomial] }, apply_instance end section variables (σ α) lemma is_basis_monomials [discrete_field α] : is_basis α ((λs, (monomial s 1 : mv_polynomial σ α))) := suffices is_basis α (λ (sa : Σ _, unit), (monomial sa.1 1 : mv_polynomial σ α)), begin apply is_basis.comp this (λ (s : σ →₀ ℕ), ⟨s, punit.star⟩), split, { intros x y hxy, simpa using hxy }, { intros x, rcases x with ⟨x₁, x₂⟩, use x₁, rw punit_eq punit.star x₂ } end, begin apply finsupp.is_basis_single (λ _ _, (1 : α)), intro _, apply is_basis_singleton_one, end end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [discrete_field α] open_locale classical lemma dim_mv_polynomial : vector_space.dim α (mv_polynomial σ α) = cardinal.mk (σ →₀ ℕ) := by rw [← cardinal.lift_inj, ← (is_basis_monomials σ α).mk_eq_dim] end mv_polynomial namespace mv_polynomial variables {α : Type*} {σ : Type*} variables [discrete_field α] [fintype α] [fintype σ] def indicator (a : σ → α) : mv_polynomial σ α := finset.univ.prod (λn, 1 - (X n - C (a n))^(fintype.card α - 1)) lemma eval_indicator_apply_eq_one (a : σ → α) : eval a (indicator a) = 1 := have 0 < fintype.card α - 1, begin rw [← finite_field.card_units, fintype.card_pos_iff], exact ⟨1⟩ end, by simp only [indicator, (finset.prod_hom (eval a)).symm, eval_sub, is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] lemma eval_indicator_apply_eq_zero (a b : σ → α) (h : a ≠ b) : eval a (indicator b) = 0 := have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h, begin rcases this with ⟨i, hi⟩, simp only [indicator, (finset.prod_hom (eval a)).symm, eval_sub, is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end lemma degrees_indicator (c : σ → α) : degrees (indicator c) ≤ finset.univ.sum (λs:σ, add_monoid.smul (fintype.card α - 1) {s}) := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (add_monoid.smul_le_smul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X _ end set_option class.instance_max_depth 50 lemma indicator_mem_restrict_degree (c : σ → α) : indicator c ∈ restrict_degree σ α (fintype.card α - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), rw [← finset.sum_hom (multiset.count n)], simp only [is_add_monoid_hom.map_smul (multiset.count n), multiset.singleton_eq_singleton, add_monoid.smul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_cons_self, multiset.count_zero, mul_one] } end section variables (α σ) def evalₗ : mv_polynomial σ α →ₗ[α] (σ → α) → α := ⟨ λp e, p.eval e, assume p q, funext $ assume e, eval_add, assume a p, funext $ assume e, by rw [smul_eq_C_mul, eval_mul, eval_C]; refl ⟩ end section lemma evalₗ_apply (p : mv_polynomial σ α) (e : σ → α) : evalₗ α σ p e = p.eval e := rfl end lemma map_restrict_dom_evalₗ : (restrict_degree σ α (fintype.card α - 1)).map (evalₗ α σ) = ⊤ := begin refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _), refine ⟨finset.univ.sum (λn:σ → α, e n • indicator n), _, _⟩, { exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @pi.finset_sum_apply (σ → α) (λ_, α) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n _ _, { assume b _ h, rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { assume h, exact (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [fintype σ] [discrete_field α] [fintype α] @[derive [add_comm_group, vector_space α]] def R : Type u := restrict_degree σ α (fintype.card α - 1) noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := by simp only [set.mem_set_of_eq]; apply_instance set_option class.instance_max_depth 60 lemma dim_R : vector_space.dim α (R σ α) = fintype.card (σ → α) := calc vector_space.dim α (R σ α) = vector_space.dim α (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} →₀ α) : linear_equiv.dim_eq (finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card α - 1 }) ... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} : by rw [finsupp.dim_eq, dim_of_field, mul_one] ... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card α } : begin refine quotient.sound ⟨equiv.subtype_congr finsupp.equiv_fun_on_fintype $ assume f, _⟩, refine forall_congr (assume n, nat.le_sub_right_iff_add_le _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = cardinal.mk (σ → {n // n < fintype.card α}) : quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card α)⟩ ... = cardinal.mk (σ → fin (fintype.card α)) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩ ... = cardinal.mk (σ → α) : begin refine (trunc.induction_on (fintype.equiv_fin α) $ assume (e : α ≃ fin (fintype.card α)), _), refine quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) e.symm⟩ end ... = fintype.card (σ → α) : cardinal.fintype_card _ def evalᵢ : R σ α →ₗ[α] (σ → α) → α := ((evalₗ α σ).comp (restrict_degree σ α (fintype.card α - 1)).subtype) lemma range_evalᵢ : (evalᵢ σ α).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ : (evalᵢ σ α).ker = ⊥ := begin refine injective_of_surjective _ _ _ (range_evalᵢ _ _), { rw [dim_R], exact cardinal.nat_lt_omega _ }, { rw [dim_R, dim_fun, dim_of_field, mul_one] } end lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ α) (h : ∀v:σ → α, p.eval v = 0) (hp : p ∈ restrict_degree σ α (fintype.card α - 1)) : p = 0 := let p' : R σ α := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ α).ker := by rw [mem_ker]; ext v; exact h v, show p'.1 = (0 : R σ α).1, begin rw [ker_evalₗ, mem_bot] at this, rw [this] end end mv_polynomial
b6eb3b1ea558db932af3192e8fe8d3fd6ab92a54
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/topology/sheaves/sheaf_condition/pairwise_intersections.lean
3e0e6ce5611db1f426b129e17693b5883b1e9280
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
12,851
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.sheaf import category_theory.limits.preserves.basic import category_theory.category.pairwise /-! # Equivalent formulations of the sheaf condition We give an equivalent formulation of the sheaf condition. Given any indexed type `ι`, we define `overlap ι`, a category with objects corresponding to * individual open sets, `single i`, and * intersections of pairs of open sets, `pair i j`, with morphisms from `pair i j` to both `single i` and `single j`. Any open cover `U : ι → opens X` provides a functor `diagram U : overlap ι ⥤ (opens X)ᵒᵖ`. There is a canonical cone over this functor, `cone U`, whose cone point is `supr U`, and in fact this is a limit cone. A presheaf `F : presheaf C X` is a sheaf precisely if it preserves this limit. We express this in two equivalent ways, as * `is_limit (F.map_cone (cone U))`, or * `preserves_limit (diagram U) F` -/ noncomputable theory universes v u open topological_space open Top open opposite open category_theory open category_theory.limits namespace Top.presheaf variables {X : Top.{v}} variables {C : Type u} [category.{v} C] /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `sheaf_condition_equiv_sheaf_condition_pairwise_intersections`). A presheaf is a sheaf if `F` sends the cone `(pairwise.cocone U).op` to a limit cone. (Recall `pairwise.cocone U`, has cone point `supr U`, mapping down to the `U i` and the `U i ⊓ U j`.) -/ @[derive subsingleton, nolint has_inhabited_instance] def sheaf_condition_pairwise_intersections (F : presheaf C X) : Type (max u (v+1)) := Π ⦃ι : Type v⦄ (U : ι → opens X), is_limit (F.map_cone (pairwise.cocone U).op) /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `sheaf_condition_equiv_sheaf_condition_preserves_limit_pairwise_intersections`). A presheaf is a sheaf if `F` preserves the limit of `pairwise.diagram U`. (Recall `pairwise.diagram U` is the diagram consisting of the pairwise intersections `U i ⊓ U j` mapping into the open sets `U i`. This diagram has limit `supr U`.) -/ @[derive subsingleton, nolint has_inhabited_instance] def sheaf_condition_preserves_limit_pairwise_intersections (F : presheaf C X) : Type (max u (v+1)) := Π ⦃ι : Type v⦄ (U : ι → opens X), preserves_limit (pairwise.diagram U).op F /-! The remainder of this file shows that these conditions are equivalent to the usual sheaf condition. -/ variables [has_products C] namespace sheaf_condition_pairwise_intersections open category_theory.pairwise category_theory.pairwise.hom open sheaf_condition_equalizer_products /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor_obj (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : limits.cone ((diagram U).op ⋙ F)) : limits.cone (sheaf_condition_equalizer_products.diagram F U) := { X := c.X, π := { app := λ Z, walking_parallel_pair.cases_on Z (pi.lift (λ (i : ι), c.π.app (op (single i)))) (pi.lift (λ (b : ι × ι), c.π.app (op (pair b.1 b.2)))), naturality' := λ Y Z f, begin cases Y; cases Z; cases f, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.left_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (has_hom.hom.op (hom.left i j)), dsimp at h, simpa using h, }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.right_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (has_hom.hom.op (hom.right i j)), dsimp at h, simpa using h, }, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, end, }, } section local attribute [tidy] tactic.case_bash /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) : limits.cone ((diagram U).op ⋙ F) ⥤ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { obj := λ c, cone_equiv_functor_obj F U c, map := λ c c' f, { hom := f.hom, }, }. end /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse_obj (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : limits.cone (sheaf_condition_equalizer_products.diagram F U)) : limits.cone ((diagram U).op ⋙ F) := { X := c.X, π := { app := begin intro x, op_induction x, rcases x with (⟨i⟩|⟨i,j⟩), { exact c.π.app (walking_parallel_pair.zero) ≫ pi.π _ i, }, { exact c.π.app (walking_parallel_pair.one) ≫ pi.π _ (i, j), } end, naturality' := begin -- Unfortunately `op_induction` isn't up to the task here, and we need to use `generalize`. intros x y f, have ex : x = op (unop x) := rfl, have ey : y = op (unop y) := rfl, revert ex ey, generalize : unop x = x', generalize : unop y = y', rintro rfl rfl, have ef : f = f.unop.op := rfl, revert ef, generalize : f.unop = f', rintro rfl, rcases x' with ⟨i⟩|⟨⟩; rcases y' with ⟨⟩|⟨j,j⟩; rcases f' with ⟨⟩, { dsimp, erw [F.map_id], simp, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.left), dsimp [sheaf_condition_equalizer_products.left_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (i, j), rw h', simp, refl, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.right), dsimp [sheaf_condition_equalizer_products.right_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (j, i), rw h', simp, refl, }, { dsimp, erw [F.map_id], simp, }, end, }, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) : limits.cone (sheaf_condition_equalizer_products.diagram F U) ⥤ limits.cone ((diagram U).op ⋙ F) := { obj := λ c, cone_equiv_inverse_obj F U c, map := λ c c' f, { hom := f.hom, w' := begin intro x, op_induction x, rcases x with (⟨i⟩|⟨i,j⟩), { dsimp, rw [←(f.w walking_parallel_pair.zero), category.assoc], }, { dsimp, rw [←(f.w walking_parallel_pair.one), category.assoc], }, end }, }. /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso_app (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X) (c : cone ((diagram U).op ⋙ F)) : (𝟭 (cone ((diagram U).op ⋙ F))).obj c ≅ (cone_equiv_functor F U ⋙ cone_equiv_inverse F U).obj c := { hom := { hom := 𝟙 _, w' := λ j, begin op_induction j, rcases j; tidy, end, }, inv := { hom := 𝟙 _, w' := λ j, begin op_induction j, rcases j; tidy, end }} /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : 𝟭 (limits.cone ((diagram U).op ⋙ F)) ≅ cone_equiv_functor F U ⋙ cone_equiv_inverse F U := nat_iso.of_components (cone_equiv_unit_iso_app F U) (by tidy) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_counit_iso (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : cone_equiv_inverse F U ⋙ cone_equiv_functor F U ≅ 𝟭 (limits.cone (sheaf_condition_equalizer_products.diagram F U)) := nat_iso.of_components (λ c, { hom := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext, dsimp, simp, }, { ext ⟨i,j⟩, dsimp, simp, }, end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext, dsimp, simp, }, { ext ⟨i,j⟩, dsimp, simp, }, end, }}) (by tidy) /-- Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram. -/ @[simps] def cone_equiv (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) : limits.cone ((diagram U).op ⋙ F) ≌ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { functor := cone_equiv_functor F U, inverse := cone_equiv_inverse F U, unit_iso := cone_equiv_unit_iso F U, counit_iso := cone_equiv_counit_iso F U, } local attribute [reducible] sheaf_condition_equalizer_products.res sheaf_condition_equalizer_products.left_res /-- If `sheaf_condition_equalizer_products.fork` is an equalizer, then `F.map_cone (cone U)` is a limit cone. -/ def is_limit_map_cone_of_is_limit_sheaf_condition_fork (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) (P : is_limit (sheaf_condition_equalizer_products.fork F U)) : is_limit (F.map_cone (cocone U).op) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U).symm).symm P) { hom := { hom := 𝟙 _, w' := begin intro x, op_induction x, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin intro x, op_induction x, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, } /-- If `F.map_cone (cone U)` is a limit cone, then `sheaf_condition_equalizer_products.fork` is an equalizer. -/ def is_limit_sheaf_condition_fork_of_is_limit_map_cone (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) (Q : is_limit (F.map_cone (cocone U).op)) : is_limit (sheaf_condition_equalizer_products.fork F U) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U)).symm Q) { hom := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, } end sheaf_condition_pairwise_intersections open sheaf_condition_pairwise_intersections /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`. -/ def sheaf_condition_equiv_sheaf_condition_pairwise_intersections (F : presheaf C X) : F.sheaf_condition ≃ F.sheaf_condition_pairwise_intersections := equiv.Pi_congr_right (λ i, equiv.Pi_congr_right (λ U, equiv_of_subsingleton_of_subsingleton (is_limit_map_cone_of_is_limit_sheaf_condition_fork F U) (is_limit_sheaf_condition_fork_of_is_limit_map_cone F U))) /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of the presheaf preserving the limit of the diagram consisting of the `U i` and `U i ⊓ U j`. -/ def sheaf_condition_equiv_sheaf_condition_preserves_limit_pairwise_intersections (F : presheaf C X) : F.sheaf_condition ≃ F.sheaf_condition_preserves_limit_pairwise_intersections := equiv.trans (sheaf_condition_equiv_sheaf_condition_pairwise_intersections F) (equiv.Pi_congr_right (λ i, equiv.Pi_congr_right (λ U, equiv_of_subsingleton_of_subsingleton (λ P, preserves_limit_of_preserves_limit_cone (pairwise.cocone_is_colimit U).op P) (by { introI, exact preserves_limit.preserves (pairwise.cocone_is_colimit U).op })))) end Top.presheaf
1cdab74b2f9a091a699366925896bd2de056ba8e
0c1546a496eccfb56620165cad015f88d56190c5
/tests/lean/run/my_tac_class.lean
1f230427200b3e945dc2457e56d4e963ef899926
[ "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,632
lean
meta def mytac := state_t nat tactic meta instance : monad mytac := state_t.monad _ _ meta instance : monad.has_monad_lift tactic mytac := monad.monad_transformer_lift (state_t nat) tactic meta instance (α : Type) : has_coe (tactic α) (mytac α) := ⟨monad.monad_lift⟩ namespace mytac meta def step {α : Type} (t : mytac α) : mytac unit := t >> return () meta def rstep {α : Type} (line : nat) (col : nat) (t : mytac α) : mytac unit := λ v s, tactic_result.cases_on (@scope_trace _ line col (t v s)) (λ ⟨a, v⟩ new_s, tactic_result.success ((), v) new_s) (λ msg_thunk e new_s, let msg := msg_thunk () ++ format.line ++ to_fmt "value: " ++ to_fmt v ++ format.line ++ to_fmt "state:" ++ format.line ++ new_s^.to_format in (tactic.report_error line col msg >> tactic.failed) new_s) meta def execute (tac : mytac unit) : tactic unit := tac 0 >> return () meta def save_info (line col : nat) : mytac unit := do v ← state_t.read, s ← tactic.read, tactic.save_info_thunk line col (λ _, to_fmt "Custom state: " ++ to_fmt v ++ format.line ++ tactic_state.to_format s) namespace interactive meta def intros : mytac unit := tactic.intros >> return () meta def constructor : mytac unit := tactic.constructor meta def trace (s : string) : mytac unit := tactic.trace s meta def assumption : mytac unit := tactic.assumption meta def inc : mytac unit := do v ← state_t.read, state_t.write (v+1) end interactive end mytac example (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, inc, trace "test", constructor, inc, assumption, assumption end
683878f0b18d1e4332d5f55c6f20a5e50913b10e
9028d228ac200bbefe3a711342514dd4e4458bff
/src/topology/category/Compactum.lean
f3c248c0c9f5f054d1b0dd01ea6b14639c2695de
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,248
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.types import category_theory.monad.limits import category_theory.equivalence import topology.category.CompHaus import data.set.constructions /-! # Compacta and Compact Hausdorff Spaces Recall that, given a monad `M` on `Type*`, an *algebra* for `M` consists of the following data: - A type `X : Type*` - A "structure" map `M X → X`. This data must also satisfy a distributivity and unit axiom, and algebras for `M` form a category in an evident way. See the file `category_theory.monad.algebra` for a general version, as well as the following link. https://ncatlab.org/nlab/show/monad This file proves the equivalence between the category of *compact Hausdorff topological spaces* and the category of algebras for the *ultrafilter monad*. ## Notation: Here are the main objects introduced in this file. - `Compactum` is the type of compacta, which we define as algebras for the ultrafilter monad. - `Compactum_to_CompHaus` is the functor `Compactum ⥤ CompHaus`. Here `CompHaus` is the usual category of compact Hausdorff spaces. - `Compactum_to_CompHaus.is_equivalence` is a term of type `is_equivalence Compactum_to_CompHaus`. The proof of this equivalence is a bit technical. But the idea is quite simply that the structure map `ultrafilter X → X` for an algebra `X` of the ultrafilter monad should be considered as the map sending an ultrafilter to its limit in `X`. The topology on `X` is then defined by mimicking the characterization of open sets in terms of ultrafilters. Any `X : Compactum` is endowed with a coercion to `Type*`, as well as the following instances: - `topological_space X`. - `compact_space X`. - `t2_space X`. Any morphism `f : X ⟶ Y` of is endowed with a coercion to a function `X → Y`, which is shown to be continuous in `continuous_of_hom`. The function `Compactum.of_topological_space` can be used to construct a `Compactum` from a topological space which satisfies `compact_space` and `t2_space`. We also add wrappers around structures which already exist. Here are the main ones, all in the `Compactum` namespace: - `forget : Compactum ⥤ Type*` is the forgetful functor, which induces a `concrete_category` instance for `Compactum`. - `free : Type* ⥤ Compactum` is the left adjoint to `forget`, and the adjunction is in `adj`. - `str : ultrafilter X → X` is the structure map for `X : Compactum`. The notation `X.str` is preferred. - `join : ultrafilter (ultrafilter X) → ultrafilter X` is the monadic join for `X : Compactum`. Again, the notation `X.join` is preferred. - `incl : X → ultrafilter X` is the unit for `X : Compactum`. The notation `X.incl` is preferred. ## References - E. Manes, Algebraic Theories, Graduate Texts in Mathematics 26, Springer-Verlag, 1976. - https://ncatlab.org/nlab/show/ultrafilter -/ open category_theory filter topological_space category_theory.limits has_finite_inter open_locale classical local notation `β` := of_type_functor ultrafilter /-- The type `Compactum` of Compacta, defined as algebras for the ultrafilter monad. -/ @[derive [category, inhabited]] def Compactum := monad.algebra β namespace Compactum /-- The forgetful functor to Type* -/ @[derive [creates_limits,faithful]] def forget : Compactum ⥤ Type* := monad.forget _ /-- The "free" Compactum functor. -/ def free : Type* ⥤ Compactum := monad.free _ /-- The adjunction between `free` and `forget`. -/ def adj : free ⊣ forget := monad.adj _ -- Basic instances instance : concrete_category Compactum := { forget := forget } instance : has_coe_to_sort Compactum := ⟨Type*,forget.obj⟩ instance {X Y : Compactum} : has_coe_to_fun (X ⟶ Y) := ⟨λ f, X → Y, λ f, f.f⟩ instance : has_limits Compactum := has_limits_of_has_limits_creates_limits forget /-- The structure map for a compactum, essentially sending an ultrafilter to its limit. -/ def str (X : Compactum) : ultrafilter X → X := X.a /-- The monadic join. -/ def join (X : Compactum) : ultrafilter (ultrafilter X) → ultrafilter X := (μ_ β).app _ /-- The inclusion of `X` into `ultrafilter X`. -/ def incl (X : Compactum) : X → ultrafilter X := (η_ β).app _ @[simp] lemma str_incl (X : Compactum) (x : X) : X.str (X.incl x) = x := begin change ((η_ β).app _ ≫ X.a) _ = _, rw monad.algebra.unit, refl, end @[simp] lemma str_hom_commute (X Y : Compactum) (f : X ⟶ Y) (xs : ultrafilter X) : f (X.str xs) = Y.str (ultrafilter.map f xs) := begin change (X.a ≫ f.f) _ = _, rw ←f.h, refl, end @[simp] lemma join_distrib (X : Compactum) (uux : ultrafilter (ultrafilter X)) : X.str (X.join uux) = X.str (ultrafilter.map X.str uux) := begin change ((μ_ β).app _ ≫ X.a) _ = _, rw monad.algebra.assoc, refl, end instance {X : Compactum} : topological_space X := { is_open := { U | ∀ (F : ultrafilter X), X.str F ∈ U → U ∈ F.1 }, is_open_univ := λ _ _, filter.univ_sets _, is_open_inter := λ S T h3 h4 h5 h6, filter.inter_sets _ (h3 _ h6.1) (h4 _ h6.2), is_open_sUnion := λ S h1 F ⟨T,hT,h2⟩, filter.sets_of_superset _ (h1 T hT _ h2) (set.subset_sUnion_of_mem hT) } theorem is_closed_iff {X : Compactum} (S : set X) : is_closed S ↔ (∀ F : ultrafilter X, S ∈ F.1 → X.str F ∈ S) := begin split, { intros cond F h, by_contradiction c, specialize cond F c, cases F with F hF, rw ultrafilter_iff_compl_mem_iff_not_mem at hF, rw hF at cond, contradiction }, { intros h1 F h2, specialize h1 F, cases mem_or_compl_mem_of_ultrafilter F.2 S; finish } end instance {X : Compactum} : compact_space X := begin constructor, rw compact_iff_ultrafilter_le_nhds, intros F hF h, refine ⟨X.str ⟨F,hF⟩, by tauto, _⟩, rw le_nhds_iff, intros S h1 h2, exact h2 ⟨F,hF⟩ h1, end /-- A local definition used only in the proofs. -/ private def basic {X : Compactum} (A : set X) : set (ultrafilter X) := {F | A ∈ F.1} /-- A local definition used only in the proofs. -/ private def cl {X : Compactum} (A : set X) : set X := X.str '' (basic A) private lemma basic_inter {X : Compactum} (A B : set X) : basic (A ∩ B) = basic A ∩ basic B := begin ext G, split, { intro hG, refine ⟨_, _⟩; apply filter.sets_of_superset _ hG; intros x hx; finish }, { rintros ⟨h1,h2⟩, exact G.val.inter_sets h1 h2 } end private lemma subset_cl {X : Compactum} (A : set X) : A ⊆ cl A := λ a ha, ⟨X.incl a, ha,by simp⟩ private theorem cl_cl {X : Compactum} (A : set X) : cl (cl A) ⊆ cl A := begin rintros _ ⟨F,hF,rfl⟩, -- Notation to be used in this proof. let fsu := finset (set (ultrafilter X)), let ssu := set (set (ultrafilter X)), let ι : fsu → ssu := coe, let C0 : ssu := {Z | ∃ B ∈ F.1, X.str ⁻¹' B = Z}, let AA := {G : ultrafilter X | A ∈ G.1}, let C1 := insert AA C0, let C2 := finite_inter_closure C1, -- C0 is closed under intersections. have claim1 : ∀ B C ∈ C0, B ∩ C ∈ C0, { rintros B C ⟨Q,hQ,rfl⟩ ⟨R,hR,rfl⟩, use Q ∩ R, simp only [and_true, eq_self_iff_true, set.preimage_inter, subtype.val_eq_coe], exact inter_sets _ hQ hR }, -- All sets in C0 are nonempty. have claim2 : ∀ B ∈ C0, set.nonempty B, { rintros B ⟨Q,hQ,rfl⟩, obtain ⟨q⟩ := nonempty_of_mem_ultrafilter _ F.2 hQ, use X.incl q, simpa, }, -- The intersection of AA with every set in C0 is nonempty. have claim3 : ∀ B ∈ C0, (AA ∩ B).nonempty, { rintros B ⟨Q,hQ,rfl⟩, have : (Q ∩ cl A).nonempty, { apply nonempty_of_mem_ultrafilter _ F.2, exact F.1.inter_sets hQ hF }, rcases this with ⟨q,hq1,P,hq2,hq3⟩, refine ⟨P,hq2,_⟩, rw ←hq3 at hq1, simpa }, -- Suffices to show that the intersection of any finite subcollection of C1 is nonempty. suffices : ∀ (T : fsu), ι T ⊆ C1 → (⋂₀ ι T).nonempty, { obtain ⟨G,h1,hG⟩ := exists_ultrafilter_of_finite_inter_nonempty _ this, let GG : ultrafilter (ultrafilter X) := ⟨G, hG⟩, use X.join GG, have : ultrafilter.map X.str GG = F, { suffices : (ultrafilter.map X.str GG).1 ≤ F.1, { ext1, exact is_ultrafilter.unique F.2 (ultrafilter.map X.str GG).2.1 this }, intros S hS, refine h1 (or.inr ⟨S, by simpa⟩) }, rw [join_distrib, this], exact ⟨h1 (or.inl rfl), rfl⟩ }, -- C2 is closed under finite intersections (by construction!). have claim4 := finite_inter_closure_has_finite_inter C1, -- C0 is closed under finite intersections by claim1. have claim5 : has_finite_inter C0 := ⟨⟨set.univ, filter.univ_sets _, by simp⟩, claim1⟩, -- Every element of C2 is nonempty. have claim6 : ∀ P ∈ C2, (P : set (ultrafilter X)).nonempty, { suffices : ∀ P ∈ C2, P ∈ C0 ∨ ∃ Q ∈ C0, P = AA ∩ Q, { intros P hP, cases this P hP, { exact claim2 _ h }, { rcases h with ⟨Q, hQ, rfl⟩, exact claim3 _ hQ } }, intros P hP, exact claim5.finite_inter_closure_insert _ hP }, intros T hT, -- Suffices to show that the intersection of the T's is contained in C2. suffices : ⋂₀ ι T ∈ C2, by exact claim6 _ this, -- Finish apply claim4.finite_inter_mem, intros t ht, exact finite_inter_closure.basic (@hT t ht), end lemma is_closed_cl {X : Compactum} (A : set X) : is_closed (cl A) := begin rw is_closed_iff, intros F hF, exact cl_cl _ ⟨F, hF, rfl⟩, end lemma str_eq_of_le_nhds {X : Compactum} (F : ultrafilter X) (x : X) : F.1 ≤ nhds x → X.str F = x := begin -- Notation to be used in this proof. let fsu := finset (set (ultrafilter X)), let ssu := set (set (ultrafilter X)), let ι : fsu → ssu := coe, let T0 : ssu := { S | ∃ A ∈ F.1, S = basic A }, let AA := (X.str ⁻¹' {x}), let T1 := insert AA T0, let T2 := finite_inter_closure T1, intro cond, -- If F contains a closed set A, then x is contained in A. have claim1 : ∀ (A : set X), is_closed A → A ∈ F.1 → x ∈ A, { intros A hA h, by_contradiction, rw le_nhds_iff at cond, specialize cond Aᶜ a hA, rw ultrafilter_iff_compl_mem_iff_not_mem.mp F.2 at cond, contradiction }, -- If A ∈ F, then x ∈ cl A. have claim2 : ∀ (A : set X), A ∈ F.1 → x ∈ cl A, { intros A hA, exact claim1 (cl A) (is_closed_cl A) (F.val.sets_of_superset hA (subset_cl A)) }, -- T0 is closed under intersections. have claim3 : ∀ (S1 S2 ∈ T0), S1 ∩ S2 ∈ T0, { rintros S1 S2 ⟨S1, hS1, rfl⟩ ⟨S2, hS2, rfl⟩, exact ⟨S1 ∩ S2, F.1.inter_sets hS1 hS2, by simp [basic_inter]⟩ }, -- For every S ∈ T0, the intersection AA ∩ S is nonempty. have claim4 : ∀ (S ∈ T0), (AA ∩ S).nonempty, { rintros S ⟨S, hS, rfl⟩, rcases claim2 _ hS with ⟨G, hG, hG2⟩, exact ⟨G, hG2, hG⟩ }, -- Every element of T0 is nonempty. have claim5 : ∀ (S ∈ T0), set.nonempty S, { rintros S ⟨S, hS, rfl⟩, exact ⟨F, hS⟩ }, -- Every element of T2 is nonempty. have claim6 : ∀ (S ∈ T2), set.nonempty S, { suffices : ∀ S ∈ T2, S ∈ T0 ∨ ∃ Q ∈ T0, S = AA ∩ Q, { intros S hS, cases this _ hS with h h, { exact claim5 S h }, { rcases h with ⟨Q, hQ, rfl⟩, exact claim4 Q hQ } }, intros S hS, apply finite_inter_closure_insert, { split, { use set.univ, refine ⟨filter.univ_sets _, _⟩, ext, refine ⟨_, by tauto⟩, { intro, apply filter.univ_sets, } }, { exact claim3} }, { exact hS} }, -- It suffices to show that the intersection of any finite subset of T1 is nonempty. suffices : ∀ (F : fsu), ↑F ⊆ T1 → (⋂₀ ι F).nonempty, { obtain ⟨G,h1,hG⟩ := exists_ultrafilter_of_finite_inter_nonempty _ this, let GG : ultrafilter (ultrafilter X) := ⟨G, hG⟩, have c1 : X.join GG = F, { suffices : (X.join GG).1 ≤ F.1, { ext1, exact is_ultrafilter.unique F.2 (join X GG).2.1 this}, intros P hP, exact h1 (or.inr ⟨P, hP, rfl⟩) }, have c2 : ultrafilter.map X.str GG = X.incl x, { suffices : (ultrafilter.map X.str GG).1 ≤ (X.incl x).1, { ext1, exact is_ultrafilter.unique (incl X x).2 (ultrafilter.map (str X) GG).2.1 this }, intros P hP, apply filter.sets_of_superset _ (h1 (or.inl rfl)), rintros x ⟨rfl⟩, exact hP }, simp [←c1, c2] }, -- Finish... intros T hT, refine claim6 _ (finite_inter_mem (finite_inter_closure_has_finite_inter _) _ _), intros t ht, exact finite_inter_closure.basic (@hT t ht) end lemma le_nhds_of_str_eq {X : Compactum} (F : ultrafilter X) (x : X) : X.str F = x → F.1 ≤ nhds x := λ h, le_nhds_iff.mpr (λ s hx hs, hs _ $ by rwa h) -- All the hard work above boils down to this t2_space instance. instance {X : Compactum} : t2_space X := begin rw t2_iff_ultrafilter, intros _ _ _ hF hx hy, replace hx := str_eq_of_le_nhds ⟨_, hF⟩ _ hx, replace hy := str_eq_of_le_nhds ⟨_, hF⟩ _ hy, cc, end /-- The structure map of a compactum actually computes limits. -/ lemma Lim_eq_str {X : Compactum} (F : ultrafilter X) : F.Lim = X.str F := begin erw [is_ultrafilter.Lim_eq_iff_le_nhds, le_nhds_iff], tauto, end lemma cl_eq_closure {X : Compactum} (A : set X) : cl A = closure A := begin ext, rw mem_closure_iff_ultrafilter, split, { rintro ⟨F, h1, h2⟩, exact ⟨F, h1, le_nhds_of_str_eq _ _ h2⟩ }, { rintro ⟨F, h1, h2⟩, exact ⟨F, h1, str_eq_of_le_nhds _ _ h2⟩ } end /-- Any morphism of compacta is continuous. -/ lemma continuous_of_hom {X Y : Compactum} (f : X ⟶ Y) : continuous f := begin rw continuous_iff_ultrafilter, intros x _ h1 h2, change (ultrafilter.map f ⟨_, h1⟩).1 ≤ _, apply le_nhds_of_str_eq, rw [← str_hom_commute, str_eq_of_le_nhds ⟨_, h1⟩ x h2], end /-- Given any compact Hausdorff space, we construct a Compactum. -/ noncomputable def of_topological_space (X : Type*) [topological_space X] [compact_space X] [t2_space X] : Compactum := { A := X, a := ultrafilter.Lim, unit' := by {ext x, exact Lim_eq (by finish [le_nhds_iff]) }, assoc' := begin ext FF, change ultrafilter (ultrafilter X) at FF, set x := (ultrafilter.map ultrafilter.Lim FF).Lim with c1, have c2 : ∀ (U : set X) (F : ultrafilter X), F.Lim ∈ U → is_open U → U ∈ F.1, { intros U F h1 hU, exact c1 ▸ is_open_iff_ultrafilter.mp hU _ h1 _ F.2 (is_ultrafilter.le_nhds_Lim _) }, have c3 : (ultrafilter.map ultrafilter.Lim FF).1 ≤ nhds x, { rw le_nhds_iff, intros U hx hU, refine c2 _ _ (by rwa ← c1) hU }, have c4 : ∀ (U : set X), x ∈ U → is_open U → { G : ultrafilter X | U ∈ G.1 } ∈ FF.1, { intros U hx hU, suffices : ultrafilter.Lim ⁻¹' U ∈ FF.1, { apply filter.sets_of_superset _ this, intros P hP, exact c2 U P hP hU}, exact @c3 U (mem_nhds_sets hU hx) }, apply Lim_eq, rw le_nhds_iff, exact c4, end } /-- Any continuous map between Compacta is a morphism of compacta. -/ def hom_of_continuous {X Y : Compactum} (f : X → Y) (cont : continuous f) : X ⟶ Y := { f := f, h' := begin rw continuous_iff_ultrafilter at cont, ext (F : ultrafilter X), specialize cont (X.str F) F.1 F.2 (le_nhds_of_str_eq F (X.str F) rfl), have := str_eq_of_le_nhds (ultrafilter.map f F) _ cont, simpa only [←this, types_comp_apply, of_type_functor_map], end } end Compactum /-- The functor functor from Compactum to CompHaus. -/ def Compactum_to_CompHaus : Compactum ⥤ CompHaus := { obj := λ X, { to_Top := { α := X } }, map := λ X Y f, { to_fun := f, continuous_to_fun := Compactum.continuous_of_hom _ }} namespace Compactum_to_CompHaus /-- The functor Compactum_to_CompHaus is full. -/ def full : full Compactum_to_CompHaus := { preimage := λ X Y f, Compactum.hom_of_continuous f.1 f.2 } /-- The functor Compactum_to_CompHaus is faithful. -/ lemma faithful : faithful Compactum_to_CompHaus := {} /-- This definition is used to prove essential surjectivity of Compactum_to_CompHaus. -/ noncomputable def iso_of_topological_space {D : CompHaus} : Compactum_to_CompHaus.obj (Compactum.of_topological_space D) ≅ D := { hom := { to_fun := id, continuous_to_fun := λ _ h, by {rw is_open_iff_ultrafilter' at h, exact h} }, inv := { to_fun := id, continuous_to_fun := λ _ h1, by {rw is_open_iff_ultrafilter', intros _ h2, exact h1 _ h2} } } /-- The functor Compactum_to_CompHaus is essentially surjective. -/ noncomputable def ess_surj : ess_surj Compactum_to_CompHaus := { obj_preimage := λ X, Compactum.of_topological_space X, iso' := λ _, iso_of_topological_space } /-- The functor Compactum_to_CompHaus is an equivalence of categories. -/ noncomputable def is_equivalence : is_equivalence Compactum_to_CompHaus := begin apply equivalence.equivalence_of_fully_faithfully_ess_surj _, exact Compactum_to_CompHaus.full, exact Compactum_to_CompHaus.faithful, exact Compactum_to_CompHaus.ess_surj, end end Compactum_to_CompHaus
b0086eb07d72e5a12b32bc73fadff6af5abdad78
0c1546a496eccfb56620165cad015f88d56190c5
/library/tools/super/resolution.lean
6d8cdf7d6f528c0e2afede768a4b8947dcb6cba4
[ "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
2,294
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state .utils open tactic monad namespace super variable gt : expr → expr → bool variables (ac1 ac2 : derived_clause) variables (c1 c2 : clause) variables (i1 i2 : nat) -- c1 : ... → ¬a → ... -- c2 : ... → a → ... meta def try_resolve : tactic clause := do qf1 ← c1^.open_metan c1^.num_quants, qf2 ← c2^.open_metan c2^.num_quants, -- FIXME: using default transparency unifies m*n with (x*y*z)*w here ??? unify_core transparency.reducible (qf1.1^.get_lit i1)^.formula (qf2.1^.get_lit i2)^.formula, qf1i ← qf1.1^.inst_mvars, guard $ clause.is_maximal gt qf1i i1, op1 ← qf1.1^.open_constn i1, op2 ← qf2.1^.open_constn c2^.num_lits, a_in_op2 ← (op2.2^.nth i2)^.to_monad, clause.meta_closure (qf1.2 ++ qf2.2) $ (op1.1^.inst (op2.1^.close_const a_in_op2)^.proof)^.close_constn (op1.2 ++ op2.2^.remove_nth i2) meta def try_add_resolvent : prover unit := do c' ← try_resolve gt ac1^.c ac2^.c i1 i2, inf_score 1 [ac1^.sc, ac2^.sc] >>= mk_derived c' >>= add_inferred meta def maybe_add_resolvent : prover unit := try_add_resolvent gt ac1 ac2 i1 i2 <|> return () meta def resolution_left_inf : inference := take given, do active ← get_active, sequence' $ do given_i ← given^.selected, guard $ clause.literal.is_neg (given^.c^.get_lit given_i), other ← rb_map.values active, guard $ ¬given^.sc^.in_sos ∨ ¬other^.sc^.in_sos, other_i ← other^.selected, guard $ clause.literal.is_pos (other^.c^.get_lit other_i), [maybe_add_resolvent gt other given other_i given_i] meta def resolution_right_inf : inference := take given, do active ← get_active, sequence' $ do given_i ← given^.selected, guard $ clause.literal.is_pos (given^.c^.get_lit given_i), other ← rb_map.values active, guard $ ¬given^.sc^.in_sos ∨ ¬other^.sc^.in_sos, other_i ← other^.selected, guard $ clause.literal.is_neg (other^.c^.get_lit other_i), [maybe_add_resolvent gt given other given_i other_i] @[super.inf] meta def resolution_inf : inf_decl := inf_decl.mk 40 $ take given, do gt ← get_term_order, resolution_left_inf gt given >> resolution_right_inf gt given end super
57dcfac18c48bb72fb8568afce08e3c4f14dbf47
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/add_torsor.lean
c840681c3923a8915af8511d356c6a829ef33d29
[ "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,340
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import algebra.group.prod import algebra.group.type_tags import algebra.group.pi import algebra.pointwise import data.equiv.basic import data.set.finite /-! # Torsors of additive group actions This file defines torsors of additive group actions. ## Notations The group elements are referred to as acting on points. This file defines the notation `+ᵥ` for adding a group element to a point and `-ᵥ` for subtracting two points to produce a group element. ## Implementation notes Affine spaces are the motivating example of torsors of additive group actions. It may be appropriate to refactor in terms of the general definition of group actions, via `to_additive`, when there is a use for multiplicative torsors (currently mathlib only develops the theory of group actions for multiplicative group actions). ## Notations * `v +ᵥ p` is a notation for `has_vadd.vadd`, the left action of an additive monoid; * `p₁ -ᵥ p₂` is a notation for `has_vsub.vsub`, difference between two points in an additive torsor as an element of the corresponding additive group; ## References * https://en.wikipedia.org/wiki/Principal_homogeneous_space * https://en.wikipedia.org/wiki/Affine_space -/ /-- Type class for the `-ᵥ` notation. -/ class has_vsub (G : out_param Type*) (P : Type*) := (vsub : P → P → G) infix ` -ᵥ `:65 := has_vsub.vsub /-- An `add_torsor G P` gives a structure to the nonempty type `P`, acted on by an `add_group G` with a transitive and free action given by the `+ᵥ` operation and a corresponding subtraction given by the `-ᵥ` operation. In the case of a vector space, it is an affine space. -/ class add_torsor (G : out_param Type*) (P : Type*) [out_param $ add_group G] extends add_action G P, has_vsub G P := [nonempty : nonempty P] (vsub_vadd' : ∀ (p1 p2 : P), (p1 -ᵥ p2 : G) +ᵥ p2 = p1) (vadd_vsub' : ∀ (g : G) (p : P), g +ᵥ p -ᵥ p = g) attribute [instance, priority 100, nolint dangerous_instance] add_torsor.nonempty attribute [nolint dangerous_instance] add_torsor.to_has_vsub /-- An `add_group G` is a torsor for itself. -/ @[nolint instance_priority] instance add_group_is_add_torsor (G : Type*) [add_group G] : add_torsor G G := { vsub := has_sub.sub, vsub_vadd' := sub_add_cancel, vadd_vsub' := add_sub_cancel } /-- Simplify subtraction for a torsor for an `add_group G` over itself. -/ @[simp] lemma vsub_eq_sub {G : Type*} [add_group G] (g1 g2 : G) : g1 -ᵥ g2 = g1 - g2 := rfl section general variables {G : Type*} {P : Type*} [add_group G] [T : add_torsor G P] include T /-- Adding the result of subtracting from another point produces that point. -/ @[simp] lemma vsub_vadd (p1 p2 : P) : p1 -ᵥ p2 +ᵥ p2 = p1 := add_torsor.vsub_vadd' p1 p2 /-- Adding a group element then subtracting the original point produces that group element. -/ @[simp] lemma vadd_vsub (g : G) (p : P) : g +ᵥ p -ᵥ p = g := add_torsor.vadd_vsub' g p /-- If the same point added to two group elements produces equal results, those group elements are equal. -/ lemma vadd_right_cancel {g1 g2 : G} (p : P) (h : g1 +ᵥ p = g2 +ᵥ p) : g1 = g2 := by rw [←vadd_vsub g1, h, vadd_vsub] @[simp] lemma vadd_right_cancel_iff {g1 g2 : G} (p : P) : g1 +ᵥ p = g2 +ᵥ p ↔ g1 = g2 := ⟨vadd_right_cancel p, λ h, h ▸ rfl⟩ /-- Adding a group element to the point `p` is an injective function. -/ lemma vadd_right_injective (p : P) : function.injective ((+ᵥ p) : G → P) := λ g1 g2, vadd_right_cancel p /-- Adding a group element to a point, then subtracting another point, produces the same result as subtracting the points then adding the group element. -/ lemma vadd_vsub_assoc (g : G) (p1 p2 : P) : g +ᵥ p1 -ᵥ p2 = g + (p1 -ᵥ p2) := begin apply vadd_right_cancel p2, rw [vsub_vadd, add_vadd, vsub_vadd] end /-- Subtracting a point from itself produces 0. -/ @[simp] lemma vsub_self (p : P) : p -ᵥ p = (0 : G) := by rw [←zero_add (p -ᵥ p), ←vadd_vsub_assoc, vadd_vsub] /-- If subtracting two points produces 0, they are equal. -/ lemma eq_of_vsub_eq_zero {p1 p2 : P} (h : p1 -ᵥ p2 = (0 : G)) : p1 = p2 := by rw [←vsub_vadd p1 p2, h, zero_vadd] /-- Subtracting two points produces 0 if and only if they are equal. -/ @[simp] lemma vsub_eq_zero_iff_eq {p1 p2 : P} : p1 -ᵥ p2 = (0 : G) ↔ p1 = p2 := iff.intro eq_of_vsub_eq_zero (λ h, h ▸ vsub_self _) /-- Cancellation adding the results of two subtractions. -/ @[simp] lemma vsub_add_vsub_cancel (p1 p2 p3 : P) : p1 -ᵥ p2 + (p2 -ᵥ p3) = (p1 -ᵥ p3) := begin apply vadd_right_cancel p3, rw [add_vadd, vsub_vadd, vsub_vadd, vsub_vadd] end /-- Subtracting two points in the reverse order produces the negation of subtracting them. -/ @[simp] lemma neg_vsub_eq_vsub_rev (p1 p2 : P) : -(p1 -ᵥ p2) = (p2 -ᵥ p1) := begin refine neg_eq_of_add_eq_zero (vadd_right_cancel p1 _), rw [vsub_add_vsub_cancel, vsub_self], end /-- Subtracting the result of adding a group element produces the same result as subtracting the points and subtracting that group element. -/ lemma vsub_vadd_eq_vsub_sub (p1 p2 : P) (g : G) : p1 -ᵥ (g +ᵥ p2) = (p1 -ᵥ p2) - g := by rw [←add_right_inj (p2 -ᵥ p1 : G), vsub_add_vsub_cancel, ←neg_vsub_eq_vsub_rev, vadd_vsub, ←add_sub_assoc, ←neg_vsub_eq_vsub_rev, neg_add_self, zero_sub] /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_right (p1 p2 p3 : P) : (p1 -ᵥ p3) - (p2 -ᵥ p3) = (p1 -ᵥ p2) := by rw [←vsub_vadd_eq_vsub_sub, vsub_vadd] /-- Convert between an equality with adding a group element to a point and an equality of a subtraction of two points with a group element. -/ lemma eq_vadd_iff_vsub_eq (p1 : P) (g : G) (p2 : P) : p1 = g +ᵥ p2 ↔ p1 -ᵥ p2 = g := ⟨λ h, h.symm ▸ vadd_vsub _ _, λ h, h ▸ (vsub_vadd _ _).symm⟩ lemma vadd_eq_vadd_iff_neg_add_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} : v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ - v₁ + v₂ = p₁ -ᵥ p₂ := by rw [eq_vadd_iff_vsub_eq, vadd_vsub_assoc, ← add_right_inj (-v₁), neg_add_cancel_left, eq_comm] namespace set instance has_vsub : has_vsub (set G) (set P) := ⟨set.image2 (-ᵥ)⟩ section vsub variables (s t : set P) @[simp] lemma vsub_empty : s -ᵥ ∅ = ∅ := set.image2_empty_right @[simp] lemma empty_vsub : ∅ -ᵥ s = ∅ := set.image2_empty_left @[simp] lemma singleton_vsub (p : P) : {p} -ᵥ s = ((-ᵥ) p) '' s := image2_singleton_left @[simp] lemma vsub_singleton (p : P) : s -ᵥ {p} = (-ᵥ p) '' s := image2_singleton_right @[simp] lemma singleton_vsub_self (p : P) : ({p} : set P) -ᵥ {p} = {(0:G)} := by simp variables {s t} /-- `vsub` of a finite set is finite. -/ lemma finite.vsub (hs : finite s) (ht : finite t) : finite (s -ᵥ t) := hs.image2 _ ht /-- Each pairwise difference is in the `vsub` set. -/ lemma vsub_mem_vsub {ps pt : P} (hs : ps ∈ s) (ht : pt ∈ t) : (ps -ᵥ pt) ∈ s -ᵥ t := mem_image2_of_mem hs ht /-- `s -ᵥ t` is monotone in both arguments. -/ @[mono] lemma vsub_subset_vsub {s' t' : set P} (hs : s ⊆ s') (ht : t ⊆ t') : s -ᵥ t ⊆ s' -ᵥ t' := image2_subset hs ht lemma vsub_self_mono (h : s ⊆ t) : s -ᵥ s ⊆ t -ᵥ t := vsub_subset_vsub h h lemma vsub_subset_iff {u : set G} : s -ᵥ t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), x -ᵥ y ∈ u := image2_subset_iff end vsub instance add_action : add_action (set G) (set P) := { vadd := set.image2 (+ᵥ), zero_vadd := λ s, by simp [← singleton_zero], add_vadd := λ s t p, by { apply image2_assoc, intros, apply add_vadd } } variables {s s' : set G} {t t' : set P} @[mono] lemma vadd_subset_vadd (hs : s ⊆ s') (ht : t ⊆ t') : s +ᵥ t ⊆ s' +ᵥ t' := image2_subset hs ht @[simp] lemma vadd_singleton (s : set G) (p : P) : s +ᵥ {p} = (+ᵥ p) '' s := image2_singleton_right @[simp] lemma singleton_vadd (v : G) (s : set P) : ({v} : set G) +ᵥ s = ((+ᵥ) v) '' s := image2_singleton_left lemma finite.vadd (hs : finite s) (ht : finite t) : finite (s +ᵥ t) := hs.image2 _ ht end set @[simp] lemma vadd_vsub_vadd_cancel_right (v₁ v₂ : G) (p : P) : (v₁ +ᵥ p) -ᵥ (v₂ +ᵥ p) = v₁ - v₂ := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, vsub_self, add_zero] /-- If the same point subtracted from two points produces equal results, those points are equal. -/ lemma vsub_left_cancel {p1 p2 p : P} (h : p1 -ᵥ p = p2 -ᵥ p) : p1 = p2 := by rwa [←sub_eq_zero, vsub_sub_vsub_cancel_right, vsub_eq_zero_iff_eq] at h /-- The same point subtracted from two points produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_left_cancel_iff {p1 p2 p : P} : (p1 -ᵥ p) = p2 -ᵥ p ↔ p1 = p2 := ⟨vsub_left_cancel, λ h, h ▸ rfl⟩ /-- Subtracting the point `p` is an injective function. -/ lemma vsub_left_injective (p : P) : function.injective ((-ᵥ p) : P → G) := λ p2 p3, vsub_left_cancel /-- If subtracting two points from the same point produces equal results, those points are equal. -/ lemma vsub_right_cancel {p1 p2 p : P} (h : p -ᵥ p1 = p -ᵥ p2) : p1 = p2 := begin refine vadd_left_cancel (p -ᵥ p2) _, rw [vsub_vadd, ← h, vsub_vadd] end /-- Subtracting two points from the same point produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_right_cancel_iff {p1 p2 p : P} : p -ᵥ p1 = p -ᵥ p2 ↔ p1 = p2 := ⟨vsub_right_cancel, λ h, h ▸ rfl⟩ /-- Subtracting a point from the point `p` is an injective function. -/ lemma vsub_right_injective (p : P) : function.injective ((-ᵥ) p : P → G) := λ p2 p3, vsub_right_cancel end general section comm variables {G : Type*} {P : Type*} [add_comm_group G] [add_torsor G P] include G /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_left (p1 p2 p3 : P) : (p3 -ᵥ p2) - (p3 -ᵥ p1) = (p1 -ᵥ p2) := by rw [sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm, vsub_add_vsub_cancel] @[simp] lemma vadd_vsub_vadd_cancel_left (v : G) (p1 p2 : P) : (v +ᵥ p1) -ᵥ (v +ᵥ p2) = p1 -ᵥ p2 := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub_cancel'] lemma vsub_vadd_comm (p1 p2 p3 : P) : (p1 -ᵥ p2 : G) +ᵥ p3 = p3 -ᵥ p2 +ᵥ p1 := begin rw [←@vsub_eq_zero_iff_eq G, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub], simp end lemma vadd_eq_vadd_iff_sub_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} : v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ v₂ - v₁ = p₁ -ᵥ p₂ := by rw [vadd_eq_vadd_iff_neg_add_eq_vsub, neg_add_eq_sub] lemma vsub_sub_vsub_comm (p₁ p₂ p₃ p₄ : P) : (p₁ -ᵥ p₂) - (p₃ -ᵥ p₄) = (p₁ -ᵥ p₃) - (p₂ -ᵥ p₄) := by rw [← vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub] end comm namespace prod variables {G : Type*} {P : Type*} {G' : Type*} {P' : Type*} [add_group G] [add_group G'] [add_torsor G P] [add_torsor G' P'] instance : add_torsor (G × G') (P × P') := { vadd := λ v p, (v.1 +ᵥ p.1, v.2 +ᵥ p.2), zero_vadd := λ p, by simp, add_vadd := by simp [add_vadd], vsub := λ p₁ p₂, (p₁.1 -ᵥ p₂.1, p₁.2 -ᵥ p₂.2), nonempty := prod.nonempty, vsub_vadd' := λ p₁ p₂, show (p₁.1 -ᵥ p₂.1 +ᵥ p₂.1, _) = p₁, by simp, vadd_vsub' := λ v p, show (v.1 +ᵥ p.1 -ᵥ p.1, v.2 +ᵥ p.2 -ᵥ p.2) =v, by simp } @[simp] lemma fst_vadd (v : G × G') (p : P × P') : (v +ᵥ p).1 = v.1 +ᵥ p.1 := rfl @[simp] lemma snd_vadd (v : G × G') (p : P × P') : (v +ᵥ p).2 = v.2 +ᵥ p.2 := rfl @[simp] lemma mk_vadd_mk (v : G) (v' : G') (p : P) (p' : P') : (v, v') +ᵥ (p, p') = (v +ᵥ p, v' +ᵥ p') := rfl @[simp] lemma fst_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').1 = p₁.1 -ᵥ p₂.1 := rfl @[simp] lemma snd_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').2 = p₁.2 -ᵥ p₂.2 := rfl @[simp] lemma mk_vsub_mk (p₁ p₂ : P) (p₁' p₂' : P') : ((p₁, p₁') -ᵥ (p₂, p₂') : G × G') = (p₁ -ᵥ p₂, p₁' -ᵥ p₂') := rfl end prod namespace pi universes u v w variables {I : Type u} {fg : I → Type v} [∀ i, add_group (fg i)] {fp : I → Type w} open add_action add_torsor /-- A product of `add_torsor`s is an `add_torsor`. -/ instance [T : ∀ i, add_torsor (fg i) (fp i)] : add_torsor (Π i, fg i) (Π i, fp i) := { vadd := λ g p, λ i, g i +ᵥ p i, zero_vadd := λ p, funext $ λ i, zero_vadd (fg i) (p i), add_vadd := λ g₁ g₂ p, funext $ λ i, add_vadd (g₁ i) (g₂ i) (p i), vsub := λ p₁ p₂, λ i, p₁ i -ᵥ p₂ i, nonempty := ⟨λ i, classical.choice (T i).nonempty⟩, vsub_vadd' := λ p₁ p₂, funext $ λ i, vsub_vadd (p₁ i) (p₂ i), vadd_vsub' := λ g p, funext $ λ i, vadd_vsub (g i) (p i) } /-- Addition in a product of `add_torsor`s. -/ @[simp] lemma vadd_apply [T : ∀ i, add_torsor (fg i) (fp i)] (x : Π i, fg i) (y : Π i, fp i) {i : I} : (x +ᵥ y) i = x i +ᵥ y i := rfl end pi namespace equiv variables {G : Type*} {P : Type*} [add_group G] [add_torsor G P] include G /-- `v ↦ v +ᵥ p` as an equivalence. -/ def vadd_const (p : P) : G ≃ P := { to_fun := λ v, v +ᵥ p, inv_fun := λ p', p' -ᵥ p, left_inv := λ v, vadd_vsub _ _, right_inv := λ p', vsub_vadd _ _ } @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const p) = λ v, v+ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const p).symm = λ p', p' -ᵥ p := rfl /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P) : P ≃ G := { to_fun := (-ᵥ) p, inv_fun := λ v, -v +ᵥ p, left_inv := λ p', by simp, right_inv := λ v, by simp [vsub_vadd_eq_vsub_sub] } @[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P) : ⇑(const_vsub p).symm = λ v, -v +ᵥ p := rfl variables (P) /-- The permutation given by `p ↦ v +ᵥ p`. -/ def const_vadd (v : G) : equiv.perm P := { to_fun := (+ᵥ) v, inv_fun := (+ᵥ) (-v), left_inv := λ p, by simp [vadd_vadd], right_inv := λ p, by simp [vadd_vadd] } @[simp] lemma coe_const_vadd (v : G) : ⇑(const_vadd P v) = (+ᵥ) v := rfl variable (G) @[simp] lemma const_vadd_zero : const_vadd P (0:G) = 1 := ext $ zero_vadd G variable {G} @[simp] lemma const_vadd_add (v₁ v₂ : G) : const_vadd P (v₁ + v₂) = const_vadd P v₁ * const_vadd P v₂ := ext $ add_vadd v₁ v₂ /-- `equiv.const_vadd` as a homomorphism from `multiplicative G` to `equiv.perm P` -/ def const_vadd_hom : multiplicative G →* equiv.perm P := { to_fun := λ v, const_vadd P v.to_add, map_one' := const_vadd_zero G P, map_mul' := const_vadd_add P } variable {P} open function /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : P) : perm P := (const_vsub x).trans (vadd_const x) lemma point_reflection_apply (x y : P) : point_reflection x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_symm (x : P) : (point_reflection x).symm = point_reflection x := ext $ by simp [point_reflection] @[simp] lemma point_reflection_self (x : P) : point_reflection x x = x := vsub_vadd _ _ lemma point_reflection_involutive (x : P) : involutive (point_reflection x : P → P) := λ y, (equiv.apply_eq_iff_eq_symm_apply _).2 $ by rw point_reflection_symm /-- `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 : G → G)) : point_reflection x y = y ↔ y = x := by rw [point_reflection_apply, eq_comm, eq_vadd_iff_vsub_eq, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero, ← bit0, ← bit0_zero, h.eq_iff, vsub_eq_zero_iff_eq, eq_comm] omit G lemma injective_point_reflection_left_of_injective_bit0 {G P : Type*} [add_comm_group G] [add_torsor G P] (h : injective (bit0 : G → G)) (y : P) : injective (λ x : P, point_reflection x y) := λ x₁ x₂ (hy : point_reflection x₁ y = point_reflection x₂ y), by rwa [point_reflection_apply, point_reflection_apply, vadd_eq_vadd_iff_sub_eq_vsub, vsub_sub_vsub_cancel_right, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero, ← bit0, ← bit0_zero, h.eq_iff, vsub_eq_zero_iff_eq] at hy end equiv
c2f640a96f8c1291aaece872c033d63f4d903cb9
ce4db867008cc96ee6ea6a34d39c2fa7c6ccb536
/src/Supposons.lean
0e5099226e70069385a5b230d1ed24e7c5932b31
[]
no_license
PatrickMassot/lean-bavard
ab0ceedd6bab43dc0444903a80b911c5fbfb23c3
92a1a8c7ff322e4f575ec709b8c5348990d64f18
refs/heads/master
1,679,565,084,665
1,616,158,570,000
1,616,158,570,000
348,144,867
1
1
null
null
null
null
UTF-8
Lean
false
false
2,510
lean
import tactic import .tokens import .commun namespace tactic setup_tactic_parser @[derive has_reflect] meta inductive Supposons_args | regular : list pexpr → Supposons_args | absurde : name → option pexpr → Supposons_args meta def Supposons_parser : lean.parser Supposons_args := with_desc "... / Supposons par l'absurde ..." $ do { _ ← tk "par", _ ← tk "l'absurde", n ← ident, do { _ ← tk ":", hyp ← texpr, pure (Supposons_args.absurde n (some hyp)) } <|> pure (Supposons_args.absurde n none)} <|> Supposons_args.regular <$> ((tk "que")? *>parse_binders tac_rbp) private meta def supposons_core (n : name) (ty : pexpr) := do verifie_nom n, t ← target, when (not $ t.is_pi) whnf_target, t ← target, when (not $ t.is_arrow) $ fail "Il n'y a rien à supposer ici, le but n'est pas une implication", ty ← i_to_expr ty, unify ty t.binding_domain, intro_core n >> skip open Supposons_args /-- Introduit une hypothèse quand le but est une implication, ou bien démarre un raisonnement par l'absurde. -/ @[interactive] meta def Supposons : parse Supposons_parser → tactic unit | (regular le) := do le.mmap' (λ b : pexpr, supposons_core b.local_pp_name b.local_type) | (absurde n hyp) := do by_contradiction n, try (interactive.push_neg (loc.ns [n])), when hyp.is_some (do Hyp ← hyp >>= to_expr, let sp := simp_arg_type.symm_expr ``(exists_prop), try (interactive.simp_core {} skip tt [sp] [] $ loc.ns [n]), ehyp ← get_local n, change_core Hyp (some ehyp)) end tactic example : ∀ n > 0, true := begin intro n, success_if_fail { Supposons H : n < 0 }, success_if_fail { Supposons n : n > 0 }, Supposons H : n > 0, trivial end example : ∀ n > 0, true := begin intro n, Supposons que H : n > 0, trivial end example : ∀ n > 0, true := begin success_if_fail { Supposons n }, intro n, Supposons H : n > 0, trivial end example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q := begin Supposons hP, Supposons par l'absurde hnQ, exact h hnQ hP, end example (P Q : Prop) (h : ¬ Q → ¬ P) : P → Q := begin Supposons hP, Supposons par l'absurde hnQ : ¬ Q, exact h hnQ hP, end example (P Q : Prop) (h : Q → ¬ P) : P → ¬ Q := begin Supposons hP, Supposons par l'absurde hnQ : Q, exact h hnQ hP, end
e8b7c2d1c7963da7fedd7198786cd03f4571eb70
f3a5af2927397cf346ec0e24312bfff077f00425
/src/mynat/pow.lean
045da93a38ecccce10bca2117f5dd35b9ba0f964
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
380
lean
import mynat.mul namespace mynat def pow : mynat → mynat → mynat | m zero := one | m (succ n) := pow m n * m instance : has_pow mynat mynat := ⟨pow⟩ -- notation a ^ b := pow a b example : (1 : mynat) ^ (1 : mynat) = 1 := begin refl end lemma pow_zero (m : mynat) : m ^ (0 : mynat) = 1 := rfl lemma pow_succ (m n : mynat) : m ^ (succ n) = m ^ n * m := rfl end mynat
8257869b85a298289ff23d19abbc1c2f5176cf3f
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/squarefree.lean
f7aa6904f762dacd92e196fcc4de8a100399f50f
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,747
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import ring_theory.unique_factorization_domain import ring_theory.int.basic import number_theory.divisors /-! # Squarefree elements of monoids An element of a monoid is squarefree when it is not divisible by any squares except the squares of units. ## Main Definitions - `squarefree r` indicates that `r` is only divisible by `x * x` if `x` is a unit. ## Main Results - `multiplicity.squarefree_iff_multiplicity_le_one`: `x` is `squarefree` iff for every `y`, either `multiplicity y x ≤ 1` or `is_unit y`. - `unique_factorization_monoid.squarefree_iff_nodup_factors`: A nonzero element `x` of a unique factorization monoid is squarefree iff `factors x` has no duplicate factors. - `nat.squarefree_iff_nodup_factors`: A positive natural number `x` is squarefree iff the list `factors x` has no duplicate factors. ## Tags squarefree, multiplicity -/ variables {R : Type*} /-- An element of a monoid is squarefree if the only squares that divide it are the squares of units. -/ def squarefree [monoid R] (r : R) : Prop := ∀ x : R, x * x ∣ r → is_unit x @[simp] lemma is_unit.squarefree [comm_monoid R] {x : R} (h : is_unit x) : squarefree x := λ y hdvd, is_unit_of_mul_is_unit_left (is_unit_of_dvd_unit hdvd h) @[simp] lemma squarefree_one [comm_monoid R] : squarefree (1 : R) := is_unit_one.squarefree @[simp] lemma not_squarefree_zero [monoid_with_zero R] [nontrivial R] : ¬ squarefree (0 : R) := begin erw [not_forall], exact ⟨0, (by simp)⟩, end @[simp] lemma irreducible.squarefree [comm_monoid R] {x : R} (h : irreducible x) : squarefree x := begin rintros y ⟨z, hz⟩, rw mul_assoc at hz, rcases h.is_unit_or_is_unit hz with hu | hu, { exact hu }, { apply is_unit_of_mul_is_unit_left hu }, end @[simp] lemma prime.squarefree [comm_cancel_monoid_with_zero R] {x : R} (h : prime x) : squarefree x := h.irreducible.squarefree lemma squarefree_of_dvd_of_squarefree [comm_monoid R] {x y : R} (hdvd : x ∣ y) (hsq : squarefree y) : squarefree x := λ a h, hsq _ (h.trans hdvd) namespace multiplicity variables [comm_monoid R] [decidable_rel (has_dvd.dvd : R → R → Prop)] lemma squarefree_iff_multiplicity_le_one (r : R) : squarefree r ↔ ∀ x : R, multiplicity x r ≤ 1 ∨ is_unit x := begin refine forall_congr (λ a, _), rw [← sq, pow_dvd_iff_le_multiplicity, or_iff_not_imp_left, not_le, imp_congr], swap, { refl }, convert enat.add_one_le_iff_lt (enat.coe_ne_top 1), norm_cast, end end multiplicity namespace unique_factorization_monoid variables [comm_cancel_monoid_with_zero R] [nontrivial R] [unique_factorization_monoid R] variables [normalization_monoid R] lemma squarefree_iff_nodup_normalized_factors [decidable_eq R] {x : R} (x0 : x ≠ 0) : squarefree x ↔ multiset.nodup (normalized_factors x) := begin have drel : decidable_rel (has_dvd.dvd : R → R → Prop), { classical, apply_instance, }, haveI := drel, rw [multiplicity.squarefree_iff_multiplicity_le_one, multiset.nodup_iff_count_le_one], split; intros h a, { by_cases hmem : a ∈ normalized_factors x, { have ha := irreducible_of_normalized_factor _ hmem, rcases h a with h | h, { rw ← normalize_normalized_factor _ hmem, rw [multiplicity_eq_count_normalized_factors ha x0] at h, assumption_mod_cast }, { have := ha.1, contradiction, } }, { simp [multiset.count_eq_zero_of_not_mem hmem] } }, { rw or_iff_not_imp_right, intro hu, by_cases h0 : a = 0, { simp [h0, x0] }, rcases wf_dvd_monoid.exists_irreducible_factor hu h0 with ⟨b, hib, hdvd⟩, apply le_trans (multiplicity.multiplicity_le_multiplicity_of_dvd_left hdvd), rw [multiplicity_eq_count_normalized_factors hib x0], specialize h (normalize b), assumption_mod_cast } end lemma dvd_pow_iff_dvd_of_squarefree {x y : R} {n : ℕ} (hsq : squarefree x) (h0 : n ≠ 0) : x ∣ y ^ n ↔ x ∣ y := begin classical, by_cases hx : x = 0, { simp [hx, pow_eq_zero_iff (nat.pos_of_ne_zero h0)] }, by_cases hy : y = 0, { simp [hy, zero_pow (nat.pos_of_ne_zero h0)] }, refine ⟨λ h, _, λ h, h.pow h0⟩, rw [dvd_iff_normalized_factors_le_normalized_factors hx (pow_ne_zero n hy), normalized_factors_pow, ((squarefree_iff_nodup_normalized_factors hx).1 hsq).le_nsmul_iff_le h0] at h, rwa dvd_iff_normalized_factors_le_normalized_factors hx hy, end end unique_factorization_monoid namespace nat lemma squarefree_iff_nodup_factors {n : ℕ} (h0 : n ≠ 0) : squarefree n ↔ n.factors.nodup := begin rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors h0, nat.factors_eq], simp, end instance : decidable_pred (squarefree : ℕ → Prop) | 0 := is_false not_squarefree_zero | (n + 1) := decidable_of_iff _ (squarefree_iff_nodup_factors (nat.succ_ne_zero n)).symm open unique_factorization_monoid lemma divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) : (n.divisors.filter squarefree).val = (unique_factorization_monoid.normalized_factors n).to_finset.powerset.val.map (λ x, x.val.prod) := begin rw multiset.nodup_ext (finset.nodup _) (multiset.nodup_map_on _ (finset.nodup _)), { intro a, simp only [multiset.mem_filter, id.def, multiset.mem_map, finset.filter_val, ← finset.mem_def, mem_divisors], split, { rintro ⟨⟨an, h0⟩, hsq⟩, use (unique_factorization_monoid.normalized_factors a).to_finset, simp only [id.def, finset.mem_powerset], rcases an with ⟨b, rfl⟩, rw mul_ne_zero_iff at h0, rw unique_factorization_monoid.squarefree_iff_nodup_normalized_factors h0.1 at hsq, rw [multiset.to_finset_subset, multiset.to_finset_val, multiset.erase_dup_eq_self.2 hsq, ← associated_iff_eq, normalized_factors_mul h0.1 h0.2], exact ⟨multiset.subset_of_le (multiset.le_add_right _ _), normalized_factors_prod h0.1⟩ }, { rintro ⟨s, hs, rfl⟩, rw [finset.mem_powerset, ← finset.val_le_iff, multiset.to_finset_val] at hs, have hs0 : s.val.prod ≠ 0, { rw [ne.def, multiset.prod_eq_zero_iff], simp only [exists_prop, id.def, exists_eq_right], intro con, apply not_irreducible_zero (irreducible_of_normalized_factor 0 (multiset.mem_erase_dup.1 (multiset.mem_of_le hs con))) }, rw (normalized_factors_prod h0).symm.dvd_iff_dvd_right, refine ⟨⟨multiset.prod_dvd_prod (le_trans hs (multiset.erase_dup_le _)), h0⟩, _⟩, have h := unique_factorization_monoid.factors_unique irreducible_of_normalized_factor (λ x hx, irreducible_of_normalized_factor x (multiset.mem_of_le (le_trans hs (multiset.erase_dup_le _)) hx)) (normalized_factors_prod hs0), rw [associated_eq_eq, multiset.rel_eq] at h, rw [unique_factorization_monoid.squarefree_iff_nodup_normalized_factors hs0, h], apply s.nodup } }, { intros x hx y hy h, rw [← finset.val_inj, ← multiset.rel_eq, ← associated_eq_eq], rw [← finset.mem_def, finset.mem_powerset] at hx hy, apply unique_factorization_monoid.factors_unique _ _ (associated_iff_eq.2 h), { intros z hz, apply irreducible_of_normalized_factor z, rw ← multiset.mem_to_finset, apply hx hz }, { intros z hz, apply irreducible_of_normalized_factor z, rw ← multiset.mem_to_finset, apply hy hz } } end open_locale big_operators lemma sum_divisors_filter_squarefree {n : ℕ} (h0 : n ≠ 0) {α : Type*} [add_comm_monoid α] {f : ℕ → α} : ∑ i in (n.divisors.filter squarefree), f i = ∑ i in (unique_factorization_monoid.normalized_factors n).to_finset.powerset, f (i.val.prod) := by rw [finset.sum_eq_multiset_sum, divisors_filter_squarefree h0, multiset.map_map, finset.sum_eq_multiset_sum] lemma sq_mul_squarefree_of_pos {n : ℕ} (hn : 0 < n) : ∃ a b : ℕ, 0 < a ∧ 0 < b ∧ b ^ 2 * a = n ∧ squarefree a := begin let S := {s ∈ finset.range (n + 1) | s ∣ n ∧ ∃ x, s = x ^ 2}, have hSne : S.nonempty, { use 1, have h1 : 0 < n ∧ ∃ (x : ℕ), 1 = x ^ 2 := ⟨hn, ⟨1, (one_pow 2).symm⟩⟩, simpa [S] }, let s := finset.max' S hSne, have hs : s ∈ S := finset.max'_mem S hSne, simp only [finset.sep_def, S, finset.mem_filter, finset.mem_range] at hs, obtain ⟨hsn1, ⟨a, hsa⟩, ⟨b, hsb⟩⟩ := hs, rw hsa at hn, obtain ⟨hlts, hlta⟩ := canonically_ordered_comm_semiring.mul_pos.mp hn, rw hsb at hsa hn hlts, refine ⟨a, b, hlta, (pow_pos_iff zero_lt_two).mp hlts, hsa.symm, _⟩, rintro x ⟨y, hy⟩, rw nat.is_unit_iff, by_contra hx, refine lt_le_antisymm _ (finset.le_max' S ((b * x) ^ 2) _), { simp_rw [S, hsa, finset.sep_def, finset.mem_filter, finset.mem_range], refine ⟨lt_succ_iff.mpr (le_of_dvd hn _), _, ⟨b * x, rfl⟩⟩; use y; rw hy; ring }, { convert lt_mul_of_one_lt_right hlts (one_lt_pow 2 x zero_lt_two (one_lt_iff_ne_zero_and_ne_one.mpr ⟨λ h, by simp * at *, hx⟩)), rw mul_pow }, end lemma sq_mul_squarefree_of_pos' {n : ℕ} (h : 0 < n) : ∃ a b : ℕ, (b + 1) ^ 2 * (a + 1) = n ∧ squarefree (a + 1) := begin obtain ⟨a₁, b₁, ha₁, hb₁, hab₁, hab₂⟩ := sq_mul_squarefree_of_pos h, refine ⟨a₁.pred, b₁.pred, _, _⟩; simpa only [add_one, succ_pred_eq_of_pos, ha₁, hb₁], end lemma sq_mul_squarefree (n : ℕ) : ∃ a b : ℕ, b ^ 2 * a = n ∧ squarefree a := begin cases n, { exact ⟨1, 0, (by simp), squarefree_one⟩ }, { obtain ⟨a, b, -, -, h₁, h₂⟩ := sq_mul_squarefree_of_pos (succ_pos n), exact ⟨a, b, h₁, h₂⟩ }, end end nat
c4b46dbae1601b636a184b534f85b9cca264fd31
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/src/builtin/optional.lean
aa7b685fc62c7ce5df7b147a8e7d4fc7d5cb4859
[ "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
4,978
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import macros subtype using subtype -- We are encoding the (optional A) as a subset of A → Bool where -- none is the predicate that is false everywhere -- some(a) is the predicate that is true only at a definition optional_pred (A : (Type U)) := (λ p : A → Bool, (∀ x, ¬ p x) ∨ exists_unique p) definition optional (A : (Type U)) := subtype (A → Bool) (optional_pred A) namespace optional theorem some_pred {A : (Type U)} (a : A) : optional_pred A (λ x, x = a) := or_intror (∀ x, ¬ x = a) (exists_intro a (and_intro (refl a) (take y, assume H : y ≠ a, H))) theorem none_pred (A : (Type U)) : optional_pred A (λ x, false) := or_introl (take x, not_false_trivial) (exists_unique (λ x, false)) theorem inhab (A : (Type U)) : inhabited (optional A) := subtype_inhabited (exists_intro (λ x, false) (none_pred A)) definition none {A : (Type U)} : optional A := abst (λ x, false) (inhab A) definition some {A : (Type U)} (a : A) : optional A := abst (λ x, x = a) (inhab A) definition is_some {A : (Type U)} (n : optional A) := ∃ x : A, some x = n theorem injectivity {A : (Type U)} {a a' : A} : some a = some a' → a = a' := assume Heq : some a = some a', have eq_reps : (λ x, x = a) = (λ x, x = a'), from abst_inj (inhab A) (some_pred a) (some_pred a') Heq, show a = a', from (congr1 eq_reps a) ◂ (refl a) theorem distinct {A : (Type U)} (a : A) : some a ≠ none := not_intro (assume N : some a = none, have eq_reps : (λ x, x = a) = (λ x, false), from abst_inj (inhab A) (some_pred a) (none_pred A) N, show false, from (congr1 eq_reps a) ◂ (refl a)) definition value {A : (Type U)} (n : optional A) (H : is_some n) : A := ε (inhabited_ex_intro H) (λ x, some x = n) theorem is_some_some {A : (Type U)} (a : A) : is_some (some a) := exists_intro a (refl (some a)) theorem not_is_some_none {A : (Type U)} : ¬ is_some (@none A) := not_intro (assume N : is_some (@none A), obtain (w : A) (Hw : some w = @none A), from N, show false, from absurd Hw (distinct w)) theorem value_some {A : (Type U)} (a : A) (H : is_some (some a)) : value (some a) H = a := have eq1 : some (value (some a) H) = some a, from eps_ax (inhabited_ex_intro H) a (refl (some a)), show value (some a) H = a, from injectivity eq1 theorem false_pred {A : (Type U)} {p : A → Bool} (H : ∀ x, ¬ p x) : p = λ x, false := funext (λ x, eqf_intro (H x)) theorem singleton_pred {A : (Type U)} {p : A → Bool} {w : A} (H : p w ∧ ∀ y, y ≠ w → ¬ p y) : p = (λ x, x = w) := funext (take x, iff_intro (assume Hpx : p x, show x = w, from by_contradiction (assume N : x ≠ w, show false, from absurd Hpx (and_elimr H x N))) (assume Heq : x = w, show p x, from subst (and_eliml H) (symm Heq))) theorem dichotomy {A : (Type U)} (n : optional A) : n = none ∨ ∃ a, n = some a := have pred : optional_pred A (rep n), from P_rep n, show n = none ∨ ∃ a, n = some a, from or_elim pred (assume Hl : ∀ x : A, ¬ rep n x, have rep_n_eq : rep n = λ x, false, from false_pred Hl, have rep_none_eq : rep none = λ x, false, from rep_abst (inhab A) (λ x, false) (none_pred A), show n = none ∨ ∃ a, n = some a, from or_introl (rep_inj (trans rep_n_eq (symm rep_none_eq))) (∃ a, n = some a)) (assume Hr : ∃ x, rep n x ∧ ∀ y, y ≠ x → ¬ rep n y, obtain (w : A) (Hw : rep n w ∧ ∀ y, y ≠ w → ¬ rep n y), from Hr, have rep_n_eq : rep n = λ x, x = w, from singleton_pred Hw, have rep_some_eq : rep (some w) = λ x, x = w, from rep_abst (inhab A) (λ x, x = w) (some_pred w), have n_eq_some : n = some w, from rep_inj (trans rep_n_eq (symm rep_some_eq)), show n = none ∨ ∃ a, n = some a, from or_intror (n = none) (exists_intro w n_eq_some)) theorem induction {A : (Type U)} {P : optional A → Bool} (H1 : P none) (H2 : ∀ x, P (some x)) : ∀ n, P n := take n, or_elim (dichotomy n) (assume Heq : n = none, show P n, from subst H1 (symm Heq)) (assume Hex : ∃ a, n = some a, obtain (w : A) (Hw : n = some w), from Hex, show P n, from subst (H2 w) (symm Hw)) set_opaque some true set_opaque none true set_opaque is_some true set_opaque value true end set_opaque optional true set_opaque optional_pred true definition optional_inhabited := optional::inhab add_rewrite optional::is_some_some optional::not_is_some_none optional::distinct optional::value_some