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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0c276a8c154a37866a24d08c739ed586074b6ccd | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Elab/BindersUtil.lean | b6dc925fdeed6a6376a75185afe754b87ffa5359 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 1,662 | 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.Parser.Term
namespace Lean.Elab.Term
/--
Recall that
```
def typeSpec := leading_parser " : " >> termParser
def optType : Parser := optional typeSpec
```
-/
def expandOptType (ref : Syntax) (optType : Syntax) : Syntax :=
if optType.isNone then
mkHole ref
else
optType[0][1]
open Lean.Parser.Term
/-- Helper function for `expandEqnsIntoMatch` -/
def getMatchAltsNumPatterns (matchAlts : Syntax) : Nat :=
let alt0 := matchAlts[0][0]
let pats := alt0[1][0].getSepArgs
pats.size
/--
Expand a match alternative such as `| 0 | 1 => rhs` to an array containing `| 0 => rhs` and `| 1 => rhs`.
-/
def expandMatchAlt (stx : TSyntax ``matchAlt) : MacroM (Array (TSyntax ``matchAlt)) :=
match stx with
| `(matchAltExpr| | $[$patss,*]|* => $rhs) =>
if patss.size ≤ 1 then
return #[stx]
else
patss.mapM fun pats => `(matchAltExpr| | $pats,* => $rhs)
| _ => return #[stx]
def shouldExpandMatchAlt : TSyntax ``matchAlt → Bool
| `(matchAltExpr| | $[$patss,*]|* => $_) => patss.size > 1
| _ => false
def expandMatchAlts? (stx : Syntax) : MacroM (Option Syntax) := do
match stx with
| `(match $[$gen]? $[$motive]? $discrs,* with $alts:matchAlt*) =>
if alts.any shouldExpandMatchAlt then
let alts ← alts.foldlM (init := #[]) fun alts alt => return alts ++ (← expandMatchAlt alt)
`(match $[$gen]? $[$motive]? $discrs,* with $alts:matchAlt*)
else
return none
| _ => return none
end Lean.Elab.Term
|
b2ae5a0311d277a2bf7635053a79113f5f6005ab | fe84e287c662151bb313504482b218a503b972f3 | /src/commutative_algebra/nilpotent.lean | 5196b8eb7f4311a9af794da72a6894305fe20960 | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 11,786 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
This is about the ideal of nilpotent elements in a commutative ring.
It is written in a somewhat constructive style, to allow us to keep
track of nilpotence exponents:
* `is_nilpotent a` is the proposition that `a` is nilpotent.
* `as_nilpotent a` is the type of pairs `⟨n,h⟩` where `h` is a proof
that `a ^ n = 0`. This type is nonempty iff `a` is nilpotent.
Note that we allow `n = 0`, but `a ^ 0 = 0` only holds if the
whole ring is trivial.
* `w_nilradical A` is the type of triples `⟨a,⟨n,h⟩⟩`, where `h` is
a proof that `a ^ n = 0`. The prefix `w_` is for "witnessed".
* `nilradical A` is the ideal of nilpotent elements in `A`. This
is represented as a structure with
`(nilradical A).carrier = is_nilpotent : A → Prop`. There are
additional fields in the structure, which contain proofs that
this carrier contains zero and is closed under addition and
scalar multiplication.
* Lifting this, we can introduce a zero element and addition and
scalar multiplication operations for `w_nilradical A`. These
satisfy most of the usual identities except that
`0 • ⟨a,n,h⟩ = ⟨0,n,_⟩`, and this can be different from
`0 = ⟨0,1,_⟩`,
-/
import algebra.ring
import algebra.group_power algebra.geom_sum
import data.nat.choose
import ring_theory.ideal.basic ring_theory.ideal.quotient
universe u
variables {A : Type u} [comm_ring A]
namespace commutative_algebra
def as_nilpotent (a : A) := {n : ℕ // a ^ n = 0}
def as_nilpotent_congr {a b : A} (e : a = b)
(ha : as_nilpotent a) : as_nilpotent b :=
⟨ha.val,e ▸ ha.property⟩
lemma as_nilpotent_congr_exp {a b : A} (e : a = b)
(ha : as_nilpotent a) :
(as_nilpotent_congr e ha).1 = ha.1 := rfl
inductive is_nilpotent (a : A) : Prop
| mk : (as_nilpotent a) → is_nilpotent
def as_nilpotent_zero : as_nilpotent (0 : A) := ⟨1,pow_one 0⟩
lemma is_nilpotent_zero : is_nilpotent (0 : A) := ⟨as_nilpotent_zero⟩
/-- The meaning of the mul_exp function is as follows:
if x ^ n = y ^ m = 0, then (x + y) ^ (mul_exp n m) = 0.
Usually we just have (mul_exp n m) = n + m - 1, but if
n or m is zero then the whole ring is necessarily trivial
and so it is natural to take mul_exp n m = 0. With this
definition, it works out that the mul_exp operation gives
a commutative monoid structure on ℕ, with 1 as the identity
element. We prove the commutative monoid laws but we do
not define a comm_monoid instance, to avoid interfering
with the standard multiplicative monoid structure on ℕ.
-/
def mul_exp : ℕ → ℕ → ℕ
| 0 m := 0
| (n + 1) 0 := 0
| (n + 1) (m + 1) := n + m + 1
namespace mul_exp
lemma zero_mul (m : ℕ) : mul_exp 0 m = 0 := rfl
lemma mul_zero (n : ℕ) : mul_exp n 0 = 0 := by { cases n; refl }
lemma one_mul (m : ℕ) : mul_exp 1 m = m :=
by { cases m, refl, change 0 + m + 1 = m + 1, rw[nat.zero_add] }
lemma mul_one (n : ℕ) : mul_exp n 1 = n :=
by { cases n; refl }
lemma mul_comm (n m : ℕ) : mul_exp n m = mul_exp m n :=
by {cases n; cases m; dsimp[mul_exp]; try {refl}, rw[add_comm n m]}
lemma mul_assoc (n m p : ℕ) :
mul_exp (mul_exp n m) p = mul_exp n (mul_exp m p) :=
by { cases n; cases m; cases p; dsimp[mul_exp]; try {refl},
repeat{rw[add_assoc]},}
end mul_exp
lemma nilpotent_add_aux {a b : A} {n m : ℕ}
(ea : a ^ n = 0) (eb : b ^ m = 0) : (a + b) ^ (mul_exp n m) = 0 :=
begin
have hz : (1 : A) = 0 → (∀ (x : A), x = 0) :=
λ h x, by { rw[← mul_one x, h, mul_zero] },
rcases n with ⟨_|n⟩,
{ rw [pow_zero] at ea, exact hz ea _ },
rcases m with ⟨_|m⟩,
{ rw[pow_zero] at eb, exact hz eb _ },
have : mul_exp n.succ m.succ = n + m + 1 := rfl,
rw [this, add_pow],
rw[← @finset.sum_const_zero A ℕ (finset.range (n + m + 1).succ)],
congr, ext i,
by_cases hi : i ≥ n + 1,
{ rw[← nat.add_sub_of_le hi,pow_add,ea],
repeat {rw[zero_mul]} },
{ replace hi := nat.le_of_lt_succ (lt_of_not_ge hi),
have := nat.add_sub_of_le hi,
have : n + m + 1 - i = (m + 1) + (n - i) :=
by rw [← this, add_comm i, add_assoc, nat.add_sub_cancel,
add_assoc, add_comm i, ← add_assoc,
nat.add_sub_cancel, add_comm],
rw [this, pow_add, eb, zero_mul, mul_zero, zero_mul] }
end
def as_nilpotent_add {a b : A}
(ha : as_nilpotent a) (hb : as_nilpotent b) : as_nilpotent (a + b) :=
⟨mul_exp ha.val hb.val, nilpotent_add_aux ha.property hb.property⟩
lemma as_nilpotent_add_exp {a b : A}
(ha : as_nilpotent a) (hb : as_nilpotent b) :
(as_nilpotent_add ha hb).1 = mul_exp ha.1 hb.1 := rfl
lemma is_nilpotent_add {a b : A} :
is_nilpotent a → is_nilpotent b → is_nilpotent (a + b) :=
λ ⟨ha⟩ ⟨hb⟩, ⟨as_nilpotent_add ha hb⟩
def as_nilpotent_smul (a : A) {b : A}
(hb : as_nilpotent b) : as_nilpotent (a * b) :=
⟨hb.1,by { rw [mul_pow, hb.2, mul_zero] }⟩
lemma as_nilpotent_smul_exp (a : A) {b : A} (hb : as_nilpotent b) :
(as_nilpotent_smul a hb).1 = hb.1 := rfl
lemma is_nilpotent_smul (a : A) {b : A} :
is_nilpotent b → is_nilpotent (a * b) :=
λ ⟨hb⟩, ⟨as_nilpotent_smul a hb⟩
def as_nilpotent_neg {b : A} :
as_nilpotent b → as_nilpotent (-b) :=
λ h, as_nilpotent_congr (neg_eq_neg_one_mul b).symm (as_nilpotent_smul (-1) h)
lemma as_nilpotent_neg_exp {a : A} (ha : as_nilpotent a) :
(as_nilpotent_neg ha).1 = ha.1 :=
by { rw[ ← as_nilpotent_smul_exp (-1) ha],
rw[ ← as_nilpotent_congr_exp (neg_eq_neg_one_mul a).symm (as_nilpotent_smul (-1) ha)],
refl }
lemma is_nilpotent_neg {b : A} :
is_nilpotent b → is_nilpotent (-b) :=
λ ⟨hb⟩, ⟨as_nilpotent_neg hb⟩
def as_nilpotent_sub {a b : A}
(ha : as_nilpotent a) (hb : as_nilpotent b) : as_nilpotent (a - b) :=
as_nilpotent_congr (sub_eq_add_neg a b).symm (as_nilpotent_add ha (as_nilpotent_neg hb))
lemma as_nilpotent_sub_exp {a b : A}
(ha : as_nilpotent a) (hb : as_nilpotent b) :
(as_nilpotent_sub ha hb).1 = mul_exp ha.1 hb.1 :=
by {
rw [← as_nilpotent_neg_exp hb, ← as_nilpotent_add_exp ha (as_nilpotent_neg hb)],
dsimp[as_nilpotent_sub], refl
}
lemma is_nilpotent_sub {a b : A} :
is_nilpotent a → is_nilpotent b → is_nilpotent (a - b) :=
λ ⟨ha⟩ ⟨hb⟩, ⟨as_nilpotent_sub ha hb⟩
def as_nilpotent_chain {a : A} {n : ℕ} :
as_nilpotent (a ^ n) → as_nilpotent a
| ⟨m,ha⟩ := ⟨n * m,(pow_mul a n m).symm ▸ ha⟩
lemma is_nilpotent_chain {a : A} {n : ℕ} :
is_nilpotent (a ^ n) → is_nilpotent a :=
λ ⟨ha⟩, ⟨as_nilpotent_chain ha⟩
variable (A)
def w_nilradical := Σ (a : A), as_nilpotent a
variable {A}
namespace w_nilradical
variables (a b c : w_nilradical A)
instance : has_coe (w_nilradical A) A := ⟨λ a, a.1⟩
def exp : ℕ := a.2.val
def prop : (a : A) ^ a.exp = 0 := a.2.property
@[ext]
lemma ext : ∀ {a b : w_nilradical A},
(a : A) = (b : A) → a.exp = b.exp → a = b :=
begin
rintro ⟨a,⟨n,ha⟩⟩ ⟨b,⟨m,hb⟩⟩ hv he,
change a = b at hv, dsimp[exp] at he, rw[hv] at ha,
cases hv,cases he,refl,
end
instance : has_zero (w_nilradical A) := ⟨⟨(0 : A),as_nilpotent_zero⟩⟩
lemma zero_coe : ((0 : w_nilradical A) : A) = 0 := rfl
lemma zero_exp : (0 : w_nilradical A).exp = 1 := rfl
instance : has_add (w_nilradical A) :=
⟨λ a b, ⟨a.1 + b.1,as_nilpotent_add a.2 b.2⟩⟩
lemma add_coe : ((a + b : w_nilradical A) : A) = a + b := rfl
lemma exp_add : (a + b).exp = mul_exp a.exp b.exp := rfl
instance : has_scalar A (w_nilradical A) :=
⟨λ a b, ⟨a * b.1,as_nilpotent_smul a b.2⟩⟩
lemma smul_coe (a : A) (b : w_nilradical A) : ((a • b) : A) = a * b := rfl
lemma exp_smul (a : A) (b : w_nilradical A) : (a • b).exp = b.exp := rfl
instance : has_neg (w_nilradical A) :=
⟨λ a, ⟨-a.1, as_nilpotent_neg a.2⟩⟩
lemma neg_coe : ((- a : w_nilradical A) : A) = - a := rfl
lemma exp_neg : (- a).exp = a.exp := rfl
instance : has_sub (w_nilradical A) :=
⟨λ a b, ⟨a.1 - b.1,as_nilpotent_sub a.2 b.2⟩⟩
lemma sub_coe : ((a - b : w_nilradical A) : A) = a - b := rfl
lemma exp_sub (a b : w_nilradical A) : (a - b).exp = mul_exp a.exp b.exp :=
as_nilpotent_sub_exp a.2 b.2
instance : add_comm_monoid (w_nilradical A) := {
zero := has_zero.zero,
add := (+),
zero_add := λ a,
by {ext, rw[add_coe,zero_coe,zero_add],
rw[exp_add,zero_exp,mul_exp.one_mul]},
add_zero := λ a,
by {ext, rw[add_coe,zero_coe,add_zero],
rw[exp_add,zero_exp,mul_exp.mul_one]},
add_comm := λ a b,
by {ext, rw[add_coe,add_coe,add_comm],rw[exp_add,exp_add,mul_exp.mul_comm]},
add_assoc := λ a b c,
by {ext,
{repeat {rw[add_coe]}, rw[add_assoc]},
{repeat {rw[exp_add]}, rw[mul_exp.mul_assoc]}
}
}
lemma smul_zero (a : A) : a • (0 : w_nilradical A) = 0 :=
by {ext, change (a * 0 : A) = 0, exact mul_zero a,rw[exp_smul]}
lemma smul_add (a : A) (b c : w_nilradical A) : a • (b + c) = (a • b) + (a • c) :=
by {ext,
change (a * (b + c) : A) = a * b + a * c, apply mul_add,
rw[exp_smul,exp_add,exp_add,exp_smul,exp_smul]}
lemma one_smul (b : w_nilradical A) : (1 : A) • b = b :=
by {ext, change (1 * b : A) = b, apply one_mul, rw[exp_smul]}
lemma mul_smul (a b : A) (c : w_nilradical A) : (a * b) • c = a • (b • c) :=
by {ext, change ((a * b) * c : A) = a * (b * c), apply mul_assoc,
rw[exp_smul,exp_smul,exp_smul]}
/- Neither zero_smul or add_smul are satisfied in this context -/
end w_nilradical
variable (A)
def is_reduced: Prop := ∀ (x : A), (is_nilpotent x) → (x = 0)
def nilradical : ideal A := {
carrier := is_nilpotent,
zero_mem' := is_nilpotent_zero,
add_mem' := λ _ _, is_nilpotent_add,
smul_mem' := λ (a : A) {b : A} (hb : is_nilpotent b),is_nilpotent_smul a hb
}
lemma mem_nilradical (x : A) : x ∈ nilradical A ↔ is_nilpotent x :=
by {refl}
def reduced_quotient := A ⧸ (nilradical A)
namespace reduced_quotient
instance : comm_ring (reduced_quotient A) :=
by { dsimp[reduced_quotient]; apply_instance }
variable {A}
def mk : A →+* reduced_quotient A := ideal.quotient.mk (nilradical A)
lemma mk_eq_zero_iff {x : A} : mk x = 0 ↔ (is_nilpotent x) :=
ideal.quotient.eq_zero_iff_mem
lemma is_reduced : is_reduced (reduced_quotient A) :=
begin
rintros ⟨x0⟩ ⟨n,e0⟩,
change (mk x0) ^ n = 0 at e0,
rw[← (map_pow mk x0 n)] at e0,
rcases (mk_eq_zero_iff.mp e0) with ⟨m,e1⟩,
rw[← pow_mul] at e1,
apply mk_eq_zero_iff.mpr,
exact ⟨⟨n * m, e1⟩⟩,
end
end reduced_quotient
variable {A}
lemma unit_not_nilpotent (a b : A) :
(a * b = 1) → ((1 : A) ≠ 0) → ¬ is_nilpotent a :=
λ hab hz ⟨⟨m,ha⟩⟩,
hz (by {rw[← _root_.one_pow m,← hab,mul_pow,ha,zero_mul]})
lemma one_sub_nilpotent_aux {a : A} {n : ℕ} (ha : a ^ n = 0) :
(1 - a) * (geom_sum a n) = 1 :=
by rw[mul_neg_geom_sum, ha, sub_zero]
lemma unit_add_nilpotent_aux {u v a : A} {n : ℕ}
(hu : u * v = 1) (ha : a ^ n = 0) :
(u + a) * (v * (finset.range n).sum (λ i, (- v * a) ^ i)) = 1 :=
begin
rw[← mul_assoc,add_mul,hu,mul_comm a v,← sub_neg_eq_add 1 (v * a),neg_mul_eq_neg_mul],
let h₀ : (- v * a) ^ n = 0 := by {rw[mul_pow,ha,mul_zero],},
exact one_sub_nilpotent_aux h₀,
end
def unit_add_nilpotent (u : units A) (a : w_nilradical A) : units A := {
val := u + a,
inv := u.inv * (finset.range a.exp).sum (λ i, (- u.inv * a) ^ i),
val_inv := unit_add_nilpotent_aux u.val_inv a.prop,
inv_val := (mul_comm _ _).trans (unit_add_nilpotent_aux u.val_inv a.prop)
}
lemma unit_add_nilpotent_coe (u : units A) (a : w_nilradical A) :
(unit_add_nilpotent u a).val = u + a := rfl
end commutative_algebra |
0f0c85bda105bb4a7563d6583b8c31b12fe6d06f | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/squarefree.lean | 05ea4821b2864cf43e55467cd0ef1e3ba81b32dd | [
"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 | 9,452 | 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 :=
(irreducible_of_prime h).squarefree
lemma squarefree_of_dvd_of_squarefree [comm_monoid R]
{x y : R} (hdvd : x ∣ y) (hsq : squarefree y) :
squarefree x :=
λ a h, hsq _ (dvd.trans h 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 _),
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_factors [decidable_eq R] {x : R} (x0 : x ≠ 0) :
squarefree x ↔ multiset.nodup (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 ∈ factors x,
{ have ha := irreducible_of_factor _ hmem,
rcases h a with h | h,
{ rw ← normalize_factor _ hmem,
rw [multiplicity_eq_count_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_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, dvd_pow h h0⟩,
rw [dvd_iff_factors_le_factors hx (pow_ne_zero n hy), factors_pow,
((squarefree_iff_nodup_factors hx).1 hsq).le_nsmul_iff_le h0] at h,
rwa dvd_iff_factors_le_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_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.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.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_factors h0.1 at hsq,
rw [multiset.to_finset_subset, multiset.to_finset_val, multiset.erase_dup_eq_self.2 hsq,
← associated_iff_eq, factors_mul h0.1 h0.2],
exact ⟨multiset.subset_of_le (multiset.le_add_right _ _), 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_factor 0
(multiset.mem_erase_dup.1 (multiset.mem_of_le hs con))) },
rw [dvd_iff_dvd_of_rel_right (factors_prod h0).symm],
refine ⟨⟨multiset.prod_dvd_prod (le_trans hs (multiset.erase_dup_le _)), h0⟩, _⟩,
have h := unique_factorization_monoid.factors_unique irreducible_of_factor
(λ x hx, irreducible_of_factor x (multiset.mem_of_le
(le_trans hs (multiset.erase_dup_le _)) hx)) (factors_prod hs0),
rw [associated_eq_eq, multiset.rel_eq] at h,
rw [unique_factorization_monoid.squarefree_iff_nodup_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_factor z,
rw ← multiset.mem_to_finset,
apply hx hz },
{ intros z hz,
apply irreducible_of_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.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_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
|
7c7b973d69336a52bb72ae973447007ef8744215 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/diamond1.lean | ec5f27d47204947eb1dac441a19a0335ade14952 | [
"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 | 417 | lean | set_option structureDiamondWarning false
class Foo (α : Type) extends Add α where
zero : α
class FooComm (α : Type) extends Foo α where
comm (a b : α) : a + b = b + a
class FooAssoc (α : Type) extends Foo α where
assoc (a b c : α) : (a + b) + c = a + (b + c)
class FooAC (α : Type) extends FooComm α, FooAssoc α
def f [FooAssoc α] (a : α) :=
a + a
def g [FooAC α] (a : α) :=
f a + f a
|
e8f0a3616d53116dd94b69f4746d96e191bcea09 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/tactic/interactive.lean | 1cd1708469ddc3e094ccc560b5c69d6b14d47bdf | [
"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 | 38,750 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Sébastien Gouëzel, Scott Morrison
-/
import tactic.lint
import tactic.dependencies
setup_tactic_parser
namespace tactic
namespace interactive
open interactive interactive.types expr
/-- Similar to `constructor`, but does not reorder goals. -/
meta def fconstructor : tactic unit := concat_tags tactic.fconstructor
add_tactic_doc
{ name := "fconstructor",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fconstructor],
tags := ["logic", "goal management"] }
/-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal.
Never fails. Useful for debugging. -/
meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit :=
do max ← i_to_expr_strict max >>= tactic.eval_expr nat,
λ s, match _root_.try_for max (tac s) with
| some r := r
| none := (tactic.trace "try_for timeout, using sorry" >> admit) s
end
/-- Multiple `subst`. `substs x y z` is the same as `subst x, subst y, subst z`. -/
meta def substs (l : parse ident*) : tactic unit :=
propagate_tags $ l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible)
add_tactic_doc
{ name := "substs",
category := doc_category.tactic,
decl_names := [`tactic.interactive.substs],
tags := ["rewriting"] }
/-- Unfold coercion-related definitions -/
meta def unfold_coes (loc : parse location) : tactic unit :=
unfold [
``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe,
``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift,
``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc
add_tactic_doc
{ name := "unfold_coes",
category := doc_category.tactic,
decl_names := [`tactic.interactive.unfold_coes],
tags := ["simplification"] }
/-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/
meta def unfold_wf :=
propagate_tags (well_founded_tactics.unfold_wf_rel; well_founded_tactics.unfold_sizeof)
/-- Unfold auxiliary definitions associated with the current declaration. -/
meta def unfold_aux : tactic unit :=
do tgt ← target,
name ← decl_name,
let to_unfold := (tgt.list_names_with_prefix name),
guard (¬ to_unfold.empty),
-- should we be using simp_lemmas.mk_default?
simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change
/-- For debugging only. This tactic checks the current state for any
missing dropped goals and restores them. Useful when there are no
goals to solve but "result contains meta-variables". -/
meta def recover : tactic unit :=
metavariables >>= tactic.set_goals
/-- Like `try { tac }`, but in the case of failure it continues
from the failure state instead of reverting to the original state. -/
meta def continue (tac : itactic) : tactic unit :=
λ s, result.cases_on (tac s)
(λ a, result.success ())
(λ e ref, result.success ())
/-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without
requiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a
non-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/
@[inline] protected meta def id (tac : itactic) : tactic unit := tac
/--
`work_on_goal n { tac }` creates a block scope for the `n`-goal (indexed from zero),
and does not require that the goal be solved at the end
(any remaining subgoals are inserted back into the list of goals).
Typically usage might look like:
````
intros,
simp,
apply lemma_1,
work_on_goal 2 {
dsimp,
simp
},
refl
````
See also `id { tac }`, which is equivalent to `work_on_goal 0 { tac }`.
-/
meta def work_on_goal : parse small_nat → itactic → tactic unit
| n t := do
goals ← get_goals,
let earlier_goals := goals.take n,
let later_goals := goals.drop (n+1),
set_goals (goals.nth n).to_list,
t,
new_goals ← get_goals,
set_goals (earlier_goals ++ new_goals ++ later_goals)
/--
`swap n` will move the `n`th goal to the front.
`swap` defaults to `swap 2`, and so interchanges the first and second goals.
See also `tactic.interactive.rotate`, which moves the first `n` goals to the back.
-/
meta def swap (n := 2) : tactic unit :=
do gs ← get_goals,
match gs.nth (n-1) with
| (some g) := set_goals (g :: gs.remove_nth (n-1))
| _ := skip
end
add_tactic_doc
{ name := "swap",
category := doc_category.tactic,
decl_names := [`tactic.interactive.swap],
tags := ["goal management"] }
/--
`rotate` moves the first goal to the back. `rotate n` will do this `n` times.
See also `tactic.interactive.swap`, which moves the `n`th goal to the front.
-/
meta def rotate (n := 1) : tactic unit := tactic.rotate n
add_tactic_doc
{ name := "rotate",
category := doc_category.tactic,
decl_names := [`tactic.interactive.rotate],
tags := ["goal management"] }
/-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/
meta def clear_ : tactic unit := tactic.repeat $ do
l ← local_context,
l.reverse.mfirst $ λ h, do
name.mk_string s p ← return $ local_pp_name h,
guard (s.front = '_'),
cl ← infer_type h >>= is_class, guard (¬ cl),
tactic.clear h
add_tactic_doc
{ name := "clear_",
category := doc_category.tactic,
decl_names := [`tactic.interactive.clear_],
tags := ["context management"] }
/--
Acts like `have`, but removes a hypothesis with the same name as
this one. For example if the state is `h : p ⊢ goal` and `f : p → q`,
then after `replace h := f h` the goal will be `h : q ⊢ goal`,
where `have h := f h` would result in the state `h : p, h : q ⊢ goal`.
This can be used to simulate the `specialize` and `apply at` tactics
of Coq. -/
meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?)
(q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit :=
do let h := h.get_or_else `this,
old ← try_core (get_local h),
«have» h q₁ q₂,
match old, q₂ with
| none, _ := skip
| some o, some _ := tactic.clear o
| some o, none := swap >> tactic.clear o >> swap
end
add_tactic_doc
{ name := "replace",
category := doc_category.tactic,
decl_names := [`tactic.interactive.replace],
tags := ["context management"] }
/-- Make every proposition in the context decidable. -/
meta def classical := tactic.classical
add_tactic_doc
{ name := "classical",
category := doc_category.tactic,
decl_names := [`tactic.interactive.classical],
tags := ["classical logic", "type class"] }
private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def generalize_arg_p : parser (pexpr × name) :=
with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux
@[nolint def_lemma]
lemma {u} generalize_a_aux {α : Sort u}
(h : ∀ x : Sort u, (α → x) → x) : α := h α id
/--
Like `generalize` but also considers assumptions
specified by the user. The user can also specify to
omit the goal.
-/
meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":")
(p : parse generalize_arg_p)
(l : parse location) :
tactic unit :=
do h' ← get_unused_name `h,
x' ← get_unused_name `x,
g ← if ¬ l.include_goal then
do refine ``(generalize_a_aux _),
some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h')
else pure none,
n ← l.get_locals >>= tactic.revert_lst,
generalize h () p,
intron n,
match g with
| some (x',h') :=
do tactic.apply h',
tactic.clear h',
tactic.clear x'
| none := return ()
end
add_tactic_doc
{ name := "generalize_hyp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.generalize_hyp],
tags := ["context management"] }
meta def compact_decl_aux : list name → binder_info → expr → list expr →
tactic (list (list name × binder_info × expr))
| ns bi t [] := pure [(ns.reverse, bi, t)]
| ns bi t (v'@(local_const n pp bi' t') :: xs) :=
do t' ← infer_type v',
if bi = bi' ∧ t = t'
then compact_decl_aux (pp :: ns) bi t xs
else do vs ← compact_decl_aux [pp] bi' t' xs,
pure $ (ns.reverse, bi, t) :: vs
| ns bi t (_ :: xs) := compact_decl_aux ns bi t xs
/-- go from (x₀ : t₀) (x₁ : t₀) (x₂ : t₀) to (x₀ x₁ x₂ : t₀) -/
meta def compact_decl : list expr → tactic (list (list name × binder_info × expr))
| [] := pure []
| (v@(local_const n pp bi t) :: xs) :=
do t ← infer_type v,
compact_decl_aux [pp] bi t xs
| (_ :: xs) := compact_decl xs
/--
Remove identity functions from a term. These are normally
automatically generated with terms like `show t, from p` or
`(p : t)` which translate to some variant on `@id t p` in
order to retain the type.
-/
meta def clean (q : parse texpr) : tactic unit :=
do tgt : expr ← target,
e ← i_to_expr_strict ``(%%q : %%tgt),
tactic.exact $ e.clean
meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) :=
do e ← to_expr e,
t ← infer_type e,
let struct_n : name := t.get_app_fn.const_name,
fields ← expanded_field_list struct_n,
let exp_fields := fields.filter (λ x, x.2 ∈ missing),
exp_fields.mmap $ λ ⟨p,n⟩,
(prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e]
meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e :=
do some str ← pure (e.get_structure_instance_info)
| e.traverse collect_struct',
v ← monad_lift mk_mvar,
modify (list.cons (v,str)),
pure $ to_pexpr v
meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) :=
prod.map id list.reverse <$> (collect_struct' e).run []
meta def refine_one (str : structure_instance_info) :
tactic $ list (expr×structure_instance_info) :=
do tgt ← target >>= whnf,
let struct_n : name := tgt.get_app_fn.const_name,
exp_fields ← expanded_field_list struct_n,
let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names),
(src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$>
str.sources.mmap (source_fields $ missing_f.map prod.snd),
let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names),
let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names),
vs ← mk_mvar_list missing_f'.length,
(field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _),
e' ← to_expr $ pexpr.mk_structure_instance
{ struct := some struct_n
, field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names
, field_values := field_values ++ vs.map to_pexpr ++ src_field_vals },
tactic.exact e',
gs ← with_enable_tags (
mzip_with (λ (n : name × name) v, do
set_goals [v],
try (dsimp_target simp_lemmas.mk),
apply_auto_param
<|> apply_opt_param
<|> (set_main_tag [`_field,n.2,n.1]),
get_goals)
missing_f' vs),
set_goals gs.join,
return new_goals.join
meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) :=
do set_goals [e],
rs ← refine_one str,
gs ← get_goals,
gs' ← rs.mmap refine_recursively,
return $ gs'.join ++ gs
/--
`refine_struct { .. }` acts like `refine` but works only with structure instance
literals. It creates a goal for each missing field and tags it with the name of the
field so that `have_field` can be used to generically refer to the field currently
being refined.
As an example, we can use `refine_struct` to automate the construction of semigroup
instances:
```lean
refine_struct ( { .. } : semigroup α ),
-- case semigroup, mul
-- α : Type u,
-- ⊢ α → α → α
-- case semigroup, mul_assoc
-- α : Type u,
-- ⊢ ∀ (a b c : α), a * b * c = a * (b * c)
```
`have_field`, used after `refine_struct _`, poses `field` as a local constant
with the type of the field of the current goal:
```lean
refine_struct ({ .. } : semigroup α),
{ have_field, ... },
{ have_field, ... },
```
behaves like
```lean
refine_struct ({ .. } : semigroup α),
{ have field := @semigroup.mul, ... },
{ have field := @semigroup.mul_assoc, ... },
```
-/
meta def refine_struct : parse texpr → tactic unit | e :=
do (x,xs) ← collect_struct e,
refine x,
gs ← get_goals,
xs' ← xs.mmap refine_recursively,
set_goals (xs'.join ++ gs)
/--
`guard_hyp' h : t` fails if the hypothesis `h` does not have type `t`.
We use this tactic for writing tests.
Fixes `guard_hyp` by instantiating meta variables
-/
meta def guard_hyp' (n : parse ident) (p : parse $ tk ":" *> texpr) : tactic unit :=
do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p
/--
`match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern).
We use this tactic for writing tests.
-/
meta def match_hyp (n : parse ident) (p : parse $ tk ":" *> texpr) (m := reducible) :
tactic (list expr) :=
do
h ← get_local n >>= infer_type >>= instantiate_mvars,
match_expr p h m
/--
`guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast
to `guard_expr`, this tests strict (syntactic) equality.
We use this tactic for writing tests.
-/
meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do e ← to_expr p, guard (t = e)
/--
`guard_target_strict t` fails if the target of the main goal is not syntactically `t`.
We use this tactic for writing tests.
-/
meta def guard_target_strict (p : parse texpr) : tactic unit :=
do t ← target, guard_expr_strict t p
/--
`guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal
to `t`.
We use this tactic for writing tests.
-/
meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":" *> texpr) : tactic unit :=
do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p
/-- Tests that there are `n` hypotheses in the current context. -/
meta def guard_hyp_nums (n : ℕ) : tactic unit :=
do k ← local_context,
guard (n = k.length) <|> fail format!"{k.length} hypotheses found"
/-- Test that `t` is the tag of the main goal. -/
meta def guard_tags (tags : parse ident*) : tactic unit :=
do (t : list name) ← get_main_tag,
guard (t = tags)
/-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term
unifies with `p`. -/
meta def guard_proof_term (t : itactic) (p : parse texpr) : itactic :=
do
g :: _ ← get_goals,
e ← to_expr p,
t,
g ← instantiate_mvars g,
unify e g
/-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with
error message `msg` (for test writing purposes). -/
meta def success_if_fail_with_msg (tac : tactic.interactive.itactic) :=
tactic.success_if_fail_with_msg tac
/-- Get the field of the current goal. -/
meta def get_current_field : tactic name :=
do [_,field,str] ← get_main_tag,
expr.const_name <$> resolve_name (field.update_prefix str)
meta def field (n : parse ident) (tac : itactic) : tactic unit :=
do gs ← get_goals,
ts ← gs.mmap get_tag,
([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n),
set_goals [g.1],
tac, done,
set_goals $ gs'.map prod.fst
/--
`have_field`, used after `refine_struct _` poses `field` as a local constant
with the type of the field of the current goal:
```lean
refine_struct ({ .. } : semigroup α),
{ have_field, ... },
{ have_field, ... },
```
behaves like
```lean
refine_struct ({ .. } : semigroup α),
{ have field := @semigroup.mul, ... },
{ have field := @semigroup.mul_assoc, ... },
```
-/
meta def have_field : tactic unit :=
propagate_tags $
get_current_field
>>= mk_const
>>= note `field none
>> return ()
/-- `apply_field` functions as `have_field, apply field, clear field` -/
meta def apply_field : tactic unit :=
propagate_tags $
get_current_field >>= applyc
add_tactic_doc
{ name := "refine_struct",
category := doc_category.tactic,
decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field,
`tactic.interactive.have_field],
tags := ["structures"],
inherit_description_from := `tactic.interactive.refine_struct }
/--
`apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times.
`n` is optional, equal to 50 by default.
You can pass an `apply_cfg` option argument as `apply_rules hs n opt`.
(A typical usage would be with `apply_rules hs n { md := reducible })`,
which asks `apply_rules` to not unfold `semireducible` definitions (i.e. most)
when checking if a lemma matches the goal.)
`hs` can contain user attributes: in this case all theorems with this
attribute are added to the list of rules.
For instance:
```lean
@[user_attribute]
meta def mono_rules : user_attribute :=
{ name := `mono_rules,
descr := "lemmas usable to prove monotonicity" }
attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right
lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) :
a + c * e + a + c + 0 ≤ b + d * e + b + d + e :=
-- any of the following lines solve the goal:
add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3
by apply_rules [add_le_add, mul_le_mul_of_nonneg_right]
by apply_rules [mono_rules]
by apply_rules mono_rules
```
-/
meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) (opt : apply_cfg := {}) :
tactic unit :=
tactic.apply_rules hs n opt
add_tactic_doc
{ name := "apply_rules",
category := doc_category.tactic,
decl_names := [`tactic.interactive.apply_rules],
tags := ["lemma application"] }
meta def return_cast (f : option expr) (t : option (expr × expr))
(es : list (expr × expr × expr))
(e x x' eq_h : expr) :
tactic (option (expr × expr) × list (expr × expr × expr)) :=
(do guard (¬ e.has_var),
unify x x',
u ← mk_meta_univ,
f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)],
t' ← infer_type e,
some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es),
infer_type e >>= is_def_eq t,
unify f f',
return (some (f,t), (e,x',eq_h) :: es)) <|>
return (t, es)
meta def list_cast_of_aux (x : expr) (t : option (expr × expr))
(es : list (expr × expr × expr)) :
expr → tactic (option (expr × expr) × list (expr × expr × expr))
| e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h
| e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h
| e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x'
| e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h
| e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x'
| e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h
| e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h
| e := return (t,es)
meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) :=
(list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e)
private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name)
| (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x)
| _ := fail "parse error"
private meta def h_generalize_arg_p : parser (pexpr × name) :=
with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux
/--
`h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with
`x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple
times (not necessarily with the same proof), they are all replaced by `x`. `cast`
`eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated
as casts.
- `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`;
- `h_generalize Hx : e == x with _` chooses automatically chooses the name of
assumption `α = β`;
- `h_generalize! Hx : e == x` reverts `Hx`;
- when `Hx` is omitted, assumption `Hx : e == x` is not added.
-/
meta def h_generalize (rev : parse (tk "!")?)
(h : parse ident_?)
(_ : parse (tk ":"))
(arg : parse h_generalize_arg_p)
(eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) :
tactic unit :=
do let (e,n) := arg,
let h' := if h = `_ then none else h,
h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string),
e ← to_expr e,
tgt ← target,
((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found",
interactive.generalize h' () (to_pexpr e, n),
asm ← get_local h',
v ← get_local n,
hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]),
(eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do
h ← if h ≠ `_ then pure h else get_unused_name `h,
() <$ note h none eq_h ),
hs.mmap' (λ h,
do h' ← assert `h h,
tactic.exact asm,
try (rewrite_target h'),
tactic.clear h' ),
when h.is_some (do
(to_expr ``(heq_of_eq_rec_left %%eq_h %%asm)
<|> to_expr ``(heq_of_cast_eq %%eq_h %%asm))
>>= note h' none >> pure ()),
tactic.clear asm,
when rev.is_some (interactive.revert [n])
add_tactic_doc
{ name := "h_generalize",
category := doc_category.tactic,
decl_names := [`tactic.interactive.h_generalize],
tags := ["context management"] }
/-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that
this uses definitional equality instead of alpha-equivalence. -/
meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit :=
do e ← to_expr p, is_def_eq t e
/--
`guard_target' t` fails if the target of the main goal is not definitionally equal to `t`.
We use this tactic for writing tests.
The difference with `guard_target` is that this uses definitional equality instead of
alpha-equivalence.
-/
meta def guard_target' (p : parse texpr) : tactic unit :=
do t ← target, guard_expr_eq' t p
add_tactic_doc
{ name := "guard_target'",
category := doc_category.tactic,
decl_names := [`tactic.interactive.guard_target'],
tags := ["testing"] }
/--
a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true,
unfolding only `reducible` constants. -/
meta def triv : tactic unit :=
tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed"
add_tactic_doc
{ name := "triv",
category := doc_category.tactic,
decl_names := [`tactic.interactive.triv],
tags := ["finishing"] }
/--
Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. It
will then try to close the new goal using `triv`, or try to simplify it by applying `exists_prop`.
Unlike `existsi`, `x` is elaborated with respect to the expected type.
`use` will alternatively take a list of terms `[x0, ..., xn]`.
`use` will work with constructors of arbitrary inductive types.
Examples:
```lean
example (α : Type) : ∃ S : set α, S = S :=
by use ∅
example : ∃ x : ℤ, x = x :=
by use 42
example : ∃ n > 0, n = n :=
begin
use 1,
-- goal is now 1 > 0 ∧ 1 = 1, whereas it would be ∃ (H : 1 > 0), 1 = 1 after existsi 1.
exact ⟨zero_lt_one, rfl⟩,
end
example : ∃ a b c : ℤ, a + b + c = 6 :=
by use [1, 2, 3]
example : ∃ p : ℤ × ℤ, p.1 = 1 :=
by use ⟨1, 42⟩
example : Σ x y : ℤ, (ℤ × ℤ) × ℤ :=
by use [1, 2, 3, 4, 5]
inductive foo
| mk : ℕ → bool × ℕ → ℕ → foo
example : foo :=
by use [100, tt, 4, 3]
```
-/
meta def use (l : parse pexpr_list_or_texpr) : tactic unit :=
focus1 $
tactic.use l;
try (triv <|> (do
`(Exists %%p) ← target,
to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip))
add_tactic_doc
{ name := "use",
category := doc_category.tactic,
decl_names := [`tactic.interactive.use, `tactic.interactive.existsi],
tags := ["logic"],
inherit_description_from := `tactic.interactive.use }
/--
`clear_aux_decl` clears every `aux_decl` in the local context for the current goal.
This includes the induction hypothesis when using the equation compiler and
`_let_match` and `_fun_match`.
It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these
auxiliary declarations, and produce an error saying the recursion is not well founded.
```lean
example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n :=
let ⟨a, ha⟩ := h₂ in
begin
clear_aux_decl, -- subst will fail without this line
subst h₁
end
example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y :=
let ⟨n, hn⟩ := h₁ in
begin
clear_aux_decl, -- finish produces an error without this line
finish
end
```
-/
meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl
add_tactic_doc
{ name := "clear_aux_decl",
category := doc_category.tactic,
decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl],
tags := ["context management"],
inherit_description_from := `tactic.interactive.clear_aux_decl }
meta def loc.get_local_pp_names : loc → tactic (list name)
| loc.wildcard := list.map expr.local_pp_name <$> local_context
| (loc.ns l) := return l.reduce_option
meta def loc.get_local_uniq_names (l : loc) : tactic (list name) :=
list.map expr.local_uniq_name <$> l.get_locals
/--
The logic of `change x with y at l` fails when there are dependencies.
`change'` mimics the behavior of `change`, except in the case of `change x with y at l`.
In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses
in `l`. As long as `x` and `y` are defeq, it should never fail.
-/
meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit
| none (loc.ns [none]) := do e ← i_to_expr q, change_core e none
| none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh)
| none _ := fail "change-at does not support multiple locations"
| (some w) l :=
do l' ← loc.get_local_pp_names l,
l'.mmap' (λ e, try (change_with_at q w e)),
when l.include_goal $ change q w (loc.ns [none])
add_tactic_doc
{ name := "change'",
category := doc_category.tactic,
decl_names := [`tactic.interactive.change', `tactic.interactive.change],
tags := ["renaming"],
inherit_description_from := `tactic.interactive.change' }
private meta def opt_dir_with : parser (option (bool × name)) :=
(do tk "with",
arrow ← (tk "<-")?,
h ← ident,
return (arrow.is_some, h)) <|> return none
/--
`set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to
the local context and replaces `t` with `a` everywhere it can.
`set a := t with ←h` will add `h : t = a` instead.
`set! a := t with h` does not do any replacing.
```lean
example (x : ℕ) (h : x = 3) : x + x + x = 9 :=
begin
set y := x with ←h_xy,
/-
x : ℕ,
y : ℕ := x,
h_xy : x = y,
h : y = 3
⊢ y + y + y = 9
-/
end
```
-/
meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?)
(_ : parse (tk ":=")) (pv : parse texpr)
(rev_name : parse opt_dir_with) :=
do tp ← i_to_expr $ tp.get_or_else pexpr.mk_placeholder,
pv ← to_expr ``(%%pv : %%tp),
tp ← instantiate_mvars tp,
definev a tp pv,
when h_simp.is_none $ change' ``(%%pv) (some (expr.const a [])) $ interactive.loc.wildcard,
match rev_name with
| some (flip, id) :=
do nv ← get_local a,
mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id,
reflexivity
| none := skip
end
add_tactic_doc
{ name := "set",
category := doc_category.tactic,
decl_names := [`tactic.interactive.set],
tags := ["context management"] }
/--
`clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`.
-/
meta def clear_except (xs : parse ident *) : tactic unit :=
do n ← xs.mmap (try_core ∘ get_local) >>= revert_lst ∘ list.filter_map id,
ls ← local_context,
ls.reverse.mmap' $ try ∘ tactic.clear,
intron_no_renames n
add_tactic_doc
{ name := "clear_except",
category := doc_category.tactic,
decl_names := [`tactic.interactive.clear_except],
tags := ["context management"] }
meta def format_names (ns : list name) : format :=
format.join $ list.intersperse " " (ns.map to_fmt)
private meta def indent_bindents (l r : string) : option (list name) → expr → tactic format
| none e :=
do e ← pp e,
pformat!"{l}{format.nest l.length e}{r}"
| (some ns) e :=
do e ← pp e,
let ns := format_names ns,
let margin := l.length + ns.to_string.length + " : ".length,
pformat!"{l}{ns} : {format.nest margin e}{r}"
private meta def format_binders : list name × binder_info × expr → tactic format
| (ns, binder_info.default, t) := indent_bindents "(" ")" ns t
| (ns, binder_info.implicit, t) := indent_bindents "{" "}" ns t
| (ns, binder_info.strict_implicit, t) := indent_bindents "⦃" "⦄" ns t
| ([n], binder_info.inst_implicit, t) :=
if "_".is_prefix_of n.to_string
then indent_bindents "[" "]" none t
else indent_bindents "[" "]" [n] t
| (ns, binder_info.inst_implicit, t) := indent_bindents "[" "]" ns t
| (ns, binder_info.aux_decl, t) := indent_bindents "(" ")" ns t
private meta def partition_vars' (s : name_set) :
list expr → list expr → list expr → tactic (list expr × list expr)
| [] as bs := pure (as.reverse, bs.reverse)
| (x :: xs) as bs :=
do t ← infer_type x,
if t.has_local_in s then partition_vars' xs as (x :: bs)
else partition_vars' xs (x :: as) bs
private meta def partition_vars : tactic (list expr × list expr) :=
do ls ← local_context,
partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] []
/--
Format the current goal as a stand-alone example. Useful for testing tactics
or creating [minimal working examples](https://leanprover-community.github.io/mwe.html).
* `extract_goal`: formats the statement as an `example` declaration
* `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration
called `my_decl`
* `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration
Examples:
```lean
example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k :=
begin
extract_goal,
-- prints:
-- example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k :=
-- begin
-- admit,
-- end
extract_goal my_lemma
-- prints:
-- lemma my_lemma (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k :=
-- begin
-- admit,
-- end
end
example {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k :=
begin
extract_goal my_lemma,
-- prints:
-- lemma my_lemma {i j k x y z w p q r m n : ℕ}
-- (h₀ : i ≤ j)
-- (h₁ : j ≤ k)
-- (h₁ : k ≤ p)
-- (h₁ : p ≤ q) :
-- i ≤ k :=
-- begin
-- admit,
-- end
extract_goal my_lemma with i j k
-- prints:
-- lemma my_lemma {p i j k : ℕ}
-- (h₀ : i ≤ j)
-- (h₁ : j ≤ k)
-- (h₁ : k ≤ p) :
-- i ≤ k :=
-- begin
-- admit,
-- end
end
example : true :=
begin
let n := 0,
have m : ℕ, admit,
have k : fin n, admit,
have : n + m + k.1 = 0, extract_goal,
-- prints:
-- example (m : ℕ) : let n : ℕ := 0 in ∀ (k : fin n), n + m + k.val = 0 :=
-- begin
-- intros n k,
-- admit,
-- end
end
```
-/
meta def extract_goal (print_use : parse $ tt <$ tk "!" <|> pure ff)
(n : parse ident?) (vs : parse (tk "with" *> ident*)?)
: tactic unit :=
do tgt ← target,
solve_aux tgt $ do {
((cxt₀,cxt₁,ls,tgt),_) ← solve_aux tgt $ do {
vs.mmap clear_except,
ls ← local_context,
ls ← ls.mfilter $ succeeds ∘ is_local_def,
n ← revert_lst ls,
(c₀,c₁) ← partition_vars,
tgt ← target,
ls ← intron' n,
pure (c₀,c₁,ls,tgt) },
is_prop ← is_prop tgt,
let title := match n, is_prop with
| none, _ := to_fmt "example"
| (some n), tt := format!"lemma {n}"
| (some n), ff := format!"def {n}"
end,
cxt₀ ← compact_decl cxt₀ >>= list.mmap format_binders,
cxt₁ ← compact_decl cxt₁ >>= list.mmap format_binders,
stmt ← pformat!"{tgt} :=",
let fmt :=
format.group $ format.nest 2 $
title ++ cxt₀.foldl (λ acc x, acc ++ format.group (format.line ++ x)) "" ++
format.join (list.map (λ x, format.line ++ x) cxt₁) ++ " :" ++
format.line ++ stmt,
trace $ fmt.to_string $ options.mk.set_nat `pp.width 80,
let var_names := format.intercalate " " $ ls.map (to_fmt ∘ local_pp_name),
let call_intron := if ls.empty
then to_fmt ""
else format!"\n intros {var_names},",
trace!"begin{call_intron}\n admit,\nend\n" },
skip
add_tactic_doc
{ name := "extract_goal",
category := doc_category.tactic,
decl_names := [`tactic.interactive.extract_goal],
tags := ["goal management", "proof extraction", "debugging"] }
/--
`inhabit α` tries to derive a `nonempty α` instance and then upgrades this
to an `inhabited α` instance.
If the target is a `Prop`, this is done constructively;
otherwise, it uses `classical.choice`.
```lean
example (α) [nonempty α] : ∃ a : α, true :=
begin
inhabit α,
existsi default α,
trivial
end
```
-/
meta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit :=
do ty ← i_to_expr t,
nm ← returnopt inst_name <|> get_unused_name `inst,
tgt ← target,
tgt_is_prop ← is_prop tgt,
if tgt_is_prop then do
decorate_error "could not infer nonempty instance:" $
mk_mapp ``nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply,
introI nm
else do
decorate_error "could not infer nonempty instance:" $
mk_mapp ``classical.inhabited_of_nonempty' [ty, none] >>= note nm none,
resetI
add_tactic_doc
{ name := "inhabit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.inhabit],
tags := ["context management", "type class"] }
/-- `revert_deps n₁ n₂ ...` reverts all the hypotheses that depend on one of `n₁, n₂, ...`
It does not revert `n₁, n₂, ...` themselves (unless they depend on another `nᵢ`). -/
meta def revert_deps (ns : parse ident*) : tactic unit :=
propagate_tags $
ns.mmap get_local >>= revert_reverse_dependencies_of_hyps >> skip
add_tactic_doc
{ name := "revert_deps",
category := doc_category.tactic,
decl_names := [`tactic.interactive.revert_deps],
tags := ["context management", "goal management"] }
/-- `revert_after n` reverts all the hypotheses after `n`. -/
meta def revert_after (n : parse ident) : tactic unit :=
propagate_tags $ get_local n >>= tactic.revert_after >> skip
add_tactic_doc
{ name := "revert_after",
category := doc_category.tactic,
decl_names := [`tactic.interactive.revert_after],
tags := ["context management", "goal management"] }
/-- Reverts all local constants on which the target depends (recursively). -/
meta def revert_target_deps : tactic unit :=
propagate_tags $ tactic.revert_target_deps >> skip
add_tactic_doc
{ name := "revert_target_deps",
category := doc_category.tactic,
decl_names := [`tactic.interactive.revert_target_deps],
tags := ["context management", "goal management"] }
/-- `clear_value n₁ n₂ ...` clears the bodies of the local definitions `n₁, n₂ ...`, changing them
into regular hypotheses. A hypothesis `n : α := t` is changed to `n : α`. -/
meta def clear_value (ns : parse ident*) : tactic unit :=
propagate_tags $ ns.reverse.mmap get_local >>= tactic.clear_value
add_tactic_doc
{ name := "clear_value",
category := doc_category.tactic,
decl_names := [`tactic.interactive.clear_value],
tags := ["context management"] }
/--
`generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of
the same type.
`generalize' h : e = x` in addition registers the hypothesis `h : e = x`.
`generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also
succeeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis
`x` is not a local definition.
-/
meta def generalize' (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) :
tactic unit :=
propagate_tags $
do let (p, x) := p,
e ← i_to_expr p,
some h ← pure h | tactic.generalize' e x >> skip,
-- `h` is given, the regular implementation of `generalize` works.
tgt ← target,
tgt' ← do {
⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target),
to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) }
<|> to_expr ``(Π x, %%e = x → %%tgt),
t ← assert h tgt',
swap,
exact ``(%%t %%e rfl),
intro x,
intro h
add_tactic_doc
{ name := "generalize'",
category := doc_category.tactic,
decl_names := [`tactic.interactive.generalize'],
tags := ["context management"] }
/--
If the expression `q` is a local variable with type `x = t` or `t = x`, where `x` is a local
constant, `tactic.interactive.subst' q` substitutes `x` by `t` everywhere in the main goal and
then clears `q`.
If `q` is another local variable, then we find a local constant with type `q = t` or `t = q` and
substitute `t` for `q`.
Like `tactic.interactive.subst`, but fails with a nicer error message if the substituted variable is
a local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib.
-/
meta def subst' (q : parse texpr) : tactic unit := do
i_to_expr q >>= tactic.subst' >> try (tactic.reflexivity reducible)
add_tactic_doc
{ name := "subst'",
category := doc_category.tactic,
decl_names := [`tactic.interactive.subst'],
tags := ["context management"] }
end interactive
end tactic
|
6f75d0ef75cdb1e00a37c24c61d22bdc25388bfe | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/coe6.lean | 66fa38f99480baa393bff94547ceae6571003581 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 340 | lean | import data.unit
open unit
constant int : Type.{1}
constant nat : Type.{1}
constant izero : int
constant nzero : nat
constant isucc : int → int
constant nsucc : nat → nat
definition f [coercion] (a : unit) : int := izero
definition g [coercion] (a : unit) : nat := nzero
set_option pp.coercions true
check isucc star
check nsucc star
|
37aa2f938cd919b1cb87bf1e439f3c91a6fadde1 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /archive/examples/prop_encodable.lean | 250a3d6055ffc5eae40e79f64953fff4aa153a87 | [
"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 | 2,983 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import data.W
/-!
# W types
The file `data/W.lean` shows that if `α` is an an encodable fintype and for every `a : α`,
`β a` is encodable, then `W β` is encodable.
As an example of how this can be used, we show that the type of propositional formulas with
variables labeled from an encodable type is encodable.
The strategy is to define a type of labels corresponding to the constructors.
From the definition (using `sum`, `unit`, and an encodable type), Lean can infer
that it is encodable. We then define a map from propositional formulas to the
corresponding `Wfin` type, and show that map has a left inverse.
We mark the auxiliary constructions `private`, since their only purpose is to
show encodability.
-/
/-- Propositional formulas with labels from `α`. -/
inductive prop_form (α : Type*)
| var : α → prop_form
| not : prop_form → prop_form
| and : prop_form → prop_form → prop_form
| or : prop_form → prop_form → prop_form
/-!
The next three functions make it easier to construct functions from a small
`fin`.
-/
section
variable {α : Type*}
/-- the trivial function out of `fin 0`. -/
def mk_fn0 : fin 0 → α
| ⟨_, h⟩ := absurd h dec_trivial
/-- defines a function out of `fin 1` -/
def mk_fn1 (t : α) : fin 1 → α
| ⟨0, _⟩ := t
| ⟨n+1, h⟩ := absurd h dec_trivial
/-- defines a function out of `fin 2` -/
def mk_fn2 (s t : α) : fin 2 → α
| ⟨0, _⟩ := s
| ⟨1, _⟩ := t
| ⟨n+2, h⟩ := absurd h dec_trivial
attribute [simp] mk_fn0 mk_fn1 mk_fn2
end
namespace prop_form
private def constructors (α : Type*) := α ⊕ unit ⊕ unit ⊕ unit
local notation `cvar` a := sum.inl a
local notation `cnot` := sum.inr (sum.inl unit.star)
local notation `cand` := sum.inr (sum.inr (sum.inr unit.star))
local notation `cor` := sum.inr (sum.inr (sum.inl unit.star))
@[simp]
private def arity (α : Type*) : constructors α → nat
| (cvar a) := 0
| cnot := 1
| cand := 2
| cor := 2
variable {α : Type*}
private def f : prop_form α → W_type (λ i, fin (arity α i))
| (var a) := ⟨cvar a, mk_fn0⟩
| (not p) := ⟨cnot, mk_fn1 (f p)⟩
| (and p q) := ⟨cand, mk_fn2 (f p) (f q)⟩
| (or p q) := ⟨cor, mk_fn2 (f p) (f q)⟩
private def finv : W_type (λ i, fin (arity α i)) → prop_form α
| ⟨cvar a, fn⟩ := var a
| ⟨cnot, fn⟩ := not (finv (fn ⟨0, dec_trivial⟩))
| ⟨cand, fn⟩ := and (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩))
| ⟨cor, fn⟩ := or (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩))
instance [encodable α] : encodable (prop_form α) :=
begin
haveI : encodable (constructors α) :=
by { unfold constructors, apply_instance },
exact encodable.of_left_inverse f finv
(by { intro p, induction p; simp [f, finv, *] })
end
end prop_form
|
b84bf0887910e9957a02e0db5f2088fcd9462c67 | 54d7e71c3616d331b2ec3845d31deb08f3ff1dea | /library/init/meta/smt/smt_tactic.lean | 9d908f00d65732e8cdb0e351bf56424a834a5fe6 | [
"Apache-2.0"
] | permissive | pachugupta/lean | 6f3305c4292288311cc4ab4550060b17d49ffb1d | 0d02136a09ac4cf27b5c88361750e38e1f485a1a | refs/heads/master | 1,611,110,653,606 | 1,493,130,117,000 | 1,493,167,649,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,120 | 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.category
import init.meta.simp_tactic
import init.meta.smt.congruence_closure
import init.meta.smt.ematch
universe u
run_cmd mk_simp_attr `pre_smt
run_cmd mk_hinst_lemma_attr_set `ematch [] [`ematch_lhs]
/--
Configuration for the smt tactic preprocessor. The preprocessor
is applied whenever a new hypothesis is introduced.
- simp_attr: is the attribute name for the simplification lemmas
that are used during the preprocessing step.
- max_steps: it is the maximum number of steps performed by the simplifier.
- zeta: if tt, then zeta reduction (i.e., unfolding let-expressions)
is used during preprocessing.
-/
structure smt_pre_config :=
(simp_attr : name := `pre_smt)
(max_steps : nat := 1000000)
(zeta : bool := ff)
/--
Configuration for the smt_state object.
- em_attr: is the attribute name for the hinst_lemmas
that are used for ematching -/
structure smt_config :=
(cc_cfg : cc_config := {})
(em_cfg : ematch_config := {})
(pre_cfg : smt_pre_config := {})
(em_attr : name := `ematch)
meta def smt_config.set_classical (c : smt_config) (b : bool) : smt_config :=
{c with cc_cfg := { (c.cc_cfg) with em := b}}
meta constant smt_goal : Type
meta def smt_state :=
list smt_goal
meta constant smt_state.mk : smt_config → tactic smt_state
meta constant smt_state.to_format : smt_state → tactic_state → format
/-- Return tt iff classical excluded middle was enabled at smt_state.mk -/
meta constant smt_state.classical : smt_state → bool
meta def smt_tactic :=
state_t smt_state tactic
meta instance : has_append smt_state :=
list.has_append
meta instance : monad smt_tactic :=
state_t.monad _ _
/- We don't use the default state_t lift operation because only
tactics that do not change hypotheses can be automatically lifted to smt_tactic. -/
meta constant tactic_to_smt_tactic (α : Type) : tactic α → smt_tactic α
meta instance : monad.has_monad_lift tactic smt_tactic :=
⟨tactic_to_smt_tactic⟩
meta instance (α : Type) : has_coe (tactic α) (smt_tactic α) :=
⟨monad.monad_lift⟩
meta def smt_tactic_orelse {α : Type} (t₁ t₂ : smt_tactic α) : smt_tactic α :=
λ ss ts, result.cases_on (t₁ ss ts)
result.success
(λ e₁ ref₁ s', result.cases_on (t₂ ss ts)
result.success
result.exception)
meta instance : monad_fail smt_tactic :=
{ smt_tactic.monad with fail := λ α s, (tactic.fail (to_fmt s) : smt_tactic α) }
meta instance : alternative smt_tactic :=
{ smt_tactic.monad with
failure := λ α, @tactic.failed α,
orelse := @smt_tactic_orelse }
namespace smt_tactic
open tactic (transparency)
meta constant intros : smt_tactic unit
meta constant intron : nat → smt_tactic unit
meta constant intro_lst : list name → smt_tactic unit
/--
Try to close main goal by using equalities implied by the congruence
closure module.
-/
meta constant close : smt_tactic unit
/--
Produce new facts using heuristic lemma instantiation based on E-matching.
This tactic tries to match patterns from lemmas in the main goal with terms
in the main goal. The set of lemmas is populated with theorems
tagged with the attribute specified at smt_config.em_attr, and lemmas
added using tactics such as `smt_tactic.add_lemmas`.
The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`.
Remark: the given predicate is applied to every new instance. The instance
is only added to the state if the predicate returns tt.
-/
meta constant ematch_core : (expr → bool) → smt_tactic unit
/--
Produce new facts using heuristic lemma instantiation based on E-matching.
This tactic tries to match patterns from the given lemmas with terms in
the main goal.
-/
meta constant ematch_using : hinst_lemmas → smt_tactic unit
meta constant mk_ematch_eqn_lemmas_for_core : transparency → name → smt_tactic hinst_lemmas
meta constant to_cc_state : smt_tactic cc_state
meta constant to_em_state : smt_tactic ematch_state
meta constant get_config : smt_tactic smt_config
/--
Preprocess the given term using the same simplifications rules used when
we introduce a new hypothesis. The result is pair containing the resulting
term and a proof that it is equal to the given one.
-/
meta constant preprocess : expr → smt_tactic (expr × expr)
meta constant get_lemmas : smt_tactic hinst_lemmas
meta constant set_lemmas : hinst_lemmas → smt_tactic unit
meta constant add_lemmas : hinst_lemmas → smt_tactic unit
meta def add_ematch_lemma_core (md : transparency) (as_simp : bool) (e : expr) : smt_tactic unit :=
do h ← hinst_lemma.mk_core md e as_simp,
add_lemmas (mk_hinst_singleton h)
meta def add_ematch_lemma_from_decl_core (md : transparency) (as_simp : bool) (n : name) : smt_tactic unit :=
do h ← hinst_lemma.mk_from_decl_core md n as_simp,
add_lemmas (mk_hinst_singleton h)
meta def add_ematch_eqn_lemmas_for_core (md : transparency) (n : name) : smt_tactic unit :=
do hs ← mk_ematch_eqn_lemmas_for_core md n,
add_lemmas hs
meta def ematch : smt_tactic unit :=
ematch_core (λ _, tt)
meta def failed {α} : smt_tactic α :=
tactic.failed
meta def fail {α : Type} {β : Type u} [has_to_format β] (msg : β) : tactic α :=
tactic.fail msg
meta def try {α : Type} (t : smt_tactic α) : smt_tactic unit :=
λ ss ts, result.cases_on (t ss ts)
(λ ⟨a, new_ss⟩, result.success ((), new_ss))
(λ e ref s', result.success ((), ss) ts)
/- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/
meta def repeat_at_most : nat → smt_tactic unit → smt_tactic unit
| 0 t := return ()
| (n+1) t := (do t, repeat_at_most n t) <|> return ()
/-- (repeat_exactly n t) : execute t n times -/
meta def repeat_exactly : nat → smt_tactic unit → smt_tactic unit
| 0 t := return ()
| (n+1) t := do t, repeat_exactly n t
meta def repeat : smt_tactic unit → smt_tactic unit :=
repeat_at_most 100000
meta def eblast : smt_tactic unit :=
repeat (ematch >> try close)
open tactic
protected meta def read : smt_tactic (smt_state × tactic_state) :=
do s₁ ← state_t.read,
s₂ ← tactic.read,
return (s₁, s₂)
protected meta def write : smt_state × tactic_state → smt_tactic unit :=
λ ⟨ss, ts⟩ _ _, result.success ((), ss) ts
private meta def mk_smt_goals_for (cfg : smt_config) : list expr → list smt_goal → list expr
→ tactic (list smt_goal × list expr)
| [] sr tr := return (sr.reverse, tr.reverse)
| (tg::tgs) sr tr := do
tactic.set_goals [tg],
[new_sg] ← smt_state.mk cfg | tactic.failed,
[new_tg] ← get_goals | tactic.failed,
mk_smt_goals_for tgs (new_sg::sr) (new_tg::tr)
/- See slift -/
meta def slift_aux {α : Type} (t : tactic α) (cfg : smt_config) : smt_tactic α :=
λ ss, do
_::sgs ← return ss | fail "slift tactic failed, there no smt goals to be solved",
tg::tgs ← tactic.get_goals | tactic.failed,
tactic.set_goals [tg], a ← t,
new_tgs ← tactic.get_goals,
(new_sgs, new_tgs) ← mk_smt_goals_for cfg new_tgs [] [],
tactic.set_goals (new_tgs ++ tgs),
return (a, new_sgs ++ sgs)
/--
This lift operation will restart the SMT state.
It is useful for using tactics that change the set of hypotheses. -/
meta def slift {α : Type} (t : tactic α) : smt_tactic α :=
get_config >>= slift_aux t
meta def trace_state : smt_tactic unit :=
do (s₁, s₂) ← smt_tactic.read,
trace (smt_state.to_format s₁ s₂)
meta def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic unit :=
tactic.trace a
meta def to_expr (q : pexpr) (allow_mvars := tt) : smt_tactic expr :=
tactic.to_expr q allow_mvars
meta def classical : smt_tactic bool :=
do s ← state_t.read,
return s.classical
meta def num_goals : smt_tactic nat :=
λ ss, return (ss.length, ss)
/- Low level primitives for managing set of goals -/
meta def get_goals : smt_tactic (list smt_goal × list expr) :=
do (g₁, _) ← smt_tactic.read,
g₂ ← tactic.get_goals,
return (g₁, g₂)
meta def set_goals : list smt_goal → list expr → smt_tactic unit :=
λ g₁ g₂ ss, tactic.set_goals g₂ >> return ((), g₁)
private meta def all_goals_core (tac : smt_tactic unit) : list smt_goal → list expr → list smt_goal → list expr → smt_tactic unit
| [] ts acs act := set_goals acs (ts ++ act)
| (s :: ss) [] acs act := fail "ill-formed smt_state"
| (s :: ss) (t :: ts) acs act :=
do set_goals [s] [t],
tac,
(new_ss, new_ts) ← get_goals,
all_goals_core ss ts (acs ++ new_ss) (act ++ new_ts)
/- Apply the given tactic to all goals. -/
meta def all_goals (tac : smt_tactic unit) : smt_tactic unit :=
do (ss, ts) ← get_goals,
all_goals_core tac ss ts [] []
/- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/
meta def seq (tac1 : smt_tactic unit) (tac2 : smt_tactic unit) : smt_tactic unit :=
do (s::ss, t::ts) ← get_goals,
set_goals [s] [t],
tac1, all_goals tac2,
(new_ss, new_ts) ← get_goals,
set_goals (new_ss ++ ss) (new_ts ++ ts)
meta instance : has_andthen (smt_tactic unit) :=
⟨seq⟩
meta def focus1 {α} (tac : smt_tactic α) : smt_tactic α :=
do (s::ss, t::ts) ← get_goals,
match ss with
| [] := tac
| _ := do
set_goals [s] [t],
a ← tac,
(ss', ts') ← get_goals,
set_goals (ss' ++ ss) (ts' ++ ts),
return a
end
meta def solve1 (tac : smt_tactic unit) : smt_tactic unit :=
do (ss, gs) ← get_goals,
match ss, gs with
| [], _ := fail "solve1 tactic failed, there isn't any goal left to focus"
| _, [] := fail "solve1 tactic failed, there isn't any smt goal left to focus"
| s::ss, g::gs :=
do set_goals [s] [g],
tac,
(ss', gs') ← get_goals,
match ss', gs' with
| [], [] := set_goals ss gs
| _, _ := fail "solve1 tactic failed, focused goal has not been solved"
end
end
meta def swap : smt_tactic unit :=
do (ss, ts) ← get_goals,
match ss, ts with
| (s₁ :: s₂ :: ss), (t₁ :: t₂ :: ts) := set_goals (s₂ :: s₁ :: ss) (t₂ :: t₁ :: ts)
| _, _ := failed
end
/-- Add a new goal for t, and the hypothesis (h : t) in the current goal. -/
meta def assert (h : name) (t : expr) : smt_tactic unit :=
tactic.assert_core h t >> swap >> intros >> swap >> try close
/-- Add the hypothesis (h : t) in the current goal if v has type t. -/
meta def assertv (h : name) (t : expr) (v : expr) : smt_tactic unit :=
tactic.assertv_core h t v >> intros >> return ()
/-- Add a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/
meta def define (h : name) (t : expr) : smt_tactic unit :=
tactic.define_core h t >> swap >> intros >> swap >> try close
/-- Add the hypothesis (h : t := v) in the current goal if v has type t. -/
meta def definev (h : name) (t : expr) (v : expr) : smt_tactic unit :=
tactic.definev_core h t v >> intros >> return ()
/-- Add (h : t := pr) to the current goal -/
meta def pose (h : name) (pr : expr) : smt_tactic unit :=
do t ← tactic.infer_type pr,
definev h t pr
/- Add (h : t) to the current goal, given a proof (pr : t) -/
meta def note (n : name) (pr : expr) : smt_tactic unit :=
do t ← tactic.infer_type pr,
assertv n t pr
meta def destruct (e : expr) : smt_tactic unit :=
smt_tactic.seq (tactic.destruct e) smt_tactic.intros
meta def by_cases (e : expr) : smt_tactic unit :=
do c ← classical,
if c then
destruct (expr.app (expr.const `classical.em []) e)
else do
dec_e ← (mk_app `decidable [e] <|> fail "by_cases smt_tactic failed, type is not a proposition"),
inst ← (mk_instance dec_e <|> fail "by_cases smt_tactic failed, type of given expression is not decidable"),
em ← mk_app `decidable.em [e, inst],
destruct em
meta def by_contradiction : smt_tactic unit :=
do t ← target,
c ← classical,
if t.is_false then skip
else if c then do
apply (expr.app (expr.const `classical.by_contradiction []) t),
intros
else do
dec_t ← (mk_app `decidable [t] <|> fail "by_contradiction smt_tactic failed, target is not a proposition"),
inst ← (mk_instance dec_t <|> fail "by_contradiction smt_tactic failed, target is not decidable"),
a ← mk_mapp `decidable.by_contradiction [some t, some inst],
apply a,
intros
/- Return a proof for e, if 'e' is a known fact in the main goal. -/
meta def proof_for (e : expr) : smt_tactic expr :=
do cc ← to_cc_state, cc.proof_for e
/- Return a refutation for e (i.e., a proof for (not e)), if 'e' has been refuted in the main goal. -/
meta def refutation_for (e : expr) : smt_tactic expr :=
do cc ← to_cc_state, cc.refutation_for e
meta def get_facts : smt_tactic (list expr) :=
do cc ← to_cc_state,
return $ cc.eqc_of expr.mk_true
meta def get_refuted_facts : smt_tactic (list expr) :=
do cc ← to_cc_state,
return $ cc.eqc_of expr.mk_false
meta def add_ematch_lemma : expr → smt_tactic unit :=
add_ematch_lemma_core reducible ff
meta def add_ematch_lhs_lemma : expr → smt_tactic unit :=
add_ematch_lemma_core reducible tt
meta def add_ematch_lemma_from_decl : name → smt_tactic unit :=
add_ematch_lemma_from_decl_core reducible ff
meta def add_ematch_lhs_lemma_from_decl : name → smt_tactic unit :=
add_ematch_lemma_from_decl_core reducible ff
meta def add_ematch_eqn_lemmas_for : name → smt_tactic unit :=
add_ematch_eqn_lemmas_for_core reducible
meta def add_lemmas_from_facts_core : list expr → smt_tactic unit
| [] := return ()
| (f::fs) := do
try (is_prop f >> guard (f.is_pi && bnot (f.is_arrow)) >> proof_for f >>= add_ematch_lemma_core reducible ff),
add_lemmas_from_facts_core fs
meta def add_lemmas_from_facts : smt_tactic unit :=
get_facts >>= add_lemmas_from_facts_core
meta def induction (e : expr) (ids : list name := []) (rec : option name := none) : smt_tactic unit :=
slift (tactic.induction e ids rec >> return ()) -- pass on the information?
meta def when (c : Prop) [decidable c] (tac : smt_tactic unit) : smt_tactic unit :=
if c then tac else skip
meta def when_tracing (n : name) (tac : smt_tactic unit) : smt_tactic unit :=
when (is_trace_enabled_for n = tt) tac
end smt_tactic
open smt_tactic
meta def using_smt {α} (t : smt_tactic α) (cfg : smt_config := {}) : tactic α :=
do ss ← smt_state.mk cfg,
(a, _) ← (do a ← t, repeat close, return a) ss,
return a
meta def using_smt_with {α} (cfg : smt_config) (t : smt_tactic α) : tactic α :=
using_smt t cfg
|
419f07a2ff082bf1b3c1fce59ffa9fd99159f9b1 | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/exercises_sources/thursday/afternoon/category_theory/exercise9.lean | 8bd8c5460d6c17d62ad489c417478b13a2e122d3 | [] | permissive | Vtec234/lftcm2020 | ad2610ab614beefe44acc5622bb4a7fff9a5ea46 | bbbd4c8162f8c2ef602300ab8fdeca231886375d | refs/heads/master | 1,668,808,098,623 | 1,594,989,081,000 | 1,594,990,079,000 | 280,423,039 | 0 | 0 | MIT | 1,594,990,209,000 | 1,594,990,209,000 | null | UTF-8 | Lean | false | false | 2,684 | lean | import category_theory.limits.shapes.biproducts
/-!
Let's show that every preadditive category embeds into a preadditive category with biproducts,
and identify a good universal property.
This is a more advanced exercise, for which I've indicated a suggested structure,
but not written a full solution. I hope this structure will work out!
-/
universes v u
variables (C : Type u)
structure additive_envelope :=
(ι : Type v)
[fintype : fintype ι]
[decidable_eq : decidable_eq ι]
(val : ι → C)
attribute [instance] additive_envelope.fintype additive_envelope.decidable_eq
variables {C}
def dmatrix {X Y : additive_envelope C} (Z : X.ι → Y.ι → Type*) := Π (i : X.ι) (j : Y.ι), Z i j
-- You may need to develop some API for `dmatrix`, parallel to that in `data.matrix.basic`.
-- One thing you'll certainly need is an "extensionality" lemma,
-- showing that you can prove two `dmatrix`s are equal by checking componentwise.
open category_theory
variables [category.{v} C] [preadditive C]
namespace family
def hom (X Y : additive_envelope C) := dmatrix (λ i j, X.val i ⟶ Y.val j)
open_locale big_operators
instance : category.{v (max u (v+1))} (additive_envelope.{v} C) :=
{ hom := hom,
id := λ X i j, if h : i = j then eq_to_hom (by subst h) else 0,
comp := λ X Y Z f g i k, ∑ (j : Y.ι), f i j ≫ g j k,
id_comp' := sorry,
comp_id' := sorry,
assoc' := sorry, }
variables (C)
@[simps]
def embedding : C ⥤ additive_envelope.{v} C :=
{ obj := λ X, ⟨punit.{v+1}, λ _, X⟩,
map := λ X Y f _ _, f,
map_id' := sorry,
map_comp' := sorry, }
lemma embedding.faithful : faithful (embedding C) :=
sorry
instance : preadditive (additive_envelope.{v} C) :=
sorry -- probably best to go back and make `dmatrix` an `add_comm_group` first.
open category_theory.limits
instance : has_finite_biproducts (additive_envelope.{v} C) :=
{ has_biproducts_of_shape := λ J _ _,
by exactI -- this makes the `fintype` and `decidable_eq` instances on `J` available
{ has_biproduct := λ F,
{ bicone :=
{ X :=
{ ι := Σ (j : J), (F j).ι,
val := λ p, (F p.1).val p.2 },
ι := sorry,
π := sorry,
ι_π := sorry, },
is_limit := sorry,
is_colimit := sorry, }}}
variables {C}
def factor {D : Type u} [category.{v} D] [preadditive D] [has_finite_biproducts D]
(F : C ⥤ D) : additive_envelope.{v} C ⥤ D :=
{ obj := λ X, ⨁ (λ i, F.obj (X.val i)),
map := sorry,
map_id' := sorry,
map_comp' := sorry, }
def factor_factorisation {D : Type u} [category.{v} D] [preadditive D] [has_finite_biproducts D]
(F : C ⥤ D) : F ≅ embedding C ⋙ factor F :=
sorry
end family
|
8174e5348a82460beaeb427fad677fa31c515737 | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2021/logic/sheet4.lean | 05a3dbf2ee62ce69ae477a1bc24224b7fa285f0a | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 1,415 | lean | /-
Copyright (c) 2021 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Kevin Buzzard
-/
import tactic -- imports all the Lean tactics
/-!
# Logic in Lean, example sheet 4 : "and" (`∧`)
We learn about how to manipulate `P ∧ Q` in Lean.
## Tactics
You'll need to know about the tactics from the previous sheets,
and also the following tactics:
* `cases`
* `split`
### The `cases` tactic
If `h : P ∧ Q` is a hypothesis, then `cases h with hP hQ,`
decomposes it into two hypotheses `hP : P` and `hQ : Q`.
### The `split` tactic
If `⊢ P ∧ Q` is in the goal, The `split` tactic will turn it into
two goals, `⊢ P` and `⊢ Q`. NB tactics operate on the first goal only.
-/
-- Throughout this sheet, `P`, `Q` and `R` will denote propositions.
variables (P Q R : Prop)
example : P ∧ Q → P :=
begin
sorry
end
example : P ∧ Q → Q :=
begin
sorry
end
example : (P → Q → R) → (P ∧ Q → R) :=
begin
sorry
end
example : P → Q → P ∧ Q :=
begin
sorry
end
/-- `∧` is symmetric -/
example : P ∧ Q → Q ∧ P :=
begin
sorry
end
example : P → P ∧ true :=
begin
sorry
end
example : false → P ∧ false :=
begin
sorry
end
/-- `∧` is transitive -/
example : (P ∧ Q) → (Q ∧ R) → (P ∧ R) :=
begin
sorry,
end
example : ((P ∧ Q) → R) → (P → Q → R) :=
begin
sorry,
end
|
3fe6908d6bd8dc4745b505656b55965f1accbeeb | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/preadditive/functor_category.lean | 6117d69648326ee7d354528f42a8de1d50e5e45e | [
"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 | 2,814 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import category_theory.preadditive.basic
/-!
# Preadditive structure on functor categories
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
If `C` and `D` are categories and `D` is preadditive,
then `C ⥤ D` is also preadditive.
-/
open_locale big_operators
namespace category_theory
open category_theory.limits preadditive
variables {C D : Type*} [category C] [category D] [preadditive D]
instance functor_category_preadditive : preadditive (C ⥤ D) :=
{ hom_group := λ F G,
{ add := λ α β,
{ app := λ X, α.app X + β.app X,
naturality' := by { intros, rw [comp_add, add_comp, α.naturality, β.naturality] } },
zero := { app := λ X, 0, naturality' := by { intros, rw [zero_comp, comp_zero] } },
neg := λ α,
{ app := λ X, -α.app X,
naturality' := by { intros, rw [comp_neg, neg_comp, α.naturality] } },
sub := λ α β,
{ app := λ X, α.app X - β.app X,
naturality' := by { intros, rw [comp_sub, sub_comp, α.naturality, β.naturality] } },
add_assoc := by { intros, ext, apply add_assoc },
zero_add := by { intros, ext, apply zero_add },
add_zero := by { intros, ext, apply add_zero },
sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg },
add_left_neg := by { intros, ext, apply add_left_neg },
add_comm := by { intros, ext, apply add_comm } },
add_comp' := by { intros, ext, apply add_comp },
comp_add' := by { intros, ext, apply comp_add } }
namespace nat_trans
variables {F G : C ⥤ D}
/-- Application of a natural transformation at a fixed object,
as group homomorphism -/
@[simps] def app_hom (X : C) : (F ⟶ G) →+ (F.obj X ⟶ G.obj X) :=
{ to_fun := λ α, α.app X,
map_zero' := rfl,
map_add' := λ _ _, rfl }
@[simp] lemma app_zero (X : C) : (0 : F ⟶ G).app X = 0 := rfl
@[simp] lemma app_add (X : C) (α β : F ⟶ G) : (α + β).app X = α.app X + β.app X := rfl
@[simp] lemma app_sub (X : C) (α β : F ⟶ G) : (α - β).app X = α.app X - β.app X := rfl
@[simp] lemma app_neg (X : C) (α : F ⟶ G) : (-α).app X = -α.app X := rfl
@[simp] lemma app_nsmul (X : C) (α : F ⟶ G) (n : ℕ) : (n • α).app X = n • α.app X :=
(app_hom X).map_nsmul α n
@[simp] lemma app_zsmul (X : C) (α : F ⟶ G) (n : ℤ) : (n • α).app X = n • α.app X :=
(app_hom X : (F ⟶ G) →+ (F.obj X ⟶ G.obj X)).map_zsmul α n
@[simp] lemma app_sum {ι : Type*} (s : finset ι) (X : C) (α : ι → (F ⟶ G)) :
(∑ i in s, α i).app X = ∑ i in s, ((α i).app X) :=
by { rw [← app_hom_apply, add_monoid_hom.map_sum], refl }
end nat_trans
end category_theory
|
f0b57b780319b1e3b7d5bb875c704c7488b0705c | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /tests/lean/run/structInst2.lean | f7a7af4d7174740453a396f92e9c652e5130ddee | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 1,588 | lean | import Init.Control.Option
universes u v
def OptionT2 (m : Type u → Type v) (α : Type u) : Type v :=
m (Option α)
namespace OptionT2
variables {m : Type u → Type v} [Monad m] {α β : Type u}
@[inline] protected def bind (ma : OptionT2 m α) (f : α → OptionT2 m β) : OptionT2 m β :=
(do {
a? ← ma;
match a? with
| some a => f a
| none => pure none
} : m (Option β))
@[inline] protected def pure (a : α) : OptionT2 m α :=
(pure (some a) : m (Option α))
@[inline] protected def orelse (ma : OptionT2 m α) (mb : OptionT2 m α) : OptionT2 m α :=
(do { a? ← ma;
match a? with
| some a => pure (some a)
| _ => mb } : m (Option α))
@[inline] protected def fail : OptionT2 m α :=
(pure none : m (Option α))
end OptionT2
new_frontend
instance optMonad1 {m} [Monad m] : Monad (OptionT2 m) :=
{ pure := OptionT2.pure, bind := OptionT2.bind }
def optMonad2 {m} [Monad m] : Monad (OptionT m) :=
{ pure := OptionT.pure, bind := OptionT.bind }
def optAlt1 {m} [Monad m] : Alternative (OptionT m) :=
{ failure := OptionT.fail,
orelse := OptionT.orelse,
toApplicative := Monad.toApplicative (OptionT m) } -- TODO: check toApplicative binder annotations
def optAlt2 {m} [Monad m] : Alternative (OptionT m) :=
⟨OptionT.fail, OptionT.orelse⟩ -- it works because it treats `toApplicative` as an instance implicit argument
def optAlt3 {m} [Monad m] : Alternative (OptionT2 m) :=
{ failure := OptionT2.fail,
orelse := OptionT2.orelse,
toApplicative := Monad.toApplicative (OptionT2 m) }
|
4bec7e9b29595f3978cf191df2fd8275d10e88ca | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/lambda_simp.lean | f12fab9d06c678a8fdbe2b7089a6b1265f3d6014 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 160 | lean | print [simp] default
constant addz (a : nat) : 0 + a = a
attribute [simp] addz
open tactic
def ex : (λ a b : nat, 0 + a) = (λ a b, a) :=
by simp
print ex
|
b4a44236e25887c91a46cb1927264876c2e24f17 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/data/nat/cast.lean | f330158ae4e29ba67a0c9cc0af28c4d387e4e9c3 | [
"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 | 9,051 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Natural homomorphism from the natural numbers into a monoid with one.
-/
import algebra.ordered_field
import data.nat.basic
namespace nat
variables {α : Type*}
section
variables [has_zero α] [has_one α] [has_add α]
/-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/
protected def cast : ℕ → α
| 0 := 0
| (n+1) := cast n + 1
/--
Coercions such as `nat.cast_coe` that go from a concrete structure such as
`ℕ` to an arbitrary ring `α` should be set up as follows:
```lean
@[priority 900] instance : has_coe_t ℕ α := ⟨...⟩
```
It needs to be `has_coe_t` instead of `has_coe` because otherwise type-class
inference would loop when constructing the transitive coercion `ℕ → ℕ → ℕ → ...`.
The reduced priority is necessary so that it doesn't conflict with instances
such as `has_coe_t α (option α)`.
For this to work, we reduce the priority of the `coe_base` and `coe_trans`
instances because we want the instances for `has_coe_t` to be tried in the
following order:
1. `has_coe_t` instances declared in mathlib (such as `has_coe_t α (with_top α)`, etc.)
2. `coe_base`, which contains instances such as `has_coe (fin n) n`
3. `nat.cast_coe : has_coe_t ℕ α` etc.
4. `coe_trans`
If `coe_trans` is tried first, then `nat.cast_coe` doesn't get a chance to apply.
-/
library_note "coercion into rings"
attribute [instance, priority 950] coe_base
attribute [instance, priority 500] coe_trans
-- see note [coercion into rings]
@[priority 900] instance cast_coe : has_coe_t ℕ α := ⟨nat.cast⟩
@[simp, norm_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl
theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl
@[simp, norm_cast, priority 500]
theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl
@[simp, norm_cast] theorem cast_ite (P : Prop) [decidable P] (m n : ℕ) :
(((ite P m n) : ℕ) : α) = ite P (m : α) (n : α) :=
by { split_ifs; refl, }
end
@[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _
@[simp, norm_cast] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n
| 0 := (add_zero _).symm
| (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc]
/-- `coe : ℕ → α` as an `add_monoid_hom`. -/
def cast_add_monoid_hom (α : Type*) [add_monoid α] [has_one α] : ℕ →+ α :=
{ to_fun := coe,
map_add' := cast_add,
map_zero' := cast_zero }
@[simp] lemma coe_cast_add_monoid_hom [add_monoid α] [has_one α] :
(cast_add_monoid_hom α : ℕ → α) = coe := rfl
@[simp, norm_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) :
((bit0 n : ℕ) : α) = bit0 n := cast_add _ _
@[simp, norm_cast] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) :
((bit1 n : ℕ) : α) = bit1 n :=
by rw [bit1, cast_add_one, cast_bit0]; refl
lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp
@[simp, norm_cast] theorem cast_pred [add_group α] [has_one α] :
∀ {n}, 0 < n → ((n - 1 : ℕ) : α) = n - 1
| (n+1) h := (add_sub_cancel (n:α) 1).symm
@[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) :
((n - m : ℕ) : α) = n - m :=
eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h]
@[simp, norm_cast] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n
| 0 := (mul_zero _).symm
| (n+1) := (cast_add _ _).trans $
show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one]
@[simp] theorem cast_dvd {α : Type*} [field α] {m n : ℕ} (n_dvd : n ∣ m) (n_nonzero : (n:α) ≠ 0) : ((m / n : ℕ) : α) = m / n :=
begin
rcases n_dvd with ⟨k, rfl⟩,
have : n ≠ 0, {rintro rfl, simpa using n_nonzero},
rw nat.mul_div_cancel_left _ (nat.pos_iff_ne_zero.2 this),
rw [nat.cast_mul, mul_div_cancel_left _ n_nonzero],
end
/-- `coe : ℕ → α` as a `ring_hom` -/
def cast_ring_hom (α : Type*) [semiring α] : ℕ →+* α :=
{ to_fun := coe,
map_one' := cast_one,
map_mul' := cast_mul,
.. cast_add_monoid_hom α }
@[simp] lemma coe_cast_ring_hom [semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl
lemma cast_commute [semiring α] (n : ℕ) (x : α) : commute ↑n x :=
nat.rec_on n (commute.zero_left x) $ λ n ihn, ihn.add_left $ commute.one_left x
lemma commute_cast [semiring α] (x : α) (n : ℕ) : commute x n :=
(n.cast_commute x).symm
@[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α)
| 0 := le_refl _
| (n+1) := add_nonneg (cast_nonneg n) zero_le_one
@[simp, norm_cast] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n
| 0 n := by simp [zero_le]
| (m+1) 0 := by simpa [not_succ_le_zero] using
lt_add_of_nonneg_of_lt (@cast_nonneg α _ m) zero_lt_one
| (m+1) (n+1) := (add_le_add_iff_right 1).trans $
(@cast_le m n).trans $ (add_le_add_iff_right 1).symm
@[simp, norm_cast] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
lemma cast_add_one_pos [linear_ordered_semiring α] (n : ℕ) : 0 < (n : α) + 1 :=
add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one
@[simp, norm_cast] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} :
(↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp, norm_cast] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} :
(↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp, norm_cast] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) :
abs (a : α) = a :=
abs_of_nonneg (cast_nonneg a)
section linear_ordered_field
variables [linear_ordered_field α]
lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ :=
inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one
lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) :=
by { rw one_div_eq_inv, exact inv_pos_of_nat }
lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) :=
by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa }
lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) :=
by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa }
end linear_ordered_field
end nat
namespace add_monoid_hom
variables {A : Type*} [add_monoid A]
@[ext] lemma ext_nat {f g : ℕ →+ A} (h : f 1 = g 1) : f = g :=
ext $ λ n, nat.rec_on n (f.map_zero.trans g.map_zero.symm) $ λ n ihn,
by simp only [nat.succ_eq_add_one, *, map_add]
lemma eq_nat_cast {A} [add_monoid A] [has_one A] (f : ℕ →+ A) (h1 : f 1 = 1) :
∀ n : ℕ, f n = n :=
ext_iff.1 $ show f = nat.cast_add_monoid_hom A, from ext_nat (h1.trans nat.cast_one.symm)
end add_monoid_hom
namespace ring_hom
variables {R : Type*} {S : Type*} [semiring R] [semiring S]
@[simp] lemma eq_nat_cast (f : ℕ →+* R) (n : ℕ) : f n = n :=
f.to_add_monoid_hom.eq_nat_cast f.map_one n
@[simp] lemma map_nat_cast (f : R →+* S) (n : ℕ) :
f n = n :=
(f.comp (nat.cast_ring_hom R)).eq_nat_cast n
lemma ext_nat (f g : ℕ →+* R) : f = g :=
coe_add_monoid_hom_injective $ add_monoid_hom.ext_nat $ f.map_one.trans g.map_one.symm
end ring_hom
@[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n :=
((ring_hom.id ℕ).eq_nat_cast n).symm
@[simp] theorem nat.cast_with_bot : ∀ (n : ℕ),
@coe ℕ (with_bot ℕ) (@coe_to_lift _ _ nat.cast_coe) n = n
| 0 := rfl
| (n+1) := by rw [with_bot.coe_add, nat.cast_add, nat.cast_with_bot n]; refl
instance nat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℕ →+* R) :=
⟨ring_hom.ext_nat⟩
namespace with_top
variables {α : Type*}
variables [has_zero α] [has_one α] [has_add α]
@[simp, norm_cast] lemma coe_nat : ∀(n : nat), ((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
@[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
|
f28f114c6e2c9156eb00fbbe5bfe24b8a6b38a50 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/support.lean | 65bbbcf19c9c04b2c9a8bd73f238efe99af6a5db | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,470 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.conditionally_complete_lattice
import Mathlib.algebra.big_operators.basic
import Mathlib.algebra.group.prod
import Mathlib.algebra.group.pi
import Mathlib.PostPort
universes u x w v y
namespace Mathlib
/-!
# Support of a function
In this file we define `function.support f = {x | f x ≠ 0}` and prove its basic properties.
-/
namespace function
/-- `support` of a function is the set of points `x` such that `f x ≠ 0`. -/
def support {α : Type u} {A : Type x} [HasZero A] (f : α → A) : set α :=
set_of fun (x : α) => f x ≠ 0
theorem nmem_support {α : Type u} {A : Type x} [HasZero A] {f : α → A} {x : α} : ¬x ∈ support f ↔ f x = 0 :=
not_not
theorem mem_support {α : Type u} {A : Type x} [HasZero A] {f : α → A} {x : α} : x ∈ support f ↔ f x ≠ 0 :=
iff.rfl
theorem support_subset_iff {α : Type u} {A : Type x} [HasZero A] {f : α → A} {s : set α} : support f ⊆ s ↔ ∀ (x : α), f x ≠ 0 → x ∈ s :=
iff.rfl
theorem support_subset_iff' {α : Type u} {A : Type x} [HasZero A] {f : α → A} {s : set α} : support f ⊆ s ↔ ∀ (x : α), ¬x ∈ s → f x = 0 :=
forall_congr fun (x : α) => not_imp_comm
@[simp] theorem support_eq_empty_iff {α : Type u} {A : Type x} [HasZero A] {f : α → A} : support f = ∅ ↔ f = 0 := sorry
@[simp] theorem support_zero' {α : Type u} {A : Type x} [HasZero A] : support 0 = ∅ :=
iff.mpr support_eq_empty_iff rfl
@[simp] theorem support_zero {α : Type u} {A : Type x} [HasZero A] : (support fun (x : α) => 0) = ∅ :=
support_zero'
theorem support_binop_subset {α : Type u} {A : Type x} [HasZero A] (op : A → A → A) (op0 : op 0 0 = 0) (f : α → A) (g : α → A) : (support fun (x : α) => op (f x) (g x)) ⊆ support f ∪ support g := sorry
theorem support_add {α : Type u} {A : Type x} [add_monoid A] (f : α → A) (g : α → A) : (support fun (x : α) => f x + g x) ⊆ support f ∪ support g :=
support_binop_subset Add.add (zero_add 0) f g
@[simp] theorem support_neg {α : Type u} {A : Type x} [add_group A] (f : α → A) : (support fun (x : α) => -f x) = support f :=
set.ext fun (x : α) => not_congr neg_eq_zero
theorem support_sub {α : Type u} {A : Type x} [add_group A] (f : α → A) (g : α → A) : (support fun (x : α) => f x - g x) ⊆ support f ∪ support g :=
support_binop_subset Sub.sub (sub_self 0) f g
@[simp] theorem support_mul {α : Type u} {A : Type x} [mul_zero_class A] [no_zero_divisors A] (f : α → A) (g : α → A) : (support fun (x : α) => f x * g x) = support f ∩ support g := sorry
@[simp] theorem support_inv {α : Type u} {A : Type x} [division_ring A] (f : α → A) : (support fun (x : α) => f x⁻¹) = support f :=
set.ext fun (x : α) => not_congr inv_eq_zero
@[simp] theorem support_div {α : Type u} {A : Type x} [division_ring A] (f : α → A) (g : α → A) : (support fun (x : α) => f x / g x) = support f ∩ support g := sorry
theorem support_sup {α : Type u} {A : Type x} [HasZero A] [semilattice_sup A] (f : α → A) (g : α → A) : (support fun (x : α) => f x ⊔ g x) ⊆ support f ∪ support g :=
support_binop_subset has_sup.sup sup_idem f g
theorem support_inf {α : Type u} {A : Type x} [HasZero A] [semilattice_inf A] (f : α → A) (g : α → A) : (support fun (x : α) => f x ⊓ g x) ⊆ support f ∪ support g :=
support_binop_subset has_inf.inf inf_idem f g
theorem support_max {α : Type u} {A : Type x} [HasZero A] [linear_order A] (f : α → A) (g : α → A) : (support fun (x : α) => max (f x) (g x)) ⊆ support f ∪ support g :=
support_sup f g
theorem support_min {α : Type u} {A : Type x} [HasZero A] [linear_order A] (f : α → A) (g : α → A) : (support fun (x : α) => min (f x) (g x)) ⊆ support f ∪ support g :=
support_inf f g
theorem support_supr {α : Type u} {ι : Sort w} {A : Type x} [HasZero A] [conditionally_complete_lattice A] [Nonempty ι] (f : ι → α → A) : (support fun (x : α) => supr fun (i : ι) => f i x) ⊆ set.Union fun (i : ι) => support (f i) := sorry
theorem support_infi {α : Type u} {ι : Sort w} {A : Type x} [HasZero A] [conditionally_complete_lattice A] [Nonempty ι] (f : ι → α → A) : (support fun (x : α) => infi fun (i : ι) => f i x) ⊆ set.Union fun (i : ι) => support (f i) :=
support_supr f
theorem support_sum {α : Type u} {β : Type v} {A : Type x} [add_comm_monoid A] (s : finset α) (f : α → β → A) : (support fun (x : β) => finset.sum s fun (i : α) => f i x) ⊆
set.Union fun (i : α) => set.Union fun (H : i ∈ s) => support (f i) := sorry
theorem support_prod_subset {α : Type u} {β : Type v} {A : Type x} [comm_monoid_with_zero A] (s : finset α) (f : α → β → A) : (support fun (x : β) => finset.prod s fun (i : α) => f i x) ⊆
set.Inter fun (i : α) => set.Inter fun (H : i ∈ s) => support (f i) :=
fun (x : β) (hx : x ∈ support fun (x : β) => finset.prod s fun (i : α) => f i x) =>
iff.mpr set.mem_bInter_iff
fun (i : α) (hi : i ∈ fun (i : α) => i ∈ finset.val s) (H : f i x = 0) => hx (finset.prod_eq_zero hi H)
theorem support_prod {α : Type u} {β : Type v} {A : Type x} [comm_monoid_with_zero A] [no_zero_divisors A] [nontrivial A] (s : finset α) (f : α → β → A) : (support fun (x : β) => finset.prod s fun (i : α) => f i x) =
set.Inter fun (i : α) => set.Inter fun (H : i ∈ s) => support (f i) := sorry
theorem support_comp_subset {α : Type u} {A : Type x} {B : Type y} [HasZero A] [HasZero B] {g : A → B} (hg : g 0 = 0) (f : α → A) : support (g ∘ f) ⊆ support f := sorry
theorem support_subset_comp {α : Type u} {A : Type x} {B : Type y} [HasZero A] [HasZero B] {g : A → B} (hg : ∀ {x : A}, g x = 0 → x = 0) (f : α → A) : support f ⊆ support (g ∘ f) :=
fun (x : α) => mt hg
theorem support_comp_eq {α : Type u} {A : Type x} {B : Type y} [HasZero A] [HasZero B] (g : A → B) (hg : ∀ {x : A}, g x = 0 ↔ x = 0) (f : α → A) : support (g ∘ f) = support f :=
set.ext fun (x : α) => not_congr hg
theorem support_prod_mk {α : Type u} {A : Type x} {B : Type y} [HasZero A] [HasZero B] (f : α → A) (g : α → B) : (support fun (x : α) => (f x, g x)) = support f ∪ support g := sorry
|
fb78df009c88f8bca2123bcee36298278d52d0cf | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /tests/lean/run/695d.lean | 19fed078b9892030595455cd2f3d677e309d86b0 | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 107 | lean | import data.nat
open nat
example (a b : nat) : 0 + a + 0 = a :=
begin
rewrite [add_zero, zero_add,]
end
|
210c9c129b79756e9c96e412e77de9b9bb74e6ed | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/data/set/countable.lean | 225ee3d5fc6db6689b73aa8daef844e55bcfd9e4 | [
"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 | 8,121 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Countable sets.
-/
import data.equiv.list data.set.finite logic.function data.set.function
noncomputable theory
open function set encodable
open classical (hiding some)
open_locale classical
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
namespace set
/-- Countable sets
A set is countable if there exists an encoding of the set into the natural numbers.
An encoding is an injection with a partial inverse, which can be viewed as a
constructive analogue of countability. (For the most part, theorems about
`countable` will be classical and `encodable` will be constructive.)
-/
def countable (s : set α) : Prop := nonempty (encodable s)
lemma countable_iff_exists_injective {s : set α} :
countable s ↔ ∃f:s → ℕ, injective f :=
⟨λ ⟨h⟩, by exactI ⟨encode, encode_injective⟩,
λ ⟨f, h⟩, ⟨⟨f, partial_inv f, partial_inv_left h⟩⟩⟩
lemma countable_iff_exists_inj_on {s : set α} :
countable s ↔ ∃ f : α → ℕ, inj_on f s :=
countable_iff_exists_injective.trans
⟨λ ⟨f, hf⟩, ⟨λ a, if h : a ∈ s then f ⟨a, h⟩ else 0,
λ a b as bs h, congr_arg subtype.val $
hf $ by simpa [as, bs] using h⟩,
λ ⟨f, hf⟩, ⟨_, inj_on_iff_injective.1 hf⟩⟩
lemma countable_iff_exists_surjective [ne : inhabited α] {s : set α} :
countable s ↔ ∃f:ℕ → α, s ⊆ range f :=
⟨λ ⟨h⟩, by exactI ⟨λ n, ((decode s n).map subtype.val).iget,
λ a as, ⟨encode (⟨a, as⟩ : s), by simp [encodek]⟩⟩,
λ ⟨f, hf⟩, ⟨⟨
λ x, inv_fun f x.1,
λ n, if h : f n ∈ s then some ⟨f n, h⟩ else none,
λ ⟨x, hx⟩, begin
have := inv_fun_eq (hf hx), dsimp at this ⊢,
simp [this, hx]
end⟩⟩⟩
/--
A non-empty set is countable iff there exists a surjection from the
natural numbers onto the subtype induced by the set.
-/
lemma countable_iff_exists_surjective_to_subtype {s : set α} (hs : s ≠ ∅) :
countable s ↔ ∃ f : ℕ → s, surjective f :=
have inhabited s, from ⟨classical.choice (coe_nonempty_iff_ne_empty.mpr hs)⟩,
have countable s → ∃ f : ℕ → s, surjective f, from assume ⟨h⟩,
by exactI ⟨λ n, (decode s n).iget, λ a, ⟨encode a, by simp [encodek]⟩⟩,
have (∃ f : ℕ → s, surjective f) → countable s, from assume ⟨f, fsurj⟩,
⟨⟨inv_fun f, option.some ∘ f,
by intro h; simp [(inv_fun_eq (fsurj h) : f (inv_fun f h) = h)]⟩⟩,
by split; assumption
def countable.to_encodable {s : set α} : countable s → encodable s :=
classical.choice
lemma countable_encodable' (s : set α) [H : encodable s] : countable s :=
⟨H⟩
lemma countable_encodable [encodable α] (s : set α) : countable s :=
⟨by apply_instance⟩
lemma exists_surjective_of_countable {s : set α} (hs : s ≠ ∅) (hc : countable s) :
∃f:ℕ → α, s = range f :=
begin
rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hx⟩,
letI : encodable s := countable.to_encodable hc,
letI : inhabited s := ⟨⟨x, hx⟩⟩,
have : countable (univ : set s) := countable_encodable _,
rcases countable_iff_exists_surjective.1 this with ⟨g, hg⟩,
have : range g = univ := univ_subset_iff.1 hg,
use subtype.val ∘ g,
rw [range_comp, this],
simp
end
@[simp] lemma countable_empty : countable (∅ : set α) :=
⟨⟨λ x, x.2.elim, λ n, none, λ x, x.2.elim⟩⟩
@[simp] lemma countable_singleton (a : α) : countable ({a} : set α) :=
⟨of_equiv _ (equiv.set.singleton a)⟩
lemma countable_subset {s₁ s₂ : set α} (h : s₁ ⊆ s₂) : countable s₂ → countable s₁
| ⟨H⟩ := ⟨@of_inj _ _ H _ (embedding_of_subset h).2⟩
lemma countable_image {s : set α} (f : α → β) (hs : countable s) : countable (f '' s) :=
let f' : s → f '' s := λ⟨a, ha⟩, ⟨f a, mem_image_of_mem f ha⟩ in
have hf' : surjective f', from assume ⟨b, a, ha, hab⟩, ⟨⟨a, ha⟩, subtype.eq hab⟩,
⟨@encodable.of_inj _ _ hs.to_encodable (surj_inv hf') (injective_surj_inv hf')⟩
lemma countable_range [encodable α] (f : α → β) : countable (range f) :=
by rw ← image_univ; exact countable_image _ (countable_encodable _)
lemma countable_of_injective_of_countable_image {s : set α} {f : α → β}
(hf : inj_on f s) (hs : countable (f '' s)) : countable s :=
let ⟨g, hg⟩ := countable_iff_exists_inj_on.1 hs in
countable_iff_exists_inj_on.2 ⟨g ∘ f, inj_on_comp (maps_to_image _ _) hg hf⟩
lemma countable_Union {t : α → set β} [encodable α] (ht : ∀a, countable (t a)) :
countable (⋃a, t a) :=
by haveI := (λ a, (ht a).to_encodable);
rw Union_eq_range_sigma; apply countable_range
lemma countable_bUnion {s : set α} {t : α → set β} (hs : countable s) (ht : ∀a∈s, countable (t a)) :
countable (⋃a∈s, t a) :=
begin
rw bUnion_eq_Union,
haveI := hs.to_encodable,
exact countable_Union (by simpa using ht)
end
lemma countable_sUnion {s : set (set α)} (hs : countable s) (h : ∀a∈s, countable a) :
countable (⋃₀ s) :=
by rw sUnion_eq_bUnion; exact countable_bUnion hs h
lemma countable_Union_Prop {p : Prop} {t : p → set β} (ht : ∀h:p, countable (t h)) :
countable (⋃h:p, t h) :=
by by_cases p; simp [h, ht]
lemma countable_union {s₁ s₂ : set α} (h₁ : countable s₁) (h₂ : countable s₂) : countable (s₁ ∪ s₂) :=
by rw union_eq_Union; exact
countable_Union (bool.forall_bool.2 ⟨h₂, h₁⟩)
lemma countable_insert {s : set α} {a : α} (h : countable s) : countable (insert a s) :=
by rw [set.insert_eq]; from countable_union (countable_singleton _) h
lemma countable_finite {s : set α} : finite s → countable s
| ⟨h⟩ := nonempty_of_trunc (by exactI trunc_encodable_of_fintype s)
lemma countable_set_of_finite_subset {s : set α} : countable s →
countable {t | finite t ∧ t ⊆ s} | ⟨h⟩ :=
begin
resetI,
refine countable_subset _ (countable_range
(λ t : finset s, {a | ∃ h:a ∈ s, subtype.mk a h ∈ t})),
rintro t ⟨⟨ht⟩, ts⟩,
refine ⟨finset.univ.map (embedding_of_subset ts),
set.ext $ λ a, _⟩,
simp, split,
{ rintro ⟨as, b, bt, e⟩,
cases congr_arg subtype.val e, exact bt },
{ exact λ h, ⟨ts h, _, h, rfl⟩ }
end
lemma countable_pi {π : α → Type*} [fintype α] {s : Πa, set (π a)} (hs : ∀a, countable (s a)) :
countable {f : Πa, π a | ∀a, f a ∈ s a} :=
countable_subset
(show {f : Πa, π a | ∀a, f a ∈ s a} ⊆ range (λf : Πa, s a, λa, (f a).1), from
assume f hf, ⟨λa, ⟨f a, hf a⟩, funext $ assume a, rfl⟩) $
have trunc (encodable (Π (a : α), s a)), from
@encodable.fintype_pi α _ _ _ (assume a, (hs a).to_encodable),
trunc.induction_on this $ assume h,
@countable_range _ _ h _
lemma countable_prod {s : set α} {t : set β} (hs : countable s) (ht : countable t) :
countable (set.prod s t) :=
begin
haveI : encodable s := hs.to_encodable,
haveI : encodable t := ht.to_encodable,
haveI : encodable (s × t) := by apply_instance,
have : range (λp, ⟨p.1, p.2⟩ : s × t → α × β) = set.prod s t,
{ ext z,
rcases z with ⟨x, y⟩,
simp only [exists_prop, set.mem_range, set_coe.exists, prod.mk.inj_iff,
set.prod_mk_mem_set_prod_eq, subtype.coe_mk, prod.exists],
split,
{ rintros ⟨x', x's, y', y't, x'x, y'y⟩,
simp [x'x.symm, y'y.symm, x's, y't] },
{ rintros ⟨xs, yt⟩,
exact ⟨x, xs, y, yt, rfl, rfl⟩ }},
rw ← this,
exact countable_range _
end
section enumerate
/-- Enumerate elements in a countable set.-/
def enumerate_countable {s : set α} (h : countable s) (default : α) : ℕ → α :=
assume n, match @encodable.decode s (h.to_encodable) n with
| (some y) := y
| (none) := default
end
lemma subset_range_enumerate {s : set α} (h : countable s) (default : α) :
s ⊆ range (enumerate_countable h default) :=
assume x hx,
⟨@encodable.encode s h.to_encodable ⟨x, hx⟩,
by simp [enumerate_countable, encodable.encodek]⟩
end enumerate
end set
|
86198b660851b762e3a4528049632d41be7d653e | 07c76fbd96ea1786cc6392fa834be62643cea420 | /tests/lean/hott/beginend2.hlean | c6261c8a5a980bef61b0b9c38a336329952aacc2 | [
"Apache-2.0"
] | permissive | fpvandoorn/lean2 | 5a430a153b570bf70dc8526d06f18fc000a60ad9 | 0889cf65b7b3cebfb8831b8731d89c2453dd1e9f | refs/heads/master | 1,592,036,508,364 | 1,545,093,958,000 | 1,545,093,958,000 | 75,436,854 | 0 | 0 | null | 1,480,718,780,000 | 1,480,718,780,000 | null | UTF-8 | Lean | false | false | 307 | hlean | open eq tactic
open eq (rec_on)
definition concat_whisker2 {A} {x y z : A} (p p' : x = y) (q q' : y = z) (a : p = p') (b : q = q') :
(whisker_right q a) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right q' a) :=
begin
apply (rec_on b),
apply (rec_on a),
apply ((idp_con _)⁻¹),
end
|
15ff03ae6434dd1b0e2b4515bf4abbb1c04d1ca7 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/order/bounded_lattice.lean | b8629ec7c543579d08e96a79faaf5839aaa48c3c | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 48,222 | 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 data.option.basic
import logic.nontrivial
import order.lattice
import order.order_dual
import tactic.pi_instances
/-!
# ⊤ and ⊥, bounded lattices and variants
This file defines top and bottom elements (greatest and least elements) of a type, the bounded
variants of different kinds of lattices, sets up the typeclass hierarchy between them and provides
instances for `Prop` and `fun`.
## Main declarations
* `has_<top/bot> α`: Typeclasses to declare the `⊤`/`⊥` notation.
* `order_<top/bot> α`: Order with a top/bottom element.
* `with_<top/bot> α`: Equips `option α` with the order on `α` plus `none` as the top/bottom element.
* `semilattice_<sup/inf>_<top/bot>`: Semilattice with a join/meet and a top/bottom element (all four
combinations). Typical examples include `ℕ`.
* `bounded_lattice α`: Lattice with a top and bottom element.
* `distrib_lattice_bot α`: Distributive lattice with a bottom element. It captures the properties
of `disjoint` that are common to `generalized_boolean_algebra` and `bounded_distrib_lattice`.
* `bounded_distrib_lattice α`: Bounded and distributive lattice. Typical examples include `Prop` and
`set α`.
* `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a
non distributive lattice, an element can have several complements.
* `is_complemented α`: Typeclass stating that any element of a lattice has a complement.
## Implementation notes
We didn't define `distrib_lattice_top` because the dual notion of `disjoint` isn't really used
anywhere.
-/
/-! ### Top, bottom element -/
set_option old_structure_cmd true
universes u v
variables {α : Type u} {β : Type v}
/-- Typeclass for the `⊤` (`\top`) notation -/
@[notation_class] class has_top (α : Type u) := (top : α)
/-- Typeclass for the `⊥` (`\bot`) notation -/
@[notation_class] class has_bot (α : Type u) := (bot : α)
notation `⊤` := has_top.top
notation `⊥` := has_bot.bot
@[priority 100] instance has_top_nonempty (α : Type u) [has_top α] : nonempty α := ⟨⊤⟩
@[priority 100] instance has_bot_nonempty (α : Type u) [has_bot α] : nonempty α := ⟨⊥⟩
attribute [pattern] has_bot.bot has_top.top
/-- An `order_top` is a partial order with a greatest element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_top (α : Type u) extends has_top α, partial_order α :=
(le_top : ∀ a : α, a ≤ ⊤)
section order_top
variables [order_top α] {a b : α}
@[simp] theorem le_top : a ≤ ⊤ :=
order_top.le_top a
theorem top_unique (h : ⊤ ≤ a) : a = ⊤ :=
le_top.antisymm h
-- TODO: delete in favor of the next?
theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a :=
⟨λ eq, eq.symm ▸ le_refl ⊤, top_unique⟩
@[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ :=
⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩
@[simp] theorem not_top_lt : ¬ ⊤ < a :=
λ h, lt_irrefl a (lt_of_le_of_lt le_top h)
@[simp] theorem is_top_iff_eq_top : is_top a ↔ a = ⊤ :=
⟨λ h, h.unique le_top, λ h b, h.symm ▸ le_top⟩
theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ :=
top_le_iff.1 $ h₂ ▸ h
lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := le_top.lt_iff_ne
lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ :=
lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top
alias ne_top_of_lt ← has_lt.lt.ne_top
theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ :=
λ ha, hb $ top_unique $ ha ▸ hab
lemma eq_top_of_maximal (h : ∀ b, ¬ a < b) : a = ⊤ :=
or.elim (lt_or_eq_of_le le_top) (λ hlt, absurd hlt (h ⊤)) (λ he, he)
lemma ne.lt_top (h : a ≠ ⊤) : a < ⊤ := lt_top_iff_ne_top.mpr h
lemma ne.lt_top' (h : ⊤ ≠ a) : a < ⊤ := h.symm.lt_top
end order_top
lemma strict_mono.maximal_preimage_top [linear_order α] [order_top β]
{f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) :
x ≤ a :=
H.maximal_of_maximal_image (λ p, by { rw h_top, exact le_top }) x
theorem order_top.ext_top {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊤ : α) = ⊤ :=
top_unique $ by rw ← H; apply le_top
theorem order_top.ext {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_top.ext_top H,
casesI A, casesI B,
injection this; congr'
end
/-- An `order_bot` is a partial order with a least element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_bot (α : Type u) extends has_bot α, partial_order α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section order_bot
variables [order_bot α] {a b : α}
@[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a
theorem bot_unique (h : a ≤ ⊥) : a = ⊥ :=
h.antisymm bot_le
-- TODO: delete?
theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ :=
⟨λ eq, eq.symm ▸ le_refl ⊥, bot_unique⟩
@[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ :=
⟨bot_unique, λ h, h.symm ▸ le_refl ⊥⟩
@[simp] theorem not_lt_bot : ¬ a < ⊥ :=
λ h, lt_irrefl a (lt_of_lt_of_le h bot_le)
@[simp] theorem is_bot_iff_eq_bot : is_bot a ↔ a = ⊥ :=
⟨λ h, h.unique bot_le, λ h b, h.symm ▸ bot_le⟩
theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ :=
λ ha, hb $ bot_unique $ ha ▸ hab
theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ :=
le_bot_iff.1 $ h₂ ▸ h
lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff,
simp only [lt_iff_le_not_le, not_iff_not.mpr le_bot_iff, true_and, bot_le],
end
lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ :=
bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h
alias ne_bot_of_gt ← has_lt.lt.ne_bot
lemma eq_bot_of_minimal (h : ∀ b, ¬ b < a) : a = ⊥ :=
or.elim (lt_or_eq_of_le bot_le) (λ hlt, absurd hlt (h ⊥)) (λ he, he.symm)
lemma ne.bot_lt (h : a ≠ ⊥) : ⊥ < a := bot_lt_iff_ne_bot.mpr h
lemma ne.bot_lt' (h : ⊥ ≠ a) : ⊥ < a := h.symm.bot_lt
end order_bot
lemma strict_mono.minimal_preimage_bot [linear_order α] [order_bot β]
{f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) :
a ≤ x :=
H.minimal_of_minimal_image (λ p, by { rw h_bot, exact bot_le }) x
theorem order_bot.ext_bot {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊥ : α) = ⊥ :=
bot_unique $ by rw ← H; apply bot_le
theorem order_bot.ext {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection this; congr'
end
/-- A `semilattice_sup_top` is a semilattice with top and join. -/
class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α
section semilattice_sup_top
variables [semilattice_sup_top α] {a : α}
@[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
/-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/
class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α
section semilattice_sup_bot
variables [semilattice_sup_bot α] {a b : α}
@[simp] theorem bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp] theorem sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by rw [eq_bot_iff, sup_le_iff]; simp
end semilattice_sup_bot
instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice }
/-- A `semilattice_inf_top` is a semilattice with top and meet. -/
class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α
section semilattice_inf_top
variables [semilattice_inf_top α] {a b : α}
@[simp] theorem top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp] theorem inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by rw [eq_top_iff, le_inf_iff]; simp
end semilattice_inf_top
/-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/
class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a : α}
@[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/-! ### Bounded lattice -/
/-- A bounded lattice is a lattice with a top and bottom element,
denoted `⊤` and `⊥` respectively. This allows for the interpretation
of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/
class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_inf_top α :=
{ le_top := λ x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_inf_bot α :=
{ bot_le := λ x, @bot_le α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_sup_top α :=
{ le_top := λ x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] :
semilattice_sup_bot α :=
{ bot_le := λ x, @bot_le α _ x, ..bl }
theorem bounded_lattice.ext {α} {A B : bounded_lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have H1 : @bounded_lattice.to_lattice α A =
@bounded_lattice.to_lattice α B := lattice.ext H,
have H2 := order_bot.ext H,
have H3 : @bounded_lattice.to_order_top α A =
@bounded_lattice.to_order_top α B := order_top.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection H1; injection H2; injection H3; congr'
end
/-- A `distrib_lattice_bot` is a distributive lattice with a least element. -/
class distrib_lattice_bot α extends distrib_lattice α, semilattice_inf_bot α, semilattice_sup_bot α
/-- A bounded distributive lattice is exactly what it sounds like. -/
class bounded_distrib_lattice α extends distrib_lattice_bot α, bounded_lattice α
lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α}
(h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c :=
⟨λ h,
calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁]
... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left]
... ≤ c : by simp [h, inf_le_right],
λ h,
bot_unique $
calc a ⊓ b ≤ b ⊓ c : by { rw inf_comm, exact inf_le_inf_left _ h }
... = ⊥ : h₂⟩
/-- Propositions form a bounded distributive lattice. -/
instance Prop.bounded_distrib_lattice : bounded_distrib_lattice Prop :=
{ le := λ a b, a → b,
le_refl := λ _, id,
le_trans := λ a b c f g, g ∘ f,
le_antisymm := λ a b Hab Hba, propext ⟨Hab, Hba⟩,
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 H, or_iff_not_imp_left.2 $
λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩,
top := true,
le_top := λ a Ha, true.intro,
bot := false,
bot_le := @false.elim }
noncomputable instance Prop.linear_order : linear_order Prop :=
@lattice.to_linear_order Prop _ (classical.dec_eq _) (classical.dec_rel _) (classical.dec_rel _) $
λ p q, by { change (p → q) ∨ (q → p), tauto! }
@[simp] lemma le_Prop_eq : ((≤) : Prop → Prop → Prop) = (→) := rfl
@[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl
@[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl
section logic
variable [preorder α]
theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λ x, p x ∧ q x) :=
λ a b h, and.imp (m_p h) (m_q h)
-- Note: by finish [monotone] doesn't work
theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λ x, p x ∨ q x) :=
λ a b h, or.imp (m_p h) (m_q h)
end logic
instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) :=
{ bot := λ _, ⊥,
bot_le := λ x a, bot_le,
.. pi.partial_order }
/-! ### Function lattices -/
namespace pi
variables {ι : Type*} {α' : ι → Type*}
instance [Π i, has_bot (α' i)] : has_bot (Π i, α' i) := ⟨λ i, ⊥⟩
@[simp] lemma bot_apply [Π i, has_bot (α' i)] (i : ι) : (⊥ : Π i, α' i) i = ⊥ := rfl
lemma bot_def [Π i, has_bot (α' i)] : (⊥ : Π i, α' i) = λ i, ⊥ := rfl
instance [Π i, has_top (α' i)] : has_top (Π i, α' i) := ⟨λ i, ⊤⟩
@[simp] lemma top_apply [Π i, has_top (α' i)] (i : ι) : (⊤ : Π i, α' i) i = ⊤ := rfl
lemma top_def [Π i, has_top (α' i)] : (⊤ : Π i, α' i) = λ i, ⊤ := rfl
instance [Π i, semilattice_inf_bot (α' i)] : semilattice_inf_bot (Π i, α' i) :=
by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_inf_top (α' i)] : semilattice_inf_top (Π i, α' i) :=
by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_sup_bot (α' i)] : semilattice_sup_bot (Π i, α' i) :=
by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, semilattice_sup_top (α' i)] : semilattice_sup_top (Π i, α' i) :=
by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance [Π i, bounded_lattice (α' i)] : bounded_lattice (Π i, α' i) :=
{ .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot }
instance [Π i, distrib_lattice_bot (α' i)] : distrib_lattice_bot (Π i, α' i) :=
{ .. pi.distrib_lattice, .. pi.order_bot }
instance [Π i, bounded_distrib_lattice (α' i)] : bounded_distrib_lattice (Π i, α' i) :=
{ .. pi.bounded_lattice, .. pi.distrib_lattice }
end pi
lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊥ : α) :=
eq_bot_mono le_top (eq.symm hα)
lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊤ : α) :=
eq_top_mono bot_le hα
lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) :
subsingleton α :=
⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩
lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) :
subsingleton α :=
subsingleton_of_top_le_bot (ge_of_eq hα)
lemma subsingleton_iff_bot_eq_top {α : Type*} [bounded_lattice α] :
(⊥ : α) = (⊤ : α) ↔ subsingleton α :=
⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩
/-! ### `with_bot`, `with_top` -/
/-- Attach `⊥` to a type. -/
def with_bot (α : Type*) := option α
namespace with_bot
meta instance {α} [has_to_format α] : has_to_format (with_bot α) :=
{ to_format := λ x,
match x with
| none := "⊥"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_bot α) := ⟨some⟩
instance has_bot : has_bot (with_bot α) := ⟨none⟩
instance : inhabited (with_bot α) := ⟨⊥⟩
lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl
lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl
@[simp] theorem bot_ne_coe (a : α) : ⊥ ≠ (a : with_bot α) .
@[simp] theorem coe_ne_bot (a : α) : (a : with_bot α) ≠ ⊥ .
/-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/
@[elab_as_eliminator]
def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) :
Π (n : with_bot α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
lemma ne_bot_iff_exists {x : with_bot α} : x ≠ ⊥ ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
/-- Deconstruct a `x : with_bot α` to the underlying value in `α`, given a proof that `x ≠ ⊥`. -/
def unbot : Π (x : with_bot α), x ≠ ⊥ → α
| ⊥ h := absurd rfl h
| (some x) h := x
@[simp] lemma coe_unbot {α : Type*} (x : with_bot α) (h : x ≠ ⊥) :
(x.unbot h : with_bot α) = x :=
by { cases x, simpa using h, refl, }
@[simp] lemma unbot_coe (x : α) (h : (x : with_bot α) ≠ ⊥ := coe_ne_bot _) :
(x : with_bot α).unbot h = x := rfl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_bot α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
lemma none_lt_some [has_lt α] (a : α) :
@has_lt.lt (with_bot α) _ none (some a) :=
⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩
lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := none_lt_some a
instance : can_lift (with_bot α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊥,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_bot α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b,
lt := (<),
lt_iff_le_not_le := by intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<)];
split; refl,
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha,
let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in
⟨c, hc, le_trans ab bc⟩ }
instance partial_order [partial_order α] : partial_order (with_bot α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₁ with a,
{ cases o₂ with b, {refl},
rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩,
rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_bot.preorder }
instance order_bot [partial_order α] : order_bot (with_bot α) :=
{ bot_le := λ a a' h, option.no_confusion h,
..with_bot.partial_order, ..with_bot.has_bot }
@[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} :
(a : with_bot α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩
@[simp] theorem some_le_some [preorder α] {a b : α} :
@has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe
theorem coe_le [preorder α] {a b : α} :
∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b)
| _ rfl := coe_le_coe
@[norm_cast]
lemma coe_lt_coe [preorder α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some
lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b
| (some a) b := le_refl a
| none b := λ _ h, option.no_confusion h
@[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl
lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} :
a.get_or_else ⊥ ≤ b ↔ a ≤ b :=
by cases a; simp [none_eq_bot, some_eq_coe]
instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤)
| none x := is_true $ λ a h, option.no_confusion h
| (some x) (some y) :=
if h : x ≤ y
then is_true (some_le_some.2 h)
else is_false $ by simp *
| (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<)
| none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩
| (some x) (some y) :=
if h : x < y
then is_true $ by simp *
else is_false $ by simp *
| x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩
instance [partial_order α] [is_total α (≤)] : is_total (with_bot α) (≤) :=
{ total := λ a b, match a, b with
| none , _ := or.inl bot_le
| _ , none := or.inr bot_le
| some x, some y := by simp only [some_le_some, total_of]
end }
instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) :=
{ sup := option.lift_or_get (⊔),
le_sup_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
le_sup_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₁ with b; cases o₂ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, sup_le h₁' h₂⟩ }
end,
..with_bot.order_bot }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_bot α) = a ⊔ b := rfl
instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) :=
{ inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)),
inf_le_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_left⟩
end,
inf_le_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_right⟩
end,
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, le_inf ab ac⟩
end,
..with_bot.order_bot }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_bot α) = a ⊓ b := rfl
instance lattice [lattice α] : lattice (with_bot α) :=
{ ..with_bot.semilattice_sup, ..with_bot.semilattice_inf }
instance linear_order [linear_order α] : linear_order (with_bot α) :=
lattice.to_linear_order _ $ λ o₁ o₂,
begin
cases o₁ with a, {exact or.inl bot_le},
cases o₂ with b, {exact or.inr bot_le},
simp [le_total]
end
@[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used
lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_bot α) = min x y := rfl
@[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used
lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_bot α) = max x y := rfl
instance order_top [order_top α] : order_top (with_bot α) :=
{ top := some ⊤,
le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩,
..with_bot.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) :=
{ ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot }
lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_bot α → with_bot α → Prop) :=
have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ :=
acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim),
⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot)
(λ b, well_founded.induction h b
(show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) b,
from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot)
(λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] :
densely_ordered (with_bot α) :=
⟨ λ a b,
match a, b with
| a, none := λ h : a < ⊥, (not_lt_bot h).elim
| none, some b := λ h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩
| some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
end with_bot
--TODO(Mario): Construct using order dual on with_bot
/-- Attach `⊤` to a type. -/
def with_top (α : Type*) := option α
namespace with_top
meta instance {α} [has_to_format α] : has_to_format (with_top α) :=
{ to_format := λ x,
match x with
| none := "⊤"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_top α) := ⟨some⟩
instance has_top : has_top (with_top α) := ⟨none⟩
instance : inhabited (with_top α) := ⟨⊤⟩
lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl
lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl
/-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/
@[elab_as_eliminator]
def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) :
Π (n : with_top α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) .
@[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ .
lemma ne_top_iff_exists {x : with_top α} : x ≠ ⊤ ↔ ∃ (a : α), ↑a = x :=
option.ne_none_iff_exists
/-- Deconstruct a `x : with_top α` to the underlying value in `α`, given a proof that `x ≠ ⊤`. -/
def untop : Π (x : with_top α), x ≠ ⊤ → α :=
with_bot.unbot
@[simp] lemma coe_untop {α : Type*} (x : with_top α) (h : x ≠ ⊤) :
(x.untop h : with_top α) = x :=
by { cases x, simpa using h, refl, }
@[simp] lemma untop_coe (x : α) (h : (x : with_top α) ≠ ⊤ := coe_ne_top) :
(x : with_top α).untop h = x := rfl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_top α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a }
@[priority 10]
instance has_le [has_le α] : has_le (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b :=
by simp [(≤)]
@[simp] theorem le_none [has_le α] {a : with_top α} :
@has_le.le (with_top α) _ a none :=
by simp [(≤)]
@[simp] theorem some_lt_none [has_lt α] (a : α) :
@has_lt.lt (with_top α) _ (some a) none :=
by simp [(<)]; existsi a; refl
instance : can_lift (with_top α) α :=
{ coe := coe,
cond := λ r, r ≠ ⊤,
prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ }
instance [preorder α] : preorder (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a,
lt := (<),
lt_iff_le_not_le := by { intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<),(≤)] },
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc,
let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in
⟨a, ha, le_trans ab bc⟩,
}
instance partial_order [partial_order α] : partial_order (with_top α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₂ with b,
{ cases o₁ with a, {refl},
rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩,
rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_top.preorder }
instance order_top [partial_order α] : order_top (with_top α) :=
{ le_top := λ a a' h, option.no_confusion h,
..with_top.partial_order, .. with_top.has_top }
@[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} :
(a : with_top α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩
theorem le_coe [preorder α] {a b : α} :
∀ {o : option α}, a ∈ o →
(@has_le.le (with_top α) _ o b ↔ a ≤ b)
| _ rfl := coe_le_coe
theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b)
| (some a) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b)
| (some b) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b)
| (some a) b := by simp [some_eq_coe, coe_eq_coe]
| none b := by simp [none_eq_top]
@[norm_cast]
lemma coe_lt_coe [preorder α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some
lemma coe_lt_top [preorder α] (a : α) : (a : with_top α) < ⊤ := some_lt_none a
theorem coe_lt_iff [preorder α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b)
| (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe]
| none := by simp [none_eq_top, coe_lt_top]
lemma not_top_le_coe [preorder α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a :=
λ h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim
instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) :=
λ x y, @with_bot.decidable_le (order_dual α) _ _ y x
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) :=
λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x
instance [partial_order α] [is_total α (≤)] : is_total (with_top α) (≤) :=
{ total := λ a b, match a, b with
| none , _ := or.inr le_top
| _ , none := or.inl le_top
| some x, some y := by simp only [some_le_some, total_of]
end }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) :=
{ inf := option.lift_or_get (⊓),
inf_le_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
inf_le_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₂ with b; cases o₃ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, le_inf h₁' h₂⟩ }
end,
..with_top.order_top }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl
instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) :=
{ sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)),
le_sup_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_left⟩
end,
le_sup_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_right⟩
end,
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, sup_le ab ac⟩
end,
..with_top.order_top }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl
instance lattice [lattice α] : lattice (with_top α) :=
{ ..with_top.semilattice_sup, ..with_top.semilattice_inf }
instance linear_order [linear_order α] : linear_order (with_top α) :=
lattice.to_linear_order _ $ λ o₁ o₂,
begin
cases o₁ with a, {exact or.inr le_top},
cases o₂ with b, {exact or.inl le_top},
simp [le_total]
end
@[simp, norm_cast]
lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_top α) = min x y := rfl
@[simp, norm_cast]
lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_top α) = max x y := rfl
instance order_bot [order_bot α] : order_bot (with_top α) :=
{ bot := some ⊥,
bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩,
..with_top.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) :=
{ ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_top α → with_top α → Prop) :=
have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) :=
λ a, acc.intro _ (well_founded.induction h a
(show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) →
∀ y : with_top α, y < some b → acc (<) y,
from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim)
(λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))),
⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim)
(λ _ _, acc_some _))) acc_some⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] :
densely_ordered (with_top α) :=
⟨ λ a b,
match a, b with
| none, a := λ h : ⊤ < a, (not_top_lt h).elim
| some a, none := λ h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩
| some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α]
{a b : with_top α} :
(a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) :=
⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩,
λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩
end with_top
/-! ### Subtype, order dual, product lattices -/
namespace subtype
/-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop}
(Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop}
(Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a `⊔`-`⊤`-semilattice if `⊤` and `⊔` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_sup_top [semilattice_sup_top α] {P : α → Prop}
(Ptop : P ⊤) (Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)) : semilattice_sup_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ x, @le_top α _ x,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property.
See note [reducible non-instances]. -/
@[reducible]
protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop}
(Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ x, @le_top α _ x,
..subtype.semilattice_inf Pinf }
end subtype
namespace order_dual
variable (α)
instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩
instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩
instance [order_bot α] : order_top (order_dual α) :=
{ le_top := @bot_le α _,
.. order_dual.partial_order α, .. order_dual.has_top α }
instance [order_top α] : order_bot (order_dual α) :=
{ bot_le := @le_top α _,
.. order_dual.partial_order α, .. order_dual.has_bot α }
instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_top α }
instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_bot α }
instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_top α }
instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_bot α }
instance [bounded_lattice α] : bounded_lattice (order_dual α) :=
{ .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α }
/- If you define `distrib_lattice_top`, add the `order_dual` instances between `distrib_lattice_bot`
and `distrib_lattice_top` here -/
instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) :=
{ .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α }
end order_dual
namespace prod
variables (α β)
instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩
instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩
instance [order_top α] [order_top β] : order_top (α × β) :=
{ le_top := λ a, ⟨le_top, le_top⟩,
.. prod.partial_order α β, .. prod.has_top α β }
instance [order_bot α] [order_bot β] : order_bot (α × β) :=
{ bot_le := λ a, ⟨bot_le, bot_le⟩,
.. prod.partial_order α β, .. prod.has_bot α β }
instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_top α β }
instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_top α β }
instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_bot α β }
instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_bot α β }
instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) :=
{ .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β }
instance [distrib_lattice_bot α] [distrib_lattice_bot β] :
distrib_lattice_bot (α × β) :=
{ .. prod.distrib_lattice α β, .. prod.order_bot α β }
instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] :
bounded_distrib_lattice (α × β) :=
{ .. prod.bounded_lattice α β, .. prod.distrib_lattice α β }
end prod
/-! ### Disjointness and complements -/
section disjoint
section semilattice_inf_bot
variable [semilattice_inf_bot α]
/-- Two elements of a lattice are disjoint if their inf is the bottom element.
(This generalizes disjoint sets, viewed as members of the subset lattice.) -/
def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥
theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ :=
eq_bot_iff.2 h
theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ :=
eq_bot_iff.symm
theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a :=
by rw [disjoint, disjoint, inf_comm]
@[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a :=
disjoint.comm.1
lemma symmetric_disjoint : symmetric (disjoint : α → α → Prop) := disjoint.symm
@[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left
@[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right
theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂)
theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c :=
disjoint.mono h (le_refl _)
theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b :=
disjoint.mono (le_refl _) h
@[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ :=
by simp [disjoint]
lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b :=
by { intro h, rw [←h, disjoint_self] at hab, exact ha hab }
lemma disjoint.eq_bot_of_le {a b : α} (hab : disjoint a b) (h : a ≤ b) : a = ⊥ :=
eq_bot_iff.2 (by rwa ←inf_eq_left.2 h)
lemma disjoint.of_disjoint_inf_of_le {a b c : α} (h : disjoint (a ⊓ b) c) (hle : a ≤ c) :
disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_left.trans hle)]
lemma disjoint.of_disjoint_inf_of_le' {a b c : α} (h : disjoint (a ⊓ b) c) (hle : b ≤ c) :
disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_right.trans hle)]
end semilattice_inf_bot
section bounded_lattice
variables [bounded_lattice α] {a : α}
@[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff]
@[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff]
lemma eq_bot_of_disjoint_absorbs
{a b : α} (w : disjoint a b) (h : a ⊔ b = a) : b = ⊥ :=
begin
rw disjoint_iff at w,
rw [←w, right_eq_inf],
rwa sup_eq_left at h,
end
end bounded_lattice
section distrib_lattice_bot
variables [distrib_lattice_bot α] {a b c : α}
@[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c :=
by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff]
@[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c :=
by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff]
lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c :=
disjoint_sup_left.2 ⟨ha, hb⟩
lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) :=
disjoint_sup_right.2 ⟨hb, hc⟩
lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b :=
(λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le)
lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b :=
@le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le)
((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left))
end distrib_lattice_bot
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a b : α} (c : α)
lemma disjoint.inf_left (h : disjoint a b) : disjoint (a ⊓ c) b :=
h.mono_left inf_le_left
lemma disjoint.inf_left' (h : disjoint a b) : disjoint (c ⊓ a) b :=
h.mono_left inf_le_right
lemma disjoint.inf_right (h : disjoint a b) : disjoint a (b ⊓ c) :=
h.mono_right inf_le_left
lemma disjoint.inf_right' (h : disjoint a b) : disjoint a (c ⊓ b) :=
h.mono_right inf_le_right
end semilattice_inf_bot
end disjoint
section is_compl
/-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/
structure is_compl [bounded_lattice α] (x y : α) : Prop :=
(inf_le_bot : x ⊓ y ≤ ⊥)
(top_le_sup : ⊤ ≤ x ⊔ y)
namespace is_compl
section bounded_lattice
variables [bounded_lattice α] {x y z : α}
protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1
@[symm] protected lemma symm (h : is_compl x y) : is_compl y x :=
⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩
lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y :=
⟨le_of_eq h₁, le_of_eq h₂.symm⟩
lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot
lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup
open order_dual (to_dual)
lemma to_order_dual (h : is_compl x y) : is_compl (to_dual x) (to_dual y) := ⟨h.2, h.1⟩
end bounded_lattice
variables [bounded_distrib_lattice α] {x y z : α}
lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z :=
inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot
lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y :=
h.symm.inf_left_eq_bot_iff
lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z :=
by { rw disjoint_iff, exact h.inf_left_eq_bot_iff }
lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y :=
h.symm.disjoint_left_iff
lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y :=
h.disjoint_right_iff.symm
lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x :=
h.symm.le_left_iff
lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y :=
h.to_order_dual.le_left_iff
lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x :=
h.symm.left_le_iff
protected lemma antitone {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') :
y' ≤ y :=
h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _)
lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) :
y = z :=
le_antisymm (hxz.antitone hxy $ le_refl x) (hxy.antitone hxz $ le_refl x)
lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) :
x = y :=
hxz.symm.right_unique hyz.symm
lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊔ x') (y ⊓ y') :=
of_eq
(by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm,
h'.inf_eq_bot, inf_bot_eq])
(by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq,
sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq])
lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊓ x') (y ⊔ y') :=
(h.symm.sup_inf h'.symm).symm
end is_compl
lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ :=
is_compl.of_eq bot_inf_eq sup_top_eq
lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ :=
is_compl.of_eq inf_bot_eq top_sup_eq
section
variables [bounded_lattice α] {x : α}
lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ :=
sup_bot_eq.symm.trans h.sup_eq_top
lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ :=
eq_top_of_is_compl_bot h.symm
lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ :=
eq_top_of_is_compl_bot h.to_order_dual
lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ :=
eq_top_of_bot_is_compl h.to_order_dual
end
/-- A complemented bounded lattice is one where every element has a (not necessarily unique)
complement. -/
class is_complemented (α) [bounded_lattice α] : Prop :=
(exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b)
export is_complemented (exists_is_compl)
namespace is_complemented
variables [bounded_lattice α] [is_complemented α]
instance : is_complemented (order_dual α) :=
⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.to_order_dual⟩⟩
end is_complemented
end is_compl
section nontrivial
variables [bounded_lattice α] [nontrivial α]
lemma bot_ne_top : (⊥ : α) ≠ ⊤ :=
λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_›
lemma top_ne_bot : (⊤ : α) ≠ ⊥ := ne.symm bot_ne_top
end nontrivial
namespace bool
-- Could be generalised to `bounded_distrib_lattice` and `is_complemented`
instance : bounded_lattice bool :=
{ top := tt,
le_top := λ x, le_tt,
bot := ff,
bot_le := λ x, ff_le,
.. (infer_instance : lattice bool)}
end bool
section bool
@[simp] lemma top_eq_tt : ⊤ = tt := rfl
@[simp] lemma bot_eq_ff : ⊥ = ff := rfl
end bool
|
4d0c7fdb1bb1ca43bfb22d3b02af512dba8af079 | 6b2a480f27775cba4f3ae191b1c1387a29de586e | /group_rep1/caracteristique_pol/carac_pol.lean | c3319ca7673649b3fd1aaada304e6acd1d934a71 | [] | no_license | Or7ando/group_representation | a681de2e19d1930a1e1be573d6735a2f0b8356cb | 9b576984f17764ebf26c8caa2a542d248f1b50d2 | refs/heads/master | 1,662,413,107,324 | 1,590,302,389,000 | 1,590,302,389,000 | 258,130,829 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 7,224 | lean | import data.complex.basic
import linear_algebra.basic
import linear_algebra.determinant
import analysis.complex.polynomial
import data.polynomial
import tools.caracteristic.tools
open finset
universes u v w w'
variables
{R : Type u}[nonzero_comm_ring R]
{A : Type v} [fintype A][decidable_eq A]
(M : matrix A A R)
(N : matrix A A (polynomial R))
open polynomial open matrix
open with_bot tools
open_locale big_operators
/-
unfold car_matrix, split_ifs, rw eval_add, rw eval_C, rw eval_X, rw h, rw add_val, rw smul_val, rw one_val, rw mul_ite,
rw mul_one, rw mul_zero,simp, rw eval_C,rw add_val, rw smul_val, rw one_val, rw mul_ite,split_ifs, rw mul_zero,rw add_zero,
-/
lemma eval_ite (r : R) (P Q : polynomial R) (φ : Prop) [decidable φ]:
eval r (if φ then P else Q) = if φ then eval r P else eval r Q :=
by split_ifs; exact rfl
#check if_congr
#check if_true
noncomputable def car_matrix :
matrix A A (polynomial R) := λ x y, if x=y then C (M x y) + X else C (M x y)
namespace car_matrix
lemma eval (r : R) (i j : A): eval r (car_matrix M i j) = (M + r • 1) i j :=
begin
unfold car_matrix, rw eval_ite, rw eval_add, rw eval_C, rw eval_X,
rw add_val, rw smul_val, rw one_val, rw mul_ite, rw mul_one, rw mul_zero,
rw add_ite, rw add_zero,
end
noncomputable def car_pol : polynomial R := det (car_matrix M)
/-!
We admit a theorem
-/
-- monic_mul monic_X_add_C
lemma degree_coeff (x : A) : degree(car_matrix M x x) = 1 :=
begin
unfold car_matrix, split_ifs, let g := @degree_C_le R (M x x) _,
rw degree_add_eq_of_degree_lt,
exact degree_X, rw degree_X,refine (lt_iff_not_ge (degree (C (M x x))) 1).mpr _, intro,
let tr := le_trans a g, let g := zero_le_one,
have : 0 = 1,
apply le_antisymm,
exact g, exact (with_bot.coe_le rfl).mp tr, trivial, trivial,
end
lemma degree_coeff_ne {x y : A} (hyp : x ≠ y) : degree(car_matrix M x y) ≤ 0 := begin
unfold car_matrix, split_ifs, trivial, exact degree_C_le,
end
lemma degree_coef_lt_one {x y : A} (hyp : x ≠ y) : degree(car_matrix M x y) < 1 :=
begin
let g := degree_coeff_ne M hyp,
refine lt_of_le_of_lt g _,apply coe_lt_coe.mpr,
exact zero_lt_one,
end
lemma zero_le_one : (0 : with_bot ℕ ) ≤ 1 :=
begin apply coe_le_coe.mpr,
exact zero_le_one,
end
lemma degree_le_one (x y : A) : degree(car_matrix M x y) ≤ 1 :=
begin
by_cases x = y,
let g := degree_coeff M x, rw ← h, rw g, exact le_refl 1,
let g := degree_coeff_ne M h,
exact le_trans g (zero_le_one),
end
/--
-/
lemma leading_coef (x : A) : leading_coeff (car_matrix M x x) = 1 :=
begin
apply (monic.def).mp ,
unfold car_matrix,
split_ifs, rw add_comm, apply monic_X_add_C, trivial,
end
/--
Technical lemma
-/
lemma car_monic (x : A) : monic (car_matrix M x x) := begin
unfold monic, exact leading_coef M x,
end
end car_matrix
namespace car_pol
open car_matrix equiv.perm
/-!
Now we reconstruct the coeffcient of det_car the
` Σ (σ ∈ perm A), sign σ × ∏ (ℓ ∈ A) car_matrix M σ ℓ ℓ
-/
lemma eval_sum (φ : A → polynomial R) (r : R) : eval r (Σ φ ) = Σ (λ a : A,(eval r (φ a))) :=
begin
rw finset.sum_hom finset.univ (polynomial.eval r),
end
lemma eval_prod (φ : A → polynomial R) (r : R) : eval r (finset.prod finset.univ φ) =
finset.prod finset.univ (λ a : A,(eval r (φ a))) :=
begin
rw finset.prod_hom finset.univ (polynomial.eval r),
end
lemma test (a : ℤ )(r : R) : eval r (a : polynomial R) = (a : R) :=
begin
rw int_cast_eq_C, rw eval_C,
end
theorem eval_car_poly ( r : R) : eval r (car_pol M) = det (M+ r • 1) := begin
unfold det, unfold car_pol, unfold det,
erw eval_sum, congr, ext σ ,
rw eval_mul,
rw eval_prod,
rw int_cast_eq_C, rw eval_C, congr, ext,
rw car_matrix.eval,
end
lemma perm_mul (σ : equiv.perm A) (P : polynomial R) : degree ((sign σ : polynomial R) * P) = degree P := begin
rcases int.units_eq_one_or (sign σ), congr,
rw h, erw int.cast_one, rw one_mul,
rw h,
erw int.cast_neg, erw int.cast_one,
norm_cast,simp,
end
lemma equiv_not_id (σ : equiv.perm A) (hyp : σ ≠ 1) : ∃ x : A, σ x ≠ x := begin
refine not_forall.mp _,
intro, have : σ =1,
ext, exact a x, trivial,
end
lemma exists_le_one (σ : equiv.perm A) (hyp : σ ≠ 1) : ∃ ℓ0 : A, degree( car_matrix M (σ ℓ0 ) ℓ0 ) < 1:= begin
rcases (equiv_not_id σ hyp) with ⟨ℓ0,hyp_l ⟩,
use ℓ0,
let r := degree_coeff_ne M hyp_l,
refine lt_of_le_of_lt r _,
apply coe_lt_coe.mpr,
exact zero_lt_one,
end
noncomputable def term_wihout (σ : equiv.perm A) :=
finset.prod univ (λ (x : A), car_matrix M (σ x) x)
noncomputable def term (σ : equiv.perm A) :=
((equiv.perm.sign σ) : polynomial R ) * finset.prod univ (λ (x : A), car_matrix M (σ x) x)
lemma degree_term_eq_degree_term_without (σ : equiv.perm A ) : degree (term M σ ) = degree (term_wihout M σ ) := perm_mul _ _
lemma degree_term_wihout (σ : equiv.perm A) : if σ = 1 then degree (term_wihout M σ) = fintype.card A else degree (term_wihout M σ) < fintype.card A
:= begin
split_ifs, rw h, {
unfold term_wihout,
exact prod_monic_one (finset.univ) (λ ℓ, car_matrix M ℓ ℓ )(degree_coeff M ) (car_monic M),
},
{
unfold term_wihout,
apply degree_prod_le_one_lt_card((λ ℓ, car_matrix M (σ ℓ) ℓ )),
intros ℓ, refine degree_le_one M _ _,
rcases equiv_not_id (σ ) h with ⟨ℓ0 ,hyp_l0 ⟩ ,
use ℓ0,
exact degree_coef_lt_one M hyp_l0,
},
end
lemma degree_term (σ : equiv.perm A) :
if σ = 1 then degree (term M σ) = fintype.card A else degree (term M σ) < fintype.card A :=
begin
rw degree_term_eq_degree_term_without, exact degree_term_wihout M σ,
end
lemma degree_term_id : degree (term M (1 : equiv.perm A)) = fintype.card A :=
begin
let g := degree_term M (1 : equiv.perm A),
split_ifs at g, exact g, trivial,
end
lemma degree_term_ne (σ : equiv.perm A) (hyp : 1 ≠ σ ) : degree (term M σ) < fintype.card A :=
begin
let g := degree_term M σ ,
split_ifs at g, rw h at hyp,trivial, exact g,
end
lemma degree_car : degree (car_pol M) = fintype.card A :=
begin
unfold car_pol, unfold det,
rw ← degree_term_id M,
apply proof_strategy.car_pol_degree(term M),
rw degree_term_id M,
exact degree_term_ne M,
rw degree_term_id, exact bot_lt_some _,
end
theorem eigen_values_exist_mat (hyp : 0 < fintype.card A ): ∀ M : matrix A A ℂ , ∃ t : ℂ, det ( M + t •(1 : matrix A A ℂ )) = 0
:= begin
intros M,
let χ := car_pol M,
let FTOA := @complex.exists_root χ,
have : 0 < degree χ,
erw degree_car, apply coe_lt_coe.mpr,exact hyp,
specialize FTOA this,
rcases FTOA with ⟨ ζ,hyp⟩ ,
use ζ,
rw ← eval_car_poly M ζ ,
exact hyp,
end
end car_pol |
c200dd20315326ab4da09069d8dbc2357094216e | b7fc5b86b12212bea5542eb2c9d9f0988fd78697 | /src/solutions/thursday/linear_algebra.lean | 8cbce8f992af4af0791cb53fd974b6dd0907c7dc | [] | no_license | stjordanis/lftcm2020 | 3b16591aec853c8546d9c8b69c0bf3f5f3956fee | 1f3485e4dafdc587b451ec5144a1d8d3ec9b411e | refs/heads/master | 1,675,958,865,413 | 1,609,901,722,000 | 1,609,901,722,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,273 | lean | import analysis.normed_space.inner_product
import data.matrix.notation
import linear_algebra.bilinear_form
import linear_algebra.matrix
import tactic
universes u v
section exercise1
namespace semimodule
variables (R M : Type*) [comm_semiring R] [add_comm_monoid M] [semimodule R M]
/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exercise 1: defining modules and submodules
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/
/-- The endomorphisms of an `R`-semimodule `M` are the `R`-linear maps from `M` to `M`. -/
def End := M →ₗ[R] M
/-- The following line tells Lean we can apply `f : End R M` as if it was a function. -/
instance : has_coe_to_fun (End R M) := { F := λ _, M → M, coe := linear_map.to_fun }
/-- Endomorphisms inherit the pointwise addition operator from linear maps. -/
instance : add_comm_monoid (End R M) := linear_map.add_comm_monoid
/- Define the identity endomorphism `id`. -/
def End.id : End R M :=
-- sorry
{ to_fun := λ x, x,
map_add' := λ x y, rfl,
map_smul' := λ s x, rfl }
-- sorry
/-
Show that the endomorphisms of `M` form a semimodule over `R`.
Hint: we can re-use the scalar multiplication of linear maps using the `refine` tactic:
```
refine { smul := linear_map.has_scalar.smul, .. },
```
This will fill in the `smul` field of the `semimodule` structure with the given value.
The remaining fields become goals that you can fill in yourself.
Hint: Prove the equalities using the semimodule structure on `M`.
If `f` and `g` are linear maps, the `ext` tactic turns the goal `f = g` into `∀ x, f x = g x`.
-/
instance : semimodule R (End R M) :=
begin
-- sorry
refine { smul := linear_map.has_scalar.smul, ..},
{ intros f, ext x, apply one_smul },
{ intros a b f, ext x, apply mul_smul },
{ intros a f g, ext x, apply smul_add },
{ intros a, ext x, apply smul_zero },
{ intros a b f, ext x, apply add_smul },
{ intros f, ext x, apply zero_smul }
-- or:
-- refine { smul := linear_map.has_scalar.smul, ..}; intros; ext; simp
-- sorry
end
variables {R M}
/- Bonus exercise: define the submodule of `End R M` consisting of the scalar multiplications.
That is, `f ∈ homothety R M` iff `f` is of the form `λ (x : M), s • x` for some `s : R`.
Hints:
* You could specify the carrier subset and show it is closed under the operations.
* You could instead use library functions: try `submodule.map` or `linear_map.range`.
-/
def homothety : submodule R (End R M) :=
-- sorry
{ carrier := { f | ∃ (s : R), (∀ (x : M), f x = s • x) },
zero_mem' := ⟨0, by simp⟩,
add_mem' := λ f g hf hg, begin
obtain ⟨r, hr⟩ := hf,
obtain ⟨s, hs⟩ := hg,
use r + s,
intro x,
simp [hr, hs, add_smul]
end,
smul_mem' := λ c f hf, begin
obtain ⟨r, hr⟩ := hf,
use c * r,
simp [hr, mul_smul]
end }
-- or:
def smulₗ (s : R) : End R M :=
{ to_fun := λ x, s • x,
map_smul' := smul_comm s,
map_add' := smul_add s }
def to_homothety : R →ₗ[R] End R M :=
{ to_fun := smulₗ,
map_smul' := by { intros, ext, simp [smulₗ, mul_smul] },
map_add' := by { intros, ext, simp [smulₗ, add_smul] } }
def homothety' : submodule R (End R M) :=
linear_map.range to_homothety
-- sorry
end semimodule
end exercise1
section exercise2
namespace matrix
variables {m n R M : Type} [fintype m] [fintype n] [comm_ring R] [add_comm_group M] [module R M]
/- The following line allows us to write `⬝` (`\cdot`) and `ᵀ` (`\^T`) for
matrix multiplication and transpose. -/
open_locale matrix
/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exercise 2: working with matrices
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/
/-- Prove the following four lemmas, that were missing from `mathlib`.
Hints:
* Look up the definition of `vec_mul` and `mul_vec`.
* Search the library for useful lemmas about the function used in that definition.
-/
@[simp] lemma add_vec_mul (v w : m → R) (M : matrix m n R) :
vec_mul (v + w) M = vec_mul v M + vec_mul w M :=
-- sorry
by { ext, apply add_dot_product }
-- sorry
@[simp] lemma smul_vec_mul (x : R) (v : m → R) (M : matrix m n R) :
vec_mul (x • v) M = x • vec_mul v M :=
-- sorry
by { ext, apply smul_dot_product }
-- sorry
@[simp] lemma mul_vec_add (M : matrix m n R) (v w : n → R) :
mul_vec M (v + w) = mul_vec M v + mul_vec M w :=
-- sorry
by { ext, apply dot_product_add }
-- sorry
@[simp] lemma mul_vec_smul (M : matrix m n R) (x : R) (v : n → R) :
mul_vec M (x • v) = x • mul_vec M v :=
-- sorry
by { ext, apply dot_product_smul }
-- sorry
/- Define the canonical map from bilinear forms to matrices.
We assume `R` has a basis `v` indexed by `ι`.
Hint: Follow your nose, the types will guide you.
A matrix `A : matrix ι ι R` is not much more than a function `ι → ι → R`,
and a bilinear form is not much more than a function `M → M → R`. -/
def bilin_form_to_matrix {ι : Type*} [fintype ι] (v : ι → M)
(B : bilin_form R M) : matrix ι ι R :=
-- sorry
λ i j, B (v i) (v j)
-- sorry
/-- Define the canonical map from matrices to bilinear forms.
For a matrix `A`, `to_bilin_form A` should take two vectors `v`, `w`
and multiply `A` by `v` on the left and `v` on the right.
-/
def matrix_to_bilin_form (A : matrix n n R) : bilin_form R (n → R) :=
-- sorry
{ bilin := λ v w, dot_product v (mul_vec A w),
bilin_add_left := by { intros, rw [add_dot_product] },
bilin_add_right := by { intros, rw [mul_vec_add, dot_product_add] },
bilin_smul_left := by { intros, rw [smul_dot_product] },
bilin_smul_right := by { intros, rw [mul_vec_smul, dot_product_smul] } }
-- sorry
/- Can you define a bilinear form directly that is equivalent to this matrix `A`?
Don't use `bilin_form_to_matrix`, give the map explicitly in the form `λ v w, _`.
Check your definition by putting your cursor on the lines starting with `#eval`.
Hints:
* Use the `simp` tactic to simplify `(x + y) i` to `x i + y i` and `(s • x) i` to `s * x i`.
* To deal with equalities containing many `+` and `*` symbols, use the `ring` tactic.
-/
def A : matrix (fin 2) (fin 2) R := ![![1, 0], ![-2, 1]]
def your_bilin_form : bilin_form R (fin 2 → R) :=
-- sorry
{ bilin := λ v w, v 0 * w 0 + v 1 * w 1 - 2 * v 1 * w 0,
bilin_add_left := by { intros, simp, ring },
bilin_add_right := by { intros, simp, ring },
bilin_smul_left := by { intros, simp, ring },
bilin_smul_right := by { intros, simp, ring } }
-- sorry
/- Check your definition here, by uncommenting the #eval lines: -/
def v : fin 2 → ℤ := ![1, 3]
def w : fin 2 → ℤ := ![2, 4]
-- #eval matrix_to_bilin_form A v w
-- #eval your_bilin_form v w
end matrix
end exercise2
section exercise3
namespace pi
variables {n : Type*} [fintype n]
open matrix
/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exercise 3: inner product spaces
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/
/- Use the `dot_product` function to put an inner product on `n → R`.
Hints:
* Try the lemmas `finset.sum_nonneg`, `finset.sum_eq_zero_iff_of_nonneg`,
`mul_self_nonneg` and `mul_self_eq_zero`.
-/
noncomputable instance : inner_product_space ℝ (n → ℝ) :=
inner_product_space.of_core
-- sorry
{ inner := dot_product,
nonneg_re := λ x, finset.sum_nonneg (λ i _, mul_self_nonneg _),
nonneg_im := λ x, by simp,
definite := λ x hx, funext (λ i, mul_self_eq_zero.mp
((finset.sum_eq_zero_iff_of_nonneg (λ i _, mul_self_nonneg (x i))).mp hx i (finset.mem_univ i))),
conj_sym := λ x y, dot_product_comm _ _,
add_left := λ x y z, add_dot_product _ _ _,
smul_left := λ s x y, smul_dot_product _ _ _ }
-- sorry
end pi
end exercise3
section exercise4
namespace pi
variables (R n : Type) [comm_ring R] [fintype n] [decidable_eq n]
/- Enable sum and product notation with `∑` and `∏`. -/
open_locale big_operators
/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Exercise 4: basis and dimension
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/
/-- The `i`'th vector in the standard basis of `n → R` is `1` at the `i`th entry
and `0` otherwise. -/
def std_basis (i : n) : (n → R) := λ j, if i = j then 1 else 0
/- Bonus exercise: Show the standard basis of `n → R` is a basis.
This is a difficult exercise, so feel free to skip some parts.
Hints for showing linear independence:
* Try using the lemma `linear_independent_iff` or `linear_independent_iff'`.
* To derive `f x = 0` from `h : f = 0`, use a tactic `have := congr_fun h x`.
* Take a term out of a sum by combining `finset.insert_erase` and `finset.sum_insert`.
Hints for showing it spans the whole module:
* To show equality of set-like terms, apply the `ext` tactic.
* First show `x = ∑ i, x i • std_basis R n i`, then rewrite with this equality.
-/
lemma std_basis_is_basis : is_basis R (std_basis R n) :=
-- sorry
begin
split,
{ apply linear_independent_iff'.mpr,
intros s v hs i hi,
have hs : s.sum (λ (i : n), v i • std_basis R n i) i = 0 := congr_fun hs i,
unfold std_basis at hs,
rw [←finset.insert_erase hi, finset.sum_insert (finset.not_mem_erase i s)] at hs,
simpa using hs },
{ ext,
simp only [submodule.mem_top, iff_true],
rw (show x = ∑ i, x i • std_basis R n i, by { ext, simp [std_basis] }),
refine submodule.sum_mem _ (λ i _, _),
refine submodule.smul_mem _ _ _,
apply submodule.subset_span,
apply set.mem_range_self }
end
-- sorry
variables {K : Type} [field K]
/-
Conclude `n → K` is a finite dimensional vector space for each field `K`
and the dimension of `n → K` over `K` is the cardinality of `n`.
You don't need to complete `std_basis_is_basis` to prove these two lemmas.
Hint: search the library for appropriate lemmas.
-/
lemma finite_dimensional : finite_dimensional K (n → K) :=
-- sorry
finite_dimensional.of_fintype_basis (std_basis_is_basis K n)
-- sorry
lemma findim_eq : finite_dimensional.findim K (n → K) = fintype.card n :=
-- sorry
finite_dimensional.findim_eq_card_basis (std_basis_is_basis K n)
-- sorry
end pi
end exercise4
|
8a475ac85a6df5f56fe90ec01102bd1a168e0b5c | 6b10c15e653d49d146378acda9f3692e9b5b1950 | /examples/introduction/unnamed_59.lean | 33a9be601ace0e471faa714e3263445ead05c1a0 | [] | no_license | gebner/mathematics_in_lean | 3cf7f18767208ea6c3307ec3a67c7ac266d8514d | 6d1462bba46d66a9b948fc1aef2714fd265cde0b | refs/heads/master | 1,655,301,945,565 | 1,588,697,505,000 | 1,588,697,505,000 | 261,523,603 | 0 | 0 | null | 1,588,695,611,000 | 1,588,695,610,000 | null | UTF-8 | Lean | false | false | 102 | lean | -- Give an example here
-- Instead of a ``try it!'' button,
-- there should be a ``see more!`` button. |
4f44ff377805ff8c6385140a22d39baca24c8484 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/set_theory/ordinal_arithmetic.lean | ab6ad7df3f5b44528157cb188e55c11007f83b8c | [
"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 | 70,455 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn
-/
import set_theory.ordinal
/-!
# Ordinal arithmetic
Ordinals have an addition (corresponding to disjoint union) that turns them into an additive
monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns
them into a monoid. One can also define correspondingly a subtraction, a division, a successor
function, a power function and a logarithm function.
We also define limit ordinals and prove the basic induction principle on ordinals separating
successor ordinals and limit ordinals, in `limit_rec_on`.
## Main definitions and results
* `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`.
* `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`.
* `o₁ * o₂` is the lexicographic order on `o₂ × o₁`.
* `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the
divisibility predicate, and a modulo operation.
* `succ o = o + 1` is the successor of `o`.
* `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`.
We also define the power function and the logarithm function on ordinals, and discuss the properties
of casts of natural numbers of and of `omega` with respect to these operations.
Some properties of the operations are also used to discuss general tools on ordinals:
* `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor.
* `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals.
* `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing
and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`.
* `nfp f a`: the next fixed point of a function `f` on ordinals, above `a`. It behaves well
for normal functions.
* `CNF b o` is the Cantor normal form of the ordinal `o` in base `b`.
* `sup`: the supremum of an indexed family of ordinals in `Type u`, as an ordinal in `Type u`.
* `bsup`: the supremum of a set of ordinals indexed by ordinals less than a given ordinal `o`.
-/
noncomputable theory
open function cardinal set equiv
open_locale classical cardinal
universes u v w
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
namespace ordinal
/-! ### Further properties of addition on ordinals -/
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
by unfold succ; simp only [lift_add, lift_one]
theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c :=
⟨induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨
have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a,
by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply]
using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂)
((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a,
have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin
intro b, cases e : f (sum.inr b),
{ rw ← fl at e, have := f.inj' e, contradiction },
{ exact ⟨_, rfl⟩ }
end,
let g (b) := (this b).1 in
have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2,
⟨⟨⟨g, λ x y h, by injection f.inj'
(by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩,
λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding,
initial_seg.coe_fn_to_rel_embedding, function.embedding.coe_fn_mk]
using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩,
λ a b H, begin
rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩,
{ rw fl at h, cases h },
{ rw fr at h, exact ⟨a', sum.inr.inj h⟩ }
end⟩⟩,
λ h, add_le_add_left h _⟩
theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) :=
(add_assoc _ _ _).symm
@[simp] theorem succ_zero : succ 0 = 1 := zero_add _
theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 :=
by rw [one_le_iff_pos, ordinal.pos_iff_ne_zero]
theorem succ_pos (o : ordinal) : 0 < succ o :=
lt_of_le_of_lt (ordinal.zero_le _) (lt_succ_self _)
theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 :=
ne_of_gt $ succ_pos o
@[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 :=
by simp only [succ, card_add, card_one]
theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl
theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c :=
by simp only [le_antisymm_iff, add_le_add_iff_left]
theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c :=
by rw [← not_le, ← not_le, add_le_add_iff_left]
theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c :=
lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _)
@[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b :=
by rw [lt_succ, succ_le]
@[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 succ_lt_succ
theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b :=
by simp only [le_antisymm_iff, succ_le_succ]
theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b :=
by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero],
rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]]
theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b :=
by simp only [le_antisymm_iff, add_le_add_iff_right]
/-! ### The zero ordinal -/
@[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 :=
⟨induction_on o $ λ α r _ h, begin
refine le_antisymm (le_of_not_lt $
λ hn, mk_ne_zero_iff.2 _ h) (ordinal.zero_le _),
rw [← succ_le, succ_zero] at hn, cases hn with f,
exact ⟨f punit.star⟩
end, λ e, by simp only [e, card_zero]⟩
@[simp] theorem type_eq_zero_of_empty [is_well_order α r] [is_empty α] : type r = 0 :=
card_eq_zero.symm.mpr (mk_eq_zero _)
@[simp] theorem type_eq_zero_iff_is_empty [is_well_order α r] : type r = 0 ↔ is_empty α :=
(@card_eq_zero (type r)).symm.trans mk_eq_zero_iff
theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α :=
(not_congr (@card_eq_zero (type r))).symm.trans mk_ne_zero_iff
protected lemma one_ne_zero : (1 : ordinal) ≠ 0 :=
type_ne_zero_iff_nonempty.2 ⟨punit.star⟩
instance : nontrivial ordinal.{u} :=
⟨⟨1, 0, ordinal.one_ne_zero⟩⟩
theorem zero_lt_one : (0 : ordinal) < 1 :=
lt_iff_le_and_ne.2 ⟨ordinal.zero_le _, ne.symm $ ordinal.one_ne_zero⟩
/-! ### The predecessor of an ordinal -/
/-- The ordinal predecessor of `o` is `o'` if `o = succ o'`,
and `o` otherwise. -/
def pred (o : ordinal.{u}) : ordinal.{u} :=
if h : ∃ a, o = succ a then classical.some h else o
@[simp] theorem pred_succ (o) : pred (succ o) = o :=
by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩;
simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm
theorem pred_le_self (o) : pred o ≤ o :=
if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in
by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _)
else by rw [pred, dif_neg h]
theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a :=
⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e,
λ h, dif_neg h⟩
theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a :=
iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le])
(iff_not_comm.1 pred_eq_iff_not_succ).symm
theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a :=
⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩
theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o :=
⟨lt_trans (lt_succ_self _), λ l,
lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩
theorem lt_pred {a b} : a < pred b ↔ succ a < b :=
if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in
by rw [e, pred_succ, succ_lt_succ]
else by simp only [pred, dif_neg h, succ_lt_of_not_succ h]
theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b :=
le_iff_le_iff_lt_iff_lt.2 lt_pred
@[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) :=
⟨λ ⟨a, h⟩,
let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $
h.symm ▸ lt_succ_self _ in
⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩,
λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩
@[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) :=
if h : ∃ a, o = succ a then
by cases h with a e; simp only [e, pred_succ, lift_succ]
else by rw [pred_eq_iff_not_succ.2 h,
pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)]
/-! ### Limit ordinals -/
/-- A limit ordinal is an ordinal which is not zero and not a successor. -/
def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o
theorem not_zero_is_limit : ¬ is_limit 0
| ⟨h, _⟩ := h rfl
theorem not_succ_is_limit (o) : ¬ is_limit (succ o)
| ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _))
theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a
| ⟨a, e⟩ := not_succ_is_limit a (e ▸ h)
theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o :=
⟨lt_trans (lt_succ_self _), h.2 _⟩
theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a :=
le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h
theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a :=
⟨λ h x l, le_trans (le_of_lt l) h,
λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn,
not_lt_of_le (H _ hn) (lt_succ_self _)⟩
theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x :=
by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a)
@[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o :=
and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0)
⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h),
λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
by rw [← e, ← lift_succ, lift_lt];
rw [← e, lift_lt] at h; exact H a' h⟩
theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o :=
lt_of_le_of_ne (ordinal.zero_le _) h.1.symm
theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o :=
by simpa only [succ_zero] using h.2 _ h.pos
theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := h.pos
| (n+1) := h.2 _ (is_limit.nat_lt n)
theorem zero_or_succ_or_limit (o : ordinal) :
o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o :=
if o0 : o = 0 then or.inl o0 else
if h : ∃ a, o = succ a then or.inr (or.inl h) else
or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩
/-- Main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/
@[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*}
(o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o))
(H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o :=
wf.fix (λ o IH,
if o0 : o = 0 then by rw o0; exact H₁ else
if h : ∃ a, o = succ a then
by rw ← succ_pred_iff_is_succ.2 h; exact
H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h)
else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o
@[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ :=
by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl
@[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) :
@limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) :=
begin
have h : ∃ a, succ o = succ a := ⟨_, rfl⟩,
rw [limit_rec_on, well_founded.fix_eq,
dif_neg (succ_ne_zero o), dif_pos h],
generalize : limit_rec_on._proof_2 (succ o) h = h₂,
generalize : limit_rec_on._proof_3 (succ o) h = h₃,
revert h₂ h₃, generalize e : pred (succ o) = o', intros,
rw pred_succ at e, subst o', refl
end
@[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) :
@limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) :=
by rw [limit_rec_on, well_founded.fix_eq,
dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl
lemma has_succ_of_is_limit {α} {r : α → α → Prop} [wo : is_well_order α r]
(h : (type r).is_limit) (x : α) : ∃y, r x y :=
begin
use enum r (typein r x).succ (h.2 _ (typein_lt_type r x)),
convert (enum_lt (typein_lt_type r x) _).mpr (lt_succ_self _), rw [enum_typein]
end
lemma type_subrel_lt (o : ordinal.{u}) :
type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u+1} o :=
begin
refine quotient.induction_on o _,
rintro ⟨α, r, wo⟩, resetI, apply quotient.sound,
constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (typein_iso r)
end
lemma mk_initial_seg (o : ordinal.{u}) :
#{o' : ordinal | o' < o} = cardinal.lift.{u+1} o.card :=
by rw [lift_card, ←type_subrel_lt, card_type]
/-! ### Normal ordinal functions -/
/-- A normal ordinal function is a strictly increasing function which is
order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`. -/
def is_normal (f : ordinal → ordinal) : Prop :=
(∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a
theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o →
∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2
theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} :
a < f o ↔ ∃ b < o, a < f b :=
not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a
theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b :=
strict_mono.lt_iff_lt $ λ a b,
limit_rec_on b (not.elim (not_lt_of_le $ ordinal.zero_le _))
(λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim
(λ h, lt_trans (IH h) (H.1 _))
(λ e, e ▸ H.1 _))
(λ b l IH h, lt_of_lt_of_le (H.1 a)
((H.2 _ l _).1 (le_refl _) _ (l.2 _ h)))
theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_iff
theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b :=
by simp only [le_antisymm_iff, H.le_iff]
theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a :=
limit_rec_on a (ordinal.zero_le _)
(λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _))
(λ a l IH, (limit_le l).2 $ λ b h,
le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h)
theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f a ≤ o :=
⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h,
λ h, begin
revert H₂, apply limit_rec_on S,
{ intro H₂,
cases p0 with x px,
have := ordinal.le_zero.1 ((H₂ _).1 (ordinal.zero_le _) _ px),
rw this at px, exact h _ px },
{ intros S _ H₂,
rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) },
{ intros S L _ H₂, apply (H.2 _ L _).2, intros a h',
rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) }
end⟩
theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o :=
(H.le_set (λ x, ∃ y, p y ∧ x = g y)
(let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _
(λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1,
λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans
⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩
theorem is_normal.refl : is_normal id :=
⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩
theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) :
is_normal (λ x, f (g x)) :=
⟨λ x, H₁.lt_iff.2 (H₂.1 _),
λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩
theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) :
is_limit (f o) :=
⟨ne_of_gt $ lt_of_le_of_lt (ordinal.zero_le _) $ H.lt_iff.2 l.pos,
λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in
lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩
theorem add_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c :=
⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h,
λ H, le_of_not_lt $
induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin
resetI,
suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l),
{ cases enum _ _ l with x x,
{ cases this (enum s 0 h.pos) },
{ exact irrefl _ (this _) } },
intros x,
rw [← typein_lt_typein (sum.lex r s), typein_enum],
have := H _ (h.2 _ (typein_lt_type s x)),
rw [add_succ, succ_le] at this,
refine lt_of_le_of_lt (type_le'.2
⟨rel_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this,
{ rcases a with ⟨a | b, h⟩,
{ exact sum.inl a },
{ exact sum.inr ⟨b, by cases h; assumption⟩ } },
{ rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂;
rintro ⟨⟩; constructor; assumption }
end) h H⟩
theorem add_is_normal (a : ordinal) : is_normal ((+) a) :=
⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _),
λ b l c, add_le_of_limit l⟩
theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) :=
(add_is_normal a).is_limit
/-! ### Subtraction on ordinals-/
/-- `a - b` is the unique ordinal satisfying
`b + (a - b) = a` when `b ≤ a`. -/
def sub (a b : ordinal.{u}) : ordinal.{u} :=
omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩
instance : has_sub ordinal := ⟨sub⟩
theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) :=
omin_mem {o | a ≤ b+o} _
theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c :=
⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _),
λ h, omin_le h⟩
theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b :=
lt_iff_lt_of_le_iff_le sub_le
theorem add_sub_cancel (a b : ordinal) : a + b - a = b :=
le_antisymm (sub_le.2 $ le_refl _)
((add_le_add_iff_left a).1 $ le_add_sub _ _)
theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b :=
h ▸ add_sub_cancel _ _
theorem sub_le_self (a b : ordinal) : a - b ≤ a :=
sub_le.2 $ le_add_left _ _
protected theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a :=
le_antisymm begin
rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l,
{ simp only [e, add_zero, h] },
{ rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self },
{ exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) }
end (le_add_sub _ _)
@[simp] theorem sub_zero (a : ordinal) : a - 0 = a :=
by simpa only [zero_add] using add_sub_cancel 0 a
@[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 :=
by rw ← ordinal.le_zero; apply sub_le_self
@[simp] theorem sub_self (a : ordinal) : a - a = 0 :=
by simpa only [add_zero] using add_sub_cancel a 0
protected theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b :=
⟨λ h, by simpa only [h, add_zero] using le_add_sub a b,
λ h, by rwa [← ordinal.le_zero, sub_le, add_zero]⟩
theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) :=
eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc]
theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c :=
by rw [← sub_sub, add_sub_cancel]
theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) :=
⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero,
λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩
@[simp] theorem one_add_omega : 1 + omega.{u} = omega :=
begin
refine le_antisymm _ (le_add_left _ _),
rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add],
have : is_well_order unit empty_relation := by apply_instance,
refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩,
{ apply sum.rec, exact λ _, 0, exact nat.succ },
{ intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H;
[cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] }
end
@[simp, priority 990]
theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o :=
by rw [← ordinal.add_sub_cancel_of_le h, ← add_assoc, one_add_omega]
/-! ### Multiplication of ordinals-/
/-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on
`o₂ × o₁`. -/
instance : monoid ordinal.{u} :=
{ mul := λ a b, quotient.lift_on₂ a b
(λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧
: Well_order → Well_order → ordinal) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
quot.sound ⟨rel_iso.prod_lex_congr g f⟩,
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin
rcases a with ⟨⟨a₁, a₂⟩, a₃⟩,
rcases b with ⟨⟨b₁, b₂⟩, b₃⟩,
simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc]
end⟩⟩,
mul_one := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩;
simp only [prod.lex_def, empty_relation, false_or];
simp only [eq_self_iff_true, true_and]; refl⟩⟩,
one_mul := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩;
simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ }
@[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop)
[is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem card_mul (a b) : card (a * b) = card a * card b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
mul_comm (mk β) (mk α)
@[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 :=
induction_on a $ λ α _ _, by exactI type_eq_zero_of_empty
@[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 :=
induction_on a $ λ α _ _, by exactI type_eq_zero_of_empty
theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin
rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def,
sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr,
sum_prod_distrib_apply_left, sum_prod_distrib_apply_right];
simp only [sum.inl.inj_iff, true_or, false_and, false_or]
end⟩⟩
@[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a :=
by simp only [mul_add, mul_one]
@[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _
theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨rel_embedding.of_monotone
(λ a, (f a.1, a.2))
(λ a b h, _)⟩, clear_,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.2 h') },
{ exact prod.lex.right _ h' }
end
theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨rel_embedding.of_monotone
(λ a, (a.1, f a.2))
(λ a b h, _)⟩,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ h' },
{ exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.2 h') }
end
theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d :=
le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁)
private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s]
{c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c)
(l : c < type r * type s) : false :=
begin
suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l),
{ cases enum _ _ l with b a, exact irrefl _ (this _ _) },
intros a b,
rw [← typein_lt_typein (prod.lex s r), typein_enum],
have := H _ (h.2 _ (typein_lt_type s b)),
rw [mul_succ] at this,
have := lt_of_lt_of_le ((add_lt_add_iff_left _).2
(typein_lt_type _ a)) this,
refine lt_of_le_of_lt _ this,
refine (type_le'.2 _),
constructor,
refine rel_embedding.of_monotone (λ a, _) (λ a b, _),
{ rcases a with ⟨⟨b', a'⟩, h⟩,
by_cases e : b = b',
{ refine sum.inr ⟨a', _⟩,
subst e, cases h with _ _ _ _ h _ _ _ h,
{ exact (irrefl _ h).elim },
{ exact h } },
{ refine sum.inl (⟨b', _⟩, a'),
cases h with _ _ _ _ h _ _ _ h,
{ exact h }, { exact (e rfl).elim } } },
{ rcases a with ⟨⟨b₁, a₁⟩, h₁⟩,
rcases b with ⟨⟨b₂, a₂⟩, h₂⟩,
intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂,
{ substs b₁ b₂,
simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true,
dif_pos, sum.lex_inr_inr] using h },
{ subst b₁,
simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true,
or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢,
cases h₂; [exact asymm h h₂_h, exact e₂ rfl] },
{ simp only [e₂, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] },
{ simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk,
sum.lex_inl_inl] using h } }
end
theorem mul_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c :=
⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h,
λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _,
by exactI mul_le_of_limit_aux) h H⟩
theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) :=
⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h,
λ b l c, mul_le_of_limit l⟩
theorem lt_mul_of_limit {a b c : ordinal.{u}}
(h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' :=
by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h)
theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c :=
(mul_is_normal a0).lt_iff
theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c :=
(mul_is_normal a0).le_iff
theorem mul_lt_mul_of_pos_left {a b c : ordinal}
(h : a < b) (c0 : 0 < c) : c * a < c * b :=
(mul_lt_mul_iff_left c0).2 h
theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b :=
by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁
theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 :=
by simpa only [ordinal.pos_iff_ne_zero] using mul_pos
theorem le_of_mul_le_mul_left {a b c : ordinal}
(h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b :=
le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h
theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c :=
(mul_is_normal a0).inj
theorem mul_is_limit {a b : ordinal}
(a0 : 0 < a) : is_limit b → is_limit (a * b) :=
(mul_is_normal a0).is_limit
theorem mul_is_limit_left {a b : ordinal}
(l : is_limit a) (b0 : 0 < b) : is_limit (a * b) :=
begin
rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb,
{ exact (lt_irrefl _).elim b0 },
{ rw mul_succ, exact add_is_limit _ l },
{ exact mul_is_limit l.pos lb }
end
/-! ### Division on ordinals -/
protected lemma div_aux (a b : ordinal.{u}) (h : b ≠ 0) : set.nonempty {o | a < b * succ o} :=
⟨a, succ_le.1 $
by simpa only [succ_zero, one_mul]
using mul_le_mul_right (succ a) (succ_le.2 (ordinal.pos_iff_ne_zero.2 h))⟩
/-- `a / b` is the unique ordinal `o` satisfying
`a = b * o + o'` with `o' < b`. -/
protected def div (a b : ordinal.{u}) : ordinal.{u} :=
if h : b = 0 then 0 else omin {o | a < b * succ o} (ordinal.div_aux a b h)
instance : has_div ordinal := ⟨ordinal.div⟩
@[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl
lemma div_def (a) {b : ordinal} (h : b ≠ 0) :
a / b = omin {o | a < b * succ o} (ordinal.div_aux a b h) := dif_neg h
theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) :=
by rw div_def a h; exact omin_mem {o | a < b * succ o} _
theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b :=
by simpa only [mul_succ] using lt_mul_succ_div a h
theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c :=
⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h),
λ h, by rw div_def a b0; exact omin_le h⟩
theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b :=
by rw [← not_le, div_le c0, not_lt]
theorem le_div {a b c : ordinal} (c0 : c ≠ 0) :
a ≤ b / c ↔ c * a ≤ b :=
begin
apply limit_rec_on a,
{ simp only [mul_zero, ordinal.zero_le] },
{ intros, rw [succ_le, lt_div c0] },
{ simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} }
end
theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) :
a / b < c ↔ a < b * c :=
lt_iff_lt_of_le_iff_le $ le_div b0
theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c :=
if b0 : b = 0 then by simp only [b0, div_zero, ordinal.zero_le] else
(div_le b0).2 $ lt_of_le_of_lt h $
mul_lt_mul_of_pos_left (lt_succ_self _) (ordinal.pos_iff_ne_zero.2 b0)
theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b :=
lt_imp_lt_of_le_imp_le div_le_of_le_mul
@[simp] theorem zero_div (a : ordinal) : 0 / a = 0 :=
ordinal.le_zero.1 $ div_le_of_le_mul $ ordinal.zero_le _
theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a :=
if b0 : b = 0 then by simp only [b0, zero_mul, ordinal.zero_le] else (le_div b0).1 (le_refl _)
theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b :=
begin
apply le_antisymm,
{ apply (div_le b0).2,
rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left],
apply lt_mul_div_add _ b0 },
{ rw [le_div b0, mul_add, add_le_add_iff_left],
apply mul_div_le }
end
theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 :=
begin
rw [← ordinal.le_zero, div_le $ ordinal.pos_iff_ne_zero.1 $ lt_of_le_of_lt (ordinal.zero_le _) h],
simpa only [succ_zero, mul_one] using h
end
@[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a :=
by simpa only [add_zero, zero_div] using mul_add_div a b0 0
@[simp] theorem div_one (a : ordinal) : a / 1 = a :=
by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero
@[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 :=
by simpa only [mul_one] using mul_div_cancel 1 h
theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c :=
if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else
eq_of_forall_ge_iff $ λ d,
by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0]
theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) :=
begin
split; intro h,
{ by_cases h' : b = 0,
{ rw [h', add_zero] at h, right, exact ⟨h', h⟩ },
left, rw [←add_sub_cancel a b], apply sub_is_limit h,
suffices : a + 0 < a + b, simpa only [add_zero],
rwa [add_lt_add_iff_left, ordinal.pos_iff_ne_zero] },
rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero]
end
theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c)
| a _ c ⟨b, rfl⟩ :=
⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩,
λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩
theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c :=
(dvd_add_iff h₁).2
theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩
theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 :=
⟨λ ⟨h, e⟩, by simp only [e, zero_mul], λ e, e.symm ▸ dvd_zero _⟩
theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩
theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b
| a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0]
theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b
| a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a
(one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0))
theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b :=
if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else
if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else
le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂)
/-- `a % b` is the unique ordinal `o'` satisfying
`a = b * o + o'` with `o' < b`. -/
instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩
theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl
@[simp] theorem mod_zero (a : ordinal) : a % 0 = a :=
by simp only [mod_def, div_zero, zero_mul, sub_zero]
theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a :=
by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero]
@[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 :=
by simp only [mod_def, zero_div, mul_zero, sub_self]
theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a :=
ordinal.add_sub_cancel_of_le $ mul_div_le _ _
theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b :=
(add_lt_add_iff_left (b * (a / b))).1 $
by rw div_add_mod; exact lt_mul_div_add a h
@[simp] theorem mod_self (a : ordinal) : a % a = 0 :=
if a0 : a = 0 then by simp only [a0, zero_mod] else
by simp only [mod_def, div_self a0, mul_one, sub_self]
@[simp] theorem mod_one (a : ordinal) : a % 1 = 0 :=
by simp only [mod_def, div_one, one_mul, sub_self]
/-! ### Supremum of a family of ordinals -/
/-- The supremum of a family of ordinals -/
def sup {ι} (f : ι → ordinal) : ordinal :=
omin {c | ∀ i, f i ≤ c}
⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $
cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩
theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f :=
omin_mem {c | ∀ i, f i ≤ c} _
theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩
theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i :=
by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a)
theorem is_normal.sup {f} (H : is_normal f)
{ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) :=
eq_of_forall_ge_iff $ λ a,
by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)];
intros; simp only [sup_le, true_implies_iff]
theorem sup_ord {ι} (f : ι → cardinal) : sup (λ i, (f i).ord) = (cardinal.sup f).ord :=
eq_of_forall_ge_iff $ λ a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le]
lemma sup_succ {ι} (f : ι → ordinal) : sup (λ i, succ (f i)) ≤ succ (sup f) :=
by { rw [ordinal.sup_le], intro i, rw ordinal.succ_le_succ, apply ordinal.le_sup }
lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α)
(h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) :=
begin
apply (not_bounded_iff _).mp, rintro ⟨x, hx⟩, apply not_lt_of_ge h,
refine lt_of_le_of_lt _ (typein_lt_type r x), rw [sup_le], intro y,
apply le_of_lt, rw typein_lt_typein, apply hx, apply mem_range_self
end
/-- The supremum of a family of ordinals indexed by the set
of ordinals less than some `o : ordinal.{u}`.
(This is not a special case of `sup` over the subtype,
because `{a // a < o} : Type (u+1)` and `sup` only works over
families in `Type u`.) -/
def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} :=
match o, o.out, o.out_eq with
| _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _))
end
theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a :=
match o, o.out, o.out_eq, f :
∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}),
bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with
| _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI
⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), λ H b, H _ _⟩
end
theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) :
bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) :=
eq_of_forall_ge_iff $ λ o,
by rw [bsup_le, sup_le]; exact
⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩
theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f :=
bsup_le.1 (le_refl _) _ _
theorem lt_bsup {o : ordinal} {f : Π a < o, ordinal}
(hf : ∀{a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha')
(ho : o.is_limit) (i h) : f i h < bsup o f :=
lt_of_lt_of_le (hf _ _ $ lt_succ_self i) (le_bsup f i.succ $ ho.2 _ h)
theorem bsup_id {o} (ho : is_limit o) : bsup.{u u} o (λ x _, x) = o :=
begin
apply le_antisymm, rw [bsup_le], intro i, apply le_of_lt,
rw [←not_lt], intro h, apply lt_irrefl (bsup.{u u} o (λ x _, x)),
apply lt_of_le_of_lt _ (lt_bsup _ ho _ h), refl, intros, assumption
end
theorem is_normal.bsup {f} (H : is_normal f)
{o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0),
f (bsup o g) = bsup o (λ a h, f (g a h)) :=
induction_on o $ λ α r _ g h,
by resetI; rw [bsup_type,
H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type]
theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) :
bsup.{u} o (λx _, f x) = f o :=
by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id h] }
/-! ### Ordinal exponential -/
/-- The ordinal exponential, defined by transfinite recursion. -/
def power (a b : ordinal) : ordinal :=
if a = 0 then 1 - b else
limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b)
instance : has_pow ordinal ordinal := ⟨power⟩
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a :=
by simp only [pow, power, if_pos rfl]
@[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 :=
by rwa [zero_power', ordinal.sub_eq_zero_iff_le, one_le_iff_ne_zero]
@[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 :=
by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero],
simp only [pow, power, if_neg h, limit_rec_on_zero]]
@[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a :=
if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero]
else by simp only [pow, power, limit_rec_on_succ, if_neg h]
theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b = bsup.{u u} b (λ c _, a ^ c) :=
by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl
theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c :=
by rw [power_limit a0 h, bsup_le]
theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) :
a < b ^ c ↔ ∃ c' < c, a < b ^ c' :=
by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and]
@[simp] theorem power_one (a : ordinal) : a ^ 1 = a :=
by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul]
@[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 :=
begin
apply limit_rec_on a,
{ simp only [power_zero] },
{ intros _ ih, simp only [power_succ, ih, mul_one] },
refine λ b l IH, eq_of_forall_ge_iff (λ c, _),
rw [power_le_of_limit ordinal.one_ne_zero l],
exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos,
λ H b' h, by rwa IH _ h⟩,
end
theorem power_pos {a : ordinal} (b)
(a0 : 0 < a) : 0 < a ^ b :=
begin
have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]},
apply limit_rec_on b,
{ exact h0 },
{ intros b IH, rw [power_succ],
exact mul_pos IH a0 },
{ exact λ b l _, (lt_power_of_limit (ordinal.pos_iff_ne_zero.1 a0) l).2
⟨0, l.pos, h0⟩ },
end
theorem power_ne_zero {a : ordinal} (b)
(a0 : a ≠ 0) : a ^ b ≠ 0 :=
ordinal.pos_iff_ne_zero.1 $ power_pos b $ ordinal.pos_iff_ne_zero.2 a0
theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) :=
have a0 : 0 < a, from lt_trans zero_lt_one h,
⟨λ b, by simpa only [mul_one, power_succ] using
(mul_lt_mul_iff_left (power_pos b a0)).2 h,
λ b l c, power_le_of_limit (ne_of_gt a0) l⟩
theorem power_lt_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b < a ^ c ↔ b < c :=
(power_is_normal a1).lt_iff
theorem power_le_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c :=
(power_is_normal a1).le_iff
theorem power_right_inj {a b c : ordinal}
(a1 : 1 < a) : a ^ b = a ^ c ↔ b = c :=
(power_is_normal a1).inj
theorem power_is_limit {a b : ordinal}
(a1 : 1 < a) : is_limit b → is_limit (a ^ b) :=
(power_is_normal a1).is_limit
theorem power_is_limit_left {a b : ordinal}
(l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) :=
begin
rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l',
{ exact absurd e hb },
{ rw power_succ,
exact mul_is_limit (power_pos _ l.pos) l },
{ exact power_is_limit l.one_lt l' }
end
theorem power_le_power_right {a b c : ordinal}
(h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c :=
begin
cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁,
{ exact (power_le_power_iff_right h₁).2 h₂ },
{ subst a, simp only [one_power] }
end
theorem power_le_power_left {a b : ordinal} (c)
(ab : a ≤ b) : a ^ c ≤ b ^ c :=
begin
by_cases a0 : a = 0,
{ subst a, by_cases c0 : c = 0,
{ subst c, simp only [power_zero] },
{ simp only [zero_power c0, ordinal.zero_le] } },
{ apply limit_rec_on c,
{ simp only [power_zero] },
{ intros c IH, simpa only [power_succ] using mul_le_mul IH ab },
{ exact λ c l IH, (power_le_of_limit a0 l).2
(λ b' h, le_trans (IH _ h) (power_le_power_right
(lt_of_lt_of_le (ordinal.pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } }
end
theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b :=
(power_is_normal a1).le_self _
theorem power_lt_power_left_of_succ {a b c : ordinal}
(ab : a < b) : a ^ succ c < b ^ succ c :=
by rw [power_succ, power_succ]; exact
lt_of_le_of_lt
(mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab)
(mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (ordinal.zero_le _) ab)))
theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c :=
begin
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]},
have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le
(ordinal.pos_iff_ne_zero.2 c0) (le_add_left _ _)),
simp only [zero_power c0, zero_power this, mul_zero] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power, mul_one] },
apply limit_rec_on c,
{ simp only [add_zero, power_zero, mul_one] },
{ intros c IH,
rw [add_succ, power_succ, IH, power_succ, mul_assoc] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(add_is_normal b)).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (((mul_is_normal $ power_pos b (ordinal.pos_iff_ne_zero.2 a0)).trans
(power_is_normal a1)).limit_le l).symm }
end
theorem power_dvd_power (a) {b c : ordinal}
(h : b ≤ c) : a ^ b ∣ a ^ c :=
by { rw [← ordinal.add_sub_cancel_of_le h, power_add], apply dvd_mul_right }
theorem power_dvd_power_iff {a b c : ordinal}
(a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c :=
⟨λ h, le_of_not_lt $ λ hn,
not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $
le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h,
power_dvd_power _⟩
theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c :=
begin
by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]},
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]},
simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power] },
apply limit_rec_on c,
{ simp only [mul_zero, power_zero] },
{ intros c IH,
rw [mul_succ, power_add, IH, power_succ] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(mul_is_normal (ordinal.pos_iff_ne_zero.2 b0))).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (power_le_of_limit (power_ne_zero _ a0) l).symm }
end
/-! ### Ordinal logarithm -/
/-- The ordinal logarithm is the solution `u` to the equation
`x = b ^ u * v + w` where `v < b` and `w < b`. -/
def log (b : ordinal) (x : ordinal) : ordinal :=
if h : 1 < b then pred $
omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩
else 0
@[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 :=
by simp only [log, dif_neg b1]
theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x =
pred (omin {o | x < b^o} (log._proof_1 b x b1)) :=
by simp only [log, dif_pos b1]
@[simp] theorem log_zero (b : ordinal) : log b 0 = 0 :=
if b1 : 1 < b then
by rw [log_def b1, ← ordinal.le_zero, pred_le];
apply omin_le; change 0<b^succ 0;
rw [succ_zero, power_one];
exact lt_trans zero_lt_one b1
else by simp only [log_not_one_lt b1]
theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) =
omin {o | x < b^o} (log._proof_1 b x b1) :=
begin
let t := omin {o | x < b^o} (log._proof_1 b x b1),
have : x < b ^ t := omin_mem {o | x < b^o} _,
rcases zero_or_succ_or_limit t with h|h|h,
{ refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim,
simpa only [h, power_zero] },
{ rw [show log b x = pred t, from log_def b1 x,
succ_pred_iff_is_succ.2 h] },
{ rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩,
exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) }
end
theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) :
x < b ^ succ (log b x) :=
begin
cases lt_or_eq_of_le (ordinal.zero_le x) with x0 x0,
{ rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ },
{ subst x, apply power_pos _ (lt_trans zero_lt_one b1) }
end
theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) :
b ^ log b x ≤ x :=
begin
by_cases b0 : b = 0,
{ rw [b0, zero_power'],
refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _),
have := @omin_le {o | x < b^o} _ _ h,
rwa ← succ_log_def b1 x0 at this },
{ rw [← b1, one_power], exact one_le_iff_pos.2 x0 }
end
theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
c ≤ log b x ↔ b ^ c ≤ x :=
⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0),
λ h, le_of_not_lt $ λ hn,
not_le_of_lt (lt_power_succ_log b1 x) $
le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩
theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
log b x < c ↔ x < b ^ c :=
lt_iff_lt_of_le_iff_le (le_log b1 x0)
theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) :
log b x ≤ log b y :=
if x0 : x = 0 then by simp only [x0, log_zero, ordinal.zero_le] else
have x0 : 0 < x, from ordinal.pos_iff_ne_zero.2 x0,
if b1 : 1 < b then
(le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy
else by simp only [log_not_one_lt b1, ordinal.zero_le]
theorem log_le_self (b x : ordinal) : log b x ≤ x :=
if x0 : x = 0 then by simp only [x0, log_zero, ordinal.zero_le] else
if b1 : 1 < b then
le_trans (le_power_self _ b1) (power_log_le b (ordinal.pos_iff_ne_zero.2 x0))
else by simp only [log_not_one_lt b1, ordinal.zero_le]
/-! ### The Cantor normal form -/
theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
o % b ^ log b o < o :=
lt_of_lt_of_le
(mod_lt _ $ power_ne_zero _ b0)
(power_log_le _ $ ordinal.pos_iff_ne_zero.2 o0)
/-- Proving properties of ordinals by induction over their Cantor normal form. -/
@[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0)
{C : ordinal → Sort*}
(H0 : C 0)
(H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o)
: ∀ o, C o
| o :=
if o0 : o = 0 then by rw o0; exact H0 else
have _, from CNF_aux b0 o0,
H o o0 this (CNF_rec (o % b ^ log b o))
using_well_founded {dec_tac := `[assumption]}
@[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 :=
by rw [CNF_rec, dif_pos rfl]; refl
@[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) :
@CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) :=
by rw [CNF_rec, dif_neg o0]
/-- The Cantor normal form of an ordinal is the list of coefficients
in the base-`b` expansion of `o`.
CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/
noncomputable def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) :=
if b0 : b = 0 then [] else
CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o
@[simp] theorem zero_CNF (o) : CNF 0 o = [] :=
dif_pos rfl
@[simp] theorem CNF_zero (b) : CNF b 0 = [] :=
if b0 : b = 0 then dif_pos b0 else
(dif_neg b0).trans $ CNF_rec_zero _
theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) :=
by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0]
theorem one_CNF {o : ordinal} (o0 : o ≠ 0) :
CNF 1 o = [(0, o)] :=
by rw [CNF_ne_zero ordinal.one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one,
CNF_zero, div_one]
theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) :
(CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o :=
CNF_rec b0 (by rw CNF_zero; refl)
(λ o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o
theorem CNF_pairwise_aux (b := omega) (o) :
(∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧
(CNF b o).pairwise (λ p q, q.1 < p.1) :=
begin
by_cases b0 : b = 0,
{ simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact λ _, false.elim },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine CNF_rec b0 _ _ o,
{ simp only [CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
intros o o0 H IH, cases IH with IH₁ IH₂,
simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IH₂, and_true],
refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩,
{ exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) },
{ refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _),
{ rw ordinal.pos_iff_ne_zero, intro e,
rw e at m, simpa only [CNF_zero] using m },
{ exact mod_lt _ (power_ne_zero _ b0) } } },
{ by_cases o0 : o = 0,
{ simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
rw [← b1, one_CNF o0],
simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and,
list.pairwise_singleton] }
end
theorem CNF_pairwise (b := omega) (o) :
(CNF b o).pairwise (λ p q, prod.fst q < p.1) :=
(CNF_pairwise_aux _ _).2
theorem CNF_fst_le_log (b := omega) (o) :
∀ p ∈ CNF b o, prod.fst p ≤ log b o :=
(CNF_pairwise_aux _ _).1
theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o :=
le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _)
theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) :
∀ p ∈ CNF b o, prod.snd p < b :=
begin
have b0 := ne_of_gt (lt_trans zero_lt_one b1),
refine CNF_rec b0 (λ _, by rw [CNF_zero]; exact false.elim) _ o,
intros o o0 H IH,
simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, forall_eq_or_imp, iff_true_intro IH, and_true],
rw [div_lt (power_ne_zero _ b0), ← power_succ],
exact lt_power_succ_log b1 _,
end
theorem CNF_sorted (b := omega) (o) :
((CNF b o).map prod.fst).sorted (>) :=
by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o
/-! ### Casting naturals into ordinals, compatibility with operations -/
@[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n :=
by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero],
rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]]
@[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n :=
by induction n with n IH; [simp only [pow_zero, nat.cast_zero, power_zero, nat.cast_one],
rw [pow_succ', nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]]
@[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n :=
by rw [← cardinal.ord_nat, ← cardinal.ord_nat,
cardinal.ord_le_ord, cardinal.nat_cast_le]
@[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n :=
by simp only [lt_iff_le_not_le, nat_cast_le]
@[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n :=
by simp only [le_antisymm_iff, nat_cast_le]
@[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 :=
@nat_cast_inj n 0
theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 :=
not_congr nat_cast_eq_zero
@[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n :=
@nat_cast_lt 0 n
@[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n :=
(_root_.le_total m n).elim
(λ h, by rw [tsub_eq_zero_iff_le.2 h, ordinal.sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl)
(λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add,
add_tsub_cancel_of_le h, ordinal.add_sub_cancel_of_le (nat_cast_le.2 h)])
@[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n :=
if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else
have n0':_, from nat_cast_ne_zero.2 n0,
le_antisymm
(by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm];
apply nat.div_mul_le_self)
(by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul,
nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)];
apply nat.lt_succ_self)
@[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n :=
by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add,
nat.div_add_mod]
@[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o :=
⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h,
λ h, card_nat n ▸ card_le_card h⟩
@[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o :=
by rw [← succ_le, ← cardinal.succ_le, ← cardinal.nat_succ, nat_le_card]; refl
@[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n :=
lt_iff_lt_of_le_iff_le nat_le_card
@[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n :=
le_iff_le_iff_lt_iff_lt.2 nat_lt_card
@[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n :=
by simp only [le_antisymm_iff, card_le_nat, nat_le_card]
@[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n :=
by rw [← card_eq_nat, card_type, mk_fin]
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n with n ih; [simp only [nat.cast_zero, lift_zero],
simp only [nat.cast_succ, lift_add, ih, lift_one]]
theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n :=
by simp only [type_fin, lift_nat_cast]
theorem fintype_card (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α :=
by rw [← card_eq_nat, card_type, fintype_card]
end ordinal
/-! ### Properties of `omega` -/
namespace cardinal
open ordinal
@[simp] theorem ord_omega : ord.{u} omega = ordinal.omega :=
le_antisymm (ord_le.2 $ le_refl _) $
le_of_forall_lt $ λ o h, begin
rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩,
rw [lt_ord, ← lift_card, ← lift_omega.{0 u},
lift_lt, ← typein_enum (<) h'],
exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩
end
@[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c :=
by rw [add_comm, ← card_ord c, ← card_one,
← card_add, one_add_of_omega_le];
rwa [← ord_omega, ord_le_ord]
end cardinal
namespace ordinal
theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n :=
by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat]
theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega :=
lt_omega.2 ⟨_, rfl⟩
theorem omega_pos : 0 < omega := nat_lt_omega 0
theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos
theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1
theorem omega_is_limit : is_limit omega :=
⟨omega_ne_zero, λ o h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e]; exact nat_lt_omega (n+1)⟩
theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ H, le_of_forall_lt $ λ a h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e, ← succ_le]; exact H (n+1)⟩
theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := lt_of_le_of_ne (ordinal.zero_le o) h.1.symm
| (n+1) := h.2 _ (nat_lt_limit n)
theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o :=
omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n
theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega :=
begin
rcases lt_omega.1 h with ⟨n, rfl⟩,
clear h, induction n with n IH,
{ rw [nat.cast_zero, zero_add] },
{ rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] }
end
theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega
end
theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a :=
begin
refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩,
{ refine (limit_le l).2 (λ x hx, le_of_lt _),
rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero,
mul_succ, add_le_of_limit omega_is_limit],
intros b hb,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
exact le_trans (add_le_add_right (mul_div_le _ _) _)
(le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) },
{ rcases h with ⟨a0, b, rfl⟩,
refine mul_is_limit_left omega_is_limit
(ordinal.pos_iff_ne_zero.2 $ mt _ a0),
intro e, simp only [e, mul_zero] }
end
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega
end
theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b :=
begin
refine le_antisymm _ (le_add_left _ _),
revert h, apply limit_rec_on b,
{ intro h, rw [power_zero, ← succ_zero, lt_succ, ordinal.le_zero] at h,
rw [h, zero_add] },
{ intros b _ h, rw [power_succ] at h,
rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩,
refine le_trans (add_le_add_right (le_of_lt ax) _) _,
rw [power_succ, ← mul_add, add_omega xo] },
{ intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩,
refine (((add_is_normal a).trans (power_is_normal one_lt_omega))
.limit_le l).2 (λ y yb, _),
let z := max x y,
have := IH z (max_lt xb yb)
(lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)),
exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _)
(le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) }
end
theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) :
a + b < omega ^ c :=
by rwa [← add_omega_power h₁, add_lt_add_iff_left]
theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c :=
by rw [← ordinal.add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁]
theorem add_absorp_iff {o : ordinal} (o0 : 0 < o) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a :=
⟨λ H, ⟨log omega o, begin
refine ((lt_or_eq_of_le (power_log_le _ o0))
.resolve_left $ λ h, _).symm,
have := H _ h,
have := lt_power_succ_log one_lt_omega o,
rw [power_succ, lt_mul_of_limit omega_is_limit] at this,
rcases this with ⟨a, ao, h'⟩,
rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao,
revert h', apply not_lt_of_le,
suffices e : omega ^ log omega o * ↑n + o = o,
{ simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o },
induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]},
simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH]
end⟩,
λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩
theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a)
(l : is_limit c)
(IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) :
(a + b) * c = a * c :=
le_antisymm
((mul_le_of_limit l).2 $ λ c' h, begin
apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)),
rw IH _ h,
apply le_trans (add_le_add_left _ _),
{ rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) },
{ rw ← ba, exact le_add_right _ _ }
end)
(mul_le_mul_right _ (le_add_right _ _))
theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) :
(a + b) * succ c = a * succ c + b :=
begin
apply limit_rec_on c,
{ simp only [succ_zero, mul_one] },
{ intros c IH,
rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] },
{ intros c l IH,
have := add_mul_limit_aux ba l IH,
rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] }
end
theorem add_mul_limit {a b c : ordinal} (ba : b + a = a)
(l : is_limit c) : (a + b) * c = a * c :=
add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba)
theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega :=
le_antisymm
((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb))
(by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0))
theorem mul_lt_omega_power {a b c : ordinal}
(c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c :=
if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin
rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l,
{ exact (lt_irrefl _).elim c0 },
{ rw power_succ at ha,
rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt
omega_is_limit).1 ha with ⟨n, hn, an⟩,
refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _,
rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)],
exact mul_lt_omega hn hb },
{ rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩,
refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _,
rw [← power_succ, power_lt_power_iff_right one_lt_omega],
exact l.2 _ hx }
end
theorem mul_omega_dvd {a : ordinal}
(a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b
| _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha]
theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) :
a * omega ^ omega ^ b = omega ^ omega ^ b :=
begin
by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊢, exact mul_omega a0 h},
refine le_antisymm _
(by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)),
rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h
with ⟨x, xb, ax⟩,
refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _,
rw [← power_add, add_omega_power xb]
end
theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega :=
le_antisymm
((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2
(λ b hb, le_of_lt (power_lt_omega h hb)))
(le_power_self _ a1)
/-! ### Fixed points of normal functions -/
/-- The next fixed point function, the least fixed point of the
normal function `f` above `a`. -/
def nfp (f : ordinal → ordinal) (a : ordinal) :=
sup (λ n : ℕ, f^[n] a)
theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a :=
le_sup _ n
theorem le_nfp_self (f a) : a ≤ nfp f a :=
iterate_le_nfp f a 0
theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} :
f b < nfp f a ↔ b < nfp f a :=
lt_sup.trans $ iff.trans
(by exact
⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩,
λ ⟨n, h⟩, ⟨n+1, by rw iterate_succ'; exact H.lt_iff.2 h⟩⟩)
lt_sup.symm
theorem is_normal.nfp_le {f} (H : is_normal f) {a b} :
nfp f a ≤ f b ↔ nfp f a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_nfp
theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b}
(ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b :=
sup_le.2 $ λ i, begin
induction i with i IH generalizing a, {exact ab},
exact IH (le_trans (H.le_iff.2 ab) h),
end
theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a :=
begin
refine le_antisymm _ (H.le_self _),
cases le_or_lt (f a) a with aa aa,
{ rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) },
rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l,
{ refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1),
simp only [e, ordinal.zero_le] },
{ have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]),
rw [e, lt_succ] at this,
have ab : a ≤ b,
{ rw [← lt_succ, ← e],
exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) },
refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this))
(le_trans this (le_of_lt _)),
simp only [e, lt_succ_self] },
{ exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) }
end
theorem is_normal.le_nfp {f} (H : is_normal f) {a b} :
f b ≤ nfp f a ↔ b ≤ nfp f a :=
⟨le_trans (H.le_self _), λ h,
by simpa only [H.nfp_fp] using H.le_iff.2 h⟩
theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a :=
le_antisymm (sup_le.mpr $ λ i, by rw [iterate_fixed h]) (le_nfp_self f a)
/-- The derivative of a normal function `f` is
the sequence of fixed points of `f`. -/
def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal :=
limit_rec_on o (nfp f 0)
(λ a IH, nfp f (succ IH))
(λ a l, bsup.{u u} a)
@[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _
@[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) :=
limit_rec_on_succ _ _ _ _
theorem deriv_limit (f) {o} : is_limit o →
deriv f o = bsup.{u u} o (λ a _, deriv f a) :=
limit_rec_on_limit _ _ _ _
theorem deriv_is_normal (f) : is_normal (deriv f) :=
⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self,
λ o l a, by rw [deriv_limit _ l, bsup_le]⟩
theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o :=
begin
apply limit_rec_on o,
{ rw [deriv_zero, H.nfp_fp] },
{ intros o ih, rw [deriv_succ, H.nfp_fp] },
intros o l IH,
rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1],
refine eq_of_forall_ge_iff (λ c, _),
simp only [bsup_le, IH] {contextual:=tt}
end
theorem is_normal.fp_iff_deriv {f} (H : is_normal f)
{a} : f a ≤ a ↔ ∃ o, a = deriv f o :=
⟨λ ha, begin
suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o,
from this a ((deriv_is_normal _).le_self _),
intro o, apply limit_rec_on o,
{ intros h₁,
refine ⟨0, le_antisymm h₁ _⟩,
rw deriv_zero,
exact H.nfp_le_fp (ordinal.zero_le _) ha },
{ intros o IH h₁,
cases le_or_lt a (deriv f o), {exact IH h},
refine ⟨succ o, le_antisymm h₁ _⟩,
rw deriv_succ,
exact H.nfp_le_fp (succ_le.2 h) ha },
{ intros o l IH h₁,
cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩},
rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h,
exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) }
end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩
end ordinal
|
8a86e9d97d38967c73bbd30d5b2357e07d95a537 | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/myrat/le.lean | d8723cea82ed11a21870577d4ffd3cc062ec44e6 | [] | no_license | Sterrs/leaning | 8fd80d1f0a6117a220bb2e57ece639b9a63deadc | 3901cc953694b33adda86cb88ca30ba99594db31 | refs/heads/master | 1,627,023,822,744 | 1,616,515,221,000 | 1,616,515,221,000 | 245,512,190 | 2 | 0 | null | 1,616,429,050,000 | 1,583,527,118,000 | Lean | UTF-8 | Lean | false | false | 5,680 | lean | import .basic
import ..myint.basic
import ..myfield.order
namespace hidden
open myring
open ordered_myring
open ordered_integral_domain
namespace frac
def le (x y : frac): Prop :=
x.num * y.denom ≤ y.num * x.denom
instance: has_le frac := ⟨le⟩
theorem le_def (x y: frac):
x ≤ y ↔ x.num * y.denom ≤ y.num * x.denom := iff.rfl
private theorem le_right {a x b y : frac} :
a ≈ b → x ≈ y → (a ≤ x) → (b ≤ y) :=
begin
assume hab hxy halx,
rw setoid_equiv at hab,
rw setoid_equiv at hxy,
rw le_def,
rw le_def at halx,
have : 0 < x.denom * a.denom, {
from zero_lt_mul x.denom_pos a.denom_pos,
},
rw ←le_mul_cancel_pos_right _ _ (x.denom * a.denom) this,
conv {
congr,
rw mul_assoc,
rw mul_comm,
rw mul_assoc,
rw mul_assoc,
congr, skip, congr, skip,
rw mul_comm,
rw ←hab,
skip,
rw mul_comm x.denom,
rw mul_assoc,
rw mul_comm,
rw mul_assoc,
rw mul_assoc,
congr, skip, congr, skip,
rw mul_comm,
rw ←hxy,
},
have hrw: y.denom * (x.denom * (a.num * b.denom)) = y.denom * b.denom * (a.num * x.denom), {
ac_refl,
},
have hrw2: b.denom * (a.denom * (x.num * y.denom)) = y.denom * b.denom * (x.num * a.denom), {
ac_refl,
},
rw hrw,
rw hrw2,
apply le_mul_nonneg_left, {
apply zero_le_mul; apply lt_impl_le, {
from y.denom_pos,
}, {
from b.denom_pos,
},
}, {
assumption,
},
end
theorem le_well_defined (a x b y : frac) :
a ≈ b → x ≈ y → (a ≤ x) = (b ≤ y) :=
begin
assume hab hxy,
apply propext,
from
iff.intro
(le_right hab hxy)
(le_right (setoid.symm hab) (setoid.symm hxy)),
end
instance decidable_le: ∀ x y: frac, decidable (x ≤ y) :=
λ x y, myint.decidable_le _ _
end frac
namespace myrat
def le := quotient.lift₂ frac.le frac.le_well_defined
instance: has_le myrat := ⟨le⟩
instance has_le2: has_le (quotient frac.frac.setoid) := ⟨le⟩
instance decidable_le: ∀ x y: myrat, decidable (x ≤ y) :=
myint.quotient_decidable_rel frac.le frac.le_well_defined
private theorem le_frac_cls {x y : myrat} {a b : frac} :
(⟦a⟧ ≤ ⟦b⟧ ↔ a ≤ b) := iff.rfl
private theorem le_cls {a b : frac} :
(⟦a⟧ ≤ ⟦b⟧ ↔ a.num * b.denom ≤ b.num * a.denom) :=
iff.rfl
private theorem add_eq_cls {x y: frac}:
⟦x⟧ + ⟦y⟧ = ⟦x + y⟧ := rfl
private theorem mul_eq_cls {x y : frac}:
⟦x⟧ * ⟦y⟧ = ⟦x * y⟧ := rfl
variables x y z : myrat
instance: ordered_myfield myrat := ⟨
by apply_instance,
λ x y z: myrat,
begin
-- turn into z + x ≤ z + y ↔ x ≤ y for copy/paste purposes
repeat {rw add_comm _ z},
cases quotient.exists_rep x with a ha, subst ha,
cases quotient.exists_rep y with b hb, subst hb,
cases quotient.exists_rep z with c hc, subst hc,
repeat { rw [add_eq_cls, le_cls] },
repeat { rw frac.add_num <|> rw frac.add_denom, },
rw [add_mul, add_mul],
have : c.num * a.denom * (c.denom * b.denom) = c.num * b.denom * (c.denom * a.denom),
ac_refl,
rw this, clear this,
rw ←le_add_cancel_left,
have : a.num * c.denom * (c.denom * b.denom) = a.num * b.denom * c.denom * c.denom,
ac_refl,
rw this, clear this,
have : b.num * c.denom * (c.denom * a.denom) = b.num * a.denom * c.denom * c.denom,
ac_refl,
rw this, clear this,
rw le_mul_cancel_pos_right _ _ c.denom c.denom_pos,
rw le_mul_cancel_pos_right _ _ c.denom c.denom_pos,
from iff.rfl.mp,
all_goals {apply myint.decidable_eq},
end,
λ x y: myrat,
begin
cases quotient.exists_rep x with a ha, subst ha,
cases quotient.exists_rep y with b hb, subst hb,
rw mul_eq_cls,
rw rat_zero,
repeat {rw le_cls},
dsimp only [],
repeat {rw zero_mul <|> rw mul_one},
from zero_le_mul,
end,
λ x y z: myrat,
begin
assume hxy hyz,
cases quotient.exists_rep x with a ha, subst ha,
cases quotient.exists_rep y with b hb, subst hb,
cases quotient.exists_rep z with c hc, subst hc,
have hxy₁ := le_mul_nonneg_left _ _ _ (lt_impl_le c.denom_pos) hxy,
have hyz₁ := le_mul_nonneg_left _ _ _ (lt_impl_le a.denom_pos) hyz,
have : c.denom * (b.num * a.denom) = a.denom * (b.num * c.denom), ac_refl,
rw this at hxy₁,
have h : c.denom * (a.num * b.denom) ≤ a.denom * (c.num * b.denom),
transitivity a.denom * (b.num * c.denom); assumption,
clear hyz hxy hxy₁ hyz₁ this,
have : c.denom * (a.num * b.denom) = b.denom * (a.num * c.denom), ac_refl,
rw this at h, clear this,
have : a.denom * (c.num * b.denom) = b.denom * (c.num * a.denom), ac_refl,
rw this at h, clear this,
rwa le_mul_cancel_pos_left _ _ b.denom b.denom_pos at h,
end,
λ x y: myrat,
begin
cases quotient.exists_rep x with a ha, subst ha,
cases quotient.exists_rep y with b hb, subst hb,
apply le_total_order,
end,
λ x y: myrat,
begin
assume hxy hyx,
cases quotient.exists_rep x with a ha, subst ha,
cases quotient.exists_rep y with b hb, subst hb,
rw le_cls at hxy hyx,
apply quotient.sound,
rw frac.setoid_equiv,
from le_antisymm hxy hyx,
end⟩
theorem archimedes (x: myrat): ∃ n: myint, x ≤ ↑n :=
begin
cases quotient.exists_rep x with a ha, subst ha,
existsi abs a.num,
rw coe_int,
rw le_cls,
simp,
apply le_trans _ (self_le_abs _),
conv {
congr,
rw mul_one,
rw ←one_mul (abs a.num),
rw mul_comm,
},
apply le_mul_comb_nonneg,
from abs_nonneg _,
from myint.le_add_rhs_coe 1 (le_refl _),
from le_refl _,
have := a.denom_pos,
rw myint.lt_iff_succ_le at this,
from this,
end
end myrat
end hidden
|
40d5a707cd4b97bfcc05ae90d1053ff3112830ef | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/data/complex/exponential.lean | bb3db3e1f1bdf9b004111a732dfec6b23bff0259 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 61,646 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir
-/
import algebra.geom_sum
import data.nat.choose.sum
import data.complex.basic
/-!
# Exponential, trigonometric and hyperbolic trigonometric functions
This file contains the definitions of the real and complex exponential, sine, cosine, tangent,
hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions.
-/
local notation `abs'` := _root_.abs
open is_absolute_value
open_locale classical big_operators nat
section
open real is_absolute_value finset
lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ}
(h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k :=
begin
assume l k hkm hkl,
generalize hp : l - k = p,
have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp,
subst this,
clear hkl hp,
induction p with p ih,
{ simp },
{ exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih }
end
section
variables {α : Type*} {β : Type*} [ring β]
[linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv]
lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a)
(hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f :=
λ ε ε0,
let ⟨k, hk⟩ := archimedean.arch a ε0 in
have h : ∃ l, ∀ n ≥ m, a - l • ε < f n :=
⟨k + k + 1, λ n hnm, lt_of_lt_of_le
(show a - (k + (k + 1)) • ε < -abs (f n),
from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin
rw [neg_sub, lt_sub_iff_add_lt, add_nsmul, add_nsmul, one_nsmul],
exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk
(lt_add_of_pos_right _ ε0)),
end))
(neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩,
let l := nat.find h in
have hl : ∀ (n : ℕ), n ≥ m → f n > a - l • ε := nat.find_spec h,
have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _))
(lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))),
begin
cases not_forall.1
(nat.find_min h (nat.pred_lt hl0)) with i hi,
rw [not_imp, not_lt] at hi,
existsi i,
assume j hj,
have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj,
rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'],
exact calc f i ≤ a - (nat.pred l) • ε : hi.2
... = a - l • ε + ε :
by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul',
sub_add, add_sub_cancel] }
... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _
end
lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a)
(hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f :=
begin
refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _
(-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ :
cau_seq α abs).2,
ext,
exact neg_neg _
end
end
section no_archimedean
variables {α : Type*} {β : Type*} [ring β]
[linear_ordered_field α] {abv : β → α} [is_absolute_value abv]
lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) :
(∀ m, n ≤ m → abv (f m) ≤ g m) →
is_cau_seq abs (λ n, ∑ i in range n, g i) →
is_cau_seq abv (λ n, ∑ i in range n, f i) :=
begin
assume hm hg ε ε0,
cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi,
existsi max n i,
assume j ji,
have hi₁ := hi j (le_trans (le_max_right n i) ji),
have hi₂ := hi (max n i) (le_max_right n i),
have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k)
(∑ k in range (max n i), g k),
have := add_lt_add hi₁ hi₂,
rw [abs_sub (∑ k in range (max n i), g k), add_halves ε] at this,
refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this,
generalize hk : j - max n i = k,
clear this hi₂ hi₁ hi ε0 ε hg sub_le,
rw nat.sub_eq_iff_eq_add ji at hk,
rw hk,
clear hk ji j,
induction k with k' hi,
{ simp [abv_zero abv] },
{ simp only [nat.succ_add, sum_range_succ_comm, sub_eq_add_neg, add_assoc],
refine le_trans (abv_add _ _ _) _,
simp only [sub_eq_add_neg] at hi,
exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi },
end
lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) →
is_cau_seq abv (λ m, ∑ n in range m, f n) :=
is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _)
end no_archimedean
section
variables {α : Type*} {β : Type*} [ring β]
[linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv]
lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
(x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) :=
have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1,
is_cau_series_of_abv_cau
begin
simp only [abv_pow abv] {eta := ff},
have : (λ (m : ℕ), ∑ n in range m, (abv x) ^ n) =
λ m, geom_sum (abv x) m := rfl,
simp only [this, geom_sum_eq hx1'] {eta := ff},
conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] },
refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _,
{ assume n hn,
rw abs_of_nonneg,
refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1)
(sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)),
refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1),
clear hn,
induction n with n ih,
{ simp },
{ rw [pow_succ, ← one_mul (1 : α)],
refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } },
{ assume n hn,
refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _),
rw [← one_mul (_ ^ n), pow_succ],
exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) }
end
lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) :
is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) :=
have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) :=
(cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2,
by simpa only [mul_sum]
lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α)
(hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) :
is_cau_seq abv (λ m, ∑ n in range m, f n) :=
have har1 : abs r < 1, by rwa abs_of_nonneg hr0,
begin
refine is_cau_series_of_abv_le_cau n.succ _
(is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1),
assume m hmn,
cases classical.em (r = 0) with r_zero r_ne_zero,
{ have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn,
have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])),
simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] },
generalize hk : m - n.succ = k,
have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero),
replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk,
induction k with k ih generalizing m n,
{ rw [hk, zero_add, mul_right_comm, inv_pow' _ _, ← div_eq_mul_inv, mul_div_cancel],
exact (ne_of_lt (pow_pos r_pos _)).symm },
{ have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp),
rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc],
exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn))
(mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) }
end
lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) :
∑ m in range n, ∑ k in range (m + 1), f k (m - k) =
∑ m in range n, ∑ k in range (n - m), f m k :=
by rw [sum_sigma', sum_sigma']; exact sum_bij
(λ a _, ⟨a.2, a.1 - a.2⟩)
(λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1,
have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2,
mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁),
mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩)
(λ _ _, rfl)
(λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h,
have ha : a₁ < n ∧ a₂ ≤ a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩,
have hb : b₁ < n ∧ b₂ ≤ b₁ :=
⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩,
have h : a₂ = b₂ ∧ _ := sigma.mk.inj h,
have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2),
sigma.mk.inj_iff.2
⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl,
(heq_of_eq h.1)⟩)
(λ ⟨a₁, a₂⟩ ha,
have ha : a₁ < n ∧ a₂ < n - a₁ :=
⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩,
⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2),
mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩,
sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩)
lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α}
{n m : ℕ} (hnm : n ≤ m) : ∑ k in range m, f k - ∑ k in range n, f k =
∑ k in (range m).filter (λ k, n ≤ k), f k :=
begin
rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)),
sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'],
refine finset.sum_congr
(finset.ext $ λ a, ⟨λ h, by simp at *; finish,
λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm,
by simp * at *⟩)
(λ _ _, rfl),
end
end
section no_archimedean
variables {α : Type*} {β : Type*} [ring β]
[linear_ordered_field α] {abv : β → α} [is_absolute_value abv]
lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) :
abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s (by simp [abv_zero abv])
(λ a s has ih, by rw [sum_insert has, sum_insert has];
exact le_trans (abv_add abv _ _) (add_le_add_left ih _))
lemma cauchy_product {a b : ℕ → β}
(ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n)))
(hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) :
∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) -
∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε :=
let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in
let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in
have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0),
have hPε0 : 0 < ε / (2 * P),
from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0),
let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in
have hQε0 : 0 < ε / (4 * Q),
from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num)
(lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))),
let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in
⟨2 * (max N M + 1), λ K hK,
have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) =
∑ m in range K, ∑ n in range (K - m), a m * b n,
by simpa using sum_range_diag_flip K (λ m n, a m * b n),
have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k),
by simp [finset.mul_sum],
have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k =
∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k)
+ ∑ i in range K, a i * ∑ k in range K, b k,
by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm],
have two_mul_two : (4 : α) = 2 * 2, by norm_num,
have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0,
have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0,
have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε,
by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)),
two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves],
have hNMK : max N M + 1 < K,
from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK,
have hKN : N < K,
from calc N ≤ max N M : le_max_left _ _
... < max N M + 1 : nat.lt_succ_self _
... < K : hNMK,
have hsumlesum : ∑ i in range (max N M + 1), abv (a i) *
abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤
∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)),
from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left
(le_of_lt (hN (K - m) K
(nat.le_sub_left_of_add_le (le_trans
(by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ))
(le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK))
(le_of_lt hKN))) (abv_nonneg abv _)),
have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P :=
calc ∑ n in range (max N M + 1), abv (a n)
= abs (∑ n in range (max N M + 1), abv (a n)) :
eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x))))
... < P : hP (max N M + 1),
begin
rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv],
refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _,
suffices : ∑ i in range (max N M + 1),
abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) +
(∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) -
∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) <
ε / (2 * P) * P + ε / (4 * Q) * (2 * Q),
{ rw hε at this, simpa [abv_mul abv] },
refine add_lt_add (lt_of_le_of_lt hsumlesum
(by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _,
rw sum_range_sub_sum_range (le_of_lt hNMK),
exact calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k),
abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)
≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) :
sum_le_sum (λ n hn, begin
refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _),
rw sub_eq_add_neg,
refine le_trans (abv_add _ _ _) _,
rw [two_mul, abv_neg abv],
exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)),
end)
... < ε / (4 * Q) * (2 * Q) :
by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)];
refine (mul_lt_mul_right $ by rw two_mul;
exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))
(lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2
(lt_of_le_of_lt (le_abs_self _)
(hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK))
(nat.le_succ_of_le (le_max_right _ _))))
end⟩
end no_archimedean
end
open finset
open cau_seq
namespace complex
lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs
(λ n, ∑ m in range n, abs (z ^ m / m!)) :=
let ⟨n, hn⟩ := exists_nat_gt (abs z) in
have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn,
series_ratio_test n (complex.abs z / n) (div_nonneg (complex.abs_nonneg _) (le_of_lt hn0))
(by rwa [div_lt_iff hn0, one_mul])
(λ m hm,
by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ,
mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc,
mul_div_right_comm, abs_mul, abs_div, abs_cast_nat];
exact mul_le_mul_of_nonneg_right
(div_le_div_of_le_left (abs_nonneg _) hn0
(nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _))
noncomputable theory
lemma is_cau_exp (z : ℂ) :
is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) :=
is_cau_series_of_abv_cau (is_cau_abs_exp z)
/-- The Cauchy sequence consisting of partial sums of the Taylor series of
the complex exponential function -/
@[pp_nodot] def exp' (z : ℂ) :
cau_seq ℂ complex.abs :=
⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩
/-- The complex exponential function, defined via its Taylor series -/
@[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z)
/-- The complex sine function, defined via `exp` -/
@[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2
/-- The complex cosine function, defined via `exp` -/
@[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2
/-- The complex tangent function, defined as `sin z / cos z` -/
@[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z
/-- The complex hyperbolic sine function, defined via `exp` -/
@[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2
/-- The complex hyperbolic cosine function, defined via `exp` -/
@[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2
/-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/
@[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z
end complex
namespace real
open complex
/-- The real exponential function, defined as the real part of the complex exponential -/
@[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re
/-- The real sine function, defined as the real part of the complex sine -/
@[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re
/-- The real cosine function, defined as the real part of the complex cosine -/
@[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re
/-- The real tangent function, defined as the real part of the complex tangent -/
@[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re
/-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/
@[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re
/-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/
@[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re
/-- The real hypebolic tangent function, defined as the real part of
the complex hyperbolic tangent -/
@[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re
end real
namespace complex
variables (x y : ℂ)
@[simp] lemma exp_zero : exp 0 = 1 :=
lim_eq_of_equiv_const $
λ ε ε0, ⟨1, λ j hj, begin
convert ε0,
cases j,
{ exact absurd hj (not_le_of_gt zero_lt_one) },
{ dsimp [exp'],
induction j with j ih,
{ dsimp [exp']; simp },
{ rw ← ih dec_trivial,
simp only [sum_range_succ, pow_succ],
simp } }
end⟩
lemma exp_add : exp (x + y) = exp x * exp y :=
show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) =
lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩)
* lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩),
from
have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! =
∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!),
from assume j,
finset.sum_congr rfl (λ m hm, begin
rw [add_pow, div_eq_mul_inv, sum_mul],
refine finset.sum_congr rfl (λ i hi, _),
have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2
(pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))),
have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi),
rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'],
simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹,
mul_comm (m.choose i : ℂ)],
rw inv_mul_cancel h₁,
simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm]
end),
by rw lim_mul_lim;
exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj];
exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y)))
attribute [irreducible] complex.exp
lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod :=
@monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l
lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod :=
@monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s
lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) :=
@monoid_hom.map_prod α (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s
lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n
| 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero]
| (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul]
lemma exp_ne_zero : exp x ≠ 0 :=
λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp
lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add];
simp [mul_inv_cancel (exp_ne_zero x)]
lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv]
@[simp] lemma exp_conj : exp (conj x) = conj (exp x) :=
begin
dsimp [exp],
rw [← lim_conj],
refine congr_arg lim (cau_seq.ext (λ _, _)),
dsimp [exp', function.comp, cau_seq_conj],
rw conj.map_sum,
refine sum_congr rfl (λ n hn, _),
rw [conj.map_div, conj.map_pow, ← of_real_nat_cast, conj_of_real]
end
@[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x :=
eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x :=
of_real_exp_of_real_re _
@[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 :=
by rw [← of_real_exp_of_real_re, of_real_im]
lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl
lemma two_sinh : 2 * sinh x = exp x - exp (-x) :=
mul_div_cancel' _ two_ne_zero'
lemma two_cosh : 2 * cosh x = exp x + exp (-x) :=
mul_div_cancel' _ two_ne_zero'
@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]
@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]
private lemma sinh_add_aux {a b c d : ℂ} :
(a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring
lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
begin
rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh,
exp_add, neg_add, exp_add, eq_comm,
mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh,
← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
mul_left_comm, two_cosh, ← mul_assoc, two_cosh],
exact sinh_add_aux
end
@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]
@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [add_comm, cosh, exp_neg]
private lemma cosh_add_aux {a b c d : ℂ} :
(a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring
lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
begin
rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh,
exp_add, neg_add, exp_add, eq_comm,
mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh,
← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
mul_left_comm, two_cosh, mul_left_comm, two_sinh],
exact cosh_add_aux
end
lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg]
lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg]
lemma sinh_conj : sinh (conj x) = conj (sinh x) :=
by rw [sinh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_sub, sinh, conj.map_div, conj_bit0,
conj.map_one]
@[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x :=
eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x :=
of_real_sinh_of_real_re _
@[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 :=
by rw [← of_real_sinh_of_real_re, of_real_im]
lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl
lemma cosh_conj : cosh (conj x) = conj (cosh x) :=
begin
rw [cosh, ← conj.map_neg, exp_conj, exp_conj, ← conj.map_add, cosh, conj.map_div,
conj_bit0, conj.map_one]
end
@[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x :=
eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x :=
of_real_cosh_of_real_re _
@[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 :=
by rw [← of_real_cosh_of_real_re, of_real_im]
lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl
lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl
@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]
@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]
lemma tanh_conj : tanh (conj x) = conj (tanh x) :=
by rw [tanh, sinh_conj, cosh_conj, ← conj.map_div, tanh]
@[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x :=
eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x :=
of_real_tanh_of_real_re _
@[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 :=
by rw [← of_real_tanh_of_real_re, of_real_im]
lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl
lemma cosh_add_sinh : cosh x + sinh x = exp x :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_add,
two_cosh, two_sinh, add_add_sub_cancel, two_mul]
lemma sinh_add_cosh : sinh x + cosh x = exp x :=
by rw [add_comm, cosh_add_sinh]
lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), mul_sub,
two_cosh, two_sinh, add_sub_sub_cancel, two_mul]
lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 :=
by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero]
lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 :=
begin
rw ← cosh_sq_sub_sinh_sq x,
ring
end
lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 :=
begin
rw ← cosh_sq_sub_sinh_sq x,
ring
end
lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 :=
by rw [two_mul, cosh_add, sq, sq]
lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x :=
begin
rw [two_mul, sinh_add],
ring
end
lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x :=
begin
have h1 : x + 2 * x = 3 * x, by ring,
rw [← h1, cosh_add x (2 * x)],
simp only [cosh_two_mul, sinh_two_mul],
have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring,
rw [h2, sinh_sq],
ring
end
lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x :=
begin
have h1 : x + 2 * x = 3 * x, by ring,
rw [← h1, sinh_add x (2 * x)],
simp only [cosh_two_mul, sinh_two_mul],
have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring,
rw [h2, cosh_sq],
ring,
end
@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]
@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul]
lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I :=
mul_div_cancel' _ two_ne_zero'
lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) :=
mul_div_cancel' _ two_ne_zero'
lemma sinh_mul_I : sinh (x * I) = sin x * I :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_sinh,
← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one,
neg_sub, neg_mul_eq_neg_mul]
lemma cosh_mul_I : cosh (x * I) = cos x :=
by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _ _), two_cosh,
two_cos, neg_mul_eq_neg_mul]
lemma tanh_mul_I : tanh (x * I) = tan x * I :=
by rw [tanh_eq_sinh_div_cosh, cosh_mul_I, sinh_mul_I, mul_div_right_comm, tan]
lemma cos_mul_I : cos (x * I) = cosh x :=
by rw ← cosh_mul_I; ring_nf; simp
lemma sin_mul_I : sin (x * I) = sinh x * I :=
have h : I * sin (x * I) = -sinh x := by { rw [mul_comm, ← sinh_mul_I], ring_nf, simp },
by simpa only [neg_mul_eq_neg_mul_symm, div_I, neg_neg]
using cancel_factors.cancel_factors_eq_div h I_ne_zero
lemma tan_mul_I : tan (x * I) = tanh x * I :=
by rw [tan, sin_mul_I, cos_mul_I, mul_div_right_comm, tanh_eq_sinh_div_cosh]
lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I,
add_mul, add_mul, mul_right_comm, ← sinh_mul_I,
mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add]
@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]
@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, sub_eq_add_neg, exp_neg, add_comm]
private lemma cos_add_aux {a b c d : ℂ} :
(a + b) * (c + d) - (b - a) * (d - c) * (-1) =
2 * (a * c + b * d) := by ring
lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I,
sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I,
mul_neg_one, sub_eq_add_neg]
lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg]
lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg]
lemma sin_add_mul_I (x y : ℂ) : sin (x + y*I) = sin x * cosh y + cos x * sinh y * I :=
by rw [sin_add, cos_mul_I, sin_mul_I, mul_assoc]
lemma sin_eq (z : ℂ) : sin z = sin z.re * cosh z.im + cos z.re * sinh z.im * I :=
by convert sin_add_mul_I z.re z.im; exact (re_add_im z).symm
lemma cos_add_mul_I (x y : ℂ) : cos (x + y*I) = cos x * cosh y - sin x * sinh y * I :=
by rw [cos_add, cos_mul_I, sin_mul_I, mul_assoc]
lemma cos_eq (z : ℂ) : cos z = cos z.re * cosh z.im - sin z.re * sinh z.im * I :=
by convert cos_add_mul_I z.re z.im; exact (re_add_im z).symm
theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) :=
begin
have s1 := sin_add ((x + y) / 2) ((x - y) / 2),
have s2 := sin_sub ((x + y) / 2) ((x - y) / 2),
rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1,
rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2,
rw [s1, s2],
ring
end
theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) :=
begin
have s1 := cos_add ((x + y) / 2) ((x - y) / 2),
have s2 := cos_sub ((x + y) / 2) ((x - y) / 2),
rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1,
rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2,
rw [s1, s2],
ring,
end
lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) :=
begin
have h2 : (2:ℂ) ≠ 0 := by norm_num,
calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _
... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2))
+ (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _
... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _,
{ congr; field_simp [h2]; ring },
{ rw [cos_add, cos_sub] },
ring,
end
lemma sin_conj : sin (conj x) = conj (sin x) :=
by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I,
← conj_neg_I, ← conj.map_mul, ← conj.map_mul, sinh_conj,
mul_neg_eq_neg_mul_symm, sinh_neg, sinh_mul_I, mul_neg_eq_neg_mul_symm]
@[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x :=
eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x :=
of_real_sin_of_real_re _
@[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 :=
by rw [← of_real_sin_of_real_re, of_real_im]
lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl
lemma cos_conj : cos (conj x) = conj (cos x) :=
by rw [← cosh_mul_I, ← conj_neg_I, ← conj.map_mul, ← cosh_mul_I,
cosh_conj, mul_neg_eq_neg_mul_symm, cosh_neg]
@[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x :=
eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x :=
of_real_cos_of_real_re _
@[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 :=
by rw [← of_real_cos_of_real_re, of_real_im]
lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl
@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]
lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl
lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x :=
by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx]
@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]
lemma tan_conj : tan (conj x) = conj (tan x) :=
by rw [tan, sin_conj, cos_conj, ← conj.map_div, tan]
@[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x :=
eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real]
@[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x :=
of_real_tan_of_real_re _
@[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 :=
by rw [← of_real_tan_of_real_re, of_real_im]
lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl
lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) :=
by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I]
lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) :=
by rw [← neg_mul_eq_neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I]
@[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 :=
eq.trans
(by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm])
(cosh_sq_sub_sinh_sq (x * I))
@[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 :=
by rw [add_comm, sin_sq_add_cos_sq]
lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 :=
by rw [two_mul, cos_add, ← sq, ← sq]
lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x),
← sub_add, sub_add_eq_add_sub, two_mul]
lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw [two_mul, sin_add, two_mul, add_mul, mul_comm]
lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 :=
by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div]
lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel']
lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel]
lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 :=
have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx,
by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] }
lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) :
tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 :=
by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul]
lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x :=
begin
have h1 : x + 2 * x = 3 * x, by ring,
rw [← h1, cos_add x (2 * x)],
simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, sq],
have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring,
rw [h2, cos_sq'],
ring
end
lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 :=
begin
have h1 : x + 2 * x = 3 * x, by ring,
rw [← h1, sin_add x (2 * x)],
simp only [cos_two_mul, sin_two_mul, cos_sq'],
have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring,
rw [h2, cos_sq'],
ring
end
lemma exp_mul_I : exp (x * I) = cos x + sin x * I :=
(cos_add_sin_I _).symm
lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) :=
by rw [exp_add, exp_mul_I]
lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) :=
by rw [← exp_add_mul_I, re_add_im]
lemma exp_re : (exp x).re = real.exp x.re * real.cos x.im :=
by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, cos_of_real_re] }
lemma exp_im : (exp x).im = real.exp x.re * real.sin x.im :=
by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, sin_of_real_re] }
/-- De Moivre's formula -/
theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) :
(cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I :=
begin
rw [← exp_mul_I, ← exp_mul_I],
induction n with n ih,
{ rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] },
{ rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] }
end
end complex
namespace real
open complex
variables (x y : ℝ)
@[simp] lemma exp_zero : exp 0 = 1 :=
by simp [real.exp]
lemma exp_add : exp (x + y) = exp x * exp y :=
by simp [exp_add, exp]
lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod :=
@monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l
lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod :=
@monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s
lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) :=
@monoid_hom.map_prod α (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s
lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n
| 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero]
| (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul]
lemma exp_ne_zero : exp x ≠ 0 :=
λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at *
lemma exp_neg : exp (-x) = (exp x)⁻¹ :=
by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg,
of_real_inv, of_real_exp]
lemma exp_sub : exp (x - y) = exp x / exp y :=
by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv]
@[simp] lemma sin_zero : sin 0 = 0 := by simp [sin]
@[simp] lemma sin_neg : sin (-x) = -sin x :=
by simp [sin, exp_neg, (neg_div _ _).symm, add_mul]
lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y :=
by rw [← of_real_inj]; simp [sin, sin_add]
@[simp] lemma cos_zero : cos 0 = 1 := by simp [cos]
@[simp] lemma cos_neg : cos (-x) = cos x :=
by simp [cos, exp_neg]
lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y :=
by rw ← of_real_inj; simp [cos, cos_add]
lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y :=
by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg]
lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y :=
by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg]
lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) :=
begin
rw ← of_real_inj,
simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul,
of_real_one, of_real_bit0],
convert sin_sub_sin _ _;
norm_cast
end
theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) :=
begin
rw ← of_real_inj,
simp only [cos, neg_mul_eq_neg_mul_symm, of_real_sin, of_real_sub, of_real_add,
of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0],
convert cos_sub_cos _ _,
ring,
end
lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) :=
begin
rw ← of_real_inj,
simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul,
of_real_one, of_real_bit0],
convert cos_add_cos _ _;
norm_cast,
end
lemma tan_eq_sin_div_cos : tan x = sin x / cos x :=
by rw [← of_real_inj, of_real_tan, tan_eq_sin_div_cos, of_real_div, of_real_sin, of_real_cos]
lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x :=
by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx]
@[simp] lemma tan_zero : tan 0 = 0 := by simp [tan]
@[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div]
@[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 :=
of_real_inj.1 $ by simp
@[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 :=
by rw [add_comm, sin_sq_add_cos_sq]
lemma sin_sq_le_one : sin x ^ 2 ≤ 1 :=
by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (sq_nonneg _)
lemma cos_sq_le_one : cos x ^ 2 ≤ 1 :=
by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (sq_nonneg _)
lemma abs_sin_le_one : abs' (sin x) ≤ 1 :=
abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, sin_sq_le_one]
lemma abs_cos_le_one : abs' (cos x) ≤ 1 :=
abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, cos_sq_le_one]
lemma sin_le_one : sin x ≤ 1 :=
(abs_le.1 (abs_sin_le_one _)).2
lemma cos_le_one : cos x ≤ 1 :=
(abs_le.1 (abs_cos_le_one _)).2
lemma neg_one_le_sin : -1 ≤ sin x :=
(abs_le.1 (abs_sin_le_one _)).1
lemma neg_one_le_cos : -1 ≤ cos x :=
(abs_le.1 (abs_cos_le_one _)).1
lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 :=
by rw ← of_real_inj; simp [cos_two_mul]
lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 :=
by rw ← of_real_inj; simp [cos_two_mul']
lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x :=
by rw ← of_real_inj; simp [sin_two_mul]
lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 :=
of_real_inj.1 $ by simpa using cos_sq x
lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 :=
by rw [←sin_sq_add_cos_sq x, add_sub_cancel']
lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 :=
eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _
lemma abs_sin_eq_sqrt_one_sub_cos_sq (x : ℝ) :
abs' (sin x) = sqrt (1 - cos x ^ 2) :=
by rw [← sin_sq, sqrt_sq_eq_abs]
lemma abs_cos_eq_sqrt_one_sub_sin_sq (x : ℝ) :
abs' (cos x) = sqrt (1 - sin x ^ 2) :=
by rw [← cos_sq', sqrt_sq_eq_abs]
lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 :=
have complex.cos x ≠ 0, from mt (congr_arg re) hx,
of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this
lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) :
tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 :=
by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul]
lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) :
(sqrt (1 + tan x ^ 2))⁻¹ = cos x :=
by rw [← sqrt_sq hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne']
lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) :
tan x / sqrt (1 + tan x ^ 2) = sin x :=
by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv]
lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x :=
by rw ← of_real_inj; simp [cos_three_mul]
lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 :=
by rw ← of_real_inj; simp [sin_three_mul]
/-- The definition of `sinh` in terms of `exp`. -/
lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 :=
eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two,
← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re]
@[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh]
@[simp] lemma sinh_neg : sinh (-x) = -sinh x :=
by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul]
lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y :=
by rw ← of_real_inj; simp [sinh_add]
/-- The definition of `cosh` in terms of `exp`. -/
lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 :=
eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two,
← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re]
@[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh]
@[simp] lemma cosh_neg : cosh (-x) = cosh x :=
by simp [cosh, exp_neg]
lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y :=
by rw ← of_real_inj; simp [cosh, cosh_add]
lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y :=
by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg]
lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y :=
by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg]
lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x :=
of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh]
@[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh]
@[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div]
lemma cosh_add_sinh : cosh x + sinh x = exp x :=
by rw ← of_real_inj; simp [cosh_add_sinh]
lemma sinh_add_cosh : sinh x + cosh x = exp x :=
by rw ← of_real_inj; simp [sinh_add_cosh]
lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 :=
by rw ← of_real_inj; simp [cosh_sq_sub_sinh_sq]
lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 :=
by rw ← of_real_inj; simp [cosh_sq]
lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 :=
by rw ← of_real_inj; simp [sinh_sq]
lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 :=
by rw ← of_real_inj; simp [cosh_two_mul]
lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x :=
by rw ← of_real_inj; simp [sinh_two_mul]
lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x :=
by rw ← of_real_inj; simp [cosh_three_mul]
lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x :=
by rw ← of_real_inj; simp [sinh_three_mul]
open is_absolute_value
/- TODO make this private and prove ∀ x -/
lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x :=
calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') :
le_lim (cau_seq.le_of_exists ⟨2,
λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re,
from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp,
have h₂ : ((x : ℂ) ^ 0 / 0!).re = 1, by simp,
begin
rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ',
add_re, add_re, h₁, h₂, add_assoc,
← @sum_hom _ _ _ _ _ _ _ complex.re
(is_add_group_hom.to_is_add_monoid_hom _)],
refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) (le_refl _),
rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re],
exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _),
end⟩)
... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re]
lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x :=
by linarith [add_one_le_exp_of_nonneg hx]
lemma exp_pos (x : ℝ) : 0 < exp x :=
(le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp)
(λ h, by rw [← neg_neg x, real.exp_neg];
exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h))))
@[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x :=
abs_of_pos (exp_pos _)
lemma exp_strict_mono : strict_mono exp :=
λ x y h, by rw [← sub_add_cancel y x, real.exp_add];
exact (lt_mul_iff_one_lt_left (exp_pos _)).2
(lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith)))
@[mono] lemma exp_monotone : ∀ {x y : ℝ}, x ≤ y → exp x ≤ exp y := exp_strict_mono.monotone
@[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt
@[simp] lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le
lemma exp_injective : function.injective exp := exp_strict_mono.injective
@[simp] lemma exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff
@[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 :=
by rw [← exp_zero, exp_injective.eq_iff]
@[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x :=
by rw [← exp_zero, exp_lt_exp]
@[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 :=
by rw [← exp_zero, exp_lt_exp]
@[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 :=
exp_zero ▸ exp_le_exp
@[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x :=
exp_zero ▸ exp_le_exp
/-- `real.cosh` is always positive -/
lemma cosh_pos (x : ℝ) : 0 < real.cosh x :=
(cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x)))
end real
namespace complex
lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) :
∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ / (n! * n) :=
calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α)
= ∑ m in range (j - n), 1 / (m + n)! :
sum_bij (λ m _, m - n)
(λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2
(by simp at hm; tauto))
(λ m hm, by rw nat.sub_add_cancel; simp at *; tauto)
(λ a₁ a₂ ha₁ ha₂ h,
by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add,
add_left_inj, eq_comm] at h;
simp at *; tauto)
(λ b hb, ⟨b + n,
mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩,
by rw nat.add_sub_cancel⟩)
... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ :
begin
refine sum_le_sum (assume m n, _),
rw [one_div, inv_le_inv],
{ rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm],
exact nat.factorial_mul_pow_le_factorial },
{ exact nat.cast_pos.2 (nat.factorial_pos _) },
{ exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _))
(pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) },
end
... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m :
by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow']
... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) :
have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1
(mt nat.succ.inj (pos_iff_ne_zero.1 hn)),
have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _),
have h₃ : (n! * n : α) ≠ 0,
from mul_ne_zero (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.factorial_pos _)))
(nat.cast_ne_zero.2 (pos_iff_ne_zero.1 hn)),
have h₄ : (n.succ - 1 : α) = n, by simp,
by rw [← geom_sum_def, geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃,
mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev', h₄,
← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃];
simp [mul_add, add_mul, mul_assoc, mul_comm]
... ≤ n.succ / (n! * n) :
begin
refine iff.mpr (div_le_div_right (mul_pos _ _)) _,
exact nat.cast_pos.2 (nat.factorial_pos _),
exact nat.cast_pos.2 hn,
exact sub_le_self _
(mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _))
end
lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) :
abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) :=
begin
rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs],
refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩),
simp_rw ← sub_eq_add_neg,
show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!)
≤ abs x ^ n * (n.succ * (n! * n)⁻¹),
rw sum_range_sub_sum_range hj,
exact calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ))
= abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) :
begin
refine congr_arg abs (sum_congr rfl (λ m hm, _)),
rw [mem_filter, mem_range] at hm,
rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel' hm.2]
end
... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _
... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) :
begin
refine sum_le_sum (λ m hm, _),
rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat],
refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _,
exact nat.cast_pos.2 (nat.factorial_pos _),
rw abv_pow abs,
exact (pow_le_one _ (abs_nonneg _) hx),
exact pow_nonneg (abs_nonneg _) _
end
... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) :
by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm]
... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) :
mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs_nonneg _) _)
end
lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) :
abs (exp x - 1) ≤ 2 * abs x :=
calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) :
by simp [sum_range_succ]
... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) :
exp_bound hx dec_trivial
... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm]
lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) :
abs (exp x - 1 - x) ≤ (abs x)^2 :=
calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) :
by simp [sub_eq_add_neg, sum_range_succ_comm, add_assoc]
... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) :
exp_bound hx dec_trivial
... ≤ (abs x)^2 * 1 :
mul_le_mul_of_nonneg_left (by norm_num) (sq_nonneg (abs x))
... = (abs x)^2 :
by rw [mul_one]
end complex
namespace real
open complex finset
lemma exp_bound {x : ℝ} (hx : abs' x ≤ 1) {n : ℕ} (hn : 0 < n) :
abs' (exp x - ∑ m in range n, x ^ m / m!) ≤ abs' x ^ n * (n.succ / (n! * n)) :=
begin
have hxc : complex.abs x ≤ 1, by exact_mod_cast hx,
convert exp_bound hxc hn; norm_cast
end
/-- A finite initial segment of the exponential series, followed by an arbitrary tail.
For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function
of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`,
for any `r`. -/
def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r
@[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near]
@[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) :=
by simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv,
mul_inv']; ac_refl
theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) :=
by simp [exp_near, mul_sub]
lemma exp_approx_end (n m : ℕ) (x : ℝ)
(e₁ : n + 1 = m) (h : abs' x ≤ 1) :
abs' (exp x - exp_near m x 0) ≤ abs' x ^ m / m! * ((m+1)/m) :=
by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith }
lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ)
(e₁ : n + 1 = m) (a₂ b₂ : ℝ)
(e : abs' (1 + x / m * a₂ - a₁) ≤ b₁ - abs' x / m * b₂)
(h : abs' (exp x - exp_near m x a₂) ≤ abs' x ^ m / m! * b₂) :
abs' (exp x - exp_near n x a₁) ≤ abs' x ^ n / n! * b₁ :=
begin
refine (_root_.abs_sub_le _ _ _).trans ((add_le_add_right h _).trans _),
subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul],
convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _,
{ simp [mul_add, pow_succ', div_eq_mul_inv, _root_.abs_mul, _root_.abs_inv, ← pow_abs, mul_inv'],
ac_refl },
{ simp [_root_.div_nonneg, _root_.abs_nonneg] }
end
lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ)
(e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : abs' x ≤ 1)
(e : abs' (1 - a) ≤ b - abs' x / rm * ((rm+1)/rm)) :
abs' (exp x - exp_near n x a) ≤ abs' x ^ n / n! * b :=
by subst er; exact
exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h)
lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ}
(en : n + 1 = m) {rm : ℝ} (er : ↑m = rm)
(h : abs' (exp 1 - exp_near m 1 ((a₁ - 1) * rm)) ≤ abs' 1 ^ m / m! * (b₁ * rm)) :
abs' (exp 1 - exp_near n 1 a₁) ≤ abs' 1 ^ n / n! * b₁ :=
begin
subst er,
refine exp_approx_succ _ en _ _ _ h,
field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith],
end
lemma exp_approx_start (x a b : ℝ)
(h : abs' (exp x - exp_near 0 x a) ≤ abs' x ^ 0 / 0! * b) :
abs' (exp x - a) ≤ b :=
by simpa using h
lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) :
abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) :=
calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) :
by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) :
by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)]
... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) +
((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) :
congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
simp only [sum_range_succ],
simp [pow_succ],
apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
end)
... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) +
abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) :
by rw add_div; exact abs_add _ _
... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 +
abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) :
by simp [complex.abs_div]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 +
(complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) :
add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]
lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) :
abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) :=
calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) :
by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv]
... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) :
by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _),
div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num]
... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) -
(complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) :
congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin
simp only [sum_range_succ],
simp [pow_succ],
apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring
end)
... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) +
abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) :
by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _
... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 +
abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) :
by simp [add_comm, complex.abs_div, complex.abs_mul]
... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 +
(complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) :
add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial))
... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc]
lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x :=
calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) :
sub_pos.2 $ lt_sub_iff_add_lt.2
(calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2
≤ 1 * (5 / 96) + 1 / 2 :
add_le_add
(mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num))
((div_le_div_right (by norm_num)).2 (by rw [sq, ← abs_mul_self, _root_.abs_mul];
exact mul_le_one hx (abs_nonneg _) hx))
... < 1 : by norm_num)
... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2
lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x :=
calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) :
sub_pos.2 $ lt_sub_iff_add_lt.2
(calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6
≤ x * (5 / 96) + x / 6 :
add_le_add
(mul_le_mul_of_nonneg_right
(calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _)
(by rwa _root_.abs_of_nonneg (le_of_lt hx0))
dec_trivial
... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num))
((div_le_div_right (by norm_num)).2
(calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial
... = x : pow_one _))
... < x : by linarith)
... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound
(by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2
lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x :=
have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa),
calc 0 < 2 * sin (x / 2) * cos (x / 2) :
mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this))
(cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))]))
... = sin x : by rw [← sin_two_mul, two_mul, add_halves]
lemma cos_one_le : cos 1 ≤ 2 / 3 :=
calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) :
sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1
... ≤ 2 / 3 : by norm_num
lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp)
lemma cos_two_neg : cos 2 < 0 :=
calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm
... = _ : real.cos_two_mul 1
... ≤ 2 * (2 / 3) ^ 2 - 1 :
sub_le_sub_right (mul_le_mul_of_nonneg_left
(by rw [sq, sq]; exact
mul_self_le_mul_self (le_of_lt cos_one_pos)
cos_one_le)
(by norm_num)) _
... < 0 : by norm_num
end real
namespace complex
lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 :=
have _ := real.sin_sq_add_cos_sq x,
by simp [add_comm, abs, norm_sq, sq, *, sin_of_real_re, cos_of_real_re, mul_re] at *
lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re :=
by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y,
abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I,
← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)),
abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one];
exact ⟨λ h, real.exp_injective h, congr_arg _⟩
@[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x :=
by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _))
end complex
|
3590e1fb5c5bea94a1d5a77d7fed3d61fde6c83b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/action_auto.lean | e33cc516b9a1b41f3308ec64761fef88613df98e | [] | 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 | 4,264 | lean | /-
Copyright (c) 2020 David Wärn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Wärn
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.elements
import Mathlib.category_theory.single_obj
import Mathlib.group_theory.group_action.basic
import Mathlib.PostPort
universes u u_1
namespace Mathlib
/-!
# Actions as functors and as categories
From a multiplicative action M ↻ X, we can construct a functor from M to the category of
types, mapping the single object of M to X and an element `m : M` to map `X → X` given by
multiplication by `m`.
This functor induces a category structure on X -- a special case of the category of elements.
A morphism `x ⟶ y` in this category is simply a scalar `m : M` such that `m • x = y`. In the case
where M is a group, this category is a groupoid -- the `action groupoid'.
-/
namespace category_theory
/-- A multiplicative action M ↻ X viewed as a functor mapping the single object of M to X
and an element `m : M` to the map `X → X` given by multiplication by `m`. -/
@[simp] theorem action_as_functor_obj (M : Type u_1) [monoid M] (X : Type u) [mul_action M X]
(_x : single_obj M) : functor.obj (action_as_functor M X) _x = X :=
Eq.refl (functor.obj (action_as_functor M X) _x)
/-- A multiplicative action M ↻ X induces a category strucure on X, where a morphism
from x to y is a scalar taking x to y. Due to implementation details, the object type
of this category is not equal to X, but is in bijection with X. -/
def action_category (M : Type u_1) [monoid M] (X : Type u) [mul_action M X] :=
functor.elements (action_as_functor M X)
namespace action_category
protected instance category_theory.groupoid (X : Type u) (G : Type u_1) [group G] [mul_action G X] :
groupoid (action_category G X) :=
category_theory.groupoid_of_elements (action_as_functor G X)
/-- The projection from the action category to the monoid, mapping a morphism to its
label. -/
def π (M : Type u_1) [monoid M] (X : Type u) [mul_action M X] :
action_category M X ⥤ single_obj M :=
category_of_elements.π (action_as_functor M X)
@[simp] theorem π_map (M : Type u_1) [monoid M] (X : Type u) [mul_action M X]
(p : action_category M X) (q : action_category M X) (f : p ⟶ q) :
functor.map (π M X) f = subtype.val f :=
rfl
@[simp] theorem π_obj (M : Type u_1) [monoid M] (X : Type u) [mul_action M X]
(p : action_category M X) : functor.obj (π M X) p = single_obj.star M :=
subsingleton.elim (functor.obj (π M X) p) (single_obj.star M)
/-- An object of the action category given by M ↻ X corresponds to an element of X. -/
def obj_equiv (M : Type u_1) [monoid M] (X : Type u) [mul_action M X] : X ≃ action_category M X :=
equiv.mk (fun (x : X) => sigma.mk (single_obj.star M) x)
(fun (p : action_category M X) => sigma.snd p) sorry sorry
theorem hom_as_subtype (M : Type u_1) [monoid M] (X : Type u) [mul_action M X]
(p : action_category M X) (q : action_category M X) :
(p ⟶ q) =
Subtype
fun (m : M) =>
m • coe_fn (equiv.symm (obj_equiv M X)) p = coe_fn (equiv.symm (obj_equiv M X)) q :=
rfl
protected instance inhabited (M : Type u_1) [monoid M] (X : Type u) [mul_action M X] [Inhabited X] :
Inhabited (action_category M X) :=
{ default := coe_fn (obj_equiv M X) Inhabited.default }
/-- The stabilizer of a point is isomorphic to the endomorphism monoid at the
corresponding point. In fact they are definitionally equivalent. -/
def stabilizer_iso_End (M : Type u_1) [monoid M] {X : Type u} [mul_action M X] (x : X) :
↥(mul_action.stabilizer.submonoid M x) ≃* End (coe_fn (obj_equiv M X) x) :=
mul_equiv.refl ↥(mul_action.stabilizer.submonoid M x)
@[simp] theorem stabilizer_iso_End_apply (M : Type u_1) [monoid M] {X : Type u} [mul_action M X]
(x : X) (f : ↥(mul_action.stabilizer.submonoid M x)) :
mul_equiv.to_fun (stabilizer_iso_End M x) f = f :=
rfl
@[simp] theorem stabilizer_iso_End_symm_apply (M : Type u_1) [monoid M] {X : Type u}
[mul_action M X] (x : X) (f : End (coe_fn (obj_equiv M X) x)) :
mul_equiv.inv_fun (stabilizer_iso_End M x) f = f :=
rfl
end Mathlib |
28639a781c42d24118a4a4de1b57843514a38952 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/testing/slim_check/testable.lean | 1e480b26dfc3230e9a505f5ed967bf0fb352b6f4 | [] | 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 | 27,344 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.testing.slim_check.sampleable
import Mathlib.PostPort
universes l v u_1 u u_2
namespace Mathlib
/-!
# `testable` Class
Testable propositions have a procedure that can generate counter-examples
together with a proof that they invalidate the proposition.
This is a port of the Haskell QuickCheck library.
## Creating Customized Instances
The type classes `testable` and `sampleable` are the means by which
`slim_check` creates samples and tests them. For instance, the proposition
`∀ i j : ℕ, i ≤ j` has a `testable` instance because `ℕ` is sampleable
and `i ≤ j` is decidable. Once `slim_check` finds the `testable`
instance, it can start using the instance to repeatedly creating samples
and checking whether they satisfy the property. This allows the
user to create new instances and apply `slim_check` to new situations.
### Polymorphism
The property `testable.check (∀ (α : Type) (xs ys : list α), xs ++ ys
= ys ++ xs)` shows us that type-polymorphic properties can be
tested. `α` is instantiated with `ℤ` first and then tested as normal
monomorphic properties.
The monomorphisation limits the applicability of `slim_check` to
polymorphic properties that can be stated about integers. The
limitation may be lifted in the future but, for now, if
one wishes to use a different type than `ℤ`, one has to refer to
the desired type.
### What do I do if I'm testing a property about my newly defined type?
Let us consider a type made for a new formalization:
```lean
structure my_type :=
(x y : ℕ)
(h : x ≤ y)
```
How do we test a property about `my_type`? For instance, let us consider
`testable.check $ ∀ a b : my_type, a.y ≤ b.x → a.x ≤ b.y`. Writing this
property as is will give us an error because we do not have an instance
of `sampleable my_type`. We can define one as follows:
```lean
instance : sampleable my_type :=
{ sample := do
x ← sample ℕ,
xy_diff ← sample ℕ,
return { x := x, y := x + xy_diff, h := /- some proof -/ } }
```
We can see that the instance is very simple because our type is built
up from other type that have `sampleable` instances. `sampleable` also
has a `shrink` method but it is optional. We may want to implement one
for ease of testing as:
```lean
/- ... -/
/- no specialized sampling -/
-- discard
-- x := 1
-- discard
-- x := 41
-- discard
-- x := 3
-- discard
-- x := 5
-- discard
-- x := 5
-- discard
-- x := 197
-- discard
-- x := 469
-- discard
-- x := 9
-- discard
-- ===================
-- Found problems!
-- x := 552
-- -------------------
/- let us define a specialized sampling instance -/
-- ===================
-- Found problems!
-- x := 358
-- -------------------
namespace slim_check
/-- Result of trying to disprove `p`
The constructors are:
* `success : (psum unit p) → test_result`
succeed when we find another example satisfying `p`
In `success h`, `h` is an optional proof of the proposition.
Without the proof, all we know is that we found one example
where `p` holds. With a proof, the one test was sufficient to
prove that `p` holds and we do not need to keep finding examples.
* `gave_up {} : ℕ → test_result`
give up when a well-formed example cannot be generated.
`gave_up n` tells us that `n` invalid examples were tried.
Above 100, we give up on the proposition and report that we
did not find a way to properly test it.
* `failure : ¬ p → (list string) → ℕ → test_result`
a counter-example to `p`; the strings specify values for the relevant variables.
`failure h vs n` also carries a proof that `p` does not hold. This way, we can
guarantee that there will be no false positive. The last component, `n`,
is the number of times that the counter-example was shrunk.
-/
inductive test_result (p : Prop)
where
| success : psum Unit p → test_result p
| gave_up : ℕ → test_result p
| failure : ¬p → List string → ℕ → test_result p
/-- format a `test_result` as a string. -/
protected def test_result.to_string {p : Prop} : test_result p → string :=
sorry
/-- configuration for testing a property -/
structure slim_check_cfg
where
num_inst : ℕ
max_size : ℕ
trace_discarded : Bool
trace_success : Bool
trace_shrink : Bool
trace_shrink_candidates : Bool
random_seed : Option ℕ
quiet : Bool
protected instance test_result.has_to_string {p : Prop} : has_to_string (test_result p) :=
has_to_string.mk test_result.to_string
/--
`printable_prop p` allows one to print a proposition so that
`slim_check` can indicate how values relate to each other.
-/
class printable_prop (p : Prop)
where
print_prop : Option string
protected instance default_printable_prop {p : Prop} : printable_prop p :=
printable_prop.mk none
/-- `testable p` uses random examples to try to disprove `p`. -/
class testable (p : Prop)
where
run : slim_check_cfg → Bool → gen (test_result p)
/-- applicative combinator proof carrying test results -/
def combine {p : Prop} {q : Prop} : psum Unit (p → q) → psum Unit p → psum Unit q :=
sorry
/-- Combine the test result for properties `p` and `q` to create a test for their conjunction. -/
def and_counter_example {p : Prop} {q : Prop} : test_result p → test_result q → test_result (p ∧ q) :=
sorry
/-- Combine the test result for properties `p` and `q` to create a test for their disjunction -/
def or_counter_example {p : Prop} {q : Prop} : test_result p → test_result q → test_result (p ∨ q) :=
sorry
/-- If `q → p`, then `¬ p → ¬ q` which means that testing `p` can allow us
to find counter-examples to `q`. -/
def convert_counter_example {p : Prop} {q : Prop} (h : q → p) : test_result p → optParam (psum Unit (p → q)) (psum.inl Unit.unit) → test_result q :=
sorry
/-- Test `q` by testing `p` and proving the equivalence between the two. -/
def convert_counter_example' {p : Prop} {q : Prop} (h : p ↔ q) (r : test_result p) : test_result q :=
convert_counter_example (iff.mpr h) r (psum.inr (iff.mp h))
/-- When we assign a value to a universally quantified variable,
we record that value using this function so that our counter-examples
can be informative. -/
def add_to_counter_example (x : string) {p : Prop} {q : Prop} (h : q → p) : test_result p → optParam (psum Unit (p → q)) (psum.inl Unit.unit) → test_result q :=
sorry
/-- Add some formatting to the information recorded by `add_to_counter_example`. -/
def add_var_to_counter_example {γ : Type v} [has_repr γ] (var : string) (x : γ) {p : Prop} {q : Prop} (h : q → p) : test_result p → optParam (psum Unit (p → q)) (psum.inl Unit.unit) → test_result q :=
add_to_counter_example
(var ++
string.str
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat (bit0 (bit1 (bit0 (bit1 (bit1 1)))))))
(char.of_nat (bit1 (bit0 (bit1 (bit1 (bit1 1)))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
repr x)
h
/-- Gadget used to introspect the name of bound variables.
It is used with the `testable` typeclass so that
`testable (named_binder "x" (∀ x, p x))` can use the variable name
of `x` in error messages displayed to the user. If we find that instantiating
the above quantifier with 3 falsifies it, we can print:
```
==============
Problem found!
==============
x := 3
```
-/
@[simp] def named_binder (n : string) (p : Prop) :=
p
/-- Is the given test result a failure? -/
def is_failure {p : Prop} : test_result p → Bool :=
sorry
protected instance and_testable (p : Prop) (q : Prop) [testable p] [testable q] : testable (p ∧ q) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
do
let xp ← testable.run p cfg min
let xq ← testable.run q cfg min
pure (and_counter_example xp xq)
protected instance or_testable (p : Prop) (q : Prop) [testable p] [testable q] : testable (p ∨ q) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
do
testable.run p cfg min
sorry
protected instance iff_testable (p : Prop) (q : Prop) [testable (p ∧ q ∨ ¬p ∧ ¬q)] : testable (p ↔ q) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
do
let xp ← testable.run (p ∧ q ∨ ¬p ∧ ¬q) cfg min
return (convert_counter_example' sorry xp)
protected instance dec_guard_testable (var : string) (p : Prop) [printable_prop p] [Decidable p] (β : p → Prop) [(h : p) → testable (β h)] : testable (named_binder var (∀ (h : p), β h)) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
dite p (fun (h : p) => sorry)
fun (h : ¬p) =>
ite (↥(slim_check_cfg.trace_discarded cfg) ∨ ↥(slim_check_cfg.trace_success cfg)) sorry
(return (test_result.gave_up 1))
/-- Type tag that replaces a type's `has_repr` instance with its `has_to_string` instance. -/
def use_has_to_string (α : Type u_1) :=
α
protected instance use_has_to_string.inhabited (α : Type u) [I : Inhabited α] : Inhabited (use_has_to_string α) :=
I
/-- Add the type tag `use_has_to_string` to an expression's type. -/
def use_has_to_string.mk {α : Type u_1} (x : α) : use_has_to_string α :=
x
protected instance use_has_to_string.has_repr (α : Type u) [has_to_string α] : has_repr (use_has_to_string α) :=
has_repr.mk to_string
protected instance all_types_testable (var : string) (f : Type → Prop) [testable (f ℤ)] : testable (named_binder var (∀ (x : Type), f x)) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
do
let r ← testable.run (f ℤ) cfg min
return
(add_var_to_counter_example var
(use_has_to_string.mk
(string.str string.empty
(char.of_nat
(bit0 (bit0 (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit0 (bit0 1))))))))))))))))
sorry r (psum.inl Unit.unit))
/-- Trace the value of sampled variables if the sample is discarded. -/
def trace_if_giveup {p : Prop} {α : Type u_1} {β : Type u_2} [has_repr α] (tracing_enabled : Bool) (var : string) (val : α) : test_result p → thunk β → β :=
sorry
/-- testable instance for a property iterating over the element of a list -/
protected instance test_forall_in_list (var : string) (var' : string) (α : Type u) (β : α → Prop) [(x : α) → testable (β x)] [has_repr α] (xs : List α) : testable (named_binder var (∀ (x : α), named_binder var' (x ∈ xs → β x))) :=
sorry
/-- Test proposition `p` by randomly selecting one of the provided
testable instances. -/
def combine_testable (p : Prop) (t : List (testable p)) (h : 0 < list.length t) : testable p :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
(fun (this : 0 < list.length (list.map (fun (t : testable p) => testable.run p cfg min) t)) =>
gen.one_of (list.map (fun (t : testable p) => testable.run p cfg min) t) this)
sorry
/--
Format the counter-examples found in a test failure.
-/
def format_failure (s : string) (xs : List string) (n : ℕ) : string := sorry
-------------------
/--
Format the counter-examples found in a test failure.
-/
def format_failure' (s : string) {p : Prop} : test_result p → string :=
sorry
/--
Increase the number of shrinking steps in a test result.
-/
def add_shrinks {p : Prop} (n : ℕ) : test_result p → test_result p :=
sorry
/-- Shrink a counter-example `x` by using `shrink x`, picking the first
candidate that falsifies a property and recursively shrinking that one.
The process is guaranteed to terminate because `shrink x` produces
a proof that all the values it produces are smaller (according to `sizeof`)
than `x`. -/
def minimize_aux (α : Type u) (β : α → Prop) [sampleable_ext α] [(x : α) → testable (β x)] (cfg : slim_check_cfg) (var : string) : sampleable_ext.proxy_repr α →
ℕ → option_t gen (sigma fun (x : sampleable_ext.proxy_repr α) => test_result (β (sampleable_ext.interp α x))) := sorry
/-- Once a property fails to hold on an example, look for smaller counter-examples
to show the user. -/
def minimize (α : Type u) (β : α → Prop) [sampleable_ext α] [(x : α) → testable (β x)] (cfg : slim_check_cfg) (var : string) (x : sampleable_ext.proxy_repr α) (r : test_result (β (sampleable_ext.interp α x))) : gen (sigma fun (x : sampleable_ext.proxy_repr α) => test_result (β (sampleable_ext.interp α x))) := sorry
protected instance exists_testable (var : string) (var' : string) (α : Type u) (β : α → Prop) (p : Prop) [testable (named_binder var (∀ (x : α), named_binder var' (β x → p)))] : testable (named_binder var' (named_binder var (∃ (x : α), β x) → p)) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
do
let x ← testable.run (named_binder var (∀ (x : α), named_binder var' (β x → p))) cfg min
pure (convert_counter_example' sorry x)
/-- Test a universal property by creating a sample of the right type and instantiating the
bound variable with it -/
protected instance var_testable (var : string) (α : Type u) (β : α → Prop) [sampleable_ext α] [(x : α) → testable (β x)] : testable (named_binder var (∀ (x : α), β x)) := sorry
/-- Test a universal property about propositions -/
protected instance prop_var_testable (var : string) (β : Prop → Prop) [I : (b : Bool) → testable (β ↥b)] : testable (named_binder var (∀ (p : Prop), β p)) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
(fun (ᾰ : test_result (∀ (b : Bool), β ↥b)) => convert_counter_example sorry ᾰ (psum.inl Unit.unit)) <$>
testable.run (named_binder var (∀ (b : Bool), β ↥b)) cfg min
protected instance unused_var_testable (var : string) (α : Type u) (β : Prop) [Inhabited α] [testable β] : testable (named_binder var (α → β)) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
do
let r ← testable.run β cfg min
pure (convert_counter_example sorry r (psum.inr sorry))
protected instance subtype_var_testable (var : string) (var' : string) (α : Type u) (β : α → Prop) {p : α → Prop} [(x : α) → printable_prop (p x)] [(x : α) → testable (β x)] [I : sampleable_ext (Subtype p)] : testable (named_binder var (∀ (x : α), named_binder var' (p x → β x))) :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
let test : (x : Subtype p) → testable (β ↑x) :=
fun (x : Subtype p) =>
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
do
testable.run (β (subtype.val x)) cfg min
sorry;
do
let r ← testable.run (∀ (x : Subtype p), β (subtype.val x)) cfg min
pure (convert_counter_example' sorry r)
protected instance decidable_testable (p : Prop) [printable_prop p] [Decidable p] : testable p :=
testable.mk
fun (cfg : slim_check_cfg) (min : Bool) =>
return (dite p (fun (h : p) => test_result.success (psum.inr h)) fun (h : ¬p) => sorry)
protected instance eq.printable_prop {α : Type u_1} [has_repr α] (x : α) (y : α) : printable_prop (x = y) :=
printable_prop.mk
(some
(string.empty ++ to_string (repr x) ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat (bit1 (bit0 (bit1 (bit1 (bit1 1)))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string (repr y) ++
string.empty)))
protected instance ne.printable_prop {α : Type u_1} [has_repr α] (x : α) (y : α) : printable_prop (x ≠ y) :=
printable_prop.mk
(some
(string.empty ++ to_string (repr x) ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat
(bit0 (bit0 (bit0 (bit0 (bit0 (bit1 (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit0 1)))))))))))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string (repr y) ++
string.empty)))
protected instance le.printable_prop {α : Type u_1} [HasLessEq α] [has_repr α] (x : α) (y : α) : printable_prop (x ≤ y) :=
printable_prop.mk
(some
(string.empty ++ to_string (repr x) ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat
(bit0 (bit0 (bit1 (bit0 (bit0 (bit1 (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit0 1)))))))))))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string (repr y) ++
string.empty)))
protected instance lt.printable_prop {α : Type u_1} [HasLess α] [has_repr α] (x : α) (y : α) : printable_prop (x < y) :=
printable_prop.mk
(some
(string.empty ++ to_string (repr x) ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat (bit0 (bit0 (bit1 (bit1 (bit1 1)))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string (repr y) ++
string.empty)))
protected instance perm.printable_prop {α : Type u_1} [has_repr α] (xs : List α) (ys : List α) : printable_prop (xs ~ ys) :=
printable_prop.mk
(some
(string.empty ++ to_string (repr xs) ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat (bit0 (bit1 (bit1 (bit1 (bit1 (bit1 1))))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string (repr ys) ++
string.empty)))
protected instance and.printable_prop (x : Prop) (y : Prop) [printable_prop x] [printable_prop y] : printable_prop (x ∧ y) :=
printable_prop.mk
(do
let x' ← printable_prop.print_prop x
let y' ← printable_prop.print_prop y
some
(string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 1)))))) ++ to_string x' ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat
(bit1 (bit1 (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit0 (bit1 (bit0 (bit0 (bit0 1)))))))))))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string y' ++
string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 1)))))))))
protected instance or.printable_prop (x : Prop) (y : Prop) [printable_prop x] [printable_prop y] : printable_prop (x ∨ y) :=
printable_prop.mk
(do
let x' ← printable_prop.print_prop x
let y' ← printable_prop.print_prop y
some
(string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 1)))))) ++ to_string x' ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat
(bit0 (bit0 (bit0 (bit1 (bit0 (bit1 (bit0 (bit0 (bit0 (bit1 (bit0 (bit0 (bit0 1)))))))))))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string y' ++
string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 1)))))))))
protected instance iff.printable_prop (x : Prop) (y : Prop) [printable_prop x] [printable_prop y] : printable_prop (x ↔ y) :=
printable_prop.mk
(do
let x' ← printable_prop.print_prop x
let y' ← printable_prop.print_prop y
some
(string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 1)))))) ++ to_string x' ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat
(bit0 (bit0 (bit1 (bit0 (bit1 (bit0 (bit0 (bit1 (bit1 (bit0 (bit0 (bit0 (bit0 1)))))))))))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string y' ++
string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 1)))))))))
protected instance imp.printable_prop (x : Prop) (y : Prop) [printable_prop x] [printable_prop y] : printable_prop (x → y) :=
printable_prop.mk
(do
let x' ← printable_prop.print_prop x
let y' ← printable_prop.print_prop y
some
(string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit1 (bit0 1)))))) ++ to_string x' ++
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))
(char.of_nat
(bit0 (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 (bit1 (bit0 (bit0 (bit0 (bit0 1)))))))))))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string y' ++
string.str string.empty (char.of_nat (bit1 (bit0 (bit0 (bit1 (bit0 1)))))))))
protected instance not.printable_prop (x : Prop) [printable_prop x] : printable_prop (¬x) :=
printable_prop.mk
(do
let x' ← printable_prop.print_prop x
some
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 (bit1 (bit0 1)))))))))
(char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++
to_string x' ++
string.empty))
protected instance true.printable_prop : printable_prop True :=
printable_prop.mk
(some
(string.str
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit0 (bit1 (bit1 1))))))))
(char.of_nat (bit0 (bit1 (bit0 (bit0 (bit1 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit1 (bit0 (bit1 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))))))
protected instance false.printable_prop : printable_prop False :=
printable_prop.mk
(some
(string.str
(string.str
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit0 (bit0 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit0 (bit0 (bit0 (bit1 1))))))))
(char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 (bit1 1))))))))
(char.of_nat (bit1 (bit1 (bit0 (bit0 (bit1 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))))))
protected instance bool.printable_prop (b : Bool) : printable_prop ↥b :=
printable_prop.mk
(some
(ite (↥b)
(string.str
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit0 (bit1 (bit1 1))))))))
(char.of_nat (bit0 (bit1 (bit0 (bit0 (bit1 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit1 (bit0 (bit1 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit1 (bit0 (bit0 (bit1 1))))))))
(string.str
(string.str
(string.str
(string.str (string.str string.empty (char.of_nat (bit0 (bit1 (bit1 (bit0 (bit0 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit0 (bit0 (bit0 (bit1 1))))))))
(char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 (bit1 1))))))))
(char.of_nat (bit1 (bit1 (bit0 (bit0 (bit1 (bit1 1))))))))
(char.of_nat (bit1 (bit0 (bit1 (bit0 (bit0 (bit1 1))))))))))
/-- Execute `cmd` and repeat every time the result is `gave_up` (at most
`n` times). -/
def retry {p : Prop} (cmd : rand (test_result p)) : ℕ → rand (test_result p) :=
sorry
/-- Count the number of times the test procedure gave up. -/
def give_up {p : Prop} (x : ℕ) : test_result p → test_result p :=
sorry
/-- Try `n` times to find a counter-example for `p`. -/
def testable.run_suite_aux (p : Prop) [testable p] (cfg : slim_check_cfg) : test_result p → ℕ → rand (test_result p) :=
sorry
/-- Try to find a counter-example of `p`. -/
def testable.run_suite (p : Prop) [testable p] (cfg : optParam slim_check_cfg
(slim_check_cfg.mk (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))) (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))) false false
false false none false)) : rand (test_result p) :=
testable.run_suite_aux p cfg (test_result.success (psum.inl Unit.unit)) (slim_check_cfg.num_inst cfg)
/-- Run a test suite for `p` in `io`. -/
def testable.check' (p : Prop) [testable p] (cfg : optParam slim_check_cfg
(slim_check_cfg.mk (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))) (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))) false false
false false none false)) : io (test_result p) :=
sorry
namespace tactic
/-!
## Decorations
Instances of `testable` use `named_binder` as a decoration on
propositions in order to access the name of bound variables, as in
`named_binder "x" (forall x, x < y)`. This helps the
`testable` instances create useful error messages where variables
are matched with values that falsify a given proposition.
The following functions help support the gadget so that the user does
not have to put them in themselves.
-/
/-- `add_existential_decorations p` adds `a `named_binder` annotation at the
root of `p` if `p` is an existential quantification. -/
/-- Traverse the syntax of a proposition to find universal quantifiers
and existential quantifiers and add `named_binder` annotations next to
them. -/
/-- `decorations_of p` is used as a hint to `mk_decorations` to specify
that the goal should be satisfied with a proposition equivalent to `p`
with added annotations. -/
def decorations_of (p : Prop) :=
Prop
/-- In a goal of the shape `⊢ tactic.decorations_of p`, `mk_decoration` examines
the syntax of `p` and add `named_binder` around universal quantifications and
existential quantifications to improve error messages.
This tool can be used in the declaration of a function as follows:
```lean
def foo (p : Prop) (p' : tactic.decorations_of p . mk_decorations) [testable p'] : ...
```
`p` is the parameter given by the user, `p'` is an equivalent proposition where
the quantifiers are annotated with `named_binder`.
-/
end tactic
/-- Run a test suite for `p` and return true or false: should we believe that `p` holds? -/
def testable.check (p : Prop) (cfg : optParam slim_check_cfg
(slim_check_cfg.mk (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))) (bit0 (bit0 (bit1 (bit0 (bit0 (bit1 1)))))) false false
false false none false)) (p' : autoParam (tactic.decorations_of p)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.slim_check.tactic.mk_decorations")
(Lean.Name.mkStr
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "slim_check") "tactic")
"mk_decorations")
[])) [testable p'] : io PUnit :=
do
sorry
sorry
|
832f79f2cfe75e82979cefdbcbae04f4029f1a14 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /tests/lean/run/induction1.lean | e38f2a5aa6c6047a85d05aacdb46c10ebdb4b2f3 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 2,483 | lean | theorem tst0 {p q : Prop } (h : p ∨ q) : q ∨ p :=
by {
induction h;
{ apply Or.inr; assumption };
{ apply Or.inl; assumption }
}
theorem tst0' {p q : Prop } (h : p ∨ q) : q ∨ p := by
induction h
focus
apply Or.inr
assumption
focus
apply Or.inl
assumption
theorem tst1 {p q : Prop } (h : p ∨ q) : q ∨ p := by
induction h with
| inr h2 => exact Or.inl h2
| inl h1 => exact Or.inr h1
theorem tst6 {p q : Prop } (h : p ∨ q) : q ∨ p :=
by {
cases h with
| inr h2 => exact Or.inl h2
| inl h1 => exact Or.inr h1
}
theorem tst7 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] :=
by {
induction xs with
| nil => exact rfl
| cons z zs ih => exact absurd rfl (h z zs)
}
theorem tst8 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] := by {
induction xs;
exact rfl;
exact absurd rfl $ h _ _
}
theorem tst9 {α : Type} (xs : List α) (h : (a : α) → (as : List α) → xs ≠ a :: as) : xs = [] := by
cases xs with
| nil => exact rfl
| cons z zs => exact absurd rfl (h z zs)
theorem tst10 {p q : Prop } (h₁ : p ↔ q) (h₂ : p) : q := by
induction h₁ with
| intro h _ => exact h h₂
def Iff2 (m p q : Prop) := p ↔ q
theorem tst11 {p q r : Prop } (h₁ : Iff2 r p q) (h₂ : p) : q := by
induction h₁ using Iff.rec with
| intro h _ => exact h h₂
theorem tst12 {p q : Prop } (h₁ : p ∨ q) (h₂ : p ↔ q) (h₃ : p) : q := by
failIfSuccess induction h₁ using Iff.casesOn
induction h₂ using Iff.casesOn with
| intro h _ =>
exact h h₃
inductive Tree
| leaf₁
| leaf₂
| node : Tree → Tree → Tree
def Tree.isLeaf₁ : Tree → Bool
| leaf₁ => true
| _ => false
theorem tst13 (x : Tree) (h : x = Tree.leaf₁) : x.isLeaf₁ = true := by
cases x with
| leaf₁ => rfl
| _ => injection h
theorem tst14 (x : Tree) (h : x = Tree.leaf₁) : x.isLeaf₁ = true := by
induction x with
| leaf₁ => rfl
| _ => injection h
inductive Vec (α : Type) : Nat → Type
| nil : Vec α 0
| cons : (a : α) → {n : Nat} → (as : Vec α n) → Vec α (n+1)
def getHeads {α β} {n} (xs : Vec α (n+1)) (ys : Vec β (n+1)) : α × β := by
cases xs
cases ys
apply Prod.mk
repeat
traceState
assumption
done
theorem ex1 (n m o : Nat) : n = m + 0 → m = o → m = o := by
intro (h₁ : n = m) h₂
rw [← h₁, ← h₂]
assumption
|
e7dd70981b534069a4ec548fd94bb0886c2e9f98 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/Specialize.lean | b27a8c040ead7be5cc058f56a7d12b3a2cd00c26 | [
"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 | 5,079 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Basic
import Lean.Attributes
namespace Lean.Compiler
inductive SpecializeAttributeKind where
| specialize | nospecialize
deriving Inhabited, BEq
builtin_initialize nospecializeAttr : TagAttribute ←
registerTagAttribute `nospecialize "mark definition to never be specialized"
private def elabSpecArgs (declName : Name) (args : Array Syntax) : MetaM (Array Nat) := do
if args.isEmpty then return #[]
let info ← getConstInfo declName
Meta.forallTelescopeReducing info.type fun xs _ => do
let argNames ← xs.mapM fun x => x.fvarId!.getUserName
let mut result := #[]
for arg in args do
if let some idx := arg.isNatLit? then
if idx == 0 then throwErrorAt arg "invalid specialization argument index, index must be greater than 0"
let idx := idx - 1
if idx >= argNames.size then
throwErrorAt arg "invalid argument index, `{declName}` has #{argNames.size} arguments"
if result.contains idx then throwErrorAt arg "invalid specialization argument index, `{argNames[idx]!}` has already been specified as a specialization candidate"
result := result.push idx
else
let argName := arg.getId
if let some idx := argNames.getIdx? argName then
if result.contains idx then throwErrorAt arg "invalid specialization argument name `{argName}`, it has already been specified as a specialization candidate"
result := result.push idx
else
throwErrorAt arg "invalid specialization argument name `{argName}`, `{declName}` does have an argument with this name"
return result.qsort (·<·)
builtin_initialize specializeAttr : ParametricAttribute (Array Nat) ←
registerParametricAttribute {
name := `specialize
descr := "mark definition to always be specialized"
getParam := fun declName stx => do
let args := stx[1].getArgs
elabSpecArgs declName args |>.run'
}
def getSpecializationArgs? (env : Environment) (declName : Name) : Option (Array Nat) :=
specializeAttr.getParam? env declName
def hasSpecializeAttribute (env : Environment) (declName : Name) : Bool :=
getSpecializationArgs? env declName |>.isSome
def hasNospecializeAttribute (env : Environment) (declName : Name) : Bool :=
nospecializeAttr.hasTag env declName
/- TODO: the rest of the file is for the old / current code generator. We should remove it as soon as we move to the new one. -/
@[export lean_has_specialize_attribute]
partial def hasSpecializeAttributeOld (env : Environment) (n : Name) : Bool :=
match specializeAttr.getParam? env n with
| some _ => true
| none => if n.isInternal then hasSpecializeAttributeOld env n.getPrefix else false -- TODO: remove recursion after we move to new compiler
@[export lean_has_nospecialize_attribute]
partial def hasNospecializeAttributeOld (env : Environment) (n : Name) : Bool :=
nospecializeAttr.hasTag env n ||
(n.isInternal && hasNospecializeAttributeOld env n.getPrefix) -- TODO: remove recursion after we move to new compiler
inductive SpecArgKind where
| fixed
| fixedNeutral -- computationally neutral
| fixedHO -- higher order
| fixedInst -- type class instance
| other
deriving Inhabited
structure SpecInfo where
mutualDecls : List Name
argKinds : List SpecArgKind
deriving Inhabited
structure SpecState where
specInfo : SMap Name SpecInfo := {}
cache : SMap Expr Name := {}
deriving Inhabited
inductive SpecEntry where
| info (name : Name) (info : SpecInfo)
| cache (key : Expr) (fn : Name)
deriving Inhabited
namespace SpecState
def addEntry (s : SpecState) (e : SpecEntry) : SpecState :=
match e with
| SpecEntry.info name info => { s with specInfo := s.specInfo.insert name info }
| SpecEntry.cache key fn => { s with cache := s.cache.insert key fn }
def switch : SpecState → SpecState
| ⟨m₁, m₂⟩ => ⟨m₁.switch, m₂.switch⟩
end SpecState
builtin_initialize specExtension : SimplePersistentEnvExtension SpecEntry SpecState ←
registerSimplePersistentEnvExtension {
addEntryFn := SpecState.addEntry,
addImportedFn := fun es => (mkStateFromImportedEntries SpecState.addEntry {} es).switch
}
@[export lean_add_specialization_info]
def addSpecializationInfo (env : Environment) (fn : Name) (info : SpecInfo) : Environment :=
specExtension.addEntry env (SpecEntry.info fn info)
@[export lean_get_specialization_info]
def getSpecializationInfo (env : Environment) (fn : Name) : Option SpecInfo :=
(specExtension.getState env).specInfo.find? fn
@[export lean_cache_specialization]
def cacheSpecialization (env : Environment) (e : Expr) (fn : Name) : Environment :=
specExtension.addEntry env (SpecEntry.cache e fn)
@[export lean_get_cached_specialization]
def getCachedSpecialization (env : Environment) (e : Expr) : Option Name :=
(specExtension.getState env).cache.find? e
end Lean.Compiler
|
5655180985b14d007c08bb228e52189ff1f742ad | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/homology/homotopy_category.lean | d9c581898935efe0f49c789245880f4a02b9f488 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 7,567 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.homology.homotopy
import category_theory.quotient
/-!
# The homotopy category
`homotopy_category V c` gives the category of chain complexes of shape `c` in `V`,
with chain maps identified when they are homotopic.
-/
universes v u
open_locale classical
noncomputable theory
open category_theory category_theory.limits homological_complex
variables {ι : Type*}
variables (V : Type u) [category.{v} V] [preadditive V]
variables (c : complex_shape ι)
/--
The congruence on `homological_complex V c` given by the existence of a homotopy.
-/
def homotopic : hom_rel (homological_complex V c) := λ C D f g, nonempty (homotopy f g)
instance homotopy_congruence : congruence (homotopic V c) :=
{ is_equiv := λ C D,
{ refl := λ C, ⟨homotopy.refl C⟩,
symm := λ f g ⟨w⟩, ⟨w.symm⟩,
trans := λ f g h ⟨w₁⟩ ⟨w₂⟩, ⟨w₁.trans w₂⟩, },
comp_left := λ E F G m₁ m₂ g ⟨i⟩, ⟨i.comp_left _⟩,
comp_right := λ E F G f m₁ m₂ ⟨i⟩, ⟨i.comp_right _⟩, }
/-- `homotopy_category V c` is the category of chain complexes of shape `c` in `V`,
with chain maps identified when they are homotopic. -/
@[derive category]
def homotopy_category := category_theory.quotient (homotopic V c)
-- TODO the homotopy_category is preadditive
namespace homotopy_category
/-- The quotient functor from complexes to the homotopy category. -/
def quotient : homological_complex V c ⥤ homotopy_category V c :=
category_theory.quotient.functor _
open_locale zero_object
-- TODO upgrade this to `has_zero_object`, presumably for any `quotient`.
instance [has_zero_object V] : inhabited (homotopy_category V c) := ⟨(quotient V c).obj 0⟩
variables {V c}
@[simp] lemma quotient_obj_as (C : homological_complex V c) :
((quotient V c).obj C).as = C := rfl
@[simp] lemma quotient_map_out {C D : homotopy_category V c} (f : C ⟶ D) :
(quotient V c).map f.out = f :=
quot.out_eq _
lemma eq_of_homotopy {C D : homological_complex V c} (f g : C ⟶ D) (h : homotopy f g) :
(quotient V c).map f = (quotient V c).map g :=
category_theory.quotient.sound _ ⟨h⟩
/-- If two chain maps become equal in the homotopy category, then they are homotopic. -/
def homotopy_of_eq {C D : homological_complex V c} (f g : C ⟶ D)
(w : (quotient V c).map f = (quotient V c).map g) : homotopy f g :=
((quotient.functor_map_eq_iff _ _ _).mp w).some
/--
An arbitrarily chosen representation of the image of a chain map in the homotopy category
is homotopic to the original chain map.
-/
def homotopy_out_map {C D : homological_complex V c} (f : C ⟶ D) :
homotopy ((quotient V c).map f).out f :=
begin
apply homotopy_of_eq,
simp,
end
@[simp] lemma quotient_map_out_comp_out {C D E : homotopy_category V c} (f : C ⟶ D) (g : D ⟶ E) :
(quotient V c).map (quot.out f ≫ quot.out g) = f ≫ g :=
by conv_rhs { erw [←quotient_map_out f, ←quotient_map_out g, ←(quotient V c).map_comp], }
/-- Homotopy equivalent complexes become isomorphic in the homotopy category. -/
@[simps]
def iso_of_homotopy_equiv {C D : homological_complex V c} (f : homotopy_equiv C D) :
(quotient V c).obj C ≅ (quotient V c).obj D :=
{ hom := (quotient V c).map f.hom,
inv := (quotient V c).map f.inv,
hom_inv_id' := begin
rw [←(quotient V c).map_comp, ←(quotient V c).map_id],
exact eq_of_homotopy _ _ f.homotopy_hom_inv_id,
end,
inv_hom_id' := begin
rw [←(quotient V c).map_comp, ←(quotient V c).map_id],
exact eq_of_homotopy _ _ f.homotopy_inv_hom_id,
end }
/-- If two complexes become isomorphic in the homotopy category,
then they were homotopy equivalent. -/
def homotopy_equiv_of_iso
{C D : homological_complex V c} (i : (quotient V c).obj C ≅ (quotient V c).obj D) :
homotopy_equiv C D :=
{ hom := quot.out i.hom,
inv := quot.out i.inv,
homotopy_hom_inv_id := homotopy_of_eq _ _ (by { simp, refl, }),
homotopy_inv_hom_id := homotopy_of_eq _ _ (by { simp, refl, }), }
variables (V c) [has_equalizers V] [has_images V] [has_image_maps V]
[has_cokernels V]
/-- The `i`-th homology, as a functor from the homotopy category. -/
def homology_functor (i : ι) : homotopy_category V c ⥤ V :=
category_theory.quotient.lift _ (homology_functor V c i)
(λ C D f g ⟨h⟩, homology_map_eq_of_homotopy h i)
/-- The homology functor on the homotopy category is just the usual homology functor. -/
def homology_factors (i : ι) :
quotient V c ⋙ homology_functor V c i ≅ _root_.homology_functor V c i :=
category_theory.quotient.lift.is_lift _ _ _
@[simp] lemma homology_factors_hom_app (i : ι) (C : homological_complex V c) :
(homology_factors V c i).hom.app C = 𝟙 _ :=
rfl
@[simp] lemma homology_factors_inv_app (i : ι) (C : homological_complex V c) :
(homology_factors V c i).inv.app C = 𝟙 _ :=
rfl
lemma homology_functor_map_factors (i : ι) {C D : homological_complex V c} (f : C ⟶ D) :
(_root_.homology_functor V c i).map f =
((homology_functor V c i).map ((quotient V c).map f) : _) :=
(category_theory.quotient.lift_map_functor_map _ (_root_.homology_functor V c i) _ f).symm
end homotopy_category
namespace category_theory
variables {V} {W : Type*} [category W] [preadditive W]
/-- An additive functor induces a functor between homotopy categories. -/
@[simps]
def functor.map_homotopy_category (c : complex_shape ι) (F : V ⥤ W) [F.additive] :
homotopy_category V c ⥤ homotopy_category W c :=
{ obj := λ C, (homotopy_category.quotient W c).obj ((F.map_homological_complex c).obj C.as),
map := λ C D f,
(homotopy_category.quotient W c).map ((F.map_homological_complex c).map (quot.out f)),
map_id' := λ C, begin
rw ←(homotopy_category.quotient W c).map_id,
apply homotopy_category.eq_of_homotopy,
rw ←(F.map_homological_complex c).map_id,
apply F.map_homotopy,
apply homotopy_category.homotopy_of_eq,
exact quot.out_eq _,
end,
map_comp' := λ C D E f g, begin
rw ←(homotopy_category.quotient W c).map_comp,
apply homotopy_category.eq_of_homotopy,
rw ←(F.map_homological_complex c).map_comp,
apply F.map_homotopy,
apply homotopy_category.homotopy_of_eq,
convert quot.out_eq _,
exact homotopy_category.quotient_map_out_comp_out _ _,
end }.
-- TODO `F.map_homotopy_category c` is additive (and linear when `F` is linear).
/-- A natural transformation induces a natural transformation between
the induced functors on the homotopy category. -/
@[simps]
def nat_trans.map_homotopy_category {F G : V ⥤ W} [F.additive] [G.additive]
(α : F ⟶ G) (c : complex_shape ι) : F.map_homotopy_category c ⟶ G.map_homotopy_category c :=
{ app := λ C,
(homotopy_category.quotient W c).map ((nat_trans.map_homological_complex α c).app C.as),
naturality' := λ C D f,
begin
dsimp,
simp only [←functor.map_comp],
congr' 1,
ext,
dsimp,
simp,
end }
@[simp] lemma nat_trans.map_homotopy_category_id (c : complex_shape ι) (F : V ⥤ W) [F.additive] :
nat_trans.map_homotopy_category (𝟙 F) c = 𝟙 (F.map_homotopy_category c) :=
by tidy
@[simp] lemma nat_trans.map_homotopy_category_comp (c : complex_shape ι)
{F G H : V ⥤ W} [F.additive] [G.additive] [H.additive]
(α : F ⟶ G) (β : G ⟶ H):
nat_trans.map_homotopy_category (α ≫ β) c =
nat_trans.map_homotopy_category α c ≫ nat_trans.map_homotopy_category β c :=
by tidy
end category_theory
|
257ca591decfabf17b579ad2b57858db132a99fb | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/field_simp.lean | cafdbf648a60b3dc8e6c1b65b1a934b1a4866a7a | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 4,204 | 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 tactic.interactive
import tactic.norm_num
/-!
# `field_simp` tactic
Tactic to clear denominators in algebraic expressions, based on `simp` with a specific simpset.
-/
namespace tactic
/-- Try to prove a goal of the form `x ≠ 0` by calling `assumption`, or `norm_num1` if `x` is
a numeral. -/
meta def field_simp.ne_zero : tactic unit := do
goal ← tactic.target,
match goal with
| `(%%e ≠ 0) := assumption <|> do n ← e.to_rat, `[norm_num1]
| _ := tactic.fail "goal should be of the form `x ≠ 0`"
end
namespace interactive
open interactive interactive.types
/--
The goal of `field_simp` is to reduce an expression in a field to an expression of the form `n / d`
where neither `n` nor `d` contains any division symbol, just using the simplifier (with a carefully
crafted simpset named `field_simps`) to reduce the number of division symbols whenever possible by
iterating the following steps:
- write an inverse as a division
- in any product, move the division to the right
- if there are several divisions in a product, group them together at the end and write them as a
single division
- reduce a sum to a common denominator
If the goal is an equality, this simpset will also clear the denominators, so that the proof
can normally be concluded by an application of `ring` or `ring_exp`.
`field_simp [hx, hy]` is a short form for
`simp [-one_div, -mul_eq_zero, hx, hy] with field_simps {discharger := [field_simp.ne_zero]}`
Note that this naive algorithm will not try to detect common factors in denominators to reduce the
complexity of the resulting expression. Instead, it relies on the ability of `ring` to handle
complicated expressions in the next step.
As always with the simplifier, reduction steps will only be applied if the preconditions of the
lemmas can be checked. This means that proofs that denominators are nonzero should be included. The
fact that a product is nonzero when all factors are, and that a power of a nonzero number is
nonzero, are included in the simpset, but more complicated assertions (especially dealing with sums)
should be given explicitly. If your expression is not completely reduced by the simplifier
invocation, check the denominators of the resulting expression and provide proofs that they are
nonzero to enable further progress.
To check that denominators are nonzero, `field_simp` will look for facts in the context, and
will try to apply `norm_num` to close numerical goals.
The invocation of `field_simp` removes the lemma `one_div` from the simpset, as this lemma
works against the algorithm explained above. It also removes
`mul_eq_zero : x * y = 0 ↔ x = 0 ∨ y = 0`, as `norm_num` can not work on disjunctions to
close goals of the form `24 ≠ 0`, and replaces it with `mul_ne_zero : x ≠ 0 → y ≠ 0 → x * y ≠ 0`
creating two goals instead of a disjunction.
For example,
```lean
example (a b c d x y : ℂ) (hx : x ≠ 0) (hy : y ≠ 0) :
a + b / x + c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x + c) / x) :=
begin
field_simp,
ring
end
```
See also the `cancel_denoms` tactic, which tries to do a similar simplification for expressions
that have numerals in denominators.
The tactics are not related: `cancel_denoms` will only handle numeric denominators, and will try to
entirely remove (numeric) division from the expression by multiplying by a factor.
-/
meta def field_simp (no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list)
(locat : parse location)
(cfg : simp_config_ext := {discharger := field_simp.ne_zero}) : tactic unit :=
let attr_names := `field_simps :: attr_names,
hs := simp_arg_type.except `one_div :: simp_arg_type.except `mul_eq_zero :: hs in
propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat >> skip)
add_tactic_doc
{ name := "field_simp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.field_simp],
tags := ["simplification", "arithmetic"] }
end interactive
end tactic
|
01bacad8d1ca00cd3c3706c2c5c9438f4f33e762 | c65da2ef2a10991ca5f329be68b231f8f5aed210 | /src/solutions/friday/topology.lean | 00894212c74af9ff5a691fc411658efa24f8fe45 | [] | no_license | arademaker/lftcm2020 | 5d6aa964837cfea82a98d32b6e2a0b9a6c97dfdc | e83aab9d2c514c4fccfb6d6043200f1bdc7b3841 | refs/heads/master | 1,672,633,876,208 | 1,602,728,317,000 | 1,602,728,317,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,731 | lean | import topology.metric_space.basic
open_locale classical filter topological_space
namespace lftcm
open filter set
/-!
# Filters
## Definition of filters
-/
def principal {α : Type*} (s : set α) : filter α :=
{ sets := {t | s ⊆ t},
univ_sets := begin
-- sorry
tauto,
-- sorry
end,
sets_of_superset := begin
-- sorry
intros U V hU hUV,
tauto,
-- sorry
end,
inter_sets := begin
-- sorry
rintros U V hU hV,
intros x xs,
split ; tauto,
-- sorry
end}
def at_top : filter ℕ :=
{ sets := {s | ∃ a, ∀ b, a ≤ b → b ∈ s},
univ_sets := begin
-- sorry
use 42,
finish,
-- sorry
end,
sets_of_superset := begin
-- sorry
rintros U V ⟨N, hN⟩ hUV,
use N,
tauto,
-- sorry
end,
inter_sets := begin
-- sorry
rintros U V ⟨N, hN⟩ ⟨N', hN'⟩,
use max N N',
intros b hb,
rw max_le_iff at hb,
split ; tauto,
-- sorry
end}
-- The next exercise is slightly more tricky, you should probably keep it for later
def nhds (x : ℝ) : filter ℝ :=
{ sets := {s | ∃ ε > 0, Ioo (x - ε) (x + ε) ⊆ s},
univ_sets := begin
-- sorry
use 42⁻¹,
split,
norm_num,
tauto,
-- sorry
end,
sets_of_superset := begin
-- sorry
rintros U V ⟨ε, hε⟩ hUV,
use ε,
tauto,
-- sorry
end,
inter_sets := begin
-- sorry
rintros U V ⟨ε, hε, hU⟩ ⟨ε', hε', hV⟩,
use [min ε ε', lt_min hε hε'],
intros b hb,
rw mem_Ioo at hb,
split,
{ apply hU,
split ; linarith [min_le_left ε ε'] },
{ apply hV,
split ; linarith [min_le_right ε ε'] },
-- sorry
end}
/-
The filter axiom are also available as standalone lemmas where the filter argument is implicit
Compare
-/
#check @filter.sets_of_superset
#check @mem_sets_of_superset
-- And analogously:
#check @inter_mem_sets
/-!
## Definition of "tends to"
-/
-- We'll practive using tendsto by reproving the composition lemma `tendsto.comp` from mathlib
-- Let's first use the concrete definition recorded by `tendsto_def`
#check @tendsto_def
#check @preimage_comp
example {α β γ : Type*} {A : filter α} {B : filter β} {C : filter γ} {f : α → β} {g : β → γ}
(hf : tendsto f A B) (hg : tendsto g B C) : tendsto (g ∘ f) A C :=
begin
-- sorry
rw tendsto_def at *,
intros U U_in,
rw preimage_comp,
apply hf,
apply hg,
assumption,
-- sorry
end
-- Now let's get functorial (same statement as above, different proof packaging).
example {α β γ : Type*} {A : filter α} {B : filter β} {C : filter γ} {f : α → β} {g : β → γ}
(hf : tendsto f A B) (hg : tendsto g B C) : tendsto (g ∘ f) A C :=
begin
calc
map (g ∘ f) A = map g (map f A) : /- inline sorry -/ map_map/- inline sorry -/
... ≤ map g B : /- inline sorry -/map_mono hf/- inline sorry -/
... ≤ C : /- inline sorry -/hg/- inline sorry -/,
end
/-
Let's now focus on the pull-back operation `filter.comap` which takes `f : X → Y`
and a filter `G` on `Y` and returns a filter on `X`.
-/
#check @mem_comap_sets -- this is by definition, the proof is `iff.rfl`
-- It also help to record a special case of one implication:
#check @preimage_mem_comap
-- The following exercise, which reproves `comap_ne_bot_iff` can start using
#check @forall_sets_nonempty_iff_ne_bot
example {α β : Type*} {f : filter β} {m : α → β} :
(comap m f).ne_bot ↔ ∀ t ∈ f, ∃ a, m a ∈ t :=
begin
-- sorry
rw ← forall_sets_nonempty_iff_ne_bot,
split ; intro h,
{ intros t t_in,
exact h (m ⁻¹' t) ⟨t, t_in, subset.refl _⟩, },
{ rintros s ⟨u, u_in, hu⟩,
cases h u u_in with x hx,
exact ⟨x, hu hx⟩ },
-- sorry
end
/-!
## Properties holding eventually
-/
/--
The next exercise only needs the definition of filters and the fact that
`∀ᶠ x in f, p x` is a notation for `{x | p x} ∈ f`.
It is called `eventually_and` in mathlib, and won't be needed below.
For instance, applied to `α = ℕ` and the `at_top` filter above, it says
that, given two predicates `p` and `q` on natural numbers,
p n and q n for n large enough if and only if p n holds for n large enough
and q n holds for n large enough.
-/
example {α : Type*} {p q : α → Prop} {f : filter α} :
(∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) :=
begin
-- sorry
split,
{ intro h,
split,
{ apply mem_sets_of_superset h,
intros x x_in,
exact x_in.1 },
{ apply mem_sets_of_superset h,
intros x x_in,
exact x_in.2 } },
{ intros h,
exact f.inter_sets h.1 h.2, },
-- sorry
end
/-!
## Topological spaces
-/
section
-- This is how we can talk about two topological spaces X and Y
variables {X Y : Type*} [topological_space X] [topological_space Y]
/-
Given a topological space `X` and some `A : set X`, we have the usual zoo of predicates
`is_open A`, `is_closed A`, `is_connected A`, `is_compact A` (and some more)
There are also additional type classes referring to properties of `X` itself,
like `compact_space X` or `connected_space X`
-/
/-- We can talk about continuous functions from `X` to `Y` -/
example (f : X → Y) : continuous f ↔ ∀ V, is_open V → is_open (f ⁻¹' V) := iff.rfl
/- Each point `x` of a topological space has a neighborhood filter `𝓝 x`
made of sets containing an open set containing `x`.
It is always a proper filter, as recorded by `nhds_ne_bot`
Asking for continuity is the same as asking for continuity at each point
the right-hand side below is known as `continuous_at f x` -/
example (f : X → Y) : continuous f ↔ ∀ x, tendsto f (𝓝 x) (𝓝 (f x)) := continuous_iff_continuous_at
/- The topological structure also brings operations on sets.
To each `A : set X`, we can associate `closure A`, `interior A` and `frontier A`.
We'll focus on `closure A`. It is defined as the intersection of closed sets containing `A`
but we can characterize it in terms of neighborhoods. The most concrete version is
`mem_closure_iff_nhds : a ∈ closure A ↔ ∀ B ∈ 𝓝 a, (B ∩ A).nonempty`
We'll pratice by reproving the slightly more abstract `mem_closure_iff_comap_ne_bot`.
First let's review sets and subtypes. Fix a type `X` and recall
that `A : set X` is not a type a priori, but Lean coerces automatically when needed to the
type `↥A` whose terms are build of a term `x : X` and a proof of `x ∈ A`.
In the other direction, inhabitants of `↥A` can be coerced to `X` automatically.
This inclusion coercion map is called `coe : A → X` and `coe a` is also denoted by `↑a`.
Now assume `X` is a topological space, and let's understand the closure of A in terms
of `coe` and the neighborhood filter.
In the next exercise, you can use `simp_rw` instead of `rw` to rewrite inside a quantifier
-/
#check nonempty_inter_iff_exists_right
example {A : set X} {x : X} :
x ∈ closure A ↔ (comap (coe : A → X) (𝓝 x)).ne_bot :=
begin
-- sorry
simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, nonempty_inter_iff_exists_right],
-- sorry
end
/-
In elementary contexts, the main property of `closure A` is that a converging sequence
`u : ℕ → X` such that `∀ n, u n ∈ A` has its limit in `closure A`.
Note we don't need all the full sequence to be in
`A`, it's enough to ask it for `n` large enough, ie. `∀ᶠ n in at_top, u n ∈ A`.
Also there is no reason to use sequences only, we can use any map and any source filter.
We hence have the important
`mem_closure_of_tendsto` : ∀ {f : β → X} {F : filter β} {a : X}
{A : set X}, F ≠ ⊥ → tendsto f F (𝓝 a) → (∀ᶠ x in F, f x ∈ A) → a ∈ closure A
If `A` is known to be closed then we can replace `closure A` by `A`, this is
`is_closed.mem_of_tendsto`.
-/
/-
We need one last piece of filter technology: bases. By definition, each neighborhood of a point
`x` contains an *open* neighborhood of `x`.
Hence we can often restrict our attention to such neighborhoods.
The general definition recording such a situation is:
`has_basis` (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop :=
(mem_iff' : ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t)
You can now inspect three examples of how bases allow to restrict attention to certain elements
of a filter.
-/
#check @has_basis.mem_iff
#check @has_basis.tendsto_left_iff
#check @has_basis.tendsto_right_iff
-- We'll use the following bases:
#check @nhds_basis_opens'
#check @closed_nhds_basis
/--
Our main goal is now to prove the basic theorem which allows extension by continuity.
From Bourbaki's general topology book, I.8.5, Theorem 1 (taking only the non-trivial implication):
Let `X` be a topological space, `A` a dense subset of `X`, `f : A → Y` a mapping of `A` into a
regular space `Y`. If, for each `x` in `X`, `f(y)` tends to a limit in `Y` when `y` tends to `x`
while remaining in `A` then there exists a continuous extension `φ` of `f` to `X`.
The regularity assumption on `Y` ensures that each point of `Y` has a basis of *closed*
neighborhoods, this is `closed_nhds_basis`.
It also ensures that `Y` is Hausdorff so limits in `Y` are unique, this is `tendsto_nhds_unique`.
mathlib contains a refinement of the above lemma, `dense_inducing.continuous_at_extend`,
but we'll stick to Bourbaki's version here.
Remember that, given `A : set X`, `↥A` is the subtype associated to `A`, and Lean will automatically
insert that funny up arrow when needed. And the (inclusion) coercion map is `coe : A → X`.
The assumption "tends to `x` while remaining in `A`" corresponds to the pull-back filter
`comap coe (𝓝 x)`.
Let's prove first an auxilliary lemma, extracted to simplify the context
(in particular we don't need Y to be a topological space here).
-/
lemma aux {X Y A : Type*} [topological_space X] {c : A → X} {f : A → Y} {x : X} {F : filter Y}
(h : tendsto f (comap c (𝓝 x)) F) {V' : set Y} (V'_in : V' ∈ F) :
∃ V ∈ 𝓝 x, is_open V ∧ c ⁻¹' V ⊆ f ⁻¹' V' :=
begin
-- sorry
simpa [and_assoc] using ((nhds_basis_opens' x).comap c).tendsto_left_iff.mp h V' V'_in
-- sorry
end
/--
Let's now turn to the main proof of the extension by continuity theorem.
When Lean needs a topology on `↥A` it will use the induced topology, thanks to the instance
`subtype.topological_space`.
This all happens automatically. The only relevant lemma is
`nhds_induced coe : ∀ a : ↥A, 𝓝 a = comap coe (𝓝 ↑a)`
(this is actually a general lemma about induced topologies).
The proof outline is:
The main assumption and the axiom of choice give a function `φ` such that
`∀ x, tendsto f (comap coe $ 𝓝 x) (𝓝 (φ x))`
(because `Y` is Hausdorff, `φ` is entirely determined, but we won't need that until we try to
prove that `φ` indeed extends `f`).
Let's first prove `φ` is continuous. Fix any `x : X`.
Since `Y` is regular, it suffices to check that for every *closed* neighborhood
`V'` of `φ x`, `φ ⁻¹' V' ∈ 𝓝 x`.
The limit assumption gives (through the auxilliary lemma above)
some `V ∈ 𝓝 x` such `is_open V ∧ coe ⁻¹' V ⊆ f ⁻¹' V'`.
Since `V ∈ 𝓝 x`, it suffices to prove `V ⊆ φ ⁻¹' V'`, ie `∀ y ∈ V, φ y ∈ V'`.
Let's fix `y` in `V`. Because `V` is *open*, it is a neighborhood of `y`.
In particular `coe ⁻¹' V ∈ comap coe (𝓝 y)` and a fortiori `f ⁻¹' V' ∈ comap coe (𝓝 y)`.
In addition `comap coe $ 𝓝 y ≠ ⊥` because `A` is dense.
Because we know `tendsto f (comap coe $ 𝓝 y) (𝓝 (φ y))` this implies
`φ y ∈ closure V'` and, since `V'` is closed, we have proved `φ y ∈ V'`.
It remains to prove that `φ` extends `f`. This is were continuity of `f` enters the discussion,
together with the fact that `Y` is Hausdorff.
-/
example [regular_space Y] {A : set X} (hA : ∀ x, x ∈ closure A)
{f : A → Y} (f_cont : continuous f)
(hf : ∀ x : X, ∃ c : Y, tendsto f (comap coe $ 𝓝 x) $ 𝓝 c) :
∃ φ : X → Y, continuous φ ∧ ∀ a : A, φ a = f a :=
begin
-- sorry
choose φ hφ using hf,
use φ,
split,
{ rw continuous_iff_continuous_at,
intros x,
suffices : ∀ V' ∈ 𝓝 (φ x), is_closed V' → φ ⁻¹' V' ∈ 𝓝 x,
by simpa [continuous_at, (closed_nhds_basis _).tendsto_right_iff],
intros V' V'_in V'_closed,
obtain ⟨V, V_in, V_op, hV⟩ : ∃ V ∈ 𝓝 x, is_open V ∧ coe ⁻¹' V ⊆ f ⁻¹' V',
{ exact aux (hφ x) V'_in },
suffices : ∀ y ∈ V, φ y ∈ V',
from mem_sets_of_superset V_in this,
intros y y_in,
have hVx : V ∈ 𝓝 y := mem_nhds_sets V_op y_in,
haveI : (comap (coe : A → X) (𝓝 y)).ne_bot := by simpa [mem_closure_iff_comap_ne_bot] using hA y,
apply is_closed.mem_of_tendsto V'_closed (hφ y),
exact mem_sets_of_superset (preimage_mem_comap hVx) hV },
{ intros a,
have lim : tendsto f (𝓝 a) (𝓝 $ φ a),
by simpa [nhds_induced] using hφ a,
exact tendsto_nhds_unique lim f_cont.continuous_at },
-- sorry
end
end
/-!
## Metric spaces
-/
/--
We now leave general topology and turn to metric spaces. The distance function is denoted by `dist`.
A slight difficulty here is that, as in Bourbaki, many results you may expect
to see stated for metric spaces are stated for uniform spaces, a more general notion that also
includes topological groups. In this tutorial we will avoid uniform spaces for simplicity.
We will prove that continuous functions from a compact metric space to a
metric space are uniformly continuous. mathlib has a much more general
version (about functions between uniform spaces...).
The lemma `metric.uniform_continuous_iff` allows to translate the general definition
of uniform continuity to the ε-δ definition that works for metric spaces only.
So let's fix `ε > 0` and start looking for `δ`.
We will deduce Heine-Cantor from the fact that a real value continuous function
on a nonempty compact set reaches its infimum. There are several ways to state that,
but here we recommend `is_compact.exists_forall_le`.
Let `φ : X × X → ℝ := λ p, dist (f p.1) (f p.2)` and let `K := { p : X × X | ε ≤ φ p }`.
Observe `φ` is continuous by assumption on `f` and using `continuous_dist`.
And `K` is closed using `is_closed_le` hence compact since `X` is compact.
Then we discuss two possibilities using `eq_empty_or_nonempty`.
If `K` is empty then we are clearly done (we can set `δ = 1` for instance).
So let's assume `K` is not empty, and choose `(x₀, x₁)` attaining the infimum
of `φ` on `K`. We can then set `δ = dist x₀ x₁` and check everything works.
-/
example {X : Type*} [metric_space X] [compact_space X] {Y : Type*} [metric_space Y]
{f : X → Y} (hf : continuous f) : uniform_continuous f :=
begin
-- sorry
rw metric.uniform_continuous_iff,
intros ε ε_pos,
let φ : X × X → ℝ := λ p, dist (f p.1) (f p.2),
have φ_cont : continuous φ := continuous_dist.comp (hf.prod_map hf),
let K := { p : X × X | ε ≤ φ p },
have K_closed : is_closed K := is_closed_le continuous_const φ_cont,
have K_cpct : is_compact K := K_closed.compact,
cases eq_empty_or_nonempty K with hK hK,
{ use [1, by norm_num],
intros x y hxy,
have : (x, y) ∉ K, by simp [hK],
simpa [K] },
{ rcases K_cpct.exists_forall_le hK continuous_dist.continuous_on with ⟨⟨x₀, x₁⟩, xx_in, H⟩,
use dist x₀ x₁,
split,
{ change _ < _,
rw dist_pos,
intro h,
have : ε ≤ 0, by simpa [*] using xx_in,
linarith },
{ intros x x',
contrapose!,
intros hxx',
linarith [H (x, x') hxx'] } },
-- sorry
end
end lftcm
|
ca71b103813bf9f95e00b288beb696dfcee4c3e6 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/localization/integer.lean | aee8886cdb5c60041b81305eb837328ddf6f3ac7 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 5,367 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen
-/
import ring_theory.localization.basic
/-!
# Integer elements of a localization
## Main definitions
* `is_localization.is_integer` is a predicate stating that `x : S` is in the image of `R`
## Implementation notes
See `src/ring_theory/localization/basic.lean` for a design overview.
## Tags
localization, ring localization, commutative ring localization, characteristic predicate,
commutative ring, field of fractions
-/
variables {R : Type*} [comm_ring R] {M : submonoid R} {S : Type*} [comm_ring S]
variables [algebra R S] {P : Type*} [comm_ring P]
open function
open_locale big_operators
namespace is_localization
section
variables (R) {M S}
-- TODO: define a subalgebra of `is_integer`s
/-- Given `a : S`, `S` a localization of `R`, `is_integer R a` iff `a` is in the image of
the localization map from `R` to `S`. -/
def is_integer (a : S) : Prop := a ∈ (algebra_map R S).range
end
lemma is_integer_zero : is_integer R (0 : S) := subring.zero_mem _
lemma is_integer_one : is_integer R (1 : S) := subring.one_mem _
lemma is_integer_add {a b : S} (ha : is_integer R a) (hb : is_integer R b) :
is_integer R (a + b) :=
subring.add_mem _ ha hb
lemma is_integer_mul {a b : S} (ha : is_integer R a) (hb : is_integer R b) :
is_integer R (a * b) :=
subring.mul_mem _ ha hb
lemma is_integer_smul {a : R} {b : S} (hb : is_integer R b) :
is_integer R (a • b) :=
begin
rcases hb with ⟨b', hb⟩,
use a * b',
rw [←hb, (algebra_map R S).map_mul, algebra.smul_def]
end
variables (M) {S} [is_localization M S]
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the right, matching the argument order in `localization_map.surj`.
-/
lemma exists_integer_multiple' (a : S) :
∃ (b : M), is_integer R (a * algebra_map R S b) :=
let ⟨⟨num, denom⟩, h⟩ := is_localization.surj _ a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩
/-- Each element `a : S` has an `M`-multiple which is an integer.
This version multiplies `a` on the left, matching the argument order in the `has_scalar` instance.
-/
lemma exists_integer_multiple (a : S) :
∃ (b : M), is_integer R ((b : R) • a) :=
by { simp_rw [algebra.smul_def, mul_comm _ a], apply exists_integer_multiple' }
/-- We can clear the denominators of a `finset`-indexed family of fractions. -/
lemma exist_integer_multiples {ι : Type*} (s : finset ι) (f : ι → S) :
∃ (b : M), ∀ i ∈ s, is_localization.is_integer R ((b : R) • f i) :=
begin
haveI := classical.prop_decidable,
refine ⟨∏ i in s, (sec M (f i)).2, λ i hi, ⟨_, _⟩⟩,
{ exact (∏ j in s.erase i, (sec M (f j)).2) * (sec M (f i)).1 },
rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←(algebra_map R S).map_mul, ← algebra.smul_def],
congr' 2,
refine trans _ ((submonoid.subtype M).map_prod _ _).symm,
rw [mul_comm, ←finset.prod_insert (s.not_mem_erase i), finset.insert_erase hi],
refl
end
/-- We can clear the denominators of a `fintype`-indexed family of fractions. -/
lemma exist_integer_multiples_of_fintype {ι : Type*} [fintype ι] (f : ι → S) :
∃ (b : M), ∀ i, is_localization.is_integer R ((b : R) • f i) :=
begin
obtain ⟨b, hb⟩ := exist_integer_multiples M finset.univ f,
exact ⟨b, λ i, hb i (finset.mem_univ _)⟩
end
/-- We can clear the denominators of a finite set of fractions. -/
lemma exist_integer_multiples_of_finset (s : finset S) :
∃ (b : M), ∀ a ∈ s, is_integer R ((b : R) • a) :=
exist_integer_multiples M s id
/-- A choice of a common multiple of the denominators of a `finset`-indexed family of fractions. -/
noncomputable
def common_denom {ι : Type*} (s : finset ι) (f : ι → S) : M :=
(exist_integer_multiples M s f).some
/-- The numerator of a fraction after clearing the denominators
of a `finset`-indexed family of fractions. -/
noncomputable
def integer_multiple {ι : Type*} (s : finset ι) (f : ι → S) (i : s) : R :=
((exist_integer_multiples M s f).some_spec i i.prop).some
@[simp]
lemma map_integer_multiple {ι : Type*} (s : finset ι) (f : ι → S) (i : s) :
algebra_map R S (integer_multiple M s f i) = common_denom M s f • f i :=
((exist_integer_multiples M s f).some_spec _ i.prop).some_spec
/-- A choice of a common multiple of the denominators of a finite set of fractions. -/
noncomputable
def common_denom_of_finset (s : finset S) : M :=
common_denom M s id
/-- The finset of numerators after clearing the denominators of a finite set of fractions. -/
noncomputable
def finset_integer_multiple [decidable_eq R] (s : finset S) : finset R :=
s.attach.image (λ t, integer_multiple M s id t)
open_locale pointwise
lemma finset_integer_multiple_image [decidable_eq R] (s : finset S) :
algebra_map R S '' (finset_integer_multiple M s) =
common_denom_of_finset M s • s :=
begin
delta finset_integer_multiple common_denom,
rw finset.coe_image,
ext,
split,
{ rintro ⟨_, ⟨x, -, rfl⟩, rfl⟩,
rw map_integer_multiple,
exact set.mem_image_of_mem _ x.prop },
{ rintro ⟨x, hx, rfl⟩,
exact ⟨_, ⟨⟨x, hx⟩, s.mem_attach _, rfl⟩, map_integer_multiple M s id _⟩ }
end
end is_localization
|
8cf3aaee93e3f193d71d9ab10b2bfef23319a925 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/LCNF/JoinPoints.lean | 6acbb730affd7755815a104572d2979821f31786 | [
"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 | 22,459 | lean | /-
Copyright (c) 2022 Henrik Böving. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Henrik Böving
-/
import Lean.Compiler.LCNF.CompilerM
import Lean.Compiler.LCNF.PassManager
import Lean.Compiler.LCNF.PullFunDecls
import Lean.Compiler.LCNF.FVarUtil
import Lean.Compiler.LCNF.ScopeM
import Lean.Compiler.LCNF.InferType
namespace Lean.Compiler.LCNF
namespace JoinPointFinder
open ScopeM
/--
Info about a join point candidate (a `fun` declaration) during the find phase.
-/
structure CandidateInfo where
/--
The arity of the candidate
-/
arity : Nat
/--
The set of candidates that rely on this candidate to be a join point.
For a more detailed explanation see the documentation of `find`
-/
associated : HashSet FVarId
deriving Inhabited
/--
The state for the join point candidate finder.
-/
structure FindState where
/--
All current join point candidates accessible by their `FVarId`.
-/
candidates : HashMap FVarId CandidateInfo := .empty
/--
The `FVarId`s of all `fun` declarations that were declared within the
current `fun`.
-/
scope : HashSet FVarId := .empty
abbrev ReplaceCtx := HashMap FVarId Name
abbrev FindM := ReaderT (Option FVarId) StateRefT FindState ScopeM
abbrev ReplaceM := ReaderT ReplaceCtx CompilerM
/--
Attempt to find a join point candidate by its `FVarId`.
-/
private def findCandidate? (fvarId : FVarId) : FindM (Option CandidateInfo) := do
return (← get).candidates.find? fvarId
/--
Erase a join point candidate as well as all the ones that depend on it
by its `FVarId`, no error is thrown is the candidate does not exist.
-/
private partial def eraseCandidate (fvarId : FVarId) : FindM Unit := do
if let some info ← findCandidate? fvarId then
modify (fun state => { state with candidates := state.candidates.erase fvarId })
info.associated.forM eraseCandidate
/--
Combinator for modifying the candidates in `FindM`.
-/
private def modifyCandidates (f : HashMap FVarId CandidateInfo → HashMap FVarId CandidateInfo) : FindM Unit :=
modify (fun state => {state with candidates := f state.candidates })
/--
Remove all join point candidates contained in `a`.
-/
private partial def removeCandidatesInArg (a : Arg) : FindM Unit := do
forFVarM eraseCandidate a
/--
Remove all join point candidates contained in `a`.
-/
private partial def removeCandidatesInLetValue (e : LetValue) : FindM Unit := do
forFVarM eraseCandidate e
/--
Add a new join point candidate to the state.
-/
private def addCandidate (fvarId : FVarId) (arity : Nat) : FindM Unit := do
let cinfo := { arity, associated := .empty }
modifyCandidates (fun cs => cs.insert fvarId cinfo )
/--
Add a new join point dependency from `src` to `dst`.
-/
private def addDependency (src : FVarId) (target : FVarId) : FindM Unit := do
if let some targetInfo ← findCandidate? target then
modifyCandidates (fun cs => cs.insert target { targetInfo with associated := targetInfo.associated.insert src })
else
eraseCandidate src
/--
Find all `fun` declarations that qualify as a join point, that is:
- are always fully applied
- are always called in tail position
Where a `fun` `f` is in tail position iff it is called as follows:
```
let res := f arg
res
```
The majority (if not all) tail calls will be brought into this form
by the simplifier pass.
Furthermore a `fun` disqualifies as a join point if turning it into a join
point would turn a call to it into an out of scope join point.
This can happen if we have something like:
```
def test (b : Bool) (x y : Nat) : Nat :=
fun myjp x => Nat.add x (Nat.add x x)
fun f y =>
let x := Nat.add y y
myjp x
fun f y =>
let x := Nat.mul y y
myjp x
cases b (f x) (g y)
```
`f` and `g` can be detected as a join point right away, however
`myjp` can only ever be detected as a join point after we have established
this. This is because otherwise the calls to `myjp` in `f` and `g` would
produce out of scope join point jumps.
-/
partial def find (decl : Decl) : CompilerM FindState := do
let (_, candidates) ← go decl.value |>.run none |>.run {} |>.run' {}
return candidates
where
go : Code → FindM Unit
| .let decl k => do
match k, decl.value with
| .return valId, .fvar fvarId args =>
args.forM removeCandidatesInArg
if let some candidateInfo ← findCandidate? fvarId then
-- Erase candidate that are not fully applied or applied outside of tail position
if valId != decl.fvarId || args.size != candidateInfo.arity then
eraseCandidate fvarId
-- Out of scope join point candidate handling
else if let some upperCandidate ← read then
if !(← isInScope fvarId) then
addDependency fvarId upperCandidate
else
eraseCandidate fvarId
| _, _ =>
removeCandidatesInLetValue decl.value
go k
| .fun decl k => do
withReader (fun _ => some decl.fvarId) do
withNewScope do
go decl.value
addCandidate decl.fvarId decl.getArity
addToScope decl.fvarId
go k
| .jp decl k => do
go decl.value
go k
| .jmp _ args => args.forM removeCandidatesInArg
| .return val => eraseCandidate val
| .cases c => do
eraseCandidate c.discr
c.alts.forM (·.forCodeM go)
| .unreach .. => return ()
/--
Replace all join point candidate `fun` declarations with `jp` ones
and all calls to them with `jmp`s.
-/
partial def replace (decl : Decl) (state : FindState) : CompilerM Decl := do
let mapper := fun acc cname _ => do return acc.insert cname (← mkFreshJpName)
let replaceCtx : ReplaceCtx ← state.candidates.foldM (init := .empty) mapper
let newValue ← go decl.value |>.run replaceCtx
return { decl with value := newValue }
where
go (code : Code) : ReplaceM Code := do
match code with
| .let decl k =>
match k, decl.value with
| .return valId, .fvar fvarId args =>
if valId == decl.fvarId then
if (← read).contains fvarId then
eraseLetDecl decl
return .jmp fvarId args
else
return code
else
return code
| _, _ => return Code.updateLet! code decl (← go k)
| .fun decl k =>
if let some replacement := (← read).find? decl.fvarId then
let newDecl := { decl with
binderName := replacement,
value := (← go decl.value)
}
modifyLCtx fun lctx => lctx.addFunDecl newDecl
return .jp newDecl (← go k)
else
let newDecl ← decl.updateValue (← go decl.value)
return Code.updateFun! code newDecl (← go k)
| .jp decl k =>
let newDecl ← decl.updateValue (← go decl.value)
return Code.updateFun! code newDecl (← go k)
| .cases cs =>
return Code.updateCases! code cs.resultType cs.discr (← cs.alts.mapM (·.mapCodeM go))
| .jmp .. | .return .. | .unreach .. =>
return code
end JoinPointFinder
namespace JoinPointContextExtender
open ScopeM
/--
The context managed by `ExtendM`.
-/
structure ExtendContext where
/--
The `FVarId` of the current join point if we are currently inside one.
-/
currentJp? : Option FVarId := none
/--
The list of valid candidates for extending the context. This will be
all `let` and `fun` declarations as well as all `jp` parameters up
until the last `fun` declaration in the tree.
-/
candidates : FVarIdSet := {}
/--
The state managed by `ExtendM`.
-/
structure ExtendState where
/--
A map from join point `FVarId`s to a respective map from free variables
to `Param`s. The free variables in this map are the once that the context
of said join point will be extended by by passing in the respective parameter.
-/
fvarMap : HashMap FVarId (HashMap FVarId Param) := {}
/--
The monad for the `extendJoinPointContext` pass.
-/
abbrev ExtendM := ReaderT ExtendContext StateRefT ExtendState ScopeM
/--
Replace a free variable if necessary, that is:
- It is in the list of candidates
- We are currently within a join point (if we are within a function there
cannot be a need to replace them since we dont extend their context)
- Said join point actually has a replacement parameter registered.
otherwise just return `fvar`.
-/
def replaceFVar (fvar : FVarId) : ExtendM FVarId := do
if (← read).candidates.contains fvar then
if let some currentJp := (← read).currentJp? then
if let some replacement := (← get).fvarMap.find! currentJp |>.find? fvar then
return replacement.fvarId
return fvar
/--
Add a new candidate to the current scope + to the list of candidates
if we are currently within a join point. Then execute `x`.
-/
def withNewCandidate (fvar : FVarId) (x : ExtendM α) : ExtendM α := do
addToScope fvar
if (← read).currentJp?.isSome then
withReader (fun ctx => { ctx with candidates := ctx.candidates.insert fvar }) do
x
else
x
/--
Same as `withNewCandidate` but with multiple `FVarId`s.
-/
def withNewCandidates (fvars : Array FVarId) (x : ExtendM α) : ExtendM α := do
if (← read).currentJp?.isSome then
let candidates := (← read).candidates
let folder (acc : FVarIdSet) (val : FVarId) := do
addToScope val
return acc.insert val
let newCandidates ← fvars.foldlM (init := candidates) folder
withReader (fun ctx => { ctx with candidates := newCandidates }) do
x
else
x
/--
Extend the context of the current join point (if we are within one)
by `fvar` if necessary.
This is necessary if:
- `fvar` is not in scope (that is, was declared outside of the current jp)
- we have not already extended the context by `fvar`
- the list of candidates contains `fvar`. This is because if we have something
like:
```
let x := ..
fun f a =>
jp j b =>
let y := x
y
```
There is no point in extending the context of `j` by `x` because we
cannot lift a join point outside of a local function declaration.
-/
def extendByIfNecessary (fvar : FVarId) : ExtendM Unit := do
if let some currentJp := (← read).currentJp? then
let mut translator := (← get).fvarMap.find! currentJp
let candidates := (← read).candidates
if !(← isInScope fvar) && !translator.contains fvar && candidates.contains fvar then
let typ ← getType fvar
let newParam ← mkAuxParam typ
translator := translator.insert fvar newParam
modify fun s => { s with fvarMap := s.fvarMap.insert currentJp translator }
/--
Merge the extended context of two join points if necessary. That is
if we have a structure such as:
```
jp j.1 ... =>
jp j.2 .. =>
...
...
```
And we are just done visiting `j.2` we want to extend the context of
`j.1` by all free variables that the context of `j.2` was extended by
as well because we need to drag these variables through at the call sites
of `j.2` in `j.1`.
-/
def mergeJpContextIfNecessary (jp : FVarId) : ExtendM Unit := do
if (← read).currentJp?.isSome then
let additionalArgs := (← get).fvarMap.find! jp |>.toArray
for (fvar, _) in additionalArgs do
extendByIfNecessary fvar
/--
We call this whenever we enter a new local function. It clears both the
current join point and the list of candidates since we cant lift join
points outside of functions as explained in `mergeJpContextIfNecessary`.
-/
def withNewFunScope (decl : FunDecl) (x : ExtendM α): ExtendM α := do
withReader (fun ctx => { ctx with currentJp? := none, candidates := {} }) do
withNewScope do
x
/--
We call this whenever we enter a new join point. It will set the current
join point and extend the list of candidates by all of the parameters of
the join point. This is so in the case of nested join points that refer
to parameters of the current one we extend the context of the nested
join points by said parameters.
-/
def withNewJpScope (decl : FunDecl) (x : ExtendM α): ExtendM α := do
withReader (fun ctx => { ctx with currentJp? := some decl.fvarId }) do
modify fun s => { s with fvarMap := s.fvarMap.insert decl.fvarId {} }
withNewScope do
withNewCandidates (decl.params.map (·.fvarId)) do
x
/--
We call this whenever we visit a new arm of a cases statement.
It will back up the current scope (since we are doing a case split
and want to continue with other arms afterwards) and add all of the
parameters of the match arm to the list of candidates.
-/
def withNewAltScope (alt : Alt) (x : ExtendM α) : ExtendM α := do
withBackTrackingScope do
withNewCandidates (alt.getParams.map (·.fvarId)) do
x
/--
Use all of the above functions to find free variables declared outside
of join points that said join points can be reasonaly extended by. Reasonable
meaning that in case the current join point is nested within a function
declaration we will not extend it by free variables declared before the
function declaration because we cannot lift join points outside of function
declarations.
All of this is done to eliminate dependencies of join points onto their
position within the code so we can pull them out as far as possible, hopefully
enabling new inlining possibilities in the next simplifier run.
-/
partial def extend (decl : Decl) : CompilerM Decl := do
let newValue ← go decl.value |>.run {} |>.run' {} |>.run' {}
let decl := { decl with value := newValue }
decl.pullFunDecls
where
goFVar (fvar : FVarId) : ExtendM FVarId := do
extendByIfNecessary fvar
replaceFVar fvar
go (code : Code) : ExtendM Code := do
match code with
| .let decl k =>
let decl ← decl.updateValue (← mapFVarM goFVar decl.value)
withNewCandidate decl.fvarId do
return Code.updateLet! code decl (← go k)
| .jp decl k =>
let decl ← withNewJpScope decl do
let value ← go decl.value
let additionalParams := (← get).fvarMap.find! decl.fvarId |>.toArray |>.map Prod.snd
let newType := additionalParams.foldr (init := decl.type) (fun val acc => .forallE val.binderName val.type acc .default)
decl.update newType (additionalParams ++ decl.params) value
mergeJpContextIfNecessary decl.fvarId
withNewCandidate decl.fvarId do
return Code.updateFun! code decl (← go k)
| .fun decl k =>
let decl ← withNewFunScope decl do
decl.updateValue (← go decl.value)
withNewCandidate decl.fvarId do
return Code.updateFun! code decl (← go k)
| .cases cs =>
extendByIfNecessary cs.discr
let discr ← replaceFVar cs.discr
let visitor := fun alt => do
withNewAltScope alt do
alt.mapCodeM go
let alts ← cs.alts.mapM visitor
return Code.updateCases! code cs.resultType discr alts
| .jmp fn args =>
let mut newArgs ← args.mapM (mapFVarM goFVar)
let additionalArgs := (← get).fvarMap.find! fn |>.toArray |>.map Prod.fst
if let some _currentJp := (← read).currentJp? then
let f := fun arg => do
return .fvar (← goFVar arg)
newArgs := (←additionalArgs.mapM f) ++ newArgs
else
newArgs := (additionalArgs.map .fvar) ++ newArgs
return Code.updateJmp! code fn newArgs
| .return var =>
extendByIfNecessary var
return Code.updateReturn! code (← replaceFVar var)
| .unreach .. => return code
end JoinPointContextExtender
namespace JoinPointCommonArgs
/--
Context for `ReduceAnalysisM`.
-/
structure AnalysisCtx where
/--
The variables that are in scope at the time of the definition of
the join point.
-/
jpScopes : FVarIdMap FVarIdSet := {}
/--
State for `ReduceAnalysisM`.
-/
structure AnalysisState where
/--
A map, that for each join point id contains a map from all (so far)
duplicated argument ids to the respective duplicate value
-/
jpJmpArgs : FVarIdMap FVarSubst := {}
abbrev ReduceAnalysisM := ReaderT AnalysisCtx StateRefT AnalysisState ScopeM
abbrev ReduceActionM := ReaderT AnalysisState CompilerM
def isInJpScope (jp : FVarId) (var : FVarId) : ReduceAnalysisM Bool := do
return (← read).jpScopes.find! jp |>.contains var
open ScopeM
/--
Take a look at each join point and each of their call sites. If all
call sites of a join point have one or more arguments in common, for example:
```
jp _jp.1 a b c => ...
...
cases foo
| n1 => jmp _jp.1 d e f
| n2 => jmp _jp.1 g e h
```
We can get rid of the common argument in favour of inlining it directly
into the join point (in this case the `e`). This reduces the amount of
arguments we have to pass around drastically for example in `ReaderT` based
monad stacks.
Note 1: This transformation can in certain niche cases obtain better results.
For example:
```
jp foo a b => ..
let x := ...
cases discr
| n1 => jmp foo x y
| n2 => jmp foo x z
```
Here we will not collapse the `x` since it is defined after the join point `foo`
and thus not accessible for substitution yet. We could however reorder the code in
such a way that this is possible, this is currently not done since we observe
than in praxis most of the applications of this transformation can occur naturally
without reordering.
Note 2: This transformation is kind of the opposite of `JoinPointContextExtender`.
However we still benefit from the extender because in the `simp` run after it
we might be able to pull join point declarations further up in the hierarchy
of nested functions/join points which in turn might enable additional optimizations.
After we have performed all of these optimizations we can take away the
(remaining) common arguments and end up with nicely floated and optimized
code that has as little arguments as possible in the join points.
-/
partial def reduce (decl : Decl) : CompilerM Decl := do
let (_, analysis) ← goAnalyze decl.value |>.run {} |>.run {} |>.run' {}
let newValue ← goReduce decl.value |>.run analysis
return { decl with value := newValue }
where
goAnalyzeFunDecl (fn : FunDecl) : ReduceAnalysisM Unit := do
withNewScope do
fn.params.forM (addToScope ·.fvarId)
goAnalyze fn.value
goAnalyze (code : Code) : ReduceAnalysisM Unit := do
match code with
| .let decl k =>
addToScope decl.fvarId
goAnalyze k
| .jp decl k =>
goAnalyzeFunDecl decl
let scope ← getScope
withReader (fun ctx => { ctx with jpScopes := ctx.jpScopes.insert decl.fvarId scope }) do
addToScope decl.fvarId
goAnalyze k
| .fun decl k =>
goAnalyzeFunDecl decl
addToScope decl.fvarId
goAnalyze k
| .cases cs =>
let visitor alt := do
withNewScope do
alt.getParams.forM (addToScope ·.fvarId)
goAnalyze alt.getCode
cs.alts.forM visitor
| .jmp fn args =>
let decl ← getFunDecl fn
if let some knownArgs := (← get).jpJmpArgs.find? fn then
let mut newArgs := knownArgs
for (param, arg) in decl.params.zip args do
if let some knownVal := newArgs.find? param.fvarId then
if arg.toExpr != knownVal then
newArgs := newArgs.erase param.fvarId
modify fun s => { s with jpJmpArgs := s.jpJmpArgs.insert fn newArgs }
else
let folder := fun acc (param, arg) => do
if (← allFVarM (isInJpScope fn) arg) then
return acc.insert param.fvarId arg.toExpr
else
return acc
let interestingArgs ← decl.params.zip args |>.foldlM (init := {}) folder
modify fun s => { s with jpJmpArgs := s.jpJmpArgs.insert fn interestingArgs }
| .return .. | .unreach .. => return ()
goReduce (code : Code) : ReduceActionM Code := do
match code with
| .jp decl k =>
if let some reducibleArgs := (← read).jpJmpArgs.find? decl.fvarId then
let filter param := do
let erasable := reducibleArgs.contains param.fvarId
if erasable then
eraseParam param
return !erasable
let newParams ← decl.params.filterM filter
let mut newValue ← goReduce decl.value
newValue ← replaceFVars newValue reducibleArgs false
let newType ←
if newParams.size != decl.params.size then
mkForallParams newParams (← newValue.inferType)
else
pure decl.type
let k ← goReduce k
let decl ← decl.update newType newParams newValue
return Code.updateFun! code decl k
else
return Code.updateFun! code decl (← goReduce k)
| .jmp fn args =>
let reducibleArgs := (← read).jpJmpArgs.find! fn
let decl ← getFunDecl fn
let newParams := decl.params.zip args
|>.filter (!reducibleArgs.contains ·.fst.fvarId)
|>.map Prod.snd
return Code.updateJmp! code fn newParams
| .let decl k =>
return Code.updateLet! code decl (← goReduce k)
| .fun decl k =>
let decl ← decl.updateValue (← goReduce decl.value)
return Code.updateFun! code decl (← goReduce k)
| .cases cs =>
let alts ← cs.alts.mapM (·.mapCodeM goReduce)
return Code.updateCases! code cs.resultType cs.discr alts
| .return .. | .unreach .. => return code
end JoinPointCommonArgs
/--
Find all `fun` declarations in `decl` that qualify as join points then replace
their definitions and call sites with `jp`/`jmp`.
-/
def Decl.findJoinPoints (decl : Decl) : CompilerM Decl := do
let findResult ← JoinPointFinder.find decl
trace[Compiler.findJoinPoints] "Found: {findResult.candidates.size} jp candidates"
JoinPointFinder.replace decl findResult
def findJoinPoints : Pass :=
.mkPerDeclaration `findJoinPoints Decl.findJoinPoints .base
builtin_initialize
registerTraceClass `Compiler.findJoinPoints (inherited := true)
def Decl.extendJoinPointContext (decl : Decl) : CompilerM Decl := do
JoinPointContextExtender.extend decl
def extendJoinPointContext (occurrence : Nat := 0) (phase := Phase.mono) (_h : phase ≠ .base := by simp): Pass :=
.mkPerDeclaration `extendJoinPointContext Decl.extendJoinPointContext phase (occurrence := occurrence)
builtin_initialize
registerTraceClass `Compiler.extendJoinPointContext (inherited := true)
def Decl.commonJoinPointArgs (decl : Decl) : CompilerM Decl := do
JoinPointCommonArgs.reduce decl
def commonJoinPointArgs : Pass :=
.mkPerDeclaration `commonJoinPointArgs Decl.commonJoinPointArgs .mono
builtin_initialize
registerTraceClass `Compiler.commonJoinPointArgs (inherited := true)
end Lean.Compiler.LCNF
|
32233b45c1208f2a7a08d2fc7022dd7a9dcc103f | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/category_theory/sites/sheafification.lean | 792eb964d8788f8839778a2c4de390dd6fe17538 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 23,829 | 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 category_theory.sites.plus
import category_theory.limits.concrete_category
/-!
# Sheafification
We construct the sheafification of a presheaf over a site `C` with values in `D` whenever
`D` is a concrete category for which the forgetful functor preserves the appropriate (co)limits
and reflects isomorphisms.
We generally follow the approach of https://stacks.math.columbia.edu/tag/00W1
-/
namespace category_theory
open category_theory.limits opposite
universes w v u
variables {C : Type u} [category.{v} C] {J : grothendieck_topology C}
variables {D : Type w} [category.{max v u} D]
section
variables [concrete_category.{max v u} D]
local attribute [instance]
concrete_category.has_coe_to_sort
concrete_category.has_coe_to_fun
/-- A concrete version of the multiequalizer, to be used below. -/
@[nolint has_nonempty_instance]
def meq {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) :=
{ x : Π (I : S.arrow), P.obj (op I.Y) //
∀ (I : S.relation), P.map I.g₁.op (x I.fst) = P.map I.g₂.op (x I.snd) }
end
namespace meq
variables [concrete_category.{max v u} D]
local attribute [instance]
concrete_category.has_coe_to_sort
concrete_category.has_coe_to_fun
instance {X} (P : Cᵒᵖ ⥤ D) (S : J.cover X) : has_coe_to_fun (meq P S)
(λ x, Π (I : S.arrow), P.obj (op I.Y)) := ⟨λ x, x.1⟩
@[ext]
lemma ext {X} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x y : meq P S)
(h : ∀ I : S.arrow, x I = y I) : x = y := subtype.ext $ funext $ h
lemma condition {X} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (I : S.relation) :
P.map I.g₁.op (x ((S.index P).fst_to I)) = P.map I.g₂.op (x ((S.index P).snd_to I)) := x.2 _
/-- Refine a term of `meq P T` with respect to a refinement `S ⟶ T` of covers. -/
def refine {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (x : meq P T) (e : S ⟶ T) :
meq P S :=
⟨λ I, x ⟨I.Y, I.f, (le_of_hom e) _ I.hf⟩,
λ I, x.condition ⟨I.Y₁, I.Y₂, I.Z, I.g₁, I.g₂, I.f₁, I.f₂,
(le_of_hom e) _ I.h₁, (le_of_hom e) _ I.h₂, I.w⟩⟩
@[simp]
lemma refine_apply {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (x : meq P T) (e : S ⟶ T)
(I : S.arrow) : x.refine e I = x ⟨I.Y, I.f, (le_of_hom e) _ I.hf⟩ := rfl
/-- Pull back a term of `meq P S` with respect to a morphism `f : Y ⟶ X` in `C`. -/
def pullback {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X) :
meq P ((J.pullback f).obj S) :=
⟨λ I, x ⟨_,I.f ≫ f, I.hf⟩, λ I, x.condition
⟨I.Y₁, I.Y₂, I.Z, I.g₁, I.g₂, I.f₁ ≫ f, I.f₂ ≫ f, I.h₁, I.h₂, by simp [reassoc_of I.w]⟩ ⟩
@[simp]
lemma pullback_apply {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X)
(I : ((J.pullback f).obj S).arrow) : x.pullback f I = x ⟨_, I.f ≫ f, I.hf⟩ := rfl
@[simp]
lemma pullback_refine {Y X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X} (h : S ⟶ T)
(f : Y ⟶ X) (x : meq P T) : (x.pullback f).refine
((J.pullback f).map h) = (refine x h).pullback _ := rfl
/-- Make a term of `meq P S`. -/
def mk {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) : meq P S :=
⟨λ I, P.map I.f.op x, λ I, by { dsimp, simp only [← comp_apply, ← P.map_comp, ← op_comp, I.w] }⟩
lemma mk_apply {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) (I : S.arrow) :
mk S x I = P.map I.f.op x := rfl
variable [preserves_limits (forget D)]
/-- The equivalence between the type associated to `multiequalizer (S.index P)` and `meq P S`. -/
noncomputable
def equiv {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) [has_multiequalizer (S.index P)] :
(multiequalizer (S.index P) : D) ≃ meq P S :=
limits.concrete.multiequalizer_equiv _
@[simp]
lemma equiv_apply {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} [has_multiequalizer (S.index P)]
(x : multiequalizer (S.index P)) (I : S.arrow) :
equiv P S x I = multiequalizer.ι (S.index P) I x := rfl
@[simp]
lemma equiv_symm_eq_apply {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} [has_multiequalizer (S.index P)]
(x : meq P S) (I : S.arrow) : multiequalizer.ι (S.index P) I ((meq.equiv P S).symm x) = x I :=
begin
let z := (meq.equiv P S).symm x,
rw ← equiv_apply,
simp,
end
end meq
namespace grothendieck_topology
namespace plus
variables [concrete_category.{max v u} D]
local attribute [instance]
concrete_category.has_coe_to_sort
concrete_category.has_coe_to_fun
variable [preserves_limits (forget D)]
variables [∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]
variables [∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]
noncomputable theory
/-- Make a term of `(J.plus_obj P).obj (op X)` from `x : meq P S`. -/
def mk {X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) : (J.plus_obj P).obj (op X) :=
colimit.ι (J.diagram P X) (op S) ((meq.equiv P S).symm x)
lemma res_mk_eq_mk_pullback {Y X : C} {P : Cᵒᵖ ⥤ D} {S : J.cover X} (x : meq P S) (f : Y ⟶ X) :
(J.plus_obj P).map f.op (mk x) = mk (x.pullback f) :=
begin
dsimp [mk, plus_obj],
simp only [← comp_apply, colimit.ι_pre, ι_colim_map_assoc],
simp_rw [comp_apply],
congr' 1,
apply_fun meq.equiv P _,
erw equiv.apply_symm_apply,
ext i,
simp only [diagram_pullback_app,
meq.pullback_apply, meq.equiv_apply, ← comp_apply],
erw [multiequalizer.lift_ι, meq.equiv_symm_eq_apply],
cases i, refl,
end
lemma to_plus_mk {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : P.obj (op X)) :
(J.to_plus P).app _ x = mk (meq.mk S x) :=
begin
dsimp [mk, to_plus],
let e : S ⟶ ⊤ := hom_of_le (order_top.le_top _),
rw ← colimit.w _ e.op,
delta cover.to_multiequalizer,
simp only [comp_apply],
congr' 1,
dsimp [diagram],
apply concrete.multiequalizer_ext,
intros i,
simpa only [← comp_apply, category.assoc, multiequalizer.lift_ι,
category.comp_id, meq.equiv_symm_eq_apply],
end
lemma to_plus_apply {X : C} {P : Cᵒᵖ ⥤ D} (S : J.cover X) (x : meq P S) (I : S.arrow) :
(J.to_plus P).app _ (x I) = (J.plus_obj P).map I.f.op (mk x) :=
begin
dsimp only [to_plus, plus_obj],
delta cover.to_multiequalizer,
dsimp [mk],
simp only [← comp_apply, colimit.ι_pre, ι_colim_map_assoc],
simp only [comp_apply],
dsimp only [functor.op],
let e : (J.pullback I.f).obj (unop (op S)) ⟶ ⊤ := hom_of_le (order_top.le_top _),
rw ← colimit.w _ e.op,
simp only [comp_apply],
congr' 1,
apply concrete.multiequalizer_ext,
intros i,
dsimp [diagram],
simp only [← comp_apply, category.assoc, multiequalizer.lift_ι,
category.comp_id, meq.equiv_symm_eq_apply],
let RR : S.relation :=
⟨_, _, _, i.f, 𝟙 _, I.f, i.f ≫ I.f, I.hf, sieve.downward_closed _ I.hf _, by simp⟩,
cases I,
erw x.condition RR,
simpa [RR],
end
lemma to_plus_eq_mk {X : C} {P : Cᵒᵖ ⥤ D} (x : P.obj (op X)) :
(J.to_plus P).app _ x = mk (meq.mk ⊤ x) :=
begin
dsimp [mk, to_plus],
delta cover.to_multiequalizer,
simp only [comp_apply],
congr' 1,
apply_fun (meq.equiv P ⊤),
ext i,
simpa,
end
variables [∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)]
lemma exists_rep {X : C} {P : Cᵒᵖ ⥤ D} (x : (J.plus_obj P).obj (op X)) :
∃ (S : J.cover X) (y : meq P S), x = mk y :=
begin
obtain ⟨S,y,h⟩ := concrete.colimit_exists_rep (J.diagram P X) x,
use [S.unop, meq.equiv _ _ y],
rw ← h,
dsimp [mk],
simp,
end
lemma eq_mk_iff_exists {X : C} {P : Cᵒᵖ ⥤ D} {S T : J.cover X}
(x : meq P S) (y : meq P T) : mk x = mk y ↔ (∃ (W : J.cover X) (h1 : W ⟶ S) (h2 : W ⟶ T),
x.refine h1 = y.refine h2) :=
begin
split,
{ intros h,
obtain ⟨W, h1, h2, hh⟩ := concrete.colimit_exists_of_rep_eq _ _ _ h,
use [W.unop, h1.unop, h2.unop],
ext I,
apply_fun (multiequalizer.ι (W.unop.index P) I) at hh,
convert hh,
all_goals
{ dsimp [diagram],
simp only [← comp_apply, multiequalizer.lift_ι, category.comp_id, meq.equiv_symm_eq_apply],
cases I, refl } },
{ rintros ⟨S,h1,h2,e⟩,
apply concrete.colimit_rep_eq_of_exists,
use [(op S), h1.op, h2.op],
apply concrete.multiequalizer_ext,
intros i,
apply_fun (λ ee, ee i) at e,
convert e,
all_goals
{ dsimp [diagram],
simp only [← comp_apply, multiequalizer.lift_ι, meq.equiv_symm_eq_apply],
cases i, refl } },
end
/-- `P⁺` is always separated. -/
theorem sep {X : C} (P : Cᵒᵖ ⥤ D) (S : J.cover X) (x y : (J.plus_obj P).obj (op X))
(h : ∀ (I : S.arrow), (J.plus_obj P).map I.f.op x = (J.plus_obj P).map I.f.op y) :
x = y :=
begin
-- First, we choose representatives for x and y.
obtain ⟨Sx,x,rfl⟩ := exists_rep x,
obtain ⟨Sy,y,rfl⟩ := exists_rep y,
simp only [res_mk_eq_mk_pullback] at h,
-- Next, using our assumption,
-- choose covers over which the pullbacks of these representatives become equal.
choose W h1 h2 hh using λ (I : S.arrow), (eq_mk_iff_exists _ _).mp (h I),
-- To prove equality, it suffices to prove that there exists a cover over which
-- the representatives become equal.
rw eq_mk_iff_exists,
-- Construct the cover over which the representatives become equal by combining the various
-- covers chosen above.
let B : J.cover X := S.bind W,
use B,
-- Prove that this cover refines the two covers over which our representatives are defined
-- and use these proofs.
let ex : B ⟶ Sx := hom_of_le begin
rintros Y f ⟨Z,e1,e2,he2,he1,hee⟩,
rw ← hee,
apply le_of_hom (h1 ⟨_, _, he2⟩),
exact he1,
end,
let ey : B ⟶ Sy := hom_of_le begin
rintros Y f ⟨Z,e1,e2,he2,he1,hee⟩,
rw ← hee,
apply le_of_hom (h2 ⟨_, _, he2⟩),
exact he1,
end,
use [ex, ey],
-- Now prove that indeed the representatives become equal over `B`.
-- This will follow by using the fact that our representatives become
-- equal over the chosen covers.
ext1 I,
let IS : S.arrow := I.from_middle,
specialize hh IS,
let IW : (W IS).arrow := I.to_middle,
apply_fun (λ e, e IW) at hh,
convert hh,
{ let Rx : Sx.relation := ⟨I.Y, I.Y, I.Y, 𝟙 _, 𝟙 _, I.f,
I.to_middle_hom ≫ I.from_middle_hom, _, _, by simp [I.middle_spec]⟩,
have := x.condition Rx,
simpa using this },
{ let Ry : Sy.relation := ⟨I.Y, I.Y, I.Y, 𝟙 _, 𝟙 _, I.f,
I.to_middle_hom ≫ I.from_middle_hom, _, _, by simp [I.middle_spec]⟩,
have := y.condition Ry,
simpa using this },
end
lemma inj_of_sep (P : Cᵒᵖ ⥤ D) (hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)),
(∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y) (X : C) :
function.injective ((J.to_plus P).app (op X)) :=
begin
intros x y h,
simp only [to_plus_eq_mk] at h,
rw eq_mk_iff_exists at h,
obtain ⟨W, h1, h2, hh⟩ := h,
apply hsep X W,
intros I,
apply_fun (λ e, e I) at hh,
exact hh
end
/-- An auxiliary definition to be used in the proof of `exists_of_sep` below.
Given a compatible family of local sections for `P⁺`, and representatives of said sections,
construct a compatible family of local sections of `P` over the combination of the covers
associated to the representatives.
The separatedness condition is used to prove compatibility among these local sections of `P`. -/
def meq_of_sep (P : Cᵒᵖ ⥤ D)
(hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)),
(∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y)
(X : C) (S : J.cover X)
(s : meq (J.plus_obj P) S)
(T : Π (I : S.arrow), J.cover I.Y)
(t : Π (I : S.arrow), meq P (T I))
(ht : ∀ (I : S.arrow), s I = mk (t I)) : meq P (S.bind T) :=
{ val := λ I, t I.from_middle I.to_middle,
property := begin
intros II,
apply inj_of_sep P hsep,
rw [← comp_apply, ← comp_apply, (J.to_plus P).naturality, (J.to_plus P).naturality,
comp_apply, comp_apply],
erw [to_plus_apply (T II.fst.from_middle) (t II.fst.from_middle) II.fst.to_middle,
to_plus_apply (T II.snd.from_middle) (t II.snd.from_middle) II.snd.to_middle,
← ht, ← ht, ← comp_apply, ← comp_apply, ← (J.plus_obj P).map_comp,
← (J.plus_obj P).map_comp],
rw [← op_comp, ← op_comp],
let IR : S.relation :=
⟨_, _, _, II.g₁ ≫ II.fst.to_middle_hom, II.g₂ ≫ II.snd.to_middle_hom,
II.fst.from_middle_hom, II.snd.from_middle_hom, II.fst.from_middle_condition,
II.snd.from_middle_condition, _⟩,
swap, { simp only [category.assoc, II.fst.middle_spec, II.snd.middle_spec], apply II.w },
exact s.condition IR,
end }
theorem exists_of_sep (P : Cᵒᵖ ⥤ D)
(hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)),
(∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y)
(X : C) (S : J.cover X)
(s : meq (J.plus_obj P) S) :
∃ t : (J.plus_obj P).obj (op X), meq.mk S t = s :=
begin
have inj : ∀ (X : C), function.injective ((J.to_plus P).app (op X)) := inj_of_sep _ hsep,
-- Choose representatives for the given local sections.
choose T t ht using λ I, exists_rep (s I),
-- Construct a large cover over which we will define a representative that will
-- provide the gluing of the given local sections.
let B : J.cover X := S.bind T,
choose Z e1 e2 he2 he1 hee using λ I : B.arrow, I.hf,
-- Construct a compatible system of local sections over this large cover, using the chosen
-- representatives of our local sections.
-- The compatilibity here follows from the separatedness assumption.
let w : meq P B := meq_of_sep P hsep X S s T t ht,
-- The associated gluing will be the candidate section.
use mk w,
ext I,
erw [ht, res_mk_eq_mk_pullback],
-- Use the separatedness of `P⁺` to prove that this is indeed a gluing of our
-- original local sections.
apply sep P (T I),
intros II,
simp only [res_mk_eq_mk_pullback, eq_mk_iff_exists],
-- It suffices to prove equality for representatives over a
-- convenient sufficiently large cover...
use (J.pullback II.f).obj (T I),
let e0 : (J.pullback II.f).obj (T I) ⟶ (J.pullback II.f).obj ((J.pullback I.f).obj B) :=
hom_of_le begin
intros Y f hf,
apply sieve.le_pullback_bind _ _ _ I.hf,
{ cases I,
exact hf },
end,
use [e0, 𝟙 _],
ext IV,
dsimp only [meq.refine_apply, meq.pullback_apply, w],
let IA : B.arrow := ⟨_, (IV.f ≫ II.f) ≫ I.f, _⟩,
swap,
{ refine ⟨I.Y, _, _, I.hf, _, rfl⟩,
apply sieve.downward_closed,
convert II.hf,
cases I, refl },
let IB : S.arrow := IA.from_middle,
let IC : (T IB).arrow := IA.to_middle,
let ID : (T I).arrow := ⟨IV.Y, IV.f ≫ II.f, sieve.downward_closed (T I) II.hf IV.f⟩,
change t IB IC = t I ID,
apply inj IV.Y,
erw [to_plus_apply (T I) (t I) ID, to_plus_apply (T IB) (t IB) IC, ← ht, ← ht],
-- Conclude by constructing the relation showing equality...
let IR : S.relation := ⟨_, _, IV.Y, IC.f, ID.f, IB.f, I.f, _, I.hf, IA.middle_spec⟩,
convert s.condition IR,
cases I, refl,
end
variable [reflects_isomorphisms (forget D)]
/-- If `P` is separated, then `P⁺` is a sheaf. -/
theorem is_sheaf_of_sep (P : Cᵒᵖ ⥤ D)
(hsep : ∀ (X : C) (S : J.cover X) (x y : P.obj (op X)),
(∀ I : S.arrow, P.map I.f.op x = P.map I.f.op y) → x = y) :
presheaf.is_sheaf J (J.plus_obj P) :=
begin
rw presheaf.is_sheaf_iff_multiequalizer,
intros X S,
apply is_iso_of_reflects_iso _ (forget D),
rw is_iso_iff_bijective,
split,
{ intros x y h,
apply sep P S _ _,
intros I,
apply_fun (meq.equiv _ _) at h,
apply_fun (λ e, e I) at h,
convert h,
{ erw [meq.equiv_apply, ← comp_apply, multiequalizer.lift_ι] },
{ erw [meq.equiv_apply, ← comp_apply, multiequalizer.lift_ι] } },
{ rintros (x : (multiequalizer (S.index _) : D)),
obtain ⟨t,ht⟩ := exists_of_sep P hsep X S (meq.equiv _ _ x),
use t,
apply_fun meq.equiv _ _,
swap, { apply_instance },
rw ← ht,
ext i,
dsimp,
rw [← comp_apply, multiequalizer.lift_ι],
refl }
end
variable (J)
/-- `P⁺⁺` is always a sheaf. -/
theorem is_sheaf_plus_plus (P : Cᵒᵖ ⥤ D) :
presheaf.is_sheaf J (J.plus_obj (J.plus_obj P)) :=
begin
apply is_sheaf_of_sep,
intros X S x y,
apply sep,
end
end plus
variables (J)
variables
[∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]
[∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]
/-- The sheafification of a presheaf `P`.
*NOTE:* Additional hypotheses are needed to obtain a proof that this is a sheaf! -/
def sheafify (P : Cᵒᵖ ⥤ D) : Cᵒᵖ ⥤ D := J.plus_obj (J.plus_obj P)
/-- The canonical map from `P` to its sheafification. -/
def to_sheafify (P : Cᵒᵖ ⥤ D) : P ⟶ J.sheafify P :=
J.to_plus P ≫ J.plus_map (J.to_plus P)
/-- The canonical map on sheafifications induced by a morphism. -/
def sheafify_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : J.sheafify P ⟶ J.sheafify Q :=
J.plus_map $ J.plus_map η
@[simp]
lemma sheafify_map_id (P : Cᵒᵖ ⥤ D) : J.sheafify_map (𝟙 P) = 𝟙 (J.sheafify P) :=
by { dsimp [sheafify_map, sheafify], simp }
@[simp]
lemma sheafify_map_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) :
J.sheafify_map (η ≫ γ) = J.sheafify_map η ≫ J.sheafify_map γ :=
by { dsimp [sheafify_map, sheafify], simp }
@[simp, reassoc]
lemma to_sheafify_naturality {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) :
η ≫ J.to_sheafify _ = J.to_sheafify _ ≫ J.sheafify_map η :=
by { dsimp [sheafify_map, sheafify, to_sheafify], simp }
variable (D)
/-- The sheafification of a presheaf `P`, as a functor.
*NOTE:* Additional hypotheses are needed to obtain a proof that this is a sheaf! -/
def sheafification : (Cᵒᵖ ⥤ D) ⥤ Cᵒᵖ ⥤ D := (J.plus_functor D ⋙ J.plus_functor D)
@[simp]
lemma sheafification_obj (P : Cᵒᵖ ⥤ D) : (J.sheafification D).obj P = J.sheafify P := rfl
@[simp]
lemma sheafification_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : (J.sheafification D).map η =
J.sheafify_map η := rfl
/-- The canonical map from `P` to its sheafification, as a natural transformation.
*Note:* We only show this is a sheaf under additional hypotheses on `D`. -/
def to_sheafification : 𝟭 _ ⟶ sheafification J D :=
J.to_plus_nat_trans D ≫ whisker_right (J.to_plus_nat_trans D) (J.plus_functor D)
@[simp]
lemma to_sheafification_app (P : Cᵒᵖ ⥤ D) : (J.to_sheafification D).app P = J.to_sheafify P := rfl
variable {D}
lemma is_iso_to_sheafify {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) :
is_iso (J.to_sheafify P) :=
begin
dsimp [to_sheafify],
haveI : is_iso (J.to_plus P) := by { apply is_iso_to_plus_of_is_sheaf J P hP },
haveI : is_iso ((J.plus_functor D).map (J.to_plus P)) := by { apply functor.map_is_iso },
exact @is_iso.comp_is_iso _ _ _ _ _ (J.to_plus P)
((J.plus_functor D).map (J.to_plus P)) _ _,
end
/-- If `P` is a sheaf, then `P` is isomorphic to `J.sheafify P`. -/
def iso_sheafify {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) :
P ≅ J.sheafify P :=
by letI := is_iso_to_sheafify J hP; exactI as_iso (J.to_sheafify P)
@[simp]
lemma iso_sheafify_hom {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) :
(J.iso_sheafify hP).hom = J.to_sheafify P := rfl
/-- Given a sheaf `Q` and a morphism `P ⟶ Q`, construct a morphism from
`J.sheafifcation P` to `Q`. -/
def sheafify_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) :
J.sheafify P ⟶ Q := J.plus_lift (J.plus_lift η hQ) hQ
@[simp, reassoc]
lemma to_sheafify_sheafify_lift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q) :
J.to_sheafify P ≫ sheafify_lift J η hQ = η :=
by { dsimp only [sheafify_lift, to_sheafify], simp }
lemma sheafify_lift_unique {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : presheaf.is_sheaf J Q)
(γ : J.sheafify P ⟶ Q) :
J.to_sheafify P ≫ γ = η → γ = sheafify_lift J η hQ :=
begin
intros h,
apply plus_lift_unique,
apply plus_lift_unique,
rw [← category.assoc, ← plus_map_to_plus],
exact h,
end
@[simp]
lemma iso_sheafify_inv {P : Cᵒᵖ ⥤ D} (hP : presheaf.is_sheaf J P) :
(J.iso_sheafify hP).inv = J.sheafify_lift (𝟙 _) hP :=
begin
apply J.sheafify_lift_unique,
simp [iso.comp_inv_eq],
end
lemma sheafify_hom_ext {P Q : Cᵒᵖ ⥤ D} (η γ : J.sheafify P ⟶ Q) (hQ : presheaf.is_sheaf J Q)
(h : J.to_sheafify P ≫ η = J.to_sheafify P ≫ γ) : η = γ :=
begin
apply J.plus_hom_ext _ _ hQ,
apply J.plus_hom_ext _ _ hQ,
rw [← category.assoc, ← category.assoc, ← plus_map_to_plus],
exact h,
end
@[simp, reassoc]
lemma sheafify_map_sheafify_lift {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R)
(hR : presheaf.is_sheaf J R) :
J.sheafify_map η ≫ J.sheafify_lift γ hR = J.sheafify_lift (η ≫ γ) hR :=
begin
apply J.sheafify_lift_unique,
rw [← category.assoc, ← J.to_sheafify_naturality,
category.assoc, to_sheafify_sheafify_lift],
end
end grothendieck_topology
variables (J)
variables
[concrete_category.{max v u} D]
[preserves_limits (forget D)]
[∀ (P : Cᵒᵖ ⥤ D) (X : C) (S : J.cover X), has_multiequalizer (S.index P)]
[∀ (X : C), has_colimits_of_shape (J.cover X)ᵒᵖ D]
[∀ (X : C), preserves_colimits_of_shape (J.cover X)ᵒᵖ (forget D)]
[reflects_isomorphisms (forget D)]
lemma grothendieck_topology.sheafify_is_sheaf (P : Cᵒᵖ ⥤ D) :
presheaf.is_sheaf J (J.sheafify P) :=
grothendieck_topology.plus.is_sheaf_plus_plus _ _
variables (D)
/-- The sheafification functor, as a functor taking values in `Sheaf`. -/
@[simps]
def presheaf_to_Sheaf : (Cᵒᵖ ⥤ D) ⥤ Sheaf J D :=
{ obj := λ P, ⟨J.sheafify P, J.sheafify_is_sheaf P⟩,
map := λ P Q η, ⟨J.sheafify_map η⟩,
map_id' := λ P, Sheaf.hom.ext _ _ $ J.sheafify_map_id _,
map_comp' := λ P Q R f g, Sheaf.hom.ext _ _ $ J.sheafify_map_comp _ _ }
/-- The sheafification functor is left adjoint to the forgetful functor. -/
@[simps unit_app counit_app_val]
def sheafification_adjunction : presheaf_to_Sheaf J D ⊣ Sheaf_to_presheaf J D :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ P Q,
{ to_fun := λ e, J.to_sheafify P ≫ e.val,
inv_fun := λ e, ⟨J.sheafify_lift e Q.2⟩,
left_inv := λ e, Sheaf.hom.ext _ _ $ (J.sheafify_lift_unique _ _ _ rfl).symm,
right_inv := λ e, J.to_sheafify_sheafify_lift _ _ },
hom_equiv_naturality_left_symm' := begin
intros P Q R η γ, ext1, dsimp, symmetry,
apply J.sheafify_map_sheafify_lift,
end,
hom_equiv_naturality_right' := λ P Q R η γ, by { dsimp, rw category.assoc } }
instance Sheaf_to_presheaf_is_right_adjoint : is_right_adjoint (Sheaf_to_presheaf J D) :=
⟨_, sheafification_adjunction J D⟩
instance presheaf_mono_of_mono {F G : Sheaf J D} (f : F ⟶ G) [mono f] : mono f.1 :=
(Sheaf_to_presheaf J D).map_mono _
lemma Sheaf.hom.mono_iff_presheaf_mono {F G : Sheaf J D} (f : F ⟶ G) : mono f ↔ mono f.1 :=
⟨λ m, by { resetI, apply_instance },
λ m, by { resetI, exact Sheaf.hom.mono_of_presheaf_mono J D f }⟩
variables {J D}
/-- A sheaf `P` is isomorphic to its own sheafification. -/
@[simps]
def sheafification_iso (P : Sheaf J D) :
P ≅ (presheaf_to_Sheaf J D).obj P.val :=
{ hom := ⟨(J.iso_sheafify P.2).hom⟩,
inv := ⟨(J.iso_sheafify P.2).inv⟩,
hom_inv_id' := by { ext1, apply (J.iso_sheafify P.2).hom_inv_id },
inv_hom_id' := by { ext1, apply (J.iso_sheafify P.2).inv_hom_id } }
instance is_iso_sheafification_adjunction_counit (P : Sheaf J D) :
is_iso ((sheafification_adjunction J D).counit.app P) :=
is_iso_of_fully_faithful (Sheaf_to_presheaf J D) _
instance sheafification_reflective : is_iso (sheafification_adjunction J D).counit :=
nat_iso.is_iso_of_is_iso_app _
end category_theory
|
790b164f90334259dbe9948b392134837f8198f7 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/number_theory/liouville/residual.lean | 7188ad925b8969b67ac162f3ed532c0e966ffc07 | [
"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 | 2,932 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import number_theory.liouville.basic
import topology.metric_space.baire
import topology.instances.irrational
/-!
# Density of Liouville numbers
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we prove that the set of Liouville numbers form a dense `Gδ` set. We also prove a
similar statement about irrational numbers.
-/
open_locale filter
open filter set metric
lemma set_of_liouville_eq_Inter_Union :
{x | liouville x} =
⋂ n : ℕ, ⋃ (a b : ℤ) (hb : 1 < b), ball (a / b) (1 / b ^ n) \ {a / b} :=
begin
ext x,
simp only [mem_Inter, mem_Union, liouville, mem_set_of_eq, exists_prop, mem_diff,
mem_singleton_iff, mem_ball, real.dist_eq, and_comm]
end
lemma is_Gδ_set_of_liouville : is_Gδ {x | liouville x} :=
begin
rw set_of_liouville_eq_Inter_Union,
refine is_Gδ_Inter (λ n, is_open.is_Gδ _),
refine is_open_Union (λ a, is_open_Union $ λ b, is_open_Union $ λ hb, _),
exact is_open_ball.inter is_closed_singleton.is_open_compl
end
lemma set_of_liouville_eq_irrational_inter_Inter_Union :
{x | liouville x} =
{x | irrational x} ∩ ⋂ n : ℕ, ⋃ (a b : ℤ) (hb : 1 < b), ball (a / b) (1 / b ^ n) :=
begin
refine subset.antisymm _ _,
{ refine subset_inter (λ x hx, hx.irrational) _,
rw set_of_liouville_eq_Inter_Union,
exact Inter_mono (λ n, Union₂_mono $ λ a b, Union_mono $ λ hb, diff_subset _ _) },
{ simp only [inter_Inter, inter_Union, set_of_liouville_eq_Inter_Union],
refine Inter_mono (λ n, Union₂_mono $ λ a b, Union_mono $ λ hb, _),
rw [inter_comm],
refine diff_subset_diff subset.rfl (singleton_subset_iff.2 ⟨a / b, _⟩),
norm_cast }
end
/-- The set of Liouville numbers is a residual set. -/
lemma eventually_residual_liouville : ∀ᶠ x in residual ℝ, liouville x :=
begin
rw [filter.eventually, set_of_liouville_eq_irrational_inter_Inter_Union],
refine eventually_residual_irrational.and _,
refine eventually_residual.2 ⟨_, _, rat.dense_embedding_coe_real.dense.mono _, subset.rfl⟩,
{ exact is_Gδ_Inter (λ n, is_open.is_Gδ $ is_open_Union $ λ a, is_open_Union $
λ b, is_open_Union $ λ hb, is_open_ball) },
{ rintro _ ⟨r, rfl⟩,
simp only [mem_Inter, mem_Union],
refine λ n, ⟨r.num * 2, r.denom * 2, _, _⟩,
{ have := int.coe_nat_le.2 r.pos, rw int.coe_nat_one at this, linarith },
{ convert mem_ball_self _ using 2,
{ push_cast, norm_cast, norm_num },
{ refine one_div_pos.2 (pow_pos (int.cast_pos.2 _) _),
exact mul_pos (int.coe_nat_pos.2 r.pos) zero_lt_two } } }
end
/-- The set of Liouville numbers in dense. -/
lemma dense_liouville : dense {x | liouville x} :=
dense_of_mem_residual eventually_residual_liouville
|
db53a0eb486dd4bbcbe4dd14b4a5e87d46f6c1c9 | 130c49f47783503e462c16b2eff31933442be6ff | /src/Lean/Meta/Instances.lean | 19f06b50c1cfa540dd5c11a641b6f3ceae6d3c43 | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,676 | 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.ScopedEnvExtension
import Lean.Meta.GlobalInstances
import Lean.Meta.DiscrTree
namespace Lean.Meta
structure InstanceEntry where
keys : Array DiscrTree.Key
val : Expr
priority : Nat
globalName? : Option Name := none
deriving Inhabited
instance : BEq InstanceEntry where
beq e₁ e₂ := e₁.val == e₂.val
instance : ToFormat InstanceEntry where
format e := match e.globalName? with
| some n => format n
| _ => "<local>"
structure Instances where
discrTree : DiscrTree InstanceEntry := DiscrTree.empty
deriving Inhabited
def addInstanceEntry (d : Instances) (e : InstanceEntry) : Instances :=
{ d with discrTree := d.discrTree.insertCore e.keys e }
builtin_initialize instanceExtension : SimpleScopedEnvExtension InstanceEntry Instances ←
registerSimpleScopedEnvExtension {
name := `instanceExt
initial := {}
addEntry := addInstanceEntry
}
private def mkInstanceKey (e : Expr) : MetaM (Array DiscrTree.Key) := do
let type ← inferType e
withNewMCtxDepth do
let (_, _, type) ← forallMetaTelescopeReducing type
DiscrTree.mkPath type
def addInstance (declName : Name) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do
let c ← mkConstWithLevelParams declName
let keys ← mkInstanceKey c
addGlobalInstance declName attrKind
instanceExtension.add { keys := keys, val := c, priority := prio, globalName? := declName } attrKind
builtin_initialize
registerBuiltinAttribute {
name := `instance
descr := "type class instance"
add := fun declName stx attrKind => do
let prio ← getAttrParamOptPrio stx[1]
discard <| addInstance declName attrKind prio |>.run {} {}
}
def getGlobalInstancesIndex : MetaM (DiscrTree InstanceEntry) :=
return Meta.instanceExtension.getState (← getEnv) |>.discrTree
/- Default instance support -/
structure DefaultInstanceEntry where
className : Name
instanceName : Name
priority : Nat
abbrev PrioritySet := Std.RBTree Nat (fun x y => compare y x)
structure DefaultInstances where
defaultInstances : NameMap (List (Name × Nat)) := {}
priorities : PrioritySet := {}
deriving Inhabited
def addDefaultInstanceEntry (d : DefaultInstances) (e : DefaultInstanceEntry) : DefaultInstances :=
let d := { d with priorities := d.priorities.insert e.priority }
match d.defaultInstances.find? e.className with
| some insts => { d with defaultInstances := d.defaultInstances.insert e.className <| (e.instanceName, e.priority) :: insts }
| none => { d with defaultInstances := d.defaultInstances.insert e.className [(e.instanceName, e.priority)] }
builtin_initialize defaultInstanceExtension : SimplePersistentEnvExtension DefaultInstanceEntry DefaultInstances ←
registerSimplePersistentEnvExtension {
name := `defaultInstanceExt
addEntryFn := addDefaultInstanceEntry
addImportedFn := fun es => (mkStateFromImportedEntries addDefaultInstanceEntry {} es)
}
def addDefaultInstance (declName : Name) (prio : Nat := 0) : MetaM Unit := do
match (← getEnv).find? declName with
| none => throwError "unknown constant '{declName}'"
| some info =>
forallTelescopeReducing info.type fun _ type => do
match type.getAppFn with
| Expr.const className _ _ =>
unless isClass (← getEnv) className do
throwError "invalid default instance '{declName}', it has type '({className} ...)', but {className}' is not a type class"
setEnv <| defaultInstanceExtension.addEntry (← getEnv) { className := className, instanceName := declName, priority := prio }
| _ => throwError "invalid default instance '{declName}', type must be of the form '(C ...)' where 'C' is a type class"
builtin_initialize
registerBuiltinAttribute {
name := `defaultInstance
descr := "type class default instance"
add := fun declName stx kind => do
let prio ← getAttrParamOptPrio stx[1]
unless kind == AttributeKind.global do throwError "invalid attribute 'defaultInstance', must be global"
discard <| addDefaultInstance declName prio |>.run {} {}
}
def getDefaultInstancesPriorities [Monad m] [MonadEnv m] : m PrioritySet :=
return defaultInstanceExtension.getState (← getEnv) |>.priorities
def getDefaultInstances [Monad m] [MonadEnv m] (className : Name) : m (List (Name × Nat)) :=
return defaultInstanceExtension.getState (← getEnv) |>.defaultInstances.find? className |>.getD []
end Lean.Meta
|
094484eefe17e92b1c76e5f8732e301e013309f8 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/measure_theory/measure/content.lean | 2880a8391e4f8afb05d96c195d0611ba05ff5b04 | [
"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 | 17,011 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.measure.measure_space
import measure_theory.measure.regular
import topology.opens
import topology.compacts
/-!
# Contents
In this file we work with *contents*. A content `λ` is a function from a certain class of subsets
(such as the compact subsets) to `ℝ≥0` that is
* additive: If `K₁` and `K₂` are disjoint sets in the domain of `λ`,
then `λ(K₁ ∪ K₂) = λ(K₁) + λ(K₂)`;
* subadditive: If `K₁` and `K₂` are in the domain of `λ`, then `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)`;
* monotone: If `K₁ ⊆ K₂` are in the domain of `λ`, then `λ(K₁) ≤ λ(K₂)`.
We show that:
* Given a content `λ` on compact sets, let us define a function `λ*` on open sets, by letting
`λ* U` be the supremum of `λ K` for `K` included in `U`. This is a countably subadditive map that
vanishes at `∅`. In Halmos (1950) this is called the *inner content* `λ*` of `λ`, and formalized
as `inner_content`.
* Given an inner content, we define an outer measure `μ*`, by letting `μ* E` be the infimum of
`λ* U` over the open sets `U` containing `E`. This is indeed an outer measure. It is formalized
as `outer_measure`.
* Restricting this outer measure to Borel sets gives a regular measure `μ`.
We define bundled contents as `content`.
In this file we only work on contents on compact sets, and inner contents on open sets, and both
contents and inner contents map into the extended nonnegative reals. However, in other applications
other choices can be made, and it is not a priori clear what the best interface should be.
## Main definitions
For `μ : content G`, we define
* `μ.inner_content` : the inner content associated to `μ`.
* `μ.outer_measure` : the outer measure associated to `μ`.
* `μ.measure` : the Borel measure associated to `μ`.
We prove that, on a locally compact space, the measure `μ.measure` is regular.
## References
* Paul Halmos (1950), Measure Theory, §53
* <https://en.wikipedia.org/wiki/Content_(measure_theory)>
-/
universe variables u v w
noncomputable theory
open set topological_space
open_locale nnreal ennreal
namespace measure_theory
variables {G : Type w} [topological_space G]
/-- A content is an additive function on compact sets taking values in `ℝ≥0`. It is a device
from which one can define a measure. -/
structure content (G : Type w) [topological_space G] :=
(to_fun : compacts G → ℝ≥0)
(mono' : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → to_fun K₁ ≤ to_fun K₂)
(sup_disjoint' : ∀ (K₁ K₂ : compacts G), disjoint K₁.1 K₂.1 →
to_fun (K₁ ⊔ K₂) = to_fun K₁ + to_fun K₂)
(sup_le' : ∀ (K₁ K₂ : compacts G), to_fun (K₁ ⊔ K₂) ≤ to_fun K₁ + to_fun K₂)
instance : inhabited (content G) :=
⟨{ to_fun := λ K, 0,
mono' := by simp,
sup_disjoint' := by simp,
sup_le' := by simp }⟩
/-- Although the `to_fun` field of a content takes values in `ℝ≥0`, we register a coercion to
functions taking values in `ℝ≥0∞` as most constructions below rely on taking suprs and infs, which
is more convenient in a complete lattice, and aim at constructing a measure. -/
instance : has_coe_to_fun (content G) := ⟨_, λ μ s, (μ.to_fun s : ℝ≥0∞)⟩
namespace content
variable (μ : content G)
lemma apply_eq_coe_to_fun (K : compacts G) : μ K = μ.to_fun K := rfl
lemma mono (K₁ K₂ : compacts G) (h : K₁.1 ⊆ K₂.1) : μ K₁ ≤ μ K₂ :=
by simp [apply_eq_coe_to_fun, μ.mono' _ _ h]
lemma sup_disjoint (K₁ K₂ : compacts G) (h : disjoint K₁.1 K₂.1) : μ (K₁ ⊔ K₂) = μ K₁ + μ K₂ :=
by simp [apply_eq_coe_to_fun, μ.sup_disjoint' _ _ h]
lemma sup_le (K₁ K₂ : compacts G) : μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂ :=
by { simp only [apply_eq_coe_to_fun], norm_cast, exact μ.sup_le' _ _ }
lemma lt_top (K : compacts G) : μ K < ∞ :=
ennreal.coe_lt_top
lemma empty : μ ⊥ = 0 :=
begin
have := μ.sup_disjoint' ⊥ ⊥,
simpa [apply_eq_coe_to_fun] using this,
end
/-- Constructing the inner content of a content. From a content defined on the compact sets, we
obtain a function defined on all open sets, by taking the supremum of the content of all compact
subsets. -/
def inner_content (U : opens G) : ℝ≥0∞ :=
⨆ (K : compacts G) (h : K.1 ⊆ U), μ K
lemma le_inner_content (K : compacts G) (U : opens G)
(h2 : K.1 ⊆ U) : μ K ≤ μ.inner_content U :=
le_supr_of_le K $ le_supr _ h2
lemma inner_content_le (U : opens G) (K : compacts G) (h2 : (U : set G) ⊆ K.1) :
μ.inner_content U ≤ μ K :=
bsupr_le $ λ K' hK', μ.mono _ _ (subset.trans hK' h2)
lemma inner_content_of_is_compact {K : set G} (h1K : is_compact K) (h2K : is_open K) :
μ.inner_content ⟨K, h2K⟩ = μ ⟨K, h1K⟩ :=
le_antisymm (bsupr_le $ λ K' hK', μ.mono _ ⟨K, h1K⟩ hK')
(μ.le_inner_content _ _ subset.rfl)
lemma inner_content_empty :
μ.inner_content ∅ = 0 :=
begin
refine le_antisymm _ (zero_le _), rw ←μ.empty,
refine bsupr_le (λ K hK, _),
have : K = ⊥, { ext1, rw [subset_empty_iff.mp hK, compacts.bot_val] }, rw this, refl'
end
/-- This is "unbundled", because that it required for the API of `induced_outer_measure`. -/
lemma inner_content_mono ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V)
(h2 : U ⊆ V) : μ.inner_content ⟨U, hU⟩ ≤ μ.inner_content ⟨V, hV⟩ :=
supr_le_supr $ λ K, supr_le_supr_const $ λ hK, subset.trans hK h2
lemma inner_content_exists_compact {U : opens G}
(hU : μ.inner_content U ≠ ∞) {ε : ℝ≥0} (hε : ε ≠ 0) :
∃ K : compacts G, K.1 ⊆ U ∧ μ.inner_content U ≤ μ K + ε :=
begin
have h'ε := ennreal.coe_ne_zero.2 hε,
cases le_or_lt (μ.inner_content U) ε,
{ exact ⟨⊥, empty_subset _, le_add_left h⟩ },
have := ennreal.sub_lt_self hU h.ne_bot h'ε,
conv at this {to_rhs, rw inner_content }, simp only [lt_supr_iff] at this,
rcases this with ⟨U, h1U, h2U⟩, refine ⟨U, h1U, _⟩,
rw [← ennreal.sub_le_iff_le_add], exact le_of_lt h2U
end
/-- The inner content of a supremum of opens is at most the sum of the individual inner
contents. -/
lemma inner_content_Sup_nat [t2_space G] (U : ℕ → opens G) :
μ.inner_content (⨆ (i : ℕ), U i) ≤ ∑' (i : ℕ), μ.inner_content (U i) :=
begin
have h3 : ∀ (t : finset ℕ) (K : ℕ → compacts G), μ (t.sup K) ≤ t.sum (λ i, μ (K i)),
{ intros t K, refine finset.induction_on t _ _,
{ simp only [μ.empty, nonpos_iff_eq_zero, finset.sum_empty, finset.sup_empty], },
{ intros n s hn ih, rw [finset.sup_insert, finset.sum_insert hn],
exact le_trans (μ.sup_le _ _) (add_le_add_left ih _) }},
refine bsupr_le (λ K hK, _),
rcases is_compact.elim_finite_subcover K.2 _ (λ i, (U i).prop) _ with ⟨t, ht⟩, swap,
{ convert hK, rw [opens.supr_def, subtype.coe_mk] },
rcases K.2.finite_compact_cover t (coe ∘ U) (λ i _, (U _).prop) (by simp only [ht])
with ⟨K', h1K', h2K', h3K'⟩,
let L : ℕ → compacts G := λ n, ⟨K' n, h1K' n⟩,
convert le_trans (h3 t L) _,
{ ext1, simp only [h3K', compacts.finset_sup_val, finset.sup_eq_supr, set.supr_eq_Union] },
refine le_trans (finset.sum_le_sum _) (ennreal.sum_le_tsum t),
intros i hi, refine le_trans _ (le_supr _ (L i)),
refine le_trans _ (le_supr _ (h2K' i)), refl'
end
/-- The inner content of a union of sets is at most the sum of the individual inner contents.
This is the "unbundled" version of `inner_content_Sup_nat`.
It required for the API of `induced_outer_measure`. -/
lemma inner_content_Union_nat [t2_space G] ⦃U : ℕ → set G⦄ (hU : ∀ (i : ℕ), is_open (U i)) :
μ.inner_content ⟨⋃ (i : ℕ), U i, is_open_Union hU⟩ ≤ ∑' (i : ℕ), μ.inner_content ⟨U i, hU i⟩ :=
by { have := μ.inner_content_Sup_nat (λ i, ⟨U i, hU i⟩), rwa [opens.supr_def] at this }
lemma inner_content_comap (f : G ≃ₜ G)
(h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (U : opens G) :
μ.inner_content (U.comap f.continuous) = μ.inner_content U :=
begin
refine supr_congr _ ((compacts.equiv f).surjective) _,
intro K, refine supr_congr_Prop image_subset_iff _,
intro hK, simp only [equiv.coe_fn_mk, subtype.mk_eq_mk, ennreal.coe_eq_coe, compacts.equiv],
apply h,
end
@[to_additive]
lemma is_mul_left_invariant_inner_content [group G] [topological_group G]
(h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G)
(U : opens G) : μ.inner_content (U.comap $ continuous_mul_left g) = μ.inner_content U :=
by convert μ.inner_content_comap (homeomorph.mul_left g) (λ K, h g) U
@[to_additive]
lemma inner_content_pos_of_is_mul_left_invariant [t2_space G] [group G] [topological_group G]
(h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K)
(K : compacts G) (hK : μ K ≠ 0) (U : opens G) (hU : (U : set G).nonempty) :
0 < μ.inner_content U :=
begin
have : (interior (U : set G)).nonempty, rwa [U.prop.interior_eq],
rcases compact_covered_by_mul_left_translates K.2 this with ⟨s, hs⟩,
suffices : μ K ≤ s.card * μ.inner_content U,
{ exact (ennreal.mul_pos_iff.mp $ hK.bot_lt.trans_le this).2 },
have : K.1 ⊆ ↑⨆ (g ∈ s), U.comap $ continuous_mul_left g,
{ simpa only [opens.supr_def, opens.coe_comap, subtype.coe_mk] },
refine (μ.le_inner_content _ _ this).trans _,
refine (rel_supr_sum (μ.inner_content) (μ.inner_content_empty) (≤)
(μ.inner_content_Sup_nat) _ _).trans _,
simp only [μ.is_mul_left_invariant_inner_content h3, finset.sum_const, nsmul_eq_mul, le_refl]
end
lemma inner_content_mono' ⦃U V : set G⦄
(hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) :
μ.inner_content ⟨U, hU⟩ ≤ μ.inner_content ⟨V, hV⟩ :=
supr_le_supr $ λ K, supr_le_supr_const $ λ hK, subset.trans hK h2
/-- Extending a content on compact sets to an outer measure on all sets. -/
protected def outer_measure : outer_measure G :=
induced_outer_measure (λ U hU, μ.inner_content ⟨U, hU⟩) is_open_empty μ.inner_content_empty
variables [t2_space G]
lemma outer_measure_opens (U : opens G) : μ.outer_measure U = μ.inner_content U :=
induced_outer_measure_eq' (λ _, is_open_Union) μ.inner_content_Union_nat μ.inner_content_mono U.2
lemma outer_measure_of_is_open (U : set G) (hU : is_open U) :
μ.outer_measure U = μ.inner_content ⟨U, hU⟩ :=
μ.outer_measure_opens ⟨U, hU⟩
lemma outer_measure_le
(U : opens G) (K : compacts G) (hUK : (U : set G) ⊆ K.1) : μ.outer_measure U ≤ μ K :=
(μ.outer_measure_opens U).le.trans $ μ.inner_content_le U K hUK
lemma le_outer_measure_compacts (K : compacts G) : μ K ≤ μ.outer_measure K.1 :=
begin
rw [content.outer_measure, induced_outer_measure_eq_infi],
{ exact le_infi (λ U, le_infi $ λ hU, le_infi $ μ.le_inner_content K ⟨U, hU⟩) },
{ exact μ.inner_content_Union_nat },
{ exact μ.inner_content_mono }
end
lemma outer_measure_eq_infi (A : set G) :
μ.outer_measure A = ⨅ (U : set G) (hU : is_open U) (h : A ⊆ U), μ.inner_content ⟨U, hU⟩ :=
induced_outer_measure_eq_infi _ μ.inner_content_Union_nat μ.inner_content_mono A
lemma outer_measure_interior_compacts (K : compacts G) : μ.outer_measure (interior K.1) ≤ μ K :=
le_trans (le_of_eq $ μ.outer_measure_opens (opens.interior K.1))
(μ.inner_content_le _ _ interior_subset)
lemma outer_measure_exists_compact {U : opens G} (hU : μ.outer_measure U ≠ ∞) {ε : ℝ≥0}
(hε : ε ≠ 0) : ∃ K : compacts G, K.1 ⊆ U ∧ μ.outer_measure U ≤ μ.outer_measure K.1 + ε :=
begin
rw [μ.outer_measure_opens] at hU ⊢,
rcases μ.inner_content_exists_compact hU hε with ⟨K, h1K, h2K⟩,
exact ⟨K, h1K, le_trans h2K $ add_le_add_right (μ.le_outer_measure_compacts K) _⟩,
end
lemma outer_measure_exists_open {A : set G} (hA : μ.outer_measure A ≠ ∞) {ε : ℝ≥0} (hε : ε ≠ 0) :
∃ U : opens G, A ⊆ U ∧ μ.outer_measure U ≤ μ.outer_measure A + ε :=
begin
rcases induced_outer_measure_exists_set _ _ μ.inner_content_mono hA (ennreal.coe_ne_zero.2 hε)
with ⟨U, hU, h2U, h3U⟩,
exact ⟨⟨U, hU⟩, h2U, h3U⟩, swap, exact μ.inner_content_Union_nat
end
lemma outer_measure_preimage (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K)
(A : set G) : μ.outer_measure (f ⁻¹' A) = μ.outer_measure A :=
begin
refine induced_outer_measure_preimage _ μ.inner_content_Union_nat μ.inner_content_mono _
(λ s, f.is_open_preimage) _,
intros s hs, convert μ.inner_content_comap f h ⟨s, hs⟩
end
lemma outer_measure_lt_top_of_is_compact [locally_compact_space G]
{K : set G} (hK : is_compact K) : μ.outer_measure K < ∞ :=
begin
rcases exists_compact_superset hK with ⟨F, h1F, h2F⟩,
calc
μ.outer_measure K ≤ μ.outer_measure (interior F) : outer_measure.mono' _ h2F
... ≤ μ ⟨F, h1F⟩ :
by apply μ.outer_measure_le ⟨interior F, is_open_interior⟩ ⟨F, h1F⟩ interior_subset
... < ⊤ : μ.lt_top _
end
@[to_additive]
lemma is_mul_left_invariant_outer_measure [group G] [topological_group G]
(h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G)
(A : set G) : μ.outer_measure ((λ h, g * h) ⁻¹' A) = μ.outer_measure A :=
by convert μ.outer_measure_preimage (homeomorph.mul_left g) (λ K, h g) A
lemma outer_measure_caratheodory (A : set G) :
μ.outer_measure.caratheodory.measurable_set' A ↔ ∀ (U : opens G),
μ.outer_measure (U ∩ A) + μ.outer_measure (U \ A) ≤ μ.outer_measure U :=
begin
dsimp [opens], rw subtype.forall,
apply induced_outer_measure_caratheodory,
apply inner_content_Union_nat,
apply inner_content_mono'
end
@[to_additive]
lemma outer_measure_pos_of_is_mul_left_invariant [group G] [topological_group G]
(h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K)
(K : compacts G) (hK : μ K ≠ 0) {U : set G} (h1U : is_open U) (h2U : U.nonempty) :
0 < μ.outer_measure U :=
by { convert μ.inner_content_pos_of_is_mul_left_invariant h3 K hK ⟨U, h1U⟩ h2U,
exact μ.outer_measure_opens ⟨U, h1U⟩ }
variables [S : measurable_space G] [borel_space G]
include S
/-- For the outer measure coming from a content, all Borel sets are measurable. -/
lemma borel_le_caratheodory : S ≤ μ.outer_measure.caratheodory :=
begin
rw [@borel_space.measurable_eq G _ _],
refine measurable_space.generate_from_le _,
intros U hU,
rw μ.outer_measure_caratheodory,
intro U',
rw μ.outer_measure_of_is_open ((U' : set G) ∩ U) (is_open.inter U'.prop hU),
simp only [inner_content, supr_subtype'], rw [opens.coe_mk],
haveI : nonempty {L : compacts G // L.1 ⊆ U' ∩ U} := ⟨⟨⊥, empty_subset _⟩⟩,
rw [ennreal.supr_add],
refine supr_le _, rintro ⟨L, hL⟩, simp only [subset_inter_iff] at hL,
have : ↑U' \ U ⊆ U' \ L.1 := diff_subset_diff_right hL.2,
refine le_trans (add_le_add_left (μ.outer_measure.mono' this) _) _,
rw μ.outer_measure_of_is_open (↑U' \ L.1) (is_open.sdiff U'.2 L.2.is_closed),
simp only [inner_content, supr_subtype'], rw [opens.coe_mk],
haveI : nonempty {M : compacts G // M.1 ⊆ ↑U' \ L.1} := ⟨⟨⊥, empty_subset _⟩⟩,
rw [ennreal.add_supr], refine supr_le _, rintro ⟨M, hM⟩, simp only [subset_diff] at hM,
have : (L ⊔ M).1 ⊆ U',
{ simp only [union_subset_iff, compacts.sup_val, hM, hL, and_self] },
rw μ.outer_measure_of_is_open ↑U' U'.2,
refine le_trans (ge_of_eq _) (μ.le_inner_content _ _ this),
exact μ.sup_disjoint _ _ hM.2.symm,
end
/-- The measure induced by the outer measure coming from a content, on the Borel sigma-algebra. -/
protected def measure : measure G := μ.outer_measure.to_measure μ.borel_le_caratheodory
lemma measure_apply {s : set G} (hs : measurable_set s) : μ.measure s = μ.outer_measure s :=
to_measure_apply _ _ hs
/-- In a locally compact space, any measure constructed from a content is regular. -/
instance regular [locally_compact_space G] : μ.measure.regular :=
begin
haveI : μ.measure.outer_regular,
{ refine ⟨λ A hA r (hr : _ < _), _⟩,
rw [μ.measure_apply hA, outer_measure_eq_infi] at hr,
simp only [infi_lt_iff] at hr,
rcases hr with ⟨U, hUo, hAU, hr⟩,
rw [← μ.outer_measure_of_is_open U hUo, ← μ.measure_apply hUo.measurable_set] at hr,
exact ⟨U, hAU, hUo, hr⟩ },
split,
{ intros K hK,
rw [measure_apply _ hK.measurable_set],
exact μ.outer_measure_lt_top_of_is_compact hK },
{ intros U hU r hr,
rw [measure_apply _ hU.measurable_set, μ.outer_measure_of_is_open U hU] at hr,
simp only [inner_content, lt_supr_iff] at hr,
rcases hr with ⟨K, hKU, hr⟩,
refine ⟨K.1, hKU, K.2, hr.trans_le _⟩,
exact (μ.le_outer_measure_compacts K).trans (le_to_measure_apply _ _ _) },
end
end content
end measure_theory
|
a1fd5304f826302e5bac73bff5f92d8f786b544c | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/number_theory/bernoulli.lean | a5c6fef8ba45471e0dcd2ef8ef996b4b3eca763c | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 2,900 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.rat
import data.fintype.card
/-!
# Bernoulli numbers
The Bernoulli numbers are a sequence of numbers that frequently show up in number theory.
For example, they show up in the Taylor series of many trigonometric and hyperbolic functions,
and also as (integral multiples of products of powers of `π` and)
special values of the Riemann zeta function.
(Note: these facts are not yet available in mathlib)
In this file, we provide the definition,
and the basic fact (`sum_bernoulli`) that
$$ \sum_{k < n} \binom{n}{k} * B_k = n, $$
where $B_k$ denotes the the $k$-th Bernoulli number.
-/
open_locale big_operators
/-- The Bernoulli numbers:
the $n$-th Bernoulli number $B_n$ is defined recursively via
$$B_n = \sum_{k < n} \binom{n}{k} * \frac{B_k}{n+1-k}$$ -/
def bernoulli : ℕ → ℚ :=
well_founded.fix nat.lt_wf
(λ n bernoulli, 1 - ∑ k : fin n, (n.choose k) * bernoulli k k.2 / (n + 1 - k))
lemma bernoulli_def' (n : ℕ) :
bernoulli n = 1 - ∑ k : fin n, (n.choose k) * (bernoulli k) / (n + 1 - k) :=
well_founded.fix_eq _ _ _
lemma bernoulli_def (n : ℕ) :
bernoulli n = 1 - ∑ k in finset.range n, (n.choose k) * (bernoulli k) / (n + 1 - k) :=
by { rw [bernoulli_def', ← fin.sum_univ_eq_sum_range], refl }
@[simp] lemma bernoulli_zero : bernoulli 0 = 1 := rfl
@[simp] lemma bernoulli_one : bernoulli 1 = 1/2 :=
begin
rw [bernoulli_def],
repeat { try { rw [finset.sum_range_succ] }, try { rw [nat.choose_succ_succ] }, simp, norm_num1 }
end
@[simp] lemma bernoulli_two : bernoulli 2 = 1/6 :=
begin
rw [bernoulli_def],
repeat { try { rw [finset.sum_range_succ] }, try { rw [nat.choose_succ_succ] }, simp, norm_num1 }
end
@[simp] lemma bernoulli_three : bernoulli 3 = 0 :=
begin
rw [bernoulli_def],
repeat { try { rw [finset.sum_range_succ] }, try { rw [nat.choose_succ_succ] }, simp, norm_num1 }
end
@[simp] lemma bernoulli_four : bernoulli 4 = -1/30 :=
begin
rw [bernoulli_def],
repeat { try { rw [finset.sum_range_succ] }, try { rw [nat.choose_succ_succ] }, simp, norm_num1 }
end
@[simp] lemma sum_bernoulli (n : ℕ) :
∑ k in finset.range n, (n.choose k : ℚ) * bernoulli k = n :=
begin
induction n with n ih, { simp },
rw [finset.sum_range_succ],
rw [nat.choose_succ_self_right],
rw [bernoulli_def, mul_sub, mul_one, sub_add_eq_add_sub, sub_eq_iff_eq_add],
rw [add_left_cancel_iff, finset.mul_sum, finset.sum_congr rfl],
intros k hk, rw finset.mem_range at hk,
rw [mul_div_right_comm, ← mul_assoc],
congr' 1,
rw [← mul_div_assoc, eq_div_iff],
{ rw [mul_comm ((n+1 : ℕ) : ℚ)],
have hk' : k ≤ n + 1, by linarith,
rw_mod_cast nat.choose_mul_succ_eq n k },
{ contrapose! hk with H, rw sub_eq_zero at H, norm_cast at H, linarith }
end
|
aaa19ff31c3bf0131d17339ac11c95e73deab3c8 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/choose_test.lean | 21e8668cd907103cb584864566252beb35d7a4a7 | [
"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 | 163 | lean | import data.encodable
open nat encodable
theorem ex : ∃ x : nat, x > 3 :=
exists.intro 6 dec_trivial
reveal ex
eval choose ex
example : choose ex = 4 :=
rfl
|
928f29ac815fd173184c33b390518f9893969e1b | 367134ba5a65885e863bdc4507601606690974c1 | /src/order/filter/extr.lean | 286559e5a500e38dc9e4d704a8aa4491506e550f | [
"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 | 21,292 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import order.filter.basic
/-!
# Minimum and maximum w.r.t. a filter and on a aet
## Main Definitions
This file defines six predicates of the form `is_A_B`, where `A` is `min`, `max`, or `extr`,
and `B` is `filter` or `on`.
* `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a`;
* `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a`;
* `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a`.
Similar predicates with `_on` suffix are particular cases for `l = 𝓟 s`.
## Main statements
### Change of the filter (set) argument
* `is_*_filter.filter_mono` : replace the filter with a smaller one;
* `is_*_filter.filter_inf` : replace a filter `l` with `l ⊓ l'`;
* `is_*_on.on_subset` : restrict to a smaller set;
* `is_*_on.inter` : replace a set `s` wtih `s ∩ t`.
### Composition
* `is_*_*.comp_mono` : if `x` is an extremum for `f` and `g` is a monotone function,
then `x` is an extremum for `g ∘ f`;
* `is_*_*.comp_antimono` : similarly for the case of monotonically decreasing `g`;
* `is_*_*.bicomp_mono` : if `x` is an extremum of the same type for `f` and `g`
and a binary operation `op` is monotone in both arguments, then `x` is an extremum
of the same type for `λ x, op (f x) (g x)`.
* `is_*_filter.comp_tendsto` : if `g x` is an extremum for `f` w.r.t. `l'` and `tendsto g l l'`,
then `x` is an extremum for `f ∘ g` w.r.t. `l`.
* `is_*_on.on_preimage` : if `g x` is an extremum for `f` on `s`, then `x` is an extremum
for `f ∘ g` on `g ⁻¹' s`.
### Algebraic operations
* `is_*_*.add` : if `x` is an extremum of the same type for two functions,
then it is an extremum of the same type for their sum;
* `is_*_*.neg` : if `x` is an extremum for `f`, then it is an extremum
of the opposite type for `-f`;
* `is_*_*.sub` : if `x` is an a minimum for `f` and a maximum for `g`,
then it is a minimum for `f - g` and a maximum for `g - f`;
* `is_*_*.max`, `is_*_*.min`, `is_*_*.sup`, `is_*_*.inf` : similarly for `is_*_*.add`
for pointwise `max`, `min`, `sup`, `inf`, respectively.
### Miscellaneous definitions
* `is_*_*_const` : any point is both a minimum and maximum for a constant function;
* `is_min/max_*.is_ext` : any minimum/maximum point is an extremum;
* `is_*_*.dual`, `is_*_*.undual`: conversion between codomains `α` and `dual α`;
## Missing features (TODO)
* Multiplication and division;
* `is_*_*.bicompl` : if `x` is a minimum for `f`, `y` is a minimum for `g`, and `op` is a monotone
binary operation, then `(x, y)` is a minimum for `uncurry (bicompl op f g)`. From this point of view,
`is_*_*.bicomp` is a composition
* It would be nice to have a tactic that specializes `comp_(anti)mono` or `bicomp_mono`
based on a proof of monotonicity of a given (binary) function. The tactic should maintain a `meta`
list of known (anti)monotone (binary) functions with their names, as well as a list of special
types of filters, and define the missing lemmas once one of these two lists grows.
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
open set filter
open_locale filter
section preorder
variables [preorder β] [preorder γ]
variables (f : α → β) (s : set α) (l : filter α) (a : α)
/-! ### Definitions -/
/-- `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a` -/
def is_min_filter : Prop := ∀ᶠ x in l, f a ≤ f x
/-- `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a` -/
def is_max_filter : Prop := ∀ᶠ x in l, f x ≤ f a
/-- `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a` -/
def is_extr_filter : Prop := is_min_filter f l a ∨ is_max_filter f l a
/-- `is_min_on f s a` means that `f a ≤ f x` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/
def is_min_on := is_min_filter f (𝓟 s) a
/-- `is_max_on f s a` means that `f x ≤ f a` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/
def is_max_on := is_max_filter f (𝓟 s) a
/-- `is_extr_on f s a` means `is_min_on f s a` or `is_max_on f s a` -/
def is_extr_on : Prop := is_extr_filter f (𝓟 s) a
variables {f s a l} {t : set α} {l' : filter α}
lemma is_extr_on.elim {p : Prop} :
is_extr_on f s a → (is_min_on f s a → p) → (is_max_on f s a → p) → p :=
or.elim
lemma is_min_on_iff : is_min_on f s a ↔ ∀ x ∈ s, f a ≤ f x := iff.rfl
lemma is_max_on_iff : is_max_on f s a ↔ ∀ x ∈ s, f x ≤ f a := iff.rfl
lemma is_min_on_univ_iff : is_min_on f univ a ↔ ∀ x, f a ≤ f x :=
univ_subset_iff.trans eq_univ_iff_forall
lemma is_max_on_univ_iff : is_max_on f univ a ↔ ∀ x, f x ≤ f a :=
univ_subset_iff.trans eq_univ_iff_forall
lemma is_min_filter.tendsto_principal_Ici (h : is_min_filter f l a) :
tendsto f l (𝓟 $ Ici (f a)) :=
tendsto_principal.2 h
lemma is_max_filter.tendsto_principal_Iic (h : is_max_filter f l a) :
tendsto f l (𝓟 $ Iic (f a)) :=
tendsto_principal.2 h
/-! ### Conversion to `is_extr_*` -/
lemma is_min_filter.is_extr : is_min_filter f l a → is_extr_filter f l a := or.inl
lemma is_max_filter.is_extr : is_max_filter f l a → is_extr_filter f l a := or.inr
lemma is_min_on.is_extr (h : is_min_on f s a) : is_extr_on f s a := h.is_extr
lemma is_max_on.is_extr (h : is_max_on f s a) : is_extr_on f s a := h.is_extr
/-! ### Constant function -/
lemma is_min_filter_const {b : β} : is_min_filter (λ _, b) l a :=
univ_mem_sets' $ λ _, le_refl _
lemma is_max_filter_const {b : β} : is_max_filter (λ _, b) l a :=
univ_mem_sets' $ λ _, le_refl _
lemma is_extr_filter_const {b : β} : is_extr_filter (λ _, b) l a := is_min_filter_const.is_extr
lemma is_min_on_const {b : β} : is_min_on (λ _, b) s a := is_min_filter_const
lemma is_max_on_const {b : β} : is_max_on (λ _, b) s a := is_max_filter_const
lemma is_extr_on_const {b : β} : is_extr_on (λ _, b) s a := is_extr_filter_const
/-! ### Order dual -/
lemma is_min_filter_dual_iff : @is_min_filter α (order_dual β) _ f l a ↔ is_max_filter f l a :=
iff.rfl
lemma is_max_filter_dual_iff : @is_max_filter α (order_dual β) _ f l a ↔ is_min_filter f l a :=
iff.rfl
lemma is_extr_filter_dual_iff : @is_extr_filter α (order_dual β) _ f l a ↔ is_extr_filter f l a :=
or_comm _ _
alias is_min_filter_dual_iff ↔ is_min_filter.undual is_max_filter.dual
alias is_max_filter_dual_iff ↔ is_max_filter.undual is_min_filter.dual
alias is_extr_filter_dual_iff ↔ is_extr_filter.undual is_extr_filter.dual
lemma is_min_on_dual_iff : @is_min_on α (order_dual β) _ f s a ↔ is_max_on f s a := iff.rfl
lemma is_max_on_dual_iff : @is_max_on α (order_dual β) _ f s a ↔ is_min_on f s a := iff.rfl
lemma is_extr_on_dual_iff : @is_extr_on α (order_dual β) _ f s a ↔ is_extr_on f s a := or_comm _ _
alias is_min_on_dual_iff ↔ is_min_on.undual is_max_on.dual
alias is_max_on_dual_iff ↔ is_max_on.undual is_min_on.dual
alias is_extr_on_dual_iff ↔ is_extr_on.undual is_extr_on.dual
/-! ### Operations on the filter/set -/
lemma is_min_filter.filter_mono (h : is_min_filter f l a) (hl : l' ≤ l) :
is_min_filter f l' a := hl h
lemma is_max_filter.filter_mono (h : is_max_filter f l a) (hl : l' ≤ l) :
is_max_filter f l' a := hl h
lemma is_extr_filter.filter_mono (h : is_extr_filter f l a) (hl : l' ≤ l) :
is_extr_filter f l' a :=
h.elim (λ h, (h.filter_mono hl).is_extr) (λ h, (h.filter_mono hl).is_extr)
lemma is_min_filter.filter_inf (h : is_min_filter f l a) (l') : is_min_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_max_filter.filter_inf (h : is_max_filter f l a) (l') : is_max_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_extr_filter.filter_inf (h : is_extr_filter f l a) (l') : is_extr_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_min_on.on_subset (hf : is_min_on f t a) (h : s ⊆ t) : is_min_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_max_on.on_subset (hf : is_max_on f t a) (h : s ⊆ t) : is_max_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_extr_on.on_subset (hf : is_extr_on f t a) (h : s ⊆ t) : is_extr_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_min_on.inter (hf : is_min_on f s a) (t) : is_min_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
lemma is_max_on.inter (hf : is_max_on f s a) (t) : is_max_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
lemma is_extr_on.inter (hf : is_extr_on f s a) (t) : is_extr_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
/-! ### Composition with (anti)monotone functions -/
lemma is_min_filter.comp_mono (hf : is_min_filter f l a) {g : β → γ} (hg : monotone g) :
is_min_filter (g ∘ f) l a :=
mem_sets_of_superset hf $ λ x hx, hg hx
lemma is_max_filter.comp_mono (hf : is_max_filter f l a) {g : β → γ} (hg : monotone g) :
is_max_filter (g ∘ f) l a :=
mem_sets_of_superset hf $ λ x hx, hg hx
lemma is_extr_filter.comp_mono (hf : is_extr_filter f l a) {g : β → γ} (hg : monotone g) :
is_extr_filter (g ∘ f) l a :=
hf.elim (λ hf, (hf.comp_mono hg).is_extr) (λ hf, (hf.comp_mono hg).is_extr)
lemma is_min_filter.comp_antimono (hf : is_min_filter f l a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_max_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_max_filter.comp_antimono (hf : is_max_filter f l a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_min_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_extr_filter.comp_antimono (hf : is_extr_filter f l a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_extr_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_min_on.comp_mono (hf : is_min_on f s a) {g : β → γ} (hg : monotone g) :
is_min_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_max_on.comp_mono (hf : is_max_on f s a) {g : β → γ} (hg : monotone g) :
is_max_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_extr_on.comp_mono (hf : is_extr_on f s a) {g : β → γ} (hg : monotone g) :
is_extr_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_min_on.comp_antimono (hf : is_min_on f s a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_max_on (g ∘ f) s a :=
hf.comp_antimono hg
lemma is_max_on.comp_antimono (hf : is_max_on f s a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_min_on (g ∘ f) s a :=
hf.comp_antimono hg
lemma is_extr_on.comp_antimono (hf : is_extr_on f s a) {g : β → γ}
(hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) :
is_extr_on (g ∘ f) s a :=
hf.comp_antimono hg
lemma is_min_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_min_filter f l a) {g : α → γ} (hg : is_min_filter g l a) :
is_min_filter (λ x, op (f x) (g x)) l a :=
mem_sets_of_superset (inter_mem_sets hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx
lemma is_max_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_max_filter f l a) {g : α → γ} (hg : is_max_filter g l a) :
is_max_filter (λ x, op (f x) (g x)) l a :=
mem_sets_of_superset (inter_mem_sets hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx
-- No `extr` version because we need `hf` and `hg` to be of the same kind
lemma is_min_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_min_on f s a) {g : α → γ} (hg : is_min_on g s a) :
is_min_on (λ x, op (f x) (g x)) s a :=
hf.bicomp_mono hop hg
lemma is_max_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_max_on f s a) {g : α → γ} (hg : is_max_on g s a) :
is_max_on (λ x, op (f x) (g x)) s a :=
hf.bicomp_mono hop hg
/-! ### Composition with `tendsto` -/
lemma is_min_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_min_filter f l (g b))
(hg : tendsto g l' l) :
is_min_filter (f ∘ g) l' b :=
hg hf
lemma is_max_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_max_filter f l (g b))
(hg : tendsto g l' l) :
is_max_filter (f ∘ g) l' b :=
hg hf
lemma is_extr_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_extr_filter f l (g b))
(hg : tendsto g l' l) :
is_extr_filter (f ∘ g) l' b :=
hf.elim (λ hf, (hf.comp_tendsto hg).is_extr) (λ hf, (hf.comp_tendsto hg).is_extr)
lemma is_min_on.on_preimage (g : δ → α) {b : δ} (hf : is_min_on f s (g b)) :
is_min_on (f ∘ g) (g ⁻¹' s) b :=
hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _)
lemma is_max_on.on_preimage (g : δ → α) {b : δ} (hf : is_max_on f s (g b)) :
is_max_on (f ∘ g) (g ⁻¹' s) b :=
hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _)
lemma is_extr_on.on_preimage (g : δ → α) {b : δ} (hf : is_extr_on f s (g b)) :
is_extr_on (f ∘ g) (g ⁻¹' s) b :=
hf.elim (λ hf, (hf.on_preimage g).is_extr) (λ hf, (hf.on_preimage g).is_extr)
end preorder
/-! ### Pointwise addition -/
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.add (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x + g x) l a :=
show is_min_filter (λ x, f x + g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg
lemma is_max_filter.add (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x + g x) l a :=
show is_max_filter (λ x, f x + g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg
lemma is_min_on.add (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x + g x) s a :=
hf.add hg
lemma is_max_on.add (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x + g x) s a :=
hf.add hg
end ordered_add_comm_monoid
/-! ### Pointwise negation and subtraction -/
section ordered_add_comm_group
variables [ordered_add_comm_group β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.neg (hf : is_min_filter f l a) : is_max_filter (λ x, -f x) l a :=
hf.comp_antimono (λ x y hx, neg_le_neg hx)
lemma is_max_filter.neg (hf : is_max_filter f l a) : is_min_filter (λ x, -f x) l a :=
hf.comp_antimono (λ x y hx, neg_le_neg hx)
lemma is_extr_filter.neg (hf : is_extr_filter f l a) : is_extr_filter (λ x, -f x) l a :=
hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr)
lemma is_min_on.neg (hf : is_min_on f s a) : is_max_on (λ x, -f x) s a :=
hf.comp_antimono (λ x y hx, neg_le_neg hx)
lemma is_max_on.neg (hf : is_max_on f s a) : is_min_on (λ x, -f x) s a :=
hf.comp_antimono (λ x y hx, neg_le_neg hx)
lemma is_extr_on.neg (hf : is_extr_on f s a) : is_extr_on (λ x, -f x) s a :=
hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr)
lemma is_min_filter.sub (hf : is_min_filter f l a) (hg : is_max_filter g l a) :
is_min_filter (λ x, f x - g x) l a :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma is_max_filter.sub (hf : is_max_filter f l a) (hg : is_min_filter g l a) :
is_max_filter (λ x, f x - g x) l a :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma is_min_on.sub (hf : is_min_on f s a) (hg : is_max_on g s a) :
is_min_on (λ x, f x - g x) s a :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma is_max_on.sub (hf : is_max_on f s a) (hg : is_min_on g s a) :
is_max_on (λ x, f x - g x) s a :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
end ordered_add_comm_group
/-! ### Pointwise `sup`/`inf` -/
section semilattice_sup
variables [semilattice_sup β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.sup (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x ⊔ g x) l a :=
show is_min_filter (λ x, f x ⊔ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg
lemma is_max_filter.sup (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x ⊔ g x) l a :=
show is_max_filter (λ x, f x ⊔ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg
lemma is_min_on.sup (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x ⊔ g x) s a :=
hf.sup hg
lemma is_max_on.sup (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x ⊔ g x) s a :=
hf.sup hg
end semilattice_sup
section semilattice_inf
variables [semilattice_inf β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.inf (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x ⊓ g x) l a :=
show is_min_filter (λ x, f x ⊓ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg
lemma is_max_filter.inf (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x ⊓ g x) l a :=
show is_max_filter (λ x, f x ⊓ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg
lemma is_min_on.inf (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x ⊓ g x) s a :=
hf.inf hg
lemma is_max_on.inf (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x ⊓ g x) s a :=
hf.inf hg
end semilattice_inf
/-! ### Pointwise `min`/`max` -/
section linear_order
variables [linear_order β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.min (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, min (f x) (g x)) l a :=
show is_min_filter (λ x, min (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg
lemma is_max_filter.min (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, min (f x) (g x)) l a :=
show is_max_filter (λ x, min (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg
lemma is_min_on.min (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, min (f x) (g x)) s a :=
hf.min hg
lemma is_max_on.min (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, min (f x) (g x)) s a :=
hf.min hg
lemma is_min_filter.max (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, max (f x) (g x)) l a :=
show is_min_filter (λ x, max (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg
lemma is_max_filter.max (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, max (f x) (g x)) l a :=
show is_max_filter (λ x, max (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg
lemma is_min_on.max (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, max (f x) (g x)) s a :=
hf.max hg
lemma is_max_on.max (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, max (f x) (g x)) s a :=
hf.max hg
end linear_order
section eventually
/-! ### Relation with `eventually` comparisons of two functions -/
lemma filter.eventually_le.is_max_filter {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (hle : g ≤ᶠ[l] f) (hfga : f a = g a) (h : is_max_filter f l a) :
is_max_filter g l a :=
begin
refine hle.mp (h.mono $ λ x hf hgf, _),
rw ← hfga,
exact le_trans hgf hf
end
lemma is_max_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α}
(h : is_max_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_max_filter g l a :=
heq.symm.le.is_max_filter hfga h
lemma filter.eventually_eq.is_max_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_max_filter f l a ↔ is_max_filter g l a :=
⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩
lemma filter.eventually_le.is_min_filter {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (hle : f ≤ᶠ[l] g) (hfga : f a = g a) (h : is_min_filter f l a) :
is_min_filter g l a :=
@filter.eventually_le.is_max_filter _ (order_dual β) _ _ _ _ _ hle hfga h
lemma is_min_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α}
(h : is_min_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_min_filter g l a :=
heq.le.is_min_filter hfga h
lemma filter.eventually_eq.is_min_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_min_filter f l a ↔ is_min_filter g l a :=
⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩
lemma is_extr_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α}
(h : is_extr_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_extr_filter g l a :=
begin
rw is_extr_filter at *,
rwa [← heq.is_max_filter_iff hfga, ← heq.is_min_filter_iff hfga],
end
lemma filter.eventually_eq.is_extr_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_extr_filter f l a ↔ is_extr_filter g l a :=
⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩
end eventually
|
f2edfd1249e382c60b08ca61830a627d31759cc6 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/slow_tc_synth.lean | a2ba52efbb6ade868b14c6fbf713cf160bc67e7d | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 3,041 | lean | -- Generalized version of type classes with type class parameters that are
-- common in mathlib.
-- a could be topological_space, b could be ring, ...,
-- y is topological_ring, and z is topological_group
class a (α : Type)
instance a1 (α) : a α := ⟨⟩
instance a2 (α) : a α := ⟨⟩
instance a3 (α) : a α := ⟨⟩
instance a4 (α) : a α := ⟨⟩
instance a5 (α) : a α := ⟨⟩
instance a6 (α) : a α := ⟨⟩
instance a7 (α) : a α := ⟨⟩
instance a8 (α) : a α := ⟨⟩
instance a9 (α) : a α := ⟨⟩
instance a0 (α) : a α := ⟨⟩
class b (α : Type)
instance b1 (α) : b α := ⟨⟩
instance b2 (α) : b α := ⟨⟩
instance b3 (α) : b α := ⟨⟩
instance b4 (α) : b α := ⟨⟩
instance b5 (α) : b α := ⟨⟩
instance b6 (α) : b α := ⟨⟩
instance b7 (α) : b α := ⟨⟩
instance b8 (α) : b α := ⟨⟩
instance b9 (α) : b α := ⟨⟩
instance b0 (α) : b α := ⟨⟩
class c (α : Type)
instance c1 (α) : c α := ⟨⟩
instance c2 (α) : c α := ⟨⟩
instance c3 (α) : c α := ⟨⟩
instance c4 (α) : c α := ⟨⟩
instance c5 (α) : c α := ⟨⟩
instance c6 (α) : c α := ⟨⟩
instance c7 (α) : c α := ⟨⟩
instance c8 (α) : c α := ⟨⟩
instance c9 (α) : c α := ⟨⟩
instance c0 (α) : c α := ⟨⟩
class d (α : Type)
instance d1 (α) : d α := ⟨⟩
instance d2 (α) : d α := ⟨⟩
instance d3 (α) : d α := ⟨⟩
instance d4 (α) : d α := ⟨⟩
instance d5 (α) : d α := ⟨⟩
instance d6 (α) : d α := ⟨⟩
instance d7 (α) : d α := ⟨⟩
instance d8 (α) : d α := ⟨⟩
instance d9 (α) : d α := ⟨⟩
instance d0 (α) : d α := ⟨⟩
class e (α : Type)
instance e1 (α) : e α := ⟨⟩
instance e2 (α) : e α := ⟨⟩
instance e3 (α) : e α := ⟨⟩
instance e4 (α) : e α := ⟨⟩
instance e5 (α) : e α := ⟨⟩
instance e6 (α) : e α := ⟨⟩
instance e7 (α) : e α := ⟨⟩
instance e8 (α) : e α := ⟨⟩
instance e9 (α) : e α := ⟨⟩
instance e0 (α) : e α := ⟨⟩
class f (α : Type)
instance f1 (α) : f α := ⟨⟩
instance f2 (α) : f α := ⟨⟩
instance f3 (α) : f α := ⟨⟩
instance f4 (α) : f α := ⟨⟩
instance f5 (α) : f α := ⟨⟩
instance f6 (α) : f α := ⟨⟩
instance f7 (α) : f α := ⟨⟩
instance f8 (α) : f α := ⟨⟩
instance f9 (α) : f α := ⟨⟩
instance f0 (α) : f α := ⟨⟩
class g (α : Type)
instance g1 (α) : g α := ⟨⟩
instance g2 (α) : g α := ⟨⟩
instance g3 (α) : g α := ⟨⟩
instance g4 (α) : g α := ⟨⟩
instance g5 (α) : g α := ⟨⟩
instance g6 (α) : g α := ⟨⟩
instance g7 (α) : g α := ⟨⟩
instance g8 (α) : g α := ⟨⟩
instance g9 (α) : g α := ⟨⟩
instance g0 (α) : g α := ⟨⟩
class y (α : Type) [a α] [b α] [c α] [d α] [e α] [f α] [g α]
instance y1 (α) : y α := ⟨⟩
class z (α : Type) [a α] [b α] [c α] [d α] [e α] [f α]
instance z.to_y (α : Type) [a α] [b α] [c α] [d α] [e α] [f α] [g α] [z α] : y α :=
⟨⟩
example : y unit :=
by apply_instance |
81679cd0df17646ea2caf9137040b04422711f11 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Compiler/LCNF/ForEachExpr.lean | 1bc99d153ed7914ecf014af9598f26ae3f04f2ef | [
"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 | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 1,732 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.ForEachExpr
import Lean.Compiler.LCNF.Basic
namespace Lean.Compiler.LCNF
partial def Code.forEachExpr [STWorld ω m] [MonadLiftT (ST ω) m] [Monad m] (f : Expr → m Unit) (c : Code) (skipTypes := false) : m Unit := do
visit c |>.run
where
visit (c : Code) : MonadCacheT Expr Unit m Unit := do
match c with
| .let decl k =>
visitType decl.type
visitExpr decl.value
visit k
| .jp decl k | .fun decl k =>
visitType decl.type
decl.params.forM visitParam
visit decl.value
visit k
| .unreach type => visitType type
| .return .. => return ()
| .jmp _ args => args.forM visitExpr
| .cases c => visitType c.resultType; c.alts.forM fun alt => do
match alt with
| .default k => visit k
| .alt _ ps k => ps.forM visitParam; visit k
visitParam (p : Param) : MonadCacheT Expr Unit m Unit :=
visitType p.type
visitExpr (e : Expr) : MonadCacheT Expr Unit m Unit :=
ForEachExpr.visit (fun e => f e *> return true) e
visitType (e : Expr) : MonadCacheT Expr Unit m Unit :=
unless skipTypes do
visitExpr e
def Decl.forEachExpr [STWorld ω m] [MonadLiftT (ST ω) m] [Monad m] (f : Expr → m Unit) (decl : Decl) (skipTypes := false) : m Unit := do
visit |>.run
where
visit : MonadCacheT Expr Unit m Unit := do
Code.forEachExpr.visitType f decl.type (skipTypes := skipTypes)
decl.params.forM (Code.forEachExpr.visitParam f (skipTypes := skipTypes))
Code.forEachExpr.visit f decl.value (skipTypes := skipTypes)
end Lean.Compiler.LCNF |
73ae361e948e3be019958296d7fcaa3b7cabbb98 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/analysis/complex/isometry.lean | 3d8959b7db9c0d6be2cec700ca1687092c60e109 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,955 | lean | /-
Copyright (c) 2021 François Sunatori. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: François Sunatori
-/
import analysis.complex.basic
import data.complex.exponential
import data.real.sqrt
import analysis.normed_space.linear_isometry
import algebra.group.units
/-!
# Isometries of the Complex Plane
The lemma `linear_isometry_complex` states the classification of isometries in the complex plane.
Specifically, isometries with rotations but without translation.
The proof involves:
1. creating a linear isometry `g` with two fixed points, `g(0) = 0`, `g(1) = 1`
2. applying `linear_isometry_complex_aux` to `g`
The proof of `linear_isometry_complex_aux` is separated in the following parts:
1. show that the real parts match up: `linear_isometry.re_apply_eq_re`
2. show that I maps to either I or -I
3. every z is a linear combination of a + b * I
## References
* [Isometries of the Complex Plane](http://helmut.knaust.info/mediawiki/images/b/b5/Iso.pdf)
-/
noncomputable theory
open complex
local notation `|` x `|` := complex.abs x
lemma linear_isometry.re_apply_eq_re_of_add_conj_eq (f : ℂ →ₗᵢ[ℝ] ℂ)
(h₃ : ∀ z, z + conj z = f z + conj (f z)) (z : ℂ) : (f z).re = z.re :=
by simpa [ext_iff, add_re, add_im, conj_re, conj_im, ←two_mul,
(show (2 : ℝ) ≠ 0, by simp [two_ne_zero'])] using (h₃ z).symm
lemma linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ}
(h₁ : ∀ z, |f z| = |z|) (h₂ : ∀ z, (f z).re = z.re) (z : ℂ) :
(f z).im = z.im ∨ (f z).im = -z.im :=
begin
specialize h₁ z,
simp only [complex.abs] at h₁,
rwa [real.sqrt_inj (norm_sq_nonneg _) (norm_sq_nonneg _), norm_sq_apply (f z), norm_sq_apply z,
h₂, add_left_cancel_iff, mul_self_eq_mul_self_iff] at h₁,
end
lemma linear_isometry.abs_apply_sub_one_eq_abs_sub_one {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) :
∥f z - 1∥ = ∥z - 1∥ :=
by rw [←linear_isometry.norm_map f (z - 1), linear_isometry.map_sub, h]
lemma linear_isometry.im_apply_eq_im {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) :
z + conj z = f z + conj (f z) :=
begin
have := linear_isometry.abs_apply_sub_one_eq_abs_sub_one h z,
apply_fun λ x, x ^ 2 at this,
simp only [norm_eq_abs, ←norm_sq_eq_abs] at this,
rw [←of_real_inj, ←mul_conj, ←mul_conj] at this,
rw [conj.map_sub, conj.map_sub] at this,
simp only [sub_mul, mul_sub, one_mul, mul_one] at this,
rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs, linear_isometry.norm_map] at this,
rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs] at this,
simp only [sub_sub, sub_right_inj, mul_one, of_real_pow, ring_hom.map_one, norm_eq_abs] at this,
simp only [add_sub, sub_left_inj] at this,
rw [add_comm, ←this, add_comm],
end
lemma linear_isometry.re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) : (f z).re = z.re :=
begin
apply linear_isometry.re_apply_eq_re_of_add_conj_eq,
intro z,
apply linear_isometry.im_apply_eq_im h,
end
lemma linear_isometry_complex_aux (f : ℂ →ₗᵢ[ℝ] ℂ) (h : f 1 = 1) :
(∀ z, f z = z) ∨ (∀ z, f z = conj z) :=
begin
have h0 : f I = I ∨ f I = -I,
{ have : |f I| = 1,
{ rw [←norm_eq_abs, linear_isometry.norm_map, norm_eq_abs, abs_I] },
simp only [ext_iff, ←and_or_distrib_left, neg_re, I_re, neg_im, neg_zero],
split,
{ rw ←I_re,
rw linear_isometry.re_apply_eq_re h },
{ apply linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re,
{ intro z, rw [←norm_eq_abs, ←norm_eq_abs, linear_isometry.norm_map] },
{ intro z, rw linear_isometry.re_apply_eq_re h } } },
refine or.imp (λ h1, _) (λ h1 z, _) h0,
{ suffices : f.to_linear_map = linear_isometry.id.to_linear_map,
{ simp [this, ←linear_isometry.coe_to_linear_map, linear_map.id_apply] },
apply basis.ext basis_one_I,
intro i,
fin_cases i,
{ simp [h] },
{ simp only [matrix.head_cons, linear_isometry.coe_to_linear_map,
linear_map.id_coe, id.def, matrix.cons_val_one], simpa } },
{ suffices : f.to_linear_map = conj_li.to_linear_map,
{ rw [←linear_isometry.coe_to_linear_map, this],
simp only [linear_isometry.coe_to_linear_map], refl },
apply basis.ext basis_one_I,
intro i,
fin_cases i,
{ simp only [h, linear_isometry.coe_to_linear_map, matrix.cons_val_zero], simpa },
{ simp only [matrix.head_cons, linear_isometry.coe_to_linear_map,
linear_map.id_coe, id.def, matrix.cons_val_one], simpa } },
end
lemma linear_isometry_complex (f : ℂ →ₗᵢ[ℝ] ℂ) :
∃ a : ℂ, |a| = 1 ∧ ((∀ z, f z = a * z) ∨ (∀ z, f z = a * conj z)) :=
begin
let a := f 1,
use a,
split,
{ simp only [← norm_eq_abs, a, linear_isometry.norm_map, norm_one] },
{ let g : ℂ →ₗᵢ[ℝ] ℂ :=
{ to_fun := λ z, a⁻¹ * f z,
map_add' := by {
intros x y,
rw linear_isometry.map_add,
rw mul_add },
map_smul' := by {
intros m x,
rw linear_isometry.map_smul,
rw algebra.mul_smul_comm },
norm_map' := by {
intros x,
simp,
suffices : ∥f 1∥⁻¹ * ∥f x∥ = ∥x∥, { simpa },
iterate 2 { rw linear_isometry.norm_map },
simp } },
have hg1 : g 1 = 1 := by {
change a⁻¹ * a = 1,
rw inv_mul_cancel,
rw ← norm_sq_pos,
rw norm_sq_eq_abs,
change 0 < ∥a∥ ^ 2,
rw linear_isometry.norm_map,
simp,
simp [zero_lt_one] },
have h : (∀ z, g z = z) ∨ (∀ z, g z = conj z) := linear_isometry_complex_aux g hg1,
change (∀ z, a⁻¹ * f z = z) ∨ (∀ z, a⁻¹ * f z = conj z) at h,
have ha : a ≠ 0 := by {
rw ← norm_sq_pos,
rw norm_sq_eq_abs,
change 0 < ∥a∥ ^ 2,
rw linear_isometry.norm_map,
simp,
simp [zero_lt_one] },
simpa only [← inv_mul_eq_iff_eq_mul' ha] }
end
|
468b3fcb91ef7bb23fd6459d8e36a392cff2865b | 3dc4623269159d02a444fe898d33e8c7e7e9461b | /.github/workflows/sugar_yoneda.lean | 41fd12b5d9dab0e56ce138581c42acf6ed358c9f | [] | no_license | Or7ando/lean | cc003e6c41048eae7c34aa6bada51c9e9add9e66 | d41169cf4e416a0d42092fb6bdc14131cee9dd15 | refs/heads/master | 1,650,600,589,722 | 1,587,262,906,000 | 1,587,262,906,000 | 255,387,160 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,698 | lean | import to_product
open category_theory
open opposite
open category_theory.limits
open category_theory.category
open Product_stuff
universes v u
variables {C : Type u}
variables [𝒞 : category.{v} C]
variables [has_binary_products.{v} C][has_terminal.{v} C]
include 𝒞
namespace Yoneda
def Yo (R : C)(A :C) := (yoneda.obj A).obj (op R)
def Yo_ (R : C) {A B : C}(φ : A ⟶ B) := ((yoneda.map φ).app (op R) : Yo R A ⟶ Yo R B)
notation R`⟦`:33 A`⟧`:21 := Yo R A
notation R`<`:100 φ`>` := Yo_ R φ
lemma apply_to_composition {R : C}{Z K :C}(f : R ⟶ Z)(g : Z ⟶ K) :
R < g > f = f ≫ g := rfl
lemma composition_to_apply {R : C}{Z K :C}(f : R ⟶ Z)(g : Z ⟶ K) :
f ≫ g = (R < g > f) := rfl
lemma id (R : C)(A : C) : R < 𝟙 A > = 𝟙 (R⟦ A⟧ ) := begin
funext,
exact comp_id g,
-- have T : ((yoneda.map (𝟙 A)).app (op R)) g = (g ≫ (𝟙 A)),
end
def Yoneda_preserve_product (Y : C)(A B : C) :
Y ⟦ A ⨯ B ⟧ ≅ Y ⟦ A ⟧ ⨯ Y⟦ B ⟧ :=
{ hom := (Y< π1 > | Y <π2>),
inv := λ g : (Y ⟶ A) ⨯ (Y ⟶ B),
( (π1 : (Y ⟶ A) ⨯ (Y ⟶ B) ⟶ (Y ⟶ A)) g | (π2 : (Y ⟶ A) ⨯ (Y ⟶ B) ⟶ (Y ⟶ B)) g )
, --- g ≫ π1
hom_inv_id' := begin
funext g,
rw types_comp_apply,
apply prod.hom_ext,
rw prod.lift_fst,
rw ← types_comp_apply (Y < π1> | Y < π2>) π1 g,
rw prod.lift_fst,
exact rfl,
-- rw apply_to_composition,
-- rw types_id,
tidy,
end,
inv_hom_id' := begin
apply prod.hom_ext,
rw assoc,
rw prod.lift_fst,funext ζ ,
rw types_comp_apply,rw apply_to_composition,
rw prod.lift_fst,
exact rfl,
rw assoc,
rw prod.lift_snd,funext ζ,
rw types_comp_apply,
rw apply_to_composition,
rw prod.lift_snd,
exact rfl,
end
}
-- def Yoneda_preserve_product (Y : C)(A B : C) :
-- Y ⟦ A ⨯ B ⟧ ≅ Y ⟦ A ⟧ ⨯ Y⟦ B ⟧ :=
-- { hom := prod.lift
-- (λ f, f ≫ π1)
-- (λ f, f ≫ π2),
-- inv := λ f : (Y ⟶ A) ⨯ (Y ⟶ B),
-- (prod.lift
-- ((@category_theory.limits.prod.fst _ _ (Y ⟶ A) (Y ⟶ B) _ : ((Y ⟶ A) ⨯ (Y ⟶ B)) → (Y ⟶ A)) f)
-- ((@category_theory.limits.prod.snd _ _ (Y ⟶ A) _ _ : ((Y ⟶ A) ⨯ (Y ⟶ B)) → (Y ⟶ B)) f : Y ⟶ B)),
-- hom_inv_id' := begin
-- ext f,
-- cases j, --- HERE
-- { simp, refl},
-- { simp, refl}
-- end,
-- inv_hom_id' := begin
-- apply prod.hom_ext,
-- { rw assoc, rw prod.lift_fst, obviously},
-- { rw assoc, rw prod.lift_snd, obviously}
-- end
-- }
--- Here it just sugar
lemma composition (R : C) {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) :
R < f ≫ g > = R< f > ≫ R < g >
:= begin
funext ζ,
rw apply_to_composition,
rw types_comp_apply,
iterate 2 {rw apply_to_composition},
exact eq.symm ( assoc ζ f g),
end
def convertion {R : C}{A : C}(g : R⟦ A⟧ ) : R ⟶ A := g
def Preserve.product_up_to_iso (R : C)(A B : C) : R⟦A ⨯ B⟧ ≅ R⟦A⟧ ⨯ R⟦B⟧ := Yoneda_preserve_product R A B
lemma Preserve.product.hom (R : C)(A B : C) :
(Preserve.product_up_to_iso R A B).hom = (R < π1 > | R < π2 > ) := rfl
lemma Preserve.prod_morphism (R : C)(A B : C)(X :C)(f : X ⟶ A)(g : X ⟶ B) :
R < (f | g) > ≫ (R < π1 > | R < π2 >) = (R < f > | R < g >) := -- the ≫ is :/
begin
rw prod.left_composition,
iterate 2 {rw [← composition]},
rw prod.lift_fst,
rw prod.lift_snd,
end
lemma Preserve.otimes_morphism (R : C){ X Y Z K :C}(f : X ⟶ Y )(g : Z ⟶ K) :
(R < π1 > | R < π2 >) ≫ ( R < f > ⊗ R < g > ) = R < (f ⊗ g) > ≫ (R < π1 > |R < π2 >) :=
begin
rw prod.prod_comp_otimes,
rw prod.otimes_is_prod,
rw prod.left_composition,
rw ← composition,
rw ← composition,
slice_rhs 2 3 {
rw ← composition,
rw prod.lift_snd,
},
slice_rhs 1 1 {
rw ← composition,
rw prod.lift_fst,
},
end
lemma prod_apply {R :C}{A Y Z : C }(ζ : R ⟦ A ⟧) (f : A ⟶ Y)(g : A ⟶ Y) :
( R< (f | g) >) ζ = (R < f > ζ | R < g > ζ ) :=
begin
rw apply_to_composition,
rw prod.left_composition,
iterate 2 {rw apply_to_composition},
end
lemma otimes_apply {R :C}{A1 A2 Y Z : C }(ζ1 : R ⟦ A1 ⟧)(ζ2 : R⟦ A2 ⟧ )
(f1 : A1 ⟶ Y)(f2 : A2 ⟶ Z) :
R < (f1 ⊗ f2 ) > (ζ1 | ζ2) = ( R < f1 > ζ1 | R < f2 > ζ2 ) :=
begin
rw apply_to_composition,
rw prod.prod_comp_otimes,
exact rfl,
end
end Yoneda |
e8a5960d62e801b718b5952152815a6829221e5f | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/analysis/convex/cone.lean | edd9631776b1b05110a3d4ac7f18cefd74219ce6 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,709 | lean | /-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Frédéric Dupuis
-/
import linear_algebra.linear_pmap
import analysis.convex.basic
import order.zorn
/-!
# Convex cones
In a vector space `E` over `ℝ`, we define a convex cone as a subset `s` such that
`a • x + b • y ∈ s` whenever `x, y ∈ s` and `a, b > 0`. We prove that convex cones form
a `complete_lattice`, and define their images (`convex_cone.map`) and preimages
(`convex_cone.comap`) under linear maps.
We define pointed, blunt, flat and salient cones, and prove the correspondence between
convex cones and ordered modules.
We also define `convex.to_cone` to be the minimal cone that includes a given convex set.
## Main statements
We prove two extension theorems:
* `riesz_extension`:
[M. Riesz extension theorem](https://en.wikipedia.org/wiki/M._Riesz_extension_theorem) says that
if `s` is a convex cone in a real vector space `E`, `p` is a submodule of `E`
such that `p + s = E`, and `f` is a linear function `p → ℝ` which is
nonnegative on `p ∩ s`, then there exists a globally defined linear function
`g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`.
* `exists_extension_of_le_sublinear`:
Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map
defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`,
then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x`
for all `x`
## Implementation notes
While `convex` is a predicate on sets, `convex_cone` is a bundled convex cone.
## References
* https://en.wikipedia.org/wiki/Convex_cone
## TODO
* Define the dual cone.
-/
universes u v
open set linear_map
open_locale classical
variables (E : Type*) [add_comm_group E] [module ℝ E]
{F : Type*} [add_comm_group F] [module ℝ F]
{G : Type*} [add_comm_group G] [module ℝ G]
/-!
### Definition of `convex_cone` and basic properties
-/
/-- A convex cone is a subset `s` of a vector space over `ℝ` such that `a • x + b • y ∈ s`
whenever `a, b > 0` and `x, y ∈ s`. -/
structure convex_cone :=
(carrier : set E)
(smul_mem' : ∀ ⦃c : ℝ⦄, 0 < c → ∀ ⦃x : E⦄, x ∈ carrier → c • x ∈ carrier)
(add_mem' : ∀ ⦃x⦄ (hx : x ∈ carrier) ⦃y⦄ (hy : y ∈ carrier), x + y ∈ carrier)
variable {E}
namespace convex_cone
variables (S T : convex_cone E)
instance : has_coe (convex_cone E) (set E) := ⟨convex_cone.carrier⟩
instance : has_mem E (convex_cone E) := ⟨λ m S, m ∈ S.carrier⟩
instance : has_le (convex_cone E) := ⟨λ S T, S.carrier ⊆ T.carrier⟩
instance : has_lt (convex_cone E) := ⟨λ S T, S.carrier ⊂ T.carrier⟩
@[simp, norm_cast] lemma mem_coe {x : E} : x ∈ (S : set E) ↔ x ∈ S := iff.rfl
@[simp] lemma mem_mk {s : set E} {h₁ h₂ x} : x ∈ mk s h₁ h₂ ↔ x ∈ s := iff.rfl
/-- Two `convex_cone`s are equal if the underlying subsets are equal. -/
theorem ext' {S T : convex_cone E} (h : (S : set E) = T) : S = T :=
by cases S; cases T; congr'
/-- Two `convex_cone`s are equal if and only if the underlying subsets are equal. -/
protected theorem ext'_iff {S T : convex_cone E} : (S : set E) = T ↔ S = T :=
⟨ext', λ h, h ▸ rfl⟩
/-- Two `convex_cone`s are equal if they have the same elements. -/
@[ext] theorem ext {S T : convex_cone E} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h
lemma smul_mem {c : ℝ} {x : E} (hc : 0 < c) (hx : x ∈ S) : c • x ∈ S := S.smul_mem' hc hx
lemma add_mem ⦃x⦄ (hx : x ∈ S) ⦃y⦄ (hy : y ∈ S) : x + y ∈ S := S.add_mem' hx hy
lemma smul_mem_iff {c : ℝ} (hc : 0 < c) {x : E} :
c • x ∈ S ↔ x ∈ S :=
⟨λ h, by simpa only [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]
using S.smul_mem (inv_pos.2 hc) h, λ h, S.smul_mem hc h⟩
lemma convex : convex (S : set E) :=
convex_iff_forall_pos.2 $ λ x y hx hy a b ha hb hab,
S.add_mem (S.smul_mem ha hx) (S.smul_mem hb hy)
instance : has_inf (convex_cone E) :=
⟨λ S T, ⟨S ∩ T, λ c hc x hx, ⟨S.smul_mem hc hx.1, T.smul_mem hc hx.2⟩,
λ x hx y hy, ⟨S.add_mem hx.1 hy.1, T.add_mem hx.2 hy.2⟩⟩⟩
lemma coe_inf : ((S ⊓ T : convex_cone E) : set E) = ↑S ∩ ↑T := rfl
lemma mem_inf {x} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl
instance : has_Inf (convex_cone E) :=
⟨λ S, ⟨⋂ s ∈ S, ↑s,
λ c hc x hx, mem_bInter $ λ s hs, s.smul_mem hc $ by apply mem_bInter_iff.1 hx s hs,
λ x hx y hy, mem_bInter $ λ s hs, s.add_mem (by apply mem_bInter_iff.1 hx s hs)
(by apply mem_bInter_iff.1 hy s hs)⟩⟩
lemma mem_Inf {x : E} {S : set (convex_cone E)} : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := mem_bInter_iff
instance : has_bot (convex_cone E) := ⟨⟨∅, λ c hc x, false.elim, λ x, false.elim⟩⟩
lemma mem_bot (x : E) : x ∈ (⊥ : convex_cone E) = false := rfl
instance : has_top (convex_cone E) := ⟨⟨univ, λ c hc x hx, mem_univ _, λ x hx y hy, mem_univ _⟩⟩
lemma mem_top (x : E) : x ∈ (⊤ : convex_cone E) := mem_univ x
instance : complete_lattice (convex_cone E) :=
{ le := (≤),
lt := (<),
bot := (⊥),
bot_le := λ S x, false.elim,
top := (⊤),
le_top := λ S x hx, mem_top x,
inf := (⊓),
Inf := has_Inf.Inf,
sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
Sup := λ s, Inf {T | ∀ S ∈ s, S ≤ T},
le_sup_left := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.1 hx,
le_sup_right := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.2 hx,
sup_le := λ a b c ha hb x hx, mem_Inf.1 hx c ⟨ha, hb⟩,
le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩,
inf_le_left := λ a b x, and.left,
inf_le_right := λ a b x, and.right,
le_Sup := λ s p hs x hx, mem_Inf.2 $ λ t ht, ht p hs hx,
Sup_le := λ s p hs x hx, mem_Inf.1 hx p hs,
le_Inf := λ s a ha x hx, mem_Inf.2 $ λ t ht, ha t ht hx,
Inf_le := λ s a ha x hx, mem_Inf.1 hx _ ha,
.. partial_order.lift (coe : convex_cone E → set E) (λ a b, ext') }
instance : inhabited (convex_cone E) := ⟨⊥⟩
/-- The image of a convex cone under an `ℝ`-linear map is a convex cone. -/
def map (f : E →ₗ[ℝ] F) (S : convex_cone E) : convex_cone F :=
{ carrier := f '' S,
smul_mem' := λ c hc y ⟨x, hx, hy⟩, hy ▸ f.map_smul c x ▸ mem_image_of_mem f (S.smul_mem hc hx),
add_mem' := λ y₁ ⟨x₁, hx₁, hy₁⟩ y₂ ⟨x₂, hx₂, hy₂⟩, hy₁ ▸ hy₂ ▸ f.map_add x₁ x₂ ▸
mem_image_of_mem f (S.add_mem hx₁ hx₂) }
lemma map_map (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone E) :
(S.map f).map g = S.map (g.comp f) :=
ext' $ image_image g f S
@[simp] lemma map_id : S.map linear_map.id = S := ext' $ image_id _
/-- The preimage of a convex cone under an `ℝ`-linear map is a convex cone. -/
def comap (f : E →ₗ[ℝ] F) (S : convex_cone F) : convex_cone E :=
{ carrier := f ⁻¹' S,
smul_mem' := λ c hc x hx, by { rw [mem_preimage, f.map_smul c], exact S.smul_mem hc hx },
add_mem' := λ x hx y hy, by { rw [mem_preimage, f.map_add], exact S.add_mem hx hy } }
@[simp] lemma comap_id : S.comap linear_map.id = S := ext' preimage_id
lemma comap_comap (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone G) :
(S.comap g).comap f = S.comap (g.comp f) :=
ext' $ preimage_comp.symm
@[simp] lemma mem_comap {f : E →ₗ[ℝ] F} {S : convex_cone F} {x : E} :
x ∈ S.comap f ↔ f x ∈ S := iff.rfl
/--
Constructs an ordered module given an `ordered_add_comm_group`, a cone, and a proof that
the order relation is the one defined by the cone.
-/
lemma to_ordered_module {M : Type*} [ordered_add_comm_group M] [module ℝ M]
(S : convex_cone M) (h : ∀ x y : M, x ≤ y ↔ y - x ∈ S) : ordered_module ℝ M :=
ordered_module.mk'
begin
intros x y z xy hz,
rw [h (z • x) (z • y), ←smul_sub z y x],
exact smul_mem S hz ((h x y).mp (le_of_lt xy))
end
/-! ### Convex cones with extra properties -/
/-- A convex cone is pointed if it includes 0. -/
def pointed (S : convex_cone E) : Prop := (0 : E) ∈ S
/-- A convex cone is blunt if it doesn't include 0. -/
def blunt (S : convex_cone E) : Prop := (0 : E) ∉ S
/-- A convex cone is flat if it contains some nonzero vector `x` and its opposite `-x`. -/
def flat (S : convex_cone E) : Prop := ∃ x ∈ S, x ≠ (0 : E) ∧ -x ∈ S
/-- A convex cone is salient if it doesn't include `x` and `-x` for any nonzero `x`. -/
def salient (S : convex_cone E) : Prop := ∀ x ∈ S, x ≠ (0 : E) → -x ∉ S
lemma pointed_iff_not_blunt (S : convex_cone E) : pointed S ↔ ¬blunt S :=
⟨λ h₁ h₂, h₂ h₁, λ h, not_not.mp h⟩
lemma salient_iff_not_flat (S : convex_cone E) : salient S ↔ ¬flat S :=
begin
split,
{ rintros h₁ ⟨x, xs, H₁, H₂⟩,
exact h₁ x xs H₁ H₂ },
{ intro h,
unfold flat at h,
push_neg at h,
exact h }
end
/-- A blunt cone (one not containing 0) is always salient. -/
lemma salient_of_blunt (S : convex_cone E) : blunt S → salient S :=
begin
intro h₁,
rw [salient_iff_not_flat],
intro h₂,
obtain ⟨x, xs, H₁, H₂⟩ := h₂,
have hkey : (0 : E) ∈ S := by rw [(show 0 = x + (-x), by simp)]; exact add_mem S xs H₂,
exact h₁ hkey,
end
/-- A pointed convex cone defines a preorder. -/
def to_preorder (S : convex_cone E) (h₁ : pointed S) : preorder E :=
{ le := λ x y, y - x ∈ S,
le_refl := λ x, by change x - x ∈ S; rw [sub_self x]; exact h₁,
le_trans := λ x y z xy zy, by simp [(show z - x = z - y + (y - x), by abel), add_mem S zy xy] }
/-- A pointed and salient cone defines a partial order. -/
def to_partial_order (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) : partial_order E :=
{ le_antisymm :=
begin
intros a b ab ba,
by_contradiction h,
have h' : b - a ≠ 0 := λ h'', h (eq_of_sub_eq_zero h'').symm,
have H := h₂ (b-a) ab h',
rw [neg_sub b a] at H,
exact H ba,
end,
..to_preorder S h₁ }
/-- A pointed and salient cone defines an `ordered_add_comm_group`. -/
def to_ordered_add_comm_group (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) :
ordered_add_comm_group E :=
{ add_le_add_left :=
begin
intros a b hab c,
change c + b - (c + a) ∈ S,
rw [add_sub_add_left_eq_sub],
exact hab,
end,
..to_partial_order S h₁ h₂,
..show add_comm_group E, by apply_instance }
/-! ### Positive cone of an ordered module -/
section positive_cone
variables (M : Type*) [ordered_add_comm_group M] [module ℝ M] [ordered_module ℝ M]
/--
The positive cone is the convex cone formed by the set of nonnegative elements in an ordered
module.
-/
def positive_cone : convex_cone M :=
{ carrier := {x | 0 ≤ x},
smul_mem' :=
begin
intros c hc x hx,
have := smul_le_smul_of_nonneg (show 0 ≤ x, by exact hx) (le_of_lt hc),
have h' : c • (0 : M) = 0,
{ simp only [smul_zero] },
rwa [h'] at this
end,
add_mem' := λ x hx y hy, add_nonneg (show 0 ≤ x, by exact hx) (show 0 ≤ y, by exact hy) }
/-- The positive cone of an ordered module is always salient. -/
lemma salient_of_positive_cone : salient (positive_cone M) :=
begin
intros x xs hx hx',
have := calc
0 < x : lt_of_le_of_ne xs hx.symm
... ≤ x + (-x) : (le_add_iff_nonneg_right x).mpr hx'
... = 0 : by rw [tactic.ring.add_neg_eq_sub x x]; exact sub_self x,
exact lt_irrefl 0 this,
end
/-- The positive cone of an ordered module is always pointed. -/
lemma pointed_of_positive_cone : pointed (positive_cone M) := le_refl 0
end positive_cone
end convex_cone
/-!
### Cone over a convex set
-/
namespace convex
/-- The set of vectors proportional to those in a convex set forms a convex cone. -/
def to_cone (s : set E) (hs : convex s) : convex_cone E :=
begin
apply convex_cone.mk (⋃ c > 0, (c : ℝ) • s);
simp only [mem_Union, mem_smul_set],
{ rintros c c_pos _ ⟨c', c'_pos, x, hx, rfl⟩,
exact ⟨c * c', mul_pos c_pos c'_pos, x, hx, (smul_smul _ _ _).symm⟩ },
{ rintros _ ⟨cx, cx_pos, x, hx, rfl⟩ _ ⟨cy, cy_pos, y, hy, rfl⟩,
have : 0 < cx + cy, from add_pos cx_pos cy_pos,
refine ⟨_, this, _, convex_iff_div.1 hs hx hy (le_of_lt cx_pos) (le_of_lt cy_pos) this, _⟩,
simp only [smul_add, smul_smul, mul_div_assoc', mul_div_cancel_left _ (ne_of_gt this)] }
end
variables {s : set E} (hs : convex s) {x : E}
lemma mem_to_cone : x ∈ hs.to_cone s ↔ ∃ (c > 0) (y ∈ s), (c : ℝ) • y = x :=
by simp only [to_cone, convex_cone.mem_mk, mem_Union, mem_smul_set, eq_comm, exists_prop]
lemma mem_to_cone' : x ∈ hs.to_cone s ↔ ∃ c > 0, (c : ℝ) • x ∈ s :=
begin
refine hs.mem_to_cone.trans ⟨_, _⟩,
{ rintros ⟨c, hc, y, hy, rfl⟩,
exact ⟨c⁻¹, inv_pos.2 hc, by rwa [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]⟩ },
{ rintros ⟨c, hc, hcx⟩,
exact ⟨c⁻¹, inv_pos.2 hc, _, hcx, by rw [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul]⟩ }
end
lemma subset_to_cone : s ⊆ hs.to_cone s :=
λ x hx, hs.mem_to_cone'.2 ⟨1, zero_lt_one, by rwa one_smul⟩
/-- `hs.to_cone s` is the least cone that includes `s`. -/
lemma to_cone_is_least : is_least { t : convex_cone E | s ⊆ t } (hs.to_cone s) :=
begin
refine ⟨hs.subset_to_cone, λ t ht x hx, _⟩,
rcases hs.mem_to_cone.1 hx with ⟨c, hc, y, hy, rfl⟩,
exact t.smul_mem hc (ht hy)
end
lemma to_cone_eq_Inf : hs.to_cone s = Inf { t : convex_cone E | s ⊆ t } :=
hs.to_cone_is_least.is_glb.Inf_eq.symm
end convex
lemma convex_hull_to_cone_is_least (s : set E) :
is_least {t : convex_cone E | s ⊆ t} ((convex_convex_hull s).to_cone _) :=
begin
convert (convex_convex_hull s).to_cone_is_least,
ext t,
exact ⟨λ h, convex_hull_min h t.convex, λ h, subset.trans (subset_convex_hull s) h⟩
end
lemma convex_hull_to_cone_eq_Inf (s : set E) :
(convex_convex_hull s).to_cone _ = Inf {t : convex_cone E | s ⊆ t} :=
(convex_hull_to_cone_is_least s).is_glb.Inf_eq.symm
/-!
### M. Riesz extension theorem
Given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume
that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear
function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`.
We prove this theorem using Zorn's lemma. `riesz_extension.step` is the main part of the proof.
It says that if the domain `p` of `f` is not the whole space, then `f` can be extended to a larger
subspace `p ⊔ span ℝ {y}` without breaking the non-negativity condition.
In `riesz_extension.exists_top` we use Zorn's lemma to prove that we can extend `f`
to a linear map `g` on `⊤ : submodule E`. Mathematically this is the same as a linear map on `E`
but in Lean `⊤ : submodule E` is isomorphic but is not equal to `E`. In `riesz_extension`
we use this isomorphism to prove the theorem.
-/
namespace riesz_extension
open submodule
variables (s : convex_cone E) (f : linear_pmap ℝ E ℝ)
/-- Induction step in M. Riesz extension theorem. Given a convex cone `s` in a vector space `E`,
a partially defined linear map `f : f.domain → ℝ`, assume that `f` is nonnegative on `f.domain ∩ p`
and `p + s = E`. If `f` is not defined on the whole `E`, then we can extend it to a larger
submodule without breaking the non-negativity condition. -/
lemma step (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x)
(dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) (hdom : f.domain ≠ ⊤) :
∃ g, f < g ∧ ∀ x : g.domain, (x : E) ∈ s → 0 ≤ g x :=
begin
rcases set_like.exists_of_lt (lt_top_iff_ne_top.2 hdom) with ⟨y, hy', hy⟩, clear hy',
obtain ⟨c, le_c, c_le⟩ :
∃ c, (∀ x : f.domain, -(x:E) - y ∈ s → f x ≤ c) ∧ (∀ x : f.domain, (x:E) + y ∈ s → c ≤ f x),
{ set Sp := f '' {x : f.domain | (x:E) + y ∈ s},
set Sn := f '' {x : f.domain | -(x:E) - y ∈ s},
suffices : (upper_bounds Sn ∩ lower_bounds Sp).nonempty,
by simpa only [set.nonempty, upper_bounds, lower_bounds, ball_image_iff] using this,
refine exists_between_of_forall_le (nonempty.image f _) (nonempty.image f (dense y)) _,
{ rcases (dense (-y)) with ⟨x, hx⟩,
rw [← neg_neg x, coe_neg, ← sub_eq_add_neg] at hx,
exact ⟨_, hx⟩ },
rintros a ⟨xn, hxn, rfl⟩ b ⟨xp, hxp, rfl⟩,
have := s.add_mem hxp hxn,
rw [add_assoc, add_sub_cancel'_right, ← sub_eq_add_neg, ← coe_sub] at this,
replace := nonneg _ this,
rwa [f.map_sub, sub_nonneg] at this },
have hy' : y ≠ 0, from λ hy₀, hy (hy₀.symm ▸ zero_mem _),
refine ⟨f.sup_span_singleton y (-c) hy, _, _⟩,
{ refine lt_iff_le_not_le.2 ⟨f.left_le_sup _ _, λ H, _⟩,
replace H := linear_pmap.domain_mono.monotone H,
rw [linear_pmap.domain_sup_span_singleton, sup_le_iff, span_le, singleton_subset_iff] at H,
exact hy H.2 },
{ rintros ⟨z, hz⟩ hzs,
rcases mem_sup.1 hz with ⟨x, hx, y', hy', rfl⟩,
rcases mem_span_singleton.1 hy' with ⟨r, rfl⟩,
simp only [subtype.coe_mk] at hzs,
erw [linear_pmap.sup_span_singleton_apply_mk _ _ _ _ _ hx, smul_neg,
← sub_eq_add_neg, sub_nonneg],
rcases lt_trichotomy r 0 with hr|hr|hr,
{ have : -(r⁻¹ • x) - y ∈ s,
by rwa [← s.smul_mem_iff (neg_pos.2 hr), smul_sub, smul_neg, neg_smul, neg_neg, smul_smul,
mul_inv_cancel (ne_of_lt hr), one_smul, sub_eq_add_neg, neg_smul, neg_neg],
replace := le_c (r⁻¹ • ⟨x, hx⟩) this,
rwa [← mul_le_mul_left (neg_pos.2 hr), ← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul,
neg_le_neg_iff, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel (ne_of_lt hr),
one_mul] at this },
{ subst r,
simp only [zero_smul, add_zero] at hzs ⊢,
apply nonneg,
exact hzs },
{ have : r⁻¹ • x + y ∈ s,
by rwa [← s.smul_mem_iff hr, smul_add, smul_smul, mul_inv_cancel (ne_of_gt hr), one_smul],
replace := c_le (r⁻¹ • ⟨x, hx⟩) this,
rwa [← mul_le_mul_left hr, f.map_smul, smul_eq_mul, ← mul_assoc,
mul_inv_cancel (ne_of_gt hr), one_mul] at this } }
end
theorem exists_top (p : linear_pmap ℝ E ℝ)
(hp_nonneg : ∀ x : p.domain, (x : E) ∈ s → 0 ≤ p x)
(hp_dense : ∀ y, ∃ x : p.domain, (x : E) + y ∈ s) :
∃ q ≥ p, q.domain = ⊤ ∧ ∀ x : q.domain, (x : E) ∈ s → 0 ≤ q x :=
begin
replace hp_nonneg : p ∈ { p | _ }, by { rw mem_set_of_eq, exact hp_nonneg },
obtain ⟨q, hqs, hpq, hq⟩ := zorn.zorn_nonempty_partial_order₀ _ _ _ hp_nonneg,
{ refine ⟨q, hpq, _, hqs⟩,
contrapose! hq,
rcases step s q hqs _ hq with ⟨r, hqr, hr⟩,
{ exact ⟨r, hr, le_of_lt hqr, ne_of_gt hqr⟩ },
{ exact λ y, let ⟨x, hx⟩ := hp_dense y in ⟨of_le hpq.left x, hx⟩ } },
{ intros c hcs c_chain y hy,
clear hp_nonneg hp_dense p,
have cne : c.nonempty := ⟨y, hy⟩,
refine ⟨linear_pmap.Sup c c_chain.directed_on, _, λ _, linear_pmap.le_Sup c_chain.directed_on⟩,
rintros ⟨x, hx⟩ hxs,
have hdir : directed_on (≤) (linear_pmap.domain '' c),
from directed_on_image.2 (c_chain.directed_on.mono linear_pmap.domain_mono.monotone),
rcases (mem_Sup_of_directed (cne.image _) hdir).1 hx with ⟨_, ⟨f, hfc, rfl⟩, hfx⟩,
have : f ≤ linear_pmap.Sup c c_chain.directed_on, from linear_pmap.le_Sup _ hfc,
convert ← hcs hfc ⟨x, hfx⟩ hxs,
apply this.2, refl }
end
end riesz_extension
/-- M. Riesz extension theorem: given a convex cone `s` in a vector space `E`, a submodule `p`,
and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then
there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`,
and is nonnegative on `s`. -/
theorem riesz_extension (s : convex_cone E) (f : linear_pmap ℝ E ℝ)
(nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) :
∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x ∈ s, 0 ≤ g x) :=
begin
rcases riesz_extension.exists_top s f nonneg dense with ⟨⟨g_dom, g⟩, ⟨hpg, hfg⟩, htop, hgs⟩,
clear hpg,
refine ⟨g.comp (linear_equiv.of_top _ htop).symm, _, _⟩;
simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.of_top_symm_apply],
{ exact λ x, (hfg (submodule.coe_mk _ _).symm).symm },
{ exact λ x hx, hgs ⟨x, _⟩ hx }
end
/-- Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map
defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`,
then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x`
for all `x`. -/
theorem exists_extension_of_le_sublinear (f : linear_pmap ℝ E ℝ) (N : E → ℝ)
(N_hom : ∀ (c : ℝ), 0 < c → ∀ x, N (c • x) = c * N x)
(N_add : ∀ x y, N (x + y) ≤ N x + N y)
(hf : ∀ x : f.domain, f x ≤ N x) :
∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x, g x ≤ N x) :=
begin
let s : convex_cone (E × ℝ) :=
{ carrier := {p : E × ℝ | N p.1 ≤ p.2 },
smul_mem' := λ c hc p hp,
calc N (c • p.1) = c * N p.1 : N_hom c hc p.1
... ≤ c * p.2 : mul_le_mul_of_nonneg_left hp (le_of_lt hc),
add_mem' := λ x hx y hy, le_trans (N_add _ _) (add_le_add hx hy) },
obtain ⟨g, g_eq, g_nonneg⟩ :=
riesz_extension s ((-f).coprod (linear_map.id.to_pmap ⊤)) _ _;
try { simp only [linear_pmap.coprod_apply, to_pmap_apply, id_apply,
linear_pmap.neg_apply, ← sub_eq_neg_add, sub_nonneg, subtype.coe_mk] at * },
replace g_eq : ∀ (x : f.domain) (y : ℝ), g (x, y) = y - f x,
{ intros x y,
simpa only [subtype.coe_mk, subtype.coe_eta] using g_eq ⟨(x, y), ⟨x.2, trivial⟩⟩ },
{ refine ⟨-g.comp (inl ℝ E ℝ), _, _⟩; simp only [neg_apply, inl_apply, comp_apply],
{ intro x, simp [g_eq x 0] },
{ intro x,
have A : (x, N x) = (x, 0) + (0, N x), by simp,
have B := g_nonneg ⟨x, N x⟩ (le_refl (N x)),
rw [A, map_add, ← neg_le_iff_add_nonneg'] at B,
have C := g_eq 0 (N x),
simp only [submodule.coe_zero, f.map_zero, sub_zero] at C,
rwa ← C } },
{ exact λ x hx, le_trans (hf _) hx },
{ rintros ⟨x, y⟩,
refine ⟨⟨(0, N x - y), ⟨f.domain.zero_mem, trivial⟩⟩, _⟩,
simp only [convex_cone.mem_mk, mem_set_of_eq, subtype.coe_mk, prod.fst_add, prod.snd_add,
zero_add, sub_add_cancel] }
end
|
fda4bf380a5cd3ed2e00a35f7a46c88882bf338f | 359199d7253811b032ab92108191da7336eba86e | /src/instructor/lectures/lecture_19.lean | 55c58ea2866c0605b4b7f5c10b3971cfe6324dc1 | [] | no_license | arte-et-marte/my_cs2120f21 | 0bc6215cb5018a3b7c90d9d399a173233f587064 | 91609c3609ad81fda895bee8b97cc76813241e17 | refs/heads/main | 1,693,298,928,348 | 1,634,931,202,000 | 1,634,931,202,000 | 399,946,705 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,727 | lean | import data.set
/-
PART II: BASIC SET THEORY
Give formal and English language proofs of
the following conjectures.
-/
/-
We'll use our favorite set, of the even
numbers, in what follows, so we define it
again here.
-/
def evens : set ℕ := { n | n%2 = 0}
/-
PROOFS INVOLVING SUBSET RELATIONS
-/
example : ({ 0, 2 } : set ℕ) ⊆ evens :=
/-
Before looking at the proof script, spend
a good bit of time trying to be sure that
you see how the proof will work. We want
to prove a subset relation, so we want to
prove that for all values, v, if v is in
the first set, then v is in the second.
The rest of the proof is by case analysis.
v ∈ {0, 2} means v = 0 ∨ v = 2. These are
the cases. In each case, we need to show
that the value, v, is in the second set.
This means that the value satisfies the
set membership predicate, so we will need
to prove (evens 0) and (evens 2). Writing
out the definition of evens, we'll need to
prove 0 % 2 = 0 and 2 % 2 = 0, and these
are true by the reflexivity of equality.
Here we hope you see how vitally important
it is to *learn* the basic definitions and
to *look them up* again if you forget them
or get stuck. Always go to the definitions
if you get stuck. That's how to learn or to
*remember* what the symbols and other terms
mean. Putting the smaller pieces together
again will often reveal how to get unstuck.
This principle is particularly important
right now because we've introduced a major
new layer of abstractions, from logic to
set theory, with its associated definitions
and notations (see lecture_18). You need
to memorize these definitions and notations
to be able to deal with propositions and
proofs in set theory.
-/
/-
So here's a proof script in Lean. Follow it
step by step, carefully studying your "proof
state" (context and goal) after each "move."
Be sure you can relate the informal proof
above to the formal proof generated by this
script.
-/
begin
/-
Uncomment next line to see how to use show
to rewrite a goal to "definitionally equal"
form. The rewriting here makes it easier to
see exactly when the first two moves are to
assume that you're given argument values, n
and h. This rewriting is not needed though
for the rest of the proof to work as is.
-/
-- show ∀ n, n = 0 ∨ n = 2 → n ∈ evens,
assume n,
assume h, -- n is in the set {0, 2} if n is 0 OR n is 2 (a disjunction you can apply cases to!)
cases h, -- what can you do with a proof of equality? substitutability; rw
-- case: n = 0
rw h, -- for 0 ∈ evens to be true, evens 0 should be true; what's evens 0? ->
--/-
unfold evens,
show {n : ℕ | n % 2 = 0} 0, -- replace evens in evens 0 to be its unraveled form
show 0 % 2 = 0,
---/
assume h,
cases h,
-- case: n = 0
rw h, -- by substitutability of equals
/-
Uncomment the following lines if you want
to see in more detail why it makes sense
that rfl is what's needed to finish the
proof. (But before you do, try to work it
out in your own head!)
-/
-- unfold evens,
-- show {n : ℕ | n % 2 = 0} 0,
-- show 0 % 2 = 0,
exact rfl,
-- case: n = 2
cases h,
--/-
/-
A comment is required here. Sometimes a proof
assistant will use an unusual term for what
you'd write more simply. Here (1.add 0).succ
means the successor of 1 + 0, i.e., 2. You
don't need to even ask why. Just know that
you're really just looking at "2" here.
At this point you have h, a proof, h, of
2 = 2 (albeit written in a strange way), and
you need to prove that 2 (writen weirdly)
is in the evens set. In this case, the h is
not needed, as the proof that "2 is even" is
by the reflexivity of equality.
-/
--uncomment for unnecessary gory details!
/-
show 2 ∈ evens,
show evens 2,
unfold evens,
show 2 % 2 = 0,
---/
exact rfl,
show 0 = 0,
-/
exact rfl, -- Ta Da!
end
/-s-/
/-
THE MEANING OF AND PROOF INVOLVING SET EQUALITY
-/
/-
We now look at the concept of *equality*
of sets. To show that two sets are equal,
e.g., L = X, we need to show that a value
is in L if and only if it's in X. This is
the same as showing L ⊆ X ∧ X ⊆ L. This **to prove subsets equal, show that they are subsets of each other**
in turn means
the same as showing L ⊆ X ∧ X ⊆ L. That
is a take-away message: To prove two sets
equal, you can prove that each is a subset
of the other.
Now *please* expand definitions to see that
L ⊆ X ∧ X ⊆ L means
∀ x,
(x ∈ L → x ∈ X) ∧
(x ∈ X → x ∈ L)
which we can also write as
∀ x, x ∈ L ↔ x ∈ X.
Now to get from a proof of that to a proof
of L = X requires a new axiom, the axiom
of **set extensionality**. It just says that
if we prove ∀ x, x ∈ L ↔ x ∈ X then we
can, by applying the axiom, deduce that
L = X. The set extensionality axiom in
Lean is called ext, defined in the set
namespace; so you can refer to it either
as **set.ext** (apply this to a proof of the above), or you can open the set
namepace and then just call it ext.
-/
#check @set.ext
/-
Remember that you can think about an
implication, P → Q, in two ways: first,
if P then Q; second, to prove Q it will
suffice to prove P. So to prove L = X,
it suffices to prove ∀ x, x ∈ L ↔ x ∈ X,
because one can then apply ext to that
proof to derive a proof of L = X. In
other words, ext lets you "reduce" the
need for a proof of L = X to the need
for a proof of ∀ x, x ∈ L ↔ x ∈ X. And
that is what we see next.
The concept of set equality, and the
need to prove certain sets to be equal,
is extremely common, so it's important
to master these concepts here.
-/
example : ∀ {α : Type} (L X : set α), L ⊆ X → ((L ∩ X) = L) :=
begin
intros α L X h,
apply set.ext _, -- turn = into ↔ using extensionality axiom
-- that's the whole proof as long as we can fill in the _
-- but now that's just ordinary logical reasoning
assume x,
-- apply iff.intro _ _,
split,
-- forward
assume h,
cases h,
exact h_left,
-- backward
assume k,
exact and.intro k (h k),
end
Now to get from a proof of that to a
proof of L = X requires a new axiom, called
set extensionality. It just says that if
we prove ∀ x, x ∈ L ↔ x ∈ X then we can,
by applying the axiom, deduce that L = X.
-/
#check @set.ext
/-
The set extensionality axiom in Lean is
called ext, defined in the set namespace;
so you can refer to it either as set.ext,
or you can open the set namepace and then
just call it ext.
-/
/-
NOTE ON APPLYING P → Q TO REDUCE Q TO P.
-/
/-
Remember that you can think about a
proof of an implication, P → Q, in two
ways: first (reading left to right), it
shows that if P (is true) then (so is) Q;
second (reading right to left), it says
that if you need to show Q it suffices
to show P because P → Q will then give
you the Q you need.
Reading #2 is what we exploit here. The
salient point is that if you know P → Q
and you need to show Q, then it suffices
to show P. P → Q thus allows you to reduce
the problem of showing Q to the problem of
showing P! This is a really important idea
to have in your mind. It's the principle
that we use in this next concrete example.
-/
/-
Here's how we use that basic idea.
To prove L = X, it will suffice to prove
∀ x, x ∈ L ↔ x ∈ X. If one has a proof
of ∀ x, x ∈ L ↔ x ∈ X, then one easily
obtains a proof of L = X by applying the
axiom of extensionality to it. Reading
right to left, if we need to prove L = X,
it will suffice to prove ∀ x, x ∈ L ↔ x ∈ X
(as one then just applies ext to get the
desired proof of X = L).
Look again at the definition of ext.
set.ext :
∀ {α : Type u_1} {a b : set α},
(∀ (x : α), x ∈ a ↔ x ∈ b) → a = b
What is says is that we can apply ext
to a proof of ∀ x, x ∈ L ↔ x ∈ X to get
a proof of L = X.
Here's the most important point: If we
apply ext to a "hole" where the proof
of the bi-implication should be, we will
have our proof of L = X, with only the
proof of ∀ x, x ∈ L ↔ x ∈ X remaining
to be produced. In this sense, applying
the axiom of set extensionality without
giving a proof of the bi-implication,
*reduces* the problem of proving L = X
to the problem of proving ∀ x, x ∈ L ↔
x ∈ X. And that is what we see next.
-/
example : ∀ {α : Type} (L X : set α), L ⊆ X → ((L ∩ X) = L) :=
begin
intros α L X h,
apply set.ext _, -- reduce = to ↔ by set extensionality
/-
That's the whole proof as long as we can fill in the _
That's what the rest of this proof script then does.
Notice again how "applying an implication theorem"
can be used to reduce a current proof goal to goals
the satisfaction of which "will suffice" to enable
construction of the proof that's needed.
-/
assume x,
split,
-- forward
assume h,
/-
Remember, h is a proof of a conjunction
so "cases h" really does and elimination
giving us the left and right subproofs as
the arguments that must have been given as
arguments to the and.intro that must have
been used to construct such a proof in
the first place.
-/
cases h with l r,
exact l,
-- quiz: would "exact h.left" have worked?
-- predict the answer before checking
-- backward
assume k,
exact and.intro k (h k),
/-
So this last "proof move" will take a little
time to think about. Look at the goal and think
for yourself what you really need to prove here.
Go back to the definitions! x ∈ L ∩ X really
just means L x ∧ X x. Does this help you to see
why and.intro is required here, and what each
of the terms in the preceding expression must
means?
-/
end
|
81457607d6e6b2a24349d57414d087daac5cc4a7 | 43390109ab88557e6090f3245c47479c123ee500 | /src/xenalib/Blair_Operation_on_Matrix.lean | 550facf5bbdc8428bec57843dd75bf50a91073ad | [
"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 | 968 | lean | /-
Copyright (c) 2018 Keji Neri, Blair Shi. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Blair Shi
* `adj M` gives the adjugate matrix of M
-/
import .linear_map .ring_n_is_module_of_vector
import xenalib.Ellen_Arlt_matrix_rings
import xenalib.Keji_further_matrix_things
def minor {R : Type} [comm_ring R] {n : ℕ} (M : matrix R (n + 1) (n + 1)) (a b : ℕ):
matrix R n n :=
λ I J,
if (I.1 < a ∧ J.1 < b)
then M I.1 J.1
else
if (I.1 >= a ∧ J.1 < b)
then M (I.1 + 1) J.1
else
if (I.1 >= a ∧ J.1 >= b)
then M (I.1 + 1) (J.1 + 1)
else M I.1 (J.1 + 1)
noncomputable def cofactor {R : Type} [comm_ring R] [comm_ring R] {n : ℕ} (M : matrix R (n + 1) (n + 1)) :
matrix R (n + 1) (n + 1) := λ I J, ((- 1) ^ (I.1 + J.1)) * (det (minor M I J))
noncomputable def adj {R : Type} [comm_ring R] {n : ℕ} (M : matrix R (n + 1) (n + 1)) :
matrix R (n + 1) (n + 1) := transpose (cofactor M)
|
72b2fce768d7f37276c559c216a9ffb2afc3291b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/explode_widget.lean | 0d66b7a91652055586bdd91e49c1954fdbbe76ad | [] | 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 | 640 | 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. -/
|
f424581aa82aa41c241e3c8709e203abafeb997e | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2020/sets/real_numbers.lean | d629a61fd4b16f592d388cd8c9142409a3ef87db | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 679 | lean | import data.real.ennreal
-- We define real numbers using decimals (base 10).
/-- The non-negative real numbers in the mind of a schoolkid -/
structure mynnreal : Type :=
-- An auxiliary non-negative real number $x$ has an
-- "integer part", its `floor`...
(floor : ℕ)
-- ...and the decimal part, an infinite string of digits
(frac : ℕ → fin 10) -- assuming base 10, so digits={0,1,...,9}
-- except that you're not allowed to end in infinitely many nines
(no_nines : ∀ (B : ℕ), ∃ (N : ℕ), B ≤ N ∧ frac N ≠ 9)
namespace mynnreal
def to_real (x : mynnreal) : ℝ :=
x.floor + 0 --infinite sums?
-- see thread "infinite sums of reals" on Zulip
end mynnreal
|
6dd784174c960515ec01e305653fecde77bb5f79 | 200b12985a863d01fbbde6abfc9326bb82424a8b | /src/propLogic/Ex016.lean | f9bad0cf80e6bca6922d99282cff0faa925a37ad | [] | no_license | SvenWille/LeanLogicExercises | 38eacd36733ac48e5a7aacf863c681c9a9a48271 | 2dbc920feadd63bbc50f87e69646c0081db26eba | refs/heads/master | 1,629,676,667,365 | 1,512,161,459,000 | 1,512,161,459,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 55 | lean |
theorem Ex016 (a b : Prop): a ∨ b ↔ b ∨ a :=
|
383319c9f3c7254eb592baa0b9c52dddc1973288 | d450724ba99f5b50b57d244eb41fef9f6789db81 | /src/mywork/lectures/lecture_23.lean | 9f7a341f1acb25a0e2d3cabfc2649e6dfa0630db | [] | no_license | jakekauff/CS2120F21 | 4f009adeb4ce4a148442b562196d66cc6c04530c | e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad | refs/heads/main | 1,693,841,880,030 | 1,637,604,848,000 | 1,637,604,848,000 | 399,946,698 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,178 | lean | import .lecture_21
/-
ADDITIONAL PROPERTIES OF RELATIONS
-/
namespace relations
section relation
/-
Define relation, r, as two-place predicate on
a type, β, with notation, x ≺ y, for (r x y).
-/
variables {α β : Type} (r : β → β → Prop)
local infix `≺`:50 := r
-- special relations on an arbitrary type, α
def empty_relation := λ a₁ a₂ : α, false
def full_relation := λ a₁ a₂ : α, true
def id_relation := λ a₁ a₂ : α, a₁ = a₂
-- Analog of the subset relation but now on binary relations
-- Note: subrelation is a binary relation on binary relations
def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y
/-
Commonly employed properties of relations
-/
def total := ∀ x y, x ≺ y ∨ y ≺ x
/-
Note: we will use "total" later to refer to a different
property of relations that also satisfy the constraints
needed to be "functions."
-/
def anti_reflexive := ∀ x, ¬ x ≺ x
def irreflexive := anti_reflexive r -- sometimes used
def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y
def asymmetric := ∀ ⦃x y⦄, x ≺ y → ¬ y ≺ x -- example: less than, greater than
-- Exercises:
/-
- Name a common anti_symmetric relation in arithmetic
- Name a common asymmetric relation in arithmetic
-/
example : reflexive r → ¬ asymmetric r := _-- true? true!
example : ¬ reflexive r ↔ irreflexive r := _ -- true? false!
inductive tc {α : Type} (r : α → α → Prop) : α → α → Prop
| base : ∀ a b, r a b → tc a b
| trans : ∀ a b c, tc a b → tc b c → tc a c
/-
Reflecting
https://dml.cz/bitstream/handle/10338.dmlcz/142762/ActaCarolinae_048-2007-1_5.pdf,
provide formal definition of each of the following properties of a binary relation,
r, on objects of a type, β. We will call r
– a quasiordering if r is reflexive and transitive;
– a strict (or sharp) ordering if r is irreflexive and transitive;
– a near-ordering if r is anti_symmetic and transitive;
– a (reflexive) ordering if r is reflexive, antisymmetric and transitive;
– a tolerance if r is reflexive and symmetric;
– * an equivalence if r is reflexive, symmetric and transitive
-/
def ordering := reflexive r ∧ transitive r ∧ anti_symmetric r -- new
def strict_ordering := asymmetric r ∧ transitive r
def partial_order := reflexive r ∧ anti_symmetric r ∧ transitive r ∧ ¬ total r
def total_order := reflexive r ∧ anti_symmetric r ∧ transitive r ∧ total r
/-
Definitions vary subtly. Be sure you know what is meant by these terms in any
given setting or application.
-/
end relation
end relations
/-
Pullback from binary relation along function and properties it preserves,
straight from Lean 3 Community mathlib.
def inv_image (f : α → β) : α → α → Prop :=
λ a₁ a₂, f a₁ ≺ f a₂
lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) :=
λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂
lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) :=
λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁
-/ |
9f4f923080548ac311ba606642f933391ceb95b8 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/ring_theory/algebra.lean | b2f6996628e7b34facdc051af6791f3be6c6a5c7 | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 23,070 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
Algebra over Commutative Ring (under category)
-/
import data.polynomial data.mv_polynomial
import data.complex.basic
import data.matrix.basic
import linear_algebra.tensor_product
import ring_theory.subring
import algebra.commute
noncomputable theory
universes u v w u₁ v₁
open_locale tensor_product
section prio
-- We set this priority to 0 later in this file
set_option default_priority 200 -- see Note [default priority]
/-- The category of R-algebras where R is a commutative
ring is the under category R ↓ CRing. In the categorical
setting we have a forgetful functor R-Alg ⥤ R-Mod.
However here it extends module in order to preserve
definitional equality in certain cases. -/
class algebra (R : Type u) (A : Type v) [comm_ring R] [ring A] extends has_scalar R A :=
(to_fun : R → A) [hom : is_ring_hom to_fun]
(commutes' : ∀ r x, x * to_fun r = to_fun r * x)
(smul_def' : ∀ r x, r • x = to_fun r * x)
end prio
def algebra_map {R : Type u} (A : Type v) [comm_ring R] [ring A] [algebra R A] (x : R) : A :=
algebra.to_fun A x
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w}
variables [comm_ring R] [comm_ring S] [ring A] [algebra R A]
instance : is_ring_hom (algebra_map A : R → A) := algebra.hom _ A
variables (A)
@[simp] lemma map_add (r s : R) : algebra_map A (r + s) = algebra_map A r + algebra_map A s :=
is_ring_hom.map_add _
@[simp] lemma map_neg (r : R) : algebra_map A (-r) = -algebra_map A r :=
is_ring_hom.map_neg _
@[simp] lemma map_sub (r s : R) : algebra_map A (r - s) = algebra_map A r - algebra_map A s :=
is_ring_hom.map_sub _
@[simp] lemma map_mul (r s : R) : algebra_map A (r * s) = algebra_map A r * algebra_map A s :=
is_ring_hom.map_mul _
variables (R)
@[simp] lemma map_zero : algebra_map A (0 : R) = 0 :=
is_ring_hom.map_zero _
@[simp] lemma map_one : algebra_map A (1 : R) = 1 :=
is_ring_hom.map_one _
variables {R A}
/-- Creating an algebra from a morphism in CRing. -/
def of_ring_hom (i : R → S) (hom : is_ring_hom i) : algebra R S :=
{ smul := λ c x, i c * x,
to_fun := i,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c x, rfl }
lemma smul_def'' (r : R) (x : A) : r • x = algebra_map A r * x :=
algebra.smul_def' r x
@[priority 200] -- see Note [lower instance priority]
instance to_module : module R A :=
{ one_smul := by simp [smul_def''],
mul_smul := by simp [smul_def'', mul_assoc],
smul_add := by simp [smul_def'', mul_add],
smul_zero := by simp [smul_def''],
add_smul := by simp [smul_def'', add_mul],
zero_smul := by simp [smul_def''] }
-- from now on, we don't want to use the following instance anymore
attribute [instance, priority 0] algebra.to_has_scalar
lemma smul_def (r : R) (x : A) : r • x = algebra_map A r * x :=
algebra.smul_def' r x
theorem commutes (r : R) (x : A) : x * algebra_map A r = algebra_map A r * x :=
algebra.commutes' r x
theorem left_comm (r : R) (x y : A) : x * (algebra_map A r * y) = algebra_map A r * (x * y) :=
by rw [← mul_assoc, commutes, mul_assoc]
@[simp] lemma mul_smul_comm (s : R) (x y : A) :
x * (s • y) = s • (x * y) :=
by rw [smul_def, smul_def, left_comm]
@[simp] lemma smul_mul_assoc (r : R) (x y : A) :
(r • x) * y = r • (x * y) :=
by rw [smul_def, smul_def, mul_assoc]
/-- R[X] is the generator of the category R-Alg. -/
instance polynomial (R : Type u) [comm_ring R] : algebra R (polynomial R) :=
{ to_fun := polynomial.C,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c p, (polynomial.C_mul' c p).symm,
.. polynomial.module }
/-- The algebra of multivariate polynomials. -/
instance mv_polynomial (R : Type u) [comm_ring R]
(ι : Type v) : algebra R (mv_polynomial ι R) :=
{ to_fun := mv_polynomial.C,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ c p, (mv_polynomial.C_mul' c p).symm,
.. mv_polynomial.module }
/-- Creating an algebra from a subring. This is the dual of ring extension. -/
instance of_subring (S : set R) [is_subring S] : algebra S R :=
of_ring_hom subtype.val ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩
variables (R A)
/-- The multiplication in an algebra is a bilinear map. -/
def lmul : A →ₗ A →ₗ A :=
linear_map.mk₂ R (*)
(λ x y z, add_mul x y z)
(λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y])
(λ x y z, mul_add x y z)
(λ c x y, by rw [smul_def, smul_def, left_comm])
def lmul_left (r : A) : A →ₗ A :=
lmul R A r
def lmul_right (r : A) : A →ₗ A :=
(lmul R A).flip r
variables {R A}
@[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl
@[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl
@[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl
end algebra
instance module.endomorphism_algebra (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) :=
{ to_fun := (λ r, r • linear_map.id),
hom := by apply is_ring_hom.mk; intros; ext; simp [mul_smul, add_smul],
commutes' := by intros; ext; simp,
smul_def' := by intros; ext; simp }
set_option class.instance_max_depth 40
instance matrix_algebra (n : Type u) (R : Type v)
[fintype n] [decidable_eq n] [comm_ring R] : algebra R (matrix n n R) :=
{ to_fun := (λ r, r • 1),
hom := { map_one := by { ext, simp, },
map_mul := by { intros, ext, simp [mul_assoc], },
map_add := by { intros, simp [add_smul], } },
commutes' := by { intros, simp },
smul_def' := by { intros, simp } }
set_option old_structure_cmd true
/-- Defining the homomorphism in the category R-Alg. -/
structure alg_hom (R : Type u) (A : Type v) (B : Type w)
[comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] extends ring_hom A B :=
(commutes' : ∀ r : R, to_fun (algebra_map A r) = algebra_map B r)
infixr ` →ₐ `:25 := alg_hom _
notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁}
variables {rR : comm_ring R} {rA : ring A} {rB : ring B} {rC : ring C} {rD : ring D}
variables {aA : algebra R A} {aB : algebra R B} {aC : algebra R C} {aD : algebra R D}
include R rR rA rB aA aB
instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩
instance : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩
variables (φ : A →ₐ[R] B)
instance : is_ring_hom ⇑φ := ring_hom.is_ring_hom φ.to_ring_hom
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
by cases φ₁; cases φ₂; congr' 1; ext; apply H
theorem commutes (r : R) : φ (algebra_map A r) = algebra_map B r := φ.commutes' r
@[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s :=
is_ring_hom.map_add _
@[simp] lemma map_zero : φ 0 = 0 :=
is_ring_hom.map_zero _
@[simp] lemma map_neg (x) : φ (-x) = -φ x :=
is_ring_hom.map_neg _
@[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y :=
is_ring_hom.map_sub _
@[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y :=
is_ring_hom.map_mul _
@[simp] lemma map_one : φ 1 = 1 :=
is_ring_hom.map_one _
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ B :=
{ to_fun := φ,
add := φ.map_add,
smul := λ (c : R) x, by rw [algebra.smul_def, φ.map_mul, φ.commutes c, algebra.smul_def] }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ :=
ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H
variables (R A)
omit rB aB
variables [rR] [rA] [aA]
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
variables {R A rR rA aA}
@[simp] lemma id_to_linear_map :
(alg_hom.id R A).to_linear_map = @linear_map.id R A _ _ _ := rfl
@[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
include rB rC aB aC
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C :=
{ commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl,
.. φ₁.to_ring_hom.comp ↑φ₂ }
@[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
@[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) :
φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
omit rC aC
@[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ :=
ext $ λ x, rfl
@[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ :=
ext $ λ x, rfl
include rC aC rD aD
theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext $ λ x, rfl
end alg_hom
namespace algebra
variables (R : Type u) (S : Type v) (A : Type w)
include R S A
/-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it
when `algebra R S` and `algebra S A`. -/
/- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and
`algebra ?m_1 A -/
/- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the
appropriate type classes -/
@[nolint unused_arguments] def comap : Type w := A
def comap.to_comap : A → comap R S A := id
def comap.of_comap : comap R S A → A := id
omit R S A
variables [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A]
instance comap.ring : ring (comap R S A) := _inst_3
instance comap.comm_ring (R : Type u) (S : Type v) (A : Type w)
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] :
comm_ring (comap R S A) := _inst_8
instance comap.module : module S (comap R S A) := show module S A, by apply_instance
instance comap.has_scalar : has_scalar S (comap R S A) := show has_scalar S A, by apply_instance
set_option class.instance_max_depth 40
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
instance comap.algebra : algebra R (comap R S A) :=
{ smul := λ r x, (algebra_map S r • x : A),
to_fun := (algebra_map A : S → A) ∘ algebra_map S,
hom := @is_ring_hom.comp _ _ _ _ _ _ _ _ _ _inst_5.hom,
commutes' := λ r x, algebra.commutes _ _,
smul_def' := λ _ _, algebra.smul_def _ _ }
def to_comap : S →ₐ[R] comap R S A :=
{ commutes' := λ r, rfl,
..ring_hom.of (algebra_map A : S → A) }
theorem to_comap_apply (x) : to_comap R S A x = (algebra_map A : S → A) x := rfl
end algebra
namespace alg_hom
variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁}
variables [comm_ring R] [comm_ring S] [ring A] [ring B]
variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B)
include R
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B :=
{ commutes' := λ r, φ.commutes (algebra_map S r)
..φ }
end alg_hom
namespace polynomial
variables (R : Type u) (A : Type v)
variables [comm_ring R] [comm_ring A] [algebra R A]
variables (x : A)
/-- A → Hom[R-Alg](R[X],A) -/
def aeval : polynomial R →ₐ[R] A :=
{ commutes' := λ r, eval₂_C _ _,
..ring_hom.of (eval₂ (algebra_map A) x) }
theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map A) x p := rfl
@[simp] lemma aeval_X : aeval R A x X = x := eval₂_X _ x
@[simp] lemma aeval_C (r : R) : aeval R A x (C r) = algebra_map A r := eval₂_C _ x
instance aeval.is_ring_hom : is_ring_hom (aeval R A x) :=
by apply_instance
theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) :
φ p = eval₂ (algebra_map A) (φ X) p :=
begin
apply polynomial.induction_on p,
{ intro r, rw eval₂_C, exact φ.commutes r },
{ intros f g ih1 ih2,
rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] },
{ intros n r ih,
rw [pow_succ', ← mul_assoc, is_ring_hom.map_mul φ, eval₂_mul (algebra_map A : R → A), eval₂_X, ih] }
end
end polynomial
namespace mv_polynomial
variables (R : Type u) (A : Type v)
variables [comm_ring R] [comm_ring A] [algebra R A]
variables (σ : set A)
/-- (ι → A) → Hom[R-Alg](R[ι],A) -/
def aeval : mv_polynomial σ R →ₐ[R] A :=
{ commutes' := λ r, eval₂_C _ _ _
..ring_hom.of (eval₂ (algebra_map A) subtype.val) }
theorem aeval_def (p : mv_polynomial σ R) : aeval R A σ p = eval₂ (algebra_map A) subtype.val p := rfl
@[simp] lemma aeval_X (s : σ) : aeval R A σ (X s) = s := eval₂_X _ _ _
@[simp] lemma aeval_C (r : R) : aeval R A σ (C r) = algebra_map A r := eval₂_C _ _ _
instance aeval.is_ring_hom : is_ring_hom (aeval R A σ) :=
by apply_instance
variables (ι : Type w)
theorem eval_unique (φ : mv_polynomial ι R →ₐ[R] A) (p) :
φ p = eval₂ (algebra_map A) (φ ∘ X) p :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw eval₂_C, exact φ.commutes r },
{ intros f g ih1 ih2,
rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] },
{ intros p j ih,
rw [is_ring_hom.map_mul φ, eval₂_mul, eval₂_X, ih] }
end
end mv_polynomial
namespace rat
instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α :=
{ smul := λ r x, (r : α) * x,
to_fun := coe,
hom := (rat.cast_hom α).is_ring_hom,
commutes' := λ r x, (commute.cast_int_right x r.1).div_right (commute.cast_nat_right x r.2),
smul_def' := λ _ _, rfl }
end rat
namespace complex
instance algebra_over_reals : algebra ℝ ℂ :=
algebra.of_ring_hom coe $ by constructor; intros; simp [one_re]
instance : has_scalar ℝ ℂ := { smul := λ r c, ↑r * c}
end complex
structure subalgebra (R : Type u) (A : Type v)
[comm_ring R] [ring A] [algebra R A] : Type v :=
(carrier : set A) [subring : is_subring carrier]
(range_le' : set.range (algebra_map A : R → A) ≤ carrier)
namespace subalgebra
variables {R : Type u} {A : Type v}
variables [comm_ring R] [ring A] [algebra R A]
include R
instance : has_coe (subalgebra R A) (set A) :=
⟨λ S, S.carrier⟩
lemma range_le (S : subalgebra R A) : set.range (algebra_map A : R → A) ≤ S := S.range_le'
instance : has_mem A (subalgebra R A) :=
⟨λ x S, x ∈ (S : set A)⟩
variables {A}
theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s :=
iff.rfl
@[ext] theorem ext {S T : subalgebra R A}
(h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T :=
by cases S; cases T; congr; ext x; exact h x
theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T :=
⟨λ h x, by rw h, ext⟩
variables (S : subalgebra R A)
instance : is_subring (S : set A) := S.subring
instance : ring S := @@subtype.ring _ S.is_subring
instance : inhabited S := ⟨0⟩
instance (R : Type u) (A : Type v) {rR : comm_ring R} [comm_ring A]
{aA : algebra R A} (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring
instance algebra : algebra R S :=
{ smul := λ (c:R) x, ⟨c • x.1,
by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩,
to_fun := λ r, ⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩,
hom := ⟨subtype.eq $ algebra.map_one R A, λ x y, subtype.eq $ algebra.map_mul A x y,
λ x y, subtype.eq $ algebra.map_add A x y⟩,
commutes' := λ c x, subtype.eq $ by apply _inst_3.4,
smul_def' := λ c x, subtype.eq $ by apply _inst_3.5 }
instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A]
[algebra R A] (S : subalgebra R A) : algebra S A :=
algebra.of_subring _
def val : S →ₐ[R] A :=
by refine_struct { to_fun := subtype.val }; intros; refl
def to_submodule : submodule R A :=
{ carrier := S,
zero := (0:S).2,
add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2,
smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 }
instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) :=
⟨to_submodule⟩
instance to_submodule.is_subring : is_subring ((S : submodule R A) : set A) := S.2
instance : partial_order (subalgebra R A) :=
{ le := λ S T, (S : set A) ≤ (T : set A),
le_refl := λ _, le_refl _,
le_trans := λ _ _ _, le_trans,
le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ }
def comap {R : Type u} {S : Type v} {A : Type w}
[comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A]
(iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) :=
{ carrier := (iSB : set A),
subring := iSB.is_subring,
range_le' := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ }
def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A]
{i : algebra R A} (S : subalgebra R A)
(T : subalgebra S A) : subalgebra R A :=
{ carrier := T,
range_le' := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) }
end subalgebra
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w}
variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
protected def range : subalgebra R B :=
{ carrier := set.range φ,
subring :=
{ one_mem := ⟨1, φ.map_one⟩,
mul_mem := λ y₁ y₂ ⟨x₁, hx₁⟩ ⟨x₂, hx₂⟩, ⟨x₁ * x₂, hx₁ ▸ hx₂ ▸ φ.map_mul x₁ x₂⟩ },
range_le' := λ y ⟨r, hr⟩, ⟨algebra_map A r, hr ▸ φ.commutes r⟩ }
end alg_hom
namespace algebra
variables {R : Type u} (A : Type v)
variables [comm_ring R] [ring A] [algebra R A]
include R
variables (R)
instance id : algebra R R :=
algebra.of_ring_hom id $ by apply_instance
namespace id
@[simp] lemma map_eq_self (x : R) : algebra_map R x = x := rfl
@[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl
end id
def of_id : R →ₐ A :=
{ commutes' := λ _, rfl, .. ring_hom.of (algebra_map A) }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map A r := rfl
variables (R) {A}
def adjoin (s : set A) : subalgebra R A :=
{ carrier := ring.closure (set.range (algebra_map A : R → A) ∪ s),
range_le' := le_trans (set.subset_union_left _ _) ring.subset_closure }
variables {R}
protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe :=
λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H,
λ H, ring.closure_subset $ set.union_subset S.range_le H⟩
protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe :=
{ choice := λ s hs, adjoin R s,
gc := algebra.gc,
le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _,
choice_eq := λ _ _, rfl }
instance : complete_lattice (subalgebra R A) :=
galois_insertion.lift_complete_lattice algebra.gi
instance : inhabited (subalgebra R A) := ⟨⊥⟩
theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map A : R → A) :=
suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl,
le_antisymm bot_le $ subalgebra.range_le _
theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) :=
ring.mem_closure $ or.inr trivial
theorem eq_top_iff {S : subalgebra R A} :
S = ⊤ ↔ ∀ x : A, x ∈ S :=
⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩
def to_top : A →ₐ[R] (⊤ : subalgebra R A) :=
by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl
end algebra
section int
variables (R : Type*) [comm_ring R]
/-- CRing ⥤ ℤ-Alg -/
def alg_hom_int
{R : Type u} [comm_ring R] [algebra ℤ R]
{S : Type v} [comm_ring S] [algebra ℤ S]
(f : R → S) [is_ring_hom f] : R →ₐ[ℤ] S :=
{ commutes' := λ i, by change (ring_hom.of f).to_fun with f; exact
int.induction_on i (by rw [algebra.map_zero, algebra.map_zero, is_ring_hom.map_zero f])
(λ i ih, by rw [algebra.map_add, algebra.map_add, algebra.map_one, algebra.map_one];
rw [is_ring_hom.map_add f, is_ring_hom.map_one f, ih])
(λ i ih, by rw [algebra.map_sub, algebra.map_sub, algebra.map_one, algebra.map_one];
rw [is_ring_hom.map_sub f, is_ring_hom.map_one f, ih]),
..ring_hom.of f }
/-- CRing ⥤ ℤ-Alg -/
instance algebra_int : algebra ℤ R :=
{ to_fun := coe,
commutes' := λ _ _, mul_comm _ _,
smul_def' := λ _ _, gsmul_eq_mul _ _ }
variables {R}
/-- CRing ⥤ ℤ-Alg -/
def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R :=
{ carrier := S, range_le' := λ x ⟨i, h⟩, h ▸ int.induction_on i
(by rw algebra.map_zero; exact is_add_submonoid.zero_mem _)
(λ i hi, by rw [algebra.map_add, algebra.map_one]; exact is_add_submonoid.add_mem hi (is_submonoid.one_mem _))
(λ i hi, by rw [algebra.map_sub, algebra.map_one]; exact is_add_subgroup.sub_mem _ _ _ hi (is_submonoid.one_mem _)) }
@[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] :
x ∈ subalgebra_of_subring S ↔ x ∈ S :=
iff.rfl
section span_int
open submodule
lemma span_int_eq_add_group_closure (s : set R) :
↑(span ℤ s) = add_group.closure s :=
set.subset.antisymm (λ x hx, span_induction hx
(λ _, add_group.mem_closure)
(is_add_submonoid.zero_mem _)
(λ a b ha hb, is_add_submonoid.add_mem ha hb)
(λ n a ha, by { exact is_add_subgroup.gsmul_mem ha }))
(add_group.closure_subset subset_span)
@[simp] lemma span_int_eq (s : set R) [is_add_subgroup s] :
(↑(span ℤ s) : set R) = s :=
by rw [span_int_eq_add_group_closure, add_group.closure_add_subgroup]
end span_int
end int
section restrict_scalars
/- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then
`S`-modules are also `R`-modules. -/
variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S]
(E : Type*) [add_comm_group E] [module S E] {F : Type*} [add_comm_group F] [module S F]
/-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, called `module.restrict S R E`.
Not registered as an instance as `S` can not be inferred. -/
def module.restrict_scalars : module R E :=
{ smul := λc x, (algebra_map S c) • x,
one_smul := by simp,
mul_smul := by simp [mul_smul],
smul_add := by simp [smul_add],
smul_zero := by simp [smul_zero],
add_smul := by simp [add_smul],
zero_smul := by simp [zero_smul] }
variables {S E}
local attribute [instance] module.restrict_scalars
/-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/
def linear_map.restrict_scalars (f : E →ₗ[S] F) : E →ₗ[R] F :=
{ to_fun := f.to_fun,
add := λx y, f.map_add x y,
smul := λc x, f.map_smul (algebra_map S c) x }
@[simp, squash_cast] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) :
(f.restrict_scalars R : E → F) = f := rfl
/- Register as an instance (with low priority) the fact that a complex vector space is also a real
vector space. -/
instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E :=
module.restrict_scalars ℝ ℂ E
attribute [instance, priority 900] module.complex_to_real
end restrict_scalars
|
7d77d3f28230c5a69b35a0f9e76cf260a711d7e6 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/probability/variance.lean | 4b43f159ed94907d7fa3a41736215af0921de565 | [
"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 | 10,841 | lean | /-
Copyright (c) 2022 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import probability.notation
import probability.integration
/-!
# Variance of random variables
We define the variance of a real-valued random variable as `Var[X] = 𝔼[(X - 𝔼[X])^2]` (in the
`probability_theory` locale).
We prove the basic properties of the variance:
* `variance_le_expectation_sq`: the inequality `Var[X] ≤ 𝔼[X^2]`.
* `meas_ge_le_variance_div_sq`: Chebyshev's inequality, i.e.,
`ℙ {ω | c ≤ |X ω - 𝔼[X]|} ≤ ennreal.of_real (Var[X] / c ^ 2)`.
* `indep_fun.variance_add`: the variance of the sum of two independent random variables is the sum
of the variances.
* `indep_fun.variance_sum`: the variance of a finite sum of pairwise independent random variables is
the sum of the variances.
-/
open measure_theory filter finset
noncomputable theory
open_locale big_operators measure_theory probability_theory ennreal nnreal
namespace probability_theory
/-- The variance of a random variable is `𝔼[X^2] - 𝔼[X]^2` or, equivalently, `𝔼[(X - 𝔼[X])^2]`. We
use the latter as the definition, to ensure better behavior even in garbage situations. -/
def variance {Ω : Type*} {m : measurable_space Ω} (f : Ω → ℝ) (μ : measure Ω) : ℝ :=
μ[(f - (λ x, μ[f])) ^ 2]
@[simp] lemma variance_zero {Ω : Type*} {m : measurable_space Ω} (μ : measure Ω) :
variance 0 μ = 0 :=
by simp [variance]
lemma variance_nonneg {Ω : Type*} {m : measurable_space Ω} (f : Ω → ℝ) (μ : measure Ω) :
0 ≤ variance f μ :=
integral_nonneg (λ x, sq_nonneg _)
lemma variance_mul {Ω : Type*} {m : measurable_space Ω} (c : ℝ) (f : Ω → ℝ) (μ : measure Ω) :
variance (λ x, c * f x) μ = c^2 * variance f μ :=
calc
variance (λ x, c * f x) μ
= ∫ x, (c * f x - ∫ y, c * f y ∂μ) ^ 2 ∂μ : rfl
... = ∫ x, (c * (f x - ∫ y, f y ∂μ)) ^ 2 ∂μ :
by { congr' 1 with x, simp_rw [integral_mul_left, mul_sub] }
... = c^2 * variance f μ :
by { simp_rw [mul_pow, integral_mul_left], refl }
lemma variance_smul {Ω : Type*} {m : measurable_space Ω} (c : ℝ) (f : Ω → ℝ) (μ : measure Ω) :
variance (c • f) μ = c^2 * variance f μ :=
variance_mul c f μ
lemma variance_smul' {A : Type*} [comm_semiring A] [algebra A ℝ]
{Ω : Type*} {m : measurable_space Ω} (c : A) (f : Ω → ℝ) (μ : measure Ω) :
variance (c • f) μ = c^2 • variance f μ :=
begin
convert variance_smul (algebra_map A ℝ c) f μ,
{ ext1 x, simp only [algebra_map_smul], },
{ simp only [algebra.smul_def, map_pow], }
end
localized
"notation `Var[` X `]` := probability_theory.variance X measure_theory.measure_space.volume"
in probability_theory
variables {Ω : Type*} [measure_space Ω] [is_probability_measure (volume : measure Ω)]
lemma variance_def' {X : Ω → ℝ} (hX : mem_ℒp X 2) :
Var[X] = 𝔼[X^2] - 𝔼[X]^2 :=
begin
rw [variance, sub_sq', integral_sub', integral_add'], rotate,
{ exact hX.integrable_sq },
{ convert integrable_const (𝔼[X] ^ 2),
apply_instance },
{ apply hX.integrable_sq.add,
convert integrable_const (𝔼[X] ^ 2),
apply_instance },
{ exact ((hX.integrable ennreal.one_le_two).const_mul 2).mul_const' _ },
simp only [integral_mul_right, pi.pow_apply, pi.mul_apply, pi.bit0_apply, pi.one_apply,
integral_const (integral ℙ X ^ 2), integral_mul_left (2 : ℝ), one_mul,
variance, pi.pow_apply, measure_univ, ennreal.one_to_real, algebra.id.smul_eq_mul],
ring,
end
lemma variance_le_expectation_sq {X : Ω → ℝ} :
Var[X] ≤ 𝔼[X^2] :=
begin
by_cases h_int : integrable X, swap,
{ simp only [variance, integral_undef h_int, pi.pow_apply, pi.sub_apply, sub_zero] },
by_cases hX : mem_ℒp X 2,
{ rw variance_def' hX,
simp only [sq_nonneg, sub_le_self_iff] },
{ rw [variance, integral_undef],
{ exact integral_nonneg (λ a, sq_nonneg _) },
{ assume h,
have A : mem_ℒp (X - λ (x : Ω), 𝔼[X]) 2 ℙ := (mem_ℒp_two_iff_integrable_sq
(h_int.ae_strongly_measurable.sub ae_strongly_measurable_const)).2 h,
have B : mem_ℒp (λ (x : Ω), 𝔼[X]) 2 ℙ := mem_ℒp_const _,
apply hX,
convert A.add B,
simp } }
end
/-- *Chebyshev's inequality* : one can control the deviation probability of a real random variable
from its expectation in terms of the variance. -/
theorem meas_ge_le_variance_div_sq {X : Ω → ℝ} (hX : mem_ℒp X 2) {c : ℝ} (hc : 0 < c) :
ℙ {ω | c ≤ |X ω - 𝔼[X]|} ≤ ennreal.of_real (Var[X] / c ^ 2) :=
begin
have A : (ennreal.of_real c : ℝ≥0∞) ≠ 0,
by simp only [hc, ne.def, ennreal.of_real_eq_zero, not_le],
have B : ae_strongly_measurable (λ (ω : Ω), 𝔼[X]) ℙ := ae_strongly_measurable_const,
convert meas_ge_le_mul_pow_snorm ℙ ennreal.two_ne_zero ennreal.two_ne_top
(hX.ae_strongly_measurable.sub B) A,
{ ext ω,
set d : ℝ≥0 := ⟨c, hc.le⟩ with hd,
have cd : c = d, by simp only [subtype.coe_mk],
simp only [pi.sub_apply, ennreal.coe_le_coe, ← real.norm_eq_abs, ← coe_nnnorm,
nnreal.coe_le_coe, cd, ennreal.of_real_coe_nnreal] },
{ rw (hX.sub (mem_ℒp_const _)).snorm_eq_integral_rpow_norm
ennreal.two_ne_zero ennreal.two_ne_top,
simp only [pi.sub_apply, ennreal.to_real_bit0, ennreal.one_to_real],
rw ennreal.of_real_rpow_of_nonneg _ zero_le_two, rotate,
{ apply real.rpow_nonneg_of_nonneg,
exact integral_nonneg (λ x, real.rpow_nonneg_of_nonneg (norm_nonneg _) _) },
rw [variance, ← real.rpow_mul, inv_mul_cancel], rotate,
{ exact two_ne_zero },
{ exact integral_nonneg (λ x, real.rpow_nonneg_of_nonneg (norm_nonneg _) _) },
simp only [pi.pow_apply, pi.sub_apply, real.rpow_two, real.rpow_one, real.norm_eq_abs,
pow_bit0_abs, ennreal.of_real_inv_of_pos hc, ennreal.rpow_two],
rw [← ennreal.of_real_pow (inv_nonneg.2 hc.le), ← ennreal.of_real_mul (sq_nonneg _),
div_eq_inv_mul, inv_pow] }
end
/-- The variance of the sum of two independent random variables is the sum of the variances. -/
theorem indep_fun.variance_add {X Y : Ω → ℝ}
(hX : mem_ℒp X 2) (hY : mem_ℒp Y 2) (h : indep_fun X Y) :
Var[X + Y] = Var[X] + Var[Y] :=
calc
Var[X + Y] = 𝔼[λ a, (X a)^2 + (Y a)^2 + 2 * X a * Y a] - 𝔼[X+Y]^2 :
by simp [variance_def' (hX.add hY), add_sq']
... = (𝔼[X^2] + 𝔼[Y^2] + 2 * 𝔼[X * Y]) - (𝔼[X] + 𝔼[Y])^2 :
begin
simp only [pi.add_apply, pi.pow_apply, pi.mul_apply, mul_assoc],
rw [integral_add, integral_add, integral_add, integral_mul_left],
{ exact hX.integrable ennreal.one_le_two },
{ exact hY.integrable ennreal.one_le_two },
{ exact hX.integrable_sq },
{ exact hY.integrable_sq },
{ exact hX.integrable_sq.add hY.integrable_sq },
{ apply integrable.const_mul,
exact h.integrable_mul (hX.integrable ennreal.one_le_two) (hY.integrable ennreal.one_le_two) }
end
... = (𝔼[X^2] + 𝔼[Y^2] + 2 * (𝔼[X] * 𝔼[Y])) - (𝔼[X] + 𝔼[Y])^2 :
begin
congr,
exact h.integral_mul_of_integrable
(hX.integrable ennreal.one_le_two) (hY.integrable ennreal.one_le_two),
end
... = Var[X] + Var[Y] :
by { simp only [variance_def', hX, hY, pi.pow_apply], ring }
/-- The variance of a finite sum of pairwise independent random variables is the sum of the
variances. -/
theorem indep_fun.variance_sum {ι : Type*} {X : ι → Ω → ℝ} {s : finset ι}
(hs : ∀ i ∈ s, mem_ℒp (X i) 2) (h : set.pairwise ↑s (λ i j, indep_fun (X i) (X j))) :
Var[∑ i in s, X i] = ∑ i in s, Var[X i] :=
begin
classical,
induction s using finset.induction_on with k s ks IH,
{ simp only [finset.sum_empty, variance_zero] },
rw [variance_def' (mem_ℒp_finset_sum' _ hs), sum_insert ks, sum_insert ks],
simp only [add_sq'],
calc 𝔼[X k ^ 2 + (∑ i in s, X i) ^ 2 + 2 * X k * ∑ i in s, X i] - 𝔼[X k + ∑ i in s, X i] ^ 2
= (𝔼[X k ^ 2] + 𝔼[(∑ i in s, X i) ^ 2] + 𝔼[2 * X k * ∑ i in s, X i])
- (𝔼[X k] + 𝔼[∑ i in s, X i]) ^ 2 :
begin
rw [integral_add', integral_add', integral_add'],
{ exact mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_self _ _)) },
{ apply integrable_finset_sum' _ (λ i hi, _),
exact mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_of_mem hi)) },
{ exact mem_ℒp.integrable_sq (hs _ (mem_insert_self _ _)) },
{ apply mem_ℒp.integrable_sq,
exact mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))) },
{ apply integrable.add,
{ exact mem_ℒp.integrable_sq (hs _ (mem_insert_self _ _)) },
{ apply mem_ℒp.integrable_sq,
exact mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))) } },
{ rw mul_assoc,
apply integrable.const_mul _ 2,
simp only [mul_sum, sum_apply, pi.mul_apply],
apply integrable_finset_sum _ (λ i hi, _),
apply indep_fun.integrable_mul _
(mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_self _ _)))
(mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_of_mem hi))),
apply h (mem_insert_self _ _) (mem_insert_of_mem hi),
exact (λ hki, ks (hki.symm ▸ hi)) }
end
... = Var[X k] + Var[∑ i in s, X i] +
(𝔼[2 * X k * ∑ i in s, X i] - 2 * 𝔼[X k] * 𝔼[∑ i in s, X i]) :
begin
rw [variance_def' (hs _ (mem_insert_self _ _)),
variance_def' (mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))))],
ring,
end
... = Var[X k] + Var[∑ i in s, X i] :
begin
simp only [mul_assoc, integral_mul_left, pi.mul_apply, pi.bit0_apply, pi.one_apply, sum_apply,
add_right_eq_self, mul_sum],
rw integral_finset_sum s (λ i hi, _), swap,
{ apply integrable.const_mul _ 2,
apply indep_fun.integrable_mul _
(mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_self _ _)))
(mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_of_mem hi))),
apply h (mem_insert_self _ _) (mem_insert_of_mem hi),
exact (λ hki, ks (hki.symm ▸ hi)) },
rw [integral_finset_sum s
(λ i hi, (mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_of_mem hi)))),
mul_sum, mul_sum, ← sum_sub_distrib],
apply finset.sum_eq_zero (λ i hi, _),
rw [integral_mul_left, indep_fun.integral_mul_of_integrable', sub_self],
{ apply h (mem_insert_self _ _) (mem_insert_of_mem hi),
exact (λ hki, ks (hki.symm ▸ hi)) },
{ exact mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_self _ _)) },
{ exact mem_ℒp.integrable ennreal.one_le_two (hs _ (mem_insert_of_mem hi)) }
end
... = Var[X k] + ∑ i in s, Var[X i] :
by rw IH (λ i hi, hs i (mem_insert_of_mem hi))
(h.mono (by simp only [coe_insert, set.subset_insert]))
end
end probability_theory
|
7f41ae4f5b1dabb76c8692d9a2bdfd6ef7162954 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/ind0.lean | 2c5db4fb06aa7f6d8f5f8582e9c8f8552e2cfe30 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 94 | lean | prelude
inductive nat : Type
| zero : nat
| succ : nat → nat
#check nat
#check nat.rec.{1}
|
e00e59ba87e9d88e1cb6dccb65d07ce589f85f44 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/category_theory/bicategory/functor.lean | ad5757a9bb35b2ae44909972c5c33b486b916f73 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 19,303 | lean | /-
Copyright (c) 2022 Yuma Mizuno. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yuma Mizuno
-/
import category_theory.bicategory.basic
/-!
# Oplax functors and pseudofunctors
An oplax functor `F` between bicategories `B` and `C` consists of
* a function between objects `F.obj : B ⟶ C`,
* a family of functions between 1-morphisms `F.map : (a ⟶ b) → (F.obj a ⟶ F.obj b)`,
* a family of functions between 2-morphisms `F.map₂ : (f ⟶ g) → (F.map f ⟶ F.map g)`,
* a family of 2-morphisms `F.map_id a : F.map (𝟙 a) ⟶ 𝟙 (F.obj a)`,
* a family of 2-morphisms `F.map_comp f g : F.map (f ≫ g) ⟶ F.map f ≫ F.map g`, and
* certain consistency conditions on them.
A pseudofunctor is an oplax functor whose `map_id` and `map_comp` are isomorphisms. We provide
several constructors for pseudofunctors:
* `pseudofunctor.mk` : the default constructor, which requires `map₂_whisker_left` and
`map₂_whisker_right` instead of naturality of `map_comp`.
* `pseudofunctor.mk_of_oplax` : construct a pseudofunctor from an oplax functor whose
`map_id` and `map_comp` are isomorphisms. This constructor uses `iso` to describe isomorphisms.
* `pseudofunctor.mk_of_oplax'` : similar to `mk_of_oplax`, but uses `is_iso` to describe
isomorphisms.
The additional constructors are useful when constructing a pseudofunctor where the construction
of the oplax functor associated with it is already done. For example, the composition of
pseudofunctors can be defined by using the composition of oplax functors as follows:
```lean
def pseudofunctor.comp (F : pseudofunctor B C) (G : pseudofunctor C D) : pseudofunctor B D :=
mk_of_oplax ((F : oplax_functor B C).comp G)
{ map_id_iso := λ a, (G.map_functor _ _).map_iso (F.map_id a) ≪≫ G.map_id (F.obj a),
map_comp_iso := λ a b c f g,
(G.map_functor _ _).map_iso (F.map_comp f g) ≪≫ G.map_comp (F.map f) (F.map g) }
```
although the composition of pseudofunctors in this file is defined by using the default constructor
because `obviously` is smart enough. Similarly, the composition is also defined by using
`mk_of_oplax'` after giving appropriate instances for `is_iso`. The former constructor
`mk_of_oplax` requires isomorphisms as data type `iso`, and so it is useful if you don't want
to forget the definitions of the inverses. On the other hand, the latter constructor
`mk_of_oplax'` is useful if you want to use propositional type class `is_iso`.
## Main definitions
* `category_theory.oplax_functor B C` : an oplax functor between bicategories `B` and `C`
* `category_theory.oplax_functor.comp F G` : the composition of oplax functors
* `category_theory.pseudofunctor B C` : a pseudofunctor between bicategories `B` and `C`
* `category_theory.pseudofunctor.comp F G` : the composition of pseudofunctors
## Future work
There are two types of functors between bicategories, called lax and oplax functors, depending on
the directions of `map_id` and `map_comp`. We may need both in mathlib in the future, but for
now we only define oplax functors.
-/
set_option old_structure_cmd true
namespace category_theory
open category bicategory
open_locale bicategory
universes w₁ w₂ w₃ v₁ v₂ v₃ u₁ u₂ u₃
section
variables {B : Type u₁} [quiver.{v₁+1} B] [∀ a b : B, quiver.{w₁+1} (a ⟶ b)]
variables {C : Type u₂} [quiver.{v₂+1} C] [∀ a b : C, quiver.{w₂+1} (a ⟶ b)]
variables {D : Type u₃} [quiver.{v₃+1} D] [∀ a b : D, quiver.{w₃+1} (a ⟶ b)]
/--
A prelax functor between bicategories consists of functions between objects,
1-morphisms, and 2-morphisms. This structure will be extended to define `oplax_functor`.
-/
structure prelax_functor
(B : Type u₁) [quiver.{v₁+1} B] [∀ a b : B, quiver.{w₁+1} (a ⟶ b)]
(C : Type u₂) [quiver.{v₂+1} C] [∀ a b : C, quiver.{w₂+1} (a ⟶ b)] extends prefunctor B C :=
(map₂ {a b : B} {f g : a ⟶ b} : (f ⟶ g) → (map f ⟶ map g))
/-- The prefunctor between the underlying quivers. -/
add_decl_doc prelax_functor.to_prefunctor
namespace prelax_functor
instance has_coe_to_prefunctor : has_coe (prelax_functor B C) (prefunctor B C) := ⟨to_prefunctor⟩
variables (F : prelax_functor B C)
@[simp] lemma to_prefunctor_eq_coe : F.to_prefunctor = F := rfl
@[simp] lemma to_prefunctor_obj : (F : prefunctor B C).obj = F.obj := rfl
@[simp] lemma to_prefunctor_map : (F : prefunctor B C).map = F.map := rfl
/-- The identity prelax functor. -/
@[simps]
def id (B : Type u₁) [quiver.{v₁+1} B] [∀ a b : B, quiver.{w₁+1} (a ⟶ b)] : prelax_functor B B :=
{ map₂ := λ a b f g η, η, .. prefunctor.id B }
instance : inhabited (prelax_functor B B) := ⟨prelax_functor.id B⟩
/-- Composition of prelax functors. -/
@[simps]
def comp (F : prelax_functor B C) (G : prelax_functor C D) : prelax_functor B D :=
{ map₂ := λ a b f g η, G.map₂ (F.map₂ η), .. (F : prefunctor B C).comp ↑G }
end prelax_functor
end
section
variables {B : Type u₁} [bicategory.{w₁ v₁} B] {C : Type u₂} [bicategory.{w₂ v₂} C]
variables {D : Type u₃} [bicategory.{w₃ v₃} D]
/--
This auxiliary definition states that oplax functors preserve the associators
modulo some adjustments of domains and codomains of 2-morphisms.
-/
/-
We use this auxiliary definition instead of writing it directly in the definition
of oplax functors because doing so will cause a timeout.
-/
@[simp]
def oplax_functor.map₂_associator_aux
(obj : B → C) (map : Π {X Y : B}, (X ⟶ Y) → (obj X ⟶ obj Y))
(map₂ : Π {a b : B} {f g : a ⟶ b}, (f ⟶ g) → (map f ⟶ map g))
(map_comp : Π {a b c : B} (f : a ⟶ b) (g : b ⟶ c), map (f ≫ g) ⟶ map f ≫ map g)
{a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) : Prop :=
map₂ (α_ f g h).hom ≫ map_comp f (g ≫ h) ≫ map f ◁ map_comp g h =
map_comp (f ≫ g) h ≫ map_comp f g ▷ map h ≫ (α_ (map f) (map g) (map h)).hom
/--
An oplax functor `F` between bicategories `B` and `C` consists of a function between objects
`F.obj`, a function between 1-morphisms `F.map`, and a function between 2-morphisms `F.map₂`.
Unlike functors between categories, `F.map` do not need to strictly commute with the composition,
and do not need to strictly preserve the identity. Instead, there are specified 2-morphisms
`F.map (𝟙 a) ⟶ 𝟙 (F.obj a)` and `F.map (f ≫ g) ⟶ F.map f ≫ F.map g`.
`F.map₂` strictly commute with compositions and preserve the identity. They also preserve the
associator, the left unitor, and the right unitor modulo some adjustments of domains and codomains
of 2-morphisms.
-/
structure oplax_functor (B : Type u₁) [bicategory.{w₁ v₁} B] (C : Type u₂) [bicategory.{w₂ v₂} C]
extends prelax_functor B C :=
(map_id (a : B) : map (𝟙 a) ⟶ 𝟙 (obj a))
(map_comp {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : map (f ≫ g) ⟶ map f ≫ map g)
(map_comp_naturality_left' : ∀ {a b c : B} {f f' : a ⟶ b} (η : f ⟶ f') (g : b ⟶ c),
map₂ (η ▷ g) ≫ map_comp f' g = map_comp f g ≫ map₂ η ▷ map g . obviously)
(map_comp_naturality_right' : ∀ {a b c : B} (f : a ⟶ b) {g g' : b ⟶ c} (η : g ⟶ g'),
map₂ (f ◁ η) ≫ map_comp f g' = map_comp f g ≫ map f ◁ map₂ η . obviously)
(map₂_id' : ∀ {a b : B} (f : a ⟶ b), map₂ (𝟙 f) = 𝟙 (map f) . obviously)
(map₂_comp' : ∀ {a b : B} {f g h : a ⟶ b} (η : f ⟶ g) (θ : g ⟶ h),
map₂ (η ≫ θ) = map₂ η ≫ map₂ θ . obviously)
(map₂_associator' : ∀ {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d),
oplax_functor.map₂_associator_aux obj (λ a b, map) (λ a b f g, map₂) (λ a b c, map_comp) f g h
. obviously)
(map₂_left_unitor' : ∀ {a b : B} (f : a ⟶ b),
map₂ (λ_ f).hom = map_comp (𝟙 a) f ≫ map_id a ▷ map f ≫ (λ_ (map f)).hom . obviously)
(map₂_right_unitor' : ∀ {a b : B} (f : a ⟶ b),
map₂ (ρ_ f).hom = map_comp f (𝟙 b) ≫ map f ◁ map_id b ≫ (ρ_ (map f)).hom . obviously)
namespace oplax_functor
restate_axiom map_comp_naturality_left'
restate_axiom map_comp_naturality_right'
restate_axiom map₂_id'
restate_axiom map₂_comp'
restate_axiom map₂_associator'
restate_axiom map₂_left_unitor'
restate_axiom map₂_right_unitor'
attribute [simp] map_comp_naturality_left map_comp_naturality_right map₂_id map₂_associator
attribute [reassoc]
map_comp_naturality_left map_comp_naturality_right map₂_comp
map₂_associator map₂_left_unitor map₂_right_unitor
attribute [simp] map₂_comp map₂_left_unitor map₂_right_unitor
section
/-- The prelax functor between the underlying quivers. -/
add_decl_doc oplax_functor.to_prelax_functor
instance has_coe_to_prelax : has_coe (oplax_functor B C) (prelax_functor B C) :=
⟨to_prelax_functor⟩
variables (F : oplax_functor B C)
@[simp] lemma to_prelax_eq_coe : F.to_prelax_functor = F := rfl
@[simp] lemma to_prelax_functor_obj : (F : prelax_functor B C).obj = F.obj := rfl
@[simp] lemma to_prelax_functor_map : (F : prelax_functor B C).map = F.map := rfl
@[simp] lemma to_prelax_functor_map₂ : (F : prelax_functor B C).map₂ = F.map₂ := rfl
/-- Function between 1-morphisms as a functor. -/
@[simps]
def map_functor (a b : B) : (a ⟶ b) ⥤ (F.obj a ⟶ F.obj b) :=
{ obj := λ f, F.map f,
map := λ f g η, F.map₂ η }
/-- The identity oplax functor. -/
@[simps]
def id (B : Type u₁) [bicategory.{w₁ v₁} B] : oplax_functor B B :=
{ map_id := λ a, 𝟙 (𝟙 a),
map_comp := λ a b c f g, 𝟙 (f ≫ g),
.. prelax_functor.id B }
instance : inhabited (oplax_functor B B) := ⟨id B⟩
/-- Composition of oplax functors. -/
@[simps]
def comp (F : oplax_functor B C) (G : oplax_functor C D) : oplax_functor B D :=
{ map_id := λ a,
(G.map_functor _ _).map (F.map_id a) ≫ G.map_id (F.obj a),
map_comp := λ a b c f g,
(G.map_functor _ _).map (F.map_comp f g) ≫ G.map_comp (F.map f) (F.map g),
map_comp_naturality_left' := λ a b c f f' η g, by
{ dsimp,
rw [←map₂_comp_assoc, map_comp_naturality_left, map₂_comp_assoc, map_comp_naturality_left,
assoc] },
map_comp_naturality_right' := λ a b c f g g' η, by
{ dsimp,
rw [←map₂_comp_assoc, map_comp_naturality_right, map₂_comp_assoc, map_comp_naturality_right,
assoc] },
map₂_associator' := λ a b c d f g h, by
{ dsimp,
simp only [map₂_associator, ←map₂_comp_assoc, ←map_comp_naturality_right_assoc,
whisker_left_comp, assoc],
simp only [map₂_associator, map₂_comp, map_comp_naturality_left_assoc,
comp_whisker_right, assoc] },
map₂_left_unitor' := λ a b f, by
{ dsimp,
simp only [map₂_left_unitor, map₂_comp, map_comp_naturality_left_assoc,
comp_whisker_right, assoc] },
map₂_right_unitor' := λ a b f, by
{ dsimp,
simp only [map₂_right_unitor, map₂_comp, map_comp_naturality_right_assoc,
whisker_left_comp, assoc] },
.. (F : prelax_functor B C).comp ↑G }
/--
A structure on an oplax functor that promotes an oplax functor to a pseudofunctor.
See `pseudofunctor.mk_of_oplax`.
-/
@[nolint has_nonempty_instance]
structure pseudo_core (F : oplax_functor B C) :=
(map_id_iso (a : B) : F.map (𝟙 a) ≅ 𝟙 (F.obj a))
(map_comp_iso {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : F.map (f ≫ g) ≅ F.map f ≫ F.map g)
(map_id_iso_hom' : ∀ {a : B}, (map_id_iso a).hom = F.map_id a . obviously)
(map_comp_iso_hom' : ∀ {a b c : B} (f : a ⟶ b) (g : b ⟶ c),
(map_comp_iso f g).hom = F.map_comp f g . obviously)
restate_axiom pseudo_core.map_id_iso_hom'
restate_axiom pseudo_core.map_comp_iso_hom'
attribute [simp] pseudo_core.map_id_iso_hom pseudo_core.map_comp_iso_hom
end
end oplax_functor
/--
This auxiliary definition states that pseudofunctors preserve the associators
modulo some adjustments of domains and codomains of 2-morphisms.
-/
/-
We use this auxiliary definition instead of writing it directly in the definition
of pseudofunctors because doing so will cause a timeout.
-/
@[simp]
def pseudofunctor.map₂_associator_aux
(obj : B → C) (map : Π {X Y : B}, (X ⟶ Y) → (obj X ⟶ obj Y))
(map₂ : Π {a b : B} {f g : a ⟶ b}, (f ⟶ g) → (map f ⟶ map g))
(map_comp : Π {a b c : B} (f : a ⟶ b) (g : b ⟶ c), map (f ≫ g) ≅ map f ≫ map g)
{a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) : Prop :=
map₂ (α_ f g h).hom = (map_comp (f ≫ g) h).hom ≫ (map_comp f g).hom ▷ map h ≫
(α_ (map f) (map g) (map h)).hom ≫ map f ◁ (map_comp g h).inv ≫ (map_comp f (g ≫ h)).inv
/--
A pseudofunctor `F` between bicategories `B` and `C` consists of a function between objects
`F.obj`, a function between 1-morphisms `F.map`, and a function between 2-morphisms `F.map₂`.
Unlike functors between categories, `F.map` do not need to strictly commute with the compositions,
and do not need to strictly preserve the identity. Instead, there are specified 2-isomorphisms
`F.map (𝟙 a) ≅ 𝟙 (F.obj a)` and `F.map (f ≫ g) ≅ F.map f ≫ F.map g`.
`F.map₂` strictly commute with compositions and preserve the identity. They also preserve the
associator, the left unitor, and the right unitor modulo some adjustments of domains and codomains
of 2-morphisms.
-/
structure pseudofunctor (B : Type u₁) [bicategory.{w₁ v₁} B] (C : Type u₂) [bicategory.{w₂ v₂} C]
extends prelax_functor B C :=
(map_id (a : B) : map (𝟙 a) ≅ 𝟙 (obj a))
(map_comp {a b c : B} (f : a ⟶ b) (g : b ⟶ c) : map (f ≫ g) ≅ map f ≫ map g)
(map₂_id' : ∀ {a b : B} (f : a ⟶ b), map₂ (𝟙 f) = 𝟙 (map f) . obviously)
(map₂_comp' : ∀ {a b : B} {f g h : a ⟶ b} (η : f ⟶ g) (θ : g ⟶ h),
map₂ (η ≫ θ) = map₂ η ≫ map₂ θ . obviously)
(map₂_whisker_left' : ∀ {a b c : B} (f : a ⟶ b) {g h : b ⟶ c} (η : g ⟶ h),
map₂ (f ◁ η) = (map_comp f g).hom ≫ map f ◁ map₂ η ≫ (map_comp f h).inv . obviously)
(map₂_whisker_right' : ∀ {a b c : B} {f g : a ⟶ b} (η : f ⟶ g) (h : b ⟶ c),
map₂ (η ▷ h) = (map_comp f h).hom ≫ map₂ η ▷ map h ≫ (map_comp g h).inv . obviously)
(map₂_associator' : ∀ {a b c d : B} (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d),
pseudofunctor.map₂_associator_aux obj (λ a b, map) (λ a b f g, map₂) (λ a b c, map_comp) f g h
. obviously)
(map₂_left_unitor' : ∀ {a b : B} (f : a ⟶ b),
map₂ (λ_ f).hom = (map_comp (𝟙 a) f).hom ≫ (map_id a).hom ▷ map f ≫ (λ_ (map f)).hom
. obviously)
(map₂_right_unitor' : ∀ {a b : B} (f : a ⟶ b),
map₂ (ρ_ f).hom = (map_comp f (𝟙 b)).hom ≫ map f ◁ (map_id b).hom ≫ (ρ_ (map f)).hom
. obviously)
namespace pseudofunctor
restate_axiom map₂_id'
restate_axiom map₂_comp'
restate_axiom map₂_whisker_left'
restate_axiom map₂_whisker_right'
restate_axiom map₂_associator'
restate_axiom map₂_left_unitor'
restate_axiom map₂_right_unitor'
attribute [reassoc]
map₂_comp map₂_whisker_left map₂_whisker_right map₂_associator map₂_left_unitor map₂_right_unitor
attribute [simp]
map₂_id map₂_comp map₂_whisker_left map₂_whisker_right
map₂_associator map₂_left_unitor map₂_right_unitor
section
open iso
/-- The prelax functor between the underlying quivers. -/
add_decl_doc pseudofunctor.to_prelax_functor
instance has_coe_to_prelax_functor : has_coe (pseudofunctor B C) (prelax_functor B C) :=
⟨to_prelax_functor⟩
variables (F : pseudofunctor B C)
@[simp] lemma to_prelax_functor_eq_coe : F.to_prelax_functor = F := rfl
@[simp] lemma to_prelax_functor_obj : (F : prelax_functor B C).obj = F.obj := rfl
@[simp] lemma to_prelax_functor_map : (F : prelax_functor B C).map = F.map := rfl
@[simp] lemma to_prelax_functor_map₂ : (F : prelax_functor B C).map₂ = F.map₂ := rfl
/-- The oplax functor associated with a pseudofunctor. -/
def to_oplax : oplax_functor B C :=
{ map_id := λ a, (F.map_id a).hom,
map_comp := λ a b c f g, (F.map_comp f g).hom,
.. (F : prelax_functor B C) }
instance has_coe_to_oplax : has_coe (pseudofunctor B C) (oplax_functor B C) := ⟨to_oplax⟩
@[simp] lemma to_oplax_eq_coe : F.to_oplax = F := rfl
@[simp] lemma to_oplax_obj : (F : oplax_functor B C).obj = F.obj := rfl
@[simp] lemma to_oplax_map : (F : oplax_functor B C).map = F.map := rfl
@[simp] lemma to_oplax_map₂ : (F : oplax_functor B C).map₂ = F.map₂ := rfl
@[simp] lemma to_oplax_map_id (a : B) : (F : oplax_functor B C).map_id a = (F.map_id a).hom := rfl
@[simp] lemma to_oplax_map_comp {a b c : B} (f : a ⟶ b) (g : b ⟶ c) :
(F : oplax_functor B C).map_comp f g = (F.map_comp f g).hom := rfl
/-- Function on 1-morphisms as a functor. -/
@[simps]
def map_functor (a b : B) : (a ⟶ b) ⥤ (F.obj a ⟶ F.obj b) :=
(F : oplax_functor B C).map_functor a b
/-- The identity pseudofunctor. -/
@[simps]
def id (B : Type u₁) [bicategory.{w₁ v₁} B] : pseudofunctor B B :=
{ map_id := λ a, iso.refl (𝟙 a),
map_comp := λ a b c f g, iso.refl (f ≫ g),
.. prelax_functor.id B }
instance : inhabited (pseudofunctor B B) := ⟨id B⟩
/-- Composition of pseudofunctors. -/
@[simps]
def comp (F : pseudofunctor B C) (G : pseudofunctor C D) : pseudofunctor B D :=
{ map_id := λ a, (G.map_functor _ _).map_iso (F.map_id a) ≪≫ G.map_id (F.obj a),
map_comp := λ a b c f g,
(G.map_functor _ _).map_iso (F.map_comp f g) ≪≫ G.map_comp (F.map f) (F.map g),
.. (F : prelax_functor B C).comp ↑G }
/--
Construct a pseudofunctor from an oplax functor whose `map_id` and `map_comp` are isomorphisms.
-/
@[simps]
def mk_of_oplax (F : oplax_functor B C) (F' : F.pseudo_core) : pseudofunctor B C :=
{ map_id := F'.map_id_iso,
map_comp := F'.map_comp_iso,
map₂_whisker_left' := λ a b c f g h η, by
{ dsimp,
rw [F'.map_comp_iso_hom f g, ←F.map_comp_naturality_right_assoc,
←F'.map_comp_iso_hom f h, hom_inv_id, comp_id] },
map₂_whisker_right' := λ a b c f g η h, by
{ dsimp,
rw [F'.map_comp_iso_hom f h, ←F.map_comp_naturality_left_assoc,
←F'.map_comp_iso_hom g h, hom_inv_id, comp_id] },
map₂_associator' := λ a b c d f g h, by
{ dsimp,
rw [F'.map_comp_iso_hom (f ≫ g) h, F'.map_comp_iso_hom f g, ←F.map₂_associator_assoc,
←F'.map_comp_iso_hom f (g ≫ h), ←F'.map_comp_iso_hom g h,
hom_inv_whisker_left_assoc, hom_inv_id, comp_id] },
.. (F : prelax_functor B C) }
/--
Construct a pseudofunctor from an oplax functor whose `map_id` and `map_comp` are isomorphisms.
-/
@[simps]
noncomputable
def mk_of_oplax' (F : oplax_functor B C)
[∀ a, is_iso (F.map_id a)] [∀ {a b c} (f : a ⟶ b) (g : b ⟶ c), is_iso (F.map_comp f g)] :
pseudofunctor B C :=
{ map_id := λ a, as_iso (F.map_id a),
map_comp := λ a b c f g, as_iso (F.map_comp f g),
map₂_whisker_left' := λ a b c f g h η, by
{ dsimp,
rw [←assoc, is_iso.eq_comp_inv, F.map_comp_naturality_right] },
map₂_whisker_right' := λ a b c f g η h, by
{ dsimp,
rw [←assoc, is_iso.eq_comp_inv, F.map_comp_naturality_left] },
map₂_associator' := λ a b c d f g h, by
{ dsimp,
simp only [←assoc],
rw [is_iso.eq_comp_inv, ←inv_whisker_left, is_iso.eq_comp_inv],
simp only [assoc, F.map₂_associator] },
.. (F : prelax_functor B C) }
end
end pseudofunctor
end
end category_theory
|
7baa29c1944f2855eeb08a9bf5fb4e80ab3cfa74 | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/analysis/normed_space/basic.lean | 5e3ff7106a019e985ee8ea7d07af362b6a11394e | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 56,648 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import topology.instances.nnreal
import topology.algebra.module
import topology.metric_space.antilipschitz
/-!
# Normed spaces
-/
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
noncomputable theory
open filter metric
open_locale topological_space big_operators nnreal
/-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to
be extended in more interesting classes specifying the properties of the norm. -/
class has_norm (α : Type*) := (norm : α → ℝ)
export has_norm (norm)
notation `∥`:1024 e:1 `∥`:1 := norm e
/-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines
a metric space structure. -/
class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 },
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }
end }
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this },
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }
end }
/-- A normed group can be built from a norm that satisfies algebraic properties. This is
formalised in this structure. -/
structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop :=
(norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0)
(triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥)
(norm_neg : ∀ x : α, ∥-x∥ = ∥x∥)
/-- Constructing a normed group from core properties of a norm, i.e., registering the distance and
the metric space structure from the norm properties. -/
noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α]
(C : normed_group.core α) : normed_group α :=
{ dist := λ x y, ∥x - y∥,
dist_eq := assume x y, by refl,
dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp),
eq_of_dist_eq_zero := assume x y h, sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h,
dist_triangle := assume x y z,
calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel
... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _,
dist_comm := assume x y,
calc ∥x - y∥ = ∥ -(y - x)∥ : by simp
... = ∥y - x∥ : by { rw [C.norm_neg] } }
section normed_group
variables [normed_group α] [normed_group β]
lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ :=
normed_group.dist_eq _ _
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]
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_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 :=
dist_zero_right g ▸ dist_eq_zero
@[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl
@[nontriviality] lemma norm_of_subsingleton [subsingleton α] (x : α) : ∥x∥ = 0 :=
by rw [subsingleton.elim x 0, norm_zero]
lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ :=
finset.le_sum_of_subadditive norm norm_zero norm_add_le
lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) :
∥∑ b in s, f b∥ ≤ ∑ b in s, n b :=
le_trans (norm_sum_le s f) (finset.sum_le_sum h)
@[simp] lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 :=
dist_zero_right g ▸ dist_pos
@[simp] lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 :=
by { rw[←dist_zero_right], exact dist_le_zero }
lemma eq_of_norm_sub_le_zero {g h : α} (a : ∥g - h∥ ≤ 0) : g = h :=
by rwa [← sub_eq_zero, ← norm_le_zero_iff]
lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 h
lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ - g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ :=
by { rw dist_eq_norm, apply norm_sub_le }
lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ :=
by simpa [dist_eq_norm] using abs_dist_sub_le g h 0
lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ :=
le_trans (le_abs_self _) (abs_norm_sub_norm_le g h)
lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ :=
abs_norm_sub_norm_le g h
lemma eq_of_norm_sub_eq_zero {u v : α} (h : ∥u - v∥ = 0) : u = v :=
begin
apply eq_of_dist_eq_zero,
rwa dist_eq_norm
end
lemma norm_sub_eq_zero_iff {u v : α} : ∥u - v∥ = 0 ↔ u = v :=
begin
convert dist_eq_zero,
rwa dist_eq_norm
end
lemma norm_le_insert (u v : α) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ :=
calc ∥v∥ = ∥u - (u - v)∥ : by abel
... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _
lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} :=
set.ext $ assume a, by simp
lemma mem_ball_iff_norm {g h : α} {r : ℝ} :
h ∈ ball g r ↔ ∥h - g∥ < r :=
by rw [mem_ball, dist_eq_norm]
lemma mem_ball_iff_norm' {g h : α} {r : ℝ} :
h ∈ ball g r ↔ ∥g - h∥ < r :=
by rw [mem_ball', dist_eq_norm]
lemma mem_closed_ball_iff_norm {g h : α} {r : ℝ} :
h ∈ closed_ball g r ↔ ∥h - g∥ ≤ r :=
by rw [mem_closed_ball, dist_eq_norm]
lemma mem_closed_ball_iff_norm' {g h : α} {r : ℝ} :
h ∈ closed_ball g r ↔ ∥g - h∥ ≤ r :=
by rw [mem_closed_ball', dist_eq_norm]
lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) :
∥h∥ ≤ ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H }
lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) :
∥h∥ < ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H }
@[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 nonzero_of_mem_sphere {r : ℝ} (hr : 0 < r) (x : sphere (0:α) r) : (x:α) ≠ 0 :=
by rwa [← norm_pos_iff, norm_eq_of_mem_sphere]
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 normed 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
theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} :
tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε :=
metric.tendsto_nhds.trans $ by simp only [dist_zero_right]
lemma normed_group.tendsto_nhds_nhds {f : α → β} {x : α} {y : β} :
tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε :=
by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm]
/-- A homomorphism `f` of normed groups is Lipschitz, if there exists a constant `C` such that for
all `x`, one has `∥f x∥ ≤ C * ∥x∥`.
The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/
lemma add_monoid_hom.lipschitz_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) :
lipschitz_with (nnreal.of_real C) f :=
lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y)
lemma lipschitz_on_with_iff_norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} :
lipschitz_on_with C f s ↔ ∀ (x ∈ s) (y ∈ s), ∥f x - f y∥ ≤ C * ∥x - y∥ :=
by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm]
lemma lipschitz_on_with.norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} (h : lipschitz_on_with C f s)
{x y : α} (x_in : x ∈ s) (y_in : y ∈ s) : ∥f x - f y∥ ≤ C * ∥x - y∥ :=
lipschitz_on_with_iff_norm_sub_le.mp h x x_in y y_in
/-- A homomorphism `f` of normed groups is continuous, if there exists a constant `C` such that for
all `x`, one has `∥f x∥ ≤ C * ∥x∥`.
The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/
lemma add_monoid_hom.continuous_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) :
continuous f :=
(f.lipschitz_of_bound C h).continuous
section nnnorm
/-- Version of the norm taking values in nonnegative reals. -/
def nnnorm (a : α) : ℝ≥0 := ⟨norm a, norm_nonneg a⟩
@[simp, norm_cast] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl
lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _
@[simp] lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 :=
by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero]
@[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 :=
nnreal.eq norm_zero
lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h :=
nnreal.coe_le_coe.2 $ norm_add_le g h
@[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g :=
nnreal.eq $ norm_neg g
lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) :=
nnreal.coe_le_coe.2 $ dist_norm_norm_le g h
lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) :=
ennreal.of_real_eq_coe_nnreal _
lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) :=
by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm]
lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) :=
by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero]
lemma mem_emetric_ball_0_iff {x : β} {r : ennreal} : x ∈ emetric.ball (0 : β) r ↔ ↑(nnnorm 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 : β → α),
nnnorm (∑ a in s, f a) ≤ ∑ a in s, nnnorm (f a) :=
finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le
end nnnorm
lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : ℝ≥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*} [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*} [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*} [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
/-- A submodule of a normed group is also a normed group, with the restriction of the norm.
As all instances can be inferred from the submodule `s`, they are put as implicit instead of
typeclasses. -/
instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜}
{E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s :=
{ norm := λx, norm (x : E),
dist_eq := λx y, dist_eq_norm (x : E) (y : E) }
/-- normed group instance on the product of two normed groups, using the sup norm. -/
instance prod.normed_group : normed_group (α × β) :=
{ norm := λx, max ∥x.1∥ ∥x.2∥,
dist_eq := assume (x y : α × β),
show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] }
lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl
lemma prod.nnnorm_def (x : α × β) : nnnorm x = max (nnnorm x.1) (nnnorm x.2) :=
by { have := x.norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this }
lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ :=
le_max_left _ _
lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ :=
le_max_right _ _
lemma norm_prod_le_iff {x : α × β} {r : ℝ} :
∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r :=
max_le_iff
/-- normed group instance on the product of finitely many normed groups, using the sup norm. -/
instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] :
normed_group (Πi, π i) :=
{ norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : ℝ≥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) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ }
/-- The norm of an element in a product space is `≤ r` if and only if the norm of each
component is. -/
lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r)
{x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r :=
by simp only [← dist_zero_right, 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 : α) :
nnnorm (λ i : ι, a) = nnnorm a :=
nnreal.eq $ pi_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 tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} :
tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥f e∥) a (𝓝 0) :=
by simp [tendsto_iff_norm_tendsto_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:α)
lemma continuous_norm : continuous (λg:α, ∥g∥) :=
by simpa using continuous_id.dist (continuous_const : continuous (λ g, (0:α)))
lemma continuous_nnnorm : continuous (nnnorm : α → ℝ≥0) :=
continuous_subtype_mk _ continuous_norm
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
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, nnnorm (f x)) l (𝓝 (nnnorm 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, nnnorm (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, nnnorm (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, nnnorm (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, nnnorm (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 normed group is a uniform additive group, i.e., addition and subtraction are uniformly
continuous. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_uniform_group : uniform_add_group α :=
⟨(lipschitz_with.prod_fst.sub lipschitz_with.prod_snd).uniform_continuous⟩
@[priority 100] -- see Note [lower instance priority]
instance normed_top_monoid : has_continuous_add α :=
by apply_instance -- short-circuit type class inference
@[priority 100] -- see Note [lower instance priority]
instance normed_top_group : topological_add_group α :=
by apply_instance -- short-circuit type class inference
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 }
end normed_group
section normed_ring
/-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
/-- A normed commutative ring is a commutative ring endowed with a norm which satisfies
the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_comm_ring (α : Type*) extends normed_ring α :=
(mul_comm : ∀ x y : α, x * y = y * x)
/-- A mixin class with the axiom `∥1∥ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this
axiom. -/
class norm_one_class (α : Type*) [has_norm α] [has_one α] : Prop :=
(norm_one : ∥(1:α)∥ = 1)
export norm_one_class (norm_one)
attribute [simp] norm_one
@[simp] lemma nnnorm_one [normed_group α] [has_one α] [norm_one_class α] : nnnorm (1:α) = 1 :=
nnreal.eq norm_one
@[priority 100] -- see Note [lower instance priority]
instance normed_comm_ring.to_comm_ring [β : normed_comm_ring α] : comm_ring α := { ..β }
@[priority 100] -- see Note [lower instance priority]
instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β }
instance prod.norm_one_class [normed_group α] [has_one α] [norm_one_class α]
[normed_group β] [has_one β] [norm_one_class β] :
norm_one_class (α × β) :=
⟨by simp [prod.norm_def]⟩
variables [normed_ring α]
lemma norm_mul_le (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) :=
normed_ring.norm_mul _ _
lemma list.norm_prod_le' : ∀ {l : list α}, l ≠ [] → ∥l.prod∥ ≤ (l.map norm).prod
| [] h := (h rfl).elim
| [a] _ := by simp
| (a :: b :: l) _ :=
begin
rw [list.map_cons, list.prod_cons, @list.prod_cons _ _ _ ∥a∥],
refine le_trans (norm_mul_le _ _) (mul_le_mul_of_nonneg_left _ (norm_nonneg _)),
exact list.norm_prod_le' (list.cons_ne_nil b l)
end
lemma list.norm_prod_le [norm_one_class α] : ∀ l : list α, ∥l.prod∥ ≤ (l.map norm).prod
| [] := by simp
| (a::l) := list.norm_prod_le' (list.cons_ne_nil a l)
lemma finset.norm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty)
(f : ι → α) :
∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ :=
begin
rcases s with ⟨⟨l⟩, hl⟩,
have : l.map f ≠ [], by simpa using hs,
simpa using list.norm_prod_le' this
end
lemma finset.norm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι)
(f : ι → α) :
∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ :=
begin
rcases s with ⟨⟨l⟩, hl⟩,
simpa using (l.map f).norm_prod_le
end
/-- If `α` is a normed ring, then `∥a^n∥≤ ∥a∥^n` for `n > 0`. See also `norm_pow_le`. -/
lemma norm_pow_le' (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n
| 1 h := by simp
| (n+2) h :=
le_trans (norm_mul_le a (a^(n+1)))
(mul_le_mul (le_refl _)
(norm_pow_le' (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _))
/-- If `α` is a normed ring with `∥1∥=1`, then `∥a^n∥≤ ∥a∥^n`. See also `norm_pow_le'`. -/
lemma norm_pow_le [norm_one_class α] (a : α) : ∀ (n : ℕ), ∥a^n∥ ≤ ∥a∥^n
| 0 := by simp
| (n+1) := norm_pow_le' a n.zero_lt_succ
lemma eventually_norm_pow_le (a : α) : ∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n :=
eventually_at_top.mpr ⟨1, λ b h, norm_pow_le' a (nat.succ_le_iff.mp h)⟩
lemma units.norm_pos [nontrivial α] (x : units α) : 0 < ∥(x:α)∥ :=
norm_pos_iff.mpr (units.ne_zero x)
/-- In a normed ring, the left-multiplication `add_monoid_hom` is bounded. -/
lemma mul_left_bound (x : α) :
∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ :=
norm_mul_le x
/-- In a normed ring, the right-multiplication `add_monoid_hom` is bounded. -/
lemma mul_right_bound (x : α) :
∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ :=
λ y, by {rw mul_comm, convert norm_mul_le y x}
/-- Normed ring structure on the product of two normed rings, using the sup norm. -/
instance prod.normed_ring [normed_ring β] : normed_ring (α × β) :=
{ norm_mul := assume x y,
calc
∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl
... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl
... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) :
max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2))
... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm]
... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) :
by apply max_mul_mul_le_max_mul_max; simp [norm_nonneg]
... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp [max_comm]
... = (∥x∥*∥y∥) : rfl,
..prod.normed_group }
end normed_ring
@[priority 100] -- see Note [lower instance priority]
instance normed_ring_top_monoid [normed_ring α] : has_continuous_mul α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
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 normed ring is a topological ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_top_ring [normed_ring α] : topological_ring α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α, -e - -x = -(e - x), by intro; simp,
by simp only [this, norm_neg]; apply 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 : α) : nnnorm (a * b) = nnnorm a * nnnorm 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 : ℕ) : nnnorm (a ^ n) = nnnorm a ^ n :=
nnnorm_hom.to_monoid_hom.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 : β → α) :
nnnorm (∏ b in s, f b) = ∏ b in s, nnnorm (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 : α) : nnnorm (a / b) = nnnorm a / nnnorm 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 : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ :=
nnreal.eq $ by simp
@[simp] lemma norm_fpow : ∀ (a : α) (n : ℤ), ∥a^n∥ = ∥a∥^n :=
(norm_hom : monoid_with_zero_hom α ℝ).map_fpow
@[simp] lemma nnnorm_fpow : ∀ (a : α) (n : ℤ), nnnorm (a^n) = (nnnorm 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 := λ x, abs x,
dist_eq := assume x y, rfl,
norm_mul' := abs_mul }
instance : nondiscrete_normed_field ℝ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
namespace real
lemma norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl
lemma norm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥ = x :=
abs_of_nonneg hx
@[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg
@[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp
@[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@zero_lt_two ℝ _ _)
@[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp
open_locale nnreal
@[simp] lemma nnreal.norm_eq (x : ℝ≥0) : ∥(x : ℝ)∥ = x :=
by rw [real.norm_eq_abs, x.abs_eq]
lemma nnnorm_coe_eq_self {x : ℝ≥0} : nnnorm (x : ℝ) = x :=
by { ext, exact norm_of_nonneg (zero_le x) }
lemma nnnorm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : nnnorm x = ⟨x, hx⟩ :=
@nnnorm_coe_eq_self ⟨x, hx⟩
lemma ennnorm_eq_of_real {x : ℝ} (hx : 0 ≤ x) : (nnnorm x : ennreal) = ennreal.of_real x :=
by { rw [← of_real_norm_eq_coe_nnnorm, norm_of_nonneg hx] }
end real
@[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ :=
by rw [real.norm_of_nonneg (norm_nonneg _)]
@[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a :=
by simp only [nnnorm, norm_norm]
instance : normed_comm_ring ℤ :=
{ norm := λ n, ∥(n : ℝ)∥,
norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul],
dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub],
mul_comm := mul_comm }
@[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl
instance : norm_one_class ℤ :=
⟨by simp [← int.norm_cast_real]⟩
instance : normed_field ℚ :=
{ norm := λ r, ∥(r : ℝ)∥,
norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul],
dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] }
instance : nondiscrete_normed_field ℚ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
@[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl
@[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ :=
by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast
section normed_space
section prio
set_option extends_priority 920
-- Here, we set a rather high priority for the instance `[normed_space α β] : semimodule α β`
-- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better
-- unification properties.
-- see Note[vector space definition] for why we extend `semimodule`.
/-- A normed space over a normed field is a vector space endowed with a norm which satisfies the
equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove
`∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/
class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β]
extends semimodule α β :=
(norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥)
end prio
variables [normed_field α] [normed_group β]
instance normed_field.to_normed_space : normed_space α α :=
{ norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) }
lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ :=
begin
classical,
by_cases h : s = 0,
{ simp [h] },
{ refine le_antisymm (normed_space.norm_smul_le s x) _,
calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h]
... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : _
... = ∥s • x∥ : _,
exact mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _),
rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel, one_mul],
rwa [ne.def, norm_eq_zero] }
end
@[simp] lemma abs_norm_eq_norm (z : β) : abs ∥z∥ = ∥z∥ :=
(abs_eq (norm_nonneg z)).mpr (or.inl rfl)
lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y :=
by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub]
lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x :=
nnreal.eq $ norm_smul s x
lemma nndist_smul [normed_space α β] (s : α) (x y : β) :
nndist (s • x) (s • y) = nnnorm s * nndist x y :=
nnreal.eq $ dist_smul s x y
lemma norm_smul_of_nonneg [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ :=
by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht]
variables {E : Type*} {F : Type*}
[normed_group E] [normed_space α E] [normed_group F] [normed_space α F]
@[priority 100] -- see Note [lower instance priority]
instance normed_space.topological_vector_space : topological_vector_space α E :=
begin
refine { continuous_smul := continuous_iff_continuous_at.2 $
λ p, tendsto_iff_norm_tendsto_zero.2 _ },
refine squeeze_zero (λ _, norm_nonneg _) _ _,
{ exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ },
{ intro q,
rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul],
exact norm_add_le _ _ },
{ conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr,
rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] },
exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul
(continuous_snd.tendsto p).norm).add
(tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) }
end
theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
closure (ball x r) = closed_ball x r :=
begin
refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _),
have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 :=
((continuous_id.smul continuous_const).add continuous_const).continuous_within_at,
convert this.mem_closure _ _,
{ rw [one_smul, sub_add_cancel] },
{ simp [closure_Ico (@zero_lt_one ℝ _ _), zero_le_one] },
{ rintros c ⟨hc0, hc1⟩,
rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs,
abs_of_nonneg hc0, mul_comm, ← mul_one r],
rw [mem_closed_ball, dist_eq_norm] at hy,
apply mul_lt_mul'; assumption }
end
theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
frontier (ball x r) = sphere x r :=
begin
rw [frontier, closure_ball x hr, is_open_ball.interior_eq],
ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm
end
theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
interior (closed_ball x r) = ball x r :=
begin
refine set.subset.antisymm _ ball_subset_interior_closed_ball,
intros y hy,
rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr },
set f : ℝ → E := λ c : ℝ, c • (y - x) + x,
suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1,
{ have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const,
have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f],
have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) :=
interior_mono this (preimage_interior_subset_interior_preimage hfc hf1),
contrapose h1,
simp },
intros c hc,
rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr],
simpa [f, dist_eq_norm, norm_smul] using hc
end
theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) :
interior (closed_ball x r) = ball x r :=
begin
rcases lt_trichotomy r 0 with hr|rfl|hr,
{ simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] },
{ suffices : x ∉ interior {x},
{ rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff],
intros y hy,
obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy),
exact this hy },
rw [← set.mem_compl_iff, ← closure_compl],
rcases exists_ne (0 : E) with ⟨z, hz⟩,
suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E),
by simpa only [zero_smul, add_zero] using this,
have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi],
refine (continuous_const.add (continuous_id.smul
continuous_const)).continuous_within_at.mem_closure this _,
intros c hc,
simp [smul_eq_zero, hz, ne_of_gt hc] },
{ exact interior_closed_ball x hr }
end
theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) :
frontier (closed_ball x r) = sphere x r :=
by rw [frontier, closure_closed_ball, interior_closed_ball x hr,
closed_ball_diff_ball]
theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) :
frontier (closed_ball x r) = sphere x r :=
by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball]
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
/-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to
any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows
up in applications. -/
lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) :
∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) :=
begin
have xεpos : 0 < ∥x∥/ε := div_pos (norm_pos_iff.2 hx) εpos,
rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩,
have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc,
have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 },
refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩,
show (c ^ (n + 1))⁻¹ ≠ 0,
by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff],
show ∥(c ^ (n + 1))⁻¹ • x∥ < ε,
{ rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_fpow],
exact (div_lt_iff εpos).1 (hn.2) },
show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥,
{ rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos),
fpow_one, mul_inv_rev', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos),
one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm],
exact (le_div_iff εpos).1 hn.1 },
show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥,
{ have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring,
rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul],
exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) }
end
/-- The product of two normed spaces is a normed space, with the sup norm. -/
instance : normed_space α (E × F) :=
{ norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg],
-- TODO: without the next two lines Lean unfolds `≤` to `real.le`
add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _),
smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _),
..prod.normed_group,
..prod.semimodule }
/-- The product of finitely many normed spaces is a normed space, with the sup norm. -/
instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)]
[∀i, normed_space α (E i)] : normed_space α (Πi, E i) :=
{ norm_smul_le := λ a f, le_of_eq $
show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) =
nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))),
by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] }
/-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/
instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s :=
{ norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) }
end normed_space
section normed_algebra
/-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of
`𝕜` in `𝕜'` is an isometry. -/
class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
extends algebra 𝕜 𝕜' :=
(norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥)
@[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
[h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ :=
normed_algebra.norm_algebra_map_eq _
variables (𝕜 : Type*) [normed_field 𝕜]
variables (𝕜' : Type*) [normed_ring 𝕜']
@[priority 100]
instance normed_algebra.to_normed_space [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' :=
{ norm_smul_le := λ s x, calc
∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl }
... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _
... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq,
..h }
instance normed_algebra.id : normed_algebra 𝕜 𝕜 :=
{ norm_algebra_map_eq := by simp,
.. algebra.id 𝕜}
variables {𝕜'} [normed_algebra 𝕜 𝕜']
include 𝕜
@[simp] lemma normed_algebra.norm_one : ∥(1:𝕜')∥ = 1 :=
by simpa using (norm_algebra_map_eq 𝕜' (1:𝕜))
lemma normed_algebra.norm_one_class : norm_one_class 𝕜' :=
⟨normed_algebra.norm_one 𝕜⟩
lemma normed_algebra.zero_ne_one : (0:𝕜') ≠ 1 :=
begin
refine (norm_pos_iff.mp _).symm,
rw @normed_algebra.norm_one 𝕜, norm_num,
end
lemma normed_algebra.nontrivial : nontrivial 𝕜' :=
⟨⟨0, 1, normed_algebra.zero_ne_one 𝕜⟩⟩
end normed_algebra
section restrict_scalars
variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
(E : Type*) [normed_group E] [normed_space 𝕜' E]
/-- Warning: This declaration should be used judiciously.
Please consider using `is_scalar_tower` instead.
`𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a
normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred.
The type synonym `semimodule.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default.
-/
def normed_space.restrict_scalars : normed_space 𝕜 E :=
{ norm_smul_le := λc x, le_of_eq $ begin
change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥,
simp [norm_smul]
end,
..restrict_scalars.semimodule 𝕜 𝕜' E }
instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] :
normed_group (restrict_scalars 𝕜 𝕜' E) := I
instance semimodule.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*}
[normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] :
normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I
instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) :=
(normed_space.restrict_scalars 𝕜 𝕜' E : normed_space 𝕜 E)
end restrict_scalars
section summable
open_locale classical
open finset filter
variables [normed_group α] [normed_group β]
lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} :
cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔
∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε :=
begin
rw [cauchy_seq_finset_iff_vanishing, nhds_basis_ball.forall_iff],
{ simp only [ball_0_eq, set.mem_set_of_eq] },
{ rintros s t hst ⟨s', hs'⟩,
exact ⟨s', λ t' ht', hst $ hs' _ ht'⟩ }
end
lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} :
summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm]
lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g)
(h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) :=
cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε,
let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in
⟨s, assume t ht,
have ∥∑ i in t, g i∥ < ε := hs t ht,
have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)),
lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $
by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩
lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) :
cauchy_seq (λ s : finset ι, ∑ a in s, f a) :=
cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _)
/-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space
its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable
with sum `a`. -/
lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥))
{s : γ → finset ι} {p : filter γ} [ne_bot p]
(hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) :
has_sum f a :=
tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha
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
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, nnnorm (f i) ≤ g i) : summable f :=
summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i)
lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f :=
summable_of_norm_bounded _ hf (assume i, le_refl _)
lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f :=
summable_of_nnnorm_bounded _ hf (assume i, le_refl _)
end summable
|
9993bc57f2be1b5681ea43dc0d8d1cc49e2266ab | 4727251e0cd73359b15b664c3170e5d754078599 | /src/linear_algebra/affine_space/ordered.lean | 3c3759bc516bbbcd63922dd7904198604b02edbf | [
"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,471 | 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 algebra.order.invertible
import algebra.order.module
import linear_algebra.affine_space.midpoint
import linear_algebra.affine_space.slope
import tactic.field_simp
/-!
# Ordered modules as affine spaces
In this file we prove some theorems about `slope` and `line_map` in the case when the module `E`
acting on the codomain `PE` of a function is an ordered module over its domain `k`. We also prove
inequalities that can be used to link convexity of a function on an interval to monotonicity of the
slope, see section docstring below for details.
## Implementation notes
We do not introduce the notion of ordered affine spaces (yet?). Instead, we prove various theorems
for an ordered module interpreted as an affine space.
## Tags
affine space, ordered module, slope
-/
open affine_map
variables {k E PE : Type*}
/-!
### Monotonicity of `line_map`
In this section we prove that `line_map a b r` is monotone (strictly or not) in its arguments if
other arguments belong to specific domains.
-/
section ordered_ring
variables [ordered_ring k] [ordered_add_comm_group E] [module k E] [ordered_smul k E]
variables {a a' b b' : E} {r r' : k}
lemma line_map_mono_left (ha : a ≤ a') (hr : r ≤ 1) :
line_map a b r ≤ line_map a' b r :=
begin
simp only [line_map_apply_module],
exact add_le_add_right (smul_le_smul_of_nonneg ha (sub_nonneg.2 hr)) _
end
lemma line_map_strict_mono_left (ha : a < a') (hr : r < 1) :
line_map a b r < line_map a' b r :=
begin
simp only [line_map_apply_module],
exact add_lt_add_right (smul_lt_smul_of_pos ha (sub_pos.2 hr)) _
end
lemma line_map_mono_right (hb : b ≤ b') (hr : 0 ≤ r) :
line_map a b r ≤ line_map a b' r :=
begin
simp only [line_map_apply_module],
exact add_le_add_left (smul_le_smul_of_nonneg hb hr) _
end
lemma line_map_strict_mono_right (hb : b < b') (hr : 0 < r) :
line_map a b r < line_map a b' r :=
begin
simp only [line_map_apply_module],
exact add_lt_add_left (smul_lt_smul_of_pos hb hr) _
end
lemma line_map_mono_endpoints (ha : a ≤ a') (hb : b ≤ b') (h₀ : 0 ≤ r) (h₁ : r ≤ 1) :
line_map a b r ≤ line_map a' b' r :=
(line_map_mono_left ha h₁).trans (line_map_mono_right hb h₀)
lemma line_map_strict_mono_endpoints (ha : a < a') (hb : b < b') (h₀ : 0 ≤ r) (h₁ : r ≤ 1) :
line_map a b r < line_map a' b' r :=
begin
rcases h₀.eq_or_lt with (rfl|h₀), { simpa },
exact (line_map_mono_left ha.le h₁).trans_lt (line_map_strict_mono_right hb h₀)
end
lemma line_map_lt_line_map_iff_of_lt (h : r < r') :
line_map a b r < line_map a b r' ↔ a < b :=
begin
simp only [line_map_apply_module],
rw [← lt_sub_iff_add_lt, add_sub_assoc, ← sub_lt_iff_lt_add', ← sub_smul, ← sub_smul,
sub_sub_sub_cancel_left, smul_lt_smul_iff_of_pos (sub_pos.2 h)],
apply_instance,
end
lemma left_lt_line_map_iff_lt (h : 0 < r) : a < line_map a b r ↔ a < b :=
iff.trans (by rw line_map_apply_zero) (line_map_lt_line_map_iff_of_lt h)
lemma line_map_lt_left_iff_lt (h : 0 < r) : line_map a b r < a ↔ b < a :=
@left_lt_line_map_iff_lt k Eᵒᵈ _ _ _ _ _ _ _ h
lemma line_map_lt_right_iff_lt (h : r < 1) : line_map a b r < b ↔ a < b :=
iff.trans (by rw line_map_apply_one) (line_map_lt_line_map_iff_of_lt h)
lemma right_lt_line_map_iff_lt (h : r < 1) : b < line_map a b r ↔ b < a :=
@line_map_lt_right_iff_lt k Eᵒᵈ _ _ _ _ _ _ _ h
end ordered_ring
section linear_ordered_ring
variables [linear_ordered_ring k] [ordered_add_comm_group E] [module k E]
[ordered_smul k E] [invertible (2:k)] {a a' b b' : E} {r r' : k}
lemma midpoint_le_midpoint (ha : a ≤ a') (hb : b ≤ b') :
midpoint k a b ≤ midpoint k a' b' :=
line_map_mono_endpoints ha hb (inv_of_nonneg.2 zero_le_two) $
inv_of_le_one one_le_two
end linear_ordered_ring
section linear_ordered_field
variables [linear_ordered_field k] [ordered_add_comm_group E]
variables [module k E] [ordered_smul k E]
section
variables {a b : E} {r r' : k}
lemma line_map_le_line_map_iff_of_lt (h : r < r') :
line_map a b r ≤ line_map a b r' ↔ a ≤ b :=
begin
simp only [line_map_apply_module],
rw [← le_sub_iff_add_le, add_sub_assoc, ← sub_le_iff_le_add', ← sub_smul, ← sub_smul,
sub_sub_sub_cancel_left, smul_le_smul_iff_of_pos (sub_pos.2 h)],
apply_instance,
end
lemma left_le_line_map_iff_le (h : 0 < r) : a ≤ line_map a b r ↔ a ≤ b :=
iff.trans (by rw line_map_apply_zero) (line_map_le_line_map_iff_of_lt h)
@[simp] lemma left_le_midpoint : a ≤ midpoint k a b ↔ a ≤ b :=
left_le_line_map_iff_le $ inv_pos.2 zero_lt_two
lemma line_map_le_left_iff_le (h : 0 < r) : line_map a b r ≤ a ↔ b ≤ a :=
@left_le_line_map_iff_le k Eᵒᵈ _ _ _ _ _ _ _ h
@[simp] lemma midpoint_le_left : midpoint k a b ≤ a ↔ b ≤ a :=
line_map_le_left_iff_le $ inv_pos.2 zero_lt_two
lemma line_map_le_right_iff_le (h : r < 1) : line_map a b r ≤ b ↔ a ≤ b :=
iff.trans (by rw line_map_apply_one) (line_map_le_line_map_iff_of_lt h)
@[simp] lemma midpoint_le_right : midpoint k a b ≤ b ↔ a ≤ b :=
line_map_le_right_iff_le $ inv_lt_one one_lt_two
lemma right_le_line_map_iff_le (h : r < 1) : b ≤ line_map a b r ↔ b ≤ a :=
@line_map_le_right_iff_le k Eᵒᵈ _ _ _ _ _ _ _ h
@[simp] lemma right_le_midpoint : b ≤ midpoint k a b ↔ b ≤ a :=
right_le_line_map_iff_le $ inv_lt_one one_lt_two
end
/-!
### Convexity and slope
Given an interval `[a, b]` and a point `c ∈ (a, b)`, `c = line_map a b r`, there are a few ways to
say that the point `(c, f c)` is above/below the segment `[(a, f a), (b, f b)]`:
* compare `f c` to `line_map (f a) (f b) r`;
* compare `slope f a c` to `slope `f a b`;
* compare `slope f c b` to `slope f a b`;
* compare `slope f a c` to `slope f c b`.
In this section we prove equivalence of these four approaches. In order to make the statements more
readable, we introduce local notation `c = line_map a b r`. Then we prove lemmas like
```
lemma map_le_line_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) :
f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f a b :=
```
For each inequality between `f c` and `line_map (f a) (f b) r` we provide 3 lemmas:
* `*_left` relates it to an inequality on `slope f a c` and `slope f a b`;
* `*_right` relates it to an inequality on `slope f a b` and `slope f c b`;
* no-suffix version relates it to an inequality on `slope f a c` and `slope f c b`.
These inequalities can by used in to restate `convex_on` in terms of monotonicity of the slope.
-/
variables {f : k → E} {a b r : k}
local notation `c` := line_map a b r
/-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is non-strictly below the
segment `[(a, f a), (b, f b)]` if and only if `slope f a c ≤ slope f a b`. -/
lemma map_le_line_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) :
f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f a b :=
begin
rw [line_map_apply, line_map_apply, slope, slope,
vsub_eq_sub, vsub_eq_sub, vsub_eq_sub, vadd_eq_add, vadd_eq_add,
smul_eq_mul, add_sub_cancel, smul_sub, smul_sub, smul_sub,
sub_le_iff_le_add, mul_inv_rev, mul_smul, mul_smul, ←smul_sub, ←smul_sub, ←smul_add, smul_smul,
← mul_inv_rev, smul_le_iff_of_pos (inv_pos.2 h), inv_inv, smul_smul,
mul_inv_cancel_right₀ (right_ne_zero_of_mul h.ne'), smul_add,
smul_inv_smul₀ (left_ne_zero_of_mul h.ne')],
apply_instance
end
/-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is non-strictly above the
segment `[(a, f a), (b, f b)]` if and only if `slope f a b ≤ slope f a c`. -/
lemma line_map_le_map_iff_slope_le_slope_left (h : 0 < r * (b - a)) :
line_map (f a) (f b) r ≤ f c ↔ slope f a b ≤ slope f a c :=
@map_le_line_map_iff_slope_le_slope_left k Eᵒᵈ _ _ _ _ f a b r h
/-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is strictly below the
segment `[(a, f a), (b, f b)]` if and only if `slope f a c < slope f a b`. -/
lemma map_lt_line_map_iff_slope_lt_slope_left (h : 0 < r * (b - a)) :
f c < line_map (f a) (f b) r ↔ slope f a c < slope f a b :=
lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope_left h)
(map_le_line_map_iff_slope_le_slope_left h)
/-- Given `c = line_map a b r`, `a < c`, the point `(c, f c)` is strictly above the
segment `[(a, f a), (b, f b)]` if and only if `slope f a b < slope f a c`. -/
lemma line_map_lt_map_iff_slope_lt_slope_left (h : 0 < r * (b - a)) :
line_map (f a) (f b) r < f c ↔ slope f a b < slope f a c :=
@map_lt_line_map_iff_slope_lt_slope_left k Eᵒᵈ _ _ _ _ f a b r h
/-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is non-strictly below the
segment `[(a, f a), (b, f b)]` if and only if `slope f a b ≤ slope f c b`. -/
lemma map_le_line_map_iff_slope_le_slope_right (h : 0 < (1 - r) * (b - a)) :
f c ≤ line_map (f a) (f b) r ↔ slope f a b ≤ slope f c b :=
begin
rw [← line_map_apply_one_sub, ← line_map_apply_one_sub _ _ r],
revert h, generalize : 1 - r = r', clear r, intro h,
simp_rw [line_map_apply, slope, vsub_eq_sub, vadd_eq_add, smul_eq_mul],
rw [sub_add_eq_sub_sub_swap, sub_self, zero_sub, le_smul_iff_of_pos, inv_inv, smul_smul,
neg_mul_eq_mul_neg, neg_sub, mul_inv_cancel_right₀, le_sub, ← neg_sub (f b), smul_neg,
neg_add_eq_sub],
{ exact right_ne_zero_of_mul h.ne' },
{ simpa [mul_sub] using h }
end
/-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is non-strictly above the
segment `[(a, f a), (b, f b)]` if and only if `slope f c b ≤ slope f a b`. -/
lemma line_map_le_map_iff_slope_le_slope_right (h : 0 < (1 - r) * (b - a)) :
line_map (f a) (f b) r ≤ f c ↔ slope f c b ≤ slope f a b :=
@map_le_line_map_iff_slope_le_slope_right k Eᵒᵈ _ _ _ _ f a b r h
/-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is strictly below the
segment `[(a, f a), (b, f b)]` if and only if `slope f a b < slope f c b`. -/
lemma map_lt_line_map_iff_slope_lt_slope_right (h : 0 < (1 - r) * (b - a)) :
f c < line_map (f a) (f b) r ↔ slope f a b < slope f c b :=
lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope_right h)
(map_le_line_map_iff_slope_le_slope_right h)
/-- Given `c = line_map a b r`, `c < b`, the point `(c, f c)` is strictly above the
segment `[(a, f a), (b, f b)]` if and only if `slope f c b < slope f a b`. -/
lemma line_map_lt_map_iff_slope_lt_slope_right (h : 0 < (1 - r) * (b - a)) :
line_map (f a) (f b) r < f c ↔ slope f c b < slope f a b :=
@map_lt_line_map_iff_slope_lt_slope_right k Eᵒᵈ _ _ _ _ f a b r h
/-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is non-strictly below the
segment `[(a, f a), (b, f b)]` if and only if `slope f a c ≤ slope f c b`. -/
lemma map_le_line_map_iff_slope_le_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) :
f c ≤ line_map (f a) (f b) r ↔ slope f a c ≤ slope f c b :=
begin
rw [map_le_line_map_iff_slope_le_slope_left (mul_pos h₀ (sub_pos.2 hab)),
← line_map_slope_line_map_slope_line_map f a b r, right_le_line_map_iff_le h₁],
apply_instance,
apply_instance,
end
/-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is non-strictly above the
segment `[(a, f a), (b, f b)]` if and only if `slope f c b ≤ slope f a c`. -/
lemma line_map_le_map_iff_slope_le_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) :
line_map (f a) (f b) r ≤ f c ↔ slope f c b ≤ slope f a c :=
@map_le_line_map_iff_slope_le_slope k Eᵒᵈ _ _ _ _ _ _ _ _ hab h₀ h₁
/-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is strictly below the
segment `[(a, f a), (b, f b)]` if and only if `slope f a c < slope f c b`. -/
lemma map_lt_line_map_iff_slope_lt_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) :
f c < line_map (f a) (f b) r ↔ slope f a c < slope f c b :=
lt_iff_lt_of_le_iff_le' (line_map_le_map_iff_slope_le_slope hab h₀ h₁)
(map_le_line_map_iff_slope_le_slope hab h₀ h₁)
/-- Given `c = line_map a b r`, `a < c < b`, the point `(c, f c)` is strictly above the
segment `[(a, f a), (b, f b)]` if and only if `slope f c b < slope f a c`. -/
lemma line_map_lt_map_iff_slope_lt_slope (hab : a < b) (h₀ : 0 < r) (h₁ : r < 1) :
line_map (f a) (f b) r < f c ↔ slope f c b < slope f a c :=
@map_lt_line_map_iff_slope_lt_slope k Eᵒᵈ _ _ _ _ _ _ _ _ hab h₀ h₁
end linear_ordered_field
|
7c76eb0ac6be11f5b0e0b643294fcad92c91250f | b147e1312077cdcfea8e6756207b3fa538982e12 | /order/complete_lattice.lean | cc23352ec5d54963775d0ae3f6d96e2d79792440 | [
"Apache-2.0"
] | permissive | SzJS/mathlib | 07836ee708ca27cd18347e1e11ce7dd5afb3e926 | 23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29 | refs/heads/master | 1,584,980,332,064 | 1,532,063,841,000 | 1,532,063,841,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 27,972 | 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
Theory of complete lattices.
-/
import order.bounded_lattice data.set.basic
set_option old_structure_cmd true
universes u v w w₂
variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂}
namespace lattice
/-- class for the `Sup` operator -/
class has_Sup (α : Type u) := (Sup : set α → α)
/-- class for the `Inf` operator -/
class has_Inf (α : Type u) := (Inf : set α → α)
/-- Supremum of a set -/
def Sup [has_Sup α] : set α → α := has_Sup.Sup
/-- Infimum of a set -/
def Inf [has_Inf α] : set α → α := has_Inf.Inf
/-- A complete lattice is a bounded lattice which
has suprema and infima for every subset. -/
class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
/-- A complete linear order is a linear order whose lattice structure is complete. -/
class complete_linear_order (α : Type u) extends complete_lattice α, linear_order α
/-- Indexed supremum -/
def supr [complete_lattice α] (s : ι → α) : α := Sup {a : α | ∃i : ι, a = s i}
/-- Indexed infimum -/
def infi [complete_lattice α] (s : ι → α) : α := Inf {a : α | ∃i : ι, a = s i}
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
section
open set
variables [complete_lattice α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha)
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha)
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
⟨assume : Sup s ≤ a, assume b, assume : b ∈ s,
le_trans (le_Sup ‹b ∈ s›) ‹Sup s ≤ a›,
Sup_le⟩
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
⟨assume : a ≤ Inf s, assume b, assume : b ∈ s,
le_trans ‹a ≤ Inf s› (Inf_le ‹b ∈ s›),
le_Inf⟩
-- how to state this? instead a parameter `a`, use `∃a, a ∈ s` or `s ≠ ∅`?
theorem Inf_le_Sup (h : a ∈ s) : Inf s ≤ Sup s :=
by have := le_Sup h; finish
--Inf_le_of_le h (le_Sup h)
-- TODO: it is weird that we have to add union_def
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
le_antisymm
(by finish)
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
/- old proof:
le_antisymm
(Sup_le $ assume a h, or.rec_on h (le_sup_left_of_le ∘ le_Sup) (le_sup_right_of_le ∘ le_Sup))
(sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _))
-/
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(by finish)
/- old proof:
le_antisymm
(le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _))
(le_Inf $ assume a h, or.rec_on h (inf_le_left_of_le ∘ Inf_le) (inf_le_right_of_le ∘ Inf_le))
-/
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
by finish
/-
le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t))
-/
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
le_antisymm (by finish) (by finish)
-- le_antisymm (Sup_le (assume _, false.elim)) bot_le
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
le_antisymm (by finish) (by finish)
--le_antisymm le_top (le_Inf (assume _, false.elim))
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
le_antisymm (by finish) (le_Sup ⟨⟩) -- finish fails because ⊤ ≤ a simplifies to a = ⊤
--le_antisymm le_top (le_Sup ⟨⟩)
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
le_antisymm (Inf_le ⟨⟩) bot_le
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
have Sup {b | b = a} = a,
from le_antisymm (Sup_le $ assume b b_eq, b_eq ▸ le_refl _) (le_Sup rfl),
calc Sup (insert a s) = Sup {b | b = a} ⊔ Sup s : Sup_union
... = a ⊔ Sup s : by rw [this]
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
have Inf {b | b = a} = a,
from le_antisymm (Inf_le rfl) (le_Inf $ assume b b_eq, b_eq ▸ le_refl _),
calc Inf (insert a s) = Inf {b | b = a} ⊓ Inf s : Inf_union
... = a ⊓ Inf s : by rw [this]
@[simp] theorem Sup_singleton {a : α} : Sup {a} = a :=
by finish [singleton_def]
--eq.trans Sup_insert $ by simp
@[simp] theorem Inf_singleton {a : α} : Inf {a} = a :=
by finish [singleton_def]
--eq.trans Inf_insert $ by simp
end
section complete_linear_order
variables [complete_linear_order α] {s t : set α} {a b : α}
lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) :=
iff.intro
(assume : Inf s < b, classical.by_contradiction $ assume : ¬ (∃a∈s, a < b),
have b ≤ Inf s,
from le_Inf $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩,
lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›))
(assume ⟨a, ha, h⟩, lt_of_le_of_lt (Inf_le ha) h)
lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) :=
iff.intro
(assume : b < Sup s, classical.by_contradiction $ assume : ¬ (∃a∈s, b < a),
have Sup s ≤ b,
from Sup_le $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩,
lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›))
(assume ⟨a, ha, h⟩, lt_of_lt_of_le h $ le_Sup ha)
lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) :=
iff.intro
(assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb)
(assume h, top_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h)
lemma lt_supr_iff {ι : Sort*} {f : ι → α} : a < supr f ↔ (∃i, a < f i) :=
iff.trans lt_Sup_iff $ iff.intro
(assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩)
(assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩)
lemma infi_lt_iff {ι : Sort*} {f : ι → α} : infi f < a ↔ (∃i, f i < a) :=
iff.trans Inf_lt_iff $ iff.intro
(assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩)
(assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩)
end complete_linear_order
/- supr & infi -/
section
open set
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq.symm ▸ h i
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
⟨assume : supr s ≤ a, assume i, le_trans (le_supr _ _) this, supr_le⟩
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
le_antisymm
(supr_le_supr2 $ assume j, ⟨pq.mp j, le_of_eq $ f _⟩)
(supr_le_supr2 $ assume j, ⟨pq.mpr j, le_of_eq $ (f j).symm⟩)
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
/- I wanted to see if this would help for infi_comm; it doesn't.
@[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂): (: ⨅ i j, s i j :) ≤ (: s i j :) :=
begin
transitivity,
apply (infi_le (λ i, ⨅ j, s i j) i),
apply infi_le
end
-/
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq.symm ▸ h i
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
@[congr] theorem infi_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
le_antisymm
(infi_le_infi2 $ assume j, ⟨pq.mpr j, le_of_eq $ f j⟩)
(infi_le_infi2 $ assume j, ⟨pq.mp j, le_of_eq $ (f _).symm⟩)
@[simp] theorem infi_const {a : α} [inhabited ι] : (⨅ b:ι, a) = a :=
le_antisymm (Inf_le ⟨arbitrary ι, rfl⟩) (by finish)
@[simp] theorem supr_const {a : α} [inhabited ι] : (⨆ b:ι, a) = a :=
le_antisymm (by finish) (le_Sup ⟨arbitrary ι, rfl⟩)
@[simp] lemma infi_top [complete_lattice α] : (⨅i:ι, ⊤ : α) = ⊤ :=
top_unique $ le_infi $ assume i, le_refl _
@[simp] lemma supr_bot [complete_lattice α] : (⨆i:ι, ⊥ : α) = ⊥ :=
bot_unique $ supr_le $ assume i, le_refl _
@[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _)
@[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ :=
le_antisymm le_top $ le_infi $ assume h, (hp h).elim
@[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _)
@[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ :=
le_antisymm (supr_le $ assume h, (hp h).elim) bot_le
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
le_antisymm
(supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i)
(supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j)
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
attribute [ematch] le_refl
theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_left_of_le $ infi_le _ _)
(inf_le_right_of_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right))
lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) :=
by rw [inf_comm, infi_inf i]; simp [inf_comm]
lemma binfi_inf {ι : Sort*} {p : ι → Prop}
{f : Πi, p i → α} {a : α} {i : ι} (hi : p i) :
(⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi,
le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left)
(infi_le_of_le i $ infi_le_of_le hi $ inf_le_right))
theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
le_antisymm
(supr_le $ assume i, sup_le
(le_sup_left_of_le $ le_supr _ _)
(le_sup_right_of_le $ le_supr _ _))
(sup_le
(supr_le $ assume i, le_supr_of_le i le_sup_left)
(supr_le $ assume i, le_supr_of_le i le_sup_right))
/- supr and infi under Prop -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
@[simp] theorem infi_true {s : true → α} : infi s = s trivial :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_true {s : true → α} : supr s = s trivial :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_left_of_le $ infi_le _ _
| or.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| or.inl i := le_sup_left_of_le $ le_supr _ i
| or.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩))
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume h, Inf_le h)
(le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h)
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma Sup_range {f : ι → α} : Sup (range f) = supr f :=
le_antisymm
(Sup_le $ forall_range_iff.mpr $ assume i, le_supr _ _)
(supr_le $ assume i, le_Sup (mem_range_self _))
lemma Inf_range {f : ι → α} : Inf (range f) = infi f :=
le_antisymm
(le_infi $ assume i, Inf_le (mem_range_self _))
(le_Inf $ forall_range_iff.mpr $ assume i, infi_le _ _)
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
le_antisymm
(supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i)
(supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _))
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
le_antisymm
(le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _))
(le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i)
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi
... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm]
... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm]
... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left]
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr
... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm]
... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm]
... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left]
/- supr and infi under set constructions -/
/- should work using the simplifier! -/
@[simp] theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
le_antisymm le_top (le_infi $ assume x, le_infi false.elim)
@[simp] theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
le_antisymm (supr_le $ assume x, supr_le false.elim) bot_le
@[simp] theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
show (⨅ (x : β) (H : true), f x) = ⨅ (x : β), f x,
from congr_arg infi $ funext $ assume x, infi_const
@[simp] theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
show (⨆ (x : β) (H : true), f x) = ⨆ (x : β), f x,
from congr_arg supr $ funext $ assume x, supr_const
@[simp] theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or
... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq
@[simp] theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or
... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq
@[simp] theorem insert_of_has_insert (x : α) (a : set α) : has_insert.insert x a = insert x a := rfl
@[simp] theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
@[simp] theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
@[simp] theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
show (⨅ x ∈ insert b (∅ : set β), f x) = f b,
by simp
@[simp] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
show (⨆ x ∈ insert b (∅ : set β), f x) = f b,
by simp
/- supr and infi under Type -/
@[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i)
@[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le
@[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff :=
le_antisymm
(supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end)
(sup_le (le_supr _ _) (le_supr _ _))
lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff :=
le_antisymm
(le_inf (infi_le _ _) (infi_le _ _))
(le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end)
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_prod {γ : Type w} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume i, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume s, match s with
| sum.inl i := inf_le_left_of_le $ infi_le _ _
| sum.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| sum.inl i := le_sup_left_of_le $ le_supr _ i
| sum.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩))
end
/- Instances -/
instance complete_lattice_Prop : complete_lattice Prop :=
{ Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p,
..lattice.bounded_lattice_Prop }
instance complete_lattice_fun {α : Type u} {β : Type v} [complete_lattice β] :
complete_lattice (α → β) :=
{ Sup := λs a, Sup (set.image (λf : α → β, f a) s),
le_Sup := assume s f h a, le_Sup ⟨f, h, rfl⟩,
Sup_le := assume s f h a, Sup_le $ assume b ⟨f', h', b_eq⟩, b_eq ▸ h _ h' a,
Inf := λs a, Inf (set.image (λf : α → β, f a) s),
Inf_le := assume s f h a, Inf_le ⟨f, h, rfl⟩,
le_Inf := assume s f h a, le_Inf $ assume b ⟨f', h', b_eq⟩, b_eq ▸ h _ h' a,
..lattice.bounded_lattice_fun }
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
end complete_lattice
end lattice
section ord_continuous
open lattice
variables [complete_lattice α] [complete_lattice β]
/-- A function `f` between complete lattices is order-continuous
if it preserves all suprema. -/
def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i)
lemma ord_continuous_sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ :=
have h : f (Sup {a₁, a₂}) = (⨆i∈({a₁, a₂} : set α), f i), from hf _,
have h₁ : {a₁, a₂} = (insert a₂ {a₁} : set α), from rfl,
begin
rw [h₁, Sup_insert, Sup_singleton, sup_comm] at h,
rw [h, supr_insert, supr_singleton, sup_comm]
end
lemma ord_continuous_mono {f : α → β} (hf : ord_continuous f) : monotone f :=
assume a₁ a₂ h,
calc f a₁ ≤ f a₁ ⊔ f a₂ : le_sup_left
... = f (a₁ ⊔ a₂) : (ord_continuous_sup hf).symm
... = _ : by rw [sup_of_le_right h]
end ord_continuous
/- Classical statements:
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
_
@[simp] theorem infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
_
@[simp] theorem Sup_eq_bot : Sup s = ⊤ ↔ (∀a∈s, a = ⊥) :=
_
@[simp] theorem supr_eq_top : supr s = ⊤ ↔ (∀i, s i = ⊥) :=
_
-/
|
1a1da359be656b466202358ed2e05bd99523eceb | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/ring_theory/ideal_over.lean | 9ec50538d3382d130e058b4b45a1b3816f46fbd1 | [
"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 | 3,228 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Anne Baanen
-/
import ring_theory.algebraic
/-!
# Ideals over/under ideals
This file concerns ideals lying over other ideals.
Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and
`J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`.
This is expressed here by writing `I = J.comap f`.
-/
variables {R : Type*} [comm_ring R]
namespace ideal
open polynomial
open submodule
section comm_ring
variables {S : Type*} [comm_ring S] {f : R →+* S} {I : ideal S}
lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : polynomial R}
(hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f :=
begin
rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp,
refine mem_comap.mpr ((I.add_mem_iff_right _).mp (by simpa only [←hp] using I.zero_mem)),
exact I.mul_mem_left hr
end
end comm_ring
section integral_domain
variables {S : Type*} [integral_domain S] {f : R →+* S} {I : ideal S}
lemma exists_coeff_ne_zero_mem_comap_of_root_mem {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I)
{p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0),
∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f :=
begin
refine p.rec_on_horner _ _ _,
{ intro h, contradiction },
{ intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp,
refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩,
simp [coeff_eq_zero, a_ne_zero] },
{ intros p p_nonzero ih mul_nonzero hp,
rw [eval₂_mul, eval₂_X, mul_eq_zero] at hp,
obtain ⟨i, hi, mem⟩ := ih p_nonzero (or.resolve_right hp r_ne_zero),
refine ⟨i + 1, _, _⟩; simp [hi, mem] }
end
lemma comap_ne_bot_of_root_mem {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I)
{p : polynomial R} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) :
I.comap f ≠ ⊥ :=
λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in
absurd ((mem_bot _).mp (eq_bot_iff.mp h mem)) hi
variables [algebra R S]
lemma comap_ne_bot_of_algebraic_mem {I : ideal S} {x : S}
(x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ :=
let ⟨p, p_ne_zero, hp⟩ := hx
in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp
lemma comap_ne_bot_of_integral_mem [nontrivial R] {I : ideal S} {x : S}
(x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ :=
comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R)
lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)}
(I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ :=
let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in
comap_ne_bot_of_integral_mem x_ne_zero x_mem (integral_closure.is_integral x)
lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} :
I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ :=
imp_of_not_imp_not _ _ integral_closure.comap_ne_bot
end integral_domain
end ideal
|
24d9eb36f7937f90bd34972c33d987a112d1dc52 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/t9.lean | da4bcc5c0d2059570c09b6fc8b15dc31aeadff4d | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 598 | lean | definition bool : Type.{1} := Type.{0}
definition and (p q : bool) : bool
:= ∀ c : bool, (p → q → c) → c
infixl `∧`:25 := and
theorem and_intro (p q : bool) (H1 : p) (H2 : q) : p ∧ q
:= λ (c : bool) (H : p → q → c), H H1 H2
theorem and_elim_left (p q : bool) (H : p ∧ q) : p
:= H p (λ (H1 : p) (H2 : q), H1)
theorem and_elim_right (p q : bool) (H : p ∧ q) : q
:= H q (λ (H1 : p) (H2 : q), H2)
theorem and_comm (p q : bool) (H : p ∧ q) : q ∧ p
:= have H1 : p, from and_elim_left p q H,
have H2 : q, from and_elim_right p q H,
show q ∧ p, from and_intro q p H2 H1
|
36cf591465597e80b11d26a33cd8a775f6aedbdd | c09f5945267fd905e23a77be83d9a78580e04a4a | /src/data/list/basic.lean | aeae66df96892d44060670c42666262517e11d17 | [
"Apache-2.0"
] | permissive | OHIHIYA20/mathlib | 023a6df35355b5b6eb931c404f7dd7535dccfa89 | 1ec0a1f49db97d45e8666a3bf33217ff79ca1d87 | refs/heads/master | 1,587,964,529,965 | 1,551,819,319,000 | 1,551,819,319,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 188,424 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
Basic properties of lists.
-/
import
tactic.interactive tactic.mk_iff_of_inductive_prop tactic.split_ifs
logic.basic logic.function logic.relation
algebra.group order.basic
data.list.defs data.nat.basic data.option.basic
data.bool data.prod data.sigma data.fin
open function nat
namespace list
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
instance : is_left_id (list α) has_append.append [] :=
⟨ nil_append ⟩
instance : is_right_id (list α) has_append.append [] :=
⟨ append_nil ⟩
instance : is_associative (list α) has_append.append :=
⟨ append_assoc ⟩
@[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
theorem cons_inj {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
@[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
⟨λ e, cons_inj e, congr_arg _⟩
/- mem -/
theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil
| [] := assume h, rfl
| (b :: l') := assume h, absurd (mem_cons_self b l') (h b)
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, or.inl⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] :=
by intro e; rw e at h; cases h
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] :=
⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih, {cases h}, rcases h with rfl | h,
{ exact ⟨[], l, rfl⟩ },
{ rcases ih h with ⟨s, t, rfl⟩,
exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{cases h},
{rcases h with rfl | h,
{exact or.inl rfl},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{cases h},
{cases (eq_or_mem_of_mem_cons h) with h h,
{exact ⟨c, mem_cons_self _ _, h.symm⟩},
{rcases ih h with ⟨a, ha₁, ha₂⟩,
exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
lemma bind_map {g : α → list β} {f : β → γ} :
∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f)
| [] := rfl
| (a::l) := by simp only [cons_bind, map_append, bind_map l]
/- bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
@[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} :
(∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [or_imp_distrib, forall_and_distrib, forall_eq]
theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} :
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [mem_cons_iff, forall_mem_cons']
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a :=
by simp only [mem_singleton, forall_eq]
theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_append, or_imp_distrib, forall_and_distrib]
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x.
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (mem_cons_self _ _) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, left, exact px end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
@[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
/- list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ :=
λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩
/- append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t :=
by {induction s with b s H generalizing a, refl, simp only [foldl, cons_append], rw H _}
theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s :=
by {induction s with b s H generalizing a, refl, simp only [foldr, cons_append], rw H _}
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and]
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true,
true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left']
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { rw nil_append, split,
{ rintro rfl, left, exact ⟨_, rfl, rfl⟩ },
{ rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } },
case cons : a as ih {
cases c,
{ simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm },
{ simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } }
end
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_left h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_right' h rfl
theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
⟨append_left_cancel, congr_arg _⟩
theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
⟨append_right_cancel, congr_arg _⟩
theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β}
(h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ :=
begin
have := h, rw [← take_append_drop (length s₁) l] at this ⊢,
rw map_append at this,
refine ⟨_, _, rfl, append_inj this _⟩,
rw [length_map, length_take, min_eq_left],
rw [← length_map f l, h, length_append],
apply nat.le_add_right
end
/- join -/
attribute [simp] join
theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = []
| [] := iff_of_true rfl (forall_mem_nil _)
| (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]]
/- repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂;
unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n :=
by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
@[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n :=
by induction n; [refl, simp only [*, repeat, map]]; split; refl
@[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred :=
by cases n; refl
@[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α :=
by induction n; [refl, simp only [*, repeat, join, append_nil]]
/- bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
@[simp] theorem bind_append {α β} (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
/- concat -/
@[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl
@[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by induction l; intro h; contradiction
@[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by induction l₁; simp only [*, cons_append, concat]; split; refl
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp only [*, concat]; split; refl
@[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp only [concat_eq_append, length_append, length]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by induction l₂ with b l₂ ih; simp only [concat_eq_append, nil_append, cons_append, append_assoc]
/- reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]],
(aux l nil).symm
theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ :=
by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
by simp only [reverse_cons, concat_eq_append]
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; [rw [nil_append, reverse_nil, append_nil],
simp only [*, cons_append, reverse_cons, append_assoc]]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
theorem reverse_injective : injective (@reverse α) :=
injective_of_left_inverse reverse_reverse
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
@[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] :=
@reverse_inj _ l []
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp only [concat_eq_append, reverse_cons, reverse_reverse]
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; [refl, simp only [*, reverse_cons, length_append, length]]
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; [refl, simp only [*, map, reverse_cons, map_append]]
theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) :
map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) :=
by simp only [reverse_core_eq, map_append, map_reverse]
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]]
@[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n :=
eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩
@[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ rw reverse_cons, exact H1 _ _ ih }
end
/- last -/
@[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]]
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp only [concat_eq_append, last_append]
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
/- head(') and tail -/
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
@[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s :=
by {induction s, contradiction, refl}
theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
by {induction l, contradiction, refl}
/- map -/
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in
by rw [map, map, h₁, map_congr h₂]
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; [refl, simp only [*, map]]; split; refl
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldl]]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldr]]
theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α)
(h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l :=
by revert a; induction l; intros; [refl, simp only [*, foldl]]
theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α)
(h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l :=
by revert a; induction l; intros; [refl, simp only [*, foldr]]
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; [refl, simp only [*, join, map, map_append]]
theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) :
f <$> l = map f l := rfl
@[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) :=
by cases l; refl
/- map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
/- sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih, {refl},
{ rw reverse_cons, exact sublist_app_of_sublist_left ih },
{ rw [reverse_cons, reverse_cons], exact append_sublist_append_of_sublist_right ih [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp only [reverse_reverse] at this; assumption, reverse_sublist⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by have := reverse_sublist h; simp only [reverse_append, append_sublist_append_left, reverse_sublist_iff] at this; assumption,
λ h, append_sublist_append_of_sublist_right h l⟩
theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (subset_of_sublist s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ subset_of_sublist s
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h,
λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/- index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih,
{ exact iff_of_true rfl (not_mem_nil _) },
simp only [length, mem_cons_iff, index_of_cons], split_ifs,
{ exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) },
{ simp only [h, false_or], rw ← ih, exact succ_inj' }
end
@[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih, {refl},
simp only [length, index_of_cons],
by_cases h : a = b, {rw if_pos h, exact nat.zero_le _},
rw if_neg h, exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/- nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_ge_len (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_ge_len hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a :=
let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩
theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l
| (a :: l) 0 h := mem_cons_self _ _
| (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _)
theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l :=
let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _
theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a :=
⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩
theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a :=
mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm
@[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f
| [] n := rfl
| (a :: l) 0 := rfl
| (a :: l) (n+1) := nth_map l n
theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) :=
option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl
@[simp] theorem nth_le_map' (f : α → β) {l n} (H) :
nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f _ _
@[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) :
nth_le [a] n hn = a :=
have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn),
by subst hn0; refl
lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂),
(l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂
| [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim
| (a::l) _ 0 hn₁ hn₂ := rfl
| (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append];
exact nth_le_append _ _
@[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < n) :
(list.repeat a n).nth_le m (by rwa list.length_repeat) = a :=
eq_of_mem_repeat (nth_le_mem _ _ _)
lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) :
(l₁ ++ l₂).nth n = l₁.nth n :=
have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn
(by rw length_append; exact le_add_right _ _),
by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append]
@[simp] lemma nth_concat_length: ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = a
| [] a := rfl
| (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length]
@[extensionality]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa;
simp only [aa, ext (λn, h (n+1))]; split; refl
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])]
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l]
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact
λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) :
∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) =
l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l)
lemma modify_nth_tail_modify_nth_tail_le
{f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) :
(l.modify_nth_tail f n).modify_nth_tail g m =
l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n :=
begin
rcases le_iff_exists_add.1 h with ⟨m, rfl⟩,
rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail]
end
lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) :
(l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n :=
by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl
lemma modify_nth_tail_id :
∀n (l:list α), l.modify_nth_tail id n = l
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m;
simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp only [update_nth_eq_modify_nth, modify_nth_length]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp only [nth_modify_nth, if_pos]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp only [nth_modify_nth, if_neg h, id_map']
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h]
section insert_nth
variable {a : α}
@[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl
lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1
| 0 as h := rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h)
lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l :=
by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same];
from modify_nth_tail_id _ _
lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n
| 0 0 [] has _ := (lt_irrefl _ has).elim
| 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth]
| 0 (m+1) (a::as) has hmn := rfl
| (n+1) (m+1) (a::as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1)
| n 0 (a :: as) has hmn := rfl
| (n + 1) (m + 1) (a :: as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_comm (a b : α) :
∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l),
(l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a
| 0 j l := by simp [insert_nth]
| (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim
| (i + 1) (j+1) [] := by simp
| (i + 1) (j+1) (c::l) :=
assume h₀ h₁,
by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁)
end insert_nth
/- take, drop -/
@[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
@[simp] theorem take_all : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end
theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_ge (le_of_succ_le_succ h)]
end
@[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁
| [] l₂ := rfl
| (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂)
theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take_left
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [min_zero, take_zero, take_nil]
| 0 m l := by rw [zero_min, take_zero, take_zero]
| (succ n) (succ m) nil := by simp only [take_nil]
| (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl
@[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
@[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l
| [] := rfl
| (a :: l) := rfl
theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l)
| m 0 l := rfl
| m (n+1) [] := (drop_nil _).symm
| m (n+1) (a::l) := drop_add m n _
@[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂
| [] l₂ := rfl
| (a::l₁) l₂ := drop_left l₁ l₂
theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
drop n (l₁ ++ l₂) = l₂ :=
by rw ← h; apply drop_left
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
@[simp] lemma drop_all (l : list α) : l.drop l.length = [] :=
calc l.drop l.length = (l ++ []).drop l.length : by simp
... = [] : drop_left _ _
lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length →
(l₁ ++ l₂).drop n = l₁.drop n ++ l₂
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)]
lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ},
n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)]
@[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l
| m [] := by simp
| 0 l := by simp
| (m+1) (a::l) :=
calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl
... = drop (n + m) l : drop_drop m l
... = drop (n + (m + 1)) (a :: l) : rfl
theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α),
drop m (take (m + n) l) = take n (drop m l)
| 0 n _ := by simp
| (m+1) n nil := by simp
| (m+1) n (_::l) :=
have h: m + 1 + n = (m+n) + 1, by simp,
by simpa [take_cons, h] using drop_take m n l
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
@[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] :=
by cases l; cases n; simp only [update_nth]
section take'
variable [inhabited α]
@[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n
| 0 l := rfl
| (n+1) l := congr_arg succ (take'_length _ _)
@[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n
| 0 := rfl
| (n+1) := congr_arg (cons _) (take'_nil _)
theorem take'_eq_take : ∀ {n} {l : list α},
n ≤ length l → take' n l = take n l
| 0 l h := rfl
| (n+1) (a::l) h := congr_arg (cons _) $
take'_eq_take $ le_of_succ_le_succ h
@[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ :=
(take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _)
theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take' n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take'_left
end take'
/- foldl, foldr -/
lemma foldl_ext (f g : α → β → α) (a : α)
{l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) :
foldl f a l = foldl g a l :=
begin
induction l with hd tl ih generalizing a, {refl},
unfold foldl,
rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)]
end
lemma foldr_ext (f g : α → β → β) (b : β)
{l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) :
foldr f b l = foldr g b l :=
begin
induction l with hd tl ih, {refl},
simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H,
simp only [foldr, ih H.2, H.1]
end
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : α → β → α) :
∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂
| a [] l₂ := rfl
| a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂]
@[simp] theorem foldl_join (f : α → β → α) :
∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L
| a [] := rfl
| a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L]
@[simp] theorem foldr_join (f : α → β → β) :
∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L
| a [] := rfl
| a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl
@[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l :=
by rw ←foldr_reverse; simp
/- scanr -/
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp only [scanr, scanr_aux, t, foldr_cons]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp only [foldl_cons];
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons]
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/- mfoldl, mfoldr -/
section mfoldl_mfoldr
variables {m : Type v → Type w} [monad m]
@[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl
@[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl
@[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} :
mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl
@[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} :
mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl
variables [is_lawful_monad m]
@[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂},
mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂
| _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind]
| _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc]
@[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂},
mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁
| _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure]
| _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc]
end mfoldl_mfoldr
/- sum -/
attribute [to_additive list.sum] list.prod
attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive list.sum_nil]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[simp, to_additive list.sum_cons]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, to_additive list.sum_append]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive list.sum_join]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
end monoid
@[simp, to_additive list.sum_erase]
theorem prod_erase [decidable_eq α] [comm_monoid α] {a} :
Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b::l) h :=
begin
rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; [refl, simp only [*, join, map, sum_cons, length_append]]
@[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
/- lexicographic ordering -/
inductive lex (r : α → α → Prop) : list α → list α → Prop
| nil {} {a l} : lex [] (a :: l)
| cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂)
| rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂)
namespace lex
theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} :
lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ :=
⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h;
[exact h, exact (irrefl_of r a h).elim], lex.cons⟩
instance is_order_connected (r : α → α → Prop)
[is_order_connected α r] [is_trichotomous α r] :
is_order_connected (list α) (lex r) :=
⟨λ l₁, match l₁ with
| _, [], c::l₃, nil := or.inr nil
| _, [], c::l₃, rel _ := or.inr nil
| _, [], c::l₃, cons _ := or.inr nil
| _, b::l₂, c::l₃, nil := or.inl nil
| a::l₁, b::l₂, c::l₃, rel h :=
(is_order_connected.conn _ b _ h).imp rel rel
| a::l₁, b::l₂, _::l₃, cons h := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match _ l₂ _ h).imp cons cons },
{ exact or.inr (rel ab) }
end
end⟩
instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] :
is_trichotomous (list α) (lex r) :=
⟨λ l₁, match l₁ with
| [], [] := or.inr (or.inl rfl)
| [], b::l₂ := or.inl nil
| a::l₁, [] := or.inr (or.inr nil)
| a::l₁, b::l₂ := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match l₁ l₂).imp cons
(or.imp (congr_arg _) cons) },
{ exact or.inr (or.inr (rel ab)) }
end
end⟩
instance is_asymm (r : α → α → Prop)
[is_asymm α r] : is_asymm (list α) (lex r) :=
⟨λ l₁, match l₁ with
| a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂
| a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁
| a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂
| a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ :=
by exact _match _ _ h₁ h₂
end⟩
instance is_strict_total_order (r : α → α → Prop)
[is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) :=
{..is_strict_weak_order_of_is_order_connected}
instance decidable_rel [decidable_eq α] (r : α → α → Prop)
[decidable_rel r] : decidable_rel (lex r)
| l₁ [] := is_false $ λ h, by cases h
| [] (b::l₂) := is_true lex.nil
| (a::l₁) (b::l₂) := begin
haveI := decidable_rel l₁ l₂,
refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩,
{ rcases h with h | ⟨rfl, h⟩,
{ exact lex.rel h },
{ exact lex.cons h } },
{ rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩,
{ exact or.inr ⟨rfl, h⟩ },
{ exact or.inl h } }
end
theorem append_right (r : α → α → Prop) :
∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t)
| _ _ t nil := nil
| _ _ t (cons h) := cons (append_right _ h)
| _ _ t (rel r) := rel r
theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) :
∀ s, lex R (s ++ t₁) (s ++ t₂)
| [] := h
| (a::l) := cons (append_left l)
theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) :
∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂
| _ _ nil := nil
| _ _ (cons h) := cons (imp _ _ h)
| _ _ (rel r) := rel (H _ _ r)
theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂
| _ _ (cons h) e := to_ne h (list.cons.inj e).2
| _ _ (rel r) e := r (list.cons.inj e).1
theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) :
lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨to_ne, λ h, begin
induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂,
{ contradiction },
{ apply nil },
{ exact (not_lt_of_ge H).elim (succ_pos _) },
{ cases classical.em (a = b) with ab ab,
{ subst b, apply cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact rel ab } }
end⟩
end lex
--Note: this overrides an instance in core lean
instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩
theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l :=
lex.nil
instance [linear_order α] : linear_order (list α) :=
linear_order_of_STO' (lex (<))
--Note: this overrides an instance in core lean
instance has_le' [linear_order α] : has_le (list α) :=
preorder.to_has_le _
instance [decidable_linear_order α] : decidable_linear_order (list α) :=
decidable_linear_order_of_STO' (lex (<))
/- all & any -/
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
simp only [all_cons, band_coe_iff, ih, forall_mem_cons]
end
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp only [all_iff_forall, bool.of_to_bool_iff]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_false bool.not_ff (not_exists_mem_nil _) },
simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff]
end
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
@[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/- map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β
| [] H := []
| (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) :
@pmap _ _ p (λ a _, f a) l H = map f l :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f l H₁ = pmap g l H₂ :=
by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]]
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) :=
by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl)
theorem attach_map_val (l : list α) : l.attach.map subtype.val = l :=
by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l)
@[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ :=
by have := mem_map.1 (by rw [attach_map_val]; exact h);
{ rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m }
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b :=
by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists]
@[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β}
{l H} : length (pmap f l H) = length l :=
by induction l; [refl, simp only [*, pmap, length]]
@[simp] lemma length_attach {α} (L : list α) : L.attach.length = L.length := length_pmap
/- find -/
section find
variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α}
@[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases h : p a,
{ simp only [find_cons_of_pos _ h, h, not_true, false_and] },
{ rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] }
end
@[simp] theorem find_some (H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, exact h },
{ rw find_cons_of_neg _ h at H, exact IH H }
end
@[simp] theorem find_mem (H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self },
{ rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) }
end
end find
/- lookmap -/
section lookmap
variables (f : α → option α)
@[simp] theorem lookmap_nil : [].lookmap f = [] := rfl
@[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) :
(a :: l).lookmap f = a :: l.lookmap f :=
by simp [lookmap, h]
@[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) :
(a :: l).lookmap f = b :: l :=
by simp [lookmap, h]
theorem lookmap_some : ∀ l : list α, l.lookmap some = l
| [] := rfl
| (a::l) := rfl
theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l
| [] := rfl
| (a::l) := congr_arg (cons a) (lookmap_none l)
theorem lookmap_congr {f g : α → option α} :
∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g
| [] H := rfl
| (a::l) H := begin
cases forall_mem_cons.1 H with H₁ H₂,
cases h : g a with b,
{ simp [h, H₁.trans h, lookmap_congr H₂] },
{ simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] }
end
theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l :=
(lookmap_congr H).trans (lookmap_none l)
theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) :
∀ l : list α, map g (l.lookmap f) = map g l
| [] := rfl
| (a::l) := begin
cases h' : f a with b,
{ simp [h', lookmap_map_eq] },
{ simp [lookmap_cons_some _ _ h', h _ _ h'] }
end
theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l :=
by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h
theorem length_lookmap (l : list α) : length (l.lookmap f) = length l :=
by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp
end lookmap
/- filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp only [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp only [filter_map, h]; split; refl
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {refl},
simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {refl},
by_cases pa : p a,
{ simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl },
{ simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] }
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp only [h, option.none_bind'] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp only [h, h', option.some_bind']
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases h : p x,
{ simp only [option.guard, if_pos h, option.some_bind'] },
{ simp only [option.guard, if_neg h, option.none_bind'] }
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH,
{ split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } },
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, this, exists_eq_left] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp only [map_filter_map, H, filter_map_some]
theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp only [filter_map]; cases f a with b;
simp only [filter_map, IH, sublist.cons, sublist.cons2]
theorem map_sublist_map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s
/- filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
: ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l
| [] _ := rfl
| (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a;
[simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2],
simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
subset_of_sublist $ filter_sublist l
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self
| (b::l) (or.inr ain) pa := if pb : p b
then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa
else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases p a,
{ rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] },
{ rw [filter_cons_of_neg _ h],
refine iff_of_false _ (mt and.left h), intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) }
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and]
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s
theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) :=
by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl
@[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l,
filter p (filter q l) = filter (λ a, p a ∧ q a) l
| [] := rfl
| (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false,
true_and, false_and, filter_filter l, eq_self_iff_true]
@[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while]
else by simp only [span, take_while, drop_while, if_neg pa]
@[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l]
else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append]
@[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h],
simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp only [countp_eq_length_filter, filter_append, length_append]
theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a :=
by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop]
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s)
@[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) :
countp p (filter q l) = countp (λ a, p a ∧ q a) l :=
by simp only [countp_eq_length_filter, filter_filter]
end filter
/- count -/
section count
variable [decidable_eq α]
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
begin rw count_cons, split_ifs; refl end
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append
@[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by rw [concat_eq_append, count_append, count_singleton]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp only [count, countp_pos, exists_prop, exists_eq_right']
@[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {l : list α} (h : p a) : count a (filter p l) = count a l :=
by simp only [count, countp_filter]; congr; exact
set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h))
end count
/- prefix, suffix, infix -/
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
@[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
@[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a :=
by simp only [concat_eq_append, prefix_append]
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp only [reverse_reverse]
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_left_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_left_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton],
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| ._, t, or.inl rfl := suffix_refl _
| s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inl rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩)
end⟩
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/- sublists -/
@[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl
@[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl
theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) :
map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) :
sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_eq_sublists' (l f r) :
@sublists'_aux α β l f r = map f (sublists' l) ++ r :=
by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl
@[simp] theorem sublists'_cons (a : α) (l : list α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) :=
by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl
@[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t :=
begin
induction t with a t IH generalizing s,
{ simp only [sublists'_nil, mem_singleton],
exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ },
simp only [sublists'_cons, mem_append, IH, mem_map],
split; intro h, rcases h with h | ⟨s, h, rfl⟩,
{ exact sublist_cons_of_sublist _ h },
{ exact cons_sublist_cons _ h },
{ cases h with _ _ _ h s _ _ h,
{ exact or.inl h },
{ exact or.inr ⟨s, h, rfl⟩ } }
end
@[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l
| [] := rfl
| (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map,
length, pow_succ, mul_succ, mul_zero, zero_add]
@[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl
@[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl
theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β),
sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r)
| [] f := rfl
| (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc]
theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) :
sublists_aux l cons = sublists_aux₁ l (λ x, [x]) :=
by rw [sublists_aux₁_eq_sublists_aux]; refl
theorem sublists_aux_eq_foldr.aux {a : α} {l : list α}
(IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons))
(IH₂ : ∀ (f : list α → list (list α) → list (list α)),
sublists_aux l f = foldr f [] (sublists_aux l cons))
(f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) :=
begin
simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1,
induction sublists_aux l cons with _ _ ih, {refl},
simp only [ih, foldr_cons]
end
theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons) :=
suffices _ ∧ ∀ f : list α → list (list α) → list (list α),
sublists_aux l f = foldr f [] (sublists_aux l cons),
from this.1,
begin
induction l with a l IH, {split; intro; refl},
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2,
sublists_aux_eq_foldr.aux IH.2 IH.2⟩
end
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldr]; refl
theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β),
sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++
sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x)))
| [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil]
| (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl
theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) :
sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++
f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) :=
by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil]
theorem sublists_aux₁_bind : ∀ (l : list α)
(f : list α → list β) (g : β → list γ),
(sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g)
| [] f g := rfl
| (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l]
theorem sublists_aux_cons_append (l₁ l₂ : list α) :
sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++
(do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) :=
begin
simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind],
congr, funext x, apply congr_arg _,
rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm
end
theorem sublists_append (l₁ l₂ : list α) :
sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) :=
by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind,
cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl
@[simp] theorem sublists_concat (l : list α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) :=
by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind,
map_eq_map, map_eq_map, map_id' (append_nil), append_nil]
theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) :=
by induction l with hd tl ih; [refl,
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]]
theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) :=
by rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) :=
by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)]
theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) :=
by rw [← sublists'_reverse, reverse_reverse]
theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons
| [] := id
| (a::l) := begin
rw [sublists_aux_cons_cons],
refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _,
have := sublists_aux_ne_nil l, revert this,
induction sublists_aux l cons; intro, {rwa foldr},
simp only [foldr, mem_cons_iff, false_or, not_or_distrib],
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
end
@[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t :=
by rw [← reverse_sublist_iff, ← mem_sublists',
sublists'_reverse, mem_map_of_inj reverse_injective]
@[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l :=
by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l :=
reverse_rec_on l (nil_sublist _) $
λ l a IH, by simp only [map, map_append, sublists_concat]; exact
((append_sublist_append_left _).2 $ singleton_sublist.2 $
mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans
((append_sublist_append_right _).2 IH)
/- forall₂ -/
section forall₂
variables {r : α → β → Prop} {p : γ → δ → Prop}
open relator relation
run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff
@[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} :
forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ :=
⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩
theorem forall₂.imp {R S : α → β → Prop}
(H : ∀ a b, R a b → S a b) {l₁ l₂}
(h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ :=
by induction h; constructor; solve_by_elim
lemma forall₂.mp {r q s : α → β → Prop} (h : ∀a b, r a b → q a b → s a b) :
∀{l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂
| [] [] forall₂.nil forall₂.nil := forall₂.nil
| (a::l₁) (b::l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) :=
forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs)
lemma forall₂.flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b
| _ _ forall₂.nil := forall₂.nil
| (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip
lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l
| [] _ := forall₂.nil
| (a::as) h := forall₂.cons
(h _ (mem_cons_self _ _))
(forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha)
lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l :=
forall₂_same $ assume a h, is_refl.refl _ _
lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) :=
begin
funext a b, apply propext,
split,
{ assume h, induction h, {refl}, simp only [*]; split; refl },
{ assume h, subst h, exact forall₂_refl _ }
end
@[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
@[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil :=
⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩
lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') :=
iff.intro
(assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_cons_right_iff {b l u} :
forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') :=
iff.intro
(assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end)
(assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end)
lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} :
∀l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀a∈l, p a) ∧ forall₂ r l u
| [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and]
| (a::l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons,
and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm]
@[simp] lemma forall₂_map_left_iff {f : γ → α} :
∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u
| [] _ := by simp only [map, forall₂_nil_left_iff]
| (a::l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff]
@[simp] lemma forall₂_map_right_iff {f : γ → β} :
∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u
| _ [] := by simp only [map, forall₂_nil_right_iff]
| _ (b::u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff]
lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r)
| a₀ nil a₁ forall₂.nil forall₂.nil := rfl
| (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl
lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r)
| nil a₀ a₁ forall₂.nil forall₂.nil := rfl
| (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) :=
hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl
lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) :=
⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩
theorem forall₂_length_eq {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂
| _ _ forall₂.nil := rfl
| _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂)
theorem forall₂_zip {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b
| _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁
| _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃
theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔
length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b :=
⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩,
λ h, begin
cases h with h₁ h₂,
induction l₁ with a l₁ IH generalizing l₂,
{ cases length_eq_zero.1 h₁.symm, constructor },
{ cases l₂ with b l₂; injection h₁ with h₁,
exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) }
end⟩
theorem forall₂_take {R : α → β → Prop} :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂)
| 0 _ _ _ := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n]
theorem forall₂_drop {R : α → β → Prop} :
∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂)
| 0 _ _ h := by simp only [drop, h]
| (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop]
| (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n]
theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ :=
have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h,
by rwa [take_left] at h'
theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β)
(h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ :=
have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h,
by rwa [drop_left] at h'
lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈)
| a b h [] [] forall₂.nil := by simp only [not_mem_nil]
| a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂)
lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map
| f g h [] [] forall₂.nil := forall₂.nil
| f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂)
lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append
| [] [] h l₁ l₂ hl := hl
| (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl)
lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join
| [] [] forall₂.nil := forall₂.nil
| (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂)
lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind :=
assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁)
lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs
lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr
| f g hfg _ _ h _ _ forall₂.nil := h
| f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs)
lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q]
(hpq : (r ⇒ (↔)) p q) :
(forall₂ r ⇒ forall₂ r) (filter p) (filter q)
| _ _ forall₂.nil := forall₂.nil
| (a::as) (b::bs) (forall₂.cons h₁ h₂) :=
begin
by_cases p a,
{ have : q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], },
{ have : ¬ q b, { rwa [← hpq h₁] },
simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], },
end
theorem filter_map_cons (f : α → option β) (a : α) (l : list α) :
filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) :=
begin
generalize eq : f a = b,
cases b,
{ rw filter_map_cons_none _ _ eq },
{ rw filter_map_cons_some _ _ _ eq },
end
lemma rel_filter_map {f : α → option γ} {q : β → option δ} :
((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map
| f g hfg _ _ forall₂.nil := forall₂.nil
| f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) :=
by rw [filter_map_cons, filter_map_cons];
from match f a, g b, hfg h₁ with
| _, _, option.rel.none := rel_filter_map @hfg h₂
| _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂)
end
@[to_additive list.rel_sum]
lemma rel_prod [monoid α] [monoid β]
(h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod :=
assume a b, rel_foldl (assume a b, hf) h
end forall₂
/- sections -/
theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ induction L generalizing f, {cases mem_singleton.1 h, exact forall₂.nil},
simp only [sections, bind_eq_bind, mem_bind, mem_map] at h,
rcases h with ⟨_, _, _, _, rfl⟩,
simp only [*, forall₂_cons, true_and] },
{ induction h with a l f L al fL fs, {exact or.inl rfl},
simp only [sections, bind_eq_bind, mem_bind, mem_map],
exact ⟨_, fs, _, al, rfl, rfl⟩ }
end
theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L :=
forall₂_length_eq (mem_sections.1 h)
lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections
| _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil
| _ _ (forall₂.cons h₀ h₁) :=
rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀)
/- permutations -/
section permutations
@[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by rw [permutations_aux, permutations_aux.rec]
@[simp] theorem permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by rw [permutations_aux, permutations_aux.rec]; refl
end permutations
/- insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp only [insert.def, if_pos h]
@[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp only [insert.def, if_neg h]; split; refl
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l,
{ simp only [insert_of_mem h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h' },
simp only [insert_of_not_mem h', mem_cons_iff]
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
@[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by rw insert_of_mem h
@[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by rw insert_of_not_mem h; refl
end insert
/- erasep -/
section erasep
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem erasep_nil : [].erasep p = [] := rfl
theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl
@[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l :=
by simp [erasep_cons, h]
@[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p :=
by simp [erasep_cons, h]
theorem erasep_of_forall_not {l : list α}
(h : ∀ a ∈ l, ¬ p a) : l.erasep p = l :=
by induction l with _ _ ih; [refl,
simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]]
theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) :
∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
induction l with b l IH, {cases al},
by_cases pb : p b,
{ exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ },
{ rcases al with rfl | al, {exact pb.elim pa},
rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩,
h₂, by rw h₃; refl, by simp [pb, h₄]⟩ }
end
theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) :
l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
by_cases h : ∃ a ∈ l, p a,
{ rcases h with ⟨a, ha, pa⟩,
exact or.inr (exists_of_erasep ha pa) },
{ simp at h, exact or.inl (erasep_of_forall_not h) }
end
@[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) :
length (l.erasep p) = pred (length l) :=
by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩;
rw e₂; simp [-add_comm, e₁]; refl
theorem erasep_append_left {a : α} (pa : p a) :
∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : p x; simp [h'],
rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h),
rintro rfl, exact pa
end
theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1,
erasep_append_right _ (forall_mem_cons.1 h).2]
theorem erasep_sublist (l : list α) : l.erasep p <+ l :=
by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩;
[rw h, {rw [h₄, h₃], simp}]
theorem erasep_subset (l : list α) : l.erasep p ⊆ l :=
subset_of_sublist (erasep_sublist l)
theorem erasep_sublist_erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p :=
begin
induction s,
case list.sublist.slnil { refl },
case list.sublist.cons : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] },
case list.sublist.cons2 : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [s, IH.cons2 _ _ _] }
end
theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l :=
@erasep_subset _ _ _ _ _
@[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l :=
⟨mem_of_mem_erasep, λ al, begin
rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
{ rwa h },
{ rw h₄, rw h₃ at al,
have : a ≠ c, {rintro rfl, exact pa.elim h₂},
simpa [this] using al }
end⟩
theorem erasep_map (f : β → α) :
∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f))
| [] := rfl
| (b::l) := by by_cases p (f b); simp [h, erasep_map l]
@[simp] theorem extractp_eq_find_erasep :
∀ l : list α, extractp p l = (find p l, erasep p l)
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l]
end erasep
/- erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp only [erase_cons, if_pos rfl]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a :=
by simp only [erase_cons, if_neg h]; split; refl
theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) :=
by { induction l with b l, {refl},
by_cases a = b; [simp [h], simp [h, ne.symm h, *]] }
@[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h'
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩;
rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) :=
by rw erase_eq_erasep; exact length_erasep_of_mem h rfl
theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) :
(l₁++l₂).erase a = l₁.erase a ++ l₂ :=
by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h
theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) :
(l₁++l₂).erase a = l₁ ++ l₂.erase a :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right];
rintro b h' rfl; exact h h'
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
by rw erase_eq_erasep; apply erasep_sublist
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
subset_of_sublist (erase_sublist a l)
theorem erase_sublist_erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a :=
by simp [erase_eq_erasep]; exact erasep_sublist_erasep h
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by rw ab else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)]
else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)]
theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α}
(l : list α) : map f (l.erase a) = (map f l).erase (f a) :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr;
ext b; simp [finj.eq_iff]
theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ :=
by induction l₂ generalizing l₁; [refl,
simp only [foldl_cons, map_erase finj, *]]
end erase
/- diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
if h : a ∈ l₁ then by simp only [list.diff, if_pos h]
else by simp only [list.diff, if_neg h, erase_of_not_mem h]
@[simp] theorem nil_diff (l : list α) : [].diff l = [] :=
by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp only [diff_eq_foldl, foldl_append]
@[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) :=
by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁
| l₁ [] := sublist.refl _
| l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _
... <+ l₁.erase a : diff_sublist _ _
... <+ l₁ : list.erase_sublist _ _
theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ :=
subset_of_sublist $ diff_sublist _ _
theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂
| l₁ [] h₁ h₂ := h₁
| l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact
mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂)
theorem diff_sublist_of_sublist : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃
| l₁ l₂ [] h := h
| l₁ l₂ (a::l₃) h := by simp only
[diff_cons, diff_sublist_of_sublist (erase_sublist_erase _ h)]
theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α},
l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [] l₂ h := erase_sublist _ _
| (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]
else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂]
using erase_diff_erase_sublist_of_sublist (erase_sublist_erase b h)
end diff
/- zip & unzip -/
@[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) :
zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl
@[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl
@[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] :=
by cases l; refl
@[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β),
(zip l₁ l₂).map prod.swap = zip l₂ l₁
| [] l₂ := (zip_nil_right _).symm
| l₁ [] := by rw zip_nil_right; refl
| (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl
@[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β),
length (zip l₁ l₂) = min (length l₁) (length l₂)
| [] l₂ := rfl
| l₁ [] := by simp only [length, zip_nil_right, min_zero]
| (a::l₁) (b::l₂) := by by simp only [length, zip_cons_cons, length_zip l₁ l₂, min_add_add_right]
theorem zip_append : ∀ {l₁ l₂ r₁ r₂ : list α} (h : length l₁ = length l₂),
zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂
| [] l₂ r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl
| l₁ [] r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl
| (a::l₁) (b::l₂) r₁ r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ_inj h)]; split; refl
theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β),
zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g)
| [] l₂ := rfl
| l₁ [] := by simp only [map, zip_nil_right]
| (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl
theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) :
zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) :=
by rw [← zip_map, map_id]
theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) :
zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) :=
by rw [← zip_map, map_id]
theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α),
zip (l.map f) (l.map g) = l.map (λ a, (f a, g a))
| [] := rfl
| (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl
theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β},
(a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂
| (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩
| (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h]
@[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl
@[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) :
unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) :=
by rw unzip; cases unzip l; refl
theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd)
| [] := rfl
| ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l]
theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst :=
by simp only [unzip_eq_map]
theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd :=
by simp only [unzip_eq_map]
theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap :=
by simp only [unzip_eq_map, map_map]; split; refl
theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l
| [] := rfl
| ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl
theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ →
(unzip (zip l₁ l₂)).1 = l₁
| [] l₂ h := rfl
| l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl
| (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl
theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) :
(unzip (zip l₁ l₂)).2 = l₂ :=
by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h
theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) :
unzip (zip l₁ l₂) = (l₁, l₂) :=
by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)),
unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)]
@[simp] theorem length_revzip (l : list α) : length (revzip l) = length l :=
by simp only [revzip, length_zip, length_reverse, min_self]
@[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) :=
unzip_zip (length_reverse l).symm
@[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l :=
by rw [← unzip_left, unzip_revzip]
@[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse :=
by rw [← unzip_right, unzip_revzip]
theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse :=
by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip]
theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse :=
by simp [revzip]
/- enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp only [enum, enum_from_nth, zero_add]; intros; refl
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
/- product -/
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; [exact (zero_mul _).symm,
simp only [length, product_cons, length_append, IH,
right_distrib, one_mul, length_map, add_comm]]
/- sigma -/
section
variable {σ : α → Type*}
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left,
and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; [refl,
simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]]
end
/- of_fn -/
theorem length_of_fn_aux {n} (f : fin n → α) :
∀ m h l, length (of_fn_aux f m h l) = length l + m
| 0 h l := rfl
| (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _)
@[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n :=
(length_of_fn_aux f _ _ _).trans (zero_add _)
theorem nth_of_fn_aux {n} (f : fin n → α) (i) :
∀ m h l,
(∀ i, nth l i = of_fn_nth_val f (i + m)) →
nth (of_fn_aux f m h l) i = of_fn_nth_val f i
| 0 h l H := H i
| (succ m) h l H := nth_of_fn_aux m _ _ begin
intro j, cases j with j,
{ simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] },
{ simp only [nth, H, succ_add] }
end
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) :
nth (of_fn f) i = of_fn_nth_val f i :=
nth_of_fn_aux f _ _ _ _ $ λ i,
by simp only [of_fn_nth_val, dif_neg (not_lt.2 (le_add_left n i))]; refl
@[simp] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) :
nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i :=
option.some.inj $ by rw [← nth_le_nth];
simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.2]
theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read :=
suffices ∀ {m h l}, d_array.rev_iterate_aux a
(λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
simp only [d_array.rev_iterate_aux, of_fn_aux, IH]
end
theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl
theorem of_fn_succ {n} (f : fin (succ n) → α) :
of_fn f = f 0 :: of_fn (λ i, f i.succ) :=
suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l =
f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this,
begin
intros, induction m with m IH generalizing l, {refl},
rw [of_fn_aux, IH], refl
end
theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l
| [] := rfl
| (a::l) := by rw of_fn_succ; congr; simp only [fin.succ_val]; exact of_fn_nth_le l
/- disjoint -/
section disjoint
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp only [disjoint, mem_singleton, forall_eq]; refl
@[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp only [singleton_disjoint]
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint]
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ :=
(disjoint_append_right.1 d).2
end disjoint
/- union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *]
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
if h : a ∈ l₁ ∪ l₂
then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩
else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp (λ a, and.right)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_union, or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/- inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
end inter
/- bag_inter -/
section bag_inter
variable [decidable_eq α]
@[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] :=
by cases l; refl
@[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] :=
by cases l; refl
@[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) :
(a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) :=
by cases l₂; exact if_pos h
@[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) :
(a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ :=
begin
cases l₂, {simp only [bag_inter_nil]},
simp only [erase_of_not_mem h, list.bag_inter, if_neg h]
end
theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂
| [] l₂ := by simp only [nil_bag_inter, not_mem_nil, false_and]
| (b::l₁) l₂ := begin
by_cases b ∈ l₂,
{ rw [cons_bag_inter_of_pos _ h, mem_cons_iff, mem_cons_iff, mem_bag_inter],
by_cases ba : a = b,
{ simp only [ba, h, eq_self_iff_true, true_or, true_and] },
{ simp only [mem_erase_of_ne ba, ba, false_or] } },
{ rw [cons_bag_inter_of_neg _ h, mem_bag_inter, mem_cons_iff, or_and_distrib_right],
symmetry, apply or_iff_right_of_imp,
rintro ⟨rfl, h'⟩, exact h.elim h' }
end
theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁
| [] l₂ := by simp [nil_sublist]
| (b::l₁) l₂ := begin
by_cases b ∈ l₂; simp [h],
{ apply cons_sublist_cons, apply bag_inter_sublist_left },
{ apply sublist_cons_of_sublist, apply bag_inter_sublist_left }
end
end bag_inter
/- pairwise relation (generalized no duplicate) -/
section pairwise
run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pairwise_iff
variable {R : α → α → Prop}
theorem rel_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' :=
(pairwise_cons.1 p).1
theorem pairwise_of_pairwise_cons {a : α} {l : list α}
(p : pairwise R (a::l)) : pairwise R l :=
(pairwise_cons.1 p).2
theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α}
(H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l :=
begin
induction p with a l r p IH generalizing H; constructor,
{ exact ball.imp_right
(λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r },
{ exact IH (λ a b m m', H
(mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) }
end
theorem pairwise.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l :=
pairwise.imp_of_mem (λ a b _ _, H a b)
theorem pairwise.and {S : α → α → Prop} {l : list α} :
pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l :=
⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩,
λ ⟨hR, hS⟩, begin
clear_, induction hR with a l R1 R2 IH;
simp only [pairwise.nil, pairwise_cons] at *,
exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩
end⟩
theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop}
(H : ∀ a b, R a b → S a b → T a b) {l : list α}
(hR : pairwise R l) (hS : pairwise S l) : pairwise T l :=
(pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b)
theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α}
(H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l :=
⟨pairwise.imp_of_mem (λ a b m m', (H m m').1),
pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩
theorem pairwise.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l :=
pairwise.iff_of_mem (λ a b _ _, H a b)
theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l :=
by induction l; [exact pairwise.nil,
simp only [*, pairwise_cons, forall_2_true_iff, and_true]]
theorem pairwise.and_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l :=
pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt})
theorem pairwise.imp_mem {l : list α} :
pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l :=
pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt})
theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁
| ._ ._ sublist.slnil h := h
| ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n
| ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) :=
(pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i)
theorem forall_of_forall_of_pairwise (H : symmetric R)
{l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) :
∀ (x ∈ l) (y ∈ l), R x y :=
begin
induction l with a l IH, { exact forall_mem_nil _ },
cases forall_mem_cons.1 H₁ with H₁₁ H₁₂,
cases pairwise_cons.1 H₂ with H₂₁ H₂₂,
rintro x (rfl | hx) y (rfl | hy),
exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy]
end
lemma forall_of_pairwise (H : symmetric R) {l : list α}
(hl : pairwise R l) : (∀a∈l, ∀b∈l, a ≠ b → R a b) :=
forall_of_forall_of_pairwise
(λ a b h hne, H (h hne.symm))
(λ _ _ h, (h rfl).elim)
(pairwise.imp (λ _ _ h _, h) hl)
theorem pairwise_singleton (R) (a : α) : pairwise R [a] :=
by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true]
theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b :=
by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true]
theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔
pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y :=
by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append],
simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]]
theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} :
pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) :=
have ∀ l₁ l₂ : list α,
(∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) →
(∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y),
from λ l₁ l₂ a x xm y ym, s (a y ym x xm),
by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁)
theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} :
pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) :=
show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂),
by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s];
simp only [mem_append, or_comm]
theorem pairwise_map (f : β → α) :
∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l
| [] := by simp only [map, pairwise.nil]
| (b::l) :=
have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from
forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'],
by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map]
theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : pairwise S (map f l)) : pairwise R l :=
((pairwise_map f).1 p).imp H
theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : pairwise R l) : pairwise S (map f l) :=
(pairwise_map f).2 $ p.imp H
theorem pairwise_filter_map (f : β → option α) {l : list β} :
pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l :=
let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in
begin
simp only [option.mem_def], induction l with a l IH,
{ simp only [filter_map, pairwise.nil] },
cases e : f a with b,
{ rw [filter_map_cons_none _ _ e, IH, pairwise_cons],
simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] },
rw [filter_map_cons_some _ _ _ e],
simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'],
show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔
(∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l,
from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl
end
theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β)
(H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α}
(p : pairwise R l) : pairwise S (filter_map f l) :=
(pairwise_filter_map _).2 $ p.imp H
theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} :
pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l :=
begin
rw [← filter_map_eq_filter, pairwise_filter_map],
apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'],
end
theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α}
: pairwise R l → pairwise R (filter p l) :=
pairwise_of_sublist (filter_sublist _)
theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔
(∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L :=
begin
induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]},
have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔
∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y :=
⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩,
simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons],
simp only [and_assoc, and_comm, and.left_comm],
end
@[simp] theorem pairwise_reverse : ∀ {R} {l : list α},
pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l :=
suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l),
from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩,
λ R l p, by induction p with a l h p IH;
[apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH,
pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff,
pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h]
theorem pairwise_iff_nth_le {R} : ∀ {l : list α},
pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁)
| [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (not_lt_zero j).elim h
| (a::l) := begin
rw [pairwise_cons, pairwise_iff_nth_le],
refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _,
λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩,
{ cases j with j, {exact (not_lt_zero _).elim h₂},
cases i with i,
{ exact H.1 _ (nth_le_mem l _ _) },
{ exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } },
{ rcases nth_le_of_mem m with ⟨n, h, rfl⟩,
exact H _ _ (succ_lt_succ h) (succ_pos _) }
end
theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l →
pairwise (lex (swap R)) (sublists' l)
| _ pairwise.nil := pairwise_singleton _ _
| _ (@pairwise.cons _ _ a l H₁ H₂) :=
begin
simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp],
have IH := pairwise_sublists' H₂,
refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩,
intros l₁ sl₁ x l₂ sl₂ e, subst e,
cases l₁ with b l₁, {constructor},
exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _)
end
theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) :
pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) :=
by have := pairwise_sublists' (pairwise_reverse.2 H);
rwa [sublists'_reverse, pairwise_map] at this
/- pairwise reduct -/
variable [decidable_rel R]
@[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl
@[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = a :: pw_filter R l := if_pos h
@[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) :
pw_filter R (a::l) = pw_filter R l := if_neg h
theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l
| [] := nil_sublist _
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y),
{ rw [pw_filter_cons_of_pos h],
exact cons_sublist_cons _ (pw_filter_sublist l) },
{ rw [pw_filter_cons_of_neg h],
exact sublist_cons_of_sublist _ (pw_filter_sublist l) },
end
theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l :=
subset_of_sublist (pw_filter_sublist _)
theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l)
| [] := pairwise.nil
| (x::l) := begin
by_cases (∀ y ∈ pw_filter R l, R x y),
{ rw [pw_filter_cons_of_pos h],
exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ },
{ rw [pw_filter_cons_of_neg h],
exact pairwise_pw_filter l },
end
theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l :=
⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin
induction l with x l IH, {refl},
cases pairwise_cons.1 p with al p,
rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p],
end⟩
@[simp] theorem pw_filter_idempotent {l : list α} :
pw_filter R (pw_filter R l) = pw_filter R l :=
pw_filter_eq_self.mpr (pairwise_pw_filter l)
theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z)
(a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) :=
⟨begin
induction l with x l IH, { exact λ _ _, false.elim },
simp only [forall_mem_cons],
by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h,
{ simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp],
exact λ r H, ⟨r, IH H⟩ },
{ rw [pw_filter_cons_of_neg h],
refine λ H, ⟨_, IH H⟩,
cases e : find (λ y, ¬ R x y) (pw_filter R l) with k,
{ refine h.elim (ball.imp_right _ (find_eq_none.1 e)),
exact λ y _, not_not.1 },
{ have := find_some e,
exact (neg_trans (H k (find_mem e))).resolve_right this } }
end, ball.imp_left (pw_filter_subset l)⟩
end pairwise
/- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/
section chain
run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff
variable {R : α → α → Prop}
theorem rel_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : R a b :=
(chain_cons.1 p).1
theorem chain_of_chain_cons {a b : α} {l : list α}
(p : chain R a (b::l)) : chain R b l :=
(chain_cons.1 p).2
theorem chain.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l :=
by induction p with _ a b l r p IH; constructor;
[exact H _ _ r, exact IH]
theorem chain.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l :=
⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩
theorem chain.iff_mem {a : α} {l : list α} :
chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l :=
⟨λ p, by induction p with _ a b l r p IH; constructor;
[exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩,
exact IH.imp (λ a b ⟨am, bm, h⟩,
⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)],
chain.imp (λ a b h, h.2.2)⟩
theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b :=
by simp only [chain_cons, chain.nil, and_true]
theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔
chain R a (l₁++[b]) ∧ chain R b l₂ :=
by induction l₁ with x l₁ IH generalizing a;
simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc]
theorem chain_map (f : β → α) {b : β} {l : list β} :
chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l :=
by induction l generalizing b; simp only [map, chain.nil, chain_cons, *]
theorem chain_of_chain_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α}
(p : chain S (f a) (map f l)) : chain R a l :=
((chain_map f).1 p).imp H
theorem chain_map_of_chain {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α}
(p : chain R a l) : chain S (f a) (map f l) :=
(chain_map f).2 $ p.imp H
theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l :=
begin
cases pairwise_cons.1 p with r p', clear p,
induction p' with b l r' p IH generalizing a, {exact chain.nil},
simp only [chain_cons, forall_mem_cons] at r,
exact chain_cons.2 ⟨r.1, IH r'⟩
end
theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} :
chain R a l ↔ pairwise R (a::l) :=
⟨λ c, begin
induction c with b b c l r p IH, {exact pairwise_singleton _ _},
apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and],
show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)),
end, chain_of_pairwise⟩
theorem chain'.imp {S : α → α → Prop}
(H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l :=
by cases l; [trivial, exact p.imp H]
theorem chain'.iff {S : α → α → Prop}
(H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l :=
⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩
theorem chain'.iff_mem {S : α → α → Prop} : ∀ {l : list α},
chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l
| [] := iff.rfl
| (x::l) :=
⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩,
chain'.imp $ λ a b h, h.2.2⟩
theorem chain'_singleton (a : α) : chain' R [a] := chain.nil
theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔
chain' R (l₁++[a]) ∧ chain' R (a::l₂)
| [] l₂ := (and_iff_right (chain'_singleton a)).symm
| (b::l₁) l₂ := chain_split
theorem chain'_map (f : β → α) {l : list β} :
chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l :=
by cases l; [refl, exact chain_map _]
theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α}
(p : chain' S (map f l)) : chain' R l :=
((chain'_map f).1 p).imp H
theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β)
(H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α}
(p : chain' R l) : chain' S (map f l) :=
(chain'_map f).2 $ p.imp H
theorem chain'_of_pairwise : ∀ {l : list α}, pairwise R l → chain' R l
| [] _ := trivial
| (a::l) h := chain_of_pairwise h
theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α},
chain' R l ↔ pairwise R l
| [] := (iff_true_intro pairwise.nil).symm
| (a::l) := chain_iff_pairwise tr
end chain
/- no duplicates predicate -/
section nodup
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_nil : @nodup α [] := pairwise.nil
@[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l :=
by simp only [nodup, pairwise_cons, forall_mem_ne]
lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup
| _ _ forall₂.nil := by simp only [nodup_nil]
| _ _ (forall₂.cons hab h) :=
by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h)
theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton (a : α) : nodup [a] :=
nodup_cons_of_nodup (not_mem_nil a) nodup_nil
theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l :=
(nodup_cons.1 h).1
theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) :=
imp_not_comm.1 not_mem_of_nodup_cons
theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ :=
pairwise_of_sublist
theorem not_nodup_pair (a : α) : ¬ nodup [a, a] :=
not_nodup_cons_of_mem $ mem_singleton_self _
theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l :=
⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin
induction l with a l IH; intro h, {exact nodup_nil},
exact nodup_cons_of_nodup
(λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al)
(IH $ λ a s, h a $ sublist_cons_of_sublist _ s)
end⟩
theorem nodup_iff_nth_le_inj {l : list α} :
nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j :=
pairwise_iff_nth_le.trans
⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _)
.resolve_left (λ h', H _ _ h₂ h' h))
.resolve_right (λ h', H _ _ h₁ h' h.symm),
λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩
@[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n :=
nodup_iff_nth_le_inj.1 H _ _ _ h $
index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _
theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 :=
nodup_iff_sublist.trans $ forall_congr $ λ a,
have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm,
(not_congr this).trans not_lt
theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1
| 0 := by simp [nat.zero_le]
| 1 := by simp
| (n+2) := iff_of_false
(λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (le_add_left 2 n)))
(not_le_of_lt $ le_add_left 2 n)
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α}
(d : nodup l) (h : a ∈ l) : count a l = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ :=
nodup_of_sublist (sublist_append_left l₁ l₂)
theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ :=
nodup_of_sublist (sublist_append_right l₁ l₂)
theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ :=
by simp only [nodup, pairwise_append, disjoint_iff_ne]
theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ :=
(nodup_append.1 d).2.2
theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) :=
nodup_append.2 ⟨d₁, d₂, dj⟩
theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) :=
by simp only [nodup_append, and.left_comm, disjoint_comm]
theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) :=
by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right]
theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l :=
pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f
theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y)
(d : nodup l) : nodup (map f l) :=
pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d)
theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) :=
nodup_map_on (assume x _ y _ h, hf h)
theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l :=
⟨nodup_of_nodup_map _, nodup_map hf⟩
@[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l :=
⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h,
λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) :=
by rw [pmap_eq_map_attach]; exact nodup_map
(λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h)
(nodup_attach.2 h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) :=
pairwise_filter_of_pairwise p
@[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l :=
pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm]
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l :=
begin
induction d with b l m d IH, {refl},
by_cases b = a,
{ subst h, rw [erase_cons_head, filter_cons_of_neg],
symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl },
{ rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h }
end
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_sublist (erase_sublist _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp only [mem_filter, and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl
theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L :=
by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne]
theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔
(∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ :=
by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp];
rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔
(∀ (x : α), x ∈ l₁ → nodup (f x)),
from forall_swap.trans $ forall_congr $ λ_, forall_eq']
theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) :
nodup (product l₁ l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂,
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)}
(d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) :=
nodup_bind.2
⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a),
d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin
rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩,
rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩,
exact n rfl
end⟩
theorem nodup_filter_map {f : α → option β} {l : list α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup l → nodup (filter_map f l) :=
pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm'
theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) :=
by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h)
theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) :=
if h' : a ∈ l then by rw [insert_of_mem h']; exact h
else by rw [insert_of_not_mem h', nodup_cons]; split; assumption
theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) :
nodup (l₁ ∪ l₂) :=
begin
induction l₁ with a l₁ ih generalizing l₂,
{ exact h },
apply nodup_insert,
exact ih h
end
theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) :=
nodup_filter _
@[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h),
λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩
@[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l :=
by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective,
nodup_sublists, nodup_reverse]
end nodup
/- erase duplicates function -/
section erase_dup
variable [decidable_eq α]
@[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl
theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) :
erase_dup (a::l) = erase_dup l :=
pw_filter_cons_of_neg $ by simpa only [forall_mem_ne] using h
theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) :
erase_dup (a::l) = a :: erase_dup l :=
pw_filter_cons_of_pos $ by simpa only [forall_mem_ne] using h
@[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l :=
by simpa only [erase_dup, forall_mem_ne, not_not] using not_congr (@forall_mem_pw_filter α (≠) _
(λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l)
@[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) :
erase_dup (a::l) = erase_dup l :=
erase_dup_cons_of_mem' $ mem_erase_dup.2 h
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
erase_dup (a::l) = a :: erase_dup l :=
erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h
theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist
theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset
theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l :=
λ a, mem_erase_dup.2
theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter
theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self
@[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l :=
pw_filter_idempotent
theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ :=
begin
induction l₁ with a l₁ IH, {refl}, rw [cons_union, ← IH],
show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)),
by_cases a ∈ erase_dup (l₁ ++ l₂);
[ rw [erase_dup_cons_of_mem' h, insert_of_mem h],
rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]]
end
end erase_dup
/- iota and range(') -/
@[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n
| s 0 := rfl
| s (n+1) := congr_arg succ (length_range' _ _)
@[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n
| s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1
| s (succ n) :=
have m = s → m < s + n + 1,
from λ e, e ▸ lt_succ_of_le (le_add_right _ _),
have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m,
by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm,
(mem_cons_iff _ _ _).trans $ by simp only [mem_range',
or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl
theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n
| s 0 := rfl
| s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n)
theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n)
| s 0 := chain.nil
| s (n+1) := (chain_succ_range' (s+1) n).cons rfl
theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) :=
(chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _)
theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n)
| s 0 := pairwise.nil
| s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n)
theorem nodup_range' (s n : ℕ) : nodup (range' s n) :=
(pairwise_lt_range' s n).imp (λ a b, ne_of_lt)
@[simp] theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m)
| s 0 n := rfl
| s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m),
by rw [add_right_comm, range'_append]
theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n :=
⟨λ h, by simpa only [length_range'] using length_le_of_sublist h,
λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩
theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n :=
⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $
(mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2,
λ h, subset_of_sublist (range'_sublist_right.2 h)⟩
theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m)
| s 0 (n+1) _ := rfl
| s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl
theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] :=
by rw add_comm n 1; exact (range'_append s n 1).symm
theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s)
| 0 n := rfl
| (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1)
theorem range_eq_range' (n : ℕ) : range n = range' 0 n :=
(range_core_range' n 0).trans $ by rw zero_add
theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) :=
by rw [range_eq_range', range_eq_range', range',
add_comm, ← map_add_range'];
congr; exact funext one_add
theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) :=
by rw [range_eq_range', map_add_range']; refl
@[simp] theorem length_range (n : ℕ) : length (range n) = n :=
by simp only [range_eq_range', length_range']
theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) :=
by simp only [range_eq_range', pairwise_lt_range']
theorem nodup_range (n : ℕ) : nodup (range n) :=
by simp only [range_eq_range', nodup_range']
theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_sublist_right]
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n :=
by simp only [range_eq_range', range'_subset_right]
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n :=
by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add]
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n :=
mt mem_range.1 $ lt_irrefl _
theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m :=
by simp only [range_eq_range', nth_range' _ h, zero_add]
theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] :=
by simp only [range_eq_range', range'_concat, zero_add]
theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n)
| 0 := rfl
| (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl
@[simp] theorem length_iota (n : ℕ) : length (iota n) = n :=
by simp only [iota_eq_reverse_range', length_reverse, length_range']
theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) :=
by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range']
theorem nodup_iota (n : ℕ) : nodup (iota n) :=
by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range']
theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n :=
by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff]
theorem reverse_range' : ∀ s n : ℕ,
reverse (range' s n) = map (λ i, s + n - 1 - i) (range n)
| s 0 := rfl
| s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map];
simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘),
λ a i, show a - 1 - i = a - succ i, from pred_sub _ _,
reverse_singleton, map_cons, nat.sub_zero, cons_append,
nil_append, eq_self_iff_true, true_and, map_map]
using reverse_range' s n
def Ico (n m : ℕ) : list ℕ := range' n (m - n)
namespace Ico
theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) :=
by rw [Ico, Ico, map_add_range', nat.add_sub_add_right, add_comm n k]
theorem zero_bot (n : ℕ) : Ico 0 n = range n :=
by rw [Ico, nat.sub_zero, range_eq_range']
@[simp] theorem length (n m : ℕ) : length (Ico n m) = m - n :=
by dsimp [Ico]; simp only [length_range']
theorem pairwise_lt (n m : ℕ) : pairwise (<) (Ico n m) :=
by dsimp [Ico]; simp only [pairwise_lt_range']
theorem nodup (n m : ℕ) : nodup (Ico n m) :=
by dsimp [Ico]; simp only [nodup_range']
@[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m :=
suffices n ≤ l ∧ l < n + (m - n) ↔ n ≤ l ∧ l < m, by simp [Ico, this],
begin
cases le_total n m with hnm hmn,
{ rw [nat.add_sub_of_le hnm] },
{ rw [nat.sub_eq_zero_of_le hmn, add_zero],
exact and_congr_right (assume hnl, iff.intro
(assume hln, (not_le_of_gt hln hnl).elim)
(assume hlm, lt_of_lt_of_le hlm hmn)) }
end
theorem eq_nil_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = [] :=
by simp [Ico, nat.sub_eq_zero_of_le h]
@[simp] theorem self_empty {n : ℕ} : Ico n n = [] :=
eq_nil_of_le (le_refl n)
@[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = [] ↔ m ≤ n :=
iff.intro (assume h, nat.le_of_sub_eq_zero $ by rw [← length, h]; refl) eq_nil_of_le
lemma append_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) :
Ico n m ++ Ico m l = Ico n l :=
begin
dunfold Ico,
convert range'_append _ _ _,
{ exact (nat.add_sub_of_le hnm).symm },
{ rwa [← nat.add_sub_assoc hnm, nat.sub_add_cancel] }
end
@[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = [n] :=
by dsimp [Ico]; simp [nat.add_sub_cancel_left]
theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = Ico n m ++ [m] :=
by rwa [← succ_singleton, append_consecutive]; exact nat.le_succ _
theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m :=
by rw [← append_consecutive (nat.le_succ n) h, succ_singleton]; refl
theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = [m - 1] :=
by dsimp [Ico]; rw nat.sub_sub_self h; simp
theorem chain'_succ (n m : ℕ) : chain' (λa b, b = succ a) (Ico n m) :=
begin
by_cases n < m,
{ rw [eq_cons h], exact chain_succ_range' _ _ },
{ rw [eq_nil_of_le (le_of_not_gt h)], trivial }
end
@[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m :=
by simp; intros; refl
lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m :=
filter_eq_self.2 $ assume k hk, lt_of_lt_of_le (mem.1 hk).2 hml
lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = [] :=
filter_eq_nil.2 $ assume k hk, not_lt_of_le $ le_trans hln $ (mem.1 hk).1
lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l :=
begin
cases le_total n l with hnl hln,
{ rw [← append_consecutive hnl hlm, filter_append,
filter_lt_of_top_le (le_refl l), filter_lt_of_le_bot (le_refl l), append_nil] },
{ rw [eq_nil_of_le hln, filter_lt_of_le_bot hln] }
end
@[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) :=
begin
cases le_total m l with hml hlm,
{ rw [min_eq_left hml, filter_lt_of_top_le hml] },
{ rw [min_eq_right hlm, filter_lt_of_ge hlm] }
end
lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m :=
filter_eq_self.2 $ assume k hk, le_trans hln (mem.1 hk).1
lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = [] :=
filter_eq_nil.2 $ assume k hk, not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml)
lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m :=
begin
cases le_total l m with hlm hml,
{ rw [← append_consecutive hnl hlm, filter_append,
filter_ge_of_top_le (le_refl l), filter_ge_of_le_bot (le_refl l), nil_append] },
{ rw [eq_nil_of_le hml, filter_ge_of_top_le hml] }
end
@[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m :=
begin
cases le_total n l with hnl hln,
{ rw [max_eq_right hnl, filter_ge_of_ge hnl] },
{ rw [max_eq_left hln, filter_ge_of_le_bot hln] }
end
end Ico
@[simp] theorem enum_from_map_fst : ∀ n (l : list α),
map prod.fst (enum_from n l) = range' n l.length
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _)
@[simp] theorem enum_map_fst (l : list α) :
map prod.fst (enum l) = range l.length :=
by simp only [enum, enum_from_map_fst, range_eq_range']
theorem last'_mem {α} : ∀ a l, @last' α a l ∈ a :: l
| a [] := or.inl rfl
| a (b::l) := or.inr (last'_mem b l)
@[simp] lemma nth_le_attach {α} (L : list α) (i) (H : i < L.attach.length) :
(L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) :=
calc (L.attach.nth_le i H).1
= (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map'
... = L.nth_le i _ : by congr; apply attach_map_val
@[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) :
nth_le (range n) i H = i :=
option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)]
theorem of_fn_eq_pmap {α n} {f : fin n → α} :
of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) :=
by rw [pmap_eq_map_attach]; from ext_le (by simp)
(λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩])
theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) :
nodup (of_fn f) :=
by rw of_fn_eq_pmap; from nodup_pmap
(λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n)
section tfae
/- tfae: The Following (propositions) Are Equivalent -/
theorem tfae_nil : tfae [] := forall_mem_nil _
theorem tfae_singleton (p) : tfae [p] := by simp [tfae]
theorem tfae_cons_of_mem {a b} {l : list Prop} (h : b ∈ l) :
tfae (a::l) ↔ (a ↔ b) ∧ tfae l :=
⟨λ H, ⟨H a (by simp) b (or.inr h), λ p hp q hq, H _ (or.inr hp) _ (or.inr hq)⟩,
begin
rintro ⟨ab, H⟩ p (rfl | hp) q (rfl | hq),
{ refl },
{ exact ab.trans (H _ h _ hq) },
{ exact (ab.trans (H _ h _ hp)).symm },
{ exact H _ hp _ hq }
end⟩
theorem tfae_cons_cons {a b} {l : list Prop} : tfae (a::b::l) ↔ (a ↔ b) ∧ tfae (b::l) :=
tfae_cons_of_mem (or.inl rfl)
theorem tfae_of_forall (b : Prop) (l : list Prop) (h : ∀ a ∈ l, a ↔ b) : tfae l :=
λ a₁ h₁ a₂ h₂, (h _ h₁).trans (h _ h₂).symm
theorem tfae_of_cycle {a b} {l : list Prop} :
list.chain (→) a (b::l) → (last' b l → a) → tfae (a::b::l) :=
begin
induction l with c l IH generalizing a b; simp [tfae_cons_cons, tfae_singleton] at *,
{ intros a _ b, exact iff.intro a b },
intros ab bc ch la,
have := IH bc ch (ab ∘ la),
exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (last'_mem _ _)).1 ∘ bc⟩, this⟩
end
theorem tfae.out {l} (h : tfae l) (n₁ n₂)
(h₁ : n₁ < list.length l . tactic.exact_dec_trivial)
(h₂ : n₂ < list.length l . tactic.exact_dec_trivial) :
list.nth_le l n₁ h₁ ↔ list.nth_le l n₂ h₂ :=
h _ (list.nth_le_mem _ _ _) _ (list.nth_le_mem _ _ _)
end tfae
lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n :=
by simp [rotate]
@[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; refl
@[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate]
@[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl
@[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl
lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) :
(a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate']
@[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length
| [] n := rfl
| (a::l) 0 := rfl
| (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp
lemma rotate'_eq_take_append_drop : ∀ {l : list α} {n : ℕ}, n ≤ l.length →
l.rotate' n = l.drop n ++ l.take n
| [] n h := by simp [drop_append_of_le_length h]
| l 0 h := by simp [take_append_of_le_length h]
| (a::l) (n+1) h :=
have hnl : n ≤ l.length, from le_of_succ_le_succ h,
have hnl' : n ≤ (l ++ [a]).length,
by rw [length_append, length_cons, list.length, zero_add];
exact (le_of_succ_le h),
by rw [rotate'_cons_succ, rotate'_eq_take_append_drop hnl', drop, take,
drop_append_of_le_length hnl, take_append_of_le_length hnl];
simp
lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m)
| (a::l) 0 m := by simp
| [] n m := by simp
| (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ]
@[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l :=
by rw rotate'_eq_take_append_drop (le_refl _); simp
@[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l
| 0 := by simp
| (n+1) :=
calc l.rotate' (l.length * (n + 1)) =
(l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length :
by simp [-rotate'_length, nat.mul_succ, rotate'_rotate']
... = l : by rw [rotate'_length, rotate'_length_mul]
lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n :=
calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate'
((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul
... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div]
lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n :=
if h : l.length = 0 then by simp [length_eq_zero, *] at *
else by
rw [← rotate'_mod, rotate'_eq_take_append_drop (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))];
simp [rotate]
lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) :
(a :: l : list α).rotate n.succ = (l ++ [a]).rotate n :=
by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ]
@[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l
| [] _ n := by simp
| (a::l) _ 0 := by simp
| (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm]
@[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length :=
by rw [rotate_eq_rotate', length_rotate']
lemma rotate_eq_take_append_drop {l : list α} {n : ℕ} : n ≤ l.length →
l.rotate n = l.drop n ++ l.take n :=
by rw rotate_eq_rotate'; exact rotate'_eq_take_append_drop
lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) :=
by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate']
@[simp] lemma rotate_length (l : list α) : rotate l l.length = l :=
by rw [rotate_eq_rotate', rotate'_length]
@[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l :=
by rw [rotate_eq_rotate', rotate'_length_mul]
lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ),
(l.rotate n).prod = 1
| [] _ _ := by simp
| (a::l) hl n :=
have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial),
by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl;
rw [← rotate_mod, rotate_eq_take_append_drop this, list.prod_append, mul_eq_one_iff_inv_eq,
← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one]
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
end list
theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup
| none := list.nodup_nil
| (some x) := list.nodup_singleton x
|
d7223592a07a6548cb6b3b2e5cc2e603f3ef08ba | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/category/Group/limits.lean | 7b726cfc1cd1baca776591b9fa821a86082527fa | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 12,530 | 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.Mon.limits
import algebra.category.Group.preadditive
import category_theory.over
import group_theory.subgroup.basic
import category_theory.concrete_category.elementwise
/-!
# The category of (commutative) (additive) groups has all limits
Further, these limits are preserved by the forgetful functor --- that is,
the underlying types are just the limits in the category of types.
-/
open category_theory
open category_theory.limits
universes v u
noncomputable theory
variables {J : Type v} [small_category J]
namespace Group
@[to_additive]
instance group_obj (F : J ⥤ Group.{max v u}) (j) :
group ((F ⋙ forget Group).obj j) :=
by { change group (F.obj j), apply_instance }
/--
The flat sections of a functor into `Group` form a subgroup of all sections.
-/
@[to_additive
"The flat sections of a functor into `AddGroup` form an additive subgroup of all sections."]
def sections_subgroup (F : J ⥤ Group) :
subgroup (Π j, F.obj j) :=
{ carrier := (F ⋙ forget Group).sections,
inv_mem' := λ a ah j j' f,
begin
simp only [forget_map_eq_coe, functor.comp_map, pi.inv_apply, monoid_hom.map_inv, inv_inj],
dsimp [functor.sections] at ah,
rw ah f,
end,
..(Mon.sections_submonoid (F ⋙ forget₂ Group Mon)) }
@[to_additive]
instance limit_group (F : J ⥤ Group.{max v u}) :
group (types.limit_cone (F ⋙ forget Group)).X :=
begin
change group (sections_subgroup F),
apply_instance,
end
/-- We show that the forgetful functor `Group ⥤ Mon` creates limits.
All we need to do is notice that the limit point has a `group` instance available, and then reuse
the existing limit. -/
@[to_additive "We show that the forgetful functor `AddGroup ⥤ AddMon` creates limits.
All we need to do is notice that the limit point has an `add_group` instance available, and then
reuse the existing limit."]
instance forget₂.creates_limit (F : J ⥤ Group.{max v u}) :
creates_limit F (forget₂ Group.{max v u} Mon.{max v u}) :=
creates_limit_of_reflects_iso (λ c' t,
{ lifted_cone :=
{ X := Group.of (types.limit_cone (F ⋙ forget Group)).X,
π :=
{ app := Mon.limit_π_monoid_hom (F ⋙ forget₂ Group Mon.{max v u}),
naturality' :=
(Mon.has_limits.limit_cone (F ⋙ forget₂ Group Mon.{max v u})).π.naturality, } },
valid_lift := by apply is_limit.unique_up_to_iso (Mon.has_limits.limit_cone_is_limit _) t,
makes_limit := is_limit.of_faithful (forget₂ Group Mon.{max v u})
(Mon.has_limits.limit_cone_is_limit _) (λ s, _) (λ s, rfl) })
/--
A choice of limit cone for a functor into `Group`.
(Generally, you'll just want to use `limit F`.)
-/
@[to_additive "A choice of limit cone for a functor into `Group`.
(Generally, you'll just want to use `limit F`.)"]
def limit_cone (F : J ⥤ Group.{max v u}) : cone F :=
lift_limit (limit.is_limit (F ⋙ (forget₂ Group Mon.{max v u})))
/--
The chosen cone is a limit cone.
(Generally, you'll just want to use `limit.cone F`.)
-/
@[to_additive "The chosen cone is a limit cone.
(Generally, you'll just want to use `limit.cone F`.)"]
def limit_cone_is_limit (F : J ⥤ Group.{max v u}) : is_limit (limit_cone F) :=
lifted_limit_is_limit _
/-- The category of groups has all limits. -/
@[to_additive "The category of additive groups has all limits."]
instance has_limits_of_size : has_limits_of_size.{v v} Group.{max v u} :=
{ has_limits_of_shape := λ J 𝒥, by exactI
{ has_limit := λ F, has_limit_of_created F (forget₂ Group Mon.{max v u}) } }
@[to_additive]
instance has_limits : has_limits Group.{u} := Group.has_limits_of_size.{u u}
/-- The forgetful functor from groups to monoids preserves all limits.
This means the underlying monoid of a limit can be computed as a limit in the category of monoids.
-/
@[to_additive AddGroup.forget₂_AddMon_preserves_limits "The forgetful functor from additive groups
to additive monoids preserves all limits.
This means the underlying additive monoid of a limit can be computed as a limit in the category of
additive monoids."]
instance forget₂_Mon_preserves_limits_of_size :
preserves_limits_of_size.{v v} (forget₂ Group Mon.{max v u}) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F, by apply_instance } }
@[to_additive]
instance forget₂_Mon_preserves_limits : preserves_limits (forget₂ Group Mon.{u}) :=
Group.forget₂_Mon_preserves_limits_of_size.{u u}
/-- The forgetful functor from groups to types preserves all limits.
This means the underlying type of a limit can be computed as a limit in the category of types. -/
@[to_additive "The forgetful functor from additive groups to types preserves all limits.
This means the underlying type of a limit can be computed as a limit in the category of types."]
instance forget_preserves_limits_of_size :
preserves_limits_of_size.{v v} (forget Group.{max v u}) :=
{ preserves_limits_of_shape := λ J 𝒥, by exactI
{ preserves_limit := λ F, limits.comp_preserves_limit (forget₂ Group Mon) (forget Mon) } }
@[to_additive]
instance forget_preserves_limits : preserves_limits (forget Group.{u}) :=
Group.forget_preserves_limits_of_size.{u u}
end Group
namespace CommGroup
@[to_additive]
instance comm_group_obj (F : J ⥤ CommGroup.{max v u}) (j) :
comm_group ((F ⋙ forget CommGroup).obj j) :=
by { change comm_group (F.obj j), apply_instance }
@[to_additive]
instance limit_comm_group (F : J ⥤ CommGroup.{max v u}) :
comm_group (types.limit_cone (F ⋙ forget CommGroup.{max v u})).X :=
@subgroup.to_comm_group (Π j, F.obj j) _
(Group.sections_subgroup (F ⋙ forget₂ CommGroup Group.{max v u}))
/--
We show that the forgetful functor `CommGroup ⥤ Group` creates limits.
All we need to do is notice that the limit point has a `comm_group` instance available,
and then reuse the existing limit.
-/
@[to_additive "We show that the forgetful functor `AddCommGroup ⥤ AddGroup` creates limits.
All we need to do is notice that the limit point has an `add_comm_group` instance available, and
then reuse the existing limit."]
instance forget₂.creates_limit (F : J ⥤ CommGroup.{max v u}) :
creates_limit F (forget₂ CommGroup Group.{max v u}) :=
creates_limit_of_reflects_iso (λ c' t,
{ lifted_cone :=
{ X := CommGroup.of (types.limit_cone (F ⋙ forget CommGroup)).X,
π :=
{ app := Mon.limit_π_monoid_hom
(F ⋙ forget₂ CommGroup Group.{max v u} ⋙ forget₂ Group Mon.{max v u}),
naturality' := (Mon.has_limits.limit_cone _).π.naturality, } },
valid_lift := by apply is_limit.unique_up_to_iso (Group.limit_cone_is_limit _) t,
makes_limit := is_limit.of_faithful (forget₂ _ Group.{max v u} ⋙ forget₂ _ Mon.{max v u})
(by apply Mon.has_limits.limit_cone_is_limit _) (λ s, _) (λ s, rfl) })
/--
A choice of limit cone for a functor into `CommGroup`.
(Generally, you'll just want to use `limit F`.)
-/
@[to_additive "A choice of limit cone for a functor into `CommGroup`.
(Generally, you'll just want to use `limit F`.)"]
def limit_cone (F : J ⥤ CommGroup.{max v u}) : cone F :=
lift_limit (limit.is_limit (F ⋙ (forget₂ CommGroup Group.{max v u})))
/--
The chosen cone is a limit cone.
(Generally, you'll just want to use `limit.cone F`.)
-/
@[to_additive "The chosen cone is a limit cone.
(Generally, you'll just wantto use `limit.cone F`.)"]
def limit_cone_is_limit (F : J ⥤ CommGroup.{max v u}) : is_limit (limit_cone F) :=
lifted_limit_is_limit _
/-- The category of commutative groups has all limits. -/
@[to_additive "The category of additive commutative groups has all limits."]
instance has_limits_of_size : has_limits_of_size.{v v} CommGroup.{max v u} :=
{ has_limits_of_shape := λ J 𝒥, by exactI
{ has_limit := λ F, has_limit_of_created F (forget₂ CommGroup Group.{max v u}) } }
@[to_additive]
instance has_limits : has_limits CommGroup.{u} := CommGroup.has_limits_of_size.{u u}
/--
The forgetful functor from commutative groups to groups preserves all limits.
(That is, the underlying group could have been computed instead as limits in the category
of groups.)
-/
@[to_additive AddCommGroup.forget₂_AddGroup_preserves_limits
"The forgetful functor from additive commutative groups to groups preserves all limits.
(That is, the underlying group could have been computed instead as limits in the category
of additive groups.)"]
instance forget₂_Group_preserves_limits_of_size :
preserves_limits_of_size.{v v} (forget₂ CommGroup Group.{max v u}) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F, by apply_instance } }
@[to_additive]
instance forget₂_Group_preserves_limits : preserves_limits (forget₂ CommGroup Group.{u}) :=
CommGroup.forget₂_Group_preserves_limits_of_size.{u u}
/--
An auxiliary declaration to speed up typechecking.
-/
@[to_additive AddCommGroup.forget₂_AddCommMon_preserves_limits_aux
"An auxiliary declaration to speed up typechecking."]
def forget₂_CommMon_preserves_limits_aux (F : J ⥤ CommGroup.{max v u}) :
is_limit ((forget₂ CommGroup CommMon).map_cone (limit_cone F)) :=
CommMon.limit_cone_is_limit (F ⋙ forget₂ CommGroup CommMon)
/--
The forgetful functor from commutative groups to commutative monoids preserves all limits.
(That is, the underlying commutative monoids could have been computed instead as limits
in the category of commutative monoids.)
-/
@[to_additive AddCommGroup.forget₂_AddCommMon_preserves_limits
"The forgetful functor from additive commutative groups to additive commutative monoids preserves
all limits. (That is, the underlying additive commutative monoids could have been computed instead
as limits in the category of additive commutative monoids.)"]
instance forget₂_CommMon_preserves_limits_of_size :
preserves_limits_of_size.{v v} (forget₂ CommGroup CommMon.{max v u}) :=
{ preserves_limits_of_shape := λ J 𝒥, by exactI
{ preserves_limit := λ F, preserves_limit_of_preserves_limit_cone
(limit_cone_is_limit F) (forget₂_CommMon_preserves_limits_aux F) } }
/--
The forgetful functor from commutative groups to types preserves all limits. (That is, the
underlying types could have been computed instead as limits in the category of types.)
-/
@[to_additive AddCommGroup.forget_preserves_limits
"The forgetful functor from additive commutative groups to types preserves all limits. (That is,
the underlying types could have been computed instead as limits in the category of types.)"]
instance forget_preserves_limits_of_size :
preserves_limits_of_size.{v v} (forget CommGroup.{max v u}) :=
{ preserves_limits_of_shape := λ J 𝒥, by exactI
{ preserves_limit := λ F, limits.comp_preserves_limit (forget₂ CommGroup Group) (forget Group) } }
-- Verify we can form limits indexed over smaller categories.
example (f : ℕ → AddCommGroup) : has_product f := by apply_instance
end CommGroup
namespace AddCommGroup
/--
The categorical kernel of a morphism in `AddCommGroup`
agrees with the usual group-theoretical kernel.
-/
def kernel_iso_ker {G H : AddCommGroup.{u}} (f : G ⟶ H) :
kernel f ≅ AddCommGroup.of f.ker :=
{ hom :=
{ to_fun := λ g, ⟨kernel.ι f g,
begin
-- TODO where is this `has_coe_t_aux.coe` coming from? can we prevent it appearing?
change (kernel.ι f) g ∈ f.ker,
simp [add_monoid_hom.mem_ker],
end⟩,
map_zero' := by { ext, simp, },
map_add' := λ g g', by { ext, simp, }, },
inv := kernel.lift f (add_subgroup.subtype f.ker) (by tidy),
hom_inv_id' := by { apply equalizer.hom_ext _, ext, simp, },
inv_hom_id' :=
begin
apply AddCommGroup.ext,
simp only [add_monoid_hom.coe_mk, coe_id, coe_comp],
rintro ⟨x, mem⟩,
simp,
end, }.
@[simp]
lemma kernel_iso_ker_hom_comp_subtype {G H : AddCommGroup} (f : G ⟶ H) :
(kernel_iso_ker f).hom ≫ add_subgroup.subtype f.ker = kernel.ι f :=
by ext; refl
@[simp]
lemma kernel_iso_ker_inv_comp_ι {G H : AddCommGroup} (f : G ⟶ H) :
(kernel_iso_ker f).inv ≫ kernel.ι f = add_subgroup.subtype f.ker :=
begin
ext,
simp [kernel_iso_ker],
end
/--
The categorical kernel inclusion for `f : G ⟶ H`, as an object over `G`,
agrees with the `subtype` map.
-/
@[simps]
def kernel_iso_ker_over {G H : AddCommGroup.{u}} (f : G ⟶ H) :
over.mk (kernel.ι f) ≅ @over.mk _ _ G (AddCommGroup.of f.ker) (add_subgroup.subtype f.ker) :=
over.iso_mk (kernel_iso_ker f) (by simp)
end AddCommGroup
|
d215415f3fd24046fd610c6c0d95f6cf46f5d3c2 | 3c9dc4ea6cc92e02634ef557110bde9eae393338 | /stage0/src/Init/Prelude.lean | b38de8f03993519774ed87867abb2ec0642da796 | [
"Apache-2.0"
] | permissive | shingtaklam1324/lean4 | 3d7efe0c8743a4e33d3c6f4adbe1300df2e71492 | 351285a2e8ad0cef37af05851cfabf31edfb5970 | refs/heads/master | 1,676,827,679,740 | 1,610,462,623,000 | 1,610,552,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 70,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
-/
prelude
universes u v w
@[inline] def id {α : Sort u} (a : α) : α := a
/-
The kernel definitional equality test (t =?= s) has special support for idDelta applications.
It implements the following rules
1) (idDelta t) =?= t
2) t =?= (idDelta t)
3) (idDelta t) =?= s IF (unfoldOf t) =?= s
4) t =?= idDelta s IF t =?= (unfoldOf s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use idDelta applications to address performance problems when Type checking
theorems generated by the equation Compiler.
-/
@[inline] def idDelta {α : Sort u} (a : α) : α := a
/- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/
@[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a
abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ :=
fun x => f (g x)
abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α :=
fun x => a
@[reducible] def inferInstance {α : Type u} [i : α] : α := i
@[reducible] def inferInstanceAs (α : Type u) [i : α] : α := i
set_option bootstrap.inductiveCheckResultingUniverse false in
inductive PUnit : Sort u where
| unit : PUnit
/-- An abbreviation for `PUnit.{0}`, its most common instantiation.
This Type should be preferred over `PUnit` where possible to avoid
unnecessary universe parameters. -/
abbrev Unit : Type := PUnit
@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit
/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/
unsafe axiom lcProof {α : Prop} : α
/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/
unsafe axiom lcUnreachable {α : Sort u} : α
inductive True : Prop where
| intro : True
inductive False : Prop
inductive Empty : Type
def Not (a : Prop) : Prop := a → False
@[macroInline] def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
@[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b :=
False.elim (h₂ h₁)
inductive Eq {α : Sort u} (a : α) : α → Prop where
| refl {} : Eq a a
abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b :=
Eq.rec (motive := fun α _ => motive α) m h
@[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a
theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b :=
Eq.ndrec h₂ h₁
theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a :=
h ▸ rfl
@[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β :=
Eq.rec (motive := fun α _ => α) a h
theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) :=
h ▸ rfl
/-
Initialize the Quotient Module, which effectively adds the following definitions:
constant Quot {α : Sort u} (r : α → α → Prop) : Sort u
constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r
constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β
constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :
(∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q
-/
init_quot
inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where
| refl {} : HEq a a
@[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a :=
HEq.refl a
theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' :=
have (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b from
fun α β a b h₁ =>
HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b)
(fun (h₂ : Eq α α) => rfl)
h₁
this α α a a' h rfl
structure Prod (α : Type u) (β : Type v) where
fst : α
snd : β
attribute [unbox] Prod
/-- Similar to `Prod`, but `α` and `β` can be propositions.
We use this Type internally to automatically generate the brecOn recursor. -/
structure PProd (α : Sort u) (β : Sort v) where
fst : α
snd : β
/-- Similar to `Prod`, but `α` and `β` are in the same universe. -/
structure MProd (α β : Type u) where
fst : α
snd : β
structure And (a b : Prop) : Prop where
intro :: (left : a) (right : b)
inductive Or (a b : Prop) : Prop where
| inl (h : a) : Or a b
| inr (h : b) : Or a b
inductive Bool : Type where
| false : Bool
| true : Bool
export Bool (false true)
/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/
structure Subtype {α : Sort u} (p : α → Prop) where
val : α
property : p val
/-- Gadget for optional parameter support. -/
@[reducible] def optParam (α : Sort u) (default : α) : Sort u := α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def outParam (α : Sort u) : Sort u := α
/-- Auxiliary Declaration used to implement the notation (a : α) -/
@[reducible] def typedExpr (α : Sort u) (a : α) : α := a
/-- Auxiliary Declaration used to implement the named patterns `x@p` -/
@[reducible] def namedPattern {α : Sort u} (x a : α) : α := a
/- Auxiliary axiom used to implement `sorry`. -/
axiom sorryAx (α : Sort u) (synthetic := true) : α
theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false
| true, h => False.elim (h rfl)
| false, h => rfl
theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true
| true, h => rfl
| false, h => False.elim (h rfl)
theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false)
| true, _ => fun h => Bool.noConfusion h
| false, h => Bool.noConfusion h
theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true)
| true, h => Bool.noConfusion h
| false, _ => fun h => Bool.noConfusion h
class Inhabited (α : Sort u) where
mk {} :: (default : α)
constant arbitrary [Inhabited α] : α :=
Inhabited.default
instance : Inhabited (Sort u) where
default := PUnit
instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where
default := fun _ => arbitrary
instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where
default := fun _ => arbitrary
/-- Universe lifting operation from Sort to Type -/
structure PLift (α : Sort u) : Type u where
up :: (down : α)
/- Bijection between α and PLift α -/
theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b
| up a => rfl
theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a :=
rfl
/- Pointed types -/
structure PointedType where
(type : Type u)
(val : type)
instance : Inhabited PointedType.{u} where
default := { type := PUnit.{u+1}, val := ⟨⟩ }
/-- Universe lifting operation -/
structure ULift.{r, s} (α : Type s) : Type (max s r) where
up :: (down : α)
/- Bijection between α and ULift.{v} α -/
theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b
| up a => rfl
theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a :=
rfl
class inductive Decidable (p : Prop) where
| isFalse (h : Not p) : Decidable p
| isTrue (h : p) : Decidable p
@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=
Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true)
export Decidable (isTrue isFalse decide)
abbrev DecidablePred {α : Sort u} (r : α → Prop) :=
(a : α) → Decidable (r a)
abbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=
(a b : α) → Decidable (r a b)
abbrev DecidableEq (α : Sort u) :=
(a b : α) → Decidable (Eq a b)
def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) :=
s a b
theorem decideEqTrue : {p : Prop} → [s : Decidable p] → p → Eq (decide p) true
| _, isTrue _, _ => rfl
| _, isFalse h₁, h₂ => absurd h₂ h₁
theorem decideEqFalse : {p : Prop} → [s : Decidable p] → Not p → Eq (decide p) false
| _, isTrue h₁, h₂ => absurd h₁ h₂
| _, isFalse h, _ => rfl
theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : Eq (decide p) true → p := fun h =>
match s with
| isTrue h₁ => h₁
| isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁))
theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : Eq (decide p) false → Not p := fun h =>
match s with
| isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁))
| isFalse h₁ => h₁
@[inline] instance : DecidableEq Bool :=
fun a b => match a, b with
| false, false => isTrue rfl
| false, true => isFalse (fun h => Bool.noConfusion h)
| true, false => isFalse (fun h => Bool.noConfusion h)
| true, true => isTrue rfl
class BEq (α : Type u) where
beq : α → α → Bool
open BEq (beq)
instance {α : Type u} [DecidableEq α] : BEq α where
beq a b := decide (Eq a b)
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
@[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α :=
Decidable.casesOn (motive := fun _ => α) h e t
/- if-then-else -/
@[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α :=
Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t)
@[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) :=
match dp with
| isTrue hp =>
match dq with
| isTrue hq => isTrue ⟨hp, hq⟩
| isFalse hq => isFalse (fun h => hq (And.right h))
| isFalse hp =>
isFalse (fun h => hp (And.left h))
@[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) :=
match dp with
| isTrue hp => isTrue (Or.inl hp)
| isFalse hp =>
match dq with
| isTrue hq => isTrue (Or.inr hq)
| isFalse hq =>
isFalse fun h => match h with
| Or.inl h => hp h
| Or.inr h => hq h
instance {p} [dp : Decidable p] : Decidable (Not p) :=
match dp with
| isTrue hp => isFalse (absurd hp)
| isFalse hp => isTrue hp
/- Boolean operators -/
@[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α :=
match c with
| true => x
| false => y
@[macroInline] def or (x y : Bool) : Bool :=
match x with
| true => true
| false => y
@[macroInline] def and (x y : Bool) : Bool :=
match x with
| false => false
| true => y
@[inline] def not : Bool → Bool
| true => false
| false => true
inductive Nat where
| zero : Nat
| succ (n : Nat) : Nat
instance : Inhabited Nat where
default := Nat.zero
/- For numeric literals notation -/
class OfNat (α : Type u) (n : Nat) where
ofNat : α
@[defaultInstance 100] /- low prio -/
instance (n : Nat) : OfNat Nat n where
ofNat := n
class HasLessEq (α : Type u) where LessEq : α → α → Prop
class HasLess (α : Type u) where Less : α → α → Prop
export HasLess (Less)
export HasLessEq (LessEq)
class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAdd : α → β → γ
class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hSub : α → β → γ
class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hMul : α → β → γ
class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hDiv : α → β → γ
class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hMod : α → β → γ
class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hPow : α → β → γ
class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAppend : α → β → γ
class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hOrElse : α → β → γ
class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where
hAndThen : α → β → γ
class Add (α : Type u) where
add : α → α → α
class Sub (α : Type u) where
sub : α → α → α
class Mul (α : Type u) where
mul : α → α → α
class Neg (α : Type u) where
neg : α → α
class Div (α : Type u) where
div : α → α → α
class Mod (α : Type u) where
mod : α → α → α
class Pow (α : Type u) where
pow : α → α → α
class Append (α : Type u) where
append : α → α → α
class OrElse (α : Type u) where
orElse : α → α → α
class AndThen (α : Type u) where
andThen : α → α → α
@[defaultInstance]
instance [Add α] : HAdd α α α where
hAdd a b := Add.add a b
@[defaultInstance]
instance [Sub α] : HSub α α α where
hSub a b := Sub.sub a b
@[defaultInstance]
instance [Mul α] : HMul α α α where
hMul a b := Mul.mul a b
@[defaultInstance]
instance [Div α] : HDiv α α α where
hDiv a b := Div.div a b
@[defaultInstance]
instance [Mod α] : HMod α α α where
hMod a b := Mod.mod a b
@[defaultInstance]
instance [Pow α] : HPow α α α where
hPow a b := Pow.pow a b
@[defaultInstance]
instance [Append α] : HAppend α α α where
hAppend a b := Append.append a b
@[defaultInstance]
instance [OrElse α] : HOrElse α α α where
hOrElse a b := OrElse.orElse a b
@[defaultInstance]
instance [AndThen α] : HAndThen α α α where
hAndThen a b := AndThen.andThen a b
open HAdd (hAdd)
open HMul (hMul)
open HPow (hPow)
open HAppend (hAppend)
@[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := LessEq b a
@[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := Less b a
set_option bootstrap.gen_matcher_code false in
@[extern "lean_nat_add"]
protected def Nat.add : (@& Nat) → (@& Nat) → Nat
| a, Nat.zero => a
| a, Nat.succ b => Nat.succ (Nat.add a b)
instance : Add Nat where
add := Nat.add
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation Compiler. -/
attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg
set_option bootstrap.gen_matcher_code false in
@[extern "lean_nat_mul"]
protected def Nat.mul : (@& Nat) → (@& Nat) → Nat
| a, 0 => 0
| a, Nat.succ b => Nat.add (Nat.mul a b) a
instance : Mul Nat where
mul := Nat.mul
set_option bootstrap.gen_matcher_code false in
@[extern "lean_nat_pow"]
protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat
| 0 => 1
| succ n => Nat.mul (Nat.pow m n) m
instance : Pow Nat where
pow := Nat.pow
set_option bootstrap.gen_matcher_code false in
@[extern "lean_nat_dec_eq"]
def Nat.beq : Nat → Nat → Bool
| zero, zero => true
| zero, succ m => false
| succ n, zero => false
| succ n, succ m => beq n m
theorem Nat.eqOfBeqEqTrue : {n m : Nat} → Eq (beq n m) true → Eq n m
| zero, zero, h => rfl
| zero, succ m, h => Bool.noConfusion h
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h =>
have Eq (beq n m) true from h
have Eq n m from eqOfBeqEqTrue this
this ▸ rfl
theorem Nat.neOfBeqEqFalse : {n m : Nat} → Eq (beq n m) false → Not (Eq n m)
| zero, zero, h₁, h₂ => Bool.noConfusion h₁
| zero, succ m, h₁, h₂ => Nat.noConfusion h₂
| succ n, zero, h₁, h₂ => Nat.noConfusion h₂
| succ n, succ m, h₁, h₂ =>
have Eq (beq n m) false from h₁
Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFalse this))
@[extern "lean_nat_dec_eq"]
protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) :=
match h:beq n m with
| true => isTrue (eqOfBeqEqTrue h)
| false => isFalse (neOfBeqEqFalse h)
@[inline] instance : DecidableEq Nat := Nat.decEq
set_option bootstrap.gen_matcher_code false in
@[extern "lean_nat_dec_le"]
def Nat.ble : Nat → Nat → Bool
| zero, zero => true
| zero, succ m => true
| succ n, zero => false
| succ n, succ m => ble n m
protected def Nat.le (n m : Nat) : Prop :=
Eq (ble n m) true
instance : HasLessEq Nat where
LessEq := Nat.le
protected def Nat.lt (n m : Nat) : Prop :=
Nat.le (succ n) m
instance : HasLess Nat where
Less := Nat.lt
theorem Nat.notSuccLeZero : ∀ (n : Nat), LessEq (succ n) 0 → False
| 0, h => nomatch h
| succ n, h => nomatch h
theorem Nat.notLtZero (n : Nat) : Not (Less n 0) :=
notSuccLeZero n
@[extern "lean_nat_dec_le"]
instance Nat.decLe (n m : @& Nat) : Decidable (LessEq n m) :=
decEq (Nat.ble n m) true
@[extern "lean_nat_dec_lt"]
instance Nat.decLt (n m : @& Nat) : Decidable (Less n m) :=
decLe (succ n) m
theorem Nat.zeroLe : (n : Nat) → LessEq 0 n
| zero => rfl
| succ n => rfl
theorem Nat.succLeSucc {n m : Nat} (h : LessEq n m) : LessEq (succ n) (succ m) :=
h
theorem Nat.zeroLtSucc (n : Nat) : Less 0 (succ n) :=
succLeSucc (zeroLe n)
theorem Nat.leStep : {n m : Nat} → LessEq n m → LessEq n (succ m)
| zero, zero, h => rfl
| zero, succ n, h => rfl
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h =>
have LessEq n m from h
have LessEq n (succ m) from leStep this
succLeSucc this
set_option pp.raw true
protected theorem Nat.leTrans : {n m k : Nat} → LessEq n m → LessEq m k → LessEq n k
| zero, m, k, h₁, h₂ => zeroLe _
| succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁
| succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂
| succ n, succ m, succ k, h₁, h₂ =>
have h₁' : LessEq n m from h₁
have h₂' : LessEq m k from h₂
show LessEq n k from
Nat.leTrans h₁' h₂'
protected theorem Nat.ltTrans {n m k : Nat} (h₁ : Less n m) : Less m k → Less n k :=
Nat.leTrans (leStep h₁)
theorem Nat.leSucc : (n : Nat) → LessEq n (succ n)
| zero => rfl
| succ n => leSucc n
theorem Nat.leSuccOfLe {n m : Nat} (h : LessEq n m) : LessEq n (succ m) :=
Nat.leTrans h (leSucc m)
protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LessEq n m → Or (Eq n m) (Less n m)
| zero, zero, h => Or.inl rfl
| zero, succ n, h => Or.inr (zeroLe n)
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h =>
have LessEq n m from h
match Nat.eqOrLtOfLe this with
| Or.inl h => Or.inl (h ▸ rfl)
| Or.inr h => Or.inr (succLeSucc h)
protected def Nat.leRefl : (n : Nat) → LessEq n n
| zero => rfl
| succ n => Nat.leRefl n
protected theorem Nat.ltOrGe (n m : Nat) : Or (Less n m) (GreaterEq n m) :=
match m with
| zero => Or.inr (zeroLe n)
| succ m =>
match Nat.ltOrGe n m with
| Or.inl h => Or.inl (leSuccOfLe h)
| Or.inr h =>
match Nat.eqOrLtOfLe h with
| Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _)
| Or.inr h1 => Or.inr h1
protected theorem Nat.leAntisymm : {n m : Nat} → LessEq n m → LessEq m n → Eq n m
| zero, zero, h₁, h₂ => rfl
| succ n, zero, h₁, h₂ => Bool.noConfusion h₁
| zero, succ m, h₁, h₂ => Bool.noConfusion h₂
| succ n, succ m, h₁, h₂ =>
have h₁' : LessEq n m from h₁
have h₂' : LessEq m n from h₂
(Nat.leAntisymm h₁' h₂') ▸ rfl
protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LessEq n m) (h₂ : Not (Eq n m)) : Less n m :=
match Nat.ltOrGe n m with
| Or.inl h₃ => h₃
| Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂
set_option bootstrap.gen_matcher_code false in
@[extern c inline "lean_nat_sub(#1, lean_box(1))"]
def Nat.pred : Nat → Nat
| 0 => 0
| succ a => a
set_option bootstrap.gen_matcher_code false in
@[extern "lean_nat_sub"]
protected def Nat.sub : (@& Nat) → (@& Nat) → Nat
| a, 0 => a
| a, succ b => pred (Nat.sub a b)
instance : Sub Nat where
sub := Nat.sub
theorem Nat.predLePred : {n m : Nat} → LessEq n m → LessEq (pred n) (pred m)
| zero, zero, h => rfl
| zero, succ n, h => zeroLe n
| succ n, zero, h => Bool.noConfusion h
| succ n, succ m, h => h
theorem Nat.leOfSuccLeSucc {n m : Nat} : LessEq (succ n) (succ m) → LessEq n m :=
predLePred
theorem Nat.leOfLtSucc {m n : Nat} : Less m (succ n) → LessEq m n :=
leOfSuccLeSucc
@[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) :=
fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant
def System.Platform.numBits : Nat :=
(getNumBits ()).val
theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) :=
(getNumBits ()).property
structure Fin (n : Nat) where
val : Nat
isLt : Less val n
theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j
| ⟨v, h⟩, ⟨_, _⟩, rfl => rfl
theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val :=
h ▸ rfl
theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) :=
fun h' => absurd (veqOfEq h') h
instance (n : Nat) : DecidableEq (Fin n) :=
fun i j =>
match decEq i.val j.val with
| isTrue h => isTrue (Fin.eqOfVeq h)
| isFalse h => isFalse (Fin.neOfVne h)
instance {n} : HasLess (Fin n) where
Less a b := Less a.val b.val
instance {n} : HasLessEq (Fin n) where
LessEq a b := LessEq a.val b.val
instance Fin.decLt {n} (a b : Fin n) : Decidable (Less a b) := Nat.decLt ..
instance Fin.decLe {n} (a b : Fin n) : Decidable (LessEq a b) := Nat.decLe ..
def UInt8.size : Nat := 256
structure UInt8 where
val : Fin UInt8.size
attribute [extern "lean_uint8_of_nat"] UInt8.mk
attribute [extern "lean_uint8_to_nat"] UInt8.val
@[extern "lean_uint8_of_nat"]
def UInt8.ofNatCore (n : @& Nat) (h : Less n UInt8.size) : UInt8 := {
val := { val := n, isLt := h }
}
set_option bootstrap.gen_matcher_code false in
@[extern c inline "#1 == #2"]
def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt8 := UInt8.decEq
instance : Inhabited UInt8 where
default := UInt8.ofNatCore 0 decide!
def UInt16.size : Nat := 65536
structure UInt16 where
val : Fin UInt16.size
attribute [extern "lean_uint16_of_nat"] UInt16.mk
attribute [extern "lean_uint16_to_nat"] UInt16.val
@[extern "lean_uint16_of_nat"]
def UInt16.ofNatCore (n : @& Nat) (h : Less n UInt16.size) : UInt16 := {
val := { val := n, isLt := h }
}
set_option bootstrap.gen_matcher_code false in
@[extern c inline "#1 == #2"]
def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt16 := UInt16.decEq
instance : Inhabited UInt16 where
default := UInt16.ofNatCore 0 decide!
def UInt32.size : Nat := 4294967296
structure UInt32 where
val : Fin UInt32.size
attribute [extern "lean_uint32_of_nat"] UInt32.mk
attribute [extern "lean_uint32_to_nat"] UInt32.val
@[extern "lean_uint32_of_nat"]
def UInt32.ofNatCore (n : @& Nat) (h : Less n UInt32.size) : UInt32 := {
val := { val := n, isLt := h }
}
@[extern "lean_uint32_to_nat"]
def UInt32.toNat (n : UInt32) : Nat := n.val.val
set_option bootstrap.gen_matcher_code false in
@[extern c inline "#1 == #2"]
def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt32 := UInt32.decEq
instance : Inhabited UInt32 where
default := UInt32.ofNatCore 0 decide!
instance : HasLess UInt32 where
Less a b := Less a.val b.val
instance : HasLessEq UInt32 where
LessEq a b := LessEq a.val b.val
set_option bootstrap.gen_matcher_code false in
@[extern c inline "#1 < #2"]
def UInt32.decLt (a b : UInt32) : Decidable (Less a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (Less n m))
set_option bootstrap.gen_matcher_code false in
@[extern c inline "#1 <= #2"]
def UInt32.decLe (a b : UInt32) : Decidable (LessEq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LessEq n m))
instance (a b : UInt32) : Decidable (Less a b) := UInt32.decLt a b
instance (a b : UInt32) : Decidable (LessEq a b) := UInt32.decLe a b
def UInt64.size : Nat := 18446744073709551616
structure UInt64 where
val : Fin UInt64.size
attribute [extern "lean_uint64_of_nat"] UInt64.mk
attribute [extern "lean_uint64_to_nat"] UInt64.val
@[extern "lean_uint64_of_nat"]
def UInt64.ofNatCore (n : @& Nat) (h : Less n UInt64.size) : UInt64 := {
val := { val := n, isLt := h }
}
set_option bootstrap.gen_matcher_code false in
@[extern c inline "#1 == #2"]
def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq UInt64 := UInt64.decEq
instance : Inhabited UInt64 where
default := UInt64.ofNatCore 0 decide!
def USize.size : Nat := hPow 2 System.Platform.numBits
theorem usizeSzEq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) :=
show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from
match System.Platform.numBits, System.Platform.numBitsEq with
| _, Or.inl rfl => Or.inl (decide! : (Eq (hPow 2 32) (4294967296:Nat)))
| _, Or.inr rfl => Or.inr (decide! : (Eq (hPow 2 64) (18446744073709551616:Nat)))
structure USize where
val : Fin USize.size
attribute [extern "lean_usize_of_nat"] USize.mk
attribute [extern "lean_usize_to_nat"] USize.val
@[extern "lean_usize_of_nat"]
def USize.ofNatCore (n : @& Nat) (h : Less n USize.size) : USize := {
val := { val := n, isLt := h }
}
set_option bootstrap.gen_matcher_code false in
@[extern c inline "#1 == #2"]
def USize.decEq (a b : USize) : Decidable (Eq a b) :=
match a, b with
| ⟨n⟩, ⟨m⟩ =>
dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq USize := USize.decEq
instance : Inhabited USize where
default := USize.ofNatCore 0 (match USize.size, usizeSzEq with
| _, Or.inl rfl => decide!
| _, Or.inr rfl => decide!)
@[extern "lean_usize_of_nat"]
def USize.ofNat32 (n : @& Nat) (h : Less n 4294967296) : USize := {
val := {
val := n,
isLt := match USize.size, usizeSzEq with
| _, Or.inl rfl => h
| _, Or.inr rfl => Nat.ltTrans h (decide! : Less 4294967296 18446744073709551616)
}
}
abbrev Nat.isValidChar (n : Nat) : Prop :=
Or (Less n 0xd800) (And (Less 0xdfff n) (Less n 0x110000))
abbrev UInt32.isValidChar (n : UInt32) : Prop :=
n.toNat.isValidChar
/-- The `Char` Type represents an unicode scalar value.
See http://www.unicode.org/glossary/#unicode_scalar_value). -/
structure Char where
val : UInt32
valid : val.isValidChar
private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : Less n UInt32.size :=
match h with
| Or.inl h => Nat.ltTrans h (decide! : Less 55296 UInt32.size)
| Or.inr ⟨_, h⟩ => Nat.ltTrans h (decide! : Less 1114112 UInt32.size)
@[extern "lean_uint32_of_nat"]
private def Char.ofNatAux (n : Nat) (h : n.isValidChar) : Char :=
{ val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h }
@[noinline, matchPattern]
def Char.ofNat (n : Nat) : Char :=
dite (n.isValidChar)
(fun h => Char.ofNatAux n h)
(fun _ => { val := ⟨{ val := 0, isLt := decide! }⟩, valid := Or.inl decide! })
theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d
| ⟨v, h⟩, ⟨_, _⟩, rfl => rfl
theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val
| _, _, rfl => rfl
theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) :=
fun h' => absurd (veqOfEq h') h
theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) :=
fun h' => absurd (eqOfVeq h') h
instance : DecidableEq Char :=
fun c d =>
match decEq c.val d.val with
| isTrue h => isTrue (Char.eqOfVeq h)
| isFalse h => isFalse (Char.neOfVne h)
def Char.utf8Size (c : Char) : UInt32 :=
let v := c.val
ite (LessEq v (UInt32.ofNatCore 0x7F decide!))
(UInt32.ofNatCore 1 decide!)
(ite (LessEq v (UInt32.ofNatCore 0x7FF decide!))
(UInt32.ofNatCore 2 decide!)
(ite (LessEq v (UInt32.ofNatCore 0xFFFF decide!))
(UInt32.ofNatCore 3 decide!)
(UInt32.ofNatCore 4 decide!)))
inductive Option (α : Type u) where
| none : Option α
| some (val : α) : Option α
attribute [unbox] Option
export Option (none some)
instance {α} : Inhabited (Option α) where
default := none
inductive List (α : Type u) where
| nil : List α
| cons (head : α) (tail : List α) : List α
instance {α} : Inhabited (List α) where
default := List.nil
protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b)
| nil, nil => isTrue rfl
| cons a as, nil => isFalse (fun h => List.noConfusion h)
| nil, cons b bs => isFalse (fun h => List.noConfusion h)
| cons a as, cons b bs =>
match decEq a b with
| isTrue hab =>
match List.hasDecEq as bs with
| isTrue habs => isTrue (hab ▸ habs ▸ rfl)
| isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs))
| isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab))
instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq
@[specialize]
def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α
| a, nil => a
| a, cons b l => foldl f (f a b) l
def List.set : List α → Nat → α → List α
| cons a as, 0, b => cons b as
| cons a as, Nat.succ n, b => cons a (set as n b)
| nil, _, _ => nil
def List.lengthAux {α : Type u} : List α → Nat → Nat
| nil, n => n
| cons a as, n => lengthAux as (Nat.succ n)
def List.length {α : Type u} (as : List α) : Nat :=
lengthAux as 0
theorem List.lengthConsEq {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ :=
let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ :=
match as with
| nil => fun _ => rfl
| cons a as => fun n => aux a as n.succ
aux a as 0
def List.concat {α : Type u} : List α → α → List α
| nil, b => cons b nil
| cons a as, b => cons a (concat as b)
def List.get {α : Type u} : (as : List α) → (i : Nat) → Less i as.length → α
| nil, i, h => absurd h (Nat.notLtZero _)
| cons a as, 0, h => a
| cons a as, Nat.succ i, h =>
have Less i.succ as.length.succ from lengthConsEq .. ▸ h
get as i (Nat.leOfSuccLeSucc this)
structure String where
data : List Char
attribute [extern "lean_string_mk"] String.mk
attribute [extern "lean_string_data"] String.data
@[extern "lean_string_dec_eq"]
def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) :=
match s₁, s₂ with
| ⟨s₁⟩, ⟨s₂⟩ =>
dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h)))
instance : DecidableEq String := String.decEq
/-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded.
Codepoint positions (counting the Unicode codepoints rather than bytes)
are represented by plain `Nat`s instead.
Indexing a `String` by a byte position is constant-time, while codepoint
positions need to be translated internally to byte positions in linear-time. -/
abbrev String.Pos := Nat
structure Substring where
str : String
startPos : String.Pos
stopPos : String.Pos
def String.csize (c : Char) : Nat :=
c.utf8Size.toNat
private def String.utf8ByteSizeAux : List Char → Nat → Nat
| List.nil, r => r
| List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c))
@[extern "lean_string_utf8_byte_size"]
def String.utf8ByteSize : (@& String) → Nat
| ⟨s⟩ => utf8ByteSizeAux s 0
@[inline] def String.bsize (s : String) : Nat :=
utf8ByteSize s
@[inline] def String.toSubstring (s : String) : Substring := {
str := s,
startPos := 0,
stopPos := s.bsize
}
@[extern c inline "#3"]
unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β :=
cast lcProof (PUnit.{v})
@[neverExtract, extern "lean_panic_fn"]
constant panic {α : Type u} [Inhabited α] (msg : String) : α
/-
The Compiler has special support for arrays.
They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array
-/
structure Array (α : Type u) where
data : List α
attribute [extern "lean_array_data"] Array.data
attribute [extern "lean_array_mk"] Array.mk
/- The parameter `c` is the initial capacity -/
@[extern "lean_mk_empty_array_with_capacity"]
def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := {
data := List.nil
}
def Array.empty {α : Type u} : Array α :=
mkEmpty 0
@[reducible, extern "lean_array_get_size"]
def Array.size {α : Type u} (a : @& Array α) : Nat :=
a.data.length
@[extern "lean_array_fget"]
def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α :=
a.data.get i.val i.isLt
@[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α :=
dite (Less i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀)
/- "Comfortable" version of `fget`. It performs a bound check at runtime. -/
@[extern "lean_array_get"]
def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α :=
Array.getD a i arbitrary
def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α :=
self.get! idx
@[extern "lean_array_push"]
def Array.push {α : Type u} (a : Array α) (v : α) : Array α := {
data := List.concat a.data v
}
@[extern "lean_array_fset"]
def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := {
data := a.data.set i.val v
}
@[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α :=
dite (Less i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a)
@[extern "lean_array_set"]
def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α :=
Array.setD a i v
-- Slower `Array.append` used in quotations.
protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α :=
let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α :=
dite (Less j bs.size)
(fun hlt =>
match i with
| 0 => as
| Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩)))
(fun _ => as)
loop bs.size 0 as
class Bind (m : Type u → Type v) where
bind : {α β : Type u} → m α → (α → m β) → m β
export Bind (bind)
class Pure (f : Type u → Type v) where
pure {α : Type u} : α → f α
export Pure (pure)
class Functor (f : Type u → Type v) : Type (max (u+1) v) where
map : {α β : Type u} → (α → β) → f α → f β
mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _)
class Seq (f : Type u → Type v) : Type (max (u+1) v) where
seq : {α β : Type u} → f (α → β) → f α → f β
class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where
seqLeft : {α : Type u} → f α → f PUnit → f α
class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where
seqRight : {β : Type u} → f PUnit → f β → f β
class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where
map := fun x y => Seq.seq (pure x) y
seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b
seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b
class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where
map := fun f x => bind x (Function.comp pure f)
seq := fun f x => bind f fun y => Functor.map y x
seqLeft := fun x y => bind x fun a => bind y (fun _ => pure a)
seqRight := fun x y => bind x fun _ => y
instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where
default := pure
instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where
default := pure arbitrary
-- A fusion of Haskell's `sequence` and `map`
def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) :=
let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) :=
dite (Less j as.size)
(fun hlt =>
match i with
| 0 => pure bs
| Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b))
(fun _ => bs)
loop as.size 0 Array.empty
/-- A Function for lifting a computation from an inner Monad to an outer Monad.
Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html),
but `n` does not have to be a monad transformer.
Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/
class MonadLift (m : Type u → Type v) (n : Type u → Type w) where
monadLift : {α : Type u} → m α → n α
/-- The reflexive-transitive closure of `MonadLift`.
`monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`.
Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/
class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where
monadLift : {α : Type u} → m α → n α
export MonadLiftT (monadLift)
abbrev liftM := @monadLift
instance (m n o) [MonadLiftT m n] [MonadLift n o] : MonadLiftT m o where
monadLift x := MonadLift.monadLift (m := n) (monadLift x)
instance (m) : MonadLiftT m m where
monadLift x := x
/-- A functor in the category of monads. Can be used to lift monad-transforming functions.
Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html),
but not restricted to monad transformers.
Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/
class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where
monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α
/-- The reflexive-transitive closure of `MonadFunctor`.
`monadMap` is used to transitively lift Monad morphisms -/
class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where
monadMap {α : Type u} : (∀ {β}, m β → m β) → n α → n α
export MonadFunctorT (monadMap)
instance (m n o) [MonadFunctorT m n] [MonadFunctor n o] : MonadFunctorT m o where
monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f)
instance monadFunctorRefl (m) : MonadFunctorT m m where
monadMap f := f
inductive Except (ε : Type u) (α : Type v) where
| error : ε → Except ε α
| ok : α → Except ε α
attribute [unbox] Except
instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where
default := Except.error arbitrary
/-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/
class MonadExceptOf (ε : Type u) (m : Type v → Type w) where
throw {α : Type v} : ε → m α
tryCatch {α : Type v} : m α → (ε → m α) → m α
abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α :=
MonadExceptOf.throw e
abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α :=
MonadExceptOf.tryCatch x handle
/-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/
class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where
throw {α : Type v} : ε → m α
tryCatch {α : Type v} : m α → (ε → m α) → m α
export MonadExcept (throw tryCatch)
instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where
throw := throwThe ε
tryCatch := tryCatchThe ε
namespace MonadExcept
variables {ε : Type u} {m : Type v → Type w}
@[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α :=
tryCatch t₁ fun _ => t₂
instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where
orElse := MonadExcept.orelse
end MonadExcept
/-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/
def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) :=
ρ → m α
instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where
default := fun _ => arbitrary
@[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α :=
x r
@[reducible] def Reader (ρ : Type u) := ReaderT ρ id
namespace ReaderT
section
variables {ρ : Type u} {m : Type u → Type v} {α : Type u}
instance : MonadLift m (ReaderT ρ m) where
monadLift x := fun _ => x
instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where
throw e := liftM (m := m) (throw e)
tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r)
end
section
variables {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u}
@[inline] protected def read : ReaderT ρ m ρ :=
pure
@[inline] protected def pure (a : α) : ReaderT ρ m α :=
fun r => pure a
@[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β :=
fun r => bind (x r) fun a => f a r
@[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β :=
fun r => Functor.map f (x r)
instance : Monad (ReaderT ρ m) where
pure := ReaderT.pure
bind := ReaderT.bind
map := ReaderT.map
instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where
monadMap f x := fun ctx => f (x ctx)
@[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α :=
fun x r => x (f r)
end
end ReaderT
/-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).
It does not contain `local` because this Function cannot be lifted using `monadLift`.
Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function.
Note: This class can be seen as a simplification of the more "principled" definition
```
class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where
lift {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ReaderT ρ m α) → n α
```
-/
class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where
read : m ρ
@[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ :=
MonadReaderOf.read
/-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/
class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where
read : m ρ
export MonadReader (read)
instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where
read := readThe ρ
instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadReaderOf ρ m] [MonadLift m n] : MonadReaderOf ρ n where
read := liftM (m := m) read
instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where
read := ReaderT.read
class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where
withReader {α : Type u} : (ρ → ρ) → m α → m α
@[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α :=
MonadWithReaderOf.withReader f x
class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where
withReader {α : Type u} : (ρ → ρ) → m α → m α
export MonadWithReader (withReader)
instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where
withReader := withTheReader ρ
instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadWithReaderOf ρ m] [MonadFunctor m n] : MonadWithReaderOf ρ n where
withReader f := monadMap (m := m) (withTheReader ρ f)
instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where
withReader f x := fun ctx => x (f ctx)
/-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html).
In contrast to the Haskell implementation, we use overlapping instances to derive instances
automatically from `monadLift`. -/
class MonadStateOf (σ : Type u) (m : Type u → Type v) where
/- Obtain the top-most State of a Monad stack. -/
get : m σ
/- Set the top-most State of a Monad stack. -/
set : σ → m PUnit
/- Map the top-most State of a Monad stack.
Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a`
because the latter does not use the State linearly (without sufficient inlining). -/
modifyGet {α : Type u} : (σ → Prod α σ) → m α
export MonadStateOf (set)
abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ :=
MonadStateOf.get
@[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit :=
MonadStateOf.modifyGet fun s => (PUnit.unit, f s)
@[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α :=
MonadStateOf.modifyGet f
/-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/
class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where
get : m σ
set : σ → m PUnit
modifyGet {α : Type u} : (σ → Prod α σ) → m α
export MonadState (get modifyGet)
instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where
set := MonadStateOf.set
get := getThe σ
modifyGet := fun f => MonadStateOf.modifyGet f
@[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit :=
modifyGet fun s => (PUnit.unit, f s)
@[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ :=
modifyGet fun s => (s, f s)
-- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer
-- will be picked first
instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadStateOf σ m] [MonadLift m n] : MonadStateOf σ n where
get := liftM (m := m) MonadStateOf.get
set := fun s => liftM (m := m) (MonadStateOf.set s)
modifyGet := fun f => monadLift (m := m) (MonadState.modifyGet f)
namespace EStateM
inductive Result (ε σ α : Type u) where
| ok : α → σ → Result ε σ α
| error : ε → σ → Result ε σ α
variables {ε σ α : Type u}
instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where
default := Result.error arbitrary arbitrary
end EStateM
open EStateM (Result) in
def EStateM (ε σ α : Type u) := σ → Result ε σ α
namespace EStateM
variables {ε σ α β : Type u}
instance [Inhabited ε] : Inhabited (EStateM ε σ α) where
default := fun s => Result.error arbitrary s
@[inline] protected def pure (a : α) : EStateM ε σ α := fun s =>
Result.ok a s
@[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ =>
Result.ok ⟨⟩ s
@[inline] protected def get : EStateM ε σ σ := fun s =>
Result.ok s s
@[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s =>
match f s with
| (a, s) => Result.ok a s
@[inline] protected def throw (e : ε) : EStateM ε σ α := fun s =>
Result.error e s
/-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/
class Backtrackable (δ : outParam (Type u)) (σ : Type u) where
save : σ → δ
restore : σ → δ → σ
@[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s =>
let d := Backtrackable.save s
match x s with
| Result.error e s => handle e (Backtrackable.restore s d)
| ok => ok
@[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s =>
let d := Backtrackable.save s;
match x₁ s with
| Result.error _ s => x₂ (Backtrackable.restore s d)
| ok => ok
@[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s =>
match x s with
| Result.error e s => Result.error (f e) s
| Result.ok a s => Result.ok a s
@[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s =>
match x s with
| Result.ok a s => f a s
| Result.error e s => Result.error e s
@[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s =>
match x s with
| Result.ok a s => Result.ok (f a) s
| Result.error e s => Result.error e s
@[inline] protected def seqRight (x : EStateM ε σ PUnit) (y : EStateM ε σ β) : EStateM ε σ β := fun s =>
match x s with
| Result.ok _ s => y s
| Result.error e s => Result.error e s
instance : Monad (EStateM ε σ) where
bind := EStateM.bind
pure := EStateM.pure
map := EStateM.map
seqRight := EStateM.seqRight
instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where
orElse := EStateM.orElse
instance : MonadStateOf σ (EStateM ε σ) where
set := EStateM.set
get := EStateM.get
modifyGet := EStateM.modifyGet
instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where
throw := EStateM.throw
tryCatch := EStateM.tryCatch
@[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α :=
x s
@[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α :=
match run x s with
| Result.ok v _ => some v
| Result.error _ _ => none
@[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩
@[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s
/- Dummy default instance -/
instance nonBacktrackable : Backtrackable PUnit σ where
save := dummySave
restore := dummyRestore
end EStateM
class Hashable (α : Type u) where
hash : α → USize
export Hashable (hash)
@[extern "lean_usize_mix_hash"]
constant mixHash (u₁ u₂ : USize) : USize
@[extern "lean_string_hash"]
protected constant String.hash (s : @& String) : USize
instance : Hashable String where
hash := String.hash
namespace Lean
/- Hierarchical names -/
inductive Name where
| anonymous : Name
| str : Name → String → USize → Name
| num : Name → Nat → USize → Name
instance : Inhabited Name where
default := Name.anonymous
protected def Name.hash : Name → USize
| Name.anonymous => USize.ofNat32 1723 decide!
| Name.str p s h => h
| Name.num p v h => h
instance : Hashable Name where
hash := Name.hash
namespace Name
@[export lean_name_mk_string]
def mkStr (p : Name) (s : String) : Name :=
Name.str p s (mixHash (hash p) (hash s))
@[export lean_name_mk_numeral]
def mkNum (p : Name) (v : Nat) : Name :=
Name.num p v (mixHash (hash p) (dite (Less v USize.size) (fun h => USize.ofNatCore v h) (fun _ => USize.ofNat32 17 decide!)))
def mkSimple (s : String) : Name :=
mkStr Name.anonymous s
@[extern "lean_name_eq"]
protected def beq : (@& Name) → (@& Name) → Bool
| anonymous, anonymous => true
| str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂)
| num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂)
| _, _ => false
instance : BEq Name where
beq := Name.beq
protected def append : Name → Name → Name
| n, anonymous => n
| n, str p s _ => Name.mkStr (Name.append n p) s
| n, num p d _ => Name.mkNum (Name.append n p) d
instance : Append Name where
append := Name.append
end Name
/- Syntax -/
/--
Source information of syntax atoms. All information is generally set for unquoted syntax and unset for syntax in
syntax quotations, but syntax transformations might want to invalidate only one side to make the pretty printer
reformat it. In the special case of the delaborator, we also use purely synthetic position information without
whitespace information. -/
structure SourceInfo where
/- Will be inferred after parsing by `Syntax.updateLeading`. During parsing,
it is not at all clear what the preceding token was, especially with backtracking. -/
leading : Option Substring := none
pos : Option String.Pos := none
trailing : Option Substring := none
instance : Inhabited SourceInfo := ⟨{}⟩
abbrev SyntaxNodeKind := Name
/- Syntax AST -/
inductive Syntax where
| missing : Syntax
| node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax
| atom (info : SourceInfo) (val : String) : Syntax
| ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax
instance : Inhabited Syntax where
default := Syntax.missing
/- Builtin kinds -/
def choiceKind : SyntaxNodeKind := `choice
def nullKind : SyntaxNodeKind := `null
def identKind : SyntaxNodeKind := `ident
def strLitKind : SyntaxNodeKind := `strLit
def charLitKind : SyntaxNodeKind := `charLit
def numLitKind : SyntaxNodeKind := `numLit
def scientificLitKind : SyntaxNodeKind := `scientificLit
def nameLitKind : SyntaxNodeKind := `nameLit
def fieldIdxKind : SyntaxNodeKind := `fieldIdx
def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind
def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind
namespace Syntax
def getKind (stx : Syntax) : SyntaxNodeKind :=
match stx with
| Syntax.node k args => k
-- We use these "pseudo kinds" for antiquotation kinds.
-- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident)
-- is compiled to ``if stx.isOfKind `ident ...``
| Syntax.missing => `missing
| Syntax.atom _ v => Name.mkSimple v
| Syntax.ident _ _ _ _ => identKind
def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax :=
match stx with
| Syntax.node _ args => Syntax.node k args
| _ => stx
def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool :=
beq stx.getKind k
def getArg (stx : Syntax) (i : Nat) : Syntax :=
match stx with
| Syntax.node _ args => args.getD i Syntax.missing
| _ => Syntax.missing
-- Add `stx[i]` as sugar for `stx.getArg i`
@[inline] def getOp (self : Syntax) (idx : Nat) : Syntax :=
self.getArg idx
def getArgs (stx : Syntax) : Array Syntax :=
match stx with
| Syntax.node _ args => args
| _ => Array.empty
def getNumArgs (stx : Syntax) : Nat :=
match stx with
| Syntax.node _ args => args.size
| _ => 0
def setArgs (stx : Syntax) (args : Array Syntax) : Syntax :=
match stx with
| node k _ => node k args
| stx => stx
def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax :=
match stx with
| node k args => node k (args.setD i arg)
| stx => stx
/-- Retrieve the left-most leaf's info in the Syntax tree. -/
partial def getHeadInfo : Syntax → Option SourceInfo
| atom info _ => some info
| ident info _ _ _ => some info
| node _ args =>
let rec loop (i : Nat) : Option SourceInfo :=
match decide (Less i args.size) with
| true => match getHeadInfo (args.get! i) with
| some info => some info
| none => loop (hAdd i 1)
| false => none
loop 0
| _ => none
def getPos (stx : Syntax) : Option String.Pos :=
match stx.getHeadInfo with
| some info => info.pos
| _ => none
/--
An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically
remove/insert the separators. -/
structure SepArray (sep : String) where
elemsAndSeps : Array Syntax
end Syntax
def mkAtomFrom (src : Syntax) (val : String) : Syntax :=
match src.getHeadInfo with
| some info => Syntax.atom info val
| none => Syntax.atom {} val
/- Parser descriptions -/
inductive ParserDescr where
| const (name : Name)
| unary (name : Name) (p : ParserDescr)
| binary (name : Name) (p₁ p₂ : ParserDescr)
| node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr)
| trailingNode (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr)
| symbol (val : String)
| nonReservedSymbol (val : String) (includeIdent : Bool)
| cat (catName : Name) (rbp : Nat)
| parser (declName : Name)
| nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr)
| sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false)
| sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false)
instance : Inhabited ParserDescr where
default := ParserDescr.symbol ""
abbrev TrailingParserDescr := ParserDescr
/-
Runtime support for making quotation terms auto-hygienic, by mangling identifiers
introduced by them with a "macro scope" supplied by the context. Details to appear in a
paper soon.
-/
abbrev MacroScope := Nat
/-- Macro scope used internally. It is not available for our frontend. -/
def reservedMacroScope := 0
/-- First macro scope available for our frontend -/
def firstFrontendMacroScope := hAdd reservedMacroScope 1
class MonadRef (m : Type → Type) where
getRef : m Syntax
withRef {α} : Syntax → m α → m α
export MonadRef (getRef)
instance (m n : Type → Type) [MonadRef m] [MonadFunctor m n] [MonadLift m n] : MonadRef n where
getRef := liftM (getRef : m _)
withRef := fun ref x => monadMap (m := m) (MonadRef.withRef ref) x
def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax :=
match ref.getPos with
| some _ => ref
| _ => oldRef
@[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α :=
bind getRef fun oldRef =>
let ref := replaceRef ref oldRef
MonadRef.withRef ref x
/-- A monad that supports syntax quotations. Syntax quotations (in term
position) are monadic values that when executed retrieve the current "macro
scope" from the monad and apply it to every identifier they introduce
(independent of whether this identifier turns out to be a reference to an
existing declaration, or an actually fresh binding during further
elaboration). We also apply the position of the result of `getRef` to each
introduced symbol, which results in better error positions than not applying
any position. -/
class MonadQuotation (m : Type → Type) extends MonadRef m where
-- Get the fresh scope of the current macro invocation
getCurrMacroScope : m MacroScope
getMainModule : m Name
/- Execute action in a new macro invocation context. This transformer should be
used at all places that morally qualify as the beginning of a "macro call",
e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it
can also be used internally inside a "macro" if identifiers introduced by
e.g. different recursive calls should be independent and not collide. While
returning an intermediate syntax tree that will recursively be expanded by
the elaborator can be used for the same effect, doing direct recursion inside
the macro guarded by this transformer is often easier because one is not
restricted to passing a single syntax tree. Modelling this helper as a
transformer and not just a monadic action ensures that the current macro
scope before the recursive call is restored after it, as expected. -/
withFreshMacroScope {α : Type} : m α → m α
export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope)
def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do
return { pos := (← getRef).getPos }
instance {m n : Type → Type} [MonadQuotation m] [MonadLift m n] [MonadFunctor m n] : MonadQuotation n where
getCurrMacroScope := liftM (m := m) getCurrMacroScope
getMainModule := liftM (m := m) getMainModule
withFreshMacroScope := monadMap (m := m) withFreshMacroScope
/-
We represent a name with macro scopes as
```
<actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes>
```
Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5]
```
foo.bla._@.Init.Data.List.Basic._hyg.2.5
```
We may have to combine scopes from different files/modules.
The main modules being processed is always the right most one.
This situation may happen when we execute a macro generated in
an imported file in the current file.
```
foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4
```
The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance.
-/
def Name.hasMacroScopes : Name → Bool
| str _ s _ => beq s "_hyg"
| num p _ _ => hasMacroScopes p
| _ => false
private def eraseMacroScopesAux : Name → Name
| Name.str p s _ => match beq s "_@" with
| true => p
| false => eraseMacroScopesAux p
| Name.num p _ _ => eraseMacroScopesAux p
| Name.anonymous => Name.anonymous
@[export lean_erase_macro_scopes]
def Name.eraseMacroScopes (n : Name) : Name :=
match n.hasMacroScopes with
| true => eraseMacroScopesAux n
| false => n
private def simpMacroScopesAux : Name → Name
| Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i
| n => eraseMacroScopesAux n
/- Helper function we use to create binder names that do not need to be unique. -/
@[export lean_simp_macro_scopes]
def Name.simpMacroScopes (n : Name) : Name :=
match n.hasMacroScopes with
| true => simpMacroScopesAux n
| false => n
structure MacroScopesView where
name : Name
imported : Name
mainModule : Name
scopes : List MacroScope
instance : Inhabited MacroScopesView where
default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩
def MacroScopesView.review (view : MacroScopesView) : Name :=
match view.scopes with
| List.nil => view.name
| List.cons _ _ =>
let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg")
view.scopes.foldl Name.mkNum base
private def assembleParts : List Name → Name → Name
| List.nil, acc => acc
| List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s)
| List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n)
| _, acc => panic "Error: unreachable @ assembleParts"
private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView
| n@(Name.str p str _), parts =>
match beq str "_@" with
| true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps }
| false => extractImported scps mainModule p (List.cons n parts)
| n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts)
| _, _ => panic "Error: unreachable @ extractImported"
private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView
| n@(Name.str p str _), parts =>
match beq str "_@" with
| true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps }
| false => extractMainModule scps p (List.cons n parts)
| n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil
| _, _ => panic "Error: unreachable @ extractMainModule"
private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView
| Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc)
| Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg"
| _, _ => panic "Error: unreachable @ extractMacroScopesAux"
/--
Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`.
This operation is useful for analyzing/transforming the original identifiers, then adding back
the scopes (via `MacroScopesView.review`). -/
def extractMacroScopes (n : Name) : MacroScopesView :=
match n.hasMacroScopes with
| true => extractMacroScopesAux n List.nil
| false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous }
def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name :=
match n.hasMacroScopes with
| true =>
let view := extractMacroScopes n
match beq view.mainModule mainModule with
| true => Name.mkNum n scp
| false =>
{ view with
imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule),
mainModule := mainModule,
scopes := List.cons scp List.nil
}.review
| false =>
Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp
@[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name :=
bind getMainModule fun mainModule =>
bind getCurrMacroScope fun scp =>
pure (Lean.addMacroScope mainModule n scp)
def defaultMaxRecDepth := 512
def maxRecDepthErrorMessage : String :=
"maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)"
namespace Macro
/- References -/
constant MacroEnvPointed : PointedType.{0}
def MacroEnv : Type := MacroEnvPointed.type
instance : Inhabited MacroEnv where
default := MacroEnvPointed.val
structure Context where
macroEnv : MacroEnv
mainModule : Name
currMacroScope : MacroScope
currRecDepth : Nat := 0
maxRecDepth : Nat := defaultMaxRecDepth
ref : Syntax
inductive Exception where
| error : Syntax → String → Exception
| unsupportedSyntax : Exception
end Macro
abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception MacroScope)
abbrev Macro := Syntax → MacroM Syntax
namespace Macro
instance : MonadRef MacroM where
getRef := bind read fun ctx => pure ctx.ref
withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x
def addMacroScope (n : Name) : MacroM Name :=
bind read fun ctx =>
pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope)
def throwUnsupported {α} : MacroM α :=
throw Exception.unsupportedSyntax
def throwError {α} (msg : String) : MacroM α :=
bind getRef fun ref =>
throw (Exception.error ref msg)
def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α :=
withRef ref (throwError msg)
@[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α :=
bind (modifyGet (fun s => (s, hAdd s 1))) fun fresh =>
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
@[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α :=
bind read fun ctx =>
match beq ctx.currRecDepth ctx.maxRecDepth with
| true => throw (Exception.error ref maxRecDepthErrorMessage)
| false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x
instance : MonadQuotation MacroM where
getCurrMacroScope := fun ctx => pure ctx.currMacroScope
getMainModule := fun ctx => pure ctx.mainModule
withFreshMacroScope := Macro.withFreshMacroScope
unsafe def mkMacroEnvImp (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv :=
unsafeCast expandMacro?
@[implementedBy mkMacroEnvImp]
constant mkMacroEnv (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv
def expandMacroNotAvailable? (stx : Syntax) : MacroM (Option Syntax) :=
throwErrorAt stx "expandMacro has not been set"
def mkMacroEnvSimple : MacroEnv :=
mkMacroEnv expandMacroNotAvailable?
unsafe def expandMacro?Imp (stx : Syntax) : MacroM (Option Syntax) :=
bind read fun ctx =>
let f : Syntax → MacroM (Option Syntax) := unsafeCast (ctx.macroEnv)
f stx
/-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/
@[implementedBy expandMacro?Imp] constant expandMacro? : Syntax → MacroM (Option Syntax)
end Macro
export Macro (expandMacro?)
namespace PrettyPrinter
abbrev UnexpandM := EStateM Unit Unit
/--
Function that tries to reverse macro expansions as a post-processing step of delaboration.
While less general than an arbitrary delaborator, it can be declared without importing `Lean`.
Used by the `[appUnexpander]` attribute. -/
-- a `kindUnexpander` could reasonably be added later
abbrev Unexpander := Syntax → UnexpandM Syntax
-- unexpanders should not need to introduce new names
instance : MonadQuotation UnexpandM where
getRef := pure Syntax.missing
withRef := fun _ => id
getCurrMacroScope := pure 0
getMainModule := pure `_fakeMod
withFreshMacroScope := id
end PrettyPrinter
end Lean
|
641a74912680e1bc477eff9076378a7e626b8862 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/algebra/lattice_ordered_group.lean | c27ece4fa690183e92006d0963dd97bee197bb74 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,911 | lean | /-
Copyright (c) 2021 Christopher Hoskin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Christopher Hoskin
-/
import algebra.ordered_group
import algebra.group_power.basic -- Needed for squares
import tactic.nth_rewrite
/-!
# Lattice ordered groups
Lattice ordered groups were introduced by [Birkhoff][birkhoff1942].
They form the algebraic underpinnings of vector lattices, Banach lattices, AL-space, AM-space etc.
This file develops the basic theory, concentrating on the commutative case.
## Main statements
- `pos_div_neg`: Every element `a` of a lattice ordered commutative group has a decomposition
`a⁺-a⁻` into the difference of the positive and negative component.
- `pos_inf_neg_eq_one`: The positive and negative components are coprime.
- `abs_triangle`: The absolute value operation satisfies the triangle inequality.
It is shown that the inf and sup operations are related to the absolute value operation by a
number of equations and inequalities.
## Notations
- `a⁺ = a ⊔ 0`: The *positive component* of an element `a` of a lattice ordered commutative group
- `a⁻ = (-a) ⊔ 0`: The *negative component* of an element `a` of a lattice ordered commutative group
* `|a| = a⊔(-a)`: The *absolute value* of an element `a` of a lattice ordered commutative group
## Implementation notes
A lattice ordered commutative group is a type `α` satisfying:
* `[lattice α]`
* `[comm_group α]`
* `[covariant_class α α (*) (≤)]`
The remainder of the file establishes basic properties of lattice ordered commutative groups. A
number of these results also hold in the non-commutative case ([Birkhoff][birkhoff1942],
[Fuchs][fuchs1963]) but we have not developed that here, since we are primarily interested in vector
lattices.
## References
* [Birkhoff, Lattice-ordered Groups][birkhoff1942]
* [Bourbaki, Algebra II][bourbaki1981]
* [Fuchs, Partially Ordered Algebraic Systems][fuchs1963]
* [Zaanen, Lectures on "Riesz Spaces"][zaanen1966]
* [Banasiak, Banach Lattices in Applications][banasiak]
## Tags
lattice, ordered, group
-/
universe u
-- A linearly ordered additive commutative group is a lattice ordered commutative group
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_covariant_class (α : Type u)
[linear_ordered_comm_group α] : covariant_class α α (*) (≤) :=
{ elim := λ a b c bc, linear_ordered_comm_group.mul_le_mul_left _ _ bc a }
variables {α : Type u} [lattice α] [comm_group α]
-- Special case of Bourbaki A.VI.9 (1)
/--
Let `α` be a lattice ordered commutative group. For all elements `a`, `b` and `c` in `α`,
$$c + (a ⊔ b) = (c + a) ⊔ (c + b).$$
-/
@[to_additive]
lemma mul_sup_eq_mul_sup_mul [covariant_class α α (*) (≤)]
(a b c : α) : c * (a ⊔ b) = (c * a) ⊔ (c * b) :=
begin
refine le_antisymm _ (by simp),
rw [← mul_le_mul_iff_left (c⁻¹), ← mul_assoc, inv_mul_self, one_mul],
apply sup_le,
{ simp },
{ simp },
end
-- Special case of Bourbaki A.VI.9 (2)
/--
Let `α` be a lattice ordered commutative group. For all elements `a` and `b` in `α`,
$$-(a ⊔ b)=(-a) ⊓ (-b).$$
-/
@[to_additive]
lemma inv_sup_eq_inv_inf_inv [covariant_class α α (*) (≤)] (a b : α) : (a ⊔ b)⁻¹ = a⁻¹ ⊓ b⁻¹ :=
begin
rw le_antisymm_iff,
split,
{ rw le_inf_iff,
split,
{ rw inv_le_inv_iff, apply le_sup_left, },
{ rw inv_le_inv_iff, apply le_sup_right, } },
{ rw ← inv_le_inv_iff, simp,
split,
{ rw ← inv_le_inv_iff, simp, },
{ rw ← inv_le_inv_iff, simp, } }
end
/--
Let `α` be a lattice ordered commutative group. For all elements `a` and `b` in `α`,
$$ -(a ⊓ b) = -a ⊔ -b.$$
-/
@[to_additive]
lemma inv_inf_eq_sup_inv [covariant_class α α (*) (≤)] (a b : α) : (a ⊓ b)⁻¹ = a⁻¹ ⊔ b⁻¹ :=
by rw [← inv_inv (a⁻¹ ⊔ b⁻¹), inv_sup_eq_inv_inf_inv a⁻¹ b⁻¹, inv_inv, inv_inv]
-- Bourbaki A.VI.10 Prop 7
/--
Let `α` be a lattice ordered commutative group. For all elements `a` and `b` in `α`,
$$a ⊓ b + (a ⊔ b) = a + b.$$
-/
@[to_additive]
lemma inf_mul_sup [covariant_class α α (*) (≤)] (a b : α) : a ⊓ b * (a ⊔ b) = a * b :=
calc a⊓b * (a ⊔ b) = a ⊓ b * ((a * b) * (b⁻¹ ⊔ a⁻¹)) :
by { rw mul_sup_eq_mul_sup_mul b⁻¹ a⁻¹ (a * b), simp, }
... = a⊓b * ((a * b) * (a ⊓ b)⁻¹) : by rw [inv_inf_eq_sup_inv, sup_comm]
... = a * b : by rw [mul_comm, inv_mul_cancel_right]
/--
Absolute value is a unary operator with properties similar to the absolute value of a real number.
-/
local notation `|`a`|` := mabs a
namespace lattice_ordered_comm_group
-- Bourbaki A.VI.12 Definition 4
/--
Let `α` be a lattice ordered commutative group with identity `0`. For an element `a` of type `α`,
the element `a ⊔ 0` is said to be the *positive component* of `a`, denoted `a⁺`.
-/
@[to_additive pos
"Let `α` be a lattice ordered commutative group with identity `0`. For an element `a` of type `α`,
the element `a ⊔ 0` is said to be the *positive component* of `a`, denoted `a⁺`."]
def mpos (a : α) : α := a ⊔ 1
postfix `⁺`:1000 := mpos
/--
Let `α` be a lattice ordered commutative group with identity `0`. For an element `a` of type `α`,
the element `(-a) ⊔ 0` is said to be the *negative component* of `a`, denoted `a⁻`.
-/
@[to_additive neg
"Let `α` be a lattice ordered commutative group with identity `0`. For an element `a` of type `α`,
the element `(-a) ⊔ 0` is said to be the *negative component* of `a`, denoted `a⁻`."]
def mneg (a : α) : α := a⁻¹ ⊔ 1
postfix `⁻`:1000 := mneg
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` with absolute value
`|a|`. Then,
$$a ≤ |a|.$$
-/
@[to_additive le_abs]
lemma le_mabs (a : α) : a ≤ |a| := le_sup_left
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` with absolute value
`|a|`. Then,
$$-a ≤ |a|.$$
-/
@[to_additive]
lemma inv_le_abs (a : α) : a⁻¹ ≤ |a| := le_sup_right
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` with positive
component `a⁺`. Then `a⁺` is positive.
-/
@[to_additive pos_pos]
lemma m_pos_pos (a : α) : 1 ≤ a⁺ := le_sup_right
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` withnegative
component `a⁻`. Then `a⁻` is positive.
-/
@[to_additive neg_pos]
lemma m_neg_pos (a : α) : 1 ≤ a⁻ := le_sup_right
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` with positive
component `a⁺`. Then `a⁺` dominates `a`.
-/
@[to_additive le_pos]
lemma m_le_pos (a : α) : a ≤ a⁺ := le_sup_left
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` with negative
component `a⁻`. Then `a⁻` dominates `-a`.
-/
@[to_additive le_neg]
lemma m_le_neg (a : α) : a⁻¹ ≤ a⁻ := le_sup_left
-- Bourbaki A.VI.12
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α`. Then the negative
component `a⁻` of `a` is equal to the positive component `(-a)⁺` of `-a`.
-/
@[to_additive]
lemma neg_eq_pos_inv (a : α) : a⁻ = (a⁻¹)⁺ := by { unfold mneg, unfold mpos}
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α`. Then the positive
component `a⁺` of `a` is equal to the negative component `(-a)⁻` of `-a`.
-/
@[to_additive]
lemma pos_eq_neg_inv (a : α) : a⁺ = (a⁻¹)⁻ := by simp [neg_eq_pos_inv]
-- We use this in Bourbaki A.VI.12 Prop 9 a)
/--
Let `α` be a lattice ordered commutative group. For all elements `a`, `b` and `c` in `α`,
$$c + (a ⊓ b) = (c + a) ⊓ (c + b).$$
-/
@[to_additive]
lemma mul_inf_eq_mul_inf_mul [covariant_class α α (*) (≤)]
(a b c : α) : c * (a ⊓ b) = (c * a) ⊓ (c * b) :=
begin
rw le_antisymm_iff,
split,
{ simp, },
{ rw [← mul_le_mul_iff_left c⁻¹, ← mul_assoc, inv_mul_self, one_mul, le_inf_iff], simp, }
end
-- We use this in Bourbaki A.VI.12 Prop 9 a)
/--
Let `α` be a lattice ordered commutative group with identity `0` and let `a` be an element in `α`
with negative component `a⁻`. Then
$$a⁻ = -(a ⊓ 0).$$
-/
@[to_additive]
lemma neg_eq_inv_inf_one [covariant_class α α (*) (≤)] (a : α) : a⁻ = (a ⊓ 1)⁻¹ :=
begin
unfold lattice_ordered_comm_group.mneg,
rw [← inv_inj, inv_sup_eq_inv_inf_inv, inv_inv, inv_inv, one_inv],
end
-- Bourbaki A.VI.12 Prop 9 a)
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` with positive
component `a⁺` and negative component `a⁻`. Then `a` can be decomposed as the difference of `a⁺` and
`a⁻`.
-/
@[to_additive]
lemma pos_inv_neg [covariant_class α α (*) (≤)] (a : α) : a = a⁺ / a⁻ :=
begin
rw div_eq_mul_inv,
apply eq_mul_inv_of_mul_eq,
unfold lattice_ordered_comm_group.mneg,
rw [mul_sup_eq_mul_sup_mul, mul_one, mul_right_inv, sup_comm],
unfold lattice_ordered_comm_group.mpos,
end
-- Hack to work around rewrite not working if lhs is a variable
@[to_additive, nolint doc_blame_thm]
lemma pos_div_neg' [covariant_class α α (*) (≤)] (a : α) : a⁺ / a⁻ = a := (pos_inv_neg _).symm
-- Bourbaki A.VI.12 Prop 9 a)
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` with positive
component `a⁺` and negative component `a⁻`. Then `a⁺` and `a⁻` are co-prime (and, since they are
positive, disjoint).
-/
@[to_additive]
lemma pos_inf_neg_eq_one [covariant_class α α (*) (≤)] (a : α) : a⁺ ⊓ a⁻=1 :=
by rw [←mul_right_inj (a⁻)⁻¹, mul_inf_eq_mul_inf_mul, mul_one, mul_left_inv, mul_comm,
←div_eq_mul_inv, pos_div_neg', neg_eq_inv_inf_one, inv_inv]
-- Bourbaki A.VI.12 (with a and b swapped)
/--
Let `α` be a lattice ordered commutative group, let `a` and `b` be elements in `α`, and let
`(a - b)⁺` be the positive componet of `a - b`. Then
$$a⊔b = b + (a - b)⁺.$$
-/
@[to_additive]
lemma sup_eq_mul_pos_div [covariant_class α α (*) (≤)] (a b : α) : a ⊔ b = b * (a / b)⁺ :=
calc a ⊔ b = (b * (a / b)) ⊔ (b * 1) : by {rw [mul_one b, div_eq_mul_inv, mul_comm a,
mul_inv_cancel_left], }
... = b * ((a / b) ⊔ 1) : by { rw ← mul_sup_eq_mul_sup_mul (a / b) 1 b}
-- Bourbaki A.VI.12 (with a and b swapped)
/--
Let `α` be a lattice ordered commutative group, let `a` and `b` be elements in `α`, and let
`(a - b)⁺` be the positive componet of `a - b`. Then
$$a⊓b = a - (a - b)⁺.$$
-/
@[to_additive]
lemma inf_eq_div_pos_div [covariant_class α α (*) (≤)] (a b : α) : a ⊓ b = a / (a / b)⁺ :=
calc a ⊓ b = (a * 1) ⊓ (a * (b / a)) : by { rw [mul_one a, div_eq_mul_inv, mul_comm b,
mul_inv_cancel_left], }
... = a * (1 ⊓ (b / a)) : by rw ← mul_inf_eq_mul_inf_mul 1 (b / a) a
... = a * ((b / a) ⊓ 1) : by rw inf_comm
... = a * ((a / b)⁻¹ ⊓ 1) : by { rw div_eq_mul_inv, nth_rewrite 0 ← inv_inv b,
rw [← mul_inv, mul_comm b⁻¹, ← div_eq_mul_inv], }
... = a * ((a / b)⁻¹ ⊓ 1⁻¹) : by rw one_inv
... = a / ((a / b) ⊔ 1) : by rw [← inv_sup_eq_inv_inf_inv, ← div_eq_mul_inv]
-- Bourbaki A.VI.12 Prop 9 c)
/--
Let `α` be a lattice ordered commutative group and let `a` and `b` be elements in `α` with positive
components `a⁺` and `b⁺` and negative components `a⁻` and `b⁻` respectively. Then `b` dominates `a`
if and only if `b⁺` dominates `a⁺` and `a⁻` dominates `b⁻`.
-/
@[to_additive le_iff_pos_le_neg_ge]
lemma m_le_iff_pos_le_neg_ge [covariant_class α α (*) (≤)] (a b : α) : a ≤ b ↔ a⁺ ≤ b⁺ ∧ b⁻ ≤ a⁻ :=
begin
split,
{ intro h,
split,
{ apply sup_le
(le_trans h (lattice_ordered_comm_group.m_le_pos b))
(lattice_ordered_comm_group.m_pos_pos b), },
{ rw ← inv_le_inv_iff at h,
apply sup_le
(le_trans h (lattice_ordered_comm_group.m_le_neg a))
(lattice_ordered_comm_group.m_neg_pos a), }
},
{ intro h,
rw [← pos_div_neg' a, ← pos_div_neg' b ],
apply div_le_div'' h.1 h.2, }
end
-- The proof from Bourbaki A.VI.12 Prop 9 d)
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α` with absolute value
`|a|`, positive component `a⁺` and negative component `a⁻`. Then `|a|` decomposes as the sum of `a⁺`
and `a⁻`.
-/
@[to_additive]
lemma pos_mul_neg [covariant_class α α (*) (≤)] (a : α) : |a| = a⁺ * a⁻ :=
begin
rw le_antisymm_iff,
split,
{ unfold mabs,
rw sup_le_iff,
split,
{ nth_rewrite 0 ← mul_one a,
apply mul_le_mul'
(lattice_ordered_comm_group.m_le_pos a)
(lattice_ordered_comm_group.m_neg_pos a) },
{ nth_rewrite 0 ← one_mul (a⁻¹),
apply mul_le_mul'
(lattice_ordered_comm_group.m_pos_pos a)
(lattice_ordered_comm_group.m_le_neg a) } },
{ have mod_eq_pos: |a|⁺ = |a|,
{ nth_rewrite 1 ← pos_div_neg' (|a|),
rw div_eq_mul_inv,
symmetry,
rw [mul_right_eq_self], symmetry, rw [one_eq_inv, le_antisymm_iff],
split,
{ rw ← pos_inf_neg_eq_one a,
apply le_inf,
{ rw pos_eq_neg_inv,
apply and.right
(iff.elim_left (m_le_iff_pos_le_neg_ge _ _)
(lattice_ordered_comm_group.inv_le_abs a)), },
{ apply and.right
(iff.elim_left (m_le_iff_pos_le_neg_ge _ _)
(lattice_ordered_comm_group.le_mabs a)), } },
{ apply lattice_ordered_comm_group.m_neg_pos, } },
rw [← inf_mul_sup, pos_inf_neg_eq_one, one_mul, ← mod_eq_pos ],
apply sup_le,
apply and.left
(iff.elim_left (m_le_iff_pos_le_neg_ge _ _)
(lattice_ordered_comm_group.le_mabs a)),
rw neg_eq_pos_inv,
apply and.left
(iff.elim_left (m_le_iff_pos_le_neg_ge _ _)
(lattice_ordered_comm_group.inv_le_abs a)), }
end
/--
Let `α` be a lattice ordered commutative group, let `a` and `b` be elements in `α` and let `|b - a|`
be the absolute value of `b - a`. Then,
$$a ⊔ b - (a ⊓ b) = |b - a|.$$
-/
@[to_additive]
lemma sup_div_inf_eq_abs_div [covariant_class α α (*) (≤)] (a b : α) :
(a ⊔ b) / (a ⊓ b) = |b / a| :=
begin
rw [sup_eq_mul_pos_div, inf_comm, inf_eq_div_pos_div, div_eq_mul_inv],
nth_rewrite 1 div_eq_mul_inv,
rw [mul_inv_rev, inv_inv, mul_comm, ← mul_assoc, inv_mul_cancel_right, pos_eq_neg_inv (a / b)],
nth_rewrite 1 div_eq_mul_inv,
rw [mul_inv_rev, ← div_eq_mul_inv, inv_inv, ← pos_mul_neg],
end
/--
Let `α` be a lattice ordered commutative group, let `a` and `b` be elements in `α` and let `|b - a|`
be the absolute value of `b - a`. Then,
$$2•(a ⊔ b) = a + b + |b - a|.$$
-/
@[to_additive]
lemma sup_sq_eq_mul_mul_abs_div [covariant_class α α (*) (≤)] (a b : α) :
(a ⊔ b)^2 = a * b * |b / a| :=
by rw [← inf_mul_sup a b, ← sup_div_inf_eq_abs_div, div_eq_mul_inv, ← mul_assoc, mul_comm,
mul_assoc, ← pow_two, inv_mul_cancel_left]
/--
Let `α` be a lattice ordered commutative group, let `a` and `b` be elements in `α` and let `|b-a|`
be the absolute value of `b-a`. Then,
$$2•(a ⊓ b) = a + b - |b - a|.$$
-/
@[to_additive]
lemma two_inf_eq_mul_div_abs_div [covariant_class α α (*) (≤)] (a b : α) :
(a ⊓ b)^2 = a * b / |b / a| :=
by rw [← inf_mul_sup a b, ← sup_div_inf_eq_abs_div, div_eq_mul_inv, div_eq_mul_inv,
mul_inv_rev, inv_inv, mul_assoc, mul_inv_cancel_comm_assoc, ← pow_two]
/--
Every lattice ordered commutative group is a distributive lattice
-/
@[to_additive
"Every lattice ordered commutative additive group is a distributive lattice"
]
def lattice_ordered_comm_group_to_distrib_lattice (α : Type u)
[s: lattice α] [comm_group α] [covariant_class α α (*) (≤)] : distrib_lattice α :=
{ le_sup_inf :=
begin
intros,
rw [← mul_le_mul_iff_left (x ⊓ (y ⊓ z)), inf_mul_sup x (y ⊓ z),
← inv_mul_le_iff_le_mul, le_inf_iff ],
split,
{ rw [inv_mul_le_iff_le_mul, ← inf_mul_sup x y ],
apply mul_le_mul',
{ apply inf_le_inf_left, apply inf_le_left, },
{ apply inf_le_left, } },
{ rw [inv_mul_le_iff_le_mul, ← inf_mul_sup x z ],
apply mul_le_mul',
{ apply inf_le_inf_left, apply inf_le_right, },
{ apply inf_le_right, }, }
end,
..s }
-- See, e.g. Zaanen, Lectures on Riesz Spaces
-- 3rd lecture
/--
Let `α` be a lattice ordered commutative group and let `a`, `b` and `c` be elements in `α`. Let
`|a ⊔ c - (b ⊔ c)|`, `|a ⊓ c - b ⊓ c|` and `|a - b|` denote the absolute values of
`a ⊔ c - (b ⊔ c)`, `a ⊓ c - b ⊓ c` and `a - b` respectively. Then,
$$|a ⊔ c - (b ⊔ c)| + |a ⊓ c-b ⊓ c| = |a - b|.$$
-/
@[to_additive]
theorem abs_div_sup_mul_abs_div_inf [covariant_class α α (*) (≤)] (a b c : α) :
|(a ⊔ c)/(b ⊔ c)| * |(a ⊓ c)/(b ⊓ c)| = |a / b| :=
begin
letI : distrib_lattice α := lattice_ordered_comm_group_to_distrib_lattice α,
calc |(a ⊔ c) / (b ⊔ c)| * |a ⊓ c / (b ⊓ c)| =
((b ⊔ c ⊔ (a ⊔ c)) / ((b ⊔ c) ⊓ (a ⊔ c))) * |a ⊓ c / (b ⊓ c)| : by rw sup_div_inf_eq_abs_div
... = (b ⊔ c ⊔ (a ⊔ c)) / ((b ⊔ c) ⊓ (a ⊔ c)) * (((b ⊓ c) ⊔ (a ⊓ c)) / ((b ⊓ c) ⊓ (a ⊓ c))) :
by rw sup_div_inf_eq_abs_div (b ⊓ c) (a ⊓ c)
... = (b ⊔ a ⊔ c) / ((b ⊓ a) ⊔ c) * (((b ⊔ a) ⊓ c) / (b ⊓ a ⊓ c)) : by {
rw [← sup_inf_right, ← inf_sup_right, sup_assoc ],
nth_rewrite 1 sup_comm,
rw [sup_right_idem, sup_assoc, inf_assoc ],
nth_rewrite 3 inf_comm,
rw [inf_right_idem, inf_assoc], }
... = (b ⊔ a ⊔ c) * ((b ⊔ a) ⊓ c) /(((b ⊓ a) ⊔ c) * (b ⊓ a ⊓ c)) : by rw div_mul_comm
... = (b ⊔ a) * c / (b ⊓ a * c) :
by rw [mul_comm, inf_mul_sup, mul_comm (b ⊓ a ⊔ c), inf_mul_sup]
... = (b ⊔ a) / (b ⊓ a) : by rw [div_eq_mul_inv, mul_inv_rev, mul_assoc, mul_inv_cancel_left,
← div_eq_mul_inv]
... = |a / b| : by rw sup_div_inf_eq_abs_div
end
/--
Let `α` be a lattice ordered commutative group and let `a` be a positive element in `α`. Then `a` is
equal to its positive component `a⁺`.
-/
@[to_additive pos_pos_id]
lemma m_pos_pos_id (a : α) (h : 1 ≤ a): a⁺ = a :=
begin
unfold lattice_ordered_comm_group.mpos,
apply sup_of_le_left h,
end
/--
Let `α` be a lattice ordered commutative group and let `a` be a positive element in `α`. Then `a` is
equal to its absolute value `|a|`.
-/
@[to_additive abs_pos_eq]
lemma mabs_pos_eq [covariant_class α α (*) (≤)] (a : α) (h: 1 ≤ a) : |a| = a :=
begin
unfold mabs,
rw [sup_eq_mul_pos_div, div_eq_mul_inv, inv_inv, ← pow_two, inv_mul_eq_iff_eq_mul,
← pow_two, m_pos_pos_id ],
rw pow_two,
apply one_le_mul h h,
end
/--
Let `α` be a lattice ordered commutative group and let `a` be an element in `α`. Then the absolute
value `|a|` of `a` is positive.
-/
@[to_additive abs_pos]
lemma mabs_pos [covariant_class α α (*) (≤)] (a : α) : 1 ≤ |a| :=
begin
rw pos_mul_neg,
apply one_le_mul
(lattice_ordered_comm_group.m_pos_pos a)
(lattice_ordered_comm_group.m_neg_pos a),
end
/--
Let `α` be a lattice ordered commutative group. The unary operation of taking the absolute value is
idempotent.
-/
@[to_additive abs_idempotent]
lemma mabs_idempotent [covariant_class α α (*) (≤)] (a : α) : |a| = | |a| | :=
begin
rw mabs_pos_eq (|a|),
apply lattice_ordered_comm_group.mabs_pos,
end
-- Commutative case, Zaanen, 3rd lecture
-- For the non-commutative case, see Birkhoff Theorem 19 (27)
/--
Let `α` be a lattice ordered commutative group and let `a`, `b` and `c` be elements in `α`. Let
`|a ⊔ c - (b ⊔ c)|`, `|a ⊓ c - b ⊓ c|` and `|a - b|` denote the absolute values of
`a ⊔ c - (b ⊔ c)`, `a ⊓ c - b ⊓ c` and`a - b` respectively. Then `|a - b|` dominates
`|a ⊔ c - (b ⊔ c)|` and `|a ⊓ c - b ⊓ c|`.
-/
@[to_additive Birkhoff_inequalities]
theorem m_Birkhoff_inequalities [covariant_class α α (*) (≤)] (a b c : α) :
|(a ⊔ c) / (b ⊔ c)| ⊔ |(a ⊓ c) / (b ⊓ c)| ≤ |a / b| :=
begin
rw sup_le_iff,
split,
{ apply le_of_mul_le_of_one_le_left,
rw abs_div_sup_mul_abs_div_inf,
apply lattice_ordered_comm_group.mabs_pos, },
{ apply le_of_mul_le_of_one_le_right,
rw abs_div_sup_mul_abs_div_inf,
apply lattice_ordered_comm_group.mabs_pos, }
end
-- Banasiak Proposition 2.12, Zaanen 2nd lecture
/--
Let `α` be a lattice ordered commutative group. Then the absolute value satisfies the triangle
inequality.
-/
@[to_additive abs_triangle]
lemma mabs_triangle [covariant_class α α (*) (≤)] (a b : α) : |a * b| ≤ |a| * |b| :=
begin
apply sup_le,
{ apply mul_le_mul'
(lattice_ordered_comm_group.le_mabs a)
(lattice_ordered_comm_group.le_mabs b), },
{ rw mul_inv,
apply mul_le_mul',
apply lattice_ordered_comm_group.inv_le_abs,
apply lattice_ordered_comm_group.inv_le_abs, }
end
end lattice_ordered_comm_group
|
bf333a61a08b322baa081dab12115bfe4b01ad3c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/concrete_category/basic.lean | 00524c6e2b8f4a5b6e80b894d502dfc99a2fe1ff | [
"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 | 7,729 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather, Yury Kudryashov
-/
import category_theory.types
import category_theory.epi_mono
/-!
# Concrete categories
A concrete category is a category `C` with a fixed faithful functor
`forget : C ⥤ Type*`. We define concrete categories using `class
concrete_category`. In particular, we impose no restrictions on the
carrier type `C`, so `Type` is a concrete category with the identity
forgetful functor.
Each concrete category `C` comes with a canonical faithful functor
`forget C : C ⥤ Type*`. We say that a concrete category `C` admits a
*forgetful functor* to a concrete category `D`, if it has a functor
`forget₂ C D : C ⥤ D` such that `(forget₂ C D) ⋙ (forget D) = forget C`,
see `class has_forget₂`. Due to `faithful.div_comp`, it suffices
to verify that `forget₂.obj` and `forget₂.map` agree with the equality
above; then `forget₂` will satisfy the functor laws automatically, see
`has_forget₂.mk'`.
Two classes helping construct concrete categories in the two most
common cases are provided in the files `bundled_hom` and
`unbundled_hom`, see their documentation for details.
## References
See [Ahrens and Lumsdaine, *Displayed Categories*][ahrens2017] for
related work.
-/
universes w v v' u
namespace category_theory
/--
A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type`.
Note that `concrete_category` potentially depends on three independent universe levels,
* the universe level `w` appearing in `forget : C ⥤ Type w`
* the universe level `v` of the morphisms (i.e. we have a `category.{v} C`)
* the universe level `u` of the objects (i.e `C : Type u`)
They are specified that order, to avoid unnecessary universe annotations.
-/
class concrete_category (C : Type u) [category.{v} C] :=
(forget [] : C ⥤ Type w)
[forget_faithful : faithful forget]
attribute [instance] concrete_category.forget_faithful
/-- The forgetful functor from a concrete category to `Type u`. -/
@[reducible] def forget (C : Type v) [category C] [concrete_category.{u} C] : C ⥤ Type u :=
concrete_category.forget C
instance concrete_category.types : concrete_category (Type u) :=
{ forget := 𝟭 _ }
/--
Provide a coercion to `Type u` for a concrete category. This is not marked as an instance
as it could potentially apply to every type, and so is too expensive in typeclass search.
You can use it on particular examples as:
```
instance : has_coe_to_sort X := concrete_category.has_coe_to_sort X
```
-/
def concrete_category.has_coe_to_sort (C : Type v) [category C] [concrete_category C] :
has_coe_to_sort C (Type u) :=
⟨(concrete_category.forget C).obj⟩
section
local attribute [instance] concrete_category.has_coe_to_sort
variables {C : Type v} [category C] [concrete_category C]
@[simp] lemma forget_obj_eq_coe {X : C} : (forget C).obj X = X := rfl
/-- Usually a bundled hom structure already has a coercion to function
that works with different universes. So we don't use this as a global instance. -/
def concrete_category.has_coe_to_fun {X Y : C} : has_coe_to_fun (X ⟶ Y) (λ f, X → Y) :=
⟨λ f, (forget _).map f⟩
local attribute [instance] concrete_category.has_coe_to_fun
/-- In any concrete category, we can test equality of morphisms by pointwise evaluations.-/
lemma concrete_category.hom_ext {X Y : C} (f g : X ⟶ Y) (w : ∀ x : X, f x = g x) : f = g :=
begin
apply faithful.map_injective (forget C),
ext,
exact w x,
end
@[simp] lemma forget_map_eq_coe {X Y : C} (f : X ⟶ Y) : (forget C).map f = f := rfl
/--
Analogue of `congr_fun h x`,
when `h : f = g` is an equality between morphisms in a concrete category.
-/
lemma congr_hom {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x :=
congr_fun (congr_arg (λ k : X ⟶ Y, (k : X → Y)) h) x
lemma coe_id {X : C} : ((𝟙 X) : X → X) = id :=
(forget _).map_id X
lemma coe_comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g : X → Z) = g ∘ f :=
(forget _).map_comp f g
@[simp] lemma id_apply {X : C} (x : X) : ((𝟙 X) : X → X) x = x :=
congr_fun ((forget _).map_id X) x
@[simp] lemma comp_apply {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) :
(f ≫ g) x = g (f x) :=
congr_fun ((forget _).map_comp _ _) x
@[simp] lemma coe_hom_inv_id {X Y : C} (f : X ≅ Y) (x : X) :
f.inv (f.hom x) = x :=
congr_fun ((forget C).map_iso f).hom_inv_id x
@[simp] lemma coe_inv_hom_id {X Y : C} (f : X ≅ Y) (y : Y) :
f.hom (f.inv y) = y :=
congr_fun ((forget C).map_iso f).inv_hom_id y
lemma concrete_category.congr_hom {X Y : C} {f g : X ⟶ Y} (h : f = g) (x : X) : f x = g x :=
congr_fun (congr_arg (λ f : X ⟶ Y, (f : X → Y)) h) x
lemma concrete_category.congr_arg {X Y : C} (f : X ⟶ Y) {x x' : X} (h : x = x') : f x = f x' :=
congr_arg (f : X → Y) h
/-- In any concrete category, injective morphisms are monomorphisms. -/
lemma concrete_category.mono_of_injective {X Y : C} (f : X ⟶ Y) (i : function.injective f) :
mono f :=
faithful_reflects_mono (forget C) ((mono_iff_injective f).2 i)
/-- In any concrete category, surjective morphisms are epimorphisms. -/
lemma concrete_category.epi_of_surjective {X Y : C} (f : X ⟶ Y) (s : function.surjective f) :
epi f :=
faithful_reflects_epi (forget C) ((epi_iff_surjective f).2 s)
@[simp] lemma concrete_category.has_coe_to_fun_Type {X Y : Type u} (f : X ⟶ Y) :
coe_fn f = f :=
rfl
end
/--
`has_forget₂ C D`, where `C` and `D` are both concrete categories, provides a functor
`forget₂ C D : C ⥤ D` and a proof that `forget₂ ⋙ (forget D) = forget C`.
-/
class has_forget₂ (C : Type v) (D : Type v') [category C] [concrete_category.{u} C] [category D]
[concrete_category.{u} D] :=
(forget₂ : C ⥤ D)
(forget_comp : forget₂ ⋙ (forget D) = forget C . obviously)
/-- The forgetful functor `C ⥤ D` between concrete categories for which we have an instance
`has_forget₂ C `. -/
@[reducible] def forget₂ (C : Type v) (D : Type v') [category C] [concrete_category C] [category D]
[concrete_category D] [has_forget₂ C D] : C ⥤ D :=
has_forget₂.forget₂
instance forget_faithful (C : Type v) (D : Type v') [category C] [concrete_category C] [category D]
[concrete_category D] [has_forget₂ C D] : faithful (forget₂ C D) :=
has_forget₂.forget_comp.faithful_of_comp
instance induced_category.concrete_category {C : Type v} {D : Type v'} [category D]
[concrete_category D] (f : C → D) :
concrete_category (induced_category D f) :=
{ forget := induced_functor f ⋙ forget D }
instance induced_category.has_forget₂ {C : Type v} {D : Type v'} [category D] [concrete_category D]
(f : C → D) :
has_forget₂ (induced_category D f) D :=
{ forget₂ := induced_functor f,
forget_comp := rfl }
/--
In order to construct a “partially forgetting” functor, we do not need to verify functor laws;
it suffices to ensure that compositions agree with `forget₂ C D ⋙ forget D = forget C`.
-/
def has_forget₂.mk' {C : Type v} {D : Type v'} [category C] [concrete_category C] [category D]
[concrete_category D] (obj : C → D) (h_obj : ∀ X, (forget D).obj (obj X) = (forget C).obj X)
(map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y))
(h_map : ∀ {X Y} {f : X ⟶ Y}, (forget D).map (map f) == (forget C).map f) :
has_forget₂ C D :=
{ forget₂ := faithful.div _ _ _ @h_obj _ @h_map,
forget_comp := by apply faithful.div_comp }
instance has_forget_to_Type (C : Type v) [category C] [concrete_category C] :
has_forget₂ C (Type u) :=
{ forget₂ := forget C,
forget_comp := functor.comp_id _ }
end category_theory
|
34dca49ed870b8dfefa1fcdbc03441e8d2534fc2 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/shapes/strong_epi.lean | a3ff55a80fcc95f958d9c3514680ce9caff9cecc | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,521 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.arrow
import Mathlib.PostPort
universes v u l
namespace Mathlib
/-!
# Strong epimorphisms
In this file, we define strong epimorphisms. A strong epimorphism is an epimorphism `f`, such
that for every commutative square with `f` at the top and a monomorphism at the bottom, there is
a diagonal morphism making the two triangles commute. This lift is necessarily unique (as shown in
`comma.lean`).
## Main results
Besides the definition, we show that
* the composition of two strong epimorphisms is a strong epimorphism,
* if `f ≫ g` is a strong epimorphism, then so is `g`,
* if `f` is both a strong epimorphism and a monomorphism, then it is an isomorphism
## Future work
There is also the dual notion of strong monomorphism.
## References
* [F. Borceux, *Handbook of Categorical Algebra 1*][borceux-vol1]
-/
namespace category_theory
/-- A strong epimorphism `f` is an epimorphism such that every commutative square with `f` at the
top and a monomorphism at the bottom has a lift. -/
class strong_epi {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q)
where
epi : epi f
has_lift : ∀ {X Y : C} {u : P ⟶ X} {v : Q ⟶ Y} {z : X ⟶ Y} [_inst_2 : mono z] (h : u ≫ z = f ≫ v), arrow.has_lift (arrow.hom_mk' h)
protected instance epi_of_strong_epi {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) [strong_epi f] : epi f :=
strong_epi.epi
/-- The composition of two strong epimorphisms is a strong epimorphism. -/
theorem strong_epi_comp {C : Type u} [category C] {P : C} {Q : C} {R : C} (f : P ⟶ Q) (g : Q ⟶ R) [strong_epi f] [strong_epi g] : strong_epi (f ≫ g) := sorry
/-- If `f ≫ g` is a strong epimorphism, then so is g. -/
theorem strong_epi_of_strong_epi {C : Type u} [category C] {P : C} {Q : C} {R : C} (f : P ⟶ Q) (g : Q ⟶ R) [strong_epi (f ≫ g)] : strong_epi g := sorry
/-- An isomorphism is in particular a strong epimorphism. -/
protected instance strong_epi_of_is_iso {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) [is_iso f] : strong_epi f := sorry
/-- A strong epimorphism that is a monomorphism is an isomorphism. -/
def is_iso_of_mono_of_strong_epi {C : Type u} [category C] {P : C} {Q : C} (f : P ⟶ Q) [mono f] [strong_epi f] : is_iso f :=
is_iso.mk (arrow.lift (arrow.hom_mk' sorry))
|
3e7ed2681c474c6fc648ad455807cffc613efde0 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/nat/interval.lean | 96181cf439d5d7557d8d554e6a27ab62085e300f | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 10,189 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finset.locally_finite
/-!
# Finite intervals of naturals
This file proves that `ℕ` is a `locally_finite_order` and calculates the cardinality of its
intervals as finsets and fintypes.
## TODO
Some lemmas can be generalized using `ordered_group`, `canonically_ordered_monoid` or `succ_order`
and subsequently be moved upstream to `data.finset.locally_finite`.
-/
open finset nat
instance : locally_finite_order ℕ :=
{ finset_Icc := λ a b, ⟨list.range' a (b + 1 - a), list.nodup_range' _ _⟩,
finset_Ico := λ a b, ⟨list.range' a (b - a), list.nodup_range' _ _⟩,
finset_Ioc := λ a b, ⟨list.range' (a + 1) (b - a), list.nodup_range' _ _⟩,
finset_Ioo := λ a b, ⟨list.range' (a + 1) (b - a - 1), list.nodup_range' _ _⟩,
finset_mem_Icc := λ a b x, begin
rw [finset.mem_mk, multiset.mem_coe, list.mem_range'],
cases le_or_lt a b,
{ rw [add_tsub_cancel_of_le (nat.lt_succ_of_le h).le, nat.lt_succ_iff] },
{ rw [tsub_eq_zero_iff_le.2 (succ_le_of_lt h), add_zero],
exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) }
end,
finset_mem_Ico := λ a b x, begin
rw [finset.mem_mk, multiset.mem_coe, list.mem_range'],
cases le_or_lt a b,
{ rw [add_tsub_cancel_of_le h] },
{ rw [tsub_eq_zero_iff_le.2 h.le, add_zero],
exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2.le)) }
end,
finset_mem_Ioc := λ a b x, begin
rw [finset.mem_mk, multiset.mem_coe, list.mem_range'],
cases le_or_lt a b,
{ rw [←succ_sub_succ, add_tsub_cancel_of_le (succ_le_succ h), nat.lt_succ_iff,
nat.succ_le_iff] },
{ rw [tsub_eq_zero_iff_le.2 h.le, add_zero],
exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.le.trans hx.2)) }
end,
finset_mem_Ioo := λ a b x, begin
rw [finset.mem_mk, multiset.mem_coe, list.mem_range', ← tsub_add_eq_tsub_tsub],
cases le_or_lt (a + 1) b,
{ rw [add_tsub_cancel_of_le h, nat.succ_le_iff] },
{ rw [tsub_eq_zero_iff_le.2 h.le, add_zero],
exact iff_of_false (λ hx, hx.2.not_le hx.1) (λ hx, h.not_le (hx.1.trans hx.2)) }
end }
variables (a b c : ℕ)
namespace nat
lemma Icc_eq_range' : Icc a b = ⟨list.range' a (b + 1 - a), list.nodup_range' _ _⟩ := rfl
lemma Ico_eq_range' : Ico a b = ⟨list.range' a (b - a), list.nodup_range' _ _⟩ := rfl
lemma Ioc_eq_range' : Ioc a b = ⟨list.range' (a + 1) (b - a), list.nodup_range' _ _⟩ := rfl
lemma Ioo_eq_range' : Ioo a b = ⟨list.range' (a + 1) (b - a - 1), list.nodup_range' _ _⟩ := rfl
lemma Iio_eq_range : Iio = range := by { ext b x, rw [mem_Iio, mem_range] }
@[simp] lemma Ico_zero_eq_range : Ico 0 = range := by rw [←bot_eq_zero, ←Iio_eq_Ico, Iio_eq_range]
lemma _root_.finset.range_eq_Ico : range = Ico 0 := Ico_zero_eq_range.symm
@[simp] lemma card_Icc : (Icc a b).card = b + 1 - a := list.length_range' _ _
@[simp] lemma card_Ico : (Ico a b).card = b - a := list.length_range' _ _
@[simp] lemma card_Ioc : (Ioc a b).card = b - a := list.length_range' _ _
@[simp] lemma card_Ioo : (Ioo a b).card = b - a - 1 := list.length_range' _ _
@[simp] lemma card_Iic : (Iic b).card = b + 1 :=
by rw [Iic_eq_Icc, card_Icc, bot_eq_zero, tsub_zero]
@[simp] lemma card_Iio : (Iio b).card = b := by rw [Iio_eq_Ico, card_Ico, bot_eq_zero, tsub_zero]
@[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = b + 1 - a :=
by rw [fintype.card_of_finset, card_Icc]
@[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = b - a :=
by rw [fintype.card_of_finset, card_Ico]
@[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = b - a :=
by rw [fintype.card_of_finset, card_Ioc]
@[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = b - a - 1 :=
by rw [fintype.card_of_finset, card_Ioo]
@[simp] lemma card_fintype_Iic : fintype.card (set.Iic b) = b + 1 :=
by rw [fintype.card_of_finset, card_Iic]
@[simp] lemma card_fintype_Iio : fintype.card (set.Iio b) = b :=
by rw [fintype.card_of_finset, card_Iio]
-- TODO@Yaël: Generalize all the following lemmas to `succ_order`
lemma Icc_succ_left : Icc a.succ b = Ioc a b := by { ext x, rw [mem_Icc, mem_Ioc, succ_le_iff] }
lemma Ico_succ_right : Ico a b.succ = Icc a b := by { ext x, rw [mem_Ico, mem_Icc, lt_succ_iff] }
lemma Ico_succ_left : Ico a.succ b = Ioo a b := by { ext x, rw [mem_Ico, mem_Ioo, succ_le_iff] }
lemma Icc_pred_right {b : ℕ} (h : 0 < b) : Icc a (b - 1) = Ico a b :=
by { ext x, rw [mem_Icc, mem_Ico, lt_iff_le_pred h] }
lemma Ico_succ_succ : Ico a.succ b.succ = Ioc a b :=
by { ext x, rw [mem_Ico, mem_Ioc, succ_le_iff, lt_succ_iff] }
@[simp] lemma Ico_succ_singleton : Ico a (a + 1) = {a} := by rw [Ico_succ_right, Icc_self]
@[simp] lemma Ico_pred_singleton {a : ℕ} (h : 0 < a) : Ico (a - 1) a = {a - 1} :=
by rw [←Icc_pred_right _ h, Icc_self]
@[simp] lemma Ioc_succ_singleton : Ioc b (b + 1) = {b+1} :=
by rw [← nat.Icc_succ_left, Icc_self]
variables {a b c}
lemma Ico_succ_right_eq_insert_Ico (h : a ≤ b) : Ico a (b + 1) = insert b (Ico a b) :=
by rw [Ico_succ_right, ←Ico_insert_right h]
lemma Ico_insert_succ_left (h : a < b) : insert a (Ico a.succ b) = Ico a b :=
by rw [Ico_succ_left, ←Ioo_insert_left h]
lemma image_sub_const_Ico (h : c ≤ a) : (Ico a b).image (λ x, x - c) = Ico (a - c) (b - c) :=
begin
ext x,
rw mem_image,
split,
{ rintro ⟨x, hx, rfl⟩,
rw [mem_Ico] at ⊢ hx,
exact ⟨tsub_le_tsub_right hx.1 _, tsub_lt_tsub_right_of_le (h.trans hx.1) hx.2⟩ },
{ rintro h,
refine ⟨x + c, _, add_tsub_cancel_right _ _⟩,
rw mem_Ico at ⊢ h,
exact ⟨tsub_le_iff_right.1 h.1, lt_tsub_iff_right.1 h.2⟩ }
end
lemma Ico_image_const_sub_eq_Ico (hac : a ≤ c) :
(Ico a b).image (λ x, c - x) = Ico (c + 1 - b) (c + 1 - a) :=
begin
ext x,
rw [mem_image, mem_Ico],
split,
{ rintro ⟨x, hx, rfl⟩,
rw mem_Ico at hx,
refine ⟨_, ((tsub_le_tsub_iff_left hac).2 hx.1).trans_lt ((tsub_lt_tsub_iff_right hac).2
(nat.lt_succ_self _))⟩,
cases lt_or_le c b,
{ rw tsub_eq_zero_iff_le.mpr (succ_le_of_lt h),
exact zero_le _ },
{ rw ←succ_sub_succ c,
exact (tsub_le_tsub_iff_left (succ_le_succ $ hx.2.le.trans h)).2 hx.2 } },
{ rintro ⟨hb, ha⟩,
rw [lt_tsub_iff_left, lt_succ_iff] at ha,
have hx : x ≤ c := (nat.le_add_left _ _).trans ha,
refine ⟨c - x, _, tsub_tsub_cancel_of_le hx⟩,
{ rw mem_Ico,
exact ⟨le_tsub_of_add_le_right ha, (tsub_lt_iff_left hx).2 $ succ_le_iff.1 $
tsub_le_iff_right.1 hb⟩ } }
end
lemma Ico_succ_left_eq_erase_Ico : Ico a.succ b = erase (Ico a b) a :=
begin
ext x,
rw [Ico_succ_left, mem_erase, mem_Ico, mem_Ioo, ←and_assoc, ne_comm, and_comm (a ≠ x),
lt_iff_le_and_ne],
end
lemma mod_inj_on_Ico (n a : ℕ) : set.inj_on (% a) (finset.Ico n (n+a)) :=
begin
induction n with n ih,
{ simp only [zero_add, nat_zero_eq_zero, Ico_zero_eq_range],
rintro k hk l hl (hkl : k % a = l % a),
simp only [finset.mem_range, finset.mem_coe] at hk hl,
rwa [mod_eq_of_lt hk, mod_eq_of_lt hl] at hkl, },
rw [Ico_succ_left_eq_erase_Ico, succ_add, Ico_succ_right_eq_insert_Ico le_self_add],
rintro k hk l hl (hkl : k % a = l % a),
have ha : 0 < a,
{ by_contra ha, simp only [not_lt, nonpos_iff_eq_zero] at ha, simpa [ha] using hk },
simp only [finset.mem_coe, finset.mem_insert, finset.mem_erase] at hk hl,
rcases hk with ⟨hkn, (rfl|hk)⟩; rcases hl with ⟨hln, (rfl|hl)⟩,
{ refl },
{ rw add_mod_right at hkl,
refine (hln $ ih hl _ hkl.symm).elim,
simp only [lt_add_iff_pos_right, set.left_mem_Ico, finset.coe_Ico, ha], },
{ rw add_mod_right at hkl,
suffices : k = n, { contradiction },
refine ih hk _ hkl,
simp only [lt_add_iff_pos_right, set.left_mem_Ico, finset.coe_Ico, ha], },
{ refine ih _ _ hkl; simp only [finset.mem_coe, hk, hl], },
end
/-- Note that while this lemma cannot be easily generalized to a type class, it holds for ℤ as
well. See `int.image_Ico_mod` for the ℤ version. -/
lemma image_Ico_mod (n a : ℕ) :
(Ico n (n+a)).image (% a) = range a :=
begin
obtain rfl | ha := eq_or_ne a 0,
{ rw [range_zero, add_zero, Ico_self, image_empty], },
ext i,
simp only [mem_image, exists_prop, mem_range, mem_Ico],
split,
{ rintro ⟨i, h, rfl⟩, exact mod_lt i ha.bot_lt },
intro hia,
have hn := nat.mod_add_div n a,
obtain hi | hi := lt_or_le i (n % a),
{ refine ⟨i + a * (n/a + 1), ⟨_, _⟩, _⟩,
{ rw [add_comm (n/a), mul_add, mul_one, ← add_assoc],
refine hn.symm.le.trans (add_le_add_right _ _),
simpa only [zero_add] using add_le_add (zero_le i) (nat.mod_lt n ha.bot_lt).le, },
{ refine lt_of_lt_of_le (add_lt_add_right hi (a * (n/a + 1))) _,
rw [mul_add, mul_one, ← add_assoc, hn], },
{ rw [nat.add_mul_mod_self_left, nat.mod_eq_of_lt hia], } },
{ refine ⟨i + a * (n/a), ⟨_, _⟩, _⟩,
{ exact hn.symm.le.trans (add_le_add_right hi _), },
{ rw [add_comm n a],
refine add_lt_add_of_lt_of_le hia (le_trans _ hn.le),
simp only [zero_le, le_add_iff_nonneg_left], },
{ rw [nat.add_mul_mod_self_left, nat.mod_eq_of_lt hia], } },
end
section multiset
open multiset
lemma multiset_Ico_map_mod (n a : ℕ) : (multiset.Ico n (n+a)).map (% a) = range a :=
begin
convert congr_arg finset.val (image_Ico_mod n a),
refine ((nodup_map_iff_inj_on (finset.Ico _ _).nodup).2 $ _).dedup.symm,
exact mod_inj_on_Ico _ _,
end
end multiset
end nat
namespace finset
lemma range_image_pred_top_sub (n : ℕ) : (finset.range n).image (λ j, n - 1 - j) = finset.range n :=
begin
cases n,
{ rw [range_zero, image_empty] },
{ rw [finset.range_eq_Ico, nat.Ico_image_const_sub_eq_Ico (zero_le _)],
simp_rw [succ_sub_succ, tsub_zero, tsub_self] }
end
lemma range_add_eq_union : range (a + b) = range a ∪ (range b).map (add_left_embedding a) :=
begin
rw [finset.range_eq_Ico, map_eq_image],
convert (Ico_union_Ico_eq_Ico a.zero_le le_self_add).symm,
exact image_add_left_Ico _ _ _,
end
end finset
|
2519514791bc14bda12e5e8708285b20c31fa808 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/stream/init.lean | 867b2a3c97cf6cb4102cec99f78779ddadf50aa6 | [
"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 | 19,468 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import data.stream.defs
import tactic.ext
/-!
# Streams a.k.a. infinite lists a.k.a. infinite sequences
This file used to be in the core library. It was moved to `mathlib` and renamed to `init` to avoid
name clashes. -/
open nat function option
universes u v w
namespace stream
variables {α : Type u} {β : Type v} {δ : Type w}
instance {α} [inhabited α] : inhabited (stream α) :=
⟨stream.const default⟩
protected theorem eta (s : stream α) : head s :: tail s = s :=
funext (λ i, begin cases i; refl end)
theorem nth_zero_cons (a : α) (s : stream α) : nth (a :: s) 0 = a := rfl
theorem head_cons (a : α) (s : stream α) : head (a :: s) = a := rfl
theorem tail_cons (a : α) (s : stream α) : tail (a :: s) = s := rfl
theorem tail_drop (n : nat) (s : stream α) : tail (drop n s) = drop n (tail s) :=
funext (λ i, begin unfold tail drop, simp [nth, nat.add_comm, nat.add_left_comm] end)
theorem nth_drop (n m : nat) (s : stream α) : nth (drop m s) n = nth s (n + m) := rfl
theorem tail_eq_drop (s : stream α) : tail s = drop 1 s := rfl
theorem drop_drop (n m : nat) (s : stream α) : drop n (drop m s) = drop (n+m) s :=
funext (λ i, begin unfold drop, rw nat.add_assoc end)
theorem nth_succ (n : nat) (s : stream α) : nth s (succ n) = nth (tail s) n := rfl
theorem drop_succ (n : nat) (s : stream α) : drop (succ n) s = drop n (tail s) := rfl
@[simp] lemma head_drop {α} (a : stream α) (n : ℕ) : (a.drop n).head = a.nth n :=
by simp only [drop, head, nat.zero_add, stream.nth]
@[ext] protected theorem ext {s₁ s₂ : stream α} : (∀ n, nth s₁ n = nth s₂ n) → s₁ = s₂ :=
assume h, funext h
theorem all_def (p : α → Prop) (s : stream α) : all p s = ∀ n, p (nth s n) := rfl
theorem any_def (p : α → Prop) (s : stream α) : any p s = ∃ n, p (nth s n) := rfl
theorem mem_cons (a : α) (s : stream α) : a ∈ (a::s) :=
exists.intro 0 rfl
theorem mem_cons_of_mem {a : α} {s : stream α} (b : α) : a ∈ s → a ∈ b :: s :=
assume ⟨n, h⟩,
exists.intro (succ n) (by rw [nth_succ, tail_cons, h])
theorem eq_or_mem_of_mem_cons {a b : α} {s : stream α} : a ∈ b::s → a = b ∨ a ∈ s :=
assume ⟨n, h⟩,
begin
cases n with n',
{ left, exact h },
{ right, rw [nth_succ, tail_cons] at h, exact ⟨n', h⟩ }
end
theorem mem_of_nth_eq {n : nat} {s : stream α} {a : α} : a = nth s n → a ∈ s :=
assume h, exists.intro n h
section map
variable (f : α → β)
theorem drop_map (n : nat) (s : stream α) : drop n (map f s) = map f (drop n s) :=
stream.ext (λ i, rfl)
theorem nth_map (n : nat) (s : stream α) : nth (map f s) n = f (nth s n) := rfl
theorem tail_map (s : stream α) : tail (map f s) = map f (tail s) :=
begin rw tail_eq_drop, refl end
theorem head_map (s : stream α) : head (map f s) = f (head s) := rfl
theorem map_eq (s : stream α) : map f s = f (head s) :: map f (tail s) :=
by rw [← stream.eta (map f s), tail_map, head_map]
theorem map_cons (a : α) (s : stream α) : map f (a :: s) = f a :: map f s :=
begin rw [← stream.eta (map f (a :: s)), map_eq], refl end
theorem map_id (s : stream α) : map id s = s := rfl
theorem map_map (g : β → δ) (f : α → β) (s : stream α) : map g (map f s) = map (g ∘ f) s := rfl
theorem map_tail (s : stream α) : map f (tail s) = tail (map f s) := rfl
theorem mem_map {a : α} {s : stream α} : a ∈ s → f a ∈ map f s :=
assume ⟨n, h⟩,
exists.intro n (by rw [nth_map, h])
theorem exists_of_mem_map {f} {b : β} {s : stream α} : b ∈ map f s → ∃ a, a ∈ s ∧ f a = b :=
assume ⟨n, h⟩, ⟨nth s n, ⟨n, rfl⟩, h.symm⟩
end map
section zip
variable (f : α → β → δ)
theorem drop_zip (n : nat) (s₁ : stream α) (s₂ : stream β) :
drop n (zip f s₁ s₂) = zip f (drop n s₁) (drop n s₂) :=
stream.ext (λ i, rfl)
theorem nth_zip (n : nat) (s₁ : stream α) (s₂ : stream β) :
nth (zip f s₁ s₂) n = f (nth s₁ n) (nth s₂ n) := rfl
theorem head_zip (s₁ : stream α) (s₂ : stream β) : head (zip f s₁ s₂) = f (head s₁) (head s₂) := rfl
theorem tail_zip (s₁ : stream α) (s₂ : stream β) :
tail (zip f s₁ s₂) = zip f (tail s₁) (tail s₂) := rfl
theorem zip_eq (s₁ : stream α) (s₂ : stream β) :
zip f s₁ s₂ = f (head s₁) (head s₂) :: zip f (tail s₁) (tail s₂) :=
begin rw [← stream.eta (zip f s₁ s₂)], refl end
end zip
theorem mem_const (a : α) : a ∈ const a :=
exists.intro 0 rfl
theorem const_eq (a : α) : const a = a :: const a :=
begin
apply stream.ext, intro n,
cases n; refl
end
theorem tail_const (a : α) : tail (const a) = const a :=
suffices tail (a :: const a) = const a, by rwa [← const_eq] at this, rfl
theorem map_const (f : α → β) (a : α) : map f (const a) = const (f a) := rfl
theorem nth_const (n : nat) (a : α) : nth (const a) n = a := rfl
theorem drop_const (n : nat) (a : α) : drop n (const a) = const a :=
stream.ext (λ i, rfl)
theorem head_iterate (f : α → α) (a : α) : head (iterate f a) = a := rfl
theorem tail_iterate (f : α → α) (a : α) : tail (iterate f a) = iterate f (f a) :=
begin
funext n,
induction n with n' ih,
{ refl },
{ unfold tail iterate,
unfold tail iterate at ih,
rw add_one at ih, dsimp at ih,
rw add_one, dsimp, rw ih }
end
theorem iterate_eq (f : α → α) (a : α) : iterate f a = a :: iterate f (f a) :=
begin
rw [← stream.eta (iterate f a)],
rw tail_iterate, refl
end
theorem nth_zero_iterate (f : α → α) (a : α) : nth (iterate f a) 0 = a := rfl
theorem nth_succ_iterate (n : nat) (f : α → α) (a : α) :
nth (iterate f a) (succ n) = nth (iterate f (f a)) n :=
by rw [nth_succ, tail_iterate]
section bisim
variable (R : stream α → stream α → Prop)
local infix ` ~ `:50 := R
def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → head s₁ = head s₂ ∧ tail s₁ ~ tail s₂
theorem nth_of_bisim (bisim : is_bisimulation R) :
∀ {s₁ s₂} n, s₁ ~ s₂ → nth s₁ n = nth s₂ n ∧ drop (n+1) s₁ ~ drop (n+1) s₂
| s₁ s₂ 0 h := bisim h
| s₁ s₂ (n+1) h :=
match bisim h with
| ⟨h₁, trel⟩ := nth_of_bisim n trel
end
-- If two streams are bisimilar, then they are equal
theorem eq_of_bisim (bisim : is_bisimulation R) : ∀ {s₁ s₂}, s₁ ~ s₂ → s₁ = s₂ :=
λ s₁ s₂ r, stream.ext (λ n, and.elim_left (nth_of_bisim R bisim n r))
end bisim
theorem bisim_simple (s₁ s₂ : stream α) :
head s₁ = head s₂ → s₁ = tail s₁ → s₂ = tail s₂ → s₁ = s₂ :=
assume hh ht₁ ht₂, eq_of_bisim
(λ s₁ s₂, head s₁ = head s₂ ∧ s₁ = tail s₁ ∧ s₂ = tail s₂)
(λ s₁ s₂ ⟨h₁, h₂, h₃⟩,
begin
constructor, exact h₁, rw [← h₂, ← h₃], repeat { constructor }; assumption
end)
(and.intro hh (and.intro ht₁ ht₂))
theorem coinduction {s₁ s₂ : stream α} :
head s₁ = head s₂ → (∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ →
fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ :=
assume hh ht,
eq_of_bisim
(λ s₁ s₂, head s₁ = head s₂ ∧ ∀ (β : Type u) (fr : stream α → β), fr s₁ = fr s₂ →
fr (tail s₁) = fr (tail s₂))
(λ s₁ s₂ h,
have h₁ : head s₁ = head s₂, from and.elim_left h,
have h₂ : head (tail s₁) = head (tail s₂), from and.elim_right h α (@head α) h₁,
have h₃ : ∀ (β : Type u) (fr : stream α → β),
fr (tail s₁) = fr (tail s₂) → fr (tail (tail s₁)) = fr (tail (tail s₂)),
from λ β fr, and.elim_right h β (λ s, fr (tail s)),
and.intro h₁ (and.intro h₂ h₃))
(and.intro hh ht)
theorem iterate_id (a : α) : iterate id a = const a :=
coinduction
rfl
(λ β fr ch, begin rw [tail_iterate, tail_const], exact ch end)
local attribute [reducible] stream
theorem map_iterate (f : α → α) (a : α) : iterate f (f a) = map f (iterate f a) :=
begin
funext n,
induction n with n' ih,
{ refl },
{ unfold map iterate nth, dsimp,
unfold map iterate nth at ih, dsimp at ih,
rw ih }
end
section corec
theorem corec_def (f : α → β) (g : α → α) (a : α) : corec f g a = map f (iterate g a) := rfl
theorem corec_eq (f : α → β) (g : α → α) (a : α) : corec f g a = f a :: corec f g (g a) :=
begin rw [corec_def, map_eq, head_iterate, tail_iterate], refl end
theorem corec_id_id_eq_const (a : α) : corec id id a = const a :=
by rw [corec_def, map_id, iterate_id]
theorem corec_id_f_eq_iterate (f : α → α) (a : α) : corec id f a = iterate f a := rfl
end corec
section corec'
theorem corec'_eq (f : α → β × α) (a : α) : corec' f a = (f a).1 :: corec' f (f a).2 :=
corec_eq _ _ _
end corec'
theorem unfolds_eq (g : α → β) (f : α → α) (a : α) : unfolds g f a = g a :: unfolds g f (f a) :=
begin unfold unfolds, rw [corec_eq] end
theorem nth_unfolds_head_tail : ∀ (n : nat) (s : stream α), nth (unfolds head tail s) n = nth s n :=
begin
intro n, induction n with n' ih,
{ intro s, refl },
{ intro s, rw [nth_succ, nth_succ, unfolds_eq, tail_cons, ih] }
end
theorem unfolds_head_eq : ∀ (s : stream α), unfolds head tail s = s :=
λ s, stream.ext (λ n, nth_unfolds_head_tail n s)
theorem interleave_eq (s₁ s₂ : stream α) : s₁ ⋈ s₂ = head s₁ :: head s₂ :: (tail s₁ ⋈ tail s₂) :=
begin
unfold interleave corec_on, rw corec_eq, dsimp, rw corec_eq, refl
end
theorem tail_interleave (s₁ s₂ : stream α) : tail (s₁ ⋈ s₂) = s₂ ⋈ (tail s₁) :=
begin unfold interleave corec_on, rw corec_eq, refl end
theorem interleave_tail_tail (s₁ s₂ : stream α) : tail s₁ ⋈ tail s₂ = tail (tail (s₁ ⋈ s₂)) :=
begin rw [interleave_eq s₁ s₂], refl end
theorem nth_interleave_left : ∀ (n : nat) (s₁ s₂ : stream α), nth (s₁ ⋈ s₂) (2 * n) = nth s₁ n
| 0 s₁ s₂ := rfl
| (succ n) s₁ s₂ :=
begin
change nth (s₁ ⋈ s₂) (succ (succ (2*n))) = nth s₁ (succ n),
rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_left],
refl
end
theorem nth_interleave_right : ∀ (n : nat) (s₁ s₂ : stream α), nth (s₁ ⋈ s₂) (2*n+1) = nth s₂ n
| 0 s₁ s₂ := rfl
| (succ n) s₁ s₂ :=
begin
change nth (s₁ ⋈ s₂) (succ (succ (2*n+1))) = nth s₂ (succ n),
rw [nth_succ, nth_succ, interleave_eq, tail_cons, tail_cons, nth_interleave_right],
refl
end
theorem mem_interleave_left {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₁ → a ∈ s₁ ⋈ s₂ :=
assume ⟨n, h⟩,
exists.intro (2*n) (by rw [h, nth_interleave_left])
theorem mem_interleave_right {a : α} {s₁ : stream α} (s₂ : stream α) : a ∈ s₂ → a ∈ s₁ ⋈ s₂ :=
assume ⟨n, h⟩,
exists.intro (2*n+1) (by rw [h, nth_interleave_right])
theorem odd_eq (s : stream α) : odd s = even (tail s) := rfl
theorem head_even (s : stream α) : head (even s) = head s := rfl
theorem tail_even (s : stream α) : tail (even s) = even (tail (tail s)) :=
begin unfold even, rw corec_eq, refl end
theorem even_cons_cons (a₁ a₂ : α) (s : stream α) : even (a₁ :: a₂ :: s) = a₁ :: even s :=
begin unfold even, rw corec_eq, refl end
theorem even_tail (s : stream α) : even (tail s) = odd s := rfl
theorem even_interleave (s₁ s₂ : stream α) : even (s₁ ⋈ s₂) = s₁ :=
eq_of_bisim
(λ s₁' s₁, ∃ s₂, s₁' = even (s₁ ⋈ s₂))
(λ s₁' s₁ ⟨s₂, h₁⟩,
begin
rw h₁,
constructor,
{refl},
{exact ⟨tail s₂, by rw [interleave_eq, even_cons_cons, tail_cons]⟩}
end)
(exists.intro s₂ rfl)
theorem interleave_even_odd (s₁ : stream α) : even s₁ ⋈ odd s₁ = s₁ :=
eq_of_bisim
(λ s' s, s' = even s ⋈ odd s)
(λ s' s (h : s' = even s ⋈ odd s),
begin
rw h, constructor,
{refl},
{simp [odd_eq, odd_eq, tail_interleave, tail_even]}
end)
rfl
theorem nth_even : ∀ (n : nat) (s : stream α), nth (even s) n = nth s (2*n)
| 0 s := rfl
| (succ n) s :=
begin
change nth (even s) (succ n) = nth s (succ (succ (2 * n))),
rw [nth_succ, nth_succ, tail_even, nth_even], refl
end
theorem nth_odd : ∀ (n : nat) (s : stream α), nth (odd s) n = nth s (2 * n + 1) :=
λ n s, begin rw [odd_eq, nth_even], refl end
theorem mem_of_mem_even (a : α) (s : stream α) : a ∈ even s → a ∈ s :=
assume ⟨n, h⟩,
exists.intro (2*n) (by rw [h, nth_even])
theorem mem_of_mem_odd (a : α) (s : stream α) : a ∈ odd s → a ∈ s :=
assume ⟨n, h⟩,
exists.intro (2*n+1) (by rw [h, nth_odd])
theorem nil_append_stream (s : stream α) : append_stream [] s = s := rfl
theorem cons_append_stream (a : α) (l : list α) (s : stream α) :
append_stream (a::l) s = a :: append_stream l s := rfl
theorem append_append_stream :
∀ (l₁ l₂ : list α) (s : stream α), (l₁ ++ l₂) ++ₛ s = l₁ ++ₛ (l₂ ++ₛ s)
| [] l₂ s := rfl
| (list.cons a l₁) l₂ s := by rw [list.cons_append, cons_append_stream, cons_append_stream,
append_append_stream]
theorem map_append_stream (f : α → β) :
∀ (l : list α) (s : stream α), map f (l ++ₛ s) = list.map f l ++ₛ map f s
| [] s := rfl
| (list.cons a l) s := by rw [cons_append_stream, list.map_cons, map_cons, cons_append_stream,
map_append_stream]
theorem drop_append_stream : ∀ (l : list α) (s : stream α), drop l.length (l ++ₛ s) = s
| [] s := by refl
| (list.cons a l) s := by rw [list.length_cons, add_one, drop_succ, cons_append_stream, tail_cons,
drop_append_stream]
theorem append_stream_head_tail (s : stream α) : [head s] ++ₛ tail s = s :=
by rw [cons_append_stream, nil_append_stream, stream.eta]
theorem mem_append_stream_right : ∀ {a : α} (l : list α) {s : stream α}, a ∈ s → a ∈ l ++ₛ s
| a [] s h := h
| a (list.cons b l) s h :=
have ih : a ∈ l ++ₛ s, from mem_append_stream_right l h,
mem_cons_of_mem _ ih
theorem mem_append_stream_left : ∀ {a : α} {l : list α} (s : stream α), a ∈ l → a ∈ l ++ₛ s
| a [] s h := absurd h (list.not_mem_nil _)
| a (list.cons b l) s h :=
or.elim (list.eq_or_mem_of_mem_cons h)
(λ (aeqb : a = b), exists.intro 0 aeqb)
(λ (ainl : a ∈ l), mem_cons_of_mem b (mem_append_stream_left s ainl))
@[simp] theorem take_zero (s : stream α) : take 0 s = [] := rfl
@[simp] theorem take_succ (n : nat) (s : stream α) :
take (succ n) s = head s :: take n (tail s) := rfl
@[simp] theorem length_take (n : ℕ) (s : stream α) : (take n s).length = n :=
by induction n generalizing s; simp *
theorem nth_take_succ : ∀ (n : nat) (s : stream α), list.nth (take (succ n) s) n = some (nth s n)
| 0 s := rfl
| (n+1) s := begin rw [take_succ, add_one, list.nth, nth_take_succ], refl end
theorem append_take_drop :
∀ (n : nat) (s : stream α), append_stream (take n s) (drop n s) = s :=
begin
intro n,
induction n with n' ih,
{ intro s, refl },
{ intro s, rw [take_succ, drop_succ, cons_append_stream, ih (tail s), stream.eta] }
end
-- Take theorem reduces a proof of equality of infinite streams to an
-- induction over all their finite approximations.
theorem take_theorem (s₁ s₂ : stream α) : (∀ (n : nat), take n s₁ = take n s₂) → s₁ = s₂ :=
begin
intro h, apply stream.ext, intro n,
induction n with n ih,
{ have aux := h 1, simp [take] at aux, exact aux },
{ have h₁ : some (nth s₁ (succ n)) = some (nth s₂ (succ n)),
{ rw [← nth_take_succ, ← nth_take_succ, h (succ (succ n))] },
injection h₁ }
end
protected lemma cycle_g_cons (a : α) (a₁ : α) (l₁ : list α) (a₀ : α) (l₀ : list α) :
stream.cycle_g (a, a₁::l₁, a₀, l₀) = (a₁, l₁, a₀, l₀) := rfl
theorem cycle_eq : ∀ (l : list α) (h : l ≠ []), cycle l h = l ++ₛ cycle l h
| [] h := absurd rfl h
| (list.cons a l) h :=
have gen : ∀ l' a', corec stream.cycle_f stream.cycle_g (a', l', a, l) =
(a' :: l') ++ₛ corec stream.cycle_f stream.cycle_g (a, l, a, l),
begin
intro l',
induction l' with a₁ l₁ ih,
{intros, rw [corec_eq], refl},
{intros, rw [corec_eq, stream.cycle_g_cons, ih a₁], refl}
end,
gen l a
theorem mem_cycle {a : α} {l : list α} : ∀ (h : l ≠ []), a ∈ l → a ∈ cycle l h :=
assume h ainl, begin rw [cycle_eq], exact mem_append_stream_left _ ainl end
theorem cycle_singleton (a : α) (h : [a] ≠ []) : cycle [a] h = const a :=
coinduction
rfl
(λ β fr ch, by rwa [cycle_eq, const_eq])
theorem tails_eq (s : stream α) : tails s = tail s :: tails (tail s) :=
by unfold tails; rw [corec_eq]; refl
theorem nth_tails : ∀ (n : nat) (s : stream α), nth (tails s) n = drop n (tail s) :=
begin
intro n, induction n with n' ih,
{ intros, refl },
{ intro s, rw [nth_succ, drop_succ, tails_eq, tail_cons, ih] }
end
theorem tails_eq_iterate (s : stream α) : tails s = iterate tail (tail s) := rfl
theorem inits_core_eq (l : list α) (s : stream α) :
inits_core l s = l :: inits_core (l ++ [head s]) (tail s) :=
begin unfold inits_core corec_on, rw [corec_eq], refl end
theorem tail_inits (s : stream α) :
tail (inits s) = inits_core [head s, head (tail s)] (tail (tail s)) :=
begin unfold inits, rw inits_core_eq, refl end
theorem inits_tail (s : stream α) :
inits (tail s) = inits_core [head (tail s)] (tail (tail s)) := rfl
theorem cons_nth_inits_core : ∀ (a : α) (n : nat) (l : list α) (s : stream α),
a :: nth (inits_core l s) n = nth (inits_core (a::l) s) n :=
begin
intros a n,
induction n with n' ih,
{ intros, refl },
{ intros l s, rw [nth_succ, inits_core_eq, tail_cons, ih, inits_core_eq (a::l) s], refl }
end
theorem nth_inits : ∀ (n : nat) (s : stream α), nth (inits s) n = take (succ n) s :=
begin
intro n, induction n with n' ih,
{ intros, refl },
{ intros, rw [nth_succ, take_succ, ← ih, tail_inits, inits_tail, cons_nth_inits_core] }
end
theorem inits_eq (s : stream α) : inits s = [head s] :: map (list.cons (head s)) (inits (tail s)) :=
begin
apply stream.ext, intro n,
cases n,
{ refl },
{ rw [nth_inits, nth_succ, tail_cons, nth_map, nth_inits], refl }
end
theorem zip_inits_tails (s : stream α) : zip append_stream (inits s) (tails s) = const s :=
begin
apply stream.ext, intro n,
rw [nth_zip, nth_inits, nth_tails, nth_const, take_succ,
cons_append_stream, append_take_drop, stream.eta]
end
theorem identity (s : stream α) : pure id ⊛ s = s := rfl
theorem composition (g : stream (β → δ)) (f : stream (α → β)) (s : stream α) :
pure comp ⊛ g ⊛ f ⊛ s = g ⊛ (f ⊛ s) := rfl
theorem homomorphism (f : α → β) (a : α) : pure f ⊛ pure a = pure (f a) := rfl
theorem interchange (fs : stream (α → β)) (a : α) :
fs ⊛ pure a = pure (λ f : α → β, f a) ⊛ fs := rfl
theorem map_eq_apply (f : α → β) (s : stream α) : map f s = pure f ⊛ s := rfl
theorem nth_nats (n : nat) : nth nats n = n := rfl
theorem nats_eq : nats = 0 :: map succ nats :=
begin
apply stream.ext, intro n,
cases n, refl, rw [nth_succ], refl
end
end stream
|
73a8e8afd391e8be97a5d5cac6d3a045401e7ea9 | 26bff4ed296b8373c92b6b025f5d60cdf02104b9 | /tests/lean/run/vector.lean | ad84cbfe9c0c26cc98de0e93059e31a1ab30a357 | [
"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 | 4,890 | lean | import logic data.nat.basic data.prod data.unit
open nat prod
inductive vector (A : Type) : nat → Type :=
| vnil {} : vector A zero
| vcons : Π {n : nat}, A → vector A n → vector A (succ n)
namespace vector
-- print definition no_confusion
infixr `::` := vcons
local abbreviation no_confusion := @vector.no_confusion
local abbreviation below := @vector.below
theorem vcons.inj₁ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → a₁ = a₂ :=
begin
intro h, apply (no_confusion h), intros, assumption
end
theorem vcons.inj₂ {A : Type} {n : nat} (a₁ a₂ : A) (v₁ v₂ : vector A n) : vcons a₁ v₁ = vcons a₂ v₂ → v₁ = v₂ :=
begin
intro h, apply heq.to_eq, apply (no_confusion h), intros, eassumption,
end
set_option pp.universes true
check @below
namespace manual
section
universe variables l₁ l₂
variable {A : Type.{l₁}}
variable {C : Π (n : nat), vector A n → Type.{l₂}}
definition brec_on {n : nat} (v : vector A n) (H : Π (n : nat) (v : vector A n), @vector.below A C n v → C n v) : C n v :=
have general : C n v × @vector.below A C n v, from
vector.rec_on v
(pair (H zero vnil unit.star) unit.star)
(λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (r₁ : C n₁ v₁ × @vector.below A C n₁ v₁),
have b : @vector.below A C _ (vcons a₁ v₁), from
r₁,
have c : C (succ n₁) (vcons a₁ v₁), from
H (succ n₁) (vcons a₁ v₁) b,
pair c b),
pr₁ general
end
end manual
-- check vector.brec_on
definition bw := @below
definition sum {n : nat} (v : vector nat n) : nat :=
vector.brec_on v (λ (n : nat) (v : vector nat n),
vector.cases_on v
(λ (B : bw vnil), zero)
(λ (n₁ : nat) (a : nat) (v₁ : vector nat n₁) (B : bw (vcons a v₁)),
a + pr₁ B))
example : sum (10 :: 20 :: vnil) = 30 :=
rfl
definition addk {n : nat} (v : vector nat n) (k : nat) : vector nat n :=
vector.brec_on v (λ (n : nat) (v : vector nat n),
vector.cases_on v
(λ (B : bw vnil), vnil)
(λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)),
vcons (a₁+k) (pr₁ B)))
example : addk (1 :: 2 :: vnil) 3 = 4 :: 5 :: vnil :=
rfl
definition append.{l} {A : Type.{l+1}} {n m : nat} (w : vector A m) (v : vector A n) : vector A (n + m) :=
vector.brec_on w (λ (n : nat) (w : vector A n),
vector.cases_on w
(λ (B : bw vnil), v)
(λ (n₁ : nat) (a₁ : A) (v₁ : vector A n₁) (B : bw (vcons a₁ v₁)),
vcons a₁ (pr₁ B)))
example : append (1 :: 2 :: vnil) (3 :: vnil) = 1 :: 2 :: 3 :: vnil :=
rfl
definition head {A : Type} {n : nat} (v : vector A (succ n)) : A :=
vector.cases_on v
(λ H : succ n = 0, nat.no_confusion H)
(λn' h t (H : succ n = succ n'), h)
rfl
definition tail {A : Type} {n : nat} (v : vector A (succ n)) : vector A n :=
@vector.cases_on A (λn' v, succ n = n' → vector A (pred n')) (succ n) v
(λ H : succ n = 0, nat.no_confusion H)
(λ (n' : nat) (h : A) (t : vector A n') (H : succ n = succ n'),
t)
rfl
definition add {n : nat} (w v : vector nat n) : vector nat n :=
@vector.brec_on nat (λ (n : nat) (v : vector nat n), vector nat n → vector nat n) n w
(λ (n : nat) (w : vector nat n),
vector.cases_on w
(λ (B : bw vnil) (w : vector nat zero), vnil)
(λ (n₁ : nat) (a₁ : nat) (v₁ : vector nat n₁) (B : bw (vcons a₁ v₁)) (v : vector nat (succ n₁)),
vcons (a₁ + head v) (pr₁ B (tail v)))) v
example : add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil :=
rfl
definition map {A B C : Type} {n : nat} (f : A → B → C) (w : vector A n) (v : vector B n) : vector C n :=
let P := λ (n : nat) (v : vector A n), vector B n → vector C n in
@vector.brec_on A P n w
(λ (n : nat) (w : vector A n),
begin
cases w with (n₁, h₁, t₁),
show @below A P zero vnil → vector B zero → vector C zero, from
λ b v, vnil,
show @below A P (succ n₁) (h₁ :: t₁) → vector B (succ n₁) → vector C (succ n₁), from
λ b v,
begin
cases v with (n₂, h₂, t₂),
have r : vector B n₂ → vector C n₂, from pr₁ b,
exact ((f h₁ h₂) :: r t₂),
end
end) v
theorem map_nil_nil {A B C : Type} (f : A → B → C) : map f vnil vnil = vnil :=
rfl
theorem map_cons_cons {A B C : Type} (f : A → B → C) (a : A) (b : B) {n : nat} (va : vector A n) (vb : vector B n) :
map f (a :: va) (b :: vb) = f a b :: map f va vb :=
rfl
example : map nat.add (1 :: 2 :: vnil) (3 :: 5 :: vnil) = 4 :: 7 :: vnil :=
rfl
print definition map
end vector
|
5c2f4c1d94236cda16fe579fb24376295eaf88b8 | 584b714300690a5778b5de6cc00658b00d51a434 | /hws/assn0/assn0.lean | 4e70af2b72616d229982786c4ee02bbec0f3e04a | [] | no_license | cjmazey/practical-foundations-for-programming-languages | c11966b278ec51d26a257c43f753d79521227e25 | 0d498d7993d527c1002ee835616f3fe94f223a06 | refs/heads/master | 1,610,286,208,083 | 1,445,537,235,000 | 1,445,537,235,000 | 44,196,272 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 6,034 | lean | /- 15-312 Principles of Programming Languages
Assignment 0: Rule Induction
-/
import standard
/- 2 Shuffling cards -/
inductive card : Type :=
| heart : card
| spade : card
| club : card
| diamond : card
namespace card
notation `♡` := heart
notation `♠` := spade
notation `♣` := club
notation `♢` := diamond
end card
inductive stack : Type :=
| nil : stack
| cons : card → stack → stack
namespace stack
notation h :: t := cons h t
notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l
inductive unshuffle : stack → stack → stack → Prop :=
| intro_nil : unshuffle [] [] []
| intro_right : ∀ {c s₁ s₂ s₃},
unshuffle s₁ s₂ s₃ → unshuffle (c :: s₁) s₂ (c :: s₃)
| intro_left : ∀ {c s₁ s₂ s₃},
unshuffle s₁ s₂ s₃ → unshuffle (c :: s₁) (c :: s₂) s₃
namespace unshuffle
notation `🂠🂠🂠` := intro_nil
notation `🂡🂠🂡` := intro_right
notation `🂡🂡🂠` := intro_left
end unshuffle
end stack
/- Task 2.1 -/
section
open card stack stack.unshuffle function
example : unshuffle [♡, ♠, ♠, ♢] [♠, ♢] [♡, ♠] :=
🂡🂠🂡 $ 🂡🂡🂠 $ 🂡🂠🂡 $ 🂡🂡🂠 $ 🂠🂠🂠
end
/- Task 2.2 -/
section
open card stack stack.unshuffle function
example : unshuffle [♡, ♠, ♠, ♢] [♠, ♢] [♡, ♠] :=
🂡🂠🂡 $ 🂡🂠🂡 $ 🂡🂡🂠 $ 🂡🂡🂠 $ 🂠🂠🂠
end
/- Task 2.3 -/
section
open card stack stack.unshuffle
example : ∀ s₁, ∃ s₂ s₃, unshuffle s₁ s₂ s₃ :=
take s₁,
stack.induction_on s₁
(exists.intro [] (exists.intro [] 🂠🂠🂠))
(take c s₁' IH,
obtain s₂ s₃ IH', from IH,
exists.intro s₂ (exists.intro (c :: s₃) (🂡🂠🂡 IH')))
end
/- Task 2.4 -/
namespace stack
open card
inductive seperate : stack → stack → stack → Prop :=
| intro_nil : seperate [] [] []
| intro_spade : ∀ {s₁ s₂ s₃},
seperate s₁ s₂ s₃ → seperate (♠ :: s₁) s₂ (♠ :: s₃)
| intro_club : ∀ {s₁ s₂ s₃},
seperate s₁ s₂ s₃ → seperate (♣ :: s₁) s₂ (♣ :: s₃)
| intro_heart : ∀ {s₁ s₂ s₃},
seperate s₁ s₂ s₃ → seperate (♡ :: s₁) (♡ :: s₂) s₃
| intro_diamond : ∀ {s₁ s₂ s₃},
seperate s₁ s₂ s₃ → seperate (♢ :: s₁) (♢ :: s₂) s₃
end stack
section
open card stack stack.seperate function
example : seperate [♡, ♢, ♠] [♡, ♢] [♠] :=
intro_heart $ intro_diamond $ intro_spade $ intro_nil
example : seperate [♠, ♢, ♣, ♡] [♢, ♡] [♠, ♣] :=
intro_spade $ intro_diamond $ intro_club $ intro_heart $ intro_nil
example : seperate [♣, ♡, ♣, ♠] [♡] [♣, ♣, ♠] :=
intro_club $ intro_heart $ intro_club $ intro_spade $ intro_nil
example : ¬seperate [♡, ♠] [♡, ♠] [] := sorry
example : ¬seperate [♡, ♢] [♢, ♡] [] := sorry
end
/- Task 2.5
It means s₁ uniquely determines s₂ and s₃ (and they always exist.)
"unshuffle" does not have this mode because in its case they are
not unique (e.g. Task 2.2.)
-/
section
open card stack stack.seperate
example : ∀ s₁, ∃! s₂ s₃, seperate s₁ s₂ s₃ := sorry
end
/- 3 Cutting cards -/
namespace stack
inductive even : stack → Prop :=
| nil : even []
| cons : ∀ c s, odd s → even (c :: s)
with odd : stack → Prop :=
| cons : ∀ c s, even s → odd (c :: s)
end stack
/- Task 3.1 -/
section
open stack
check @even.induction_on
check @odd.induction_on
end
/- Task 3.2
This seems quite impossible? The following is not exactly a proof.
-/
namespace stack
inductive is_a_stack : stack → Prop :=
| of_course_it_is : ∀ s, is_a_stack s
example : ∀ s, even s → is_a_stack s := sorry
end stack
/- Task 3.3 -/
namespace stack
theorem even.induction_even :
∀ {S : stack → Prop},
S [] →
(∀ c₁ c₂ s, S s → S (c₁ :: c₂ :: s)) →
∀ s, even s → S s :=
λ S IB IH,
λ s `even s`,
@even.induction_on (λ s, S s) (λ s, ∀ c, S (c :: s)) s `even s`
IB
(λ c s `_` H, H c)
(λ c₂ s `even s` `S s` c₁, IH c₁ c₂ s `S s`)
end stack
/- Task 3.4 -/
namespace stack
inductive cut : stack → stack → stack → Prop :=
| nil : ∀ s, cut s s []
| cons : ∀ c s₁ s₂ s₃, cut s₁ s₂ s₃ → cut (c :: s₁) s₂ (c :: s₃)
namespace cut
premise inversion_nil : ∀ s₁ s₂, cut s₁ s₂ [] → s₁ = s₂
premise inversion_cons : ∀ c s₁ s₂ s₃,
cut s₁ s₂ (c :: s₃) →
∃ s₁', s₁ = (c :: s₁') ∧ cut s₁' s₂ s₃
example : ∀ s₁ s₂ s₃, even s₂ → even s₃ → cut s₁ s₂ s₃ → even s₁ :=
have H : ∀ s₃, even s₃ → ∀ s₁ s₂, even s₂ → cut s₁ s₂ s₃ → even s₁, from
even.induction_even
(take s₁ s₂,
assume He₂ Hc,
have s₁ = s₂, from inversion_nil s₁ s₂ Hc,
eq.subst (eq.symm this) He₂)
(take c₁ c₂ s,
assume IH,
take s₁ s₂,
assume He₂ Hc,
obtain s₁' Es₁', from inversion_cons _ _ _ _ Hc,
obtain s₁'' Es₁'', from inversion_cons _ _ _ _ (and.right Es₁'),
have even s₁'', from IH s₁'' s₂ He₂ (and.right Es₁''),
have s₁ = c₁ :: s₁', from and.left Es₁',
have s₁' = c₂ :: s₁'', from and.left Es₁'',
have s₁ = c₁ :: c₂ :: s₁'', from eq.subst `s₁' = c₂ :: s₁''` `s₁ = c₁ :: s₁'`,
have even (c₁ :: c₂ :: s₁''), from even.cons c₁ _ (odd.cons c₂ s₁'' `even s₁''`),
eq.subst (eq.symm `s₁ = c₁ :: c₂ :: s₁''`) this),
λ s₁ s₂ s₃ He₂ He₃, H s₃ He₃ s₁ s₂ He₂
end cut
end stack
|
c6064f5b87372d31264d1ba872f0ea096807cc57 | e953c38599905267210b87fb5d82dcc3e52a4214 | /hott/init/pathover.hlean | 4454334f437d0e396802d48add4898914a2c5b3a | [
"Apache-2.0"
] | permissive | c-cube/lean | 563c1020bff98441c4f8ba60111fef6f6b46e31b | 0fb52a9a139f720be418dafac35104468e293b66 | refs/heads/master | 1,610,753,294,113 | 1,440,451,356,000 | 1,440,499,588,000 | 41,748,334 | 0 | 0 | null | 1,441,122,656,000 | 1,441,122,656,000 | null | UTF-8 | Lean | false | false | 9,463 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Basic theorems about pathovers
-/
prelude
import .path .equiv
open equiv is_equiv equiv.ops
variables {A A' : Type} {B B' : A → Type} {C : Πa, B a → Type}
{a a₂ a₃ a₄ : A} {p p' : a = a₂} {p₂ : a₂ = a₃} {p₃ : a₃ = a₄}
{b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄}
{c : C a b} {c₂ : C a₂ b₂}
namespace eq
inductive pathover.{l} (B : A → Type.{l}) (b : B a) : Π{a₂ : A}, a = a₂ → B a₂ → Type.{l} :=
idpatho : pathover B b (refl a) b
notation b `=[`:50 p:0 `]`:0 b₂:50 := pathover _ b p b₂
definition idpo [reducible] [constructor] : b =[refl a] b :=
pathover.idpatho b
/- equivalences with equality using transport -/
definition pathover_of_tr_eq (r : p ▸ b = b₂) : b =[p] b₂ :=
by cases p; cases r; exact idpo
definition pathover_of_eq_tr (r : b = p⁻¹ ▸ b₂) : b =[p] b₂ :=
by cases p; cases r; exact idpo
definition tr_eq_of_pathover [unfold 8] (r : b =[p] b₂) : p ▸ b = b₂ :=
by cases r; exact idp
definition eq_tr_of_pathover [unfold 8] (r : b =[p] b₂) : b = p⁻¹ ▸ b₂ :=
by cases r; exact idp
definition pathover_equiv_tr_eq [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂)
: (b =[p] b₂) ≃ (p ▸ b = b₂) :=
begin
fapply equiv.MK,
{ exact tr_eq_of_pathover},
{ exact pathover_of_tr_eq},
{ intro r, cases p, cases r, apply idp},
{ intro r, cases r, apply idp},
end
definition pathover_equiv_eq_tr [constructor] (p : a = a₂) (b : B a) (b₂ : B a₂)
: (b =[p] b₂) ≃ (b = p⁻¹ ▸ b₂) :=
begin
fapply equiv.MK,
{ exact eq_tr_of_pathover},
{ exact pathover_of_eq_tr},
{ intro r, cases p, cases r, apply idp},
{ intro r, cases r, apply idp},
end
definition pathover_tr [unfold 5] (p : a = a₂) (b : B a) : b =[p] p ▸ b :=
by cases p;exact idpo
definition tr_pathover [unfold 5] (p : a = a₂) (b : B a₂) : p⁻¹ ▸ b =[p] b :=
by cases p;exact idpo
definition concato [unfold 12] (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) : b =[p ⬝ p₂] b₃ :=
pathover.rec_on r₂ r
definition inverseo [unfold 8] (r : b =[p] b₂) : b₂ =[p⁻¹] b :=
pathover.rec_on r idpo
definition apdo [unfold 6] (f : Πa, B a) (p : a = a₂) : f a =[p] f a₂ :=
eq.rec_on p idpo
definition oap [unfold 6] {C : A → Type} (f : Πa, B a → C a) (p : a = a₂) : f a =[p] f a₂ :=
eq.rec_on p idpo
definition concato_eq [unfold 10] (r : b =[p] b₂) (q : b₂ = b₂') : b =[p] b₂' :=
eq.rec_on q r
definition eq_concato [unfold 9] (q : b = b') (r : b' =[p] b₂) : b =[p] b₂ :=
by induction q;exact r
-- infix `⬝` := concato
infix `⬝o`:75 := concato
infix `⬝op`:75 := concato_eq
infix `⬝po`:75 := eq_concato
-- postfix `⁻¹` := inverseo
postfix `⁻¹ᵒ`:(max+10) := inverseo
/- Some of the theorems analogous to theorems for = in init.path -/
definition cono_idpo (r : b =[p] b₂) : r ⬝o idpo =[con_idp p] r :=
pathover.rec_on r idpo
definition idpo_cono (r : b =[p] b₂) : idpo ⬝o r =[idp_con p] r :=
pathover.rec_on r idpo
definition cono.assoc' (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) :
r ⬝o (r₂ ⬝o r₃) =[!con.assoc'] (r ⬝o r₂) ⬝o r₃ :=
pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo))
definition cono.assoc (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃) (r₃ : b₃ =[p₃] b₄) :
(r ⬝o r₂) ⬝o r₃ =[!con.assoc] r ⬝o (r₂ ⬝o r₃) :=
pathover.rec_on r₃ (pathover.rec_on r₂ (pathover.rec_on r idpo))
definition cono.right_inv (r : b =[p] b₂) : r ⬝o r⁻¹ᵒ =[!con.right_inv] idpo :=
pathover.rec_on r idpo
definition cono.left_inv (r : b =[p] b₂) : r⁻¹ᵒ ⬝o r =[!con.left_inv] idpo :=
pathover.rec_on r idpo
definition eq_of_pathover {a' a₂' : A'} (q : a' =[p] a₂') : a' = a₂' :=
by cases q;reflexivity
definition pathover_of_eq {a' a₂' : A'} (q : a' = a₂') : a' =[p] a₂' :=
by cases p;cases q;exact idpo
definition pathover_constant [constructor] (p : a = a₂) (a' a₂' : A') : a' =[p] a₂' ≃ a' = a₂' :=
begin
fapply equiv.MK,
{ exact eq_of_pathover},
{ exact pathover_of_eq},
{ intro r, cases p, cases r, exact idp},
{ intro r, cases r, exact idp},
end
definition eq_of_pathover_idp [unfold 6] {b' : B a} (q : b =[idpath a] b') : b = b' :=
tr_eq_of_pathover q
--should B be explicit in the next two definitions?
definition pathover_idp_of_eq [unfold 6] {b' : B a} (q : b = b') : b =[idpath a] b' :=
pathover_of_tr_eq q
definition pathover_idp [constructor] (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' :=
equiv.MK eq_of_pathover_idp
(pathover_idp_of_eq)
(to_right_inv !pathover_equiv_tr_eq)
(to_left_inv !pathover_equiv_tr_eq)
-- definition pathover_idp (b : B a) (b' : B a) : b =[idpath a] b' ≃ b = b' :=
-- pathover_equiv_tr_eq idp b b'
-- definition eq_of_pathover_idp [reducible] {b' : B a} (q : b =[idpath a] b') : b = b' :=
-- to_fun !pathover_idp q
-- definition pathover_idp_of_eq [reducible] {b' : B a} (q : b = b') : b =[idpath a] b' :=
-- to_inv !pathover_idp q
definition idp_rec_on [recursor] {P : Π⦃b₂ : B a⦄, b =[idpath a] b₂ → Type}
{b₂ : B a} (r : b =[idpath a] b₂) (H : P idpo) : P r :=
have H2 : P (pathover_idp_of_eq (eq_of_pathover_idp r)), from
eq.rec_on (eq_of_pathover_idp r) H,
proof left_inv !pathover_idp r ▸ H2 qed
definition rec_on_right [recursor] {P : Π⦃b₂ : B a₂⦄, b =[p] b₂ → Type}
{b₂ : B a₂} (r : b =[p] b₂) (H : P !pathover_tr) : P r :=
by cases r; exact H
definition rec_on_left [recursor] {P : Π⦃b : B a⦄, b =[p] b₂ → Type}
{b : B a} (r : b =[p] b₂) (H : P !tr_pathover) : P r :=
by cases r; exact H
--pathover with fibration B' ∘ f
definition pathover_ap [unfold 10] (B' : A' → Type) (f : A → A') {p : a = a₂}
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) : b =[ap f p] b₂ :=
by cases q; exact idpo
definition pathover_of_pathover_ap (B' : A' → Type) (f : A → A') {p : a = a₂}
{b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[ap f p] b₂) : b =[p] b₂ :=
by cases p; apply (idp_rec_on q); apply idpo
definition pathover_compose (B' : A' → Type) (f : A → A') (p : a = a₂)
(b : B' (f a)) (b₂ : B' (f a₂)) : b =[p] b₂ ≃ b =[ap f p] b₂ :=
begin
fapply equiv.MK,
{ apply pathover_ap},
{ apply pathover_of_pathover_ap},
{ intro q, cases p, esimp, apply (idp_rec_on q), apply idp},
{ intro q, cases q, exact idp},
end
definition apdo_con (f : Πa, B a) (p : a = a₂) (q : a₂ = a₃)
: apdo f (p ⬝ q) = apdo f p ⬝o apdo f q :=
by cases p; cases q; exact idp
definition apdo_inv (f : Πa, B a) (p : a = a₂) : apdo f p⁻¹ = (apdo f p)⁻¹ᵒ :=
by cases p; exact idp
definition apdo_eq_pathover_of_eq_ap (f : A → A') (p : a = a₂) :
apdo f p = pathover_of_eq (ap f p) :=
eq.rec_on p idp
definition pathover_of_pathover_tr (q : b =[p ⬝ p₂] p₂ ▸ b₂) : b =[p] b₂ :=
by cases p₂;exact q
definition pathover_tr_of_pathover {p : a = a₃} (q : b =[p ⬝ p₂⁻¹] b₂) : b =[p] p₂ ▸ b₂ :=
by cases p₂;exact q
definition pathover_tr_of_eq (q : b = b') : b =[p] p ▸ b' :=
by cases q;apply pathover_tr
definition tr_pathover_of_eq (q : b₂ = b₂') : p⁻¹ ▸ b₂ =[p] b₂' :=
by cases q;apply tr_pathover
definition apo011 (f : Πa, B a → A') (Ha : a = a₂) (Hb : b =[Ha] b₂)
: f a b = f a₂ b₂ :=
by cases Hb; exact idp
definition apo0111 (f : Πa b, C a b → A') (Ha : a = a₂) (Hb : b =[Ha] b₂)
(Hc : c =[apo011 C Ha Hb] c₂) : f a b c = f a₂ b₂ c₂ :=
by cases Hb; apply (idp_rec_on Hc); apply idp
definition apo11 {f : Πb, C a b} {g : Πb₂, C a₂ b₂} (r : f =[p] g)
{b : B a} {b₂ : B a₂} (q : b =[p] b₂) : f b =[apo011 C p q] g b₂ :=
by cases r; apply (idp_rec_on q); exact idpo
definition apo10 {f : Πb, C a b} {g : Πb₂, C a₂ b₂} (r : f =[p] g)
{b : B a} : f b =[apo011 C p !pathover_tr] g (p ▸ b) :=
by cases r; exact idpo
definition cono.right_inv_eq (q : b = b')
: concato_eq (pathover_idp_of_eq q) q⁻¹ = (idpo : b =[refl a] b) :=
by induction q;constructor
definition cono.right_inv_eq' (q : b = b')
: eq_concato q (pathover_idp_of_eq q⁻¹) = (idpo : b =[refl a] b) :=
by induction q;constructor
definition cono.left_inv_eq (q : b = b')
: concato_eq (pathover_idp_of_eq q⁻¹) q = (idpo : b' =[refl a] b') :=
by induction q;constructor
definition cono.left_inv_eq' (q : b = b')
: eq_concato q⁻¹ (pathover_idp_of_eq q) = (idpo : b' =[refl a] b') :=
by induction q;constructor
definition change_path [unfold 9] (q : p = p') (r : b =[p] b₂) : b =[p'] b₂ :=
by induction q;exact r
definition change_path_equiv (f : Π{a}, B a ≃ B' a) (r : b =[p] b₂) : f b =[p] f b₂ :=
by induction r;constructor
definition change_path_equiv' (f : Π{a}, B a ≃ B' a) (r : f b =[p] f b₂) : b =[p] b₂ :=
(left_inv f b)⁻¹ ⬝po change_path_equiv (λa, f⁻¹ᵉ) r ⬝op left_inv f b₂
end eq
|
213ccb4af4dfeecbf9214962e6bcc7473d2269e1 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/ring_theory/ideals.lean | 9916180dfb3f6618cca44441c6d95bb5b3e9080a | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 19,092 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes, Mario Carneiro
-/
import algebra.associated
import linear_algebra.basic
import order.zorn
universes u v
variables {α : Type u} {β : Type v} {a b : α}
open set function
open_locale classical big_operators
namespace ideal
variables [comm_ring α] (I : ideal α)
@[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J :=
submodule.ext h
theorem eq_top_of_unit_mem
(x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ :=
eq_top_iff.2 $ λ z _, calc
z = z * (y * x) : by simp [h]
... = (z * y) * x : eq.symm $ mul_assoc z y x
... ∈ I : I.mul_mem_left hx
theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ :=
let ⟨y, hy⟩ := is_unit_iff_exists_inv'.1 h in eq_top_of_unit_mem I x y hx hy
theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I :=
⟨by rintro rfl; trivial,
λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩
theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I :=
not_congr I.eq_top_iff_one
def span (s : set α) : ideal α := submodule.span α s
lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span
lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le
lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono
@[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _
@[simp] lemma span_singleton_one : span ({1} : set α) = ⊤ :=
(eq_top_iff_one _).2 $ subset_span $ mem_singleton _
lemma mem_span_insert {s : set α} {x y} :
x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert
lemma mem_span_insert' {s : set α} {x y} :
x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert'
lemma mem_span_singleton' {x y : α} :
x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton
lemma mem_span_singleton {x y : α} :
x ∈ span ({y} : set α) ↔ y ∣ x :=
mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm]
lemma span_singleton_le_span_singleton {x y : α} :
span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x :=
span_le.trans $ singleton_subset_iff.trans mem_span_singleton
lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot
lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot
lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x :=
by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, span_singleton_one, eq_top_iff]
@[class] def is_prime (I : ideal α) : Prop :=
I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I
theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) :
∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2
theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime)
{x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I :=
hI.2 (h.symm ▸ I.zero_mem)
theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime)
{r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I :=
begin
induction n with n ih,
{ exact (mt (eq_top_iff_one _).2 hI.1).elim H },
exact or.cases_on (hI.mem_or_mem H) id ih
end
theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 :=
λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem
theorem span_singleton_prime {p : α} (hp : p ≠ 0) :
is_prime (span ({p} : set α)) ↔ prime p :=
by simp [is_prime, prime, span_singleton_eq_top, hp, mem_span_singleton]
@[class] def is_maximal (I : ideal α) : Prop :=
I ≠ ⊤ ∧ ∀ J, I < J → J = ⊤
theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔
(1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J :=
and_congr I.ne_top_iff_one $ forall_congr $ λ J,
by rw [lt_iff_le_not_le]; exact
⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $
H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩,
λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in
J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩
theorem is_maximal.eq_of_le {I J : ideal α}
(hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J :=
eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.2 _ h)⟩
theorem is_maximal.exists_inv {I : ideal α}
(hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, y * x - 1 ∈ I :=
begin
cases is_maximal_iff.1 hI with H₁ H₂,
rcases mem_span_insert'.1 (H₂ (span (insert x I)) x
(set.subset.trans (subset_insert _ _) subset_span)
hx (subset_span (mem_insert _ _))) with ⟨y, hy⟩,
rw [span_eq, ← neg_mem_iff, add_comm, neg_add', neg_mul_eq_neg_mul] at hy,
exact ⟨-y, hy⟩
end
theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime :=
⟨H.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin
cases H.exists_inv hx with z hz,
have := I.mul_mem_left hz,
rw [mul_sub, mul_one, mul_comm, mul_assoc] at this,
exact I.neg_mem_iff.1 ((I.add_mem_iff_right $ I.mul_mem_left hxy).1 this)
end⟩
@[priority 100] -- see Note [lower instance priority]
instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime
theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) :
∃ M : ideal α, M.is_maximal ∧ I ≤ M :=
begin
rcases zorn.zorn_partial_order₀ { J : ideal α | J ≠ ⊤ } _ I hI with ⟨M, M0, IM, h⟩,
{ refine ⟨M, ⟨M0, λ J hJ, by_contradiction $ λ J0, _⟩, IM⟩,
cases h J J0 (le_of_lt hJ), exact lt_irrefl _ hJ },
{ intros S SC cC I IS,
refine ⟨Sup S, λ H, _, λ _, le_Sup⟩,
obtain ⟨J, JS, J0⟩ : ∃ J ∈ S, (1 : α) ∈ J,
from (submodule.mem_Sup_of_directed ⟨I, IS⟩ cC.directed_on).1 ((eq_top_iff_one _).1 H),
exact SC JS ((eq_top_iff_one _).2 J0) }
end
theorem mem_span_pair {x y z : α} :
z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z :=
by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z]
lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} :
span ({x} : set β) < span ({y} : set β) ↔ y ≠ 0 ∧ ∃ d : β, ¬ is_unit d ∧ x = y * d :=
by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton,
dvd_and_not_dvd_iff]
lemma factors_decreasing [integral_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) :
span ({b₁ * b₂} : set β) < span {b₁} :=
lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $
ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h,
h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $
by rwa [mul_one, ← ideal.span_singleton_le_span_singleton]
def quotient (I : ideal α) := I.quotient
namespace quotient
variables {I} {x y : α}
def mk (I : ideal α) (a : α) : I.quotient := submodule.quotient.mk a
protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I
instance (I : ideal α) : has_one I.quotient := ⟨mk I 1⟩
@[simp] lemma mk_one (I : ideal α) : mk I 1 = 1 := rfl
instance (I : ideal α) : has_mul I.quotient :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, mk I (a * b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin
refine calc a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ : _
... ∈ I : I.add_mem (I.mul_mem_left h₁) (I.mul_mem_right h₂),
rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁]
end⟩
@[simp] theorem mk_mul : mk I (x * y) = mk I x * mk I y := rfl
instance (I : ideal α) : comm_ring I.quotient :=
{ mul := (*),
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg (mk _) (mul_assoc a b c),
mul_comm := λ a b, quotient.induction_on₂' a b $
λ a b, congr_arg (mk _) (mul_comm a b),
one_mul := λ a, quotient.induction_on' a $
λ a, congr_arg (mk _) (one_mul a),
mul_one := λ a, quotient.induction_on' a $
λ a, congr_arg (mk _) (mul_one a),
left_distrib := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg (mk _) (left_distrib a b c),
right_distrib := λ a b c, quotient.induction_on₃' a b c $
λ a b c, congr_arg (mk _) (right_distrib a b c),
..submodule.quotient.add_comm_group I }
/-- `ideal.quotient.mk` as a `ring_hom` -/
def mk_hom (I : ideal α) : α →+* I.quotient := ⟨mk I, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩
lemma mk_eq_mk_hom (I : ideal α) (x : α) : ideal.quotient.mk I x = ideal.quotient.mk_hom I x := rfl
def map_mk (I J : ideal α) : ideal I.quotient :=
{ carrier := mk I '' J,
zero_mem' := ⟨0, J.zero_mem, rfl⟩,
add_mem' := by rintro _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩;
exact ⟨x + y, J.add_mem hx hy, rfl⟩,
smul_mem' := by rintro ⟨c⟩ _ ⟨x, hx, rfl⟩;
exact ⟨c * x, J.mul_mem_left hx, rfl⟩ }
@[simp] lemma mk_zero (I : ideal α) : mk I 0 = 0 := rfl
@[simp] lemma mk_add (I : ideal α) (a b : α) : mk I (a + b) = mk I a + mk I b := rfl
@[simp] lemma mk_neg (I : ideal α) (a : α) : mk I (-a : α) = -mk I a := rfl
@[simp] lemma mk_sub (I : ideal α) (a b : α) : mk I (a - b : α) = mk I a - mk I b := rfl
@[simp] lemma mk_pow (I : ideal α) (a : α) (n : ℕ) : mk I (a ^ n : α) = mk I a ^ n :=
(mk_hom I).map_pow a n
lemma mk_prod {ι} (I : ideal α) (s : finset ι) (f : ι → α) :
mk I (∏ i in s, f i) = ∏ i in s, mk I (f i) :=
(mk_hom I).map_prod f s
lemma mk_sum {ι} (I : ideal α) (s : finset ι) (f : ι → α) :
mk I (∑ i in s, f i) = ∑ i in s, mk I (f i) :=
(mk_hom I).map_sum f s
lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I :=
by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq'
theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ :=
eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm
theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ :=
not_congr zero_eq_one_iff
protected theorem nonzero {I : ideal α} (hI : I ≠ ⊤) : nonzero I.quotient :=
{ zero_ne_one := zero_ne_one_iff.2 hI }
instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b,
quotient.induction_on₂' a b $ λ a b hab,
(hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim
(or.inl ∘ eq_zero_iff_mem.2)
(or.inr ∘ eq_zero_iff_mem.2),
..quotient.nonzero hI.1,
..quotient.comm_ring I }
lemma exists_inv {I : ideal α} [hI : I.is_maximal] :
∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 :=
begin
rintro ⟨a⟩ h,
cases hI.exists_inv (mt eq_zero_iff_mem.2 h) with b hb,
rw [mul_comm] at hb,
exact ⟨mk _ b, quot.sound hb⟩
end
/-- quotient by maximal ideal is a field. def rather than instance, since users will have
computable inverses in some applications -/
protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient :=
{ inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha),
mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _,
by rw dif_neg ha;
exact classical.some_spec (exists_inv ha),
inv_zero := dif_pos rfl,
..quotient.integral_domain I }
variable [comm_ring β]
/-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero,
lift it to the quotient by this ideal. -/
def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) :
quotient S →+* β :=
{ to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _),
eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h],
map_one' := f.map_one,
map_zero' := f.map_zero,
map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add,
map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul }
@[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) :
lift S f H (mk S a) = f a := rfl
end quotient
section lattice
variables {R : Type u} [comm_ring R]
theorem mem_Inf {s : set (ideal R)} {x : R} :
x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I :=
⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩
end lattice
/-- All ideals in a field are trivial. -/
lemma eq_bot_or_top {K : Type u} [field K] (I : ideal K) :
I = ⊥ ∨ I = ⊤ :=
begin
rw classical.or_iff_not_imp_right,
change _ ≠ _ → _,
rw ideal.ne_top_iff_one,
intro h1,
rw eq_bot_iff,
intros r hr,
by_cases H : r = 0, {simpa},
simpa [H, h1] using submodule.smul_mem I r⁻¹ hr,
end
lemma eq_bot_of_prime {K : Type u} [field K] (I : ideal K) [h : I.is_prime] :
I = ⊥ :=
classical.or_iff_not_imp_right.mp I.eq_bot_or_top h.1
end ideal
/-- The set of non-invertible elements of a monoid. -/
def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a }
@[simp] theorem mem_nonunits_iff [comm_monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl
theorem mul_mem_nonunits_right [comm_monoid α] :
b ∈ nonunits α → a * b ∈ nonunits α :=
mt is_unit_of_mul_is_unit_right
theorem mul_mem_nonunits_left [comm_monoid α] :
a ∈ nonunits α → a * b ∈ nonunits α :=
mt is_unit_of_mul_is_unit_left
theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 :=
not_congr is_unit_zero_iff
@[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α :=
not_not_intro is_unit_one
theorem coe_subset_nonunits [comm_ring α] {I : ideal α} (h : I ≠ ⊤) :
(I : set α) ⊆ nonunits α :=
λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu
lemma exists_max_ideal_of_mem_nonunits [comm_ring α] (h : a ∈ nonunits α) :
∃ I : ideal α, I.is_maximal ∧ a ∈ I :=
begin
have : ideal.span ({a} : set α) ≠ ⊤,
{ intro H, rw ideal.span_singleton_eq_top at H, contradiction },
rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩,
use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a
end
section prio
set_option default_priority 100 -- see Note [default priority]
class local_ring (α : Type u) extends comm_ring α, nonzero α :=
(is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a)))
end prio
namespace local_ring
variable [local_ring α]
lemma is_unit_or_is_unit_one_sub_self (a : α) :
(is_unit a) ∨ (is_unit (1 - a)) :=
is_local a
lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) :
is_unit a :=
or_iff_not_imp_right.1 (is_local a) h
lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) :
is_unit (1 - a) :=
or_iff_not_imp_left.1 (is_local a) h
lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) :
x + y ∈ nonunits α :=
begin
rintros ⟨u, hu⟩,
apply hy,
suffices : is_unit ((↑u⁻¹ : α) * y),
{ rcases this with ⟨s, hs⟩,
use u * s,
convert congr_arg (λ z, (u : α) * z) hs,
rw ← mul_assoc, simp },
rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x),
{ rw eq_sub_iff_add_eq,
replace hu := congr_arg (λ z, (↑u⁻¹ : α) * z) hu.symm,
simpa [mul_add, add_comm] using hu },
apply is_unit_one_sub_self_of_mem_nonunits,
exact mul_mem_nonunits_right hx
end
variable (α)
/-- The ideal of elements that are not units. -/
def nonunits_ideal : ideal α :=
{ carrier := nonunits α,
zero_mem' := zero_mem_nonunits.2 $ zero_ne_one,
add_mem' := λ x y hx hy, nonunits_add hx hy,
smul_mem' := λ a x, mul_mem_nonunits_right }
instance nonunits_ideal.is_maximal : (nonunits_ideal α).is_maximal :=
begin
rw ideal.is_maximal_iff,
split,
{ intro h, apply h, exact is_unit_one },
{ intros I x hI hx H,
erw not_not at hx,
rcases hx with ⟨u,rfl⟩,
simpa using I.smul_mem ↑u⁻¹ H }
end
lemma max_ideal_unique :
∃! I : ideal α, I.is_maximal :=
⟨nonunits_ideal α, nonunits_ideal.is_maximal α,
λ I hI, hI.eq_of_le (nonunits_ideal.is_maximal α).1 $
λ x hx, hI.1 ∘ I.eq_top_of_is_unit_mem hx⟩
variable {α}
@[simp] lemma mem_nonunits_ideal (x) :
x ∈ nonunits_ideal α ↔ x ∈ nonunits α := iff.rfl
end local_ring
def is_local_ring (α : Type u) [comm_ring α] : Prop :=
((0:α) ≠ 1) ∧ ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a))
def local_of_is_local_ring [comm_ring α] (h : is_local_ring α) : local_ring α :=
{ zero_ne_one := h.1,
is_local := h.2,
.. ‹comm_ring α› }
def local_of_unit_or_unit_one_sub [comm_ring α] (hnze : (0:α) ≠ 1)
(h : ∀ x : α, is_unit x ∨ is_unit (1 - x)) : local_ring α :=
local_of_is_local_ring ⟨hnze, h⟩
def local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1)
(h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α :=
local_of_is_local_ring ⟨hnze,
λ x, or_iff_not_imp_left.mpr $ λ hx,
begin
by_contra H,
apply h _ _ hx H,
simp [-sub_eq_add_neg, add_sub_cancel'_right]
end⟩
def local_of_unique_max_ideal [comm_ring α] (h : ∃! I : ideal α, I.is_maximal) :
local_ring α :=
local_of_nonunits_ideal
(let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem))
$ λ x y hx hy H,
let ⟨I, Imax, Iuniq⟩ := h in
let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in
let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in
have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx),
have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy),
Imax.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H
section prio
set_option default_priority 100 -- see Note [default priority]
class is_local_ring_hom [semiring α] [semiring β] (f : α →+* β) : Prop :=
(map_nonunit : ∀ a, is_unit (f a) → is_unit a)
end prio
@[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [is_local_ring_hom f]
(a) (h : is_unit (f a)) : is_unit a :=
is_local_ring_hom.map_nonunit a h
section
open local_ring
variables [local_ring α] [local_ring β]
variables (f : α →+* β) [is_local_ring_hom f]
lemma map_nonunit (a) (h : a ∈ nonunits_ideal α) : f a ∈ nonunits_ideal β :=
λ H, h $ is_unit_of_map_unit f a H
end
namespace local_ring
variables [local_ring α] [local_ring β]
variable (α)
def residue_field := (nonunits_ideal α).quotient
noncomputable instance residue_field.field : field (residue_field α) :=
ideal.quotient.field (nonunits_ideal α)
/-- The quotient map from a local ring to it's residue field. -/
def residue : α →+* (residue_field α) :=
ideal.quotient.mk_hom _
namespace residue_field
variables {α β}
noncomputable def map (f : α →+* β) [is_local_ring_hom f] :
residue_field α →+* residue_field β :=
ideal.quotient.lift (nonunits_ideal α) ((ideal.quotient.mk_hom _).comp f) $
λ a ha,
begin
erw ideal.quotient.eq_zero_iff_mem,
exact map_nonunit f a ha
end
end residue_field
end local_ring
namespace field
variables [field α]
@[priority 100] -- see Note [lower instance priority]
instance : local_ring α :=
{ is_local := λ a,
if h : a = 0
then or.inr (by rw [h, sub_zero]; exact is_unit_one)
else or.inl $ is_unit_of_mul_eq_one a a⁻¹ $ div_self h }
end field
|
614ae1c8c7339d1f21a68838fcc4f37f94b4fdea | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /src_icannos_totilas/topologie-espaces-normés/cpge_ten_02a.lean | 7b60d67eec5fa117853fc2ac58d8bb350e36fa89 | [] | no_license | ahayat16/lean_exos | d4f08c30adb601a06511a71b5ffb4d22d12ef77f | 682f2552d5b04a8c8eb9e4ab15f875a91b03845c | refs/heads/main | 1,693,101,073,585 | 1,636,479,336,000 | 1,636,479,336,000 | 415,000,441 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 671 | lean | import data.set.basic
import topology.basic
import algebra.module.basic
import algebra.module.submodule
import analysis.normed_space.basic
-- On désigne par p1 et p2 les applications coordonnées de R 2 définies par pi (x1 , x2 ) = xi.
-- (a) Soit O un ouvert de R 2 , montrer que p 1 (O) et p 2 (O) sont des ouverts de R.
-- (b) Soit H = (x, y) ∈ R 2 xy = 1. Montrer que H est un fermé de R 2 et que p 1 (H) et p 2 (H) ne sont pas des fermés de R .
-- (c) Montrer que si F est fermé et que p2 (F) est borné, alors p1 (F) est fermé.
theorem a:
forall o: set (real × real), is_open o -> (is_open (prod.fst '' o)) /\ (is_open (prod.snd '' o))
:= sorry
|
20963bf8f1fdff9c7c1b69e4d6902df03190985f | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/asymptotics/specific_asymptotics.lean | 12e963db4cd620b4fb3b04671254d5135a2a4125 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 3,278 | lean | /-
Copyright (c) 2021 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import analysis.normed_space.ordered
import analysis.asymptotics.asymptotics
/-!
# A collection of specific asymptotic results
This file contains specific lemmas about asymptotics which don't have their place in the general
theory developped in `analysis.asymptotics.asymptotics`.
-/
open filter asymptotics
open_locale topological_space
section normed_field
/-- If `f : 𝕜 → E` is bounded in a punctured neighborhood of `a`, then `f(x) = o((x - a)⁻¹)` as
`x → a`, `x ≠ a`. -/
lemma filter.is_bounded_under.is_o_sub_self_inv {𝕜 E : Type*} [normed_field 𝕜] [has_norm E]
{a : 𝕜} {f : 𝕜 → E} (h : is_bounded_under (≤) (𝓝[≠] a) (norm ∘ f)) :
is_o f (λ x, (x - a)⁻¹) (𝓝[≠] a) :=
begin
refine (h.is_O_const (@one_ne_zero ℝ _ _)).trans_is_o (is_o_const_left.2 $ or.inr _),
simp only [(∘), normed_field.norm_inv],
exact (tendsto_norm_sub_self_punctured_nhds a).inv_tendsto_zero
end
end normed_field
section linear_ordered_field
variables {𝕜 : Type*} [linear_ordered_field 𝕜]
lemma pow_div_pow_eventually_eq_at_top {p q : ℕ} :
(λ x : 𝕜, x^p / x^q) =ᶠ[at_top] (λ x, x^((p : ℤ) -q)) :=
begin
apply ((eventually_gt_at_top (0 : 𝕜)).mono (λ x hx, _)),
simp [zpow_sub₀ hx.ne'],
end
lemma pow_div_pow_eventually_eq_at_bot {p q : ℕ} :
(λ x : 𝕜, x^p / x^q) =ᶠ[at_bot] (λ x, x^((p : ℤ) -q)) :=
begin
apply ((eventually_lt_at_bot (0 : 𝕜)).mono (λ x hx, _)),
simp [zpow_sub₀ hx.ne'.symm],
end
lemma tendsto_zpow_at_top_at_top {n : ℤ}
(hn : 0 < n) : tendsto (λ x : 𝕜, x^n) at_top at_top :=
begin
lift n to ℕ using hn.le,
simp only [zpow_coe_nat],
exact tendsto_pow_at_top (nat.succ_le_iff.mpr $int.coe_nat_pos.mp hn)
end
lemma tendsto_pow_div_pow_at_top_at_top {p q : ℕ}
(hpq : q < p) : tendsto (λ x : 𝕜, x^p / x^q) at_top at_top :=
begin
rw tendsto_congr' pow_div_pow_eventually_eq_at_top,
apply tendsto_zpow_at_top_at_top,
linarith
end
lemma tendsto_pow_div_pow_at_top_zero [topological_space 𝕜] [order_topology 𝕜] {p q : ℕ}
(hpq : p < q) : tendsto (λ x : 𝕜, x^p / x^q) at_top (𝓝 0) :=
begin
rw tendsto_congr' pow_div_pow_eventually_eq_at_top,
apply tendsto_zpow_at_top_zero,
linarith
end
end linear_ordered_field
section normed_linear_ordered_field
variables {𝕜 : Type*} [normed_linear_ordered_field 𝕜]
lemma asymptotics.is_o_pow_pow_at_top_of_lt
[order_topology 𝕜] {p q : ℕ} (hpq : p < q) :
is_o (λ x : 𝕜, x^p) (λ x, x^q) at_top :=
begin
refine (is_o_iff_tendsto' _).mpr (tendsto_pow_div_pow_at_top_zero hpq),
exact (eventually_gt_at_top 0).mono (λ x hx hxq, (pow_ne_zero q hx.ne' hxq).elim),
end
lemma asymptotics.is_O.trans_tendsto_norm_at_top {α : Type*} {u v : α → 𝕜} {l : filter α}
(huv : is_O u v l) (hu : tendsto (λ x, ∥u x∥) l at_top) : tendsto (λ x, ∥v x∥) l at_top :=
begin
rcases huv.exists_pos with ⟨c, hc, hcuv⟩,
rw is_O_with at hcuv,
convert tendsto.at_top_div_const hc (tendsto_at_top_mono' l hcuv hu),
ext x,
rw mul_div_cancel_left _ hc.ne.symm,
end
end normed_linear_ordered_field
|
3e99182d6cd94b96a567aab66c1dd0d99c5903f3 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/sites/subsheaf.lean | 1d5cf76d944ff4cdf9fc54c98dcad9ac064d6c3c | [
"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 | 16,316 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import category_theory.elementwise
import category_theory.adjunction.evaluation
import category_theory.sites.sheafification
/-!
# Subsheaf of types
We define the sub(pre)sheaf of a type valued presheaf.
## Main results
- `category_theory.grothendieck_topology.subpresheaf` :
A subpresheaf of a presheaf of types.
- `category_theory.grothendieck_topology.subpresheaf.sheafify` :
The sheafification of a subpresheaf as a subpresheaf. Note that this is a sheaf only when the
whole sheaf is.
- `category_theory.grothendieck_topology.subpresheaf.sheafify_is_sheaf` :
The sheafification is a sheaf
- `category_theory.grothendieck_topology.subpresheaf.sheafify_lift` :
The descent of a map into a sheaf to the sheafification.
- `category_theory.grothendieck_topology.image_sheaf` : The image sheaf of a morphism.
- `category_theory.grothendieck_topology.image_factorization` : The image sheaf as a
`limits.image_factorization`.
-/
universes w v u
open opposite category_theory
namespace category_theory.grothendieck_topology
variables {C : Type u} [category.{v} C] (J : grothendieck_topology C)
/-- A subpresheaf of a presheaf consists of a subset of `F.obj U` for every `U`,
compatible with the restriction maps `F.map i`. -/
@[ext]
structure subpresheaf (F : Cᵒᵖ ⥤ Type w) :=
(obj : Π U, set (F.obj U))
(map : Π {U V : Cᵒᵖ} (i : U ⟶ V), (obj U) ⊆ (F.map i) ⁻¹' (obj V))
variables {F F' F'' : Cᵒᵖ ⥤ Type w} (G G' : subpresheaf F)
instance : partial_order (subpresheaf F) :=
partial_order.lift subpresheaf.obj subpresheaf.ext
instance : has_top (subpresheaf F) :=
⟨⟨λ U, ⊤, λ U V i x h, _root_.trivial⟩⟩
instance : nonempty (subpresheaf F) := infer_instance
/-- The subpresheaf as a presheaf. -/
@[simps]
def subpresheaf.to_presheaf : Cᵒᵖ ⥤ Type w :=
{ obj := λ U, G.obj U,
map := λ U V i x, ⟨F.map i x, G.map i x.prop⟩,
map_id' := λ X, by { ext ⟨x, _⟩, dsimp, rw F.map_id, refl },
map_comp' := λ X Y Z i j, by { ext ⟨x, _⟩, dsimp, rw F.map_comp, refl } }
instance {U} : has_coe (G.to_presheaf.obj U) (F.obj U) :=
coe_subtype
/-- The inclusion of a subpresheaf to the original presheaf. -/
@[simps]
def subpresheaf.ι : G.to_presheaf ⟶ F :=
{ app := λ U x, x }
instance : mono G.ι :=
⟨λ H f₁ f₂ e, nat_trans.ext f₁ f₂ $ funext $ λ U,
funext $ λ x, subtype.ext $ congr_fun (congr_app e U) x⟩
/-- The inclusion of a subpresheaf to a larger subpresheaf -/
@[simps]
def subpresheaf.hom_of_le {G G' : subpresheaf F} (h : G ≤ G') : G.to_presheaf ⟶ G'.to_presheaf :=
{ app := λ U x, ⟨x, h U x.prop⟩ }
instance {G G' : subpresheaf F} (h : G ≤ G') : mono (subpresheaf.hom_of_le h) :=
⟨λ H f₁ f₂ e, nat_trans.ext f₁ f₂ $ funext $ λ U,
funext $ λ x, subtype.ext $ (congr_arg subtype.val $ (congr_fun (congr_app e U) x : _) : _)⟩
@[simp, reassoc]
lemma subpresheaf.hom_of_le_ι {G G' : subpresheaf F} (h : G ≤ G') :
subpresheaf.hom_of_le h ≫ G'.ι = G.ι :=
by { ext, refl }
instance : is_iso (subpresheaf.ι (⊤ : subpresheaf F)) :=
begin
apply_with nat_iso.is_iso_of_is_iso_app { instances := ff },
{ intro X, rw is_iso_iff_bijective,
exact ⟨subtype.coe_injective, λ x, ⟨⟨x, _root_.trivial⟩, rfl⟩⟩ }
end
lemma subpresheaf.eq_top_iff_is_iso : G = ⊤ ↔ is_iso G.ι :=
begin
split,
{ rintro rfl, apply_instance },
{ introI H, ext U x, apply (iff_true _).mpr, rw ← is_iso.inv_hom_id_apply (G.ι.app U) x,
exact ((inv (G.ι.app U)) x).2 }
end
/-- If the image of a morphism falls in a subpresheaf, then the morphism factors through it. -/
@[simps]
def subpresheaf.lift (f : F' ⟶ F) (hf : ∀ U x, f.app U x ∈ G.obj U) : F' ⟶ G.to_presheaf :=
{ app := λ U x, ⟨f.app U x, hf U x⟩,
naturality' := by { have := elementwise_of f.naturality, intros, ext, simp [this] } }
@[simp, reassoc]
lemma subpresheaf.lift_ι (f : F' ⟶ F) (hf : ∀ U x, f.app U x ∈ G.obj U) :
G.lift f hf ≫ G.ι = f := by { ext, refl }
/-- Given a subpresheaf `G` of `F`, an `F`-section `s` on `U`, we may define a sieve of `U`
consisting of all `f : V ⟶ U` such that the restriction of `s` along `f` is in `G`. -/
@[simps]
def subpresheaf.sieve_of_section {U : Cᵒᵖ} (s : F.obj U) : sieve (unop U) :=
{ arrows := λ V f, F.map f.op s ∈ G.obj (op V),
downward_closed' := λ V W i hi j,
by { rw [op_comp, functor_to_types.map_comp_apply], exact G.map _ hi } }
/-- Given a `F`-section `s` on `U` and a subpresheaf `G`, we may define a family of elements in
`G` consisting of the restrictions of `s` -/
def subpresheaf.family_of_elements_of_section {U : Cᵒᵖ} (s : F.obj U) :
(G.sieve_of_section s).1.family_of_elements G.to_presheaf :=
λ V i hi, ⟨F.map i.op s, hi⟩
lemma subpresheaf.family_of_elements_compatible {U : Cᵒᵖ} (s : F.obj U) :
(G.family_of_elements_of_section s).compatible :=
begin
intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ e,
ext1,
change F.map g₁.op (F.map f₁.op s) = F.map g₂.op (F.map f₂.op s),
rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply,
← op_comp, ← op_comp, e],
end
lemma subpresheaf.nat_trans_naturality (f : F' ⟶ G.to_presheaf) {U V : Cᵒᵖ} (i : U ⟶ V)
(x : F'.obj U) :
(f.app V (F'.map i x)).1 = F.map i (f.app U x).1 :=
congr_arg subtype.val (functor_to_types.naturality _ _ f i x)
include J
/-- The sheafification of a subpresheaf as a subpresheaf.
Note that this is a sheaf only when the whole presheaf is a sheaf. -/
def subpresheaf.sheafify : subpresheaf F :=
{ obj := λ U, { s | G.sieve_of_section s ∈ J (unop U) },
map := begin
rintros U V i s hs,
refine J.superset_covering _ (J.pullback_stable i.unop hs),
intros _ _ h,
dsimp at h ⊢,
rwa ← functor_to_types.map_comp_apply,
end }
lemma subpresheaf.le_sheafify : G ≤ G.sheafify J :=
begin
intros U s hs,
change _ ∈ J _,
convert J.top_mem _,
rw eq_top_iff,
rintros V i -,
exact G.map i.op hs,
end
variable {J}
lemma subpresheaf.eq_sheafify (h : presieve.is_sheaf J F)
(hG : presieve.is_sheaf J G.to_presheaf) : G = G.sheafify J :=
begin
apply (G.le_sheafify J).antisymm,
intros U s hs,
suffices : ((hG _ hs).amalgamate _ (G.family_of_elements_compatible s)).1 = s,
{ rw ← this, exact ((hG _ hs).amalgamate _ (G.family_of_elements_compatible s)).2 },
apply (h _ hs).is_separated_for.ext,
intros V i hi,
exact (congr_arg subtype.val ((hG _ hs).valid_glue (G.family_of_elements_compatible s) _ hi) : _)
end
lemma subpresheaf.sheafify_is_sheaf (hF : presieve.is_sheaf J F) :
presieve.is_sheaf J (G.sheafify J).to_presheaf :=
begin
intros U S hS x hx,
let S' := sieve.bind S (λ Y f hf, G.sieve_of_section (x f hf).1),
have := λ {V} {i : V ⟶ U} (hi : S' i), hi,
choose W i₁ i₂ hi₂ h₁ h₂,
dsimp [-sieve.bind_apply] at *,
let x'' : presieve.family_of_elements F S' :=
λ V i hi, F.map (i₁ hi).op (x _ (hi₂ hi)),
have H : ∀ s, x.is_amalgamation s ↔ x''.is_amalgamation s.1,
{ intro s,
split,
{ intros H V i hi,
dsimp only [x''],
conv_lhs { rw ← h₂ hi },
rw ← H _ (hi₂ hi),
exact functor_to_types.map_comp_apply F (i₂ hi).op (i₁ hi).op _ },
{ intros H V i hi,
ext1,
apply (hF _ (x i hi).2).is_separated_for.ext,
intros V' i' hi',
have hi'' : S' (i' ≫ i) := ⟨_, _, _, hi, hi', rfl⟩,
have := H _ hi'',
rw [op_comp, F.map_comp] at this,
refine this.trans (congr_arg subtype.val (hx _ _ (hi₂ hi'') hi (h₂ hi''))) } },
have : x''.compatible,
{ intros V₁ V₂ V₃ g₁ g₂ g₃ g₄ S₁ S₂ e,
rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply],
exact congr_arg subtype.val
(hx (g₁ ≫ i₁ S₁) (g₂ ≫ i₁ S₂) (hi₂ S₁) (hi₂ S₂) (by simp only [category.assoc, h₂, e])) },
obtain ⟨t, ht, ht'⟩ := hF _ (J.bind_covering hS (λ V i hi, (x i hi).2)) _ this,
refine ⟨⟨t, _⟩, (H ⟨t, _⟩).mpr ht, λ y hy, subtype.ext (ht' _ ((H _).mp hy))⟩,
show G.sieve_of_section t ∈ J _,
refine J.superset_covering _ (J.bind_covering hS (λ V i hi, (x i hi).2)),
intros V i hi,
dsimp,
rw ht _ hi,
exact h₁ hi
end
lemma subpresheaf.eq_sheafify_iff (h : presieve.is_sheaf J F) :
G = G.sheafify J ↔ presieve.is_sheaf J G.to_presheaf :=
⟨λ e, e.symm ▸ G.sheafify_is_sheaf h, G.eq_sheafify h⟩
lemma subpresheaf.is_sheaf_iff (h : presieve.is_sheaf J F) :
presieve.is_sheaf J G.to_presheaf ↔
∀ U (s : F.obj U), G.sieve_of_section s ∈ J (unop U) → s ∈ G.obj U :=
begin
rw ← G.eq_sheafify_iff h,
change _ ↔ G.sheafify J ≤ G,
exact ⟨eq.ge, (G.le_sheafify J).antisymm⟩
end
lemma subpresheaf.sheafify_sheafify (h : presieve.is_sheaf J F) :
(G.sheafify J).sheafify J = G.sheafify J :=
((subpresheaf.eq_sheafify_iff _ h).mpr $ G.sheafify_is_sheaf h).symm
/-- The lift of a presheaf morphism onto the sheafification subpresheaf. -/
noncomputable
def subpresheaf.sheafify_lift (f : G.to_presheaf ⟶ F') (h : presieve.is_sheaf J F') :
(G.sheafify J).to_presheaf ⟶ F' :=
{ app := λ U s,
(h _ s.prop).amalgamate _ ((G.family_of_elements_compatible ↑s).comp_presheaf_map f),
naturality' :=
begin
intros U V i,
ext s,
apply (h _ ((subpresheaf.sheafify J G).to_presheaf.map i s).prop).is_separated_for.ext,
intros W j hj,
refine (presieve.is_sheaf_for.valid_glue _ _ _ hj).trans _,
dsimp,
conv_rhs { rw ← functor_to_types.map_comp_apply },
change _ = F'.map (j ≫ i.unop).op _,
refine eq.trans _ (presieve.is_sheaf_for.valid_glue _ _ _ _).symm,
{ dsimp at ⊢ hj, rwa functor_to_types.map_comp_apply },
{ dsimp [presieve.family_of_elements.comp_presheaf_map],
congr' 1,
ext1,
exact (functor_to_types.map_comp_apply _ _ _ _).symm }
end }
lemma subpresheaf.to_sheafify_lift (f : G.to_presheaf ⟶ F') (h : presieve.is_sheaf J F') :
subpresheaf.hom_of_le (G.le_sheafify J) ≫ G.sheafify_lift f h = f :=
begin
ext U s,
apply (h _ ((subpresheaf.hom_of_le (G.le_sheafify J)).app U s).prop).is_separated_for.ext,
intros V i hi,
have := elementwise_of f.naturality,
exact (presieve.is_sheaf_for.valid_glue _ _ _ hi).trans (this _ _)
end
lemma subpresheaf.to_sheafify_lift_unique (h : presieve.is_sheaf J F')
(l₁ l₂ : (G.sheafify J).to_presheaf ⟶ F')
(e : subpresheaf.hom_of_le (G.le_sheafify J) ≫ l₁ =
subpresheaf.hom_of_le (G.le_sheafify J) ≫ l₂) : l₁ = l₂ :=
begin
ext U ⟨s, hs⟩,
apply (h _ hs).is_separated_for.ext,
rintros V i hi,
dsimp at hi,
erw [← functor_to_types.naturality, ← functor_to_types.naturality],
exact (congr_fun (congr_app e $ op V) ⟨_, hi⟩ : _)
end
lemma subpresheaf.sheafify_le (h : G ≤ G') (hF : presieve.is_sheaf J F)
(hG' : presieve.is_sheaf J G'.to_presheaf) :
G.sheafify J ≤ G' :=
begin
intros U x hx,
convert ((G.sheafify_lift (subpresheaf.hom_of_le h) hG').app U ⟨x, hx⟩).2,
apply (hF _ hx).is_separated_for.ext,
intros V i hi,
have := congr_arg (λ f : G.to_presheaf ⟶ G'.to_presheaf, (nat_trans.app f (op V) ⟨_, hi⟩).1)
(G.to_sheafify_lift (subpresheaf.hom_of_le h) hG'),
convert this.symm,
erw ← subpresheaf.nat_trans_naturality,
refl,
end
omit J
section image
/-- The image presheaf of a morphism, whose components are the set-theoretic images. -/
@[simps]
def image_presheaf (f : F' ⟶ F) : subpresheaf F :=
{ obj := λ U, set.range (f.app U),
map := λ U V i,
by { rintros _ ⟨x, rfl⟩, have := elementwise_of f.naturality, exact ⟨_, this i x⟩ } }
@[simp] lemma top_subpresheaf_obj (U) : (⊤ : subpresheaf F).obj U = ⊤ := rfl
@[simp]
lemma image_presheaf_id : image_presheaf (𝟙 F) = ⊤ :=
by { ext, simp }
/-- A morphism factors through the image presheaf. -/
@[simps]
def to_image_presheaf (f : F' ⟶ F) : F' ⟶ (image_presheaf f).to_presheaf :=
(image_presheaf f).lift f (λ U x, set.mem_range_self _)
variables (J)
/-- A morphism factors through the sheafification of the image presheaf. -/
@[simps]
def to_image_presheaf_sheafify (f : F' ⟶ F) : F' ⟶ ((image_presheaf f).sheafify J).to_presheaf :=
to_image_presheaf f ≫ subpresheaf.hom_of_le ((image_presheaf f).le_sheafify J)
variables {J}
@[simp, reassoc]
lemma to_image_presheaf_ι (f : F' ⟶ F) : to_image_presheaf f ≫ (image_presheaf f).ι = f :=
(image_presheaf f).lift_ι _ _
lemma image_presheaf_comp_le (f₁ : F ⟶ F') (f₂ : F' ⟶ F'') :
image_presheaf (f₁ ≫ f₂) ≤ image_presheaf f₂ :=
λ U x hx, ⟨f₁.app U hx.some, hx.some_spec⟩
instance {F F' : Cᵒᵖ ⥤ Type (max v w)} (f : F ⟶ F') [hf : mono f] :
is_iso (to_image_presheaf f) :=
begin
apply_with nat_iso.is_iso_of_is_iso_app { instances := ff },
intro X,
rw is_iso_iff_bijective,
split,
{ intros x y e,
have := (nat_trans.mono_iff_mono_app _ _).mp hf X,
rw mono_iff_injective at this,
exact this (congr_arg subtype.val e : _) },
{ rintro ⟨_, ⟨x, rfl⟩⟩, exact ⟨x, rfl⟩ }
end
/-- The image sheaf of a morphism between sheaves, defined to be the sheafification of
`image_presheaf`. -/
@[simps]
def image_sheaf {F F' : Sheaf J (Type w)} (f : F ⟶ F') : Sheaf J (Type w) :=
⟨((image_presheaf f.1).sheafify J).to_presheaf,
by { rw is_sheaf_iff_is_sheaf_of_type, apply subpresheaf.sheafify_is_sheaf,
rw ← is_sheaf_iff_is_sheaf_of_type, exact F'.2 }⟩
/-- A morphism factors through the image sheaf. -/
@[simps]
def to_image_sheaf {F F' : Sheaf J (Type w)} (f : F ⟶ F') : F ⟶ image_sheaf f :=
⟨to_image_presheaf_sheafify J f.1⟩
/-- The inclusion of the image sheaf to the target. -/
@[simps]
def image_sheaf_ι {F F' : Sheaf J (Type w)} (f : F ⟶ F') : image_sheaf f ⟶ F' :=
⟨subpresheaf.ι _⟩
@[simp, reassoc]
lemma to_image_sheaf_ι {F F' : Sheaf J (Type w)} (f : F ⟶ F') :
to_image_sheaf f ≫ image_sheaf_ι f = f :=
by { ext1, simp [to_image_presheaf_sheafify] }
instance {F F' : Sheaf J (Type w)} (f : F ⟶ F') : mono (image_sheaf_ι f) :=
(Sheaf_to_presheaf J _).mono_of_mono_map (by { dsimp, apply_instance })
instance {F F' : Sheaf J (Type w)} (f : F ⟶ F') : epi (to_image_sheaf f) :=
begin
refine ⟨λ G' g₁ g₂ e, _⟩,
ext U ⟨s, hx⟩,
apply ((is_sheaf_iff_is_sheaf_of_type J _).mp G'.2 _ hx).is_separated_for.ext,
rintros V i ⟨y, e'⟩,
change (g₁.val.app _ ≫ G'.val.map _) _ = (g₂.val.app _ ≫ G'.val.map _) _,
rw [← nat_trans.naturality, ← nat_trans.naturality],
have E : (to_image_sheaf f).val.app (op V) y =
(image_sheaf f).val.map i.op ⟨s, hx⟩ := subtype.ext e',
have := congr_arg (λ f : F ⟶ G', (Sheaf.hom.val f).app _ y) e,
dsimp at this ⊢,
convert this; exact E.symm
end
/-- The mono factorization given by `image_sheaf` for a morphism. -/
def image_mono_factorization {F F' : Sheaf J (Type w)} (f : F ⟶ F') :
limits.mono_factorisation f :=
{ I := image_sheaf f,
m := image_sheaf_ι f,
e := to_image_sheaf f }
/-- The mono factorization given by `image_sheaf` for a morphism is an image. -/
noncomputable
def image_factorization {F F' : Sheaf J (Type (max v u))} (f : F ⟶ F') :
limits.image_factorisation f :=
{ F := image_mono_factorization f,
is_image :=
{ lift := λ I, begin
haveI := (Sheaf.hom.mono_iff_presheaf_mono J _ _).mp I.m_mono,
refine ⟨subpresheaf.hom_of_le _ ≫ inv (to_image_presheaf I.m.1)⟩,
apply subpresheaf.sheafify_le,
{ conv_lhs { rw ← I.fac }, apply image_presheaf_comp_le },
{ rw ← is_sheaf_iff_is_sheaf_of_type, exact F'.2 },
{ apply presieve.is_sheaf_iso J (as_iso $ to_image_presheaf I.m.1),
rw ← is_sheaf_iff_is_sheaf_of_type, exact I.I.2 }
end,
lift_fac' := λ I, begin
ext1,
dsimp [image_mono_factorization],
generalize_proofs h,
rw [← subpresheaf.hom_of_le_ι h, category.assoc],
congr' 1,
rw [is_iso.inv_comp_eq, to_image_presheaf_ι],
end } }
instance : limits.has_images (Sheaf J (Type (max v u))) :=
⟨λ _ _ f, ⟨⟨image_factorization f⟩⟩⟩
end image
end category_theory.grothendieck_topology
|
c3b676c6e8c0ebc1ab3488a7d64a454b3634b023 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/vm_string_lt_bug.lean | 43f04ac193bcd362b17daa85e4f85bbe035cf758 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 290 | lean | open native
#eval to_bool ("a" < "b")
#eval to_bool ("b" < "b")
namespace test1
meta def m := rb_map.mk string nat
meta def m' := m.insert "foo" 10
#eval m'.find "foo"
end test1
namespace test2
meta def m := rb_map.mk nat nat
meta def m' := m.insert 3 10
#eval m'.find 3
end test2
|
98022b319fb4fac9017adeb61a44c91598d36470 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/omega/nat/main.lean | a238c63501a40e4359b211649b12ceddc583e17f | [] | 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 | 659 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.omega.prove_unsats
import Mathlib.tactic.omega.nat.dnf
import Mathlib.tactic.omega.nat.neg_elim
import Mathlib.tactic.omega.nat.sub_elim
import Mathlib.PostPort
namespace Mathlib
/-
Main procedure for linear natural number arithmetic.
-/
namespace omega
namespace nat
theorem univ_close_of_unsat_neg_elim_not (m : ℕ) (p : preform) : preform.unsat (neg_elim (preform.not p)) → univ_close p (fun (_x : ℕ) => 0) m := sorry
|
cc37b18b41a43ad8aa204740078b2c45894ffcc2 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /category_theory/natural_transformation.lean | ced3df2d6d7e21cee9fddb1b5c0d848d96656142 | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 4,586 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison
Defines natural transformations between functors.
Introduces notations
`F ⟹ G` for the type of natural transformations between functors `F` and `G`,
`τ X` (a coercion) for the components of natural transformations,
`σ ⊟ τ` for vertical compositions, and
`σ ◫ τ` for horizontal compositions.
-/
import .functor
namespace category_theory
universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄
variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D]
include 𝒞 𝒟
/--
`nat_trans F G` represents a natural transformation between functors `F` and `G`.
The field `app` provides the components of the natural transformation, and there is a
coercion available so you can write `α X` for the component of a transformation `α` at an object `X`.
Naturality is expressed by `α.naturality_lemma`.
-/
structure nat_trans (F G : C ↝ D) : Type (max u₁ v₂) :=
(app : Π X : C, (F X) ⟶ (G X))
(naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ (app Y) = (app X) ≫ (G.map f) . obviously)
restate_axiom nat_trans.naturality
attribute [ematch] nat_trans.naturality_lemma
infixr ` ⟹ `:50 := nat_trans -- type as \==> or ⟹
namespace nat_trans
instance {F G : C ↝ D} : has_coe_to_fun (F ⟹ G) :=
{ F := λ α, Π X : C, (F X) ⟶ (G X),
coe := λ α, α.app }
@[simp] lemma coe_def {F G : C ↝ D} (α : F ⟹ G) (X : C) : α X = α.app X := rfl
/-- `nat_trans.id F` is the identity natural transformation on a functor `F`. -/
protected def id (F : C ↝ D) : F ⟹ F :=
{ app := λ X, 𝟙 (F X),
naturality := begin /- `obviously'` says: -/ intros, dsimp, simp end }
@[simp] lemma id_app (F : C ↝ D) (X : C) : (nat_trans.id F) X = 𝟙 (F X) := rfl
open category
open category_theory.functor
section
variables {F G H I : C ↝ D}
-- We'll want to be able to prove that two natural transformations are equal if they are componentwise equal.
@[extensionality] lemma ext (α β : F ⟹ G) (w : ∀ X : C, α X = β X) : α = β :=
begin
induction α with α_components α_naturality,
induction β with β_components β_naturality,
have hc : α_components = β_components := funext w,
subst hc
end
/-- `vcomp α β` is the vertical compositions of natural transformations. -/
def vcomp (α : F ⟹ G) (β : G ⟹ H) : F ⟹ H :=
{ app := λ X, (α X) ≫ (β X),
naturality := begin /- `obviously'` says: -/ intros, simp, rw [←assoc_lemma, naturality_lemma, assoc_lemma, ←naturality_lemma], end }
notation α `⊟` β:80 := vcomp α β
@[simp] lemma vcomp_app (α : F ⟹ G) (β : G ⟹ H) (X : C) : (α ⊟ β) X = (α X) ≫ (β X) := rfl
@[ematch] lemma vcomp_assoc (α : F ⟹ G) (β : G ⟹ H) (γ : H ⟹ I) : (α ⊟ β) ⊟ γ = (α ⊟ (β ⊟ γ)) := begin ext, intros, dsimp, rw [assoc] end
end
variables {E : Type u₃} [ℰ : category.{u₃ v₃} E]
include ℰ
/-- `hcomp α β` is the horizontal composition of natural transformations. -/
def hcomp {F G : C ↝ D} {H I : D ↝ E} (α : F ⟹ G) (β : H ⟹ I) : (F ⋙ H) ⟹ (G ⋙ I) :=
{ app := λ X : C, (β (F X)) ≫ (I.map (α X)),
naturality := begin
/- `obviously'` says: -/
intros,
dsimp,
simp,
-- Actually, obviously doesn't use exactly this sequence of rewrites, but achieves the same result
rw [← assoc_lemma, naturality_lemma, assoc_lemma],
conv { to_rhs, rw [← map_comp_lemma, ← α.naturality_lemma, map_comp_lemma] }
end }
notation α `◫` β:80 := hcomp α β
@[simp] lemma hcomp_app {F G : C ↝ D} {H I : D ↝ E} (α : F ⟹ G) (β : H ⟹ I) (X : C) : (α ◫ β) X = (β (F X)) ≫ (I.map (α X)) := rfl
-- Note that we don't yet prove a `hcomp_assoc` lemma here: even stating it is painful, because we need to use associativity of functor composition
@[ematch] lemma exchange {F G H : C ↝ D} {I J K : D ↝ E} (α : F ⟹ G) (β : G ⟹ H) (γ : I ⟹ J) (δ : J ⟹ K) : ((α ⊟ β) ◫ (γ ⊟ δ)) = ((α ◫ γ) ⊟ (β ◫ δ)) :=
begin
-- `obviously'` says:
ext,
intros,
dsimp,
simp,
-- again, this isn't actually what obviously says, but it achieves the same effect.
conv { to_lhs, congr, skip, rw [←assoc_lemma, ←naturality_lemma, assoc_lemma] }
end
end nat_trans
end category_theory |
961932cd2775f860ac77db37969834f3538ac533 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/equiv/denumerable.lean | a2ee8b8416160dfd9a14395a4f235cb9aa834b96 | [
"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 | 9,131 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Denumerable (countably infinite) types, as a typeclass extending
encodable. This is used to provide explicit encode/decode functions
from nat, where the functions are known inverses of each other.
-/
import data.equiv.encodable
import data.sigma
import data.fintype.basic
import data.list.min_max
open nat
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A denumerable type is one which is (constructively) bijective with ℕ.
Although we already have a name for this property, namely `α ≃ ℕ`,
we are here interested in using it as a typeclass. -/
class denumerable (α : Type*) extends encodable α :=
(decode_inv : ∀ n, ∃ a ∈ decode n, encode a = n)
end prio
namespace denumerable
section
variables {α : Type*} {β : Type*} [denumerable α] [denumerable β]
open encodable
theorem decode_is_some (α) [denumerable α] (n : ℕ) :
(decode α n).is_some :=
option.is_some_iff_exists.2 $
(decode_inv n).imp $ λ a, Exists.fst
def of_nat (α) [f : denumerable α] (n : ℕ) : α :=
option.get (decode_is_some α n)
@[simp, priority 900]
theorem decode_eq_of_nat (α) [denumerable α] (n : ℕ) :
decode α n = some (of_nat α n) :=
option.eq_some_of_is_some _
@[simp] theorem of_nat_of_decode {n b}
(h : decode α n = some b) : of_nat α n = b :=
option.some.inj $ (decode_eq_of_nat _ _).symm.trans h
@[simp] theorem encode_of_nat (n) : encode (of_nat α n) = n :=
let ⟨a, h, e⟩ := decode_inv n in
by rwa [of_nat_of_decode h]
@[simp] theorem of_nat_encode (a) : of_nat α (encode a) = a :=
of_nat_of_decode (encodek _)
def eqv (α) [denumerable α] : α ≃ ℕ :=
⟨encode, of_nat α, of_nat_encode, encode_of_nat⟩
def mk' {α} (e : α ≃ ℕ) : denumerable α :=
{ encode := e,
decode := some ∘ e.symm,
encodek := λ a, congr_arg some (e.symm_apply_apply _),
decode_inv := λ n, ⟨_, rfl, e.apply_symm_apply _⟩ }
def of_equiv (α) {β} [denumerable α] (e : β ≃ α) : denumerable β :=
{ decode_inv := λ n, by simp,
..encodable.of_equiv _ e }
@[simp] theorem of_equiv_of_nat (α) {β} [denumerable α] (e : β ≃ α)
(n) : @of_nat β (of_equiv _ e) n = e.symm (of_nat α n) :=
by apply of_nat_of_decode; show option.map _ _ = _; simp
def equiv₂ (α β) [denumerable α] [denumerable β] : α ≃ β := (eqv α).trans (eqv β).symm
instance nat : denumerable nat := ⟨λ n, ⟨_, rfl, rfl⟩⟩
@[simp] theorem of_nat_nat (n) : of_nat ℕ n = n := rfl
instance option : denumerable (option α) := ⟨λ n, by cases n; simp⟩
instance sum : denumerable (α ⊕ β) :=
⟨λ n, begin
suffices : ∃ a ∈ @decode_sum α β _ _ n,
encode_sum a = bit (bodd n) (div2 n), {simpa [bit_decomp]},
simp [decode_sum]; cases bodd n; simp [decode_sum, bit, encode_sum]
end⟩
section sigma
variables {γ : α → Type*} [∀ a, denumerable (γ a)]
instance sigma : denumerable (sigma γ) :=
⟨λ n, by simp [decode_sigma]; exact ⟨_, _, ⟨rfl, heq.rfl⟩, by simp⟩⟩
@[simp] theorem sigma_of_nat_val (n : ℕ) :
of_nat (sigma γ) n = ⟨of_nat α (unpair n).1, of_nat (γ _) (unpair n).2⟩ :=
option.some.inj $
by rw [← decode_eq_of_nat, decode_sigma_val]; simp; refl
end sigma
instance prod : denumerable (α × β) :=
of_equiv _ (equiv.sigma_equiv_prod α β).symm
@[simp] theorem prod_of_nat_val (n : ℕ) :
of_nat (α × β) n = (of_nat α (unpair n).1, of_nat β (unpair n).2) :=
by simp; refl
@[simp] theorem prod_nat_of_nat : of_nat (ℕ × ℕ) = unpair :=
by funext; simp
instance int : denumerable ℤ := denumerable.mk' equiv.int_equiv_nat
instance pnat : denumerable ℕ+ := denumerable.mk' equiv.pnat_equiv_nat
instance ulift : denumerable (ulift α) := of_equiv _ equiv.ulift
instance plift : denumerable (plift α) := of_equiv _ equiv.plift
def pair : α × α ≃ α := equiv₂ _ _
end
end denumerable
namespace nat.subtype
open function encodable
variables {s : set ℕ} [infinite s]
section classical
open_locale classical
lemma exists_succ (x : s) : ∃ n, x.1 + n + 1 ∈ s :=
classical.by_contradiction $ λ h,
have ∀ (a : ℕ) (ha : a ∈ s), a < x.val.succ,
from λ a ha, lt_of_not_ge (λ hax, h ⟨a - (x.1 + 1),
by rwa [add_right_comm, nat.add_sub_cancel' hax]⟩),
infinite.not_fintype
⟨(((multiset.range x.1.succ).filter (∈ s)).pmap
(λ (y : ℕ) (hy : y ∈ s), subtype.mk y hy)
(by simp [-multiset.range_succ])).to_finset,
by simpa [subtype.ext, multiset.mem_filter, -multiset.range_succ]⟩
end classical
variable [decidable_pred s]
def succ (x : s) : s :=
have h : ∃ m, x.1 + m + 1 ∈ s, from exists_succ x,
⟨x.1 + nat.find h + 1, nat.find_spec h⟩
lemma succ_le_of_lt {x y : s} (h : y < x) : succ y ≤ x :=
have hx : ∃ m, y.1 + m + 1 ∈ s, from exists_succ _,
let ⟨k, hk⟩ := nat.exists_eq_add_of_lt h in
have nat.find hx ≤ k, from nat.find_min' _ (hk ▸ x.2),
show y.1 + nat.find hx + 1 ≤ x.1,
by rw hk; exact add_le_add_right (add_le_add_left this _) _
lemma le_succ_of_forall_lt_le {x y : s} (h : ∀ z < x, z ≤ y) : x ≤ succ y :=
have hx : ∃ m, y.1 + m + 1 ∈ s, from exists_succ _,
show x.1 ≤ y.1 + nat.find hx + 1,
from le_of_not_gt $ λ hxy,
have y.1 + nat.find hx + 1 ≤ y.1 := h ⟨_, nat.find_spec hx⟩ hxy,
not_lt_of_le this $
calc y.1 ≤ y.1 + nat.find hx : le_add_of_nonneg_right (nat.zero_le _)
... < y.1 + nat.find hx + 1 : nat.lt_succ_self _
lemma lt_succ_self (x : s) : x < succ x :=
calc x.1 ≤ x.1 + _ : le_add_right (le_refl _)
... < succ x : nat.lt_succ_self (x.1 + _)
lemma lt_succ_iff_le {x y : s} : x < succ y ↔ x ≤ y :=
⟨λ h, le_of_not_gt (λ h', not_le_of_gt h (succ_le_of_lt h')),
λ h, lt_of_le_of_lt h (lt_succ_self _)⟩
def of_nat (s : set ℕ) [decidable_pred s] [infinite s] : ℕ → s
| 0 := ⊥
| (n+1) := succ (of_nat n)
lemma of_nat_surjective_aux : ∀ {x : ℕ} (hx : x ∈ s), ∃ n, of_nat s n = ⟨x, hx⟩
| x := λ hx, let t : list s := ((list.range x).filter (λ y, y ∈ s)).pmap
(λ (y : ℕ) (hy : y ∈ s), ⟨y, hy⟩) (by simp) in
have hmt : ∀ {y : s}, y ∈ t ↔ y < ⟨x, hx⟩,
by simp [list.mem_filter, subtype.ext, t]; intros; refl,
have wf : ∀ m : s, list.maximum t = m → m.1 < x,
from λ m hmax, by simpa [hmt] using list.maximum_mem hmax,
begin
cases hmax : list.maximum t with m,
{ exact ⟨0, le_antisymm (@bot_le s _ _)
(le_of_not_gt (λ h, list.not_mem_nil (⊥ : s) $
by rw [← list.maximum_eq_none.1 hmax, hmt]; exact h))⟩ },
{ cases of_nat_surjective_aux m.2 with a ha,
exact ⟨a + 1, le_antisymm
(by rw of_nat; exact succ_le_of_lt (by rw ha; exact wf _ hmax)) $
by rw of_nat; exact le_succ_of_forall_lt_le
(λ z hz, by rw ha; cases m; exact list.le_maximum_of_mem (hmt.2 hz) hmax)⟩ }
end
using_well_founded {dec_tac := `[tauto]}
lemma of_nat_surjective : surjective (of_nat s) :=
λ ⟨x, hx⟩, of_nat_surjective_aux hx
private def to_fun_aux (x : s) : ℕ :=
(list.range x).countp s
private lemma to_fun_aux_eq (x : s) :
to_fun_aux x = ((finset.range x).filter s).card :=
by rw [to_fun_aux, list.countp_eq_length_filter]; refl
open finset
private lemma right_inverse_aux : ∀ n, to_fun_aux (of_nat s n) = n
| 0 := begin
rw [to_fun_aux_eq, card_eq_zero, eq_empty_iff_forall_not_mem],
assume n,
rw [mem_filter, of_nat, mem_range],
assume h,
exact not_lt_of_le bot_le (show (⟨n, h.2⟩ : s) < ⊥, from h.1)
end
| (n+1) := have ih : to_fun_aux (of_nat s n) = n, from right_inverse_aux n,
have h₁ : (of_nat s n : ℕ) ∉ (range (of_nat s n)).filter s, by simp,
have h₂ : (range (succ (of_nat s n))).filter s =
insert (of_nat s n) ((range (of_nat s n)).filter s),
begin
simp only [finset.ext, mem_insert, mem_range, mem_filter],
assume m,
exact ⟨λ h, by simp only [h.2, and_true]; exact or.symm
(lt_or_eq_of_le ((@lt_succ_iff_le _ _ _ ⟨m, h.2⟩ _).1 h.1)),
λ h, h.elim (λ h, h.symm ▸ ⟨lt_succ_self _, subtype.property _⟩)
(λ h, ⟨lt_of_le_of_lt (le_of_lt h.1) (lt_succ_self _), h.2⟩)⟩
end,
begin
clear_aux_decl,
simp only [to_fun_aux_eq, of_nat, range_succ] at *,
conv {to_rhs, rw [← ih, ← card_insert_of_not_mem h₁, ← h₂] },
end
def denumerable (s : set ℕ) [decidable_pred s] [infinite s] : denumerable s :=
denumerable.of_equiv ℕ
{ to_fun := to_fun_aux,
inv_fun := of_nat s,
left_inv := left_inverse_of_surjective_of_right_inverse
of_nat_surjective right_inverse_aux,
right_inv := right_inverse_aux }
end nat.subtype
namespace denumerable
open encodable
def of_encodable_of_infinite (α : Type*) [encodable α] [infinite α] : denumerable α :=
begin
letI := @decidable_range_encode α _;
letI : infinite (set.range (@encode α _)) :=
infinite.of_injective _ (equiv.set.range _ encode_injective).injective,
letI := nat.subtype.denumerable (set.range (@encode α _)),
exact denumerable.of_equiv (set.range (@encode α _))
(equiv_range_encode α)
end
end denumerable
|
3fdebcf648de33428390e8b4b5b316ace52e59b1 | 2fbe653e4bc441efde5e5d250566e65538709888 | /src/linear_algebra/matrix.lean | 3aa24d01bbf1be28619ae6b8c9ba9bf57d301c86 | [
"Apache-2.0"
] | permissive | aceg00/mathlib | 5e15e79a8af87ff7eb8c17e2629c442ef24e746b | 8786ea6d6d46d6969ac9a869eb818bf100802882 | refs/heads/master | 1,649,202,698,930 | 1,580,924,783,000 | 1,580,924,783,000 | 149,197,272 | 0 | 0 | Apache-2.0 | 1,537,224,208,000 | 1,537,224,207,000 | null | UTF-8 | Lean | false | false | 11,176 | 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, Casper Putz
The equivalence between matrices and linear maps.
-/
import data.matrix.basic
import linear_algebra.dimension linear_algebra.tensor_product
/-!
# Linear maps and matrices
This file defines the maps to send matrices to a linear map,
and to send linear maps between modules with a finite bases
to matrices. This defines a linear equivalence between linear maps
between finite-dimensional vector spaces and matrices indexed by
the respective bases.
Some results are proved about the linear map corresponding to a
diagonal matrix (range, ker and rank).
## Main definitions
to_lin, to_matrix, linear_equiv_matrix
## Tags
linear_map, matrix, linear_equiv, diagonal
-/
noncomputable theory
open set submodule
universes u v w
variables {l m n : Type u} [fintype l] [fintype m] [fintype n]
namespace matrix
variables {R : Type v} [comm_ring R]
instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) :=
by unfold matrix; apply_instance
/-- Evaluation of matrices gives a linear map from matrix m n R to
linear maps (n → R) →ₗ[R] (m → R). -/
def eval : (matrix m n R) →ₗ[R] ((n → R) →ₗ[R] (m → R)) :=
begin
refine linear_map.mk₂ R mul_vec _ _ _ _,
{ assume M N v, funext x,
change finset.univ.sum (λy:n, (M x y + N x y) * v y) = _,
simp only [_root_.add_mul, finset.sum_add_distrib],
refl },
{ assume c M v, funext x,
change finset.univ.sum (λy:n, (c * M x y) * v y) = _,
simp only [_root_.mul_assoc, finset.mul_sum.symm],
refl },
{ assume M v w, funext x,
change finset.univ.sum (λy:n, M x y * (v y + w y)) = _,
simp [_root_.mul_add, finset.sum_add_distrib],
refl },
{ assume c M v, funext x,
change finset.univ.sum (λy:n, M x y * (c * v y)) = _,
rw [show (λy:n, M x y * (c * v y)) = (λy:n, c * (M x y * v y)), { funext n, ac_refl },
← finset.mul_sum],
refl }
end
/-- Evaluation of matrices gives a map from matrix m n R to
linear maps (n → R) →ₗ[R] (m → R). -/
def to_lin : matrix m n R → (n → R) →ₗ[R] (m → R) := eval.to_fun
lemma to_lin_add (M N : matrix m n R) : (M + N).to_lin = M.to_lin + N.to_lin :=
matrix.eval.map_add M N
@[simp] lemma to_lin_zero : (0 : matrix m n R).to_lin = 0 :=
matrix.eval.map_zero
instance to_lin.is_linear_map :
@is_linear_map R (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ _ _ _ to_lin :=
matrix.eval.is_linear
instance to_lin.is_add_monoid_hom :
@is_add_monoid_hom (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ to_lin :=
{ map_zero := to_lin_zero, map_add := to_lin_add }
@[simp] lemma to_lin_apply (M : matrix m n R) (v : n → R) :
(M.to_lin : (n → R) → (m → R)) v = mul_vec M v := rfl
lemma mul_to_lin [decidable_eq l] (M : matrix m n R) (N : matrix n l R) :
(M.mul N).to_lin = M.to_lin.comp N.to_lin :=
begin
ext v x,
simp [to_lin_apply, mul_vec, matrix.mul, finset.sum_mul, finset.mul_sum],
rw [finset.sum_comm],
congr, funext x, congr, funext y,
rw [mul_assoc]
end
end matrix
namespace linear_map
variables {R : Type v} [comm_ring R]
/-- The linear map from linear maps (n → R) →ₗ[R] (m → R) to matrix m n R. -/
def to_matrixₗ [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) →ₗ[R] matrix m n R :=
begin
refine linear_map.mk (λ f i j, f (λ n, ite (j = n) 1 0) i) _ _,
{ assume f g, simp only [add_apply], refl },
{ assume f g, simp only [smul_apply], refl }
end
/-- The map from linear maps (n → R) →ₗ[R] (m → R) to matrix m n R. -/
def to_matrix [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) → matrix m n R := to_matrixₗ.to_fun
end linear_map
section linear_equiv_matrix
variables {R : Type v} [comm_ring R] [decidable_eq n]
open finsupp matrix linear_map
/-- to_lin is the left inverse of to_matrix. -/
lemma to_matrix_to_lin {f : (n → R) →ₗ[R] (m → R)} :
to_lin (to_matrix f) = f :=
begin
ext : 1,
-- Show that the two sides are equal by showing that they are equal on a basis
convert linear_eq_on (set.range _) _ (is_basis.mem_span (@pi.is_basis_fun R n _ _) _),
assume e he,
rw [@std_basis_eq_single R _ _ _ 1] at he,
cases (set.mem_range.mp he) with i h,
ext j,
change finset.univ.sum (λ k, (f.to_fun (λ l, ite (k = l) 1 0)) j * (e k)) = _,
rw [←h],
conv_lhs { congr, skip, funext,
rw [mul_comm, ←smul_eq_mul, ←pi.smul_apply, ←linear_map.smul],
rw [show _ = ite (i = k) (1:R) 0, by convert single_apply],
rw [show f.to_fun (ite (i = k) (1:R) 0 • (λ l, ite (k = l) 1 0)) = ite (i = k) (f.to_fun _) 0,
{ split_ifs, { rw [one_smul] }, { rw [zero_smul], exact linear_map.map_zero f } }] },
convert finset.sum_eq_single i _ _,
{ rw [if_pos rfl], convert rfl, ext, congr },
{ assume _ _ hbi, rw [if_neg $ ne.symm hbi], refl },
{ assume hi, exact false.elim (hi $ finset.mem_univ i) }
end
/-- to_lin is the right inverse of to_matrix. -/
lemma to_lin_to_matrix {M : matrix m n R} : to_matrix (to_lin M) = M :=
begin
ext,
change finset.univ.sum (λ y, M i y * ite (j = y) 1 0) = M i j,
have h1 : (λ y, M i y * ite (j = y) 1 0) = (λ y, ite (j = y) (M i y) 0),
{ ext, split_ifs, exact mul_one _, exact ring.mul_zero _ },
have h2 : finset.univ.sum (λ y, ite (j = y) (M i y) 0) = (finset.singleton j).sum (λ y, ite (j = y) (M i y) 0),
{ refine (finset.sum_subset _ _).symm,
{ intros _ H, rwa finset.mem_singleton.1 H, exact finset.mem_univ _ },
{ exact λ _ _ H, if_neg (mt (finset.mem_singleton.2 ∘ eq.symm) H) } },
rw [h1, h2, finset.sum_singleton],
exact if_pos rfl
end
/-- Linear maps (n → R) →ₗ[R] (m → R) are linearly equivalent to matrix m n R. -/
def linear_equiv_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R :=
{ to_fun := to_matrix,
inv_fun := to_lin,
right_inv := λ _, to_lin_to_matrix,
left_inv := λ _, to_matrix_to_lin,
add := to_matrixₗ.add,
smul := to_matrixₗ.smul }
/-- Given a basis of two modules M₁ and M₂ over a commutative ring R, we get a linear equivalence
between linear maps M₁ →ₗ M₂ and matrices over R indexed by the bases. -/
def linear_equiv_matrix {ι κ M₁ M₂ : Type*}
[add_comm_group M₁] [module R M₁]
[add_comm_group M₂] [module R M₂]
[fintype ι] [decidable_eq ι] [fintype κ] [decidable_eq κ]
{v₁ : ι → M₁} {v₂ : κ → M₂} (hv₁ : is_basis R v₁) (hv₂ : is_basis R v₂) :
(M₁ →ₗ[R] M₂) ≃ₗ[R] matrix κ ι R :=
linear_equiv.trans (linear_equiv.arrow_congr (equiv_fun_basis hv₁) (equiv_fun_basis hv₂)) linear_equiv_matrix'
end linear_equiv_matrix
namespace matrix
open_locale matrix
section trace
variables {R : Type v} {M : Type w} [ring R] [add_comm_group M] [module R M]
/--
The diagonal of a square matrix.
-/
def diag (n : Type u) (R : Type v) (M : Type w)
[ring R] [add_comm_group M] [module R M] [fintype n] : (matrix n n M) →ₗ[R] n → M := {
to_fun := λ A i, A i i,
add := by { intros, ext, refl, },
smul := by { intros, ext, refl, } }
@[simp] lemma diag_one [decidable_eq n] :
diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_val_eq] }
@[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl
/--
The trace of a square matrix.
-/
def trace (n : Type u) (R : Type v) (M : Type w)
[ring R] [add_comm_group M] [module R M] [fintype n] : (matrix n n M) →ₗ[R] M := {
to_fun := finset.univ.sum ∘ (diag n R M),
add := by { intros, apply finset.sum_add_distrib, },
smul := by { intros, simp [finset.smul_sum], } }
@[simp] lemma trace_one [decidable_eq n] :
trace n R R 1 = fintype.card n :=
have h : trace n R R 1 = finset.univ.sum (diag n R R 1) := rfl,
by rw [h, diag_one, finset.sum_const, add_monoid.smul_one]; refl
@[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl
@[simp] lemma trace_transpose_mul [decidable_eq n] (A : matrix m n R) (B : matrix n m R) :
trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm
lemma trace_mul_comm {S : Type v} [comm_ring S] [decidable_eq n]
(A : matrix m n S) (B : matrix n m S) :
trace n S S (B ⬝ A) = trace m S S (A ⬝ B) :=
by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul]
end trace
section ring
variables {R : Type v} [comm_ring R]
open linear_map matrix
lemma proj_diagonal [decidable_eq m] (i : m) (w : m → R) :
(proj i).comp (to_lin (diagonal w)) = (w i) • proj i :=
by ext j; simp [mul_vec_diagonal]
lemma diagonal_comp_std_basis [decidable_eq n] (w : n → R) (i : n) :
(diagonal w).to_lin.comp (std_basis R (λ_:n, R) i) = (w i) • std_basis R (λ_:n, R) i :=
begin
ext a j,
simp only [linear_map.comp_apply, smul_apply, to_lin_apply, mul_vec_diagonal, smul_apply,
pi.smul_apply, smul_eq_mul],
by_cases i = j,
{ subst h },
{ rw [std_basis_ne R (λ_:n, R) _ _ (ne.symm h), _root_.mul_zero, _root_.mul_zero] }
end
end ring
section vector_space
variables {K : Type u} [discrete_field K] -- maybe try to relax the universe constraint
open linear_map matrix
lemma rank_vec_mul_vec [decidable_eq n] (w : m → K) (v : n → K) :
rank (vec_mul_vec w v).to_lin ≤ 1 :=
begin
rw [vec_mul_vec_eq, mul_to_lin],
refine le_trans (rank_comp_le1 _ _) _,
refine le_trans (rank_le_domain _) _,
rw [dim_fun', ← cardinal.fintype_card],
exact le_refl _
end
set_option class.instance_max_depth 100
lemma diagonal_to_lin [decidable_eq m] (w : m → K) :
(diagonal w).to_lin = linear_map.pi (λi, w i • linear_map.proj i) :=
by ext v j; simp [mul_vec_diagonal]
lemma ker_diagonal_to_lin [decidable_eq m] (w : m → K) :
ker (diagonal w).to_lin = (⨆i∈{i | w i = 0 }, range (std_basis K (λi, K) i)) :=
begin
rw [← comap_bot, ← infi_ker_proj],
simp only [comap_infi, (ker_comp _ _).symm, proj_diagonal, ker_smul'],
have : univ ⊆ {i : m | w i = 0} ∪ -{i : m | w i = 0}, { rw set.union_compl_self },
exact (supr_range_std_basis_eq_infi_ker_proj K (λi:m, K)
(disjoint_compl {i | w i = 0}) this (finite.of_fintype _)).symm
end
lemma range_diagonal [decidable_eq m] (w : m → K) :
(diagonal w).to_lin.range = (⨆ i ∈ {i | w i ≠ 0}, (std_basis K (λi, K) i).range) :=
begin
dsimp only [mem_set_of_eq],
rw [← map_top, ← supr_range_std_basis, map_supr],
congr, funext i,
rw [← linear_map.range_comp, diagonal_comp_std_basis, range_smul'],
end
lemma rank_diagonal [decidable_eq m] (w : m → K) :
rank (diagonal w).to_lin = fintype.card { i // w i ≠ 0 } :=
begin
have hu : univ ⊆ - {i : m | w i = 0} ∪ {i : m | w i = 0}, { rw set.compl_union_self },
have hd : disjoint {i : m | w i ≠ 0} {i : m | w i = 0} := (disjoint_compl {i | w i = 0}).symm,
have h₁ := supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) hd hu (finite.of_fintype _),
have h₂ := @infi_ker_proj_equiv K _ _ (λi:m, K) _ _ _ _ (by simp; apply_instance) hd hu,
rw [rank, range_diagonal, h₁, ←@dim_fun' K],
apply linear_equiv.dim_eq,
apply h₂,
end
end vector_space
end matrix
|
524994a53198c25e682708f496ed3fbc23d41e26 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/analysis/special_functions/exp.lean | b18a4cc78b02a33cacc2310f2ef2a83924d724cc | [
"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 | 10,442 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import analysis.complex.basic
import data.complex.exponential
/-!
# Complex and real exponential
In this file we prove continuity of `complex.exp` and `real.exp`. We also prove a few facts about
limits of `real.exp` at infinity.
## Tags
exp
-/
noncomputable theory
open finset filter metric asymptotics set function
open_locale classical topological_space
namespace complex
variables {z y x : ℝ}
lemma exp_bound_sq (x z : ℂ) (hz : ∥z∥ ≤ 1) :
∥exp (x + z) - exp x - z • exp x∥ ≤ ∥exp x∥ * ∥z∥ ^ 2 :=
calc ∥exp (x + z) - exp x - z * exp x∥
= ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring }
... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _
... ≤ ∥exp x∥ * ∥z∥^2 : mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le hz) (norm_nonneg _)
lemma locally_lipschitz_exp {r : ℝ} (hr_nonneg : 0 ≤ r) (hr_le : r ≤ 1) (x y : ℂ)
(hyx : ∥y - x∥ < r) :
∥exp y - exp x∥ ≤ (1 + r) * ∥exp x∥ * ∥y - x∥ :=
begin
have hy_eq : y = x + (y - x), by abel,
have hyx_sq_le : ∥y - x∥ ^ 2 ≤ r * ∥y - x∥,
{ rw pow_two,
exact mul_le_mul hyx.le le_rfl (norm_nonneg _) hr_nonneg, },
have h_sq : ∀ z, ∥z∥ ≤ 1 → ∥exp (x + z) - exp x∥ ≤ ∥z∥ * ∥exp x∥ + ∥exp x∥ * ∥z∥ ^ 2,
{ intros z hz,
have : ∥exp (x + z) - exp x - z • exp x∥ ≤ ∥exp x∥ * ∥z∥ ^ 2, from exp_bound_sq x z hz,
rw [← sub_le_iff_le_add', ← norm_smul z],
exact (norm_sub_norm_le _ _).trans this, },
calc ∥exp y - exp x∥ = ∥exp (x + (y - x)) - exp x∥ : by nth_rewrite 0 hy_eq
... ≤ ∥y - x∥ * ∥exp x∥ + ∥exp x∥ * ∥y - x∥ ^ 2 : h_sq (y - x) (hyx.le.trans hr_le)
... ≤ ∥y - x∥ * ∥exp x∥ + ∥exp x∥ * (r * ∥y - x∥) :
add_le_add_left (mul_le_mul le_rfl hyx_sq_le (sq_nonneg _) (norm_nonneg _)) _
... = (1 + r) * ∥exp x∥ * ∥y - x∥ : by ring,
end
@[continuity] lemma continuous_exp : continuous exp :=
continuous_iff_continuous_at.mpr $
λ x, continuous_at_of_locally_lipschitz zero_lt_one (2 * ∥exp x∥)
(locally_lipschitz_exp zero_le_one le_rfl x)
lemma continuous_on_exp {s : set ℂ} : continuous_on exp s :=
continuous_exp.continuous_on
end complex
section complex_continuous_exp_comp
variable {α : Type*}
open complex
lemma filter.tendsto.cexp {l : filter α} {f : α → ℂ} {z : ℂ} (hf : tendsto f l (𝓝 z)) :
tendsto (λ x, exp (f x)) l (𝓝 (exp z)) :=
(continuous_exp.tendsto _).comp hf
variables [topological_space α] {f : α → ℂ} {s : set α} {x : α}
lemma continuous_within_at.cexp (h : continuous_within_at f s x) :
continuous_within_at (λ y, exp (f y)) s x :=
h.cexp
lemma continuous_at.cexp (h : continuous_at f x) : continuous_at (λ y, exp (f y)) x :=
h.cexp
lemma continuous_on.cexp (h : continuous_on f s) : continuous_on (λ y, exp (f y)) s :=
λ x hx, (h x hx).cexp
lemma continuous.cexp (h : continuous f) : continuous (λ y, exp (f y)) :=
continuous_iff_continuous_at.2 $ λ x, h.continuous_at.cexp
end complex_continuous_exp_comp
namespace real
@[continuity] lemma continuous_exp : continuous exp :=
complex.continuous_re.comp complex.continuous_of_real.cexp
lemma continuous_on_exp {s : set ℝ} : continuous_on exp s :=
continuous_exp.continuous_on
end real
section real_continuous_exp_comp
variable {α : Type*}
open real
lemma filter.tendsto.exp {l : filter α} {f : α → ℝ} {z : ℝ} (hf : tendsto f l (𝓝 z)) :
tendsto (λ x, exp (f x)) l (𝓝 (exp z)) :=
(continuous_exp.tendsto _).comp hf
variables [topological_space α] {f : α → ℝ} {s : set α} {x : α}
lemma continuous_within_at.exp (h : continuous_within_at f s x) :
continuous_within_at (λ y, exp (f y)) s x :=
h.exp
lemma continuous_at.exp (h : continuous_at f x) : continuous_at (λ y, exp (f y)) x :=
h.exp
lemma continuous_on.exp (h : continuous_on f s) : continuous_on (λ y, exp (f y)) s :=
λ x hx, (h x hx).exp
lemma continuous.exp (h : continuous f) : continuous (λ y, exp (f y)) :=
continuous_iff_continuous_at.2 $ λ x, h.continuous_at.exp
end real_continuous_exp_comp
namespace real
variables {x y z : ℝ}
/-- The real exponential function tends to `+∞` at `+∞`. -/
lemma tendsto_exp_at_top : tendsto exp at_top at_top :=
begin
have A : tendsto (λx:ℝ, x + 1) at_top at_top :=
tendsto_at_top_add_const_right at_top 1 tendsto_id,
have B : ∀ᶠ x in at_top, x + 1 ≤ exp x :=
eventually_at_top.2 ⟨0, λx hx, add_one_le_exp x⟩,
exact tendsto_at_top_mono' at_top B A
end
/-- The real exponential function tends to `0` at `-∞` or, equivalently, `exp(-x)` tends to `0`
at `+∞` -/
lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) :=
(tendsto_inv_at_top_zero.comp tendsto_exp_at_top).congr (λx, (exp_neg x).symm)
/-- The real exponential function tends to `1` at `0`. -/
lemma tendsto_exp_nhds_0_nhds_1 : tendsto exp (𝓝 0) (𝓝 1) :=
by { convert continuous_exp.tendsto 0, simp }
lemma tendsto_exp_at_bot : tendsto exp at_bot (𝓝 0) :=
(tendsto_exp_neg_at_top_nhds_0.comp tendsto_neg_at_bot_at_top).congr $
λ x, congr_arg exp $ neg_neg x
lemma tendsto_exp_at_bot_nhds_within : tendsto exp at_bot (𝓝[>] 0) :=
tendsto_inf.2 ⟨tendsto_exp_at_bot, tendsto_principal.2 $ eventually_of_forall exp_pos⟩
/-- The function `exp(x)/x^n` tends to `+∞` at `+∞`, for any natural number `n` -/
lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top :=
begin
refine (at_top_basis_Ioi.tendsto_iff (at_top_basis' 1)).2 (λ C hC₁, _),
have hC₀ : 0 < C, from zero_lt_one.trans_le hC₁,
have : 0 < (exp 1 * C)⁻¹ := inv_pos.2 (mul_pos (exp_pos _) hC₀),
obtain ⟨N, hN⟩ : ∃ N, ∀ k ≥ N, (↑k ^ n : ℝ) / exp 1 ^ k < (exp 1 * C)⁻¹ :=
eventually_at_top.1 ((tendsto_pow_const_div_const_pow_of_one_lt n
(one_lt_exp_iff.2 zero_lt_one)).eventually (gt_mem_nhds this)),
simp only [← exp_nat_mul, mul_one, div_lt_iff, exp_pos, ← div_eq_inv_mul] at hN,
refine ⟨N, trivial, λ x hx, _⟩, rw set.mem_Ioi at hx,
have hx₀ : 0 < x, from N.cast_nonneg.trans_lt hx,
rw [set.mem_Ici, le_div_iff (pow_pos hx₀ _), ← le_div_iff' hC₀],
calc x ^ n ≤ ⌈x⌉₊ ^ n : pow_le_pow_of_le_left hx₀.le (nat.le_ceil _) _
... ≤ exp ⌈x⌉₊ / (exp 1 * C) : (hN _ (nat.lt_ceil.2 hx).le).le
... ≤ exp (x + 1) / (exp 1 * C) : div_le_div_of_le (mul_pos (exp_pos _) hC₀).le
(exp_le_exp.2 $ (nat.ceil_lt_add_one hx₀.le).le)
... = exp x / C : by rw [add_comm, exp_add, mul_div_mul_left _ _ (exp_pos _).ne']
end
/-- The function `x^n * exp(-x)` tends to `0` at `+∞`, for any natural number `n`. -/
lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) :=
(tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx,
by rw [comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg]
/-- The function `(b * exp x + c) / (x ^ n)` tends to `+∞` at `+∞`, for any positive natural number
`n` and any real numbers `b` and `c` such that `b` is positive. -/
lemma tendsto_mul_exp_add_div_pow_at_top (b c : ℝ) (n : ℕ) (hb : 0 < b) (hn : 1 ≤ n) :
tendsto (λ x, (b * (exp x) + c) / (x^n)) at_top at_top :=
begin
refine tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) _)
(((tendsto_exp_div_pow_at_top n).const_mul_at_top hb).at_top_add
((tendsto_pow_neg_at_top hn).mul (@tendsto_const_nhds _ _ _ c _))),
intros x hx,
simp only [zpow_neg₀ x n],
ring,
end
/-- The function `(x ^ n) / (b * exp x + c)` tends to `0` at `+∞`, for any positive natural number
`n` and any real numbers `b` and `c` such that `b` is nonzero. -/
lemma tendsto_div_pow_mul_exp_add_at_top (b c : ℝ) (n : ℕ) (hb : 0 ≠ b) (hn : 1 ≤ n) :
tendsto (λ x, x^n / (b * (exp x) + c)) at_top (𝓝 0) :=
begin
have H : ∀ d e, 0 < d → tendsto (λ (x:ℝ), x^n / (d * (exp x) + e)) at_top (𝓝 0),
{ intros b' c' h,
convert (tendsto_mul_exp_add_div_pow_at_top b' c' n h hn).inv_tendsto_at_top ,
ext x,
simpa only [pi.inv_apply] using inv_div.symm },
cases lt_or_gt_of_ne hb,
{ exact H b c h },
{ convert (H (-b) (-c) (neg_pos.mpr h)).neg,
{ ext x,
field_simp,
rw [← neg_add (b * exp x) c, neg_div_neg_eq] },
{ exact neg_zero.symm } },
end
/-- `real.exp` as an order isomorphism between `ℝ` and `(0, +∞)`. -/
def exp_order_iso : ℝ ≃o Ioi (0 : ℝ) :=
strict_mono.order_iso_of_surjective _ (exp_strict_mono.cod_restrict exp_pos) $
(continuous_subtype_mk _ continuous_exp).surjective
(by simp only [tendsto_Ioi_at_top, subtype.coe_mk, tendsto_exp_at_top])
(by simp [tendsto_exp_at_bot_nhds_within])
@[simp] lemma coe_exp_order_iso_apply (x : ℝ) : (exp_order_iso x : ℝ) = exp x := rfl
@[simp] lemma coe_comp_exp_order_iso : coe ∘ exp_order_iso = exp := rfl
@[simp] lemma range_exp : range exp = Ioi 0 :=
by rw [← coe_comp_exp_order_iso, range_comp, exp_order_iso.range_eq, image_univ, subtype.range_coe]
@[simp] lemma map_exp_at_top : map exp at_top = at_top :=
by rw [← coe_comp_exp_order_iso, ← filter.map_map, order_iso.map_at_top, map_coe_Ioi_at_top]
@[simp] lemma comap_exp_at_top : comap exp at_top = at_top :=
by rw [← map_exp_at_top, comap_map exp_injective, map_exp_at_top]
@[simp] lemma tendsto_exp_comp_at_top {α : Type*} {l : filter α} {f : α → ℝ} :
tendsto (λ x, exp (f x)) l at_top ↔ tendsto f l at_top :=
by rw [← tendsto_comap_iff, comap_exp_at_top]
lemma tendsto_comp_exp_at_top {α : Type*} {l : filter α} {f : ℝ → α} :
tendsto (λ x, f (exp x)) at_top l ↔ tendsto f at_top l :=
by rw [← tendsto_map'_iff, map_exp_at_top]
@[simp] lemma map_exp_at_bot : map exp at_bot = 𝓝[>] 0 :=
by rw [← coe_comp_exp_order_iso, ← filter.map_map, exp_order_iso.map_at_bot, ← map_coe_Ioi_at_bot]
lemma comap_exp_nhds_within_Ioi_zero : comap exp (𝓝[>] 0) = at_bot :=
by rw [← map_exp_at_bot, comap_map exp_injective]
lemma tendsto_comp_exp_at_bot {α : Type*} {l : filter α} {f : ℝ → α} :
tendsto (λ x, f (exp x)) at_bot l ↔ tendsto f (𝓝[>] 0) l :=
by rw [← map_exp_at_bot, tendsto_map'_iff]
end real
|
ffc907aaa91aefa75d77a6444e63ab922c431954 | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/sheaves/sheaf.lean | 72f586d4373785579fca80ac9a4230224c43055a | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 4,290 | 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_condition.equalizer_products
import category_theory.full_subcategory
/-!
# Sheaves
We define sheaves on a topological space, with values in an arbitrary category with products.
The sheaf condition for a `F : presheaf C X` requires that the morphism
`F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`)
is the equalizer of the two morphisms
`∏ F.obj (U i) ⟶ ∏ F.obj (U i ⊓ U j)`.
We provide the instance `category (sheaf C X)` as the full subcategory of presheaves,
and the fully faithful functor `sheaf.forget : sheaf C X ⥤ presheaf C X`.
## Equivalent conditions
While the "official" definition is in terms of an equalizer diagram,
in `src/topology/sheaves/sheaf_condition/pairwise_intersections.lean`
and in `src/topology/sheaves/sheaf_condition/open_le_cover.lean`
we provide two equivalent conditions (and prove they are equivalent).
The first is that `F.obj U` is the limit point of the diagram consisting of all the `F.obj (U i)`
and `F.obj (U i ⊓ U j)`.
(That is, we explode the equalizer of two products out into its component pieces.)
The second is that `F.obj U` is the limit point of the diagram constisting of all the `F.obj V`,
for those `V : opens X` such that `V ≤ U i` for some `i`.
(This condition is particularly easy to state, and perhaps should become the "official" definition.)
-/
universes v u
noncomputable theory
open category_theory
open category_theory.limits
open topological_space
open opposite
open topological_space.opens
namespace Top
variables {C : Type u} [category.{v} C] [has_products C]
variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X)
namespace presheaf
open sheaf_condition_equalizer_products
/--
The sheaf condition for a `F : presheaf C X` requires that the morphism
`F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`)
is the equalizer of the two morphisms
`∏ F.obj (U i) ⟶ ∏ F.obj (U i) ⊓ (U j)`.
-/
-- One might prefer to work with sets of opens, rather than indexed families,
-- which would reduce the universe level here to `max u v`.
-- However as it's a subsingleton the universe level doesn't matter much.
@[derive subsingleton]
def sheaf_condition (F : presheaf C X) : Type (max u (v+1)) :=
Π ⦃ι : Type v⦄ (U : ι → opens X), is_limit (sheaf_condition_equalizer_products.fork F U)
/--
The presheaf valued in `punit` over any topological space is a sheaf.
-/
def sheaf_condition_punit (F : presheaf (category_theory.discrete punit) X) :
sheaf_condition F :=
λ ι U, punit_cone_is_limit
-- Let's construct a trivial example, to keep the inhabited linter happy.
instance sheaf_condition_inhabited (F : presheaf (category_theory.discrete punit) X) :
inhabited (sheaf_condition F) := ⟨sheaf_condition_punit F⟩
/--
Transfer the sheaf condition across an isomorphism of presheaves.
-/
def sheaf_condition_equiv_of_iso {F G : presheaf C X} (α : F ≅ G) :
sheaf_condition F ≃ sheaf_condition G :=
equiv_of_subsingleton_of_subsingleton
(λ c ι U, is_limit.of_iso_limit
((is_limit.postcompose_inv_equiv _ _).symm (c U)) (sheaf_condition_equalizer_products.fork.iso_of_iso U α.symm).symm)
(λ c ι U, is_limit.of_iso_limit
((is_limit.postcompose_inv_equiv _ _).symm (c U)) (sheaf_condition_equalizer_products.fork.iso_of_iso U α).symm)
end presheaf
variables (C X)
/--
A `sheaf C X` is a presheaf of objects from `C` over a (bundled) topological space `X`,
satisfying the sheaf condition.
-/
structure sheaf :=
(presheaf : presheaf C X)
(sheaf_condition : presheaf.sheaf_condition)
instance : category (sheaf C X) := induced_category.category sheaf.presheaf
-- Let's construct a trivial example, to keep the inhabited linter happy.
instance sheaf_inhabited : inhabited (sheaf (category_theory.discrete punit) X) :=
⟨{ presheaf := functor.star _, sheaf_condition := default _ }⟩
namespace sheaf
/--
The forgetful functor from sheaves to presheaves.
-/
@[derive [full, faithful]]
def forget : Top.sheaf C X ⥤ Top.presheaf C X := induced_functor sheaf.presheaf
end sheaf
end Top
|
b3f3916393e1bf8996f24b06f363d0a094604f70 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/analysis/complex/isometry.lean | db8eb79a5c6811ed867518c1b0737a08ceebf07b | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 6,699 | lean | /-
Copyright (c) 2021 François Sunatori. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: François Sunatori
-/
import analysis.complex.circle
import linear_algebra.determinant
import linear_algebra.general_linear_group
/-!
# Isometries of the Complex Plane
The lemma `linear_isometry_complex` states the classification of isometries in the complex plane.
Specifically, isometries with rotations but without translation.
The proof involves:
1. creating a linear isometry `g` with two fixed points, `g(0) = 0`, `g(1) = 1`
2. applying `linear_isometry_complex_aux` to `g`
The proof of `linear_isometry_complex_aux` is separated in the following parts:
1. show that the real parts match up: `linear_isometry.re_apply_eq_re`
2. show that I maps to either I or -I
3. every z is a linear combination of a + b * I
## References
* [Isometries of the Complex Plane](http://helmut.knaust.info/mediawiki/images/b/b5/Iso.pdf)
-/
noncomputable theory
open complex
open_locale complex_conjugate
local notation `|` x `|` := complex.abs x
/-- An element of the unit circle defines a `linear_isometry_equiv` from `ℂ` to itself, by
rotation. -/
def rotation : circle →* (ℂ ≃ₗᵢ[ℝ] ℂ) :=
{ to_fun := λ a,
{ norm_map' := λ x, show |a * x| = |x|, by rw [complex.abs_mul, abs_coe_circle, one_mul],
..distrib_mul_action.to_linear_equiv ℝ ℂ a },
map_one' := linear_isometry_equiv.ext $ one_smul _,
map_mul' := λ _ _, linear_isometry_equiv.ext $ mul_smul _ _ }
@[simp] lemma rotation_apply (a : circle) (z : ℂ) : rotation a z = a * z := rfl
@[simp] lemma rotation_symm (a : circle) : (rotation a).symm = rotation a⁻¹ :=
linear_isometry_equiv.ext $ λ x, rfl
@[simp] lemma rotation_trans (a b : circle) :
(rotation a).trans (rotation b) = rotation (b * a) :=
by { ext1, simp }
lemma rotation_ne_conj_lie (a : circle) : rotation a ≠ conj_lie :=
begin
intro h,
have h1 : rotation a 1 = conj 1 := linear_isometry_equiv.congr_fun h 1,
have hI : rotation a I = conj I := linear_isometry_equiv.congr_fun h I,
rw [rotation_apply, ring_hom.map_one, mul_one] at h1,
rw [rotation_apply, conj_I, ← neg_one_mul, mul_left_inj' I_ne_zero, h1, eq_neg_self_iff] at hI,
exact one_ne_zero hI,
end
/-- Takes an element of `ℂ ≃ₗᵢ[ℝ] ℂ` and checks if it is a rotation, returns an element of the
unit circle. -/
@[simps]
def rotation_of (e : ℂ ≃ₗᵢ[ℝ] ℂ) : circle :=
⟨(e 1) / complex.abs (e 1), by simp⟩
@[simp]
lemma rotation_of_rotation (a : circle) : rotation_of (rotation a) = a :=
subtype.ext $ by simp
lemma rotation_injective : function.injective rotation :=
function.left_inverse.injective rotation_of_rotation
lemma linear_isometry.re_apply_eq_re_of_add_conj_eq (f : ℂ →ₗᵢ[ℝ] ℂ)
(h₃ : ∀ z, z + conj z = f z + conj (f z)) (z : ℂ) : (f z).re = z.re :=
by simpa [ext_iff, add_re, add_im, conj_re, conj_im, ←two_mul,
(show (2 : ℝ) ≠ 0, by simp [two_ne_zero'])] using (h₃ z).symm
lemma linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ}
(h₂ : ∀ z, (f z).re = z.re) (z : ℂ) :
(f z).im = z.im ∨ (f z).im = -z.im :=
begin
have h₁ := f.norm_map z,
simp only [complex.abs, norm_eq_abs] at h₁,
rwa [real.sqrt_inj (norm_sq_nonneg _) (norm_sq_nonneg _), norm_sq_apply (f z), norm_sq_apply z,
h₂, add_left_cancel_iff, mul_self_eq_mul_self_iff] at h₁,
end
lemma linear_isometry.im_apply_eq_im {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) :
z + conj z = f z + conj (f z) :=
begin
have : ∥f z - 1∥ = ∥z - 1∥ := by rw [← f.norm_map (z - 1), f.map_sub, h],
apply_fun λ x, x ^ 2 at this,
simp only [norm_eq_abs, ←norm_sq_eq_abs] at this,
rw [←of_real_inj, ←mul_conj, ←mul_conj] at this,
rw [ring_hom.map_sub, ring_hom.map_sub] at this,
simp only [sub_mul, mul_sub, one_mul, mul_one] at this,
rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs, linear_isometry.norm_map] at this,
rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs] at this,
simp only [sub_sub, sub_right_inj, mul_one, of_real_pow, ring_hom.map_one, norm_eq_abs] at this,
simp only [add_sub, sub_left_inj] at this,
rw [add_comm, ←this, add_comm],
end
lemma linear_isometry.re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) : (f z).re = z.re :=
begin
apply linear_isometry.re_apply_eq_re_of_add_conj_eq,
intro z,
apply linear_isometry.im_apply_eq_im h,
end
lemma linear_isometry_complex_aux {f : ℂ ≃ₗᵢ[ℝ] ℂ} (h : f 1 = 1) :
f = linear_isometry_equiv.refl ℝ ℂ ∨ f = conj_lie :=
begin
have h0 : f I = I ∨ f I = -I,
{ have : |f I| = 1 := by simpa using f.norm_map complex.I,
simp only [ext_iff, ←and_or_distrib_left, neg_re, I_re, neg_im, neg_zero],
split,
{ rw ←I_re,
exact @linear_isometry.re_apply_eq_re f.to_linear_isometry h I, },
{ apply @linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re f.to_linear_isometry,
intro z, rw @linear_isometry.re_apply_eq_re f.to_linear_isometry h } },
refine h0.imp (λ h' : f I = I, _) (λ h' : f I = -I, _);
{ apply linear_isometry_equiv.to_linear_equiv_injective,
apply complex.basis_one_I.ext',
intros i,
fin_cases i; simp [h, h'] }
end
lemma linear_isometry_complex (f : ℂ ≃ₗᵢ[ℝ] ℂ) :
∃ a : circle, f = rotation a ∨ f = conj_lie.trans (rotation a) :=
begin
let a : circle := ⟨f 1, by simpa using f.norm_map 1⟩,
use a,
have : (f.trans (rotation a).symm) 1 = 1,
{ simpa using rotation_apply a⁻¹ (f 1) },
refine (linear_isometry_complex_aux this).imp (λ h₁, _) (λ h₂, _),
{ simpa using eq_mul_of_inv_mul_eq h₁ },
{ exact eq_mul_of_inv_mul_eq h₂ }
end
/-- The matrix representation of `rotation a` is equal to the conformal matrix
`!![re a, -im a; im a, re a]`. -/
lemma to_matrix_rotation (a : circle) :
linear_map.to_matrix basis_one_I basis_one_I (rotation a).to_linear_equiv =
matrix.plane_conformal_matrix (re a) (im a) (by simp [pow_two, ←norm_sq_apply]) :=
begin
ext i j,
simp [linear_map.to_matrix_apply],
fin_cases i; fin_cases j; simp
end
/-- The determinant of `rotation` (as a linear map) is equal to `1`. -/
@[simp] lemma det_rotation (a : circle) : ((rotation a).to_linear_equiv : ℂ →ₗ[ℝ] ℂ).det = 1 :=
begin
rw [←linear_map.det_to_matrix basis_one_I, to_matrix_rotation, matrix.det_fin_two],
simp [←norm_sq_apply]
end
/-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/
@[simp] lemma linear_equiv_det_rotation (a : circle) : (rotation a).to_linear_equiv.det = 1 :=
by rw [←units.eq_iff, linear_equiv.coe_det, det_rotation, units.coe_one]
|
148e5d20ebbf02402351c347ffd497100fc80842 | 95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990 | /src/analysis/normed_space/bounded_linear_maps.lean | 45af40f0447fbd4ab57cba2b1cf519c2bd2df56d | [
"Apache-2.0"
] | permissive | uniformity1/mathlib | 829341bad9dfa6d6be9adaacb8086a8a492e85a4 | dd0e9bd8f2e5ec267f68e72336f6973311909105 | refs/heads/master | 1,588,592,015,670 | 1,554,219,842,000 | 1,554,219,842,000 | 179,110,702 | 0 | 0 | Apache-2.0 | 1,554,220,076,000 | 1,554,220,076,000 | null | UTF-8 | Lean | false | false | 6,772 | 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
Continuous linear functions -- functions between normed vector spaces which are bounded and linear.
-/
import algebra.field
import tactic.norm_num
import analysis.normed_space.basic
import analysis.asymptotics
@[simp] lemma mul_inv_eq' {α} [discrete_field α] (a b : α) : (a * b)⁻¹ = b⁻¹ * a⁻¹ :=
classical.by_cases (assume : a = 0, by simp [this]) $ assume ha,
classical.by_cases (assume : b = 0, by simp [this]) $ assume hb,
mul_inv_eq hb ha
noncomputable theory
local attribute [instance] classical.prop_decidable
local notation f ` →_{`:50 a `} `:0 b := filter.tendsto f (nhds a) (nhds b)
open filter (tendsto)
open metric
variables {k : Type*} [normed_field k]
variables {E : Type*} [normed_space k E]
variables {F : Type*} [normed_space k F]
variables {G : Type*} [normed_space k G]
structure is_bounded_linear_map (k : Type*)
[normed_field k] {E : Type*} [normed_space k E] {F : Type*} [normed_space k F] (L : E → F)
extends is_linear_map k L : Prop :=
(bound : ∃ M, M > 0 ∧ ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥)
include k
lemma is_linear_map.with_bound
{L : E → F} (hf : is_linear_map k L) (M : ℝ) (h : ∀ x : E, ∥ L x ∥ ≤ M * ∥ x ∥) :
is_bounded_linear_map k L :=
⟨ hf, classical.by_cases
(assume : M ≤ 0, ⟨1, zero_lt_one, assume x,
le_trans (h x) $ mul_le_mul_of_nonneg_right (le_trans this zero_le_one) (norm_nonneg x)⟩)
(assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩
namespace is_bounded_linear_map
def to_linear_map (f : E → F) (h : is_bounded_linear_map k f) : E →ₗ[k] F :=
(is_linear_map.mk' _ h.to_is_linear_map)
lemma zero : is_bounded_linear_map k (λ (x:E), (0:F)) :=
(0 : E →ₗ F).is_linear.with_bound 0 $ by simp [le_refl]
lemma id : is_bounded_linear_map k (λ (x:E), x) :=
linear_map.id.is_linear.with_bound 1 $ by simp [le_refl]
set_option class.instance_max_depth 43
lemma smul {f : E → F} (c : k) : is_bounded_linear_map k f → is_bounded_linear_map k (λ e, c • f e)
| ⟨hf, ⟨M, hM, h⟩⟩ := (c • hf.mk' f).is_linear.with_bound (∥c∥ * M) $ assume x,
calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x)
... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (h x) (norm_nonneg c)
... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm
lemma neg {f : E → F} (hf : is_bounded_linear_map k f) : is_bounded_linear_map k (λ e, -f e) :=
begin
rw show (λ e, -f e) = (λ e, (-1 : k) • f e), { funext, simp },
exact smul (-1) hf
end
lemma add {f : E → F} {g : E → F} :
is_bounded_linear_map k f → is_bounded_linear_map k g → is_bounded_linear_map k (λ e, f e + g e)
| ⟨hlf, Mf, hMf, hf⟩ ⟨hlg, Mg, hMg, hg⟩ := (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ assume x,
calc ∥f x + g x∥ ≤ ∥f x∥ + ∥g x∥ : norm_triangle _ _
... ≤ Mf * ∥x∥ + Mg * ∥x∥ : add_le_add (hf x) (hg x)
... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul
lemma sub {f : E → F} {g : E → F} (hf : is_bounded_linear_map k f) (hg : is_bounded_linear_map k g) :
is_bounded_linear_map k (λ e, f e - g e) := add hf (neg hg)
lemma comp {f : E → F} {g : F → G} :
is_bounded_linear_map k g → is_bounded_linear_map k f → is_bounded_linear_map k (g ∘ f)
| ⟨hlg, Mg, hMg, hg⟩ ⟨hlf, Mf, hMf, hf⟩ := ((hlg.mk' _).comp (hlf.mk' _)).is_linear.with_bound (Mg * Mf) $ assume x,
calc ∥g (f x)∥ ≤ Mg * ∥f x∥ : hg _
... ≤ Mg * (Mf * ∥x∥) : mul_le_mul_of_nonneg_left (hf _) (le_of_lt hMg)
... = Mg * Mf * ∥x∥ : (mul_assoc _ _ _).symm
lemma tendsto {L : E → F} (x : E) : is_bounded_linear_map k L → L →_{x} (L x)
| ⟨hL, M, hM, h_ineq⟩ := tendsto_iff_norm_tendsto_zero.2 $
squeeze_zero (assume e, norm_nonneg _)
(assume e, calc ∥L e - L x∥ = ∥hL.mk' L (e - x)∥ : by rw (hL.mk' _).map_sub e x; refl
... ≤ M*∥e-x∥ : h_ineq (e-x))
(suffices (λ (e : E), M * ∥e - x∥) →_{x} (M * 0), by simpa,
tendsto_mul tendsto_const_nhds (lim_norm _))
lemma continuous {L : E → F} (hL : is_bounded_linear_map k L) : continuous L :=
continuous_iff_continuous_at.2 $ assume x, hL.tendsto x
lemma lim_zero_bounded_linear_map {L : E → F} (H : is_bounded_linear_map k L) : (L →_{0} 0) :=
(H.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 H.continuous 0
section
open asymptotics filter
theorem is_O_id {L : E → F} (h : is_bounded_linear_map k L) (l : filter E) :
is_O L (λ x, x) l :=
let ⟨M, Mpos, hM⟩ := h.bound in
⟨M, Mpos, mem_sets_of_superset univ_mem_sets (λ x _, hM x)⟩
theorem is_O_comp {L : F → G} (h : is_bounded_linear_map k L)
{f : E → F} (l : filter E) : is_O (λ x', L (f x')) f l :=
((h.is_O_id ⊤).comp _).mono (map_le_iff_le_comap.mp lattice.le_top)
theorem is_O_sub {L : E → F} (h : is_bounded_linear_map k L) (l : filter E) (x : E) :
is_O (λ x', L (x' - x)) (λ x', x' - x) l :=
is_O_comp h l
end
end is_bounded_linear_map
set_option class.instance_max_depth 34
-- Next lemma is stated for real normed space but it would work as soon as the base field is an extension of ℝ
lemma bounded_continuous_linear_map
{E : Type*} [normed_space ℝ E] {F : Type*} [normed_space ℝ F] {L : E → F}
(lin : is_linear_map ℝ L) (cont : continuous L) : is_bounded_linear_map ℝ L :=
let ⟨δ, δ_pos, hδ⟩ := exists_delta_of_continuous cont zero_lt_one 0 in
have HL0 : L 0 = 0, from (lin.mk' _).map_zero,
have H : ∀{a}, ∥a∥ ≤ δ → ∥L a∥ < 1, by simpa only [HL0, dist_zero_right] using hδ,
lin.with_bound (δ⁻¹) $ assume x,
classical.by_cases (assume : x = 0, by simp only [this, HL0, norm_zero, mul_zero]) $
assume h : x ≠ 0,
let p := ∥x∥ * δ⁻¹, q := p⁻¹ in
have p_inv : p⁻¹ = δ*∥x∥⁻¹, by simp,
have norm_x_pos : ∥x∥ > 0 := (norm_pos_iff x).2 h,
have norm_x : ∥x∥ ≠ 0 := mt (norm_eq_zero x).1 h,
have p_pos : p > 0 := mul_pos norm_x_pos (inv_pos δ_pos),
have p0 : _ := ne_of_gt p_pos,
have q_pos : q > 0 := inv_pos p_pos,
have q0 : _ := ne_of_gt q_pos,
have ∥p⁻¹ • x∥ = δ := calc
∥p⁻¹ • x∥ = abs p⁻¹ * ∥x∥ : by rw norm_smul; refl
... = p⁻¹ * ∥x∥ : by rw [abs_of_nonneg $ le_of_lt q_pos]
... = δ : by simp [mul_assoc, inv_mul_cancel norm_x],
calc ∥L x∥ = (p * q) * ∥L x∥ : begin dsimp [q], rw [mul_inv_cancel p0, one_mul] end
... = p * ∥L (q • x)∥ : by simp [lin.smul, norm_smul, real.norm_eq_abs, abs_of_pos q_pos, mul_assoc]
... ≤ p * 1 : mul_le_mul_of_nonneg_left (le_of_lt $ H $ le_of_eq $ this) (le_of_lt p_pos)
... = δ⁻¹ * ∥x∥ : by rw [mul_one, mul_comm]
|
24c00a7b3d6187e7c13d7be8a9e40a0ecbf57528 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/limits/creates.lean | 0afabc356cc8af234ecc6344b8479b0048da63d0 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 18,106 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.limits.preserves.basic
open category_theory category_theory.limits
noncomputable theory
namespace category_theory
universes v u₁ u₂ u₃
variables {C : Type u₁} [category.{v} C]
section creates
variables {D : Type u₂} [category.{v} D]
variables {J : Type v} [small_category J] {K : J ⥤ C}
/--
Define the lift of a cone: For a cone `c` for `K ⋙ F`, give a cone for `K`
which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`.
We will then use this as part of the definition of creation of limits:
every limit cone has a lift.
Note this definition is really only useful when `c` is a limit already.
-/
structure liftable_cone (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) :=
(lifted_cone : cone K)
(valid_lift : F.map_cone lifted_cone ≅ c)
/--
Define the lift of a cocone: For a cocone `c` for `K ⋙ F`, give a cocone for
`K` which is a lift of `c`, i.e. the image of it under `F` is (iso) to `c`.
We will then use this as part of the definition of creation of colimits:
every limit cocone has a lift.
Note this definition is really only useful when `c` is a colimit already.
-/
structure liftable_cocone (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) :=
(lifted_cocone : cocone K)
(valid_lift : F.map_cocone lifted_cocone ≅ c)
/--
Definition 3.3.1 of [Riehl].
We say that `F` creates limits of `K` if, given any limit cone `c` for `K ⋙ F`
(i.e. below) we can lift it to a cone "above", and further that `F` reflects
limits for `K`.
If `F` reflects isomorphisms, it suffices to show only that the lifted cone is
a limit - see `creates_limit_of_reflects_iso`.
-/
class creates_limit (K : J ⥤ C) (F : C ⥤ D) extends reflects_limit K F :=
(lifts : Π c, is_limit c → liftable_cone K F c)
/--
`F` creates limits of shape `J` if `F` creates the limit of any diagram
`K : J ⥤ C`.
-/
class creates_limits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) :=
(creates_limit : Π {K : J ⥤ C}, creates_limit K F)
/-- `F` creates limits if it creates limits of shape `J` for any small `J`. -/
class creates_limits (F : C ⥤ D) :=
(creates_limits_of_shape : Π {J : Type v} {𝒥 : small_category J},
by exactI creates_limits_of_shape J F)
/--
Dual of definition 3.3.1 of [Riehl].
We say that `F` creates colimits of `K` if, given any limit cocone `c` for
`K ⋙ F` (i.e. below) we can lift it to a cocone "above", and further that `F`
reflects limits for `K`.
If `F` reflects isomorphisms, it suffices to show only that the lifted cocone is
a limit - see `creates_limit_of_reflects_iso`.
-/
class creates_colimit (K : J ⥤ C) (F : C ⥤ D) extends reflects_colimit K F :=
(lifts : Π c, is_colimit c → liftable_cocone K F c)
/--
`F` creates colimits of shape `J` if `F` creates the colimit of any diagram
`K : J ⥤ C`.
-/
class creates_colimits_of_shape (J : Type v) [small_category J] (F : C ⥤ D) :=
(creates_colimit : Π {K : J ⥤ C}, creates_colimit K F)
/-- `F` creates colimits if it creates colimits of shape `J` for any small `J`. -/
class creates_colimits (F : C ⥤ D) :=
(creates_colimits_of_shape : Π {J : Type v} {𝒥 : small_category J},
by exactI creates_colimits_of_shape J F)
attribute [instance, priority 100] -- see Note [lower instance priority]
creates_limits_of_shape.creates_limit creates_limits.creates_limits_of_shape
creates_colimits_of_shape.creates_colimit creates_colimits.creates_colimits_of_shape
/- Interface to the `creates_limit` class. -/
/-- `lift_limit t` is the cone for `K` given by lifting the limit `t` for `K ⋙ F`. -/
def lift_limit {K : J ⥤ C} {F : C ⥤ D} [creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) :
cone K :=
(creates_limit.lifts c t).lifted_cone
/-- The lifted cone has an image isomorphic to the original cone. -/
def lifted_limit_maps_to_original {K : J ⥤ C} {F : C ⥤ D}
[creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) :
F.map_cone (lift_limit t) ≅ c :=
(creates_limit.lifts c t).valid_lift
/-- The lifted cone is a limit. -/
def lifted_limit_is_limit {K : J ⥤ C} {F : C ⥤ D}
[creates_limit K F] {c : cone (K ⋙ F)} (t : is_limit c) :
is_limit (lift_limit t) :=
reflects_limit.reflects (is_limit.of_iso_limit t (lifted_limit_maps_to_original t).symm)
/-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/
lemma has_limit_of_created (K : J ⥤ C) (F : C ⥤ D)
[has_limit (K ⋙ F)] [creates_limit K F] : has_limit K :=
has_limit.mk { cone := lift_limit (limit.is_limit (K ⋙ F)),
is_limit := lifted_limit_is_limit _ }
/--
If `F` creates limits of shape `J`, and `D` has limits of shape `J`, then
`C` has limits of shape `J`.
-/
lemma has_limits_of_shape_of_has_limits_of_shape_creates_limits_of_shape (F : C ⥤ D)
[has_limits_of_shape J D] [creates_limits_of_shape J F] : has_limits_of_shape J C :=
⟨λ G, has_limit_of_created G F⟩
/-- If `F` creates limits, and `D` has all limits, then `C` has all limits. -/
lemma has_limits_of_has_limits_creates_limits (F : C ⥤ D) [has_limits D] [creates_limits F] :
has_limits C :=
⟨λ J I, by exactI has_limits_of_shape_of_has_limits_of_shape_creates_limits_of_shape F⟩
/- Interface to the `creates_colimit` class. -/
/-- `lift_colimit t` is the cocone for `K` given by lifting the colimit `t` for `K ⋙ F`. -/
def lift_colimit {K : J ⥤ C} {F : C ⥤ D} [creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) :
cocone K :=
(creates_colimit.lifts c t).lifted_cocone
/-- The lifted cocone has an image isomorphic to the original cocone. -/
def lifted_colimit_maps_to_original {K : J ⥤ C} {F : C ⥤ D}
[creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) :
F.map_cocone (lift_colimit t) ≅ c :=
(creates_colimit.lifts c t).valid_lift
/-- The lifted cocone is a colimit. -/
def lifted_colimit_is_colimit {K : J ⥤ C} {F : C ⥤ D}
[creates_colimit K F] {c : cocone (K ⋙ F)} (t : is_colimit c) :
is_colimit (lift_colimit t) :=
reflects_colimit.reflects (is_colimit.of_iso_colimit t (lifted_colimit_maps_to_original t).symm)
/-- If `F` creates the limit of `K` and `K ⋙ F` has a limit, then `K` has a limit. -/
lemma has_colimit_of_created (K : J ⥤ C) (F : C ⥤ D)
[has_colimit (K ⋙ F)] [creates_colimit K F] : has_colimit K :=
has_colimit.mk { cocone := lift_colimit (colimit.is_colimit (K ⋙ F)),
is_colimit := lifted_colimit_is_colimit _ }
/--
If `F` creates colimits of shape `J`, and `D` has colimits of shape `J`, then
`C` has colimits of shape `J`.
-/
lemma has_colimits_of_shape_of_has_colimits_of_shape_creates_colimits_of_shape (F : C ⥤ D)
[has_colimits_of_shape J D] [creates_colimits_of_shape J F] : has_colimits_of_shape J C :=
⟨λ G, has_colimit_of_created G F⟩
/-- If `F` creates colimits, and `D` has all colimits, then `C` has all colimits. -/
lemma has_colimits_of_has_colimits_creates_colimits (F : C ⥤ D) [has_colimits D]
[creates_colimits F] : has_colimits C :=
⟨λ J I, by exactI has_colimits_of_shape_of_has_colimits_of_shape_creates_colimits_of_shape F⟩
/--
A helper to show a functor creates limits. In particular, if we can show
that for any limit cone `c` for `K ⋙ F`, there is a lift of it which is
a limit and `F` reflects isomorphisms, then `F` creates limits.
Usually, `F` creating limits says that _any_ lift of `c` is a limit, but
here we only need to show that our particular lift of `c` is a limit.
-/
structure lifts_to_limit (K : J ⥤ C) (F : C ⥤ D) (c : cone (K ⋙ F)) (t : is_limit c)
extends liftable_cone K F c :=
(makes_limit : is_limit lifted_cone)
/--
A helper to show a functor creates colimits. In particular, if we can show
that for any limit cocone `c` for `K ⋙ F`, there is a lift of it which is
a limit and `F` reflects isomorphisms, then `F` creates colimits.
Usually, `F` creating colimits says that _any_ lift of `c` is a colimit, but
here we only need to show that our particular lift of `c` is a colimit.
-/
structure lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D) (c : cocone (K ⋙ F)) (t : is_colimit c)
extends liftable_cocone K F c :=
(makes_colimit : is_colimit lifted_cocone)
/--
If `F` reflects isomorphisms and we can lift any limit cone to a limit cone,
then `F` creates limits.
In particular here we don't need to assume that F reflects limits.
-/
def creates_limit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F]
(h : Π c t, lifts_to_limit K F c t) :
creates_limit K F :=
{ lifts := λ c t, (h c t).to_liftable_cone,
to_reflects_limit :=
{ reflects := λ (d : cone K) (hd : is_limit (F.map_cone d)),
begin
let d' : cone K := (h (F.map_cone d) hd).to_liftable_cone.lifted_cone,
let i : F.map_cone d' ≅ F.map_cone d := (h (F.map_cone d) hd).to_liftable_cone.valid_lift,
let hd' : is_limit d' := (h (F.map_cone d) hd).makes_limit,
let f : d ⟶ d' := hd'.lift_cone_morphism d,
have : (cones.functoriality K F).map f = i.inv := (hd.of_iso_limit i.symm).uniq_cone_morphism,
haveI : is_iso ((cones.functoriality K F).map f) := (by { rw this, apply_instance }),
haveI : is_iso f := is_iso_of_reflects_iso f (cones.functoriality K F),
exact is_limit.of_iso_limit hd' (as_iso f).symm,
end } }
/--
When `F` is fully faithful, and `has_limit (K ⋙ F)`, to show that `F` creates the limit for `K`
it suffices to exhibit a lift of the chosen limit cone for `K ⋙ F`.
-/
-- Notice however that even if the isomorphism is `iso.refl _`,
-- this construction will insert additional identity morphisms in the cone maps,
-- so the constructed limits may not be ideal, definitionally.
def creates_limit_of_fully_faithful_of_lift {K : J ⥤ C} {F : C ⥤ D}
[full F] [faithful F] [has_limit (K ⋙ F)]
(c : cone K) (i : F.map_cone c ≅ limit.cone (K ⋙ F)) : creates_limit K F :=
creates_limit_of_reflects_iso (λ c' t,
{ lifted_cone := c,
valid_lift := i.trans (is_limit.unique_up_to_iso (limit.is_limit _) t),
makes_limit := is_limit.of_faithful F (is_limit.of_iso_limit (limit.is_limit _) i.symm)
(λ s, F.preimage _) (λ s, F.image_preimage _) })
/--
When `F` is fully faithful, and `has_limit (K ⋙ F)`, to show that `F` creates the limit for `K`
it suffices to show that the chosen limit point is in the essential image of `F`.
-/
-- Notice however that even if the isomorphism is `iso.refl _`,
-- this construction will insert additional identity morphisms in the cone maps,
-- so the constructed limits may not be ideal, definitionally.
def creates_limit_of_fully_faithful_of_iso {K : J ⥤ C} {F : C ⥤ D}
[full F] [faithful F] [has_limit (K ⋙ F)]
(X : C) (i : F.obj X ≅ limit (K ⋙ F)) : creates_limit K F :=
creates_limit_of_fully_faithful_of_lift
({ X := X,
π :=
{ app := λ j, F.preimage (i.hom ≫ limit.π (K ⋙ F) j),
naturality' := λ Y Z f, F.map_injective (by { dsimp, simp, erw limit.w (K ⋙ F), }) }} : cone K)
(by { fapply cones.ext, exact i, tidy, })
/-- `F` preserves the limit of `K` if it creates the limit and `K ⋙ F` has the limit. -/
@[priority 100] -- see Note [lower instance priority]
instance preserves_limit_of_creates_limit_and_has_limit (K : J ⥤ C) (F : C ⥤ D)
[creates_limit K F] [has_limit (K ⋙ F)] :
preserves_limit K F :=
{ preserves := λ c t, is_limit.of_iso_limit (limit.is_limit _)
((lifted_limit_maps_to_original (limit.is_limit _)).symm ≪≫
((cones.functoriality K F).map_iso ((lifted_limit_is_limit (limit.is_limit _)).unique_up_to_iso t))) }
/-- `F` preserves the limit of shape `J` if it creates these limits and `D` has them. -/
@[priority 100] -- see Note [lower instance priority]
instance preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape (F : C ⥤ D)
[creates_limits_of_shape J F] [has_limits_of_shape J D] :
preserves_limits_of_shape J F :=
{ preserves_limit := λ K, category_theory.preserves_limit_of_creates_limit_and_has_limit K F }
/-- `F` preserves limits if it creates limits and `D` has limits. -/
@[priority 100] -- see Note [lower instance priority]
instance preserves_limits_of_creates_limits_and_has_limits (F : C ⥤ D) [creates_limits F] [has_limits D] :
preserves_limits F :=
{ preserves_limits_of_shape := λ J 𝒥,
by exactI category_theory.preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape F }
/--
If `F` reflects isomorphisms and we can lift any limit cocone to a limit cocone,
then `F` creates colimits.
In particular here we don't need to assume that F reflects colimits.
-/
def creates_colimit_of_reflects_iso {K : J ⥤ C} {F : C ⥤ D} [reflects_isomorphisms F]
(h : Π c t, lifts_to_colimit K F c t) :
creates_colimit K F :=
{ lifts := λ c t, (h c t).to_liftable_cocone,
to_reflects_colimit :=
{ reflects := λ (d : cocone K) (hd : is_colimit (F.map_cocone d)),
begin
let d' : cocone K := (h (F.map_cocone d) hd).to_liftable_cocone.lifted_cocone,
let i : F.map_cocone d' ≅ F.map_cocone d := (h (F.map_cocone d) hd).to_liftable_cocone.valid_lift,
let hd' : is_colimit d' := (h (F.map_cocone d) hd).makes_colimit,
let f : d' ⟶ d := hd'.desc_cocone_morphism d,
have : (cocones.functoriality K F).map f = i.hom := (hd.of_iso_colimit i.symm).uniq_cocone_morphism,
haveI : is_iso ((cocones.functoriality K F).map f) := (by { rw this, apply_instance }),
haveI := is_iso_of_reflects_iso f (cocones.functoriality K F),
exact is_colimit.of_iso_colimit hd' (as_iso f),
end } }
/-- `F` preserves the colimit of `K` if it creates the colimit and `K ⋙ F` has the colimit. -/
@[priority 100] -- see Note [lower instance priority]
instance preserves_colimit_of_creates_colimit_and_has_colimit (K : J ⥤ C) (F : C ⥤ D)
[creates_colimit K F] [has_colimit (K ⋙ F)] :
preserves_colimit K F :=
{ preserves := λ c t, is_colimit.of_iso_colimit (colimit.is_colimit _)
((lifted_colimit_maps_to_original (colimit.is_colimit _)).symm ≪≫
((cocones.functoriality K F).map_iso ((lifted_colimit_is_colimit (colimit.is_colimit _)).unique_up_to_iso t))) }
/-- `F` preserves the colimit of shape `J` if it creates these colimits and `D` has them. -/
@[priority 100] -- see Note [lower instance priority]
instance preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape (F : C ⥤ D)
[creates_colimits_of_shape J F] [has_colimits_of_shape J D] :
preserves_colimits_of_shape J F :=
{ preserves_colimit := λ K, category_theory.preserves_colimit_of_creates_colimit_and_has_colimit K F }
/-- `F` preserves limits if it creates limits and `D` has limits. -/
@[priority 100] -- see Note [lower instance priority]
instance preserves_colimits_of_creates_colimits_and_has_colimits (F : C ⥤ D) [creates_colimits F] [has_colimits D] :
preserves_colimits F :=
{ preserves_colimits_of_shape := λ J 𝒥,
by exactI category_theory.preserves_colimit_of_shape_of_creates_colimits_of_shape_and_has_colimits_of_shape F }
-- For the inhabited linter later.
/-- If F creates the limit of K, any cone lifts to a limit. -/
def lifts_to_limit_of_creates (K : J ⥤ C) (F : C ⥤ D)
[creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) :
lifts_to_limit K F c t :=
{ lifted_cone := lift_limit t,
valid_lift := lifted_limit_maps_to_original t,
makes_limit := lifted_limit_is_limit t }
-- For the inhabited linter later.
/-- If F creates the colimit of K, any cocone lifts to a colimit. -/
def lifts_to_colimit_of_creates (K : J ⥤ C) (F : C ⥤ D)
[creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) :
lifts_to_colimit K F c t :=
{ lifted_cocone := lift_colimit t,
valid_lift := lifted_colimit_maps_to_original t,
makes_colimit := lifted_colimit_is_colimit t }
/-- Any cone lifts through the identity functor. -/
def id_lifts_cone (c : cone (K ⋙ 𝟭 C)) : liftable_cone K (𝟭 C) c :=
{ lifted_cone :=
{ X := c.X,
π := c.π ≫ K.right_unitor.hom },
valid_lift := cones.ext (iso.refl _) (by tidy) }
/-- The identity functor creates all limits. -/
instance id_creates_limits : creates_limits (𝟭 C) :=
{ creates_limits_of_shape := λ J 𝒥, by exactI
{ creates_limit := λ F, { lifts := λ c t, id_lifts_cone c } } }
/-- Any cocone lifts through the identity functor. -/
def id_lifts_cocone (c : cocone (K ⋙ 𝟭 C)) : liftable_cocone K (𝟭 C) c :=
{ lifted_cocone :=
{ X := c.X,
ι := K.right_unitor.inv ≫ c.ι },
valid_lift := cocones.ext (iso.refl _) (by tidy) }
/-- The identity functor creates all colimits. -/
instance id_creates_colimits : creates_colimits (𝟭 C) :=
{ creates_colimits_of_shape := λ J 𝒥, by exactI
{ creates_colimit := λ F, { lifts := λ c t, id_lifts_cocone c } } }
/-- Satisfy the inhabited linter -/
instance inhabited_liftable_cone (c : cone (K ⋙ 𝟭 C)) : inhabited (liftable_cone K (𝟭 C) c) :=
⟨id_lifts_cone c⟩
instance inhabited_liftable_cocone (c : cocone (K ⋙ 𝟭 C)) : inhabited (liftable_cocone K (𝟭 C) c) :=
⟨id_lifts_cocone c⟩
/-- Satisfy the inhabited linter -/
instance inhabited_lifts_to_limit (K : J ⥤ C) (F : C ⥤ D)
[creates_limit K F] (c : cone (K ⋙ F)) (t : is_limit c) :
inhabited (lifts_to_limit _ _ _ t) :=
⟨lifts_to_limit_of_creates K F c t⟩
instance inhabited_lifts_to_colimit (K : J ⥤ C) (F : C ⥤ D)
[creates_colimit K F] (c : cocone (K ⋙ F)) (t : is_colimit c) :
inhabited (lifts_to_colimit _ _ _ t) :=
⟨lifts_to_colimit_of_creates K F c t⟩
section comp
variables {E : Type u₃} [ℰ : category.{v} E]
variables (F : C ⥤ D) (G : D ⥤ E)
instance comp_creates_limit [i₁ : creates_limit K F] [i₂ : creates_limit (K ⋙ F) G] :
creates_limit K (F ⋙ G) :=
{ lifts := λ c t,
{ lifted_cone := lift_limit (lifted_limit_is_limit t),
valid_lift := (cones.functoriality (K ⋙ F) G).map_iso
(lifted_limit_maps_to_original (lifted_limit_is_limit t)) ≪≫
(lifted_limit_maps_to_original t),
} }
end comp
end creates
end category_theory
|
0440326f567fff12659ef49c089ac7849a0770f5 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /category/traversable/basic.lean | 78ec9386f26ba13b6451372347baf8445c75665a | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 3,791 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
Type classes for traversing collections. The concepts and laws are taken from
http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html
-/
import tactic.cache
import category.applicative
open function (hiding comp)
universes u v w
section applicative_transformation
variables (f : Type u → Type v) [applicative f] [is_lawful_applicative f]
variables (g : Type u → Type w) [applicative g] [is_lawful_applicative g]
structure applicative_transformation : Type (max (u+1) v w) :=
(F : ∀ {α : Type u}, f α → g α)
(preserves_pure' : ∀ {α : Type u} (x : α), F (pure x) = pure x)
(preserves_seq' : ∀ {α β : Type u} (x : f (α → β)) (y : f α), F (x <*> y) = F x <*> F y)
end applicative_transformation
namespace applicative_transformation
variables (f : Type u → Type v) [applicative f] [is_lawful_applicative f]
variables (g : Type u → Type w) [applicative g] [is_lawful_applicative g]
instance : has_coe_to_fun (applicative_transformation f g) :=
{ F := λ _, ∀ {α}, f α → g α,
coe := λ m, m.F }
variables {f g}
variables (η : applicative_transformation f g)
@[functor_norm]
lemma preserves_pure :
∀ {α : Type u} (x : α), η (pure x) = pure x :=
by apply applicative_transformation.preserves_pure'
@[functor_norm]
lemma preserves_seq :
∀ {α β : Type u} (x : f (α → β)) (y : f α), η (x <*> y) = η x <*> η y :=
by apply applicative_transformation.preserves_seq'
@[functor_norm]
lemma preserves_map {α β : Type u} (x : α → β) (y : f α) :
η (x <$> y) = x <$> η y :=
by rw [← pure_seq_eq_map,η.preserves_seq]; simp with functor_norm
end applicative_transformation
open applicative_transformation
class traversable (t : Type u → Type u) extends functor t :=
(traverse : Π {m : Type u → Type u} [applicative m]
{α β : Type u},
(α → m β) → t α → m (t β))
open functor
export traversable (traverse)
section functions
variables {t : Type u → Type u}
variables {m : Type u → Type v} [applicative m]
variables {α β : Type u}
variables {f : Type u → Type u} [applicative f]
def sequence [traversable t] :
t (f α) → f (t α) :=
traverse id
end functions
class is_lawful_traversable (t : Type u → Type u) [traversable t]
extends is_lawful_functor t :
Type (u+1) :=
(id_traverse : ∀ {α : Type u} (x : t α), traverse id.mk x = x )
(comp_traverse : ∀ {G H : Type u → Type u}
[applicative G] [applicative H]
[is_lawful_applicative G] [is_lawful_applicative H]
{α β γ : Type u}
(g : α → G β) (h : β → H γ) (x : t α),
traverse (comp.mk ∘ map h ∘ g) x =
comp.mk (map (traverse h) (traverse g x)))
(map_traverse : ∀ {G : Type u → Type u}
[applicative G] [is_lawful_applicative G]
{α β γ : Type u}
(g : α → G β) (h : β → γ)
(x : t α),
map (map h) (traverse g x) =
traverse (map h ∘ g) x)
(traverse_map : ∀ {G : Type u → Type u}
[applicative G] [is_lawful_applicative G]
{α β γ : Type u}
(g : α → β) (h : β → G γ)
(x : t α),
traverse h (map g x) =
traverse (h ∘ g) x)
(naturality : ∀ {G H : Type u → Type u}
[applicative G] [applicative H]
[is_lawful_applicative G] [is_lawful_applicative H]
(η : applicative_transformation G H),
∀ {α β : Type u} (f : α → G β) (x : t α),
η (traverse f x) = traverse (@η _ ∘ f) x)
|
369c52d2b2e14d29fcd338d964c2f6c4e0837e75 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/analysis/normed_space/finite_dimension.lean | eafa77d5cda3bd89b37069c0dab98d1d9fffe33c | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 23,814 | 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 analysis.normed_space.add_torsor
import analysis.normed_space.operator_norm
import linear_algebra.finite_dimensional
/-!
# Finite dimensional normed spaces over complete fields
Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps
are continuous. Moreover, a finite-dimensional subspace is always complete and closed.
## Main results:
* `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a
complete field is continuous.
* `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This
is not registered as an instance, as the field would be an unknown metavariable in typeclass
resolution.
* `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is
closed
* `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This
is not registered as an instance, as the field would be an unknown metavariable in typeclass
resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness
implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or
`ℂ`.
## Implementation notes
The fact that all norms are equivalent is not written explicitly, as it would mean having two norms
on a single space, which is not the way type classes work. However, if one has a
finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm,
then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to
`linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence.
-/
universes u v w x
open set finite_dimensional topological_space filter
open_locale classical big_operators filter topological_space
noncomputable theory
/-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/
lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜]
{E : Type v} [add_comm_group E] [module 𝕜 E] [topological_space E]
[topological_add_group E] [has_continuous_smul 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f :=
begin
-- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous
-- function.
have : (f : (ι → 𝕜) → E) =
(λx, ∑ i : ι, x i • (f (λj, if i = j then 1 else 0))),
by { ext x, exact f.pi_apply_eq_sum_univ x },
rw this,
refine continuous_finset_sum _ (λi hi, _),
exact (continuous_apply i).smul continuous_const
end
section complete_field
variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜]
{E : Type v} [normed_group E] [normed_space 𝕜 E]
{F : Type w} [normed_group F] [normed_space 𝕜 F]
{F' : Type x} [add_comm_group F'] [module 𝕜 F'] [topological_space F']
[topological_add_group F'] [has_continuous_smul 𝕜 F']
[complete_space 𝕜]
/-- In finite dimension over a complete field, the canonical identification (in terms of a basis)
with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that
all norms are equivalent in finite dimension.
This statement is superceded by the fact that every linear map on a finite-dimensional space is
continuous, in `linear_map.continuous_of_finite_dimensional`. -/
lemma continuous_equiv_fun_basis {ι : Type v} [fintype ι] (ξ : basis ι 𝕜 E) :
continuous ξ.equiv_fun :=
begin
unfreezingI { induction hn : fintype.card ι with n IH generalizing ι E },
{ apply linear_map.continuous_of_bound _ 0 (λx, _),
have : ξ.equiv_fun x = 0,
by { ext i, exact (fintype.card_eq_zero_iff.1 hn).elim i },
change ∥ξ.equiv_fun x∥ ≤ 0 * ∥x∥,
rw this,
simp [norm_nonneg] },
{ haveI : finite_dimensional 𝕜 E := of_fintype_basis ξ,
-- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent
-- to a standard space of dimension n, hence it is complete and therefore closed.
have H₁ : ∀s : submodule 𝕜 E, finrank 𝕜 s = n → is_closed (s : set E),
{ assume s s_dim,
let b := basis.of_vector_space 𝕜 s,
have U : uniform_embedding b.equiv_fun.symm.to_equiv,
{ have : fintype.card (basis.of_vector_space_index 𝕜 s) = n,
by { rw ← s_dim, exact (finrank_eq_card_basis b).symm },
have : continuous b.equiv_fun := IH b this,
exact b.equiv_fun.symm.uniform_embedding (linear_map.continuous_on_pi _) this },
have : is_complete (s : set E),
from complete_space_coe_iff_is_complete.1 ((complete_space_congr U).1 (by apply_instance)),
exact this.is_closed },
-- second step: any linear form is continuous, as its kernel is closed by the first step
have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f,
{ assume f,
have : finrank 𝕜 f.ker = n ∨ finrank 𝕜 f.ker = n.succ,
{ have Z := f.finrank_range_add_finrank_ker,
rw [finrank_eq_card_basis ξ, hn] at Z,
by_cases H : finrank 𝕜 f.range = 0,
{ right,
rw H at Z,
simpa using Z },
{ left,
have : finrank 𝕜 f.range = 1,
{ refine le_antisymm _ (zero_lt_iff.mpr H),
simpa [finrank_of_field] using f.range.finrank_le },
rw [this, add_comm, nat.add_one] at Z,
exact nat.succ.inj Z } },
have : is_closed (f.ker : set E),
{ cases this,
{ exact H₁ _ this },
{ have : f.ker = ⊤,
by { apply eq_top_of_finrank_eq, rw [finrank_eq_card_basis ξ, hn, this] },
simp [this] } },
exact linear_map.continuous_iff_is_closed_ker.2 this },
-- third step: applying the continuity to the linear form corresponding to a coefficient in the
-- basis decomposition, deduce that all such coefficients are controlled in terms of the norm
have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥ξ.equiv_fun x i∥ ≤ C * ∥x∥,
{ assume i,
let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i).comp ξ.equiv_fun,
let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f },
exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ },
-- fourth step: combine the bound on each coefficient to get a global bound and the continuity
choose C0 hC0 using this,
let C := ∑ i, C0 i,
have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1),
have C0_le : ∀i, C0 i ≤ C :=
λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _),
apply linear_map.continuous_of_bound _ C (λx, _),
rw pi_semi_norm_le_iff,
{ exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) },
{ exact mul_nonneg C_nonneg (norm_nonneg _) } }
end
/-- Any linear map on a finite dimensional space over a complete field is continuous. -/
theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') :
continuous f :=
begin
-- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and
-- argue that all linear maps there are continuous.
let b := basis.of_vector_space 𝕜 E,
have A : continuous b.equiv_fun :=
continuous_equiv_fun_basis b,
have B : continuous (f.comp (b.equiv_fun.symm : (basis.of_vector_space_index 𝕜 E → 𝕜) →ₗ[𝕜] E)) :=
linear_map.continuous_on_pi _,
have : continuous ((f.comp (b.equiv_fun.symm : (basis.of_vector_space_index 𝕜 E → 𝕜) →ₗ[𝕜] E))
∘ b.equiv_fun) := B.comp A,
convert this,
ext x,
dsimp,
rw [basis.equiv_fun_symm_apply, basis.sum_repr]
end
theorem affine_map.continuous_of_finite_dimensional {PE PF : Type*}
[metric_space PE] [normed_add_torsor E PE] [metric_space PF] [normed_add_torsor F PF]
[finite_dimensional 𝕜 E] (f : PE →ᵃ[𝕜] PF) : continuous f :=
affine_map.continuous_linear_iff.1 f.linear.continuous_of_finite_dimensional
namespace linear_map
variables [finite_dimensional 𝕜 E]
/-- The continuous linear map induced by a linear map on a finite dimensional space -/
def to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F' :=
{ to_fun := λ f, ⟨f, f.continuous_of_finite_dimensional⟩,
inv_fun := coe,
map_add' := λ f g, rfl,
map_smul' := λ c f, rfl,
left_inv := λ f, rfl,
right_inv := λ f, continuous_linear_map.coe_injective rfl }
@[simp] lemma coe_to_continuous_linear_map' (f : E →ₗ[𝕜] F') :
⇑f.to_continuous_linear_map = f := rfl
@[simp] lemma coe_to_continuous_linear_map (f : E →ₗ[𝕜] F') :
(f.to_continuous_linear_map : E →ₗ[𝕜] F') = f := rfl
@[simp] lemma coe_to_continuous_linear_map_symm :
⇑(to_continuous_linear_map : (E →ₗ[𝕜] F') ≃ₗ[𝕜] E →L[𝕜] F').symm = coe := rfl
end linear_map
/-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional
space. -/
def linear_equiv.to_continuous_linear_equiv [finite_dimensional 𝕜 E] (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F :=
{ continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional,
continuous_inv_fun := begin
haveI : finite_dimensional 𝕜 F := e.finite_dimensional,
exact e.symm.to_linear_map.continuous_of_finite_dimensional
end,
..e }
lemma linear_map.exists_antilipschitz_with [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F)
(hf : f.ker = ⊥) : ∃ K > 0, antilipschitz_with K f :=
begin
cases subsingleton_or_nontrivial E; resetI,
{ exact ⟨1, zero_lt_one, antilipschitz_with.of_subsingleton⟩ },
{ let e : E ≃L[𝕜] f.range := (linear_equiv.of_injective f hf).to_continuous_linear_equiv,
exact ⟨_, e.nnnorm_symm_pos, e.antilipschitz⟩ }
end
protected lemma linear_independent.eventually {ι} [fintype ι] {f : ι → E}
(hf : linear_independent 𝕜 f) : ∀ᶠ g in 𝓝 f, linear_independent 𝕜 g :=
begin
simp only [fintype.linear_independent_iff'] at hf ⊢,
rcases linear_map.exists_antilipschitz_with _ hf with ⟨K, K0, hK⟩,
have : tendsto (λ g : ι → E, ∑ i, ∥g i - f i∥) (𝓝 f) (𝓝 $ ∑ i, ∥f i - f i∥),
from tendsto_finset_sum _ (λ i hi, tendsto.norm $
((continuous_apply i).tendsto _).sub tendsto_const_nhds),
simp only [sub_self, norm_zero, finset.sum_const_zero] at this,
refine (this.eventually (gt_mem_nhds $ inv_pos.2 K0)).mono (λ g hg, _),
replace hg : ∑ i, nnnorm (g i - f i) < K⁻¹, by { rw ← nnreal.coe_lt_coe, push_cast, exact hg },
rw linear_map.ker_eq_bot,
refine (hK.add_sub_lipschitz_with (lipschitz_with.of_dist_le_mul $ λ v u, _) hg).injective,
simp only [dist_eq_norm, linear_map.lsum_apply, pi.sub_apply, linear_map.sum_apply,
linear_map.comp_apply, linear_map.proj_apply, linear_map.smul_right_apply, linear_map.id_apply,
← finset.sum_sub_distrib, ← smul_sub, ← sub_smul, nnreal.coe_sum, coe_nnnorm, finset.sum_mul],
refine norm_sum_le_of_le _ (λ i _, _),
rw [norm_smul, mul_comm],
exact mul_le_mul_of_nonneg_left (norm_le_pi_norm (v - u) i) (norm_nonneg _)
end
lemma is_open_set_of_linear_independent {ι : Type*} [fintype ι] :
is_open {f : ι → E | linear_independent 𝕜 f} :=
is_open_iff_mem_nhds.2 $ λ f, linear_independent.eventually
lemma is_open_set_of_nat_le_rank (n : ℕ) : is_open {f : E →L[𝕜] F | ↑n ≤ rank (f : E →ₗ[𝕜] F)} :=
begin
simp only [le_rank_iff_exists_linear_independent_finset, set_of_exists, ← exists_prop],
refine is_open_bUnion (λ t ht, _),
have : continuous (λ f : E →L[𝕜] F, (λ x : (t : set E), f x)),
from continuous_pi (λ x, (continuous_linear_map.apply 𝕜 F (x : E)).continuous),
exact is_open_set_of_linear_independent.preimage this
end
/-- Two finite-dimensional normed spaces are continuously linearly equivalent if they have the same
(finite) dimension. -/
theorem finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq
[finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] (cond : finrank 𝕜 E = finrank 𝕜 F) :
nonempty (E ≃L[𝕜] F) :=
(nonempty_linear_equiv_of_finrank_eq cond).map linear_equiv.to_continuous_linear_equiv
/-- Two finite-dimensional normed spaces are continuously linearly equivalent if and only if they
have the same (finite) dimension. -/
theorem finite_dimensional.nonempty_continuous_linear_equiv_iff_finrank_eq
[finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F] :
nonempty (E ≃L[𝕜] F) ↔ finrank 𝕜 E = finrank 𝕜 F :=
⟨ λ ⟨h⟩, h.to_linear_equiv.finrank_eq,
λ h, finite_dimensional.nonempty_continuous_linear_equiv_of_finrank_eq h ⟩
/-- A continuous linear equivalence between two finite-dimensional normed spaces of the same
(finite) dimension. -/
def continuous_linear_equiv.of_finrank_eq [finite_dimensional 𝕜 E] [finite_dimensional 𝕜 F]
(cond : finrank 𝕜 E = finrank 𝕜 F) :
E ≃L[𝕜] F :=
(linear_equiv.of_finrank_eq E F cond).to_continuous_linear_equiv
variables {ι : Type*} [fintype ι]
/-- Construct a continuous linear map given the value at a finite basis. -/
def basis.constrL (v : basis ι 𝕜 E) (f : ι → F) :
E →L[𝕜] F :=
by haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v;
exact (v.constr 𝕜 f).to_continuous_linear_map
@[simp, norm_cast] lemma basis.coe_constrL (v : basis ι 𝕜 E) (f : ι → F) :
(v.constrL f : E →ₗ[𝕜] F) = v.constr 𝕜 f := rfl
/-- The continuous linear equivalence between a vector space over `𝕜` with a finite basis and
functions from its basis indexing type to `𝕜`. -/
def basis.equiv_funL (v : basis ι 𝕜 E) : E ≃L[𝕜] (ι → 𝕜) :=
{ continuous_to_fun := begin
haveI : finite_dimensional 𝕜 E := finite_dimensional.of_fintype_basis v,
apply linear_map.continuous_of_finite_dimensional,
end,
continuous_inv_fun := begin
change continuous v.equiv_fun.symm.to_fun,
apply linear_map.continuous_of_finite_dimensional,
end,
..v.equiv_fun }
@[simp] lemma basis.constrL_apply (v : basis ι 𝕜 E) (f : ι → F) (e : E) :
(v.constrL f) e = ∑ i, (v.equiv_fun e i) • f i :=
v.constr_apply_fintype 𝕜 _ _
@[simp] lemma basis.constrL_basis (v : basis ι 𝕜 E) (f : ι → F) (i : ι) :
(v.constrL f) (v i) = f i :=
v.constr_basis 𝕜 _ _
lemma basis.sup_norm_le_norm (v : basis ι 𝕜 E) :
∃ C > (0 : ℝ), ∀ e : E, ∑ i, ∥v.equiv_fun e i∥ ≤ C * ∥e∥ :=
begin
set φ := v.equiv_funL.to_continuous_linear_map,
set C := ∥φ∥ * (fintype.card ι),
use [max C 1, lt_of_lt_of_le (zero_lt_one) (le_max_right C 1)],
intros e,
calc ∑ i, ∥φ e i∥ ≤ ∑ i : ι, ∥φ e∥ : by { apply finset.sum_le_sum,
exact λ i hi, norm_le_pi_norm (φ e) i }
... = ∥φ e∥*(fintype.card ι) : by simpa only [mul_comm, finset.sum_const, nsmul_eq_mul]
... ≤ ∥φ∥ * ∥e∥ * (fintype.card ι) : mul_le_mul_of_nonneg_right (φ.le_op_norm e)
(fintype.card ι).cast_nonneg
... = ∥φ∥ * (fintype.card ι) * ∥e∥ : by ring
... ≤ max C 1 * ∥e∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _)
end
lemma basis.op_norm_le {ι : Type*} [fintype ι] (v : basis ι 𝕜 E) :
∃ C > (0 : ℝ), ∀ {u : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥u (v i)∥ ≤ M) → ∥u∥ ≤ C*M :=
begin
obtain ⟨C, C_pos, hC⟩ : ∃ C > (0 : ℝ), ∀ (e : E), ∑ i, ∥v.equiv_fun e i∥ ≤ C * ∥e∥,
from v.sup_norm_le_norm,
use [C, C_pos],
intros u M hM hu,
apply u.op_norm_le_bound (mul_nonneg (le_of_lt C_pos) hM),
intros e,
calc
∥u e∥ = ∥u (∑ i, v.equiv_fun e i • v i)∥ : by rw [v.sum_equiv_fun]
... = ∥∑ i, (v.equiv_fun e i) • (u $ v i)∥ : by simp [u.map_sum, linear_map.map_smul]
... ≤ ∑ i, ∥(v.equiv_fun e i) • (u $ v i)∥ : norm_sum_le _ _
... = ∑ i, ∥v.equiv_fun e i∥ * ∥u (v i)∥ : by simp only [norm_smul]
... ≤ ∑ i, ∥v.equiv_fun e i∥ * M : finset.sum_le_sum (λ i hi,
mul_le_mul_of_nonneg_left (hu i) (norm_nonneg _))
... = (∑ i, ∥v.equiv_fun e i∥) * M : finset.sum_mul.symm
... ≤ C * ∥e∥ * M : mul_le_mul_of_nonneg_right (hC e) hM
... = C * M * ∥e∥ : by ring
end
instance [finite_dimensional 𝕜 E] [second_countable_topology F] :
second_countable_topology (E →L[𝕜] F) :=
begin
set d := finite_dimensional.finrank 𝕜 E,
suffices :
∀ ε > (0 : ℝ), ∃ n : (E →L[𝕜] F) → fin d → ℕ, ∀ (f g : E →L[𝕜] F), n f = n g → dist f g ≤ ε,
from metric.second_countable_of_countable_discretization
(λ ε ε_pos, ⟨fin d → ℕ, by apply_instance, this ε ε_pos⟩),
intros ε ε_pos,
obtain ⟨u : ℕ → F, hu : dense_range u⟩ := exists_dense_seq F,
let v := finite_dimensional.fin_basis 𝕜 E,
obtain ⟨C : ℝ, C_pos : 0 < C,
hC : ∀ {φ : E →L[𝕜] F} {M : ℝ}, 0 ≤ M → (∀ i, ∥φ (v i)∥ ≤ M) → ∥φ∥ ≤ C * M⟩ :=
v.op_norm_le,
have h_2C : 0 < 2*C := mul_pos zero_lt_two C_pos,
have hε2C : 0 < ε/(2*C) := div_pos ε_pos h_2C,
have : ∀ φ : E →L[𝕜] F, ∃ n : fin d → ℕ, ∥φ - (v.constrL $ u ∘ n)∥ ≤ ε/2,
{ intros φ,
have : ∀ i, ∃ n, ∥φ (v i) - u n∥ ≤ ε/(2*C),
{ simp only [norm_sub_rev],
intro i,
have : φ (v i) ∈ closure (range u) := hu _,
obtain ⟨n, hn⟩ : ∃ n, ∥u n - φ (v i)∥ < ε / (2 * C),
{ rw mem_closure_iff_nhds_basis metric.nhds_basis_ball at this,
specialize this (ε/(2*C)) hε2C,
simpa [dist_eq_norm] },
exact ⟨n, le_of_lt hn⟩ },
choose n hn using this,
use n,
replace hn : ∀ i : fin d, ∥(φ - (v.constrL $ u ∘ n)) (v i)∥ ≤ ε / (2 * C), by simp [hn],
have : C * (ε / (2 * C)) = ε/2,
{ rw [eq_div_iff (two_ne_zero : (2 : ℝ) ≠ 0), mul_comm, ← mul_assoc,
mul_div_cancel' _ (ne_of_gt h_2C)] },
specialize hC (le_of_lt hε2C) hn,
rwa this at hC },
choose n hn using this,
set Φ := λ φ : E →L[𝕜] F, (v.constrL $ u ∘ (n φ)),
change ∀ z, dist z (Φ z) ≤ ε/2 at hn,
use n,
intros x y hxy,
calc dist x y ≤ dist x (Φ x) + dist (Φ x) y : dist_triangle _ _ _
... = dist x (Φ x) + dist y (Φ y) : by simp [Φ, hxy, dist_comm]
... ≤ ε : by linarith [hn x, hn y]
end
/-- Any finite-dimensional vector space over a complete field is complete.
We do not register this as an instance to avoid an instance loop when trying to prove the
completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance
explicitly when needed. -/
variables (𝕜 E)
lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E :=
begin
set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm,
have : uniform_embedding e.to_linear_equiv.to_equiv.symm := e.symm.uniform_embedding,
exact (complete_space_congr this).1 (by apply_instance)
end
variables {𝕜 E}
/-- A finite-dimensional subspace is complete. -/
lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] :
is_complete (s : set E) :=
complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s)
/-- A finite-dimensional subspace is closed. -/
lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] :
is_closed (s : set E) :=
s.complete_of_finite_dimensional.is_closed
lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F]
(f : E →L[𝕜] F) (hf : f.range = ⊤) :
∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F :=
let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in
⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩
lemma closed_embedding_smul_left {c : E} (hc : c ≠ 0) : closed_embedding (λ x : 𝕜, x • c) :=
begin
haveI : finite_dimensional 𝕜 (submodule.span 𝕜 {c}) :=
finite_dimensional.span_of_finite 𝕜 (finite_singleton c),
have m1 : closed_embedding (coe : submodule.span 𝕜 {c} → E) :=
(submodule.span 𝕜 {c}).closed_of_finite_dimensional.closed_embedding_subtype_coe,
have m2 : closed_embedding
(linear_equiv.to_span_nonzero_singleton 𝕜 E c hc : 𝕜 → submodule.span 𝕜 {c}) :=
(continuous_linear_equiv.to_span_nonzero_singleton 𝕜 c hc).to_homeomorph.closed_embedding,
exact m1.comp m2
end
/- `smul` is a closed map in the first argument. -/
lemma is_closed_map_smul_left (c : E) : is_closed_map (λ x : 𝕜, x • c) :=
begin
by_cases hc : c = 0,
{ simp_rw [hc, smul_zero], exact is_closed_map_const },
{ exact (closed_embedding_smul_left hc).is_closed_map }
end
end complete_field
section proper_field
variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜]
(E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜]
/-- Any finite-dimensional vector space over a proper field is proper.
We do not register this as an instance to avoid an instance loop when trying to prove the
properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance
explicitly when needed. -/
lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E :=
begin
set e := continuous_linear_equiv.of_finrank_eq (@finrank_fin_fun 𝕜 _ (finrank 𝕜 E)).symm,
exact e.symm.antilipschitz.proper_space e.symm.continuous e.symm.surjective
end
end proper_field
/- Over the real numbers, we can register the previous statement as an instance as it will not
cause problems in instance resolution since the properness of `ℝ` is already known. -/
instance finite_dimensional.proper_real
(E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E :=
finite_dimensional.proper ℝ E
attribute [instance, priority 900] finite_dimensional.proper_real
/-- In a finite dimensional vector space over `ℝ`, the series `∑ x, ∥f x∥` is unconditionally
summable if and only if the series `∑ x, f x` is unconditionally summable. One implication holds in
any complete normed space, while the other holds only in finite dimensional spaces. -/
lemma summable_norm_iff {α E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
{f : α → E} : summable (λ x, ∥f x∥) ↔ summable f :=
begin
refine ⟨summable_of_summable_norm, λ hf, _⟩,
-- First we use a finite basis to reduce the problem to the case `E = fin N → ℝ`
suffices : ∀ {N : ℕ} {g : α → fin N → ℝ}, summable g → summable (λ x, ∥g x∥),
{ obtain v := fin_basis ℝ E,
set e := v.equiv_funL,
have : summable (λ x, ∥e (f x)∥) := this (e.summable.2 hf),
refine summable_of_norm_bounded _ (this.mul_left
↑(nnnorm (e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E))) (λ i, _),
simpa using (e.symm : (fin (finrank ℝ E) → ℝ) →L[ℝ] E).le_op_norm (e $ f i) },
unfreezingI { clear_dependent E },
-- Now we deal with `g : α → fin N → ℝ`
intros N g hg,
have : ∀ i, summable (λ x, ∥g x i∥) := λ i, (pi.summable.1 hg i).abs,
refine summable_of_norm_bounded _ (summable_sum (λ i (hi : i ∈ finset.univ), this i)) (λ x, _),
rw [norm_norm, pi_norm_le_iff],
{ refine λ i, finset.single_le_sum (λ i hi, _) (finset.mem_univ i),
exact norm_nonneg (g x i) },
{ exact finset.sum_nonneg (λ _ _, norm_nonneg _) }
end
|
17977c07dd934cb459b22f4c81527c4ce2cf23fe | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/lie/basic.lean | e4da1a0f872de87f5a3695b5e88a81d678a69982 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,949 | lean | /-
Copyright (c) 2019 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import data.bracket
import algebra.algebra.basic
import tactic.noncomm_ring
/-!
# Lie algebras
This file defines Lie rings and Lie algebras over a commutative ring together with their
modules, morphisms and equivalences, as well as various lemmas to make these definitions usable.
## Main definitions
* `lie_ring`
* `lie_algebra`
* `lie_ring_module`
* `lie_module`
* `lie_hom`
* `lie_equiv`
* `lie_module_hom`
* `lie_module_equiv`
## Notation
Working over a fixed commutative ring `R`, we introduce the notations:
* `L →ₗ⁅R⁆ L'` for a morphism of Lie algebras,
* `L ≃ₗ⁅R⁆ L'` for an equivalence of Lie algebras,
* `M →ₗ⁅R,L⁆ N` for a morphism of Lie algebra modules `M`, `N` over a Lie algebra `L`,
* `M ≃ₗ⁅R,L⁆ N` for an equivalence of Lie algebra modules `M`, `N` over a Lie algebra `L`.
## Implementation notes
Lie algebras are defined as modules with a compatible Lie ring structure and thus, like modules,
are partially unbundled.
## References
* [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 1--3*](bourbaki1975)
## Tags
lie bracket, jacobi identity, lie ring, lie algebra, lie module
-/
universes u v w w₁ w₂
/-- A Lie ring is an additive group with compatible product, known as the bracket, satisfying the
Jacobi identity. -/
@[protect_proj] class lie_ring (L : Type v) extends add_comm_group L, has_bracket L L :=
(add_lie : ∀ (x y z : L), ⁅x + y, z⁆ = ⁅x, z⁆ + ⁅y, z⁆)
(lie_add : ∀ (x y z : L), ⁅x, y + z⁆ = ⁅x, y⁆ + ⁅x, z⁆)
(lie_self : ∀ (x : L), ⁅x, x⁆ = 0)
(leibniz_lie : ∀ (x y z : L), ⁅x, ⁅y, z⁆⁆ = ⁅⁅x, y⁆, z⁆ + ⁅y, ⁅x, z⁆⁆)
/-- A Lie algebra is a module with compatible product, known as the bracket, satisfying the Jacobi
identity. Forgetting the scalar multiplication, every Lie algebra is a Lie ring. -/
@[protect_proj] class lie_algebra (R : Type u) (L : Type v) [comm_ring R] [lie_ring L]
extends semimodule R L :=
(lie_smul : ∀ (t : R) (x y : L), ⁅x, t • y⁆ = t • ⁅x, y⁆)
/-- A Lie ring module is an additive group, together with an additive action of a
Lie ring on this group, such that the Lie bracket acts as the commutator of endomorphisms.
(For representations of Lie *algebras* see `lie_module`.) -/
@[protect_proj] class lie_ring_module (L : Type v) (M : Type w)
[lie_ring L] [add_comm_group M] extends has_bracket L M :=
(add_lie : ∀ (x y : L) (m : M), ⁅x + y, m⁆ = ⁅x, m⁆ + ⁅y, m⁆)
(lie_add : ∀ (x : L) (m n : M), ⁅x, m + n⁆ = ⁅x, m⁆ + ⁅x, n⁆)
(leibniz_lie : ∀ (x y : L) (m : M), ⁅x, ⁅y, m⁆⁆ = ⁅⁅x, y⁆, m⁆ + ⁅y, ⁅x, m⁆⁆)
/-- A Lie module is a module over a commutative ring, together with a linear action of a Lie
algebra on this module, such that the Lie bracket acts as the commutator of endomorphisms. -/
@[protect_proj] class lie_module (R : Type u) (L : Type v) (M : Type w)
[comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
[lie_ring_module L M] :=
(smul_lie : ∀ (t : R) (x : L) (m : M), ⁅t • x, m⁆ = t • ⁅x, m⁆)
(lie_smul : ∀ (t : R) (x : L) (m : M), ⁅x, t • m⁆ = t • ⁅x, m⁆)
section basic_properties
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (t : R) (x y z : L) (m n : M)
@[simp] lemma add_lie : ⁅x + y, m⁆ = ⁅x, m⁆ + ⁅y, m⁆ := lie_ring_module.add_lie x y m
@[simp] lemma lie_add : ⁅x, m + n⁆ = ⁅x, m⁆ + ⁅x, n⁆ := lie_ring_module.lie_add x m n
@[simp] lemma smul_lie : ⁅t • x, m⁆ = t • ⁅x, m⁆ := lie_module.smul_lie t x m
@[simp] lemma lie_smul : ⁅x, t • m⁆ = t • ⁅x, m⁆ := lie_module.lie_smul t x m
lemma leibniz_lie : ⁅x, ⁅y, m⁆⁆ = ⁅⁅x, y⁆, m⁆ + ⁅y, ⁅x, m⁆⁆ := lie_ring_module.leibniz_lie x y m
@[simp] lemma lie_zero : ⁅x, 0⁆ = (0 : M) := (add_monoid_hom.mk' _ (lie_add x)).map_zero
@[simp] lemma zero_lie : ⁅(0 : L), m⁆ = 0 :=
(add_monoid_hom.mk' (λ (x : L), ⁅x, m⁆) (λ x y, add_lie x y m)).map_zero
@[simp] lemma lie_self : ⁅x, x⁆ = 0 := lie_ring.lie_self x
instance lie_ring_self_module : lie_ring_module L L := { ..(infer_instance : lie_ring L) }
@[simp] lemma lie_skew : -⁅y, x⁆ = ⁅x, y⁆ :=
have h : ⁅x + y, x⁆ + ⁅x + y, y⁆ = 0, { rw ← lie_add, apply lie_self, },
by simpa [neg_eq_iff_add_eq_zero] using h
/-- Every Lie algebra is a module over itself. -/
instance lie_algebra_self_module : lie_module R L L :=
{ smul_lie := λ t x m, by rw [←lie_skew, ←lie_skew x m, lie_algebra.lie_smul, smul_neg],
lie_smul := by apply lie_algebra.lie_smul, }
@[simp] lemma neg_lie : ⁅-x, m⁆ = -⁅x, m⁆ :=
by { rw [←sub_eq_zero, sub_neg_eq_add, ←add_lie], simp, }
@[simp] lemma lie_neg : ⁅x, -m⁆ = -⁅x, m⁆ :=
by { rw [←sub_eq_zero, sub_neg_eq_add, ←lie_add], simp, }
@[simp] lemma gsmul_lie (a : ℤ) : ⁅a • x, m⁆ = a • ⁅x, m⁆ :=
add_monoid_hom.map_gsmul ⟨λ (x : L), ⁅x, m⁆, zero_lie m, λ _ _, add_lie _ _ _⟩ _ _
@[simp] lemma lie_gsmul (a : ℤ) : ⁅x, a • m⁆ = a • ⁅x, m⁆ :=
add_monoid_hom.map_gsmul ⟨λ (m : M), ⁅x, m⁆, lie_zero x, λ _ _, lie_add _ _ _⟩ _ _
@[simp] lemma lie_lie : ⁅⁅x, y⁆, m⁆ = ⁅x, ⁅y, m⁆⁆ - ⁅y, ⁅x, m⁆⁆ :=
by rw [leibniz_lie, add_sub_cancel]
lemma lie_jacobi : ⁅x, ⁅y, z⁆⁆ + ⁅y, ⁅z, x⁆⁆ + ⁅z, ⁅x, y⁆⁆ = 0 :=
by { rw [← neg_neg ⁅x, y⁆, lie_neg z, lie_skew y x, ← lie_skew, lie_lie], abel, }
end basic_properties
set_option old_structure_cmd true
/-- A morphism of Lie algebras is a linear map respecting the bracket operations. -/
structure lie_hom (R : Type u) (L : Type v) (L' : Type w)
[comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
extends L →ₗ[R] L' :=
(map_lie' : ∀ {x y : L}, to_fun ⁅x, y⁆ = ⁅to_fun x, to_fun y⁆)
attribute [nolint doc_blame] lie_hom.to_linear_map
notation L ` →ₗ⁅`:25 R:25 `⁆ `:0 L':0 := lie_hom R L L'
namespace lie_hom
variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁}
variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃]
variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃]
instance : has_coe (L₁ →ₗ⁅R⁆ L₂) (L₁ →ₗ[R] L₂) := ⟨lie_hom.to_linear_map⟩
/-- see Note [function coercion] -/
instance : has_coe_to_fun (L₁ →ₗ⁅R⁆ L₂) := ⟨_, lie_hom.to_fun⟩
initialize_simps_projections lie_hom (to_fun → apply)
@[simp] lemma coe_mk (f : L₁ → L₂) (h₁ h₂ h₃) :
((⟨f, h₁, h₂, h₃⟩ : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = f := rfl
@[simp, norm_cast] lemma coe_to_linear_map (f : L₁ →ₗ⁅R⁆ L₂) : ((f : L₁ →ₗ[R] L₂) : L₁ → L₂) = f :=
rfl
@[simp] lemma map_smul (f : L₁ →ₗ⁅R⁆ L₂) (c : R) (x : L₁) : f (c • x) = c • f x :=
linear_map.map_smul (f : L₁ →ₗ[R] L₂) c x
@[simp] lemma map_add (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f (x + y) = (f x) + (f y) :=
linear_map.map_add (f : L₁ →ₗ[R] L₂) x y
@[simp] lemma map_lie (f : L₁ →ₗ⁅R⁆ L₂) (x y : L₁) : f ⁅x, y⁆ = ⁅f x, f y⁆ := lie_hom.map_lie' f
@[simp] lemma map_zero (f : L₁ →ₗ⁅R⁆ L₂) : f 0 = 0 := (f : L₁ →ₗ[R] L₂).map_zero
/-- The constant 0 map is a Lie algebra morphism. -/
instance : has_zero (L₁ →ₗ⁅R⁆ L₂) := ⟨{ map_lie' := by simp, ..(0 : L₁ →ₗ[R] L₂)}⟩
/-- The identity map is a Lie algebra morphism. -/
instance : has_one (L₁ →ₗ⁅R⁆ L₁) := ⟨{ map_lie' := by simp, ..(1 : L₁ →ₗ[R] L₁)}⟩
instance : inhabited (L₁ →ₗ⁅R⁆ L₂) := ⟨0⟩
lemma coe_injective : function.injective (λ f : L₁ →ₗ⁅R⁆ L₂, show L₁ → L₂, from f) :=
by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr
@[ext] lemma ext {f g : L₁ →ₗ⁅R⁆ L₂} (h : ∀ x, f x = g x) : f = g :=
coe_injective $ funext h
lemma ext_iff {f g : L₁ →ₗ⁅R⁆ L₂} : f = g ↔ ∀ x, f x = g x :=
⟨by { rintro rfl x, refl }, ext⟩
/-- The composition of morphisms is a morphism. -/
def comp (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) : L₁ →ₗ⁅R⁆ L₃ :=
{ map_lie' := λ x y, by { change f (g ⁅x, y⁆) = ⁅f (g x), f (g y)⁆, rw [map_lie, map_lie], },
..linear_map.comp f.to_linear_map g.to_linear_map }
@[simp] lemma comp_apply (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) (x : L₁) :
f.comp g x = f (g x) := rfl
@[norm_cast]
lemma comp_coe (f : L₂ →ₗ⁅R⁆ L₃) (g : L₁ →ₗ⁅R⁆ L₂) :
(f : L₂ → L₃) ∘ (g : L₁ → L₂) = f.comp g := rfl
/-- The inverse of a bijective morphism is a morphism. -/
def inverse (f : L₁ →ₗ⁅R⁆ L₂) (g : L₂ → L₁)
(h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : L₂ →ₗ⁅R⁆ L₁ :=
{ map_lie' := λ x y,
calc g ⁅x, y⁆ = g ⁅f (g x), f (g y)⁆ : by { conv_lhs { rw [←h₂ x, ←h₂ y], }, }
... = g (f ⁅g x, g y⁆) : by rw map_lie
... = ⁅g x, g y⁆ : (h₁ _),
..linear_map.inverse f.to_linear_map g h₁ h₂ }
end lie_hom
/-- An equivalence of Lie algebras is a morphism which is also a linear equivalence. We could
instead define an equivalence to be a morphism which is also a (plain) equivalence. However it is
more convenient to define via linear equivalence to get `.to_linear_equiv` for free. -/
structure lie_equiv (R : Type u) (L : Type v) (L' : Type w)
[comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
extends L →ₗ⁅R⁆ L', L ≃ₗ[R] L'
attribute [nolint doc_blame] lie_equiv.to_lie_hom
attribute [nolint doc_blame] lie_equiv.to_linear_equiv
notation L ` ≃ₗ⁅`:50 R `⁆ ` L' := lie_equiv R L L'
namespace lie_equiv
variables {R : Type u} {L₁ : Type v} {L₂ : Type w} {L₃ : Type w₁}
variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_ring L₃]
variables [lie_algebra R L₁] [lie_algebra R L₂] [lie_algebra R L₃]
instance has_coe_to_lie_hom : has_coe (L₁ ≃ₗ⁅R⁆ L₂) (L₁ →ₗ⁅R⁆ L₂) := ⟨to_lie_hom⟩
instance has_coe_to_linear_equiv : has_coe (L₁ ≃ₗ⁅R⁆ L₂) (L₁ ≃ₗ[R] L₂) := ⟨to_linear_equiv⟩
/-- see Note [function coercion] -/
instance : has_coe_to_fun (L₁ ≃ₗ⁅R⁆ L₂) := ⟨_, to_fun⟩
@[simp, norm_cast] lemma coe_to_lie_equiv (e : L₁ ≃ₗ⁅R⁆ L₂) : ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) = e :=
rfl
@[simp, norm_cast] lemma coe_to_linear_equiv (e : L₁ ≃ₗ⁅R⁆ L₂) :
((e : L₁ ≃ₗ[R] L₂) : L₁ → L₂) = e := rfl
instance : has_one (L₁ ≃ₗ⁅R⁆ L₁) :=
⟨{ map_lie' := λ x y,
by { change ((1 : L₁→ₗ[R] L₁) ⁅x, y⁆) = ⁅(1 : L₁→ₗ[R] L₁) x, (1 : L₁→ₗ[R] L₁) y⁆, simp, },
..(1 : L₁ ≃ₗ[R] L₁)}⟩
@[simp] lemma one_apply (x : L₁) : (1 : (L₁ ≃ₗ⁅R⁆ L₁)) x = x := rfl
instance : inhabited (L₁ ≃ₗ⁅R⁆ L₁) := ⟨1⟩
/-- Lie algebra equivalences are reflexive. -/
@[refl]
def refl : L₁ ≃ₗ⁅R⁆ L₁ := 1
@[simp] lemma refl_apply (x : L₁) : (refl : L₁ ≃ₗ⁅R⁆ L₁) x = x := rfl
/-- Lie algebra equivalences are symmetric. -/
@[symm]
def symm (e : L₁ ≃ₗ⁅R⁆ L₂) : L₂ ≃ₗ⁅R⁆ L₁ :=
{ ..lie_hom.inverse e.to_lie_hom e.inv_fun e.left_inv e.right_inv,
..e.to_linear_equiv.symm }
@[simp] lemma symm_symm (e : L₁ ≃ₗ⁅R⁆ L₂) : e.symm.symm = e :=
by { cases e, refl, }
@[simp] lemma apply_symm_apply (e : L₁ ≃ₗ⁅R⁆ L₂) : ∀ x, e (e.symm x) = x :=
e.to_linear_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : L₁ ≃ₗ⁅R⁆ L₂) : ∀ x, e.symm (e x) = x :=
e.to_linear_equiv.symm_apply_apply
/-- Lie algebra equivalences are transitive. -/
@[trans]
def trans (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) : L₁ ≃ₗ⁅R⁆ L₃ :=
{ ..lie_hom.comp e₂.to_lie_hom e₁.to_lie_hom,
..linear_equiv.trans e₁.to_linear_equiv e₂.to_linear_equiv }
@[simp] lemma trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) (x : L₁) :
(e₁.trans e₂) x = e₂ (e₁ x) := rfl
@[simp] lemma symm_trans_apply (e₁ : L₁ ≃ₗ⁅R⁆ L₂) (e₂ : L₂ ≃ₗ⁅R⁆ L₃) (x : L₃) :
(e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl
lemma bijective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.bijective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) :=
e.to_linear_equiv.bijective
lemma injective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.injective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) :=
e.to_linear_equiv.injective
lemma surjective (e : L₁ ≃ₗ⁅R⁆ L₂) : function.surjective ((e : L₁ →ₗ⁅R⁆ L₂) : L₁ → L₂) :=
e.to_linear_equiv.surjective
end lie_equiv
section lie_module_morphisms
variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) (P : Type w₂)
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [add_comm_group N] [add_comm_group P]
variables [module R M] [module R N] [module R P]
variables [lie_ring_module L M] [lie_ring_module L N] [lie_ring_module L P]
variables [lie_module R L M] [lie_module R L N] [lie_module R L P]
set_option old_structure_cmd true
/-- A morphism of Lie algebra modules is a linear map which commutes with the action of the Lie
algebra. -/
structure lie_module_hom extends M →ₗ[R] N :=
(map_lie' : ∀ {x : L} {m : M}, to_fun ⁅x, m⁆ = ⁅x, to_fun m⁆)
attribute [nolint doc_blame] lie_module_hom.to_linear_map
notation M ` →ₗ⁅`:25 R,L:25 `⁆ `:0 N:0 := lie_module_hom R L M N
namespace lie_module_hom
variables {R L M N P}
instance : has_coe (M →ₗ⁅R,L⁆ N) (M →ₗ[R] N) := ⟨lie_module_hom.to_linear_map⟩
/-- see Note [function coercion] -/
instance : has_coe_to_fun (M →ₗ⁅R,L⁆ N) := ⟨_, lie_module_hom.to_fun⟩
@[simp] lemma coe_mk (f : M → N) (h₁ h₂ h₃) :
((⟨f, h₁, h₂, h₃⟩ : M →ₗ⁅R,L⁆ N) : M → N) = f := rfl
@[simp, norm_cast] lemma coe_to_linear_map (f : M →ₗ⁅R,L⁆ N) : ((f : M →ₗ[R] N) : M → N) = f :=
rfl
@[simp] lemma map_lie (f : M →ₗ⁅R,L⁆ N) (x : L) (m : M) : f ⁅x, m⁆ = ⁅x, f m⁆ :=
lie_module_hom.map_lie' f
/-- The constant 0 map is a Lie module morphism. -/
instance : has_zero (M →ₗ⁅R,L⁆ N) := ⟨{ map_lie' := by simp, ..(0 : M →ₗ[R] N) }⟩
/-- The identity map is a Lie module morphism. -/
instance : has_one (M →ₗ⁅R,L⁆ M) := ⟨{ map_lie' := by simp, ..(1 : M →ₗ[R] M) }⟩
instance : inhabited (M →ₗ⁅R,L⁆ N) := ⟨0⟩
lemma coe_injective : function.injective (λ f : M →ₗ⁅R,L⁆ N, show M → N, from f) :=
by { rintros ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩, congr, }
@[ext] lemma ext {f g : M →ₗ⁅R,L⁆ N} (h : ∀ m, f m = g m) : f = g :=
coe_injective $ funext h
lemma ext_iff {f g : M →ₗ⁅R,L⁆ N} : f = g ↔ ∀ m, f m = g m :=
⟨by { rintro rfl m, refl, }, ext⟩
/-- The composition of Lie module morphisms is a morphism. -/
def comp (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) : M →ₗ⁅R,L⁆ P :=
{ map_lie' := λ x m, by { change f (g ⁅x, m⁆) = ⁅x, f (g m)⁆, rw [map_lie, map_lie], },
..linear_map.comp f.to_linear_map g.to_linear_map }
@[simp] lemma comp_apply (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) (m : M) :
f.comp g m = f (g m) := rfl
@[norm_cast] lemma comp_coe (f : N →ₗ⁅R,L⁆ P) (g : M →ₗ⁅R,L⁆ N) :
(f : N → P) ∘ (g : M → N) = f.comp g := rfl
/-- The inverse of a bijective morphism of Lie modules is a morphism of Lie modules. -/
def inverse (f : M →ₗ⁅R,L⁆ N) (g : N → M)
(h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : N →ₗ⁅R,L⁆ M :=
{ map_lie' := λ x n,
calc g ⁅x, n⁆ = g ⁅x, f (g n)⁆ : by rw h₂
... = g (f ⁅x, g n⁆) : by rw map_lie
... = ⁅x, g n⁆ : (h₁ _),
..linear_map.inverse f.to_linear_map g h₁ h₂ }
end lie_module_hom
/-- An equivalence of Lie algebra modules is a linear equivalence which is also a morphism of
Lie algebra modules. -/
structure lie_module_equiv extends M ≃ₗ[R] N, M →ₗ⁅R,L⁆ N
attribute [nolint doc_blame] lie_module_equiv.to_lie_module_hom
attribute [nolint doc_blame] lie_module_equiv.to_linear_equiv
notation M ` ≃ₗ⁅`:25 R,L:25 `⁆ `:0 N:0 := lie_module_equiv R L M N
namespace lie_module_equiv
variables {R L M N P}
instance has_coe_to_lie_module_hom : has_coe (M ≃ₗ⁅R,L⁆ N) (M →ₗ⁅R,L⁆ N) := ⟨to_lie_module_hom⟩
instance has_coe_to_linear_equiv : has_coe (M ≃ₗ⁅R,L⁆ N) (M ≃ₗ[R] N) := ⟨to_linear_equiv⟩
/-- see Note [function coercion] -/
instance : has_coe_to_fun (M ≃ₗ⁅R,L⁆ N) := ⟨_, to_fun⟩
@[simp, norm_cast] lemma coe_to_lie_module_hom (e : M ≃ₗ⁅R,L⁆ N) :
((e : M →ₗ⁅R,L⁆ N) : M → N) = e := rfl
@[simp, norm_cast] lemma coe_to_linear_equiv (e : M ≃ₗ⁅R,L⁆ N) : ((e : M ≃ₗ[R] N) : M → N) = e :=
rfl
instance : has_one (M ≃ₗ⁅R,L⁆ M) := ⟨{ map_lie' := λ x m, rfl, ..(1 : M ≃ₗ[R] M) }⟩
@[simp] lemma one_apply (m : M) : (1 : (M ≃ₗ⁅R,L⁆ M)) m = m := rfl
instance : inhabited (M ≃ₗ⁅R,L⁆ M) := ⟨1⟩
/-- Lie module equivalences are reflexive. -/
@[refl] def refl : M ≃ₗ⁅R,L⁆ M := 1
@[simp] lemma refl_apply (m : M) : (refl : M ≃ₗ⁅R,L⁆ M) m = m := rfl
/-- Lie module equivalences are syemmtric. -/
@[symm] def symm (e : M ≃ₗ⁅R,L⁆ N) : N ≃ₗ⁅R,L⁆ M :=
{ ..lie_module_hom.inverse e.to_lie_module_hom e.inv_fun e.left_inv e.right_inv,
..(e : M ≃ₗ[R] N).symm }
@[simp] lemma symm_symm (e : M ≃ₗ⁅R,L⁆ N) : e.symm.symm = e :=
by { cases e, refl, }
@[simp] lemma apply_symm_apply (e : M ≃ₗ⁅R,L⁆ N) : ∀ x, e (e.symm x) = x :=
e.to_linear_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : M ≃ₗ⁅R,L⁆ N) : ∀ x, e.symm (e x) = x :=
e.to_linear_equiv.symm_apply_apply
/-- Lie module equivalences are transitive. -/
@[trans] def trans (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) : M ≃ₗ⁅R,L⁆ P :=
{ ..lie_module_hom.comp e₂.to_lie_module_hom e₁.to_lie_module_hom,
..linear_equiv.trans e₁.to_linear_equiv e₂.to_linear_equiv }
@[simp] lemma trans_apply (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) (m : M) :
(e₁.trans e₂) m = e₂ (e₁ m) := rfl
@[simp] lemma symm_trans_apply (e₁ : M ≃ₗ⁅R,L⁆ N) (e₂ : N ≃ₗ⁅R,L⁆ P) (p : P) :
(e₁.trans e₂).symm p = e₁.symm (e₂.symm p) := rfl
end lie_module_equiv
end lie_module_morphisms
|
788eec86587728e12f69cd261ccbd427b35ea3b0 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/autoImplicitChainNameIssue.lean | b5b40e657571125f30e95a995b40c9b0beefe9ce | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 437 | lean | inductive Palindrome : List α → Prop where
| nil : Palindrome []
| single : (a : α) → Palindrome [a]
| sandwish : (a : α) → Palindrome as → Palindrome ([a] ++ as ++ [a])
theorem palindrome_reverse (h : Palindrome as) : Palindrome as.reverse := by
induction h with
| nil => done
| single a => exact Palindrome.single a
| sandwish a h ih => simp; exact Palindrome.sandwish _ ih
#check @palindrome_reverse
|
b03b7ae21012433e75e87f656c25e72174fa03cd | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/special_functions/complex/log.lean | ca30aaa89c5483472531ff8c6330d36183bb1e00 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 7,336 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson
-/
import analysis.special_functions.complex.arg
import analysis.special_functions.log.basic
/-!
# The complex `log` function
Basic properties, relationship with `exp`.
-/
noncomputable theory
namespace complex
open set filter
open_locale real topological_space
/-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`.
`log 0 = 0`-/
@[pp_nodot] noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I
lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log]
lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log]
lemma neg_pi_lt_log_im (x : ℂ) : -π < (log x).im := by simp only [log_im, neg_pi_lt_arg]
lemma log_im_le_pi (x : ℂ) : (log x).im ≤ π := by simp only [log_im, arg_le_pi]
lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x :=
by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx,
← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div,
mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc,
mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im]
@[simp] lemma range_exp : range exp = {0}ᶜ :=
set.ext $ λ x, ⟨by { rintro ⟨x, rfl⟩, exact exp_ne_zero x }, λ hx, ⟨log x, exp_log hx⟩⟩
lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x :=
by rw [log, abs_exp, real.log_exp, exp_eq_exp_re_mul_sin_add_cos, ← of_real_exp,
arg_mul_cos_add_sin_mul_I (real.exp_pos _) ⟨hx₁, hx₂⟩, re_add_im]
lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π)
(hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y :=
by rw [← log_exp hx₁ hx₂, ← log_exp hy₁ hy₂, hxy]
lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x :=
complex.ext
(by rw [log_re, of_real_re, abs_of_nonneg hx])
(by rw [of_real_im, log_im, arg_of_real_of_nonneg hx])
lemma log_of_real_re (x : ℝ) : (log (x : ℂ)).re = real.log x := by simp [log_re]
@[simp] lemma log_zero : log 0 = 0 := by simp [log]
@[simp] lemma log_one : log 1 = 0 := by simp [log]
lemma log_neg_one : log (-1) = π * I := by simp [log]
lemma log_I : log I = π / 2 * I := by simp [log]
lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log]
lemma two_pi_I_ne_zero : (2 * π * I : ℂ) ≠ 0 :=
by norm_num [real.pi_ne_zero, I_ne_zero]
lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) :=
begin
split,
{ intro h,
rcases exists_unique_add_zsmul_mem_Ioc real.two_pi_pos x.im (-π) with ⟨n, hn, -⟩,
use -n,
rw [int.cast_neg, neg_mul, eq_neg_iff_add_eq_zero],
have : (x + n * (2 * π * I)).im ∈ Ioc (-π) π, by simpa [two_mul, mul_add] using hn,
rw [← log_exp this.1 this.2, exp_periodic.int_mul n, h, log_one] },
{ rintro ⟨n, rfl⟩, exact (exp_periodic.int_mul n).eq.trans exp_zero }
end
lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 :=
by rw [exp_sub, div_eq_one_iff_eq (exp_ne_zero _)]
lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) :=
by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add']
@[simp] lemma countable_preimage_exp {s : set ℂ} : countable (exp ⁻¹' s) ↔ countable s :=
begin
refine ⟨λ hs, _, λ hs, _⟩,
{ refine ((hs.image exp).insert 0).mono _,
rw [image_preimage_eq_inter_range, range_exp, ← diff_eq, ← union_singleton, diff_union_self],
exact subset_union_left _ _ },
{ rw ← bUnion_preimage_singleton,
refine hs.bUnion (λ z hz, _),
rcases em (∃ w, exp w = z) with ⟨w, rfl⟩|hne,
{ simp only [preimage, mem_singleton_iff, exp_eq_exp_iff_exists_int, set_of_exists],
exact countable_Union (λ m, countable_singleton _) },
{ push_neg at hne, simp [preimage, hne] } }
end
alias countable_preimage_exp ↔ _ set.countable.preimage_cexp
lemma tendsto_log_nhds_within_im_neg_of_re_neg_of_im_zero
{z : ℂ} (hre : z.re < 0) (him : z.im = 0) :
tendsto log (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 $ real.log (abs z) - π * I) :=
begin
have := (continuous_of_real.continuous_at.comp_continuous_within_at
(continuous_abs.continuous_within_at.log _)).tendsto.add
(((continuous_of_real.tendsto _).comp $
tendsto_arg_nhds_within_im_neg_of_re_neg_of_im_zero hre him).mul tendsto_const_nhds),
convert this,
{ simp [sub_eq_add_neg] },
{ lift z to ℝ using him, simpa using hre.ne }
end
lemma continuous_within_at_log_of_re_neg_of_im_zero
{z : ℂ} (hre : z.re < 0) (him : z.im = 0) :
continuous_within_at log {z : ℂ | 0 ≤ z.im} z :=
begin
have := (continuous_of_real.continuous_at.comp_continuous_within_at
(continuous_abs.continuous_within_at.log _)).tendsto.add
((continuous_of_real.continuous_at.comp_continuous_within_at $
continuous_within_at_arg_of_re_neg_of_im_zero hre him).mul tendsto_const_nhds),
convert this,
{ lift z to ℝ using him, simpa using hre.ne }
end
lemma tendsto_log_nhds_within_im_nonneg_of_re_neg_of_im_zero
{z : ℂ} (hre : z.re < 0) (him : z.im = 0) :
tendsto log (𝓝[{z : ℂ | 0 ≤ z.im}] z) (𝓝 $ real.log (abs z) + π * I) :=
by simpa only [log, arg_eq_pi_iff.2 ⟨hre, him⟩]
using (continuous_within_at_log_of_re_neg_of_im_zero hre him).tendsto
end complex
section log_deriv
open complex filter
open_locale topological_space
variables {α : Type*}
lemma continuous_at_clog {x : ℂ} (h : 0 < x.re ∨ x.im ≠ 0) :
continuous_at log x :=
begin
refine continuous_at.add _ _,
{ refine continuous_of_real.continuous_at.comp _,
refine (real.continuous_at_log _).comp complex.continuous_abs.continuous_at,
rw abs_ne_zero,
rintro rfl,
simpa using h },
{ have h_cont_mul : continuous (λ x : ℂ, x * I), from continuous_id'.mul continuous_const,
refine h_cont_mul.continuous_at.comp (continuous_of_real.continuous_at.comp _),
exact continuous_at_arg h, },
end
lemma filter.tendsto.clog {l : filter α} {f : α → ℂ} {x : ℂ} (h : tendsto f l (𝓝 x))
(hx : 0 < x.re ∨ x.im ≠ 0) :
tendsto (λ t, log (f t)) l (𝓝 $ log x) :=
(continuous_at_clog hx).tendsto.comp h
variables [topological_space α]
lemma continuous_at.clog {f : α → ℂ} {x : α} (h₁ : continuous_at f x)
(h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
continuous_at (λ t, log (f t)) x :=
h₁.clog h₂
lemma continuous_within_at.clog {f : α → ℂ} {s : set α} {x : α} (h₁ : continuous_within_at f s x)
(h₂ : 0 < (f x).re ∨ (f x).im ≠ 0) :
continuous_within_at (λ t, log (f t)) s x :=
h₁.clog h₂
lemma continuous_on.clog {f : α → ℂ} {s : set α} (h₁ : continuous_on f s)
(h₂ : ∀ x ∈ s, 0 < (f x).re ∨ (f x).im ≠ 0) :
continuous_on (λ t, log (f t)) s :=
λ x hx, (h₁ x hx).clog (h₂ x hx)
lemma continuous.clog {f : α → ℂ} (h₁ : continuous f) (h₂ : ∀ x, 0 < (f x).re ∨ (f x).im ≠ 0) :
continuous (λ t, log (f t)) :=
continuous_iff_continuous_at.2 $ λ x, h₁.continuous_at.clog (h₂ x)
end log_deriv
|
88ac328728042dccdae08d998feaa0e0d0005f93 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/flycheck_blast_cc_heq7.lean | 923af7aa434358fc44de695c52755fc58031139f | [
"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 | 123 | lean | set_option blast.cc.heq true
set_option trace.app_builder true
definition t3 (a b : nat) : (a = b) == (b = a) :=
by blast
|
d5ab3f6ef36f03cf50ba6c0674abd1d35e85bc9c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/vec_notation.lean | 249dce6f4147becccb8f7df3a6052321ffd0b1db | [
"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 | 783 | lean | import data.fin.vec_notation
/-! These tests are testing `pi_fin.reflect` and fail with
`local attribute [-instance] pi_fin.reflect` -/
#eval do
let x : fin 0 → ℕ := ![],
tactic.is_def_eq `(x) `(![] : fin 0 → ℕ)
#eval do
let x := ![1, 2, 3],
tactic.is_def_eq `(x) `(![1, 2, 3])
#eval do
let x := ![ulift.up.{3} 1, ulift.up.{3} 2],
tactic.is_def_eq (reflect x) `(![ulift.up.{3} 1, ulift.up.{3} 2])
#eval do
let x := ![![1, 2], ![3, 4]],
tactic.is_def_eq `(x) `(![![1, 2], ![3, 4]])
/-! These tests are testing `pi_fin.has_repr` -/
#eval show tactic unit, from guard (repr (![] : _ → ℕ) = "![]")
#eval show tactic unit, from guard (repr ![1, 2, 3] = "![1, 2, 3]")
#eval show tactic unit, from guard (repr ![![1, 2], ![3, 4]] = "![![1, 2], ![3, 4]]")
|
e38f1df467f74047375c0e030ea7253a72c2a987 | abd85493667895c57a7507870867b28124b3998f | /src/analysis/convex/specific_functions.lean | b456c368efa466bc8a593d7ce4b905c51e19c013 | [
"Apache-2.0"
] | permissive | pechersky/mathlib | d56eef16bddb0bfc8bc552b05b7270aff5944393 | f1df14c2214ee114c9738e733efd5de174deb95d | refs/heads/master | 1,666,714,392,571 | 1,591,747,567,000 | 1,591,747,567,000 | 270,557,274 | 0 | 0 | Apache-2.0 | 1,591,597,975,000 | 1,591,597,974,000 | null | UTF-8 | Lean | false | false | 5,043 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.mean_value
import data.nat.parity
import analysis.special_functions.pow
/-!
# Collection of convex functions
In this file we prove that the following functions are convex:
* `convex_on_exp` : the exponential function is convex on $(-∞, +∞)$;
* `convex_on_pow_of_even` : given an even natural number $n$, the function $f(x)=x^n$
is convex on $(-∞, +∞)$;
* `convex_on_pow` : for a natural $n$, the function $f(x)=x^n$ is convex on $[0, +∞)$;
* `convex_on_fpow` : for an integer $m$, the function $f(x)=x^m$ is convex on $(0, +∞)$.
* `convex_on_rpow : ∀ p : ℝ, 1 ≤ p → convex_on (Ici 0) (λ x, x ^ p)`
-/
open real set
open_locale big_operators
/-- `exp` is convex on the whole real line -/
lemma convex_on_exp : convex_on univ exp :=
convex_on_univ_of_deriv2_nonneg differentiable_exp (by simp)
(assume x, (iter_deriv_exp 2).symm ▸ le_of_lt (exp_pos x))
/-- `x^n`, `n : ℕ` is convex on the whole real line whenever `n` is even -/
lemma convex_on_pow_of_even {n : ℕ} (hn : n.even) : convex_on set.univ (λ x, x^n) :=
begin
apply convex_on_univ_of_deriv2_nonneg differentiable_pow,
{ simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] },
{ intro x,
rcases hn.sub (nat.even_bit0 1) with ⟨k, hk⟩,
simp only [iter_deriv_pow, finset.prod_range_succ, finset.prod_range_zero, nat.sub_zero,
mul_one, hk, pow_mul', pow_two],
exact mul_nonneg (nat.cast_nonneg _) (mul_self_nonneg _) }
end
/-- `x^n`, `n : ℕ` is convex on `[0, +∞)` for all `n` -/
lemma convex_on_pow (n : ℕ) : convex_on (Ici 0) (λ x, x^n) :=
begin
apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on;
simp only [interior_Ici, differentiable_on_pow, deriv_pow',
differentiable_on_const, differentiable_on.mul, iter_deriv_pow],
intros x hx,
exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (le_of_lt hx) _)
end
lemma finset.prod_nonneg_of_card_nonpos_even
{α β : Type*} [linear_ordered_comm_ring β]
{f : α → β} [decidable_pred (λ x, f x ≤ 0)]
{s : finset α} (h0 : (s.filter (λ x, f x ≤ 0)).card.even) :
0 ≤ ∏ x in s, f x :=
calc 0 ≤ (∏ x in s, ((if f x ≤ 0 then (-1:β) else 1) * f x)) :
finset.prod_nonneg (λ x _, by
{ split_ifs with hx hx, by simp [hx], simp at hx ⊢, exact le_of_lt hx })
... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one,
mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul]
lemma int_prod_range_nonneg (m : ℤ) (n : ℕ) (hn : n.even) :
0 ≤ ∏ k in finset.range n, (m - k) :=
begin
cases (le_or_lt ↑n m) with hnm hmn,
{ exact finset.prod_nonneg (λ k hk, sub_nonneg.2 (le_trans
(int.coe_nat_le.2 $ le_of_lt $ finset.mem_range.1 hk) hnm)) },
cases le_or_lt 0 m with hm hm,
{ lift m to ℕ using hm,
exact le_of_eq (eq.symm $ finset.prod_eq_zero
(finset.mem_range.2 $ int.coe_nat_lt.1 hmn) (sub_self _)) },
clear hmn,
apply finset.prod_nonneg_of_card_nonpos_even,
convert hn,
convert finset.card_range n,
ext k,
simp only [finset.mem_filter, finset.mem_range],
refine ⟨and.left, λ hk, ⟨hk, sub_nonpos.2 $ le_trans (le_of_lt hm) _⟩⟩,
exact int.coe_nat_nonneg k
end
/-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` -/
lemma convex_on_fpow (m : ℤ) : convex_on (Ioi 0) (λ x, x^m) :=
begin
apply convex_on_of_deriv2_nonneg (convex_Ioi 0); try { rw [interior_Ioi] },
{ exact (differentiable_on_fpow $ lt_irrefl _).continuous_on },
{ exact differentiable_on_fpow (lt_irrefl _) },
{ have : eq_on (deriv (λx:ℝ, x^m)) (λx, ↑m * x^(m-1)) (Ioi 0),
from λ x hx, deriv_fpow (ne_of_gt hx),
refine (differentiable_on_congr this).2 _,
exact (differentiable_on_fpow (lt_irrefl _)).const_mul _ },
{ intros x hx,
simp only [iter_deriv_fpow (ne_of_gt hx)],
refine mul_nonneg (int.cast_nonneg.2 _) (fpow_nonneg_of_nonneg (le_of_lt hx) _),
exact int_prod_range_nonneg _ _ (nat.even_bit0 1) }
end
lemma convex_on_rpow {p : ℝ} (hp : 1 ≤ p) : convex_on (Ici 0) (λ x, x^p) :=
begin
have A : deriv (λ (x : ℝ), x ^ p) = λ x, p * x^(p-1), by { ext x, simp [hp] },
apply convex_on_of_deriv2_nonneg (convex_Ici 0),
{ apply (continuous_rpow_of_pos (λ _, lt_of_lt_of_le zero_lt_one hp)
continuous_id continuous_const).continuous_on },
{ apply differentiable.differentiable_on, simp [hp] },
{ rw A,
assume x hx,
replace hx : x ≠ 0, by { simp at hx, exact ne_of_gt hx },
simp [differentiable_at.differentiable_within_at, hx] },
{ assume x hx,
replace hx : 0 < x, by simpa using hx,
suffices : 0 ≤ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A],
apply mul_nonneg (le_trans zero_le_one hp),
exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg (le_of_lt hx) _) }
end
|
37afbab50b76fd42aa9e4ab4bb16732e52098f37 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/order/filter/basic.lean | 6748130b7d2ef41f8ca7f1acd7bcd38aa4c11149 | [
"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 | 112,429 | 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
-/
import control.traversable.instances
import data.set.finite
import order.copy
import tactic.monotonicity
/-!
# Theory of filters on sets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Main definitions
* `filter` : filters on a set;
* `at_top`, `at_bot`, `cofinite`, `principal` : specific filters;
* `map`, `comap` : operations on filters;
* `tendsto` : limit with respect to filters;
* `eventually` : `f.eventually p` means `{x | p x} ∈ f`;
* `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`;
* `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f`
with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`;
* `ne_bot f` : an utility class stating that `f` is a non-trivial filter.
Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to
abstract two related kinds of ideas:
* *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions
at a point or at infinity, etc...
* *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough
a point `x`, or for close enough pairs of points, or things happening almost everywhere in the
sense of measure theory. Dually, filters can also express the idea of *things happening often*:
for arbitrarily large `n`, or at a point in any neighborhood of given a point etc...
In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice
structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois
insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to
the smallest filter containing it in the other direction.
We also prove `filter` is a monadic functor, with a push-forward operation
`filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the
order on filters.
The examples of filters appearing in the description of the two motivating ideas are:
* `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N`
* `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic)
* `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces
defined in topology.uniform_space.basic)
* `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in
`measure_theory.measure_space`)
The general notion of limit of a map with respect to filters on the source and target types
is `filter.tendsto`. It is defined in terms of the order and the push-forward operation.
The predicate "happening eventually" is `filter.eventually`, and "happening often" is
`filter.frequently`, whose definitions are immediate after `filter` is defined (but they come
rather late in this file in order to immediately relate them to the lattice structure).
For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to
some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of
`M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`,
which is a special case of `mem_closure_of_tendsto` from topology.basic.
## Notations
* `∀ᶠ x in f, p x` : `f.eventually p`;
* `∃ᶠ x in f, p x` : `f.frequently p`;
* `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`;
* `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`;
* `𝓟 s` : `principal s`, localized in `filter`.
## References
* [N. Bourbaki, *General Topology*][bourbaki1966]
Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which
we do *not* require. This gives `filter X` better formal properties, in particular a bottom element
`⊥` for its lattice structure, at the cost of including the assumption
`[ne_bot f]` in a number of lemmas and definitions.
-/
open function set order
universes u v w x y
open_locale classical
/-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`,
is upwards-closed, and is stable under intersection. We do not forbid this collection to be
all sets of `α`. -/
structure filter (α : Type*) :=
(sets : set (set α))
(univ_sets : set.univ ∈ sets)
(sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets)
(inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets)
/-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/
instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩
namespace filter
variables {α : Type u} {f g : filter α} {s t : set α}
@[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl
@[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl
instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩
lemma filter_eq : ∀ {f g : filter α}, f.sets = g.sets → f = g
| ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl
lemma filter_eq_iff : f = g ↔ f.sets = g.sets :=
⟨congr_arg _, filter_eq⟩
protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g :=
by simp only [filter_eq_iff, ext_iff, filter.mem_sets]
@[ext]
protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g :=
filter.ext_iff.2
/-- An extensionality lemma that is useful for filters with good lemmas about `sᶜ ∈ f` (e.g.,
`filter.comap`, `filter.coprod`, `filter.Coprod`, `filter.cofinite`). -/
protected lemma coext (h : ∀ s, sᶜ ∈ f ↔ sᶜ ∈ g) : f = g :=
filter.ext $ compl_surjective.forall.2 h
@[simp] lemma univ_mem : univ ∈ f :=
f.univ_sets
lemma mem_of_superset {x y : set α} (hx : x ∈ f) (hxy : x ⊆ y) : y ∈ f :=
f.sets_of_superset hx hxy
lemma inter_mem {s t : set α} (hs : s ∈ f) (ht : t ∈ f) : s ∩ t ∈ f :=
f.inter_sets hs ht
@[simp] lemma inter_mem_iff {s t : set α} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f :=
⟨λ h, ⟨mem_of_superset h (inter_subset_left s t),
mem_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem⟩
lemma diff_mem {s t : set α} (hs : s ∈ f) (ht : tᶜ ∈ f) : s \ t ∈ f :=
inter_mem hs ht
lemma univ_mem' (h : ∀ a, a ∈ s) : s ∈ f :=
mem_of_superset univ_mem (λ x _, h x)
lemma mp_mem (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f :=
mem_of_superset (inter_mem hs h) $ λ x ⟨h₁, h₂⟩, h₂ h₁
lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f :=
⟨λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mp)),
λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mpr))⟩
@[simp] lemma bInter_mem {β : Type v} {s : β → set α} {is : set β} (hf : is.finite) :
(⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f :=
finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs])
@[simp] lemma bInter_finset_mem {β : Type v} {s : β → set α} (is : finset β) :
(⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f :=
bInter_mem is.finite_to_set
alias bInter_finset_mem ← _root_.finset.Inter_mem_sets
attribute [protected] finset.Inter_mem_sets
@[simp] lemma sInter_mem {s : set (set α)} (hfin : s.finite) :
⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f :=
by rw [sInter_eq_bInter, bInter_mem hfin]
@[simp] lemma Inter_mem {β : Type v} {s : β → set α} [finite β] :
(⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f :=
by simpa using bInter_mem finite_univ
lemma exists_mem_subset_iff : (∃ t ∈ f, t ⊆ s) ↔ s ∈ f :=
⟨λ ⟨t, ht, ts⟩, mem_of_superset ht ts, λ hs, ⟨s, hs, subset.rfl⟩⟩
lemma monotone_mem {f : filter α} : monotone (λ s, s ∈ f) :=
λ s t hst h, mem_of_superset h hst
lemma exists_mem_and_iff {P : set α → Prop} {Q : set α → Prop} (hP : antitone P) (hQ : antitone Q) :
(∃ u ∈ f, P u) ∧ (∃ u ∈ f, Q u) ↔ (∃ u ∈ f, P u ∧ Q u) :=
begin
split,
{ rintro ⟨⟨u, huf, hPu⟩, v, hvf, hQv⟩, exact ⟨u ∩ v, inter_mem huf hvf,
hP (inter_subset_left _ _) hPu, hQ (inter_subset_right _ _) hQv⟩ },
{ rintro ⟨u, huf, hPu, hQu⟩, exact ⟨⟨u, huf, hPu⟩, u, huf, hQu⟩ }
end
lemma forall_in_swap {β : Type*} {p : set α → β → Prop} :
(∀ (a ∈ f) b, p a b) ↔ ∀ b (a ∈ f), p a b :=
set.forall_in_swap
end filter
namespace tactic.interactive
open tactic
setup_tactic_parser
/--
`filter_upwards [h₁, ⋯, hₙ]` replaces a goal of the form `s ∈ f` and terms
`h₁ : t₁ ∈ f, ⋯, hₙ : tₙ ∈ f` with `∀ x, x ∈ t₁ → ⋯ → x ∈ tₙ → x ∈ s`.
The list is an optional parameter, `[]` being its default value.
`filter_upwards [h₁, ⋯, hₙ] with a₁ a₂ ⋯ aₖ` is a short form for
`{ filter_upwards [h₁, ⋯, hₙ], intros a₁ a₂ ⋯ aₖ }`.
`filter_upwards [h₁, ⋯, hₙ] using e` is a short form for
`{ filter_upwards [h1, ⋯, hn], exact e }`.
Combining both shortcuts is done by writing `filter_upwards [h₁, ⋯, hₙ] with a₁ a₂ ⋯ aₖ using e`.
Note that in this case, the `aᵢ` terms can be used in `e`.
-/
meta def filter_upwards
(s : parse types.pexpr_list?)
(wth : parse with_ident_list?)
(tgt : parse (tk "using" *> texpr)?) : tactic unit :=
do
(s.get_or_else []).reverse.mmap (λ e, eapplyc `filter.mp_mem >> eapply e),
eapplyc `filter.univ_mem',
`[dsimp only [set.mem_set_of_eq]],
let wth := wth.get_or_else [],
if ¬wth.empty then intros wth else skip,
match tgt with
| some e := exact e
| none := skip
end
add_tactic_doc
{ name := "filter_upwards",
category := doc_category.tactic,
decl_names := [`tactic.interactive.filter_upwards],
tags := ["goal management", "lemma application"] }
end tactic.interactive
namespace filter
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type*} {ι : Sort x}
section principal
/-- The principal filter of `s` is the collection of all supersets of `s`. -/
def principal (s : set α) : filter α :=
{ sets := {t | s ⊆ t},
univ_sets := subset_univ s,
sets_of_superset := λ x y hx, subset.trans hx,
inter_sets := λ x y, subset_inter }
localized "notation (name := filter.principal) `𝓟` := filter.principal" in filter
@[simp] lemma mem_principal {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl
lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.rfl
end principal
open_locale filter
section join
/-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/
def join (f : filter (filter α)) : filter α :=
{ sets := {s | {t : filter α | s ∈ t} ∈ f},
univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true],
sets_of_superset := λ x y hx xy,
mem_of_superset hx $ λ f h, mem_of_superset h xy,
inter_sets := λ x y hx hy,
mem_of_superset (inter_mem hx hy) $ λ f ⟨h₁, h₂⟩, inter_mem h₁ h₂ }
@[simp] lemma mem_join {s : set α} {f : filter (filter α)} :
s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl
end join
section lattice
variables {f g : filter α} {s t : set α}
instance : partial_order (filter α) :=
{ le := λ f g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f,
le_antisymm := λ a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁,
le_refl := λ a, subset.rfl,
le_trans := λ a b c h₁ h₂, subset.trans h₂ h₁ }
theorem le_def : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl
protected lemma not_le : ¬ f ≤ g ↔ ∃ s ∈ g, s ∉ f := by simp_rw [le_def, not_forall]
/-- `generate_sets g s`: `s` is in the filter closure of `g`. -/
inductive generate_sets (g : set (set α)) : set α → Prop
| basic {s : set α} : s ∈ g → generate_sets s
| univ : generate_sets univ
| superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t
| inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t)
/-- `generate g` is the largest filter containing the sets `g`. -/
def generate (g : set (set α)) : filter α :=
{ sets := generate_sets g,
univ_sets := generate_sets.univ,
sets_of_superset := λ x y, generate_sets.superset,
inter_sets := λ s t, generate_sets.inter }
lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets :=
iff.intro
(λ h u hu, h $ generate_sets.basic $ hu)
(λ h u hu, hu.rec_on h univ_mem
(λ x y _ hxy hx, mem_of_superset hx hxy)
(λ x y _ _ hx hy, inter_mem hx hy))
lemma mem_generate_iff {s : set $ set α} {U : set α} :
U ∈ generate s ↔ ∃ t ⊆ s, set.finite t ∧ ⋂₀ t ⊆ U :=
begin
split ; intro h,
{ induction h,
case basic : V V_in
{ exact ⟨{V}, singleton_subset_iff.2 V_in, finite_singleton _, (sInter_singleton _).subset⟩ },
case univ { exact ⟨∅, empty_subset _, finite_empty, subset_univ _⟩ },
case superset : V W hV' hVW hV
{ rcases hV with ⟨t, hts, ht, htV⟩,
exact ⟨t, hts, ht, htV.trans hVW⟩ },
case inter : V W hV' hW' hV hW
{ rcases ⟨hV, hW⟩ with ⟨⟨t, hts, ht, htV⟩, u, hus, hu, huW⟩,
exact ⟨t ∪ u, union_subset hts hus, ht.union hu,
(sInter_union _ _).subset.trans $ inter_subset_inter htV huW⟩ } },
{ rcases h with ⟨t, hts, tfin, h⟩,
exact mem_of_superset ((sInter_mem tfin).2 $ λ V hV, generate_sets.basic $ hts hV) h },
end
/-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly
`s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/
protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α :=
{ sets := s,
univ_sets := hs ▸ (univ_mem : univ ∈ generate s),
sets_of_superset := λ x y, hs ▸ (mem_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s),
inter_sets := λ x y, hs ▸ (inter_mem : x ∈ generate s → y ∈ generate s →
x ∩ y ∈ generate s) }
lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} :
filter.mk_of_closure s hs = generate s :=
filter.ext $ λ u,
show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl
/-- Galois insertion from sets of sets into filters. -/
def gi_generate (α : Type*) :
@galois_insertion (set (set α)) (filter α)ᵒᵈ _ _ filter.generate filter.sets :=
{ gc := λ s f, sets_iff_generate,
le_l_u := λ f u h, generate_sets.basic h,
choice := λ s hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_rfl),
choice_eq := λ s hs, mk_of_closure_sets }
/-- The infimum of filters is the filter generated by intersections
of elements of the two filters. -/
instance : has_inf (filter α) := ⟨λf g : filter α,
{ sets := {s | ∃ (a ∈ f) (b ∈ g), s = a ∩ b },
univ_sets := ⟨_, univ_mem, _, univ_mem, by simp⟩,
sets_of_superset := begin
rintro x y ⟨a, ha, b, hb, rfl⟩ xy,
refine ⟨a ∪ y, mem_of_superset ha (subset_union_left a y),
b ∪ y, mem_of_superset hb (subset_union_left b y), _⟩,
rw [← inter_union_distrib_right, union_eq_self_of_subset_left xy]
end,
inter_sets := begin
rintro x y ⟨a, ha, b, hb, rfl⟩ ⟨c, hc, d, hd, rfl⟩,
refine ⟨a ∩ c, inter_mem ha hc, b ∩ d, inter_mem hb hd, _⟩,
ac_refl
end }⟩
lemma mem_inf_iff {f g : filter α} {s : set α} :
s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, s = t₁ ∩ t₂ := iff.rfl
lemma mem_inf_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g :=
⟨s, h, univ, univ_mem, (inter_univ s).symm⟩
lemma mem_inf_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g :=
⟨univ, univ_mem, s, h, (univ_inter s).symm⟩
lemma inter_mem_inf {α : Type u} {f g : filter α} {s t : set α}
(hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g :=
⟨s, hs, t, ht, rfl⟩
lemma mem_inf_of_inter {f g : filter α} {s t u : set α} (hs : s ∈ f) (ht : t ∈ g) (h : s ∩ t ⊆ u) :
u ∈ f ⊓ g :=
mem_of_superset (inter_mem_inf hs ht) h
lemma mem_inf_iff_superset {f g : filter α} {s : set α} :
s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, t₁ ∩ t₂ ⊆ s :=
⟨λ ⟨t₁, h₁, t₂, h₂, eq⟩, ⟨t₁, h₁, t₂, h₂, eq ▸ subset.rfl⟩,
λ ⟨t₁, h₁, t₂, h₂, sub⟩, mem_inf_of_inter h₁ h₂ sub⟩
instance : has_top (filter α) :=
⟨{ sets := {s | ∀ x, x ∈ s},
univ_sets := λ x, mem_univ x,
sets_of_superset := λ x y hx hxy a, hxy (hx a),
inter_sets := λ x y hx hy a, mem_inter (hx _) (hy _) }⟩
lemma mem_top_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀ x, x ∈ s) :=
iff.rfl
@[simp] lemma mem_top {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ :=
by rw [mem_top_iff_forall, eq_univ_iff_forall]
section complete_lattice
/- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately,
we want to have different definitional equalities for the lattice operations. So we define them
upfront and change the lattice operations for the complete lattice instance. -/
private def original_complete_lattice : complete_lattice (filter α) :=
@order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice
local attribute [instance] original_complete_lattice
instance : complete_lattice (filter α) := original_complete_lattice.copy
/- le -/ filter.partial_order.le rfl
/- top -/ (filter.has_top).1
(top_unique $ λ s hs, by simp [mem_top.1 hs])
/- bot -/ _ rfl
/- sup -/ _ rfl
/- inf -/ (filter.has_inf).1
begin
ext f g : 2,
exact le_antisymm
(le_inf (λ s, mem_inf_of_left) (λ s, mem_inf_of_right))
(begin
rintro s ⟨a, ha, b, hb, rfl⟩,
exact inter_sets _ (@inf_le_left (filter α) _ _ _ _ ha)
(@inf_le_right (filter α) _ _ _ _ hb)
end)
end
/- Sup -/ (join ∘ 𝓟) (by { ext s x, exact mem_Inter₂.symm.trans
(set.ext_iff.1 (sInter_image _ _) x).symm})
/- Inf -/ _ rfl
instance : inhabited (filter α) := ⟨⊥⟩
end complete_lattice
/-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set
does not belong to the filter. Bourbaki include this assumption in the definition
of a filter but we prefer to have a `complete_lattice` structure on filter, so
we use a typeclass argument in lemmas instead. -/
class ne_bot (f : filter α) : Prop := (ne' : f ≠ ⊥)
lemma ne_bot_iff {f : filter α} : ne_bot f ↔ f ≠ ⊥ := ⟨λ h, h.1, λ h, ⟨h⟩⟩
lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := ne_bot.ne'
@[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ :=
not_iff_comm.1 ne_bot_iff.symm
lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g :=
⟨ne_bot_of_le_ne_bot hf.1 hg⟩
lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g :=
hf.mono hg
@[simp] lemma sup_ne_bot {f g : filter α} : ne_bot (f ⊔ g) ↔ ne_bot f ∨ ne_bot g :=
by simp [ne_bot_iff, not_and_distrib]
lemma not_disjoint_self_iff : ¬ disjoint f f ↔ f.ne_bot := by rw [disjoint_self, ne_bot_iff]
lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl
lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets :=
(gi_generate α).gc.u_inf
lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂ f ∈ s, (f : filter α).sets) :=
(gi_generate α).gc.u_Inf
lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂ i, (f i).sets) :=
(gi_generate α).gc.u_infi
lemma generate_empty : filter.generate ∅ = (⊤ : filter α) :=
(gi_generate α).gc.l_bot
lemma generate_univ : filter.generate univ = (⊥ : filter α) :=
mk_of_closure_sets.symm
lemma generate_union {s t : set (set α)} :
filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t :=
(gi_generate α).gc.l_sup
lemma generate_Union {s : ι → set (set α)} :
filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) :=
(gi_generate α).gc.l_supr
@[simp] lemma mem_bot {s : set α} : s ∈ (⊥ : filter α) :=
trivial
@[simp] lemma mem_sup {f g : filter α} {s : set α} :
s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g :=
iff.rfl
lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) :
s ∪ t ∈ f ⊔ g :=
⟨mem_of_superset hs (subset_union_left s t), mem_of_superset ht (subset_union_right s t)⟩
@[simp] lemma mem_Sup {x : set α} {s : set (filter α)} :
x ∈ Sup s ↔ (∀ f ∈ s, x ∈ (f : filter α)) :=
iff.rfl
@[simp] lemma mem_supr {x : set α} {f : ι → filter α} :
x ∈ supr f ↔ (∀ i, x ∈ f i) :=
by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter]
@[simp] lemma supr_ne_bot {f : ι → filter α} : (⨆ i, f i).ne_bot ↔ ∃ i, (f i).ne_bot :=
by simp [ne_bot_iff]
lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) :=
show generate _ = generate _, from congr_arg _ $ congr_arg Sup $ (range_comp _ _).symm
lemma mem_infi_of_mem {f : ι → filter α} (i : ι) : ∀ {s}, s ∈ f i → s ∈ ⨅ i, f i :=
show (⨅ i, f i) ≤ f i, from infi_le _ _
lemma mem_infi_of_Inter {ι} {s : ι → filter α} {U : set α} {I : set ι} (I_fin : I.finite)
{V : I → set α} (hV : ∀ i, V i ∈ s i) (hU : (⋂ i, V i) ⊆ U) : U ∈ ⨅ i, s i :=
begin
haveI := I_fin.fintype,
refine mem_of_superset (Inter_mem.2 $ λ i, _) hU,
exact mem_infi_of_mem i (hV _)
end
lemma mem_infi {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔
∃ I : set ι, I.finite ∧ ∃ V : I → set α, (∀ i, V i ∈ s i) ∧ U = ⋂ i, V i :=
begin
split,
{ rw [infi_eq_generate, mem_generate_iff],
rintro ⟨t, tsub, tfin, tinter⟩,
rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩,
rw sInter_Union at tinter,
set V := λ i, U ∪ ⋂₀ σ i with hV,
have V_in : ∀ i, V i ∈ s i,
{ rintro i,
have : (⋂₀ σ i) ∈ s i,
{ rw sInter_mem (σfin _),
apply σsub },
exact mem_of_superset this (subset_union_right _ _) },
refine ⟨I, Ifin, V, V_in, _⟩,
rwa [hV, ← union_Inter, union_eq_self_of_subset_right] },
{ rintro ⟨I, Ifin, V, V_in, rfl⟩,
exact mem_infi_of_Inter Ifin V_in subset.rfl }
end
lemma mem_infi' {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔
∃ I : set ι, I.finite ∧ ∃ V : ι → set α, (∀ i, V i ∈ s i) ∧
(∀ i ∉ I, V i = univ) ∧ (U = ⋂ i ∈ I, V i) ∧ U = ⋂ i, V i :=
begin
simp only [mem_infi, set_coe.forall', bInter_eq_Inter],
refine ⟨_, λ ⟨I, If, V, hVs, _, hVU, _⟩, ⟨I, If, λ i, V i, λ i, hVs i, hVU⟩⟩,
rintro ⟨I, If, V, hV, rfl⟩,
refine ⟨I, If, λ i, if hi : i ∈ I then V ⟨i, hi⟩ else univ, λ i, _, λ i hi, _, _⟩,
{ split_ifs, exacts [hV _, univ_mem] },
{ exact dif_neg hi },
{ simp only [Inter_dite, bInter_eq_Inter, dif_pos (subtype.coe_prop _), subtype.coe_eta,
Inter_univ, inter_univ, eq_self_iff_true, true_and] }
end
lemma exists_Inter_of_mem_infi {ι : Type*} {α : Type*} {f : ι → filter α} {s}
(hs : s ∈ ⨅ i, f i) : ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i :=
let ⟨I, If, V, hVs, hV', hVU, hVU'⟩ := mem_infi'.1 hs in ⟨V, hVs, hVU'⟩
lemma mem_infi_of_finite {ι : Type*} [finite ι] {α : Type*} {f : ι → filter α} (s) :
s ∈ (⨅ i, f i) ↔ ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i :=
begin
refine ⟨exists_Inter_of_mem_infi, _⟩,
rintro ⟨t, ht, rfl⟩,
exact Inter_mem.2 (λ i, mem_infi_of_mem i (ht i))
end
@[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f :=
show (∀ {t}, s ⊆ t → t ∈ f) ↔ s ∈ f,
from ⟨λ h, h (subset.refl s), λ hs t ht, mem_of_superset hs ht⟩
lemma Iic_principal (s : set α) : Iic (𝓟 s) = {l | s ∈ l} :=
set.ext $ λ x, le_principal_iff
lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t :=
by simp only [le_principal_iff, iff_self, mem_principal]
@[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) :=
λ _ _, principal_mono.2
@[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t :=
by simp only [le_antisymm_iff, le_principal_iff, mem_principal]; refl
@[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl
@[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ :=
top_unique $ by simp only [le_principal_iff, mem_top, eq_self_iff_true]
@[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ :=
bot_unique $ λ s _, empty_subset _
lemma generate_eq_binfi (S : set (set α)) : generate S = ⨅ s ∈ S, 𝓟 s :=
eq_of_forall_le_iff $ λ f, by simp [sets_iff_generate, le_principal_iff, subset_def]
/-! ### Lattice equations -/
lemma empty_mem_iff_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ :=
⟨λ h, bot_unique $ λ s _, mem_of_superset h (empty_subset s),
λ h, h.symm ▸ mem_bot⟩
lemma nonempty_of_mem {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) :
s.nonempty :=
s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_mem_iff_bot.mp hf.1)) id
lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) :
s.nonempty :=
@nonempty_of_mem α f hf s hs
@[simp] lemma empty_not_mem (f : filter α) [ne_bot f] : ¬(∅ ∈ f) :=
λ h, (nonempty_of_mem h).ne_empty rfl
lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α :=
nonempty_of_exists $ nonempty_of_mem (univ_mem : univ ∈ f)
lemma compl_not_mem {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f :=
λ hsc, (nonempty_of_mem (inter_mem h hsc)).ne_empty $ inter_compl_self s
lemma filter_eq_bot_of_is_empty [is_empty α] (f : filter α) : f = ⊥ :=
empty_mem_iff_bot.mp $ univ_mem' is_empty_elim
protected lemma disjoint_iff {f g : filter α} :
disjoint f g ↔ ∃ (s ∈ f) (t ∈ g), disjoint s t :=
by simp only [disjoint_iff, ← empty_mem_iff_bot, mem_inf_iff,
inf_eq_inter, bot_eq_empty, @eq_comm _ ∅]
lemma disjoint_of_disjoint_of_mem {f g : filter α} {s t : set α} (h : disjoint s t)
(hs : s ∈ f) (ht : t ∈ g) : disjoint f g :=
filter.disjoint_iff.mpr ⟨s, hs, t, ht, h⟩
lemma ne_bot.not_disjoint (hf : f.ne_bot) (hs : s ∈ f) (ht : t ∈ f) :
¬ disjoint s t :=
λ h, not_disjoint_self_iff.2 hf $ filter.disjoint_iff.2 ⟨s, hs, t, ht, h⟩
lemma inf_eq_bot_iff {f g : filter α} :
f ⊓ g = ⊥ ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ :=
by simpa only [←disjoint_iff, set.disjoint_iff_inter_eq_empty] using filter.disjoint_iff
lemma _root_.pairwise.exists_mem_filter_of_disjoint {ι : Type*} [finite ι]
{l : ι → filter α} (hd : pairwise (disjoint on l)) :
∃ s : ι → set α, (∀ i, s i ∈ l i) ∧ pairwise (disjoint on s) :=
begin
simp only [pairwise, function.on_fun, filter.disjoint_iff, subtype.exists'] at hd,
choose! s t hst using hd,
refine ⟨λ i, ⋂ j, @s i j ∩ @t j i, λ i, _, λ i j hij, _⟩,
exacts [Inter_mem.2 (λ j, inter_mem (@s i j).2 (@t j i).2),
(hst hij).mono ((Inter_subset _ j).trans (inter_subset_left _ _))
((Inter_subset _ i).trans (inter_subset_right _ _))]
end
lemma _root_.set.pairwise_disjoint.exists_mem_filter {ι : Type*} {l : ι → filter α} {t : set ι}
(hd : t.pairwise_disjoint l) (ht : t.finite) :
∃ s : ι → set α, (∀ i, s i ∈ l i) ∧ t.pairwise_disjoint s :=
begin
casesI ht,
obtain ⟨s, hd⟩ : ∃ s : Π i : t, {s : set α // s ∈ l i}, pairwise (disjoint on λ i, (s i : set α)),
{ rcases (hd.subtype _ _).exists_mem_filter_of_disjoint with ⟨s, hsl, hsd⟩,
exact ⟨λ i, ⟨s i, hsl i⟩, hsd⟩ },
-- TODO: Lean fails to find `can_lift` instance and fails to use an instance supplied by `letI`
rcases @subtype.exists_pi_extension ι (λ i, {s // s ∈ l i}) _ _ s with ⟨s, rfl⟩,
exact ⟨λ i, s i, λ i, (s i).2, pairwise.set_of_subtype _ _ hd⟩
end
/-- There is exactly one filter on an empty type. -/
instance unique [is_empty α] : unique (filter α) :=
{ to_inhabited := filter.inhabited, uniq := filter_eq_bot_of_is_empty }
/-- There are only two filters on a `subsingleton`: `⊥` and `⊤`. If the type is empty, then they are
equal. -/
lemma eq_top_of_ne_bot [subsingleton α] (l : filter α) [ne_bot l] : l = ⊤ :=
begin
refine top_unique (λ s hs, _),
obtain rfl : s = univ, from subsingleton.eq_univ_of_nonempty (nonempty_of_mem hs),
exact univ_mem
end
lemma forall_mem_nonempty_iff_ne_bot {f : filter α} :
(∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f :=
⟨λ h, ⟨λ hf, not_nonempty_empty (h ∅ $ hf.symm ▸ mem_bot)⟩, @nonempty_of_mem _ _⟩
instance [nonempty α] : nontrivial (filter α) :=
⟨⟨⊤, ⊥, ne_bot.ne $ forall_mem_nonempty_iff_ne_bot.1 $ λ s hs,
by rwa [mem_top.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩
lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α :=
⟨λ h, by_contra $ λ h',
by { haveI := not_nonempty_iff.1 h', exact not_subsingleton (filter α) infer_instance },
@filter.nontrivial α⟩
lemma eq_Inf_of_mem_iff_exists_mem {S : set (filter α)} {l : filter α}
(h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S :=
le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩)
(λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs)
lemma eq_infi_of_mem_iff_exists_mem {f : ι → filter α} {l : filter α}
(h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) :
l = infi f :=
eq_Inf_of_mem_iff_exists_mem $ λ s, h.trans exists_range_iff.symm
lemma eq_binfi_of_mem_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α}
(h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) :
l = ⨅ i (_ : p i), f i :=
begin
rw [infi_subtype'],
apply eq_infi_of_mem_iff_exists_mem,
intro s,
exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩
end
lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] :
(infi f).sets = (⋃ i, (f i).sets) :=
let ⟨i⟩ := ne, u := { filter .
sets := (⋃ i, (f i).sets),
univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem⟩,
sets_of_superset := by simp only [mem_Union, exists_imp_distrib];
intros x y i hx hxy; exact ⟨i, mem_of_superset hx hxy⟩,
inter_sets :=
begin
simp only [mem_Union, exists_imp_distrib],
intros x y a hx b hy,
rcases h a b with ⟨c, ha, hb⟩,
exact ⟨c, inter_mem (ha hx) (hb hy)⟩
end } in
have u = infi f, from eq_infi_of_mem_iff_exists_mem
(λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]),
congr_arg filter.sets this.symm
lemma mem_infi_of_directed {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) :
s ∈ infi f ↔ ∃ i, s ∈ f i :=
by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union]
lemma mem_binfi_of_directed {f : β → filter α} {s : set β}
(h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} :
t ∈ (⨅ i ∈ s, f i) ↔ ∃ i ∈ s, t ∈ f i :=
by haveI : nonempty {x // x ∈ s} := ne.to_subtype;
erw [infi_subtype', mem_infi_of_directed h.directed_coe, subtype.exists]; refl
lemma binfi_sets_eq {f : β → filter α} {s : set β}
(h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) :
(⨅ i ∈ s, f i).sets = ⋃ i ∈ s, (f i).sets :=
ext $ λ t, by simp [mem_binfi_of_directed h ne]
lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) :
(⨅ i, f i).sets = (⋃ t : finset ι, (⨅ i ∈ t, f i).sets) :=
begin
rw [infi_eq_infi_finset, infi_sets_eq],
exact directed_of_sup (λ s₁ s₂, binfi_mono),
end
lemma infi_sets_eq_finite' (f : ι → filter α) :
(⨅ i, f i).sets = (⋃ t : finset (plift ι), (⨅ i ∈ t, f (plift.down i)).sets) :=
by { rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp], refl }
lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) :
s ∈ infi f ↔ ∃ t : finset ι, s ∈ ⨅ i ∈ t, f i :=
(set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union
lemma mem_infi_finite' {f : ι → filter α} (s) :
s ∈ infi f ↔ ∃ t : finset (plift ι), s ∈ ⨅ i ∈ t, f (plift.down i) :=
(set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union
@[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) :=
filter.ext $ λ x, by simp only [mem_sup, mem_join]
@[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} :
(⨆ x, join (f x)) = join (⨆ x, f x) :=
filter.ext $ λ x, by simp only [mem_supr, mem_join]
instance : distrib_lattice (filter α) :=
{ le_sup_inf :=
begin
intros x y z s,
simp only [and_assoc, mem_inf_iff, mem_sup, exists_prop, exists_imp_distrib, and_imp],
rintro hs t₁ ht₁ t₂ ht₂ rfl,
exact ⟨t₁, x.sets_of_superset hs (inter_subset_left t₁ t₂),
ht₁,
t₂,
x.sets_of_superset hs (inter_subset_right t₁ t₂),
ht₂,
rfl⟩
end,
..filter.complete_lattice }
-- The dual version does not hold! `filter α` is not a `complete_distrib_lattice`. -/
instance : coframe (filter α) :=
{ Inf := Inf,
infi_sup_le_sup_Inf := λ f s, begin
rw [Inf_eq_infi', infi_subtype'],
rintro t ⟨h₁, h₂⟩,
rw infi_sets_eq_finite' at h₂,
simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂,
obtain ⟨u, hu⟩ := h₂,
suffices : (⨅ i, f ⊔ ↑i) ≤ f ⊔ u.inf (λ i, ↑i.down),
{ exact this ⟨h₁, hu⟩ },
refine finset.induction_on u (le_sup_of_le_right le_top) _,
rintro ⟨i⟩ u _ ih,
rw [finset.inf_insert, sup_inf_left],
exact le_inf (infi_le _ _) ih,
end,
..filter.complete_lattice }
lemma mem_infi_finset {s : finset α} {f : α → filter β} {t : set β} :
t ∈ (⨅ a ∈ s, f a) ↔ (∃ p : α → set β, (∀ a ∈ s, p a ∈ f a) ∧ t = ⋂ a ∈ s, p a) :=
begin
simp only [← finset.set_bInter_coe, bInter_eq_Inter, infi_subtype'],
refine ⟨λ h, _, _⟩,
{ rcases (mem_infi_of_finite _).1 h with ⟨p, hp, rfl⟩,
refine ⟨λ a, if h : a ∈ s then p ⟨a, h⟩ else univ, λ a ha, by simpa [ha] using hp ⟨a, ha⟩, _⟩,
refine Inter_congr_of_surjective id surjective_id _,
rintro ⟨a, ha⟩, simp [ha] },
{ rintro ⟨p, hpf, rfl⟩,
exact Inter_mem.2 (λ a, mem_infi_of_mem a (hpf a a.2)) }
end
/-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`.
See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/
lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι]
(hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) :=
⟨begin
intro h,
have he : ∅ ∈ (infi f), from h.symm ▸ (mem_bot : ∅ ∈ (⊥ : filter α)),
obtain ⟨i, hi⟩ : ∃ i, ∅ ∈ f i,
from (mem_infi_of_directed hd ∅).1 he,
exact (hb i).ne (empty_mem_iff_bot.1 hi)
end⟩
/-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`.
See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/
lemma infi_ne_bot_of_directed {f : ι → filter α}
[hn : nonempty α] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) :=
begin
casesI is_empty_or_nonempty ι,
{ constructor, simp [infi_of_empty f, top_ne_bot] },
{ exact infi_ne_bot_of_directed' hd hb }
end
lemma Inf_ne_bot_of_directed' {s : set (filter α)} (hne : s.nonempty) (hd : directed_on (≥) s)
(hbot : ⊥ ∉ s) : ne_bot (Inf s) :=
(Inf_eq_infi' s).symm ▸ @infi_ne_bot_of_directed' _ _ _
hne.to_subtype hd.directed_coe (λ ⟨f, hf⟩, ⟨ne_of_mem_of_not_mem hf hbot⟩)
lemma Inf_ne_bot_of_directed [nonempty α] {s : set (filter α)} (hd : directed_on (≥) s)
(hbot : ⊥ ∉ s) : ne_bot (Inf s) :=
(Inf_eq_infi' s).symm ▸ infi_ne_bot_of_directed hd.directed_coe
(λ ⟨f, hf⟩, ⟨ne_of_mem_of_not_mem hf hbot⟩)
lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) :
ne_bot (infi f) ↔ ∀ i, ne_bot (f i) :=
⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩
lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) :
ne_bot (infi f) ↔ (∀ i, ne_bot (f i)) :=
⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩
@[elab_as_eliminator]
lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop}
(uni : p univ)
(ins : ∀ {i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) : p s :=
begin
rw [mem_infi_finite'] at hs,
simp only [← finset.inf_eq_infi] at hs,
rcases hs with ⟨is, his⟩,
revert s,
refine finset.induction_on is _ _,
{ intros s hs, rwa [mem_top.1 hs] },
{ rintro ⟨i⟩ js his ih s hs,
rw [finset.inf_insert, mem_inf_iff] at hs,
rcases hs with ⟨s₁, hs₁, s₂, hs₂, rfl⟩,
exact ins hs₁ (ih hs₂) }
end
/-! #### `principal` equations -/
@[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) :=
le_antisymm
(by simp only [le_principal_iff, mem_inf_iff]; exact ⟨s, subset.rfl, t, subset.rfl, rfl⟩)
(by simp [le_inf_iff, inter_subset_left, inter_subset_right])
@[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) :=
filter.ext $ λ u, by simp only [union_subset_iff, mem_sup, mem_principal]
@[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆ x, 𝓟 (s x)) = 𝓟 (⋃ i, s i) :=
filter.ext $ λ x, by simp only [mem_supr, mem_principal, Union_subset_iff]
@[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ :=
empty_mem_iff_bot.symm.trans $ mem_principal.trans subset_empty_iff
@[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty :=
ne_bot_iff.trans $ (not_congr principal_eq_bot_iff).trans nonempty_iff_ne_empty.symm
alias principal_ne_bot_iff ↔ _ _root_.set.nonempty.principal_ne_bot
lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) :=
is_compl.of_eq (by rw [inf_principal, inter_compl_self, principal_empty]) $
by rw [sup_principal, union_compl_self, principal_univ]
theorem mem_inf_principal' {f : filter α} {s t : set α} :
s ∈ f ⊓ 𝓟 t ↔ tᶜ ∪ s ∈ f :=
by simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint_assoc, inf_principal,
← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl]
theorem mem_inf_principal {f : filter α} {s t : set α} :
s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f :=
by { simp only [mem_inf_principal', imp_iff_not_or], refl }
lemma supr_inf_principal (f : ι → filter α) (s : set α) :
(⨆ i, f i ⊓ 𝓟 s) = (⨆ i, f i) ⊓ 𝓟 s :=
by { ext, simp only [mem_supr, mem_inf_principal] }
lemma inf_principal_eq_bot {f : filter α} {s : set α} : f ⊓ 𝓟 s = ⊥ ↔ sᶜ ∈ f :=
by { rw [← empty_mem_iff_bot, mem_inf_principal], refl }
lemma mem_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f :=
by rwa [inf_principal_eq_bot, compl_compl] at h
lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) :
s \ t ∈ f ⊓ 𝓟 tᶜ :=
inter_mem_inf hs $ mem_principal_self tᶜ
lemma principal_le_iff {s : set α} {f : filter α} :
𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V :=
begin
change (∀ V, V ∈ f → V ∈ _) ↔ _,
simp_rw mem_principal,
end
@[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) :
(⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) :=
begin
induction s using finset.induction_on with i s hi hs,
{ simp },
{ rw [finset.infi_insert, finset.set_bInter_insert, hs, inf_principal] },
end
@[simp] lemma infi_principal {ι : Type w} [finite ι] (f : ι → set α) :
(⨅ i, 𝓟 (f i)) = 𝓟 (⋂ i, f i) :=
by { casesI nonempty_fintype ι, simpa using infi_principal_finset finset.univ f }
lemma infi_principal_finite {ι : Type w} {s : set ι} (hs : s.finite) (f : ι → set α) :
(⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) :=
begin
lift s to finset ι using hs,
exact_mod_cast infi_principal_finset s f
end
end lattice
@[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) :
join f₁ ≤ join f₂ :=
λ s hs, h hs
/-! ### Eventually -/
/-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x`
means that `p` holds true for sufficiently large `x`. -/
protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f
notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r
lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f :=
iff.rfl
@[simp] lemma eventually_mem_set {s : set α} {l : filter α} : (∀ᶠ x in l, x ∈ s) ↔ s ∈ l := iff.rfl
protected lemma ext' {f₁ f₂ : filter α}
(h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) :
f₁ = f₂ :=
filter.ext h
lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop}
(hp : ∀ᶠ x in f₂, p x) :
∀ᶠ x in f₁, p x :=
h hp
lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) :
∀ᶠ x in f, P x :=
mem_of_superset hU h
protected lemma eventually.and {p q : α → Prop} {f : filter α} :
f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x :=
inter_mem
@[simp]
lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem
lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) :
∀ᶠ x in f, p x :=
univ_mem' hp
lemma forall_eventually_of_eventually_forall {f : filter α} {p : α → β → Prop}
(h : ∀ᶠ x in f, ∀ y, p x y) : ∀ y, ∀ᶠ x in f, p x y :=
by { intros y, filter_upwards [h], tauto, }
@[simp] lemma eventually_false_iff_eq_bot {f : filter α} :
(∀ᶠ x in f, false) ↔ f = ⊥ :=
empty_mem_iff_bot
@[simp] lemma eventually_const {f : filter α} [t : ne_bot f] {p : Prop} :
(∀ᶠ x in f, p) ↔ p :=
classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h] using t.ne)
lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} :
(∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y :=
exists_mem_subset_iff.symm
lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) :
∃ v ∈ f, ∀ y ∈ v, p y :=
eventually_iff_exists_mem.1 hp
lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x)
(hq : ∀ᶠ x in f, p x → q x) :
∀ᶠ x in f, q x :=
mp_mem hp hq
lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x)
(hq : ∀ x, p x → q x) :
∀ᶠ x in f, q x :=
hp.mp (eventually_of_forall hq)
@[simp] lemma eventually_and {p q : α → Prop} {f : filter α} :
(∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) :=
inter_mem_iff
lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x)
(h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x :=
h'.mp (h.mono $ λ x hx, hx.mp)
lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) :
(∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) :=
⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩
@[simp] lemma eventually_all {ι : Type*} [finite ι] {l} {p : ι → α → Prop} :
(∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x :=
by { casesI nonempty_fintype ι, simpa only [filter.eventually, set_of_forall] using Inter_mem }
@[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} :
(∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) :=
by simpa only [filter.eventually, set_of_forall] using bInter_mem hI
alias eventually_all_finite ← _root_.set.finite.eventually_all
attribute [protected] set.finite.eventually_all
@[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} :
(∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x :=
I.finite_to_set.eventually_all
alias eventually_all_finset ← _root_.finset.eventually_all
attribute [protected] finset.eventually_all
@[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} :
(∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) :=
classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h])
@[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} :
(∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) :=
by simp only [or_comm _ q, eventually_or_distrib_left]
@[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} :
(∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) :=
by simp only [imp_iff_not_or, eventually_or_distrib_left]
@[simp]
lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩
@[simp]
lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) :=
iff.rfl
@[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} :
(∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) :=
iff.rfl
@[simp]
lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} :
(∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) :=
iff.rfl
@[simp]
lemma eventually_supr {p : α → Prop} {fs : ι → filter α} :
(∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) :=
mem_supr
@[simp]
lemma eventually_principal {a : set α} {p : α → Prop} :
(∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) :=
iff.rfl
lemma eventually_inf {f g : filter α} {p : α → Prop} :
(∀ᶠ x in f ⊓ g, p x) ↔ ∃ (s ∈ f) (t ∈ g), ∀ x ∈ s ∩ t, p x :=
mem_inf_iff_superset
theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} :
(∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x :=
mem_inf_principal
/-! ### Frequently -/
/-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x`
means that there exist arbitrarily large `x` for which `p` holds true. -/
protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x
notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r
lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) :
∃ᶠ x in f, p x :=
compl_not_mem h
lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) :
∃ᶠ x in f, p x :=
eventually.frequently (eventually_of_forall h)
lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x)
(hpq : ∀ᶠ x in f, p x → q x) :
∃ᶠ x in f, q x :=
mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h
lemma frequently.filter_mono {p : α → Prop} {f g : filter α} (h : ∃ᶠ x in f, p x) (hle : f ≤ g) :
∃ᶠ x in g, p x :=
mt (λ h', h'.filter_mono hle) h
lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x)
(hpq : ∀ x, p x → q x) :
∃ᶠ x in f, q x :=
h.mp (eventually_of_forall hpq)
lemma frequently.and_eventually {p q : α → Prop} {f : filter α}
(hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) :
∃ᶠ x in f, p x ∧ q x :=
begin
refine mt (λ h, hq.mp $ h.mono _) hp,
exact λ x hpq hq hp, hpq ⟨hp, hq⟩
end
lemma eventually.and_frequently {p q : α → Prop} {f : filter α}
(hp : ∀ᶠ x in f, p x) (hq : ∃ᶠ x in f, q x) :
∃ᶠ x in f, p x ∧ q x :=
by simpa only [and.comm] using hq.and_eventually hp
lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x :=
begin
by_contradiction H,
replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H),
exact hp H
end
lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) :
∃ x, p x :=
hp.frequently.exists
lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} :
(∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x :=
⟨λ hp q hq, (hp.and_eventually hq).exists,
λ H hp, by simpa only [and_not_self, exists_false] using H hp⟩
lemma frequently_iff {f : filter α} {P : α → Prop} :
(∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x :=
begin
simp only [frequently_iff_forall_eventually_exists_and, exists_prop, and_comm (P _)],
refl
end
@[simp] lemma not_eventually {p : α → Prop} {f : filter α} :
(¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) :=
by simp [filter.frequently]
@[simp] lemma not_frequently {p : α → Prop} {f : filter α} :
(¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) :=
by simp only [filter.frequently, not_not]
@[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f :=
by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot_iff]
@[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp
@[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} :
(∃ᶠ x in f, p) ↔ p :=
classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h])
@[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} :
(∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) :=
by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and]
lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} :
(∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) :=
by simp
lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} :
(∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q :=
by simp
@[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} :
(∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) :=
by simp [imp_iff_not_or, not_eventually, frequently_or_distrib]
lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} :
(∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) :=
by simp
lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} :
(∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) :=
by simp
@[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} :
(∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) :=
by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently]
@[simp] lemma frequently_and_distrib_left {f : filter α} {p : Prop} {q : α → Prop} :
(∃ᶠ x in f, p ∧ q x) ↔ (p ∧ ∃ᶠ x in f, q x) :=
by simp only [filter.frequently, not_and, eventually_imp_distrib_left, not_imp]
@[simp] lemma frequently_and_distrib_right {f : filter α} {p : α → Prop} {q : Prop} :
(∃ᶠ x in f, p x ∧ q) ↔ ((∃ᶠ x in f, p x) ∧ q) :=
by simp only [and_comm _ q, frequently_and_distrib_left]
@[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp
@[simp]
lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) :=
by simp [filter.frequently]
@[simp]
lemma frequently_principal {a : set α} {p : α → Prop} :
(∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) :=
by simp [filter.frequently, not_forall]
lemma frequently_sup {p : α → Prop} {f g : filter α} :
(∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) :=
by simp only [filter.frequently, eventually_sup, not_and_distrib]
@[simp]
lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} :
(∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) :=
by simp [filter.frequently, -not_eventually, not_forall]
@[simp]
lemma frequently_supr {p : α → Prop} {fs : β → filter α} :
(∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) :=
by simp [filter.frequently, -not_eventually, not_forall]
lemma eventually.choice {r : α → β → Prop} {l : filter α}
[l.ne_bot] (h : ∀ᶠ x in l, ∃ y, r x y) : ∃ f : α → β, ∀ᶠ x in l, r x (f x) :=
begin
classical,
use (λ x, if hx : ∃ y, r x y then classical.some hx
else classical.some (classical.some_spec h.exists)),
filter_upwards [h],
intros x hx,
rw dif_pos hx,
exact classical.some_spec hx
end
/-!
### Relation “eventually equal”
-/
/-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that
`f x = g x` belongs to `l`. -/
def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x
notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g
lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) :
∀ᶠ x in l, f x = g x :=
h
lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop)
(hf : ∀ᶠ x in l, p x (f x)) :
∀ᶠ x in l, p x (g x) :=
hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl
lemma eventually_eq_set {s t : set α} {l : filter α} :
s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t :=
eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩
alias eventually_eq_set ↔ eventually_eq.mem_iff eventually.set_eq
@[simp] lemma eventually_eq_univ {s : set α} {l : filter α} : s =ᶠ[l] univ ↔ s ∈ l :=
by simp [eventually_eq_set]
lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) :
∃ s ∈ l, eq_on f g s :=
h.exists_mem
lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α}
(hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g :=
eventually_of_mem hs h
lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} :
(f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s :=
eventually_iff_exists_mem
lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) :
f =ᶠ[l'] g :=
h₂ h₁
@[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) :
f =ᶠ[l] f :=
eventually_of_forall $ λ x, rfl
lemma eventually_eq.rfl {l : filter α} {f : α → β} : f =ᶠ[l] f := eventually_eq.refl l f
@[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) :
g =ᶠ[l] f :=
H.mono $ λ _, eq.symm
@[trans] lemma eventually_eq.trans {l : filter α} {f g h : α → β}
(H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h :=
H₂.rw (λ x y, f x = y) H₁
lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') :
(λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) :=
hf.mp $ hg.mono $ by { intros, simp only * }
lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) :
(h ∘ f) =ᶠ[l] (h ∘ g) :=
H.mono $ λ x hx, congr_arg h hx
lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ)
(Hg : g =ᶠ[l] g') :
(λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) :=
(Hf.prod_mk Hg).fun_comp (uncurry h)
@[to_additive]
lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g)
(h' : f' =ᶠ[l] g') :
((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) :=
h.comp₂ (*) h'
@[to_additive]
lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) :
((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) :=
h.fun_comp has_inv.inv
@[to_additive]
lemma eventually_eq.div [has_div β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g)
(h' : f' =ᶠ[l] g') :
((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) :=
h.comp₂ (/) h'
@[to_additive] lemma eventually_eq.const_smul {𝕜} [has_smul 𝕜 β] {l : filter α} {f g : α → β}
(h : f =ᶠ[l] g) (c : 𝕜) :
(λ x, c • f x) =ᶠ[l] (λ x, c • g x) :=
h.fun_comp (λ x, c • x)
@[to_additive] lemma eventually_eq.smul {𝕜} [has_smul 𝕜 β] {l : filter α} {f f' : α → 𝕜}
{g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') :
(λ x, f x • g x) =ᶠ[l] λ x, f' x • g' x :=
hf.comp₂ (•) hg
lemma eventually_eq.sup [has_sup β] {l : filter α} {f f' g g' : α → β}
(hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') :
(λ x, f x ⊔ g x) =ᶠ[l] λ x, f' x ⊔ g' x :=
hf.comp₂ (⊔) hg
lemma eventually_eq.inf [has_inf β] {l : filter α} {f f' g g' : α → β}
(hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') :
(λ x, f x ⊓ g x) =ᶠ[l] λ x, f' x ⊓ g' x :=
hf.comp₂ (⊓) hg
lemma eventually_eq.preimage {l : filter α} {f g : α → β}
(h : f =ᶠ[l] g) (s : set β) : f ⁻¹' s =ᶠ[l] g ⁻¹' s :=
h.fun_comp s
lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') :
(s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) :=
h.comp₂ (∧) h'
lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') :
(s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) :=
h.comp₂ (∨) h'
lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) :
(sᶜ : set α) =ᶠ[l] (tᶜ : set α) :=
h.fun_comp not
lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') :
(s \ s' : set α) =ᶠ[l] (t \ t' : set α) :=
h.inter h'.compl
lemma eventually_eq_empty {s : set α} {l : filter α} :
s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s :=
eventually_eq_set.trans $ by simp
lemma inter_eventually_eq_left {s t : set α} {l : filter α} :
(s ∩ t : set α) =ᶠ[l] s ↔ ∀ᶠ x in l, x ∈ s → x ∈ t :=
by simp only [eventually_eq_set, mem_inter_iff, and_iff_left_iff_imp]
lemma inter_eventually_eq_right {s t : set α} {l : filter α} :
(s ∩ t : set α) =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ t → x ∈ s :=
by rw [inter_comm, inter_eventually_eq_left]
@[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} :
f =ᶠ[𝓟 s] g ↔ eq_on f g s :=
iff.rfl
lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} :
(f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x :=
eventually_inf_principal
lemma eventually_eq.sub_eq [add_group β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) :
f - g =ᶠ[l] 0 :=
by simpa using (eventually_eq.sub (eventually_eq.refl l f) h).symm
lemma eventually_eq_iff_sub [add_group β] {f g : α → β} {l : filter α} :
f =ᶠ[l] g ↔ f - g =ᶠ[l] 0 :=
⟨λ h, h.sub_eq, λ h, by simpa using h.add (eventually_eq.refl l g)⟩
section has_le
variables [has_le β] {l : filter α}
/-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/
def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x
notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g
lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') :
f' ≤ᶠ[l] g' :=
H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H
lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') :
f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' :=
⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩
end has_le
section preorder
variables [preorder β] {l : filter α} {f g h : α → β}
lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq
@[refl] lemma eventually_le.refl (l : filter α) (f : α → β) :
f ≤ᶠ[l] f :=
eventually_eq.rfl.le
lemma eventually_le.rfl : f ≤ᶠ[l] f := eventually_le.refl l f
@[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h :=
H₂.mp $ H₁.mono $ λ x, le_trans
@[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h :=
H₁.le.trans H₂
@[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h :=
H₁.trans H₂.le
end preorder
lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β}
(h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) :
f =ᶠ[l] g :=
h₂.mp $ h₁.mono $ λ x, le_antisymm
lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} :
f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f :=
by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and]
lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) :
g ≤ᶠ[l] f ↔ g =ᶠ[l] f :=
⟨λ h', h'.antisymm h, eventually_eq.le⟩
lemma eventually.ne_of_lt [preorder β] {l : filter α} {f g : α → β}
(h : ∀ᶠ x in l, f x < g x) : ∀ᶠ x in l, f x ≠ g x :=
h.mono (λ x hx, hx.ne)
lemma eventually.ne_top_of_lt [partial_order β] [order_top β] {l : filter α} {f g : α → β}
(h : ∀ᶠ x in l, f x < g x) : ∀ᶠ x in l, f x ≠ ⊤ :=
h.mono (λ x hx, hx.ne_top)
lemma eventually.lt_top_of_ne [partial_order β] [order_top β] {l : filter α} {f : α → β}
(h : ∀ᶠ x in l, f x ≠ ⊤) : ∀ᶠ x in l, f x < ⊤ :=
h.mono (λ x hx, hx.lt_top)
lemma eventually.lt_top_iff_ne_top [partial_order β] [order_top β] {l : filter α} {f : α → β} :
(∀ᶠ x in l, f x < ⊤) ↔ ∀ᶠ x in l, f x ≠ ⊤ :=
⟨eventually.ne_of_lt, eventually.lt_top_of_ne⟩
@[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t)
(h' : s' ≤ᶠ[l] t') :
(s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) :=
h'.mp $ h.mono $ λ x, and.imp
@[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t)
(h' : s' ≤ᶠ[l] t') :
(s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) :=
h'.mp $ h.mono $ λ x, or.imp
@[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) :
(tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) :=
h.mono $ λ x, mt
@[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t)
(h' : t' ≤ᶠ[l] s') :
(s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) :=
h.inter h'.compl
lemma eventually_le.mul_le_mul
[mul_zero_class β] [partial_order β] [pos_mul_mono β] [mul_pos_mono β]
{l : filter α} {f₁ f₂ g₁ g₂ : α → β}
(hf : f₁ ≤ᶠ[l] f₂) (hg : g₁ ≤ᶠ[l] g₂) (hg₀ : 0 ≤ᶠ[l] g₁) (hf₀ : 0 ≤ᶠ[l] f₂) :
f₁ * g₁ ≤ᶠ[l] f₂ * g₂ :=
by filter_upwards [hf, hg, hg₀, hf₀] with x using mul_le_mul
@[to_additive eventually_le.add_le_add]
lemma eventually_le.mul_le_mul' [has_mul β] [preorder β]
[covariant_class β β (*) (≤)] [covariant_class β β (swap (*)) (≤)]
{l : filter α} {f₁ f₂ g₁ g₂ : α → β} (hf : f₁ ≤ᶠ[l] f₂) (hg : g₁ ≤ᶠ[l] g₂) :
f₁ * g₁ ≤ᶠ[l] f₂ * g₂ :=
by filter_upwards [hf, hg] with x hfx hgx using mul_le_mul' hfx hgx
lemma eventually_le.mul_nonneg [ordered_semiring β] {l : filter α} {f g : α → β}
(hf : 0 ≤ᶠ[l] f) (hg : 0 ≤ᶠ[l] g) :
0 ≤ᶠ[l] f * g :=
by filter_upwards [hf, hg] with x using mul_nonneg
lemma eventually_sub_nonneg [ordered_ring β] {l : filter α} {f g : α → β} :
0 ≤ᶠ[l] g - f ↔ f ≤ᶠ[l] g :=
eventually_congr $ eventually_of_forall $ λ x, sub_nonneg
lemma eventually_le.sup [semilattice_sup β] {l : filter α} {f₁ f₂ g₁ g₂ : α → β}
(hf : f₁ ≤ᶠ[l] f₂) (hg : g₁ ≤ᶠ[l] g₂) :
f₁ ⊔ g₁ ≤ᶠ[l] f₂ ⊔ g₂ :=
by filter_upwards [hf, hg] with x hfx hgx using sup_le_sup hfx hgx
lemma eventually_le.sup_le [semilattice_sup β] {l : filter α} {f g h : α → β}
(hf : f ≤ᶠ[l] h) (hg : g ≤ᶠ[l] h) :
f ⊔ g ≤ᶠ[l] h :=
by filter_upwards [hf, hg] with x hfx hgx using sup_le hfx hgx
lemma eventually_le.le_sup_of_le_left [semilattice_sup β] {l : filter α} {f g h : α → β}
(hf : h ≤ᶠ[l] f) :
h ≤ᶠ[l] f ⊔ g :=
by filter_upwards [hf] with x hfx using le_sup_of_le_left hfx
lemma eventually_le.le_sup_of_le_right [semilattice_sup β] {l : filter α} {f g h : α → β}
(hg : h ≤ᶠ[l] g) :
h ≤ᶠ[l] f ⊔ g :=
by filter_upwards [hg] with x hgx using le_sup_of_le_right hgx
lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l :=
λ s hs, h.mono $ λ m hm, hm hs
/-! ### Push-forwards, pull-backs, and the monad structure -/
section map
/-- The forward map of a filter -/
def map (m : α → β) (f : filter α) : filter β :=
{ sets := preimage m ⁻¹' f.sets,
univ_sets := univ_mem,
sets_of_superset := λ s t hs st, mem_of_superset hs $ preimage_mono st,
inter_sets := λ s t hs ht, inter_mem hs ht }
@[simp] lemma map_principal {s : set α} {f : α → β} :
map f (𝓟 s) = 𝓟 (set.image f s) :=
filter.ext $ λ a, image_subset_iff.symm
variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β}
@[simp] lemma eventually_map {P : β → Prop} :
(∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) :=
iff.rfl
@[simp] lemma frequently_map {P : β → Prop} :
(∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) :=
iff.rfl
@[simp] lemma mem_map : t ∈ map m f ↔ m ⁻¹' t ∈ f := iff.rfl
lemma mem_map' : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl
lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f :=
f.sets_of_superset hs $ subset_preimage_image m s
lemma image_mem_map_iff (hf : injective m) : m '' s ∈ map m f ↔ s ∈ f :=
⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩
lemma range_mem_map : range m ∈ map m f :=
by { rw ←image_univ, exact image_mem_map univ_mem }
lemma mem_map_iff_exists_image : t ∈ map m f ↔ (∃ s ∈ f, m '' s ⊆ t) :=
⟨λ ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩,
λ ⟨s, hs, ht⟩, mem_of_superset (image_mem_map hs) ht⟩
@[simp] lemma map_id : filter.map id f = f :=
filter_eq $ rfl
@[simp] lemma map_id' : filter.map (λ x, x) f = f := map_id
@[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) :=
funext $ λ _, filter_eq $ rfl
@[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f :=
congr_fun (@@filter.map_compose m m') f
/-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then
they map this filter to the same filter. -/
lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) :
map m₁ f = map m₂ f :=
filter.ext' $ λ p,
by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) }
end map
section comap
/-- The inverse map of a filter. A set `s` belongs to `filter.comap m f` if either of the following
equivalent conditions hold.
1. There exists a set `t ∈ f` such that `m ⁻¹' t ⊆ s`. This is used as a definition.
2. The set `{y | ∀ x, m x = y → x ∈ s}` belongs to `f`, see `filter.mem_comap'`.
3. The set `(m '' sᶜ)ᶜ` belongs to `f`, see `filter.mem_comap_iff_compl` and
`filter.compl_mem_comap`. -/
def comap (m : α → β) (f : filter β) : filter α :=
{ sets := { s | ∃ t ∈ f, m ⁻¹' t ⊆ s },
univ_sets := ⟨univ, univ_mem, by simp only [subset_univ, preimage_univ]⟩,
sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩,
inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩,
⟨a' ∩ b', inter_mem ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ }
variables {f : α → β} {l : filter β} {p : α → Prop} {s : set α}
lemma mem_comap' : s ∈ comap f l ↔ {y | ∀ ⦃x⦄, f x = y → x ∈ s} ∈ l :=
⟨λ ⟨t, ht, hts⟩, mem_of_superset ht $ λ y hy x hx, hts $ mem_preimage.2 $ by rwa hx,
λ h, ⟨_, h, λ x hx, hx rfl⟩⟩
/-- RHS form is used, e.g., in the definition of `uniform_space`. -/
lemma mem_comap_prod_mk {x : α} {s : set β} {F : filter (α × β)} :
s ∈ comap (prod.mk x) F ↔ {p : α × β | p.fst = x → p.snd ∈ s} ∈ F :=
by simp_rw [mem_comap', prod.ext_iff, and_imp, @forall_swap β (_ = _), forall_eq, eq_comm]
@[simp] lemma eventually_comap : (∀ᶠ a in comap f l, p a) ↔ ∀ᶠ b in l, ∀ a, f a = b → p a :=
mem_comap'
@[simp] lemma frequently_comap : (∃ᶠ a in comap f l, p a) ↔ ∃ᶠ b in l, ∃ a, f a = b ∧ p a :=
by simp only [filter.frequently, eventually_comap, not_exists, not_and]
lemma mem_comap_iff_compl : s ∈ comap f l ↔ (f '' sᶜ)ᶜ ∈ l :=
by simp only [mem_comap', compl_def, mem_image, mem_set_of_eq, not_exists, not_and', not_not]
lemma compl_mem_comap : sᶜ ∈ comap f l ↔ (f '' s)ᶜ ∈ l :=
by rw [mem_comap_iff_compl, compl_compl]
end comap
/-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`.
Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the
applicative instance. -/
def bind (f : filter α) (m : α → filter β) : filter β := join (map m f)
/-- The applicative sequentiation operation. This is not induced by the bind operation. -/
def seq (f : filter (α → β)) (g : filter α) : filter β :=
⟨{ s | ∃ u ∈ f, ∃ t ∈ g, (∀ m ∈ u, ∀ x ∈ t, (m : α → β) x ∈ s) },
⟨univ, univ_mem, univ, univ_mem,
by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩,
λ s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, λ x hx y hy, hst $ h _ hx _ hy⟩,
λ s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩,
⟨t₀ ∩ u₀, inter_mem ht₀ hu₀, t₁ ∩ u₁, inter_mem ht₁ hu₁,
λ x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩
/-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but
with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/
instance : has_pure filter :=
⟨λ (α : Type u) x,
{ sets := {s | x ∈ s},
inter_sets := λ s t, and.intro,
sets_of_superset := λ s t hs hst, hst hs,
univ_sets := trivial }⟩
instance : has_bind filter := ⟨@filter.bind⟩
instance : has_seq filter := ⟨@filter.seq⟩
instance : functor filter := { map := @filter.map }
lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl
@[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl
@[simp] lemma eventually_pure {a : α} {p : α → Prop} :
(∀ᶠ x in pure a, p x) ↔ p a :=
iff.rfl
@[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a :=
filter.ext $ λ s, by simp only [mem_pure, mem_principal, singleton_subset_iff]
@[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) :=
rfl
@[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl
@[simp] lemma pure_bind (a : α) (m : α → filter β) :
bind (pure a) m = m a :=
by simp only [has_bind.bind, bind, map_pure, join_pure]
section
-- this section needs to be before applicative, otherwise the wrong instance will be chosen
/-- The monad structure on filters. -/
protected def monad : monad filter := { map := @filter.map }
local attribute [instance] filter.monad
protected lemma is_lawful_monad : is_lawful_monad filter :=
{ id_map := λ α f, filter_eq rfl,
pure_bind := λ α β, pure_bind,
bind_assoc := λ α β γ f m₁ m₂, filter_eq rfl,
bind_pure_comp_eq_map := λ α β f x, filter.ext $ λ s,
by simp only [has_bind.bind, bind, functor.map, mem_map', mem_join, mem_set_of_eq,
comp, mem_pure] }
end
instance : applicative filter := { map := @filter.map, seq := @filter.seq }
instance : alternative filter :=
{ failure := λ α, ⊥,
orelse := λ α x y, x ⊔ y }
@[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl
@[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl
/-! #### `map` and `comap` equations -/
section map
variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β}
@[simp] theorem mem_comap : s ∈ comap m g ↔ ∃ t ∈ g, m ⁻¹' t ⊆ s := iff.rfl
theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g :=
⟨t, ht, subset.rfl⟩
lemma eventually.comap {p : β → Prop} (hf : ∀ᶠ b in g, p b) (f : α → β) :
∀ᶠ a in comap f g, p (f a) :=
preimage_mem_comap hf
lemma comap_id : comap id f = f :=
le_antisymm (λ s, preimage_mem_comap) (λ s ⟨t, ht, hst⟩, mem_of_superset ht hst)
lemma comap_id' : comap (λ x, x) f = f := comap_id
lemma comap_const_of_not_mem {x : β} (ht : t ∈ g) (hx : x ∉ t) :
comap (λ y : α, x) g = ⊥ :=
empty_mem_iff_bot.1 $ mem_comap'.2 $ mem_of_superset ht $ λ x' hx' y h, hx $ h.symm ▸ hx'
lemma comap_const_of_mem {x : β} (h : ∀ t ∈ g, x ∈ t) : comap (λ y : α, x) g = ⊤ :=
top_unique $ λ s hs, univ_mem' $ λ y, h _ (mem_comap'.1 hs) rfl
lemma map_const [ne_bot f] {c : β} : f.map (λ x, c) = pure c :=
by { ext s, by_cases h : c ∈ s; simp [h] }
lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f :=
filter.coext $ λ s, by simp only [compl_mem_comap, image_image]
section comm
/-!
The variables in the following lemmas are used as in this diagram:
```
φ
α → β
θ ↓ ↓ ψ
γ → δ
ρ
```
-/
variables {φ : α → β} {θ : α → γ} {ψ : β → δ} {ρ : γ → δ} (H : ψ ∘ φ = ρ ∘ θ)
include H
lemma map_comm (F : filter α) : map ψ (map φ F) = map ρ (map θ F) :=
by rw [filter.map_map, H, ← filter.map_map]
lemma comap_comm (G : filter δ) : comap φ (comap ψ G) = comap θ (comap ρ G) :=
by rw [filter.comap_comap, H, ← filter.comap_comap]
end comm
lemma _root_.function.semiconj.filter_map {f : α → β} {ga : α → α} {gb : β → β}
(h : function.semiconj f ga gb) : function.semiconj (map f) (map ga) (map gb) :=
map_comm h.comp_eq
lemma _root_.function.commute.filter_map {f g : α → α} (h : function.commute f g) :
function.commute (map f) (map g) :=
h.filter_map
lemma _root_.function.semiconj.filter_comap {f : α → β} {ga : α → α} {gb : β → β}
(h : function.semiconj f ga gb) : function.semiconj (comap f) (comap gb) (comap ga) :=
comap_comm h.comp_eq.symm
lemma _root_.function.commute.filter_comap {f g : α → α} (h : function.commute f g) :
function.commute (comap f) (comap g) :=
h.filter_comap
@[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) :=
filter.ext $ λ s,
⟨λ ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, (preimage_mono hu).trans b,
λ h, ⟨t, subset.refl t, h⟩⟩
@[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) :=
by rw [← principal_singleton, comap_principal]
lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g :=
⟨λ h s ⟨t, ht, hts⟩, mem_of_superset (h ht) hts, λ h s ht, h ⟨_, ht, subset.rfl⟩⟩
lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) :=
λ f g, map_le_iff_le_comap
@[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l
@[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u
@[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot
@[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup
@[simp] lemma map_supr {f : ι → filter α} : map m (⨆ i, f i) = (⨆ i, map m (f i)) :=
(gc_map_comap m).l_supr
@[simp] lemma map_top (f : α → β) : map f ⊤ = 𝓟 (range f) :=
by rw [← principal_univ, map_principal, image_univ]
@[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top
@[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf
@[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅ i, f i) = (⨅ i, comap m (f i)) :=
(gc_map_comap m).u_infi
lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ :=
by { rw [comap_top], exact le_top }
lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _
lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _
@[simp] lemma comap_bot : comap m ⊥ = ⊥ :=
bot_unique $ λ s _, ⟨∅, mem_bot, by simp only [empty_subset, preimage_empty]⟩
lemma ne_bot_of_comap (h : (comap m g).ne_bot) : g.ne_bot :=
begin
rw ne_bot_iff at *,
contrapose! h,
rw h,
exact comap_bot
end
lemma comap_inf_principal_range : comap m (g ⊓ 𝓟 (range m)) = comap m g := by simp
lemma disjoint_comap (h : disjoint g₁ g₂) : disjoint (comap m g₁) (comap m g₂) :=
by simp only [disjoint_iff, ← comap_inf, h.eq_bot, comap_bot]
lemma comap_supr {ι} {f : ι → filter β} {m : α → β} :
comap m (supr f) = (⨆ i, comap m (f i)) :=
le_antisymm
(λ s hs,
have ∀ i, ∃ t, t ∈ f i ∧ m ⁻¹' t ⊆ s,
by simpa only [mem_comap, exists_prop, mem_supr] using mem_supr.1 hs,
let ⟨t, ht⟩ := classical.axiom_of_choice this in
⟨⋃ i, t i, mem_supr.2 $ λ i, (f i).sets_of_superset (ht i).1 (subset_Union _ _),
begin
rw [preimage_Union, Union_subset_iff],
exact λ i, (ht i).2
end⟩)
(supr_le $ λ i, comap_mono $ le_supr _ _)
lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆ f ∈ s, comap m f) :=
by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true]
lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ :=
by rw [sup_eq_supr, comap_supr, supr_bool_eq, bool.cond_tt, bool.cond_ff]
lemma map_comap (f : filter β) (m : α → β) : (f.comap m).map m = f ⊓ 𝓟 (range m) :=
begin
refine le_antisymm (le_inf map_comap_le $ le_principal_iff.2 range_mem_map) _,
rintro t' ⟨t, ht, sub⟩,
refine mem_inf_principal.2 (mem_of_superset ht _),
rintro _ hxt ⟨x, rfl⟩,
exact sub hxt
end
lemma map_comap_of_mem {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f :=
by rw [map_comap, inf_eq_left.2 (le_principal_iff.2 hf)]
instance can_lift (c) (p) [can_lift α β c p] :
can_lift (filter α) (filter β) (map c) (λ f, ∀ᶠ x : α in f, p x) :=
{ prf := λ f hf, ⟨comap c f, map_comap_of_mem $ hf.mono can_lift.prf⟩ }
lemma comap_le_comap_iff {f g : filter β} {m : α → β} (hf : range m ∈ f) :
comap m f ≤ comap m g ↔ f ≤ g :=
⟨λ h, map_comap_of_mem hf ▸ (map_mono h).trans map_comap_le, λ h, comap_mono h⟩
theorem map_comap_of_surjective {f : α → β} (hf : surjective f) (l : filter β) :
map f (comap f l) = l :=
map_comap_of_mem $ by simp only [hf.range_eq, univ_mem]
lemma _root_.function.surjective.filter_map_top {f : α → β} (hf : surjective f) : map f ⊤ = ⊤ :=
(congr_arg _ comap_top).symm.trans $ map_comap_of_surjective hf ⊤
lemma subtype_coe_map_comap (s : set α) (f : filter α) :
map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s :=
by rw [map_comap, subtype.range_coe]
lemma image_mem_of_mem_comap {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β}
(W_in : W ∈ comap c f) : c '' W ∈ f :=
begin
rw ← map_comap_of_mem h,
exact image_mem_map W_in
end
lemma image_coe_mem_of_mem_comap {f : filter α} {U : set α} (h : U ∈ f) {W : set U}
(W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f :=
image_mem_of_mem_comap (by simp [h]) W_in
lemma comap_map {f : filter α} {m : α → β} (h : injective m) :
comap m (map m f) = f :=
le_antisymm
(λ s hs, mem_of_superset (preimage_mem_comap $ image_mem_map hs) $
by simp only [preimage_image_eq s h])
le_comap_map
lemma mem_comap_iff {f : filter β} {m : α → β} (inj : injective m)
(large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f :=
by rw [← image_mem_map_iff inj, map_comap_of_mem large]
lemma map_le_map_iff_of_inj_on {l₁ l₂ : filter α} {f : α → β} {s : set α}
(h₁ : s ∈ l₁) (h₂ : s ∈ l₂) (hinj : inj_on f s) :
map f l₁ ≤ map f l₂ ↔ l₁ ≤ l₂ :=
⟨λ h t ht, mp_mem h₁ $ mem_of_superset (h $ image_mem_map (inter_mem h₂ ht)) $
λ y ⟨x, ⟨hxs, hxt⟩, hxy⟩ hys, hinj hxs hys hxy ▸ hxt, λ h, map_mono h⟩
lemma map_le_map_iff {f g : filter α} {m : α → β} (hm : injective m) : map m f ≤ map m g ↔ f ≤ g :=
by rw [map_le_iff_le_comap, comap_map hm]
lemma map_eq_map_iff_of_inj_on {f g : filter α} {m : α → β} {s : set α}
(hsf : s ∈ f) (hsg : s ∈ g) (hm : inj_on m s) :
map m f = map m g ↔ f = g :=
by simp only [le_antisymm_iff, map_le_map_iff_of_inj_on hsf hsg hm,
map_le_map_iff_of_inj_on hsg hsf hm]
lemma map_inj {f g : filter α} {m : α → β} (hm : injective m) :
map m f = map m g ↔ f = g :=
map_eq_map_iff_of_inj_on univ_mem univ_mem (hm.inj_on _)
lemma map_injective {m : α → β} (hm : injective m) : injective (map m) :=
λ f g, (map_inj hm).1
lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t :=
begin
simp only [← forall_mem_nonempty_iff_ne_bot, mem_comap, forall_exists_index],
exact ⟨λ h t t_in, h (m ⁻¹' t) t t_in subset.rfl, λ h s t ht hst, (h t ht).imp hst⟩,
end
lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀ t ∈ f, ∃ a, m a ∈ t) : ne_bot (comap m f) :=
comap_ne_bot_iff.mpr hm
lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} :
ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m :=
by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm]
lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} :
ne_bot (comap m f) ↔ (range m)ᶜ ∉ f :=
comap_ne_bot_iff_frequently
lemma comap_eq_bot_iff_compl_range {f : filter β} {m : α → β} :
comap m f = ⊥ ↔ (range m)ᶜ ∈ f :=
not_iff_not.mp $ ne_bot_iff.symm.trans comap_ne_bot_iff_compl_range
lemma comap_surjective_eq_bot {f : filter β} {m : α → β} (hm : surjective m) :
comap m f = ⊥ ↔ f = ⊥ :=
by rw [comap_eq_bot_iff_compl_range, hm.range_eq, compl_univ, empty_mem_iff_bot]
lemma disjoint_comap_iff (h : surjective m) : disjoint (comap m g₁) (comap m g₂) ↔ disjoint g₁ g₂ :=
by rw [disjoint_iff, disjoint_iff, ← comap_inf, comap_surjective_eq_bot h]
lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β}
(hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) :=
comap_ne_bot_iff_frequently.2 $ eventually.frequently hm
@[simp] lemma comap_fst_ne_bot_iff {f : filter α} :
(f.comap (prod.fst : α × β → α)).ne_bot ↔ f.ne_bot ∧ nonempty β :=
begin
casesI is_empty_or_nonempty β,
{ rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [simp *, apply_instance] },
{ simp [comap_ne_bot_iff_frequently, h] }
end
@[instance] lemma comap_fst_ne_bot [nonempty β] {f : filter α} [ne_bot f] :
(f.comap (prod.fst : α × β → α)).ne_bot :=
comap_fst_ne_bot_iff.2 ⟨‹_›, ‹_›⟩
@[simp] lemma comap_snd_ne_bot_iff {f : filter β} :
(f.comap (prod.snd : α × β → β)).ne_bot ↔ nonempty α ∧ f.ne_bot :=
begin
casesI is_empty_or_nonempty α with hα hα,
{ rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not];
[simp, apply_instance] },
{ simp [comap_ne_bot_iff_frequently, hα] }
end
@[instance] lemma comap_snd_ne_bot [nonempty α] {f : filter β} [ne_bot f] :
(f.comap (prod.snd : α × β → β)).ne_bot :=
comap_snd_ne_bot_iff.2 ⟨‹_›, ‹_›⟩
lemma comap_eval_ne_bot_iff' {ι : Type*} {α : ι → Type*} {i : ι} {f : filter (α i)} :
(comap (eval i) f).ne_bot ↔ (∀ j, nonempty (α j)) ∧ ne_bot f :=
begin
casesI is_empty_or_nonempty (Π j, α j) with H H,
{ rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [skip, assumption],
simp [← classical.nonempty_pi] },
{ haveI : ∀ j, nonempty (α j), from classical.nonempty_pi.1 H,
simp [comap_ne_bot_iff_frequently, *] }
end
@[simp] lemma comap_eval_ne_bot_iff {ι : Type*} {α : ι → Type*} [∀ j, nonempty (α j)]
{i : ι} {f : filter (α i)} :
(comap (eval i) f).ne_bot ↔ ne_bot f :=
by simp [comap_eval_ne_bot_iff', *]
@[instance] lemma comap_eval_ne_bot {ι : Type*} {α : ι → Type*} [∀ j, nonempty (α j)]
(i : ι) (f : filter (α i)) [ne_bot f] :
(comap (eval i) f).ne_bot :=
comap_eval_ne_bot_iff.2 ‹_›
lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β}
(hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) :
ne_bot (comap m f ⊓ 𝓟 s) :=
begin
refine ⟨compl_compl s ▸ mt mem_of_eq_bot _⟩,
rintro ⟨t, ht, hts⟩,
rcases hf.nonempty_of_mem (inter_mem hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩,
exact absurd hxs (hts hxt)
end
lemma comap_coe_ne_bot_of_le_principal {s : set γ} {l : filter γ} [h : ne_bot l] (h' : l ≤ 𝓟 s) :
ne_bot (comap (coe : s → γ) l) :=
h.comap_of_range_mem $ (@subtype.range_coe γ s).symm ▸ h' (mem_principal_self s)
lemma ne_bot.comap_of_surj {f : filter β} {m : α → β}
(hf : ne_bot f) (hm : surjective m) :
ne_bot (comap m f) :=
hf.comap_of_range_mem $ univ_mem' hm
lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f)
{s : set α} (hs : m '' s ∈ f) :
ne_bot (comap m f) :=
hf.comap_of_range_mem $ mem_of_superset hs (image_subset_range _ _)
@[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ :=
⟨by { rw [←empty_mem_iff_bot, ←empty_mem_iff_bot], exact id },
λ h, by simp only [h, map_bot]⟩
lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F :=
by simp only [ne_bot_iff, ne, map_eq_bot_iff]
lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) :=
(map_ne_bot_iff m).2 hf
lemma ne_bot.of_map : ne_bot (f.map m) → ne_bot f := (map_ne_bot_iff m).1
instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m
lemma sInter_comap_sets (f : α → β) (F : filter β) :
⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U :=
begin
ext x,
suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔
∀ (B : set β), B ∈ F → f x ∈ B,
by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap, this, and_imp,
exists_prop, mem_preimage, exists_imp_distrib],
split,
{ intros h U U_in,
simpa only [subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in },
{ intros h V U U_in f_U_V,
exact f_U_V (h U U_in) },
end
end map
-- this is a generic rule for monotone functions:
lemma map_infi_le {f : ι → filter α} {m : α → β} :
map m (infi f) ≤ (⨅ i, map m (f i)) :=
le_infi $ λ i, map_mono $ infi_le _ _
lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] :
map m (infi f) = (⨅ i, map m (f i)) :=
map_infi_le.antisymm
(λ s (hs : preimage m s ∈ infi f),
let ⟨i, hi⟩ := (mem_infi_of_directed hf _).1 hs in
have (⨅ i, map m (f i)) ≤ 𝓟 s, from
infi_le_of_le i $ by { simp only [le_principal_iff, mem_map], assumption },
filter.le_principal_iff.1 this)
lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop}
(h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃ i, p i) :
map m (⨅ i (h : p i), f i) = (⨅ i (h : p i), map m (f i)) :=
begin
haveI := nonempty_subtype.2 ne,
simp only [infi_subtype'],
exact map_infi_eq h.directed_coe
end
lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g :=
(@map_mono _ _ m).map_inf_le f g
lemma map_inf {f g : filter α} {m : α → β} (h : injective m) :
map m (f ⊓ g) = map m f ⊓ map m g :=
begin
refine map_inf_le.antisymm _,
rintro t ⟨s₁, hs₁, s₂, hs₂, ht : m ⁻¹' t = s₁ ∩ s₂⟩,
refine mem_inf_of_inter (image_mem_map hs₁) (image_mem_map hs₂) _,
rw [←image_inter h, image_subset_iff, ht]
end
lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g)
(h : inj_on m t) : map m (f ⊓ g) = map m f ⊓ map m g :=
begin
lift f to filter t using htf, lift g to filter t using htg,
replace h : injective (m ∘ coe) := h.injective,
simp only [map_map, ← map_inf subtype.coe_injective, map_inf h],
end
lemma disjoint_map {m : α → β} (hm : injective m) {f₁ f₂ : filter α} :
disjoint (map m f₁) (map m f₂) ↔ disjoint f₁ f₂ :=
by simp only [disjoint_iff, ← map_inf hm, map_eq_bot_iff]
lemma map_equiv_symm (e : α ≃ β) (f : filter β) :
map e.symm f = comap e f :=
map_injective e.injective $ by rw [map_map, e.self_comp_symm, map_id,
map_comap_of_surjective e.surjective]
lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α}
(h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f :=
map_equiv_symm ⟨n, m, congr_fun h₁, congr_fun h₂⟩ f
lemma comap_equiv_symm (e : α ≃ β) (f : filter α) :
comap e.symm f = map e f :=
(map_eq_comap_of_inverse e.self_comp_symm e.symm_comp_self).symm
lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f :=
map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq
/-- A useful lemma when dealing with uniformities. -/
lemma map_swap4_eq_comap {f : filter ((α × β) × (γ × δ))} :
map (λ p : (α × β) × (γ × δ), ((p.1.1, p.2.1), (p.1.2, p.2.2))) f =
comap (λ p : (α × γ) × (β × δ), ((p.1.1, p.2.1), (p.1.2, p.2.2))) f :=
map_eq_comap_of_inverse (funext $ λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl)
lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀ s ∈ f, m '' s ∈ g) :
g ≤ f.map m :=
λ s hs, mem_of_superset (h _ hs) $ image_preimage_subset _ _
lemma le_map_iff {f : filter α} {m : α → β} {g : filter β} : g ≤ f.map m ↔ ∀ s ∈ f, m '' s ∈ g :=
⟨λ h s hs, h (image_mem_map hs), le_map⟩
protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) :
map f (F ⊓ comap f G) = map f F ⊓ G :=
begin
apply le_antisymm,
{ calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le
... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le },
{ rintro U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩,
apply mem_inf_of_inter (image_mem_map V_in) Z_in,
calc
f '' V ∩ Z = f '' (V ∩ f ⁻¹' Z) : by rw image_inter_preimage
... ⊆ f '' (V ∩ W) : image_subset _ (inter_subset_inter_right _ ‹_›)
... = f '' (f ⁻¹' U) : by rw h
... ⊆ U : image_preimage_subset f U }
end
protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) :
map f (comap f G ⊓ F) = G ⊓ map f F :=
by simp only [filter.push_pull, inf_comm]
lemma principal_eq_map_coe_top (s : set α) : 𝓟 s = map (coe : s → α) ⊤ :=
by simp
lemma inf_principal_eq_bot_iff_comap {F : filter α} {s : set α} :
F ⊓ 𝓟 s = ⊥ ↔ comap (coe : s → α) F = ⊥ :=
by rw [principal_eq_map_coe_top s, ← filter.push_pull',inf_top_eq, map_eq_bot_iff]
section applicative
lemma singleton_mem_pure {a : α} : {a} ∈ (pure a : filter α) :=
mem_singleton a
lemma pure_injective : injective (pure : α → filter α) :=
λ a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl
instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) :=
⟨mt empty_mem_iff_bot.2 $ not_mem_empty a⟩
@[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f :=
by rw [← principal_singleton, le_principal_iff]
lemma mem_seq_def {f : filter (α → β)} {g : filter α} {s : set β} :
s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, ∀ x ∈ u, ∀ y ∈ t, (x : α → β) y ∈ s) :=
iff.rfl
lemma mem_seq_iff {f : filter (α → β)} {g : filter α} {s : set β} :
s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, set.seq u t ⊆ s) :=
by simp only [mem_seq_def, seq_subset, exists_prop, iff_self]
lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} :
s ∈ (f.map m).seq g ↔ (∃ t u, t ∈ g ∧ u ∈ f ∧ ∀ x ∈ u, ∀ y ∈ t, m x y ∈ s) :=
iff.intro
(λ ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, λ a, hts _⟩)
(λ ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, λ f ⟨a, has, eq⟩, eq ▸ hts _ has⟩)
lemma seq_mem_seq {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α}
(hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g :=
⟨s, hs, t, ht, λ f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩
lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β}
(hh : ∀ t ∈ f, ∀ u ∈ g, set.seq t u ∈ h) : h ≤ seq f g :=
λ s ⟨t, ht, u, hu, hs⟩, mem_of_superset (hh _ ht _ hu) $
λ b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha
@[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α}
(hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ :=
le_seq $ λ s hs t ht, seq_mem_seq (hf hs) (hg ht)
@[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g :=
begin
refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _),
{ rw ← singleton_seq, apply seq_mem_seq _ hs,
exact singleton_mem_pure },
{ refine sets_of_superset (map g f) (image_mem_map ht) _,
rintro b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ }
end
@[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λ g : α → β, g a) f :=
begin
refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _),
{ rw ← seq_singleton,
exact seq_mem_seq hs singleton_mem_pure },
{ refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _,
rintro b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ }
end
@[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) :
seq h (seq g x) = seq (seq (map (∘) h) g) x :=
begin
refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _),
{ rcases mem_seq_iff.1 hs with ⟨u, hu, v, hv, hs⟩,
rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hu⟩,
refine mem_of_superset _
(set.seq_mono ((set.seq_mono hu subset.rfl).trans hs) subset.rfl),
rw ← set.seq_seq,
exact seq_mem_seq hw (seq_mem_seq hv ht) },
{ rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩,
refine mem_of_superset _ (set.seq_mono subset.rfl ht),
rw set.seq_seq,
exact seq_mem_seq (seq_mem_seq (image_mem_map hs) hu) hv }
end
lemma prod_map_seq_comm (f : filter α) (g : filter β) :
(map prod.mk f).seq g = seq (map (λ b a, (a, b)) g) f :=
begin
refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _),
{ rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩,
refine mem_of_superset _ (set.seq_mono hs subset.rfl),
rw ← set.prod_image_seq_comm,
exact seq_mem_seq (image_mem_map ht) hu },
{ rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩,
refine mem_of_superset _ (set.seq_mono hs subset.rfl),
rw set.prod_image_seq_comm,
exact seq_mem_seq (image_mem_map ht) hu }
end
instance : is_lawful_functor (filter : Type u → Type u) :=
{ id_map := λ α f, map_id,
comp_map := λ α β γ f g a, map_map.symm }
instance : is_lawful_applicative (filter : Type u → Type u) :=
{ pure_seq_eq_map := λ α β, pure_seq_eq_map,
map_pure := λ α β, map_pure,
seq_pure := λ α β, seq_pure,
seq_assoc := λ α β γ, seq_assoc }
instance : is_comm_applicative (filter : Type u → Type u) :=
⟨λ α β f g, prod_map_seq_comm f g⟩
lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) :
f <*> g = seq f g := rfl
end applicative
/-! #### `bind` equations -/
section bind
@[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} :
(∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y :=
iff.rfl
@[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} :
(g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ :=
iff.rfl
@[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} :
(g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ :=
iff.rfl
lemma mem_bind' {s : set β} {f : filter α} {m : α → filter β} :
s ∈ bind f m ↔ {a | s ∈ m a} ∈ f :=
iff.rfl
@[simp] lemma mem_bind {s : set β} {f : filter α} {m : α → filter β} :
s ∈ bind f m ↔ ∃ t ∈ f, ∀ x ∈ t, s ∈ m x :=
calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl
... ↔ (∃ t ∈ f, t ⊆ {a | s ∈ m a}) : exists_mem_subset_iff.symm
... ↔ (∃ t ∈ f, ∀ x ∈ t, s ∈ m x) : iff.rfl
lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) :
f.bind g ≤ l :=
join_le $ eventually_map.2 h
@[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂)
(hg : g₁ ≤ᶠ[f₁] g₂) :
bind f₁ g₁ ≤ bind f₂ g₂ :=
begin
refine le_trans (λ s hs, _) (join_mono $ map_mono hf),
simp only [mem_join, mem_bind', mem_map] at hs ⊢,
filter_upwards [hg, hs] with _ hx hs using hx hs,
end
lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} :
f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s :=
filter.ext $ λ s, by simp only [mem_bind, mem_inf_principal]
lemma sup_bind {f g : filter α} {h : α → filter β} :
bind (f ⊔ g) h = bind f h ⊔ bind g h :=
by simp only [bind, sup_join, map_sup, eq_self_iff_true]
lemma principal_bind {s : set α} {f : α → filter β} :
(bind (𝓟 s) f) = (⨆ x ∈ s, f x) :=
show join (map f (𝓟 s)) = (⨆ x ∈ s, f x),
by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true]
end bind
section list_traverse
/- This is a separate section in order to open `list`, but mostly because of universe
equality requirements in `traverse` -/
open list
lemma sequence_mono :
∀ (as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs
| [] [] forall₂.nil := le_rfl
| (a :: as) (b :: bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs)
variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'}
lemma mem_traverse :
∀ (fs : list β') (us : list γ'),
forall₂ (λ b c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs
| [] [] forall₂.nil := mem_pure.2 $ mem_singleton _
| (f :: fs) (u :: us) (forall₂.cons h hs) := seq_mem_seq (image_mem_map h) (mem_traverse fs us hs)
lemma mem_traverse_iff (fs : list β') (t : set (list α')) :
t ∈ traverse f fs ↔
(∃ us : list (set α'), forall₂ (λ b (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) :=
begin
split,
{ induction fs generalizing t,
case nil { simp only [sequence, mem_pure, imp_self, forall₂_nil_left_iff,
exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] },
case cons : b fs ih t
{ intro ht,
rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩,
rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hwu⟩,
rcases ih v hv with ⟨us, hus, hu⟩,
exact ⟨w :: us, forall₂.cons hw hus, (set.seq_mono hwu hu).trans ht⟩ } },
{ rintro ⟨us, hus, hs⟩,
exact mem_of_superset (mem_traverse _ _ hus) hs }
end
end list_traverse
/-! ### Limits -/
/-- `tendsto` is the generic "limit of a function" predicate.
`tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`,
the `f`-preimage of `a` is an `l₁` neighborhood. -/
@[pp_nodot] def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂
lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} :
tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl
lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} :
tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) :=
iff.rfl
lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop}
(hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) :
∀ᶠ x in l₁, p (f x) :=
hf h
lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop}
(hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) :
∃ᶠ y in l₂, p y :=
mt hf.eventually h
lemma tendsto.frequently_map {l₁ : filter α} {l₂ : filter β} {p : α → Prop} {q : β → Prop}
(f : α → β) (c : filter.tendsto f l₁ l₂) (w : ∀ x, p x → q (f x)) (h : ∃ᶠ x in l₁, p x) :
∃ᶠ y in l₂, q y :=
c.frequently (h.mono w)
@[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto]
@[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top
lemma le_map_of_right_inverse {mab : α → β} {mba : β → α} {f : filter α} {g : filter β}
(h₁ : mab ∘ mba =ᶠ[g] id) (h₂ : tendsto mba g f) :
g ≤ map mab f :=
by { rw [← @map_id _ g, ← map_congr h₁, ← map_map], exact map_mono h₂ }
lemma tendsto_of_is_empty [is_empty α] {f : α → β} {la : filter α} {lb : filter β} :
tendsto f la lb :=
by simp only [filter_eq_bot_of_is_empty la, tendsto_bot]
lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α}
{fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y)
(htendsto : tendsto g₂ fb fa) :
g₁ =ᶠ[fb] g₂ :=
(htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl
lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} :
tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f :=
map_le_iff_le_comap
alias tendsto_iff_comap ↔ tendsto.le_comap _
protected lemma tendsto.disjoint {f : α → β} {la₁ la₂ : filter α} {lb₁ lb₂ : filter β}
(h₁ : tendsto f la₁ lb₁) (hd : disjoint lb₁ lb₂) (h₂ : tendsto f la₂ lb₂) :
disjoint la₁ la₂ :=
(disjoint_comap hd).mono h₁.le_comap h₂.le_comap
lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) :
tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ :=
by rw [tendsto, tendsto, map_congr hl]
lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ :=
(tendsto_congr' hl).1 h
theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ :=
tendsto_congr' (univ_mem' h)
theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β}
(h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ :=
(tendsto_congr h).1
lemma tendsto_id' {x y : filter α} : tendsto id x y ↔ x ≤ y := iff.rfl
lemma tendsto_id {x : filter α} : tendsto id x x := le_refl x
lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ}
(hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z :=
λ s hs, hf (hg hs)
lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β}
(hx : tendsto f x z) (h : y ≤ x) : tendsto f y z :=
(map_mono h).trans hx
lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β}
(hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z :=
le_trans hy hz
lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] :
ne_bot y :=
(hx.map _).mono h
lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x)
lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ}
(h : tendsto (f ∘ g) x y) : tendsto f (map g x) y :=
by rwa [tendsto, map_map]
@[simp] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} :
tendsto f (map g x) y ↔ tendsto (f ∘ g) x y :=
by { rw [tendsto, map_map], refl }
lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x :=
map_comap_le
@[simp] lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} :
tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c :=
⟨λ h, tendsto_comap.comp h, λ h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩
lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α}
(h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g :=
by { rw [tendsto, ← map_compose], simp only [(∘), map_comap_of_mem h, tendsto] }
lemma tendsto.of_tendsto_comp {f : α → β} {g : β → γ} {a : filter α} {b : filter β} {c : filter γ}
(hfg : tendsto (g ∘ f) a c) (hg : comap g c ≤ b) :
tendsto f a b :=
begin
rw tendsto_iff_comap at hfg ⊢,
calc a ≤ comap (g ∘ f) c : hfg
... ≤ comap f b : by simpa [comap_comap] using comap_mono hg
end
lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α)
(eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f :=
begin
refine ((comap_mono $ map_le_iff_le_comap.1 hψ).trans _).antisymm (map_le_iff_le_comap.1 hφ),
rw [comap_comap, eq, comap_id],
exact le_rfl
end
lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α)
(eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g :=
begin
refine le_antisymm hφ (le_trans _ (map_mono hψ)),
rw [map_map, eq, map_id],
exact le_rfl
end
lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} :
tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ :=
by simp only [tendsto, le_inf_iff, iff_self]
lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β}
(h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y :=
le_trans (map_mono inf_le_left) h
lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β}
(h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y :=
le_trans (map_mono inf_le_right) h
lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β}
(h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) :=
tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩
@[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} :
tendsto f x (⨅ i, y i) ↔ ∀ i, tendsto f x (y i) :=
by simp only [tendsto, iff_self, le_infi_iff]
lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) :
tendsto f (⨅ i, x i) y :=
hi.mono_left $ infi_le _ _
theorem tendsto_infi_infi {f : α → β} {x : ι → filter α} {y : ι → filter β}
(h : ∀ i, tendsto f (x i) (y i)) : tendsto f (infi x) (infi y) :=
tendsto_infi.2 $ λ i, tendsto_infi' i (h i)
@[simp] lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} :
tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y :=
by simp only [tendsto, map_sup, sup_le_iff]
lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} :
tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y :=
λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩
@[simp] lemma tendsto_supr {f : α → β} {x : ι → filter α} {y : filter β} :
tendsto f (⨆ i, x i) y ↔ ∀ i, tendsto f (x i) y :=
by simp only [tendsto, map_supr, supr_le_iff]
theorem tendsto_supr_supr {f : α → β} {x : ι → filter α} {y : ι → filter β}
(h : ∀ i, tendsto f (x i) (y i)) : tendsto f (supr x) (supr y) :=
tendsto_supr.2 $ λ i, (h i).mono_right $ le_supr _ _
@[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} :
tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s :=
by simp only [tendsto, le_principal_iff, mem_map', filter.eventually]
@[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} :
tendsto f (𝓟 s) (𝓟 t) ↔ ∀ a ∈ s, f a ∈ t :=
by simp only [tendsto_principal, eventually_principal]
@[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} :
tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b :=
by simp only [tendsto, le_pure_iff, mem_map', mem_singleton_iff, filter.eventually]
lemma tendsto_pure_pure (f : α → β) (a : α) :
tendsto f (pure a) (pure (f a)) :=
tendsto_pure.2 rfl
lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λ x, b) a (pure b) :=
tendsto_pure.2 $ univ_mem' $ λ _, rfl
lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s :=
iff.rfl
lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} :
tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s :=
iff.rfl
@[simp] lemma map_inf_principal_preimage {f : α → β} {s : set β} {l : filter α} :
map f (l ⊓ 𝓟 (f ⁻¹' s)) = map f l ⊓ 𝓟 s :=
filter.ext $ λ t, by simp only [mem_map', mem_inf_principal, mem_set_of_eq, mem_preimage]
/-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial
filter. -/
lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁)
[ne_bot a] (hb : disjoint b₁ b₂) :
¬ tendsto f a b₂ :=
λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot.ne hb.eq_bot
protected lemma tendsto.if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop}
[∀ x, decidable (p x)] (h₀ : tendsto f (l₁ ⊓ 𝓟 {x | p x}) l₂)
(h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) :
tendsto (λ x, if p x then f x else g x) l₁ l₂ :=
begin
simp only [tendsto_def, mem_inf_principal] at *,
intros s hs,
filter_upwards [h₀ s hs, h₁ s hs],
simp only [mem_preimage],
intros x hp₀ hp₁,
split_ifs,
exacts [hp₀ h, hp₁ h],
end
protected lemma tendsto.if' {α β : Type*} {l₁ : filter α} {l₂ : filter β} {f g : α → β}
{p : α → Prop} [decidable_pred p] (hf : tendsto f l₁ l₂) (hg : tendsto g l₁ l₂) :
tendsto (λ a, if p a then f a else g a) l₁ l₂ :=
begin
replace hf : tendsto f (l₁ ⊓ 𝓟 {x | p x}) l₂ := tendsto_inf_left hf,
replace hg : tendsto g (l₁ ⊓ 𝓟 {x | ¬ p x}) l₂ := tendsto_inf_left hg,
exact hf.if hg,
end
protected lemma tendsto.piecewise {l₁ : filter α} {l₂ : filter β} {f g : α → β}
{s : set α} [∀ x, decidable (x ∈ s)]
(h₀ : tendsto f (l₁ ⊓ 𝓟 s) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 sᶜ) l₂) :
tendsto (piecewise s f g) l₁ l₂ :=
h₀.if h₁
end filter
open_locale filter
lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) :
f =ᶠ[𝓟 s] g :=
h
lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β}
(h : eq_on f g s) (hl : s ∈ l) :
f =ᶠ[l] g :=
h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl
lemma has_subset.subset.eventually_le {α} {l : filter α} {s t : set α} (h : s ⊆ t) : s ≤ᶠ[l] t :=
filter.eventually_of_forall h
lemma set.maps_to.tendsto {α β} {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) :
filter.tendsto f (𝓟 s) (𝓟 t) :=
filter.tendsto_principal_principal.2 h
|
2b0498c8ee126245bf059303203cd8e8055dd68e | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/data/fintype/function.lean | 75de6c50ebdb97b18b244251ea77becd2b82355c | [
"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 | 18,689 | lean | /-
Copyright (c) 2015 Haitao Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author : Haitao Zhang
-/
import data
open nat function eq.ops
namespace list
-- this is in preparation for counting the number of finite functions
section list_of_lists
open prod
variable {A : Type}
definition cons_pair (pr : A × list A) := (pr1 pr) :: (pr2 pr)
definition cons_all_of (elts : list A) (ls : list (list A)) : list (list A) :=
map cons_pair (product elts ls)
lemma pair_of_cons {a} {l} {pr : A × list A} : cons_pair pr = a::l → pr = (a, l) :=
prod.destruct pr (λ p1 p2, assume Peq, list.no_confusion Peq (by intros; substvars))
lemma cons_pair_inj : injective (@cons_pair A) :=
take p1 p2, assume Pl,
prod.eq (list.no_confusion Pl (λ P1 P2, P1)) (list.no_confusion Pl (λ P1 P2, P2))
lemma nodup_of_cons_all {elts : list A} {ls : list (list A)}
: nodup elts → nodup ls → nodup (cons_all_of elts ls) :=
assume Pelts Pls,
nodup_map cons_pair_inj (nodup_product Pelts Pls)
lemma length_cons_all {elts : list A} {ls : list (list A)} :
length (cons_all_of elts ls) = length elts * length ls := calc
length (cons_all_of elts ls) = length (product elts ls) : length_map
... = length elts * length ls : length_product
variable [finA : fintype A]
include finA
definition all_lists_of_len : ∀ (n : nat), list (list A)
| 0 := [[]]
| (succ n) := cons_all_of (elements_of A) (all_lists_of_len n)
definition all_nodups_of_len [deceqA : decidable_eq A] (n : nat) : list (list A) :=
filter nodup (all_lists_of_len n)
lemma nodup_all_lists : ∀ {n : nat}, nodup (@all_lists_of_len A _ n)
| 0 := nodup_singleton []
| (succ n) := nodup_of_cons_all (fintype.unique A) nodup_all_lists
lemma nodup_all_nodups [deceqA : decidable_eq A] {n : nat} :
nodup (@all_nodups_of_len A _ _ n) :=
nodup_filter nodup nodup_all_lists
lemma mem_all_lists : ∀ {n : nat} {l : list A}, length l = n → l ∈ all_lists_of_len n
| 0 [] := assume P, mem_cons [] []
| 0 (a::l) := assume Peq, by contradiction
| (succ n) [] := assume Peq, by contradiction
| (succ n) (a::l) := assume Peq, begin
apply mem_map, apply mem_product,
exact fintype.complete a,
exact mem_all_lists (succ.inj Peq)
end
lemma mem_all_nodups [deceqA : decidable_eq A] (n : nat) (l : list A) :
length l = n → nodup l → l ∈ all_nodups_of_len n :=
assume Pl Pn, mem_filter_of_mem (mem_all_lists Pl) Pn
lemma nodup_mem_all_nodups [deceqA : decidable_eq A] {n : nat} ⦃l : list A⦄ :
l ∈ all_nodups_of_len n → nodup l :=
assume Pl, of_mem_filter Pl
lemma length_mem_all_lists : ∀ {n : nat} ⦃l : list A⦄,
l ∈ all_lists_of_len n → length l = n
| 0 [] := assume P, rfl
| 0 (a::l) := assume Pin, have Peq : (a::l) = [], from mem_singleton Pin,
by contradiction
| (succ n) [] := assume Pin, obtain pr Pprin Ppr, from exists_of_mem_map Pin,
by contradiction
| (succ n) (a::l) := assume Pin, obtain pr Pprin Ppr, from exists_of_mem_map Pin,
have Pl : l ∈ all_lists_of_len n,
from mem_of_mem_product_right ((pair_of_cons Ppr) ▸ Pprin),
by rewrite [length_cons, length_mem_all_lists Pl]
lemma length_mem_all_nodups [deceqA : decidable_eq A] {n : nat} ⦃l : list A⦄ :
l ∈ all_nodups_of_len n → length l = n :=
assume Pl, length_mem_all_lists (mem_of_mem_filter Pl)
open fintype
lemma length_all_lists : ∀ {n : nat}, length (@all_lists_of_len A _ n) = (card A) ^ n
| 0 := calc length [[]] = 1 : length_cons
| (succ n) := calc length _ = card A * length (all_lists_of_len n) : length_cons_all
... = card A * (card A ^ n) : length_all_lists
... = (card A ^ n) * card A : mul.comm
... = (card A) ^ (succ n) : pow_succ'
end list_of_lists
section kth
variable {A : Type}
definition kth : ∀ k (l : list A), k < length l → A
| k [] := begin rewrite length_nil, intro Pltz, exact absurd Pltz !not_lt_zero end
| 0 (a::l) := λ P, a
| (k+1) (a::l):= by rewrite length_cons; intro Plt; exact kth k l (lt_of_succ_lt_succ Plt)
lemma kth_zero_of_cons {a} (l : list A) (P : 0 < length (a::l)) : kth 0 (a::l) P = a :=
rfl
lemma kth_succ_of_cons {a} k (l : list A) (P : k+1 < length (a::l)) :
kth (succ k) (a::l) P = kth k l (lt_of_succ_lt_succ P) :=
rfl
lemma kth_mem : ∀ {k : nat} {l : list A} P, kth k l P ∈ l
| k [] := assume P, absurd P !not_lt_zero
| 0 (a::l) := assume P, by rewrite kth_zero_of_cons; apply mem_cons
| (succ k) (a::l) := assume P, by
rewrite [kth_succ_of_cons]; apply mem_cons_of_mem a; apply kth_mem
-- Leo provided the following proof.
lemma eq_of_kth_eq [deceqA : decidable_eq A]
: ∀ {l1 l2 : list A} (Pleq : length l1 = length l2),
(∀ (k : nat) (Plt1 : k < length l1) (Plt2 : k < length l2), kth k l1 Plt1 = kth k l2 Plt2) → l1 = l2
| [] [] h₁ h₂ := rfl
| (a₁::l₁) [] h₁ h₂ := by contradiction
| [] (a₂::l₂) h₁ h₂ := by contradiction
| (a₁::l₁) (a₂::l₂) h₁ h₂ :=
have ih₁ : length l₁ = length l₂, by injection h₁; eassumption,
have ih₂ : ∀ (k : nat) (plt₁ : k < length l₁) (plt₂ : k < length l₂), kth k l₁ plt₁ = kth k l₂ plt₂,
begin
intro k plt₁ plt₂,
have splt₁ : succ k < length l₁ + 1, from succ_le_succ plt₁,
have splt₂ : succ k < length l₂ + 1, from succ_le_succ plt₂,
have keq : kth (succ k) (a₁::l₁) splt₁ = kth (succ k) (a₂::l₂) splt₂, from h₂ (succ k) splt₁ splt₂,
rewrite *kth_succ_of_cons at keq,
exact keq
end,
have ih : l₁ = l₂, from eq_of_kth_eq ih₁ ih₂,
have k₁ : a₁ = a₂,
begin
have lt₁ : 0 < length (a₁::l₁), from !zero_lt_succ,
have lt₂ : 0 < length (a₂::l₂), from !zero_lt_succ,
have e₁ : kth 0 (a₁::l₁) lt₁ = kth 0 (a₂::l₂) lt₂, from h₂ 0 lt₁ lt₂,
rewrite *kth_zero_of_cons at e₁,
assumption
end,
by subst l₁; subst a₁
lemma kth_of_map {B : Type} {f : A → B} :
∀ {k : nat} {l : list A} Plt Pmlt, kth k (map f l) Pmlt = f (kth k l Plt)
| k [] := assume P, absurd P !not_lt_zero
| 0 (a::l) := assume Plt, by
rewrite [map_cons]; intro Pmlt; rewrite [kth_zero_of_cons]
| (succ k) (a::l) := assume P, begin
rewrite [map_cons], intro Pmlt, rewrite [*kth_succ_of_cons],
apply kth_of_map
end
lemma kth_find [deceqA : decidable_eq A] :
∀ {l : list A} {a} P, kth (find a l) l P = a
| [] := take a, assume P, absurd P !not_lt_zero
| (x::l) := take a, begin
have Pd : decidable (a = x), begin apply deceqA end,
cases Pd with Pe Pne,
rewrite [find_cons_of_eq l Pe], intro P, rewrite [kth_zero_of_cons, Pe],
rewrite [find_cons_of_ne l Pne], intro P, rewrite [kth_succ_of_cons],
apply kth_find
end
lemma find_kth [deceqA : decidable_eq A] :
∀ {k : nat} {l : list A} P, find (kth k l P) l < length l
| k [] := assume P, absurd P !not_lt_zero
| 0 (a::l) := assume P, begin
rewrite [kth_zero_of_cons, find_cons_of_eq l rfl, length_cons],
exact !zero_lt_succ
end
| (succ k) (a::l) := assume P, begin
rewrite [kth_succ_of_cons],
have Pd : decidable ((kth k l (lt_of_succ_lt_succ P)) = a),
begin apply deceqA end,
cases Pd with Pe Pne,
rewrite [find_cons_of_eq l Pe], apply zero_lt_succ,
rewrite [find_cons_of_ne l Pne], apply succ_lt_succ, apply find_kth
end
lemma find_kth_of_nodup [deceqA : decidable_eq A] :
∀ {k : nat} {l : list A} P, nodup l → find (kth k l P) l = k
| k [] := assume P, absurd P !not_lt_zero
| 0 (a::l) := assume Plt Pnodup,
by rewrite [kth_zero_of_cons, find_cons_of_eq l rfl]
| (succ k) (a::l) := assume Plt Pnodup, begin
rewrite [kth_succ_of_cons],
have Pd : decidable ((kth k l (lt_of_succ_lt_succ Plt)) = a),
begin apply deceqA end,
cases Pd with Pe Pne,
have Pin : a ∈ l, begin rewrite -Pe, apply kth_mem end,
exact absurd Pin (not_mem_of_nodup_cons Pnodup),
rewrite [find_cons_of_ne l Pne], apply congr (eq.refl succ),
apply find_kth_of_nodup (lt_of_succ_lt_succ Plt) (nodup_of_nodup_cons Pnodup)
end
end kth
end list
namespace fintype
open list
section found
variables {A B : Type}
variable [finA : fintype A]
include finA
lemma find_in_range [deceqB : decidable_eq B] {f : A → B} (b : B) :
∀ (l : list A) P, f (kth (find b (map f l)) l P) = b
| [] := assume P, begin exact absurd P !not_lt_zero end
| (a::l) := decidable.rec_on (deceqB b (f a))
(assume Peq, begin
rewrite [map_cons f a l, find_cons_of_eq _ Peq],
intro P, rewrite [kth_zero_of_cons], exact (Peq⁻¹)
end)
(assume Pne, begin
rewrite [map_cons f a l, find_cons_of_ne _ Pne],
intro P,
rewrite [kth_succ_of_cons (find b (map f l)) l P],
exact find_in_range l (lt_of_succ_lt_succ P)
end)
end found
section list_to_fun
variables {A B : Type}
variable [finA : fintype A]
include finA
definition fun_to_list (f : A → B) : list B := map f (elems A)
lemma length_map_of_fintype (f : A → B) : length (map f (elems A)) = card A :=
by apply length_map
variable [deceqA : decidable_eq A]
include deceqA
lemma fintype_find (a : A) : find a (elems A) < card A :=
find_lt_length (complete a)
definition list_to_fun (l : list B) (leq : length l = card A) : A → B :=
take x,
kth _ _ (leq⁻¹ ▸ fintype_find x)
definition all_funs [finB : fintype B] : list (A → B) :=
dmap (λ l, length l = card A) list_to_fun (all_lists_of_len (card A))
lemma list_to_fun_apply (l : list B) (leq : length l = card A) (a : A) :
∀ P, list_to_fun l leq a = kth (find a (elems A)) l P :=
assume P, rfl
variable [deceqB : decidable_eq B]
include deceqB
lemma fun_eq_list_to_fun_map (f : A → B) : ∀ P, f = list_to_fun (map f (elems A)) P :=
assume Pleq, funext (take a,
have Plt : _, from Pleq⁻¹ ▸ find_lt_length (complete a), begin
rewrite [list_to_fun_apply _ Pleq a (Pleq⁻¹ ▸ find_lt_length (complete a))],
have Pmlt : find a (elems A) < length (map f (elems A)),
begin rewrite length_map, exact Plt end,
rewrite [@kth_of_map A B f (find a (elems A)) (elems A) Plt _, kth_find]
end)
lemma list_eq_map_list_to_fun (l : list B) (leq : length l = card A)
: l = map (list_to_fun l leq) (elems A) :=
begin
apply eq_of_kth_eq, rewrite length_map, apply leq,
intro k Plt Plt2,
have Plt1 : k < length (elems A), begin apply leq ▸ Plt end,
have Plt3 : find (kth k (elems A) Plt1) (elems A) < length l,
begin rewrite leq, apply find_kth end,
rewrite [kth_of_map Plt1 Plt2, list_to_fun_apply l leq _ Plt3],
congruence,
rewrite [find_kth_of_nodup Plt1 (unique A)]
end
lemma fun_to_list_to_fun (f : A → B) : ∀ P, list_to_fun (fun_to_list f) P = f :=
assume P, (fun_eq_list_to_fun_map f P)⁻¹
lemma list_to_fun_to_list (l : list B) (leq : length l = card A) :
fun_to_list (list_to_fun l leq) = l
:= (list_eq_map_list_to_fun l leq)⁻¹
lemma dinj_list_to_fun : dinj (λ (l : list B), length l = card A) list_to_fun :=
take l1 l2 Pl1 Pl2 Peq,
by rewrite [list_eq_map_list_to_fun l1 Pl1, list_eq_map_list_to_fun l2 Pl2, Peq]
variable [finB : fintype B]
include finB
lemma nodup_all_funs : nodup (@all_funs A B _ _ _) :=
dmap_nodup_of_dinj dinj_list_to_fun nodup_all_lists
lemma all_funs_complete (f : A → B) : f ∈ all_funs :=
have Plin : map f (elems A) ∈ all_lists_of_len (card A),
from mem_all_lists (by rewrite length_map),
have Plfin : list_to_fun (map f (elems A)) (length_map_of_fintype f) ∈ all_funs,
from mem_dmap _ Plin,
begin rewrite [fun_eq_list_to_fun_map f (length_map_of_fintype f)], apply Plfin end
lemma all_funs_to_all_lists :
map fun_to_list (@all_funs A B _ _ _) = all_lists_of_len (card A) :=
map_dmap_of_inv_of_pos list_to_fun_to_list length_mem_all_lists
lemma length_all_funs : length (@all_funs A B _ _ _) = (card B) ^ (card A) := calc
length _ = length (map fun_to_list all_funs) : length_map
... = length (all_lists_of_len (card A)) : all_funs_to_all_lists
... = (card B) ^ (card A) : length_all_lists
attribute [instance]
definition fun_is_fintype : fintype (A → B) :=
fintype.mk all_funs nodup_all_funs all_funs_complete
lemma card_funs : card (A → B) = (card B) ^ (card A) := length_all_funs
end list_to_fun
section surj_inv
variables {A B : Type}
variable [finA : fintype A]
include finA
-- surj from fintype domain implies fintype range
lemma mem_map_of_surj {f : A → B} (surj : surjective f) : ∀ b, b ∈ map f (elems A) :=
take b, obtain a Peq, from surj b,
Peq ▸ mem_map f (complete a)
variable [deceqB : decidable_eq B]
include deceqB
lemma found_of_surj {f : A → B} (surj : surjective f) :
∀ b, let elts := elems A, k := find b (map f elts) in k < length elts :=
λ b, let elts := elems A, img := map f elts, k := find b img in
have Pin : b ∈ img, from mem_map_of_surj surj b,
have Pfound : k < length img, from find_lt_length (mem_map_of_surj surj b),
length_map f elts ▸ Pfound
definition right_inv {f : A → B} (surj : surjective f) : B → A :=
λ b, let elts := elems A, k := find b (map f elts) in
kth k elts (found_of_surj surj b)
lemma right_inv_of_surj {f : A → B} (surj : surjective f) : f ∘ (right_inv surj) = id :=
funext (λ b, find_in_range b (elems A) (found_of_surj surj b))
end surj_inv
-- inj functions for equal card types are also surj and therefore bij
-- the right inv (since it is surj) is also the left inv
section inj
open finset
variables {A B : Type}
variable [finA : fintype A]
include finA
variable [deceqA : decidable_eq A]
include deceqA
lemma inj_of_card_image_eq [deceqB : decidable_eq B] {f : A → B} :
finset.card (image f univ) = card A → injective f :=
assume Peq, by
rewrite [set.injective_iff_inj_on_univ, -to_set_univ];
apply inj_on_of_card_image_eq Peq
variable [deceqB : decidable_eq B]
include deceqB
lemma nodup_of_inj {f : A → B} : injective f → nodup (map f (elems A)) :=
assume Pinj, nodup_map Pinj (unique A)
lemma inj_of_nodup {f : A → B} :
nodup (map f (elems A)) → injective f :=
assume Pnodup, inj_of_card_image_eq (calc
finset.card (image f univ) = finset.card (to_finset (map f (elems A))) : rfl
... = finset.card (to_finset_of_nodup (map f (elems A)) Pnodup) : {(to_finset_eq_of_nodup Pnodup)⁻¹}
... = length (map f (elems A)) : rfl
... = length (elems A) : length_map
... = card A : rfl)
variable [finB : fintype B]
include finB
lemma surj_of_inj_eq_card : card A = card B → ∀ {f : A → B}, injective f → surjective f :=
assume Peqcard, take f, assume Pinj,
decidable.rec_on decidable_forall_finite
(assume P : surjective f, P)
(assume Pnsurj : ¬surjective f,
obtain b Pne, from exists_not_of_not_forall Pnsurj,
have Pall : ∀ a, f a ≠ b, from forall_not_of_not_exists Pne,
have Pbnin : b ∉ image f univ, from λ Pin,
obtain a Pa, from exists_of_mem_image Pin, absurd (and.right Pa) (Pall a),
have Puniv : finset.card (image f univ) = card A, from card_eq_card_image_of_inj Pinj,
have Punivb : finset.card (image f univ) = card B, from eq.trans Puniv Peqcard,
have P : image f univ = univ, from univ_of_card_eq_univ Punivb,
absurd (P⁻¹▸ mem_univ b) Pbnin)
end inj
section perm
definition all_injs (A : Type) [finA : fintype A] [deceqA : decidable_eq A] : list (A → A) :=
dmap (λ l, length l = card A) list_to_fun (all_nodups_of_len (card A))
variable {A : Type}
variable [finA : fintype A]
include finA
variable [deceqA : decidable_eq A]
include deceqA
lemma nodup_all_injs : nodup (all_injs A) :=
dmap_nodup_of_dinj dinj_list_to_fun nodup_all_nodups
lemma all_injs_complete {f : A → A} : injective f → f ∈ (all_injs A) :=
assume Pinj,
have Plin : map f (elems A) ∈ all_nodups_of_len (card A),
from begin apply mem_all_nodups, apply length_map, apply nodup_of_inj Pinj end,
have Plfin : list_to_fun (map f (elems A)) (length_map_of_fintype f) ∈ !all_injs,
from mem_dmap _ Plin,
begin rewrite [fun_eq_list_to_fun_map f (length_map_of_fintype f)], apply Plfin end
open finset
lemma univ_of_leq_univ_of_nodup {l : list A} (n : nodup l) (leq : length l = card A) :
to_finset_of_nodup l n = univ :=
univ_of_card_eq_univ (calc
finset.card (to_finset_of_nodup l n) = length l : rfl
... = card A : leq)
lemma inj_of_mem_all_injs {f : A → A} : f ∈ (all_injs A) → injective f :=
assume Pfin, obtain l Pex, from exists_of_mem_dmap Pfin,
obtain leq Pin Peq, from Pex,
have Pmap : map f (elems A) = l, from Peq⁻¹ ▸ list_to_fun_to_list l leq,
begin apply inj_of_nodup, rewrite Pmap, apply nodup_mem_all_nodups Pin end
lemma perm_of_inj {f : A → A} : injective f → perm (map f (elems A)) (elems A) :=
assume Pinj,
have P1 : univ = to_finset_of_nodup (elems A) (unique A), from rfl,
have P2 : to_finset_of_nodup (map f (elems A)) (nodup_of_inj Pinj) = univ,
from univ_of_leq_univ_of_nodup _ !length_map,
quot.exact (P1 ▸ P2)
end perm
end fintype
|
03539e5f42b60d578789968cbbf930c5f3821e1c | 367134ba5a65885e863bdc4507601606690974c1 | /src/computability/primrec.lean | 506cc108d7d468fa96efaf983fe7911b87507a6f | [
"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 | 51,970 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.equiv.list
import logic.function.iterate
/-!
# The primitive recursive functions
The primitive recursive functions are the least collection of functions
`nat → nat` which are closed under projections (using the mkpair
pairing function), composition, zero, successor, and primitive recursion
(i.e. nat.rec where the motive is C n := nat).
We can extend this definition to a large class of basic types by
using canonical encodings of types as natural numbers (Gödel numbering),
which we implement through the type class `encodable`. (More precisely,
we need that the composition of encode with decode yields a
primitive recursive function, so we have the `primcodable` type class
for this.)
## References
* [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019]
-/
open denumerable encodable
namespace nat
def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C)
@[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl
@[simp] theorem elim_succ {C} (a f n) :
@nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl
def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n)
@[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl
@[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl
@[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α :=
f n.unpair.1 n.unpair.2
/-- The primitive recursive functions `ℕ → ℕ`. -/
inductive primrec : (ℕ → ℕ) → Prop
| zero : primrec (λ n, 0)
| succ : primrec succ
| left : primrec (λ n, n.unpair.1)
| right : primrec (λ n, n.unpair.2)
| pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n))
| comp {f g} : primrec f → primrec g → primrec (λ n, f (g n))
| prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n,
n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH)))
namespace primrec
theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g :=
(funext H : f = g) ▸ hf
theorem const : ∀ (n : ℕ), primrec (λ _, n)
| 0 := zero
| (n+1) := succ.comp (const n)
protected theorem id : primrec id :=
(left.pair right).of_eq $ λ n, by simp
theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n,
n.elim m (λ y IH, f $ mkpair y IH)) :=
((prec (const m) (hf.comp right)).comp
(zero.pair primrec.id)).of_eq $
λ n, by simp; dsimp; rw [unpair_mkpair]
theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) :=
(prec1 m (hf.comp left)).of_eq $ by simp [cases]
theorem cases {f g} (hf : primrec f) (hg : primrec g) :
primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) :=
(prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases]
protected theorem swap : primrec (unpaired (function.swap mkpair)) :=
(pair right left).of_eq $ λ n, by simp
theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (function.swap f)) :=
(hf.comp primrec.swap).of_eq $ λ n, by simp
theorem pred : primrec pred :=
(cases1 0 primrec.id).of_eq $ λ n, by cases n; simp *
theorem add : primrec (unpaired (+)) :=
(prec primrec.id ((succ.comp right).comp right)).of_eq $
λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ]
theorem sub : primrec (unpaired has_sub.sub) :=
(prec primrec.id ((pred.comp right).comp right)).of_eq $
λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ]
theorem mul : primrec (unpaired (*)) :=
(prec zero (add.comp (pair left (right.comp right)))).of_eq $
λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm]
theorem pow : primrec (unpaired (^)) :=
(prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $
λ p, by simp; induction p.unpair.2; simp [*, pow_succ']
end primrec
end nat
/-- A `primcodable` type is an `encodable` type for which
the encode/decode functions are primitive recursive. -/
class primcodable (α : Type*) extends encodable α :=
(prim [] : nat.primrec (λ n, encodable.encode (decode n)))
namespace primcodable
open nat.primrec
@[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α :=
⟨succ.of_eq $ by simp⟩
def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β :=
{ prim := (primcodable.prim α).of_eq $ λ n,
show encode (decode α n) =
(option.cases_on (option.map e.symm (decode α n))
0 (λ a, nat.succ (encode (e a))) : ℕ),
by cases decode α n; dsimp; simp,
..encodable.of_equiv α e }
instance empty : primcodable empty :=
⟨zero⟩
instance unit : primcodable punit :=
⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩
instance option {α : Type*} [h : primcodable α] : primcodable (option α) :=
⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $
λ n, by cases n; simp; cases decode α n; refl⟩
instance bool : primcodable bool :=
⟨(cases1 1 (cases1 2 zero)).of_eq $
λ n, begin
cases n, {refl}, cases n, {refl},
rw decode_ge_two, {refl},
exact dec_trivial
end⟩
end primcodable
/-- `primrec f` means `f` is primitive recursive (after
encoding its input and output as natural numbers). -/
def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop :=
nat.primrec (λ n, encode ((decode α n).map f))
namespace primrec
variables {α : Type*} {β : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable σ]
open nat.primrec
protected theorem encode : primrec (@encode α _) :=
(primcodable.prim α).of_eq $ λ n, by cases decode α n; refl
protected theorem decode : primrec (decode α) :=
succ.comp (primcodable.prim α)
theorem dom_denumerable {α β} [denumerable α] [primcodable β]
{f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) :=
⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl,
λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩
theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f :=
dom_denumerable
theorem encdec : primrec (λ n, encode (decode α n)) :=
nat_iff.2 (primcodable.prim α)
theorem option_some : primrec (@some α) :=
((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $
λ n, by cases decode α n; simp
theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g :=
(funext H : f = g) ▸ hf
theorem const (x : σ) : primrec (λ a : α, x) :=
((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $
λ n, by cases decode α n; refl
protected theorem id : primrec (@id α) :=
(primcodable.prim α).of_eq $ by simp
theorem comp {f : β → σ} {g : α → β}
(hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) :=
((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $
λ n, begin
cases decode α n, {refl},
simp [encodek]
end
theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ
theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred
theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f :=
⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl,
primrec.encode.comp⟩
theorem of_nat_iff {α β} [denumerable α] [primcodable β]
{f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) :=
dom_denumerable.trans $ nat_iff.symm.trans encode_iff
protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) :=
of_nat_iff.1 primrec.id
theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f :=
⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩
theorem of_equiv {β} {e : β ≃ α} :
by haveI := primcodable.of_equiv α e; exact
primrec e :=
by letI : primcodable β := primcodable.of_equiv α e; exact encode_iff.1 primrec.encode
theorem of_equiv_symm {β} {e : β ≃ α} :
by haveI := primcodable.of_equiv α e; exact
primrec e.symm :=
by letI := primcodable.of_equiv α e; exact
encode_iff.1
(show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode])
theorem of_equiv_iff {β} (e : β ≃ α)
{f : σ → β} :
by haveI := primcodable.of_equiv α e; exact
primrec (λ a, e (f a)) ↔ primrec f :=
by letI := primcodable.of_equiv α e; exact
⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩
theorem of_equiv_symm_iff {β} (e : β ≃ α)
{f : σ → α} :
by haveI := primcodable.of_equiv α e; exact
primrec (λ a, e.symm (f a)) ↔ primrec f :=
by letI := primcodable.of_equiv α e; exact
⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩
end primrec
namespace primcodable
open nat.primrec
instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) :=
⟨((cases zero ((cases zero succ).comp
(pair right ((primcodable.prim β).comp left)))).comp
(pair right ((primcodable.prim α).comp left))).of_eq $
λ n, begin
simp [nat.unpaired],
cases decode α n.unpair.1, { simp },
cases decode β n.unpair.2; simp
end⟩
end primcodable
namespace primrec
variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ]
open nat.primrec
theorem fst {α β} [primcodable α] [primcodable β] :
primrec (@prod.fst α β) :=
((cases zero ((cases zero (nat.primrec.succ.comp left)).comp
(pair right ((primcodable.prim β).comp left)))).comp
(pair right ((primcodable.prim α).comp left))).of_eq $
λ n, begin
simp,
cases decode α n.unpair.1; simp,
cases decode β n.unpair.2; simp
end
theorem snd {α β} [primcodable α] [primcodable β] :
primrec (@prod.snd α β) :=
((cases zero ((cases zero (nat.primrec.succ.comp right)).comp
(pair right ((primcodable.prim β).comp left)))).comp
(pair right ((primcodable.prim α).comp left))).of_eq $
λ n, begin
simp,
cases decode α n.unpair.1; simp,
cases decode β n.unpair.2; simp
end
theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ]
{f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) :
primrec (λ a, (f a, g a)) :=
((cases1 0 (nat.primrec.succ.comp $
pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp
(primcodable.prim α)).of_eq $
λ n, by cases decode α n; simp [encodek]; refl
theorem unpair : primrec nat.unpair :=
(pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $
λ n, by simp
theorem list_nth₁ : ∀ (l : list α), primrec l.nth
| [] := dom_denumerable.2 zero
| (a::l) := dom_denumerable.2 $
(cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $
λ n, by cases n; simp
end primrec
/-- `primrec₂ f` means `f` is a binary primitive recursive function.
This is technically unnecessary since we can always curry all
the arguments together, but there are enough natural two-arg
functions that it is convenient to express this directly. -/
def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) :=
primrec (λ p : α × β, f p.1 p.2)
/-- `primrec_pred p` means `p : α → Prop` is a (decidable)
primitive recursive predicate, which is to say that
`to_bool ∘ p : α → bool` is primitive recursive. -/
def primrec_pred {α} [primcodable α] (p : α → Prop)
[decidable_pred p] := primrec (λ a, to_bool (p a))
/-- `primrec_rel p` means `p : α → β → Prop` is a (decidable)
primitive recursive relation, which is to say that
`to_bool ∘ p : α → β → bool` is primitive recursive. -/
def primrec_rel {α β} [primcodable α] [primcodable β]
(s : α → β → Prop) [∀ a b, decidable (s a b)] :=
primrec₂ (λ a b, to_bool (s a b))
namespace primrec₂
variables {α : Type*} {β : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable σ]
theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g :=
(by funext a b; apply H : f = g) ▸ hg
theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _
protected theorem pair : primrec₂ (@prod.mk α β) :=
primrec.pair primrec.fst primrec.snd
theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst
theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd
theorem mkpair : primrec₂ nat.mkpair :=
by simp [primrec₂, primrec]; constructor
theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f :=
⟨λ h, by simpa using h.comp mkpair,
λ h, h.comp primrec.unpair⟩
theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f :=
primrec.nat_iff.symm.trans unpaired
theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f :=
primrec.encode_iff
theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f :=
primrec.option_some_iff
theorem of_nat_iff {α β σ}
[denumerable α] [denumerable β] [primcodable σ]
{f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ,
f (of_nat α m) (of_nat β n)) :=
(primrec.of_nat_iff.trans $ by simp).trans unpaired
theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f :=
by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2,
from funext $ λ ⟨a, b⟩, rfl]; refl
theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f :=
by rw [← uncurry, function.uncurry_curry]
end primrec₂
section comp
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ]
theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ}
(hf : primrec f) (hg : primrec₂ g) :
primrec₂ (λ a b, f (g a b)) := hf.comp hg
theorem primrec₂.comp
{f : β → γ → σ} {g : α → β} {h : α → γ}
(hf : primrec₂ f) (hg : primrec g) (hh : primrec h) :
primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh)
theorem primrec₂.comp₂
{f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ}
(hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) :
primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh
theorem primrec_pred.comp
{p : β → Prop} [decidable_pred p] {f : α → β} :
primrec_pred p → primrec f →
primrec_pred (λ a, p (f a)) := primrec.comp
theorem primrec_rel.comp
{R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} :
primrec_rel R → primrec f → primrec g →
primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp
theorem primrec_rel.comp₂
{R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} :
primrec_rel R → primrec₂ f → primrec₂ g →
primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp
end comp
theorem primrec_pred.of_eq {α} [primcodable α]
{p q : α → Prop} [decidable_pred p] [decidable_pred q]
(hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q :=
primrec.of_eq hp (λ a, to_bool_congr (H a))
theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β]
{r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)]
(hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s :=
primrec₂.of_eq hr (λ a b, to_bool_congr (H a b))
namespace primrec₂
variables {α : Type*} {β : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable σ]
open nat.primrec
theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (function.swap f) :=
h.comp₂ primrec₂.right primrec₂.left
theorem nat_iff {f : α → β → σ} : primrec₂ f ↔
nat.primrec (nat.unpaired $ λ m n : ℕ,
encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) :=
have ∀ (a : option α) (b : option β),
option.map (λ (p : α × β), f p.1 p.2)
(option.bind a (λ (a : α), option.map (prod.mk a) b)) =
option.bind a (λ a, option.map (f a) b),
by intros; cases a; [refl, {cases b; refl}],
by simp [primrec₂, primrec, this]
theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ,
option.bind (decode α m) (λ a, option.map (f a) (decode β n))) :=
nat_iff.trans $ unpaired'.trans encode_iff
end primrec₂
namespace primrec
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ]
theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) :=
hf.of_eq $ λ ⟨a, b⟩, rfl
theorem nat_elim {f : α → β} {g : α → ℕ × β → β}
(hf : primrec f) (hg : primrec₂ g) :
primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) :=
primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $
(nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $
(nat.primrec.left.comp nat.primrec.right).pair $
nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $
nat.primrec.right.pair $
nat.primrec.right.comp nat.primrec.left).comp $
nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $
λ n, begin
simp,
cases decode α n.unpair.1 with a, {refl},
simp [encodek],
induction n.unpair.2 with m; simp [encodek],
simp [ih, encodek]
end
theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) :=
(nat_elim hg hh).comp primrec.id hf
theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) :
primrec (nat.elim a f) :=
nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right
theorem nat_cases' {f : α → β} {g : α → ℕ → β}
(hf : primrec f) (hg : primrec₂ g) :
primrec₂ (λ a, nat.cases (f a) (g a)) :=
nat_elim hf $ hg.comp₂ primrec₂.left $
comp₂ fst primrec₂.right
theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
primrec (λ a, (f a).cases (g a) (h a)) :=
(nat_cases' hg hh).comp primrec.id hf
theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) :
primrec (nat.cases a f) :=
nat_cases primrec.id (const a) (comp₂ hf primrec₂.right)
theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
primrec (λ a, (h a)^[f a] (g a)) :=
(nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $
λ a, by induction f a; simp [*, function.iterate_succ']
theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ}
(ho : primrec o) (hf : primrec f) (hg : primrec₂ g) :
@primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) :=
encode_iff.1 $
(nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $
pred.comp₂ $ primrec₂.encode_iff.2 $
(primrec₂.nat_iff'.1 hg).comp₂
((@primrec.encode α _).comp fst).to₂
primrec₂.right).of_eq $
λ a, by cases o a with b; simp [encodek]; refl
theorem option_bind {f : α → option β} {g : α → β → option σ}
(hf : primrec f) (hg : primrec₂ g) :
primrec (λ a, (f a).bind (g a)) :=
(option_cases hf (const none) hg).of_eq $
λ a, by cases f a; refl
theorem option_bind₁ {f : α → option σ} (hf : primrec f) :
primrec (λ o, option.bind o f) :=
option_bind primrec.id (hf.comp snd).to₂
theorem option_map {f : α → option β} {g : α → β → σ}
(hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) :=
option_bind hf (option_some.comp₂ hg)
theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) :=
option_map primrec.id (hf.comp snd).to₂
theorem option_iget [inhabited α] : primrec (@option.iget α _) :=
(option_cases primrec.id (const $ default α) primrec₂.right).of_eq $
λ o, by cases o; refl
theorem option_is_some : primrec (@option.is_some α) :=
(option_cases primrec.id (const ff) (const tt).to₂).of_eq $
λ o, by cases o; refl
theorem option_get_or_else : primrec₂ (@option.get_or_else α) :=
primrec.of_eq (option_cases primrec₂.left primrec₂.right primrec₂.right) $
λ ⟨o, a⟩, by cases o; refl
theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n,
(decode β n).bind (f a)) ↔ primrec₂ f :=
⟨λ h, by simpa [encodek] using
h.comp fst ((@primrec.encode β _).comp snd),
λ h, option_bind (primrec.decode.comp snd) $
h.comp (fst.comp fst) snd⟩
theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n,
(decode β n).map (f a)) ↔ primrec₂ f :=
bind_decode_iff.trans primrec₂.option_some_iff
theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) :=
primrec₂.unpaired'.1 nat.primrec.add
theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) :=
primrec₂.unpaired'.1 nat.primrec.sub
theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) :=
primrec₂.unpaired'.1 nat.primrec.mul
theorem cond {c : α → bool} {f : α → σ} {g : α → σ}
(hc : primrec c) (hf : primrec f) (hg : primrec g) :
primrec (λ a, cond (c a) (f a) (g a)) :=
(nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $
λ a, by cases c a; refl
theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ}
(hc : primrec_pred c) (hf : primrec f) (hg : primrec g) :
primrec (λ a, if c a then f a else g a) :=
by simpa using cond hc hf hg
theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) :=
(nat_cases nat_sub (const tt) (const ff).to₂).of_eq $
λ p, begin
dsimp [function.swap],
cases e : p.1 - p.2 with n,
{ simp [nat.sub_eq_zero_iff_le.1 e] },
{ simp [not_le.2 (nat.lt_of_sub_eq_succ e)] }
end
theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd
theorem nat_max : primrec₂ (@max ℕ _) := ite (nat_le.comp primrec.snd primrec.fst) fst snd
theorem dom_bool (f : bool → α) : primrec f :=
(cond primrec.id (const (f tt)) (const (f ff))).of_eq $
λ b, by cases b; refl
theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f :=
(cond fst
((dom_bool (f tt)).comp snd)
((dom_bool (f ff)).comp snd)).of_eq $
λ ⟨a, b⟩, by cases a; refl
protected theorem bnot : primrec bnot := dom_bool _
protected theorem band : primrec₂ band := dom_bool₂ _
protected theorem bor : primrec₂ bor := dom_bool₂ _
protected theorem not {p : α → Prop} [decidable_pred p]
(hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) :=
(primrec.bnot.comp hp).of_eq $ λ n, by simp
protected theorem and {p q : α → Prop}
[decidable_pred p] [decidable_pred q]
(hp : primrec_pred p) (hq : primrec_pred q) :
primrec_pred (λ a, p a ∧ q a) :=
(primrec.band.comp hp hq).of_eq $ λ n, by simp
protected theorem or {p q : α → Prop}
[decidable_pred p] [decidable_pred q]
(hp : primrec_pred p) (hq : primrec_pred q) :
primrec_pred (λ a, p a ∨ q a) :=
(primrec.bor.comp hp hq).of_eq $ λ n, by simp
protected theorem eq [decidable_eq α] : primrec_rel (@eq α) :=
have primrec_rel (λ a b : ℕ, a = b), from
(primrec.and nat_le nat_le.swap).of_eq $
λ a, by simp [le_antisymm_iff],
(this.comp₂
(primrec.encode.comp₂ primrec₂.left)
(primrec.encode.comp₂ primrec₂.right)).of_eq $
λ a b, encode_injective.eq_iff
theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) :=
(nat_le.comp snd fst).not.of_eq $ λ p, by simp
theorem option_guard {p : α → β → Prop}
[∀ a b, decidable (p a b)] (hp : primrec_rel p)
{f : α → β} (hf : primrec f) :
primrec (λ a, option.guard (p a) (f a)) :=
ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none)
theorem option_orelse :
primrec₂ ((<|>) : option α → option α → option α) :=
(option_cases fst snd (fst.comp fst).to₂).of_eq $
λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl
protected theorem decode2 : primrec (decode2 α) :=
option_bind primrec.decode $
option_guard ((@primrec.eq _ _ nat.decidable_eq).comp
(encode_iff.2 snd) (fst.comp fst)) snd
theorem list_find_index₁ {p : α → β → Prop}
[∀ a b, decidable (p a b)] (hp : primrec_rel p) :
∀ (l : list β), primrec (λ a, l.find_index (p a))
| [] := const 0
| (a::l) := ite (hp.comp primrec.id (const a)) (const 0)
(succ.comp (list_find_index₁ l))
theorem list_index_of₁ [decidable_eq α] (l : list α) :
primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l
theorem dom_fintype [fintype α] (f : α → σ) : primrec f :=
let ⟨l, nd, m⟩ := fintype.exists_univ_list α in
option_some_iff.1 $ begin
haveI := decidable_eq_of_encodable α,
refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _),
rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)),
list.index_of_nth_le]; refl
end
theorem nat_bodd_div2 : primrec nat.bodd_div2 :=
(nat_elim' primrec.id (const (ff, 0))
(((cond fst
(pair (const ff) (succ.comp snd))
(pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $
λ n, begin
simp [-nat.bodd_div2_eq],
induction n with n IH, {refl},
simp [-nat.bodd_div2_eq, nat.bodd_div2, *],
rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2]
end
theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2
theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2
theorem nat_bit0 : primrec (@bit0 ℕ _) :=
nat_add.comp primrec.id primrec.id
theorem nat_bit1 : primrec (@bit1 ℕ _ _) :=
nat_add.comp nat_bit0 (const 1)
theorem nat_bit : primrec₂ nat.bit :=
(cond primrec.fst
(nat_bit1.comp primrec.snd)
(nat_bit0.comp primrec.snd)).of_eq $
λ n, by cases n.1; refl
theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) :=
let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH,
if nat.succ IH.2 = a.2
then (nat.succ IH.1, 0)
else (IH.1, nat.succ IH.2)) in
have hf : primrec f, from
nat_elim' fst (const (0, 0)) $
((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst)
(pair (succ.comp $ fst.comp snd) (const 0))
(pair (fst.comp snd) (succ.comp $ snd.comp snd)))
.comp (pair (snd.comp fst) (snd.comp snd))).to₂,
suffices ∀ k n, (n / k, n % k) = f (n, k),
from hf.of_eq $ λ ⟨m, n⟩, by simp [this],
λ k n, begin
have : (f (n, k)).2 + k * (f (n, k)).1 = n
∧ (0 < k → (f (n, k)).2 < k)
∧ (k = 0 → (f (n, k)).1 = 0),
{ induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩},
rw [λ n:ℕ, show f (n.succ, k) =
_root_.ite ((f (n, k)).2.succ = k)
(nat.succ (f (n, k)).1, 0)
((f (n, k)).1, (f (n, k)).2.succ), from rfl],
by_cases h : (f (n, k)).2.succ = k; simp [h],
{ have := congr_arg nat.succ IH.1,
refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩,
rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this },
{ exact ⟨by rw [nat.succ_add, IH.1],
λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } },
revert this, cases f (n, k) with D M,
simp, intros h₁ h₂ h₃,
cases nat.eq_zero_or_pos k,
{ simp [h, h₃ h] at h₁ ⊢, simp [h₁] },
{ exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ }
end
theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod
theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod
end primrec
section
variables {α : Type*} {β : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable σ]
variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n)))
include H
open primrec
private def prim : primcodable (list β) := ⟨H⟩
private lemma list_cases'
{f : α → list β} {g : α → σ} {h : α → β × list β → σ}
(hf : by haveI := prim H; exact primrec f) (hg : primrec g)
(hh : by haveI := prim H; exact primrec₂ h) :
@primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) :=
by letI := prim H; exact
have @primrec _ (option σ) _ _ (λ a,
(decode (option (β × list β)) (encode (f a))).map
(λ o, option.cases_on o (g a) (h a))), from
((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $
to₂ $ option_cases snd (hg.comp fst)
(hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right))
.comp primrec.id (encode_iff.2 hf),
option_some_iff.1 $ this.of_eq $
λ a, by cases f a with b l; simp [encodek]; refl
private lemma list_foldl'
{f : α → list β} {g : α → σ} {h : α → σ × β → σ}
(hf : by haveI := prim H; exact primrec f) (hg : primrec g)
(hh : by haveI := prim H; exact primrec₂ h) :
primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) :=
by letI := prim H; exact
let G (a : α) (IH : σ × list β) : σ × list β :=
list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in
let F (a : α) (n : ℕ) := (G a)^[n] (g a, f a) in
have primrec (λ a, (F a (encode (f a))).1), from
fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $
list_cases' H (snd.comp snd) snd $ to₂ $ pair
(hh.comp (fst.comp fst) $
pair ((fst.comp snd).comp fst) (fst.comp snd))
(snd.comp snd),
this.of_eq $ λ a, begin
have : ∀ n, F a n =
((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a),
list.drop n (f a)),
{ intro, simp [F],
generalize : f a = l, generalize : g a = x,
induction n with n IH generalizing l x, {refl},
simp, cases l with b l; simp [IH] },
rw [this, list.take_all_of_le (length_le_encode _)]
end
private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) :=
by letI := prim H; exact
encode_iff.1 (succ.comp $
primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd))
private lemma list_reverse' : by haveI := prim H; exact
primrec (@list.reverse β) :=
by letI := prim H; exact
(list_foldl' H primrec.id (const []) $ to₂ $
((list_cons' H).comp snd fst).comp snd).of_eq
(suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r,
from λ l, this l [],
λ l, by induction l; simp [*, list.reverse_core])
end
namespace primcodable
variables {α : Type*} {β : Type*}
variables [primcodable α] [primcodable β]
open primrec
instance sum : primcodable (α ⊕ β) :=
⟨primrec.nat_iff.1 $
(encode_iff.2 (cond nat_bodd
(((@primrec.decode β _).comp nat_div2).option_map $ to₂ $
nat_bit.comp (const tt) (primrec.encode.comp snd))
(((@primrec.decode α _).comp nat_div2).option_map $ to₂ $
nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $
λ n, show _ = encode (decode_sum n), begin
simp [decode_sum],
cases nat.bodd n; simp [decode_sum],
{ cases decode α n.div2; refl },
{ cases decode β n.div2; refl }
end⟩
instance list : primcodable (list α) := ⟨
by letI H := primcodable.prim (list ℕ); exact
have primrec₂ (λ (a : α) (o : option (list ℕ)),
o.map (list.cons (encode a))), from
option_map snd $
(list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd,
have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl
(λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a))))
(some [])), from
list_foldl' H
((list_reverse' H).comp (primrec.of_nat (list ℕ)))
(const (some []))
(primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right),
nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin
rw list.foldl_reverse,
apply nat.case_strong_induction_on n, {refl},
intros n IH, simp,
cases decode α n.unpair.1 with a, {refl},
simp,
suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p),
encode (option.map (list.cons (encode a)) o) =
encode (option.map (list.cons a) p),
from this _ _ (IH _ (nat.unpair_le_right n)),
intros o p IH,
cases o; cases p; injection IH with h,
exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h
end⟩
end primcodable
namespace primrec
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
theorem sum_inl : primrec (@sum.inl α β) :=
encode_iff.1 $ nat_bit0.comp primrec.encode
theorem sum_inr : primrec (@sum.inr α β) :=
encode_iff.1 $ nat_bit1.comp primrec.encode
theorem sum_cases
{f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ}
(hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) :
@primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) :=
option_some_iff.1 $
(cond (nat_bodd.comp $ encode_iff.2 hf)
(option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh)
(option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $
λ a, by cases f a with b c;
simp [nat.div2_bit, nat.bodd_bit, encodek]; refl
theorem list_cons : primrec₂ (@list.cons α) :=
list_cons' (primcodable.prim _)
theorem list_cases
{f : α → list β} {g : α → σ} {h : α → β × list β → σ} :
primrec f → primrec g → primrec₂ h →
@primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) :=
list_cases' (primcodable.prim _)
theorem list_foldl
{f : α → list β} {g : α → σ} {h : α → σ × β → σ} :
primrec f → primrec g → primrec₂ h →
primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) :=
list_foldl' (primcodable.prim _)
theorem list_reverse : primrec (@list.reverse α) :=
list_reverse' (primcodable.prim _)
theorem list_foldr
{f : α → list β} {g : α → σ} {h : α → β × σ → σ}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) :=
(list_foldl (list_reverse.comp hf) hg $ to₂ $
hh.comp fst $ (pair snd fst).comp snd).of_eq $
λ a, by simp [list.foldl_reverse]
theorem list_head' : primrec (@list.head' α) :=
(list_cases primrec.id (const none)
(option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $
λ l, by cases l; refl
theorem list_head [inhabited α] : primrec (@list.head α _) :=
(option_iget.comp list_head').of_eq $
λ l, l.head_eq_head'.symm
theorem list_tail : primrec (@list.tail α) :=
(list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $
λ l, by cases l; refl
theorem list_rec
{f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ}
(hf : primrec f) (hg : primrec g) (hh : primrec₂ h) :
@primrec _ σ _ _ (λ a,
list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) :=
let F (a : α) := (f a).foldr
(λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in
have primrec F, from
list_foldr hf (pair (const []) hg) $ to₂ $
pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh,
(snd.comp this).of_eq $ λ a, begin
suffices : F a = (f a,
list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this},
simp [F], induction f a with b l IH; simp *
end
theorem list_nth : primrec₂ (@list.nth α) :=
let F (l : list α) (n : ℕ) :=
l.foldl (λ (s : ℕ ⊕ α) (a : α),
sum.cases_on s
(@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr)
(sum.inl n) in
have hF : primrec₂ F, from
list_foldl fst (sum_inl.comp snd) ((sum_cases fst
(nat_cases snd
(sum_inr.comp $ snd.comp fst)
(sum_inl.comp snd).to₂).to₂
(sum_inr.comp snd).to₂).comp snd).to₂,
have @primrec _ (option α) _ _ (λ p : list α × ℕ,
sum.cases_on (F p.1 p.2) (λ _, none) some), from
sum_cases hF (const none).to₂ (option_some.comp snd).to₂,
this.to₂.of_eq $ λ l n, begin
dsimp, symmetry,
induction l with a l IH generalizing n, {refl},
cases n with n,
{ rw [(_ : F (a :: l) 0 = sum.inr a)], {refl},
clear IH, dsimp [F],
induction l with b l IH; simp * },
{ apply IH }
end
theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) :=
option_iget.comp₂ list_nth
theorem list_append : primrec₂ ((++) : list α → list α → list α) :=
(list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $
λ l₁ l₂, by induction l₁; simp *
theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) :=
list_append.comp fst (list_cons.comp snd (const []))
theorem list_map
{f : α → list β} {g : α → β → σ}
(hf : primrec f) (hg : primrec₂ g) :
primrec (λ a, (f a).map (g a)) :=
(list_foldr hf (const []) $ to₂ $ list_cons.comp
(hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $
λ a, by induction f a; simp *
theorem list_range : primrec list.range :=
(nat_elim' primrec.id (const [])
((list_concat.comp snd fst).comp snd).to₂).of_eq $
λ n, by simp; induction n; simp [*, list.range_succ]; refl
theorem list_join : primrec (@list.join α) :=
(list_foldr primrec.id (const []) $ to₂ $
comp (@list_append α _) snd).of_eq $
λ l, by dsimp; induction l; simp *
theorem list_length : primrec (@list.length α) :=
(list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $
(succ.comp $ snd.comp snd).to₂).of_eq $
λ l, by dsimp; induction l; simp [*, -add_comm]
theorem list_find_index {f : α → list β} {p : α → β → Prop}
[∀ a b, decidable (p a b)]
(hf : primrec f) (hp : primrec_rel p) :
primrec (λ a, (f a).find_index (p a)) :=
(list_foldr hf (const 0) $ to₂ $
ite (hp.comp fst $ fst.comp snd) (const 0)
(succ.comp $ snd.comp snd)).of_eq $
λ a, eq.symm $ by dsimp; induction f a with b l;
[refl, simp [*, list.find_index]]
theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) :=
to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂
theorem nat_strong_rec
(f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g)
(H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f :=
suffices primrec₂ (λ a n, (list.range n).map (f a)), from
primrec₂.option_some_iff.1 $
(list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $
λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl,
primrec₂.option_some_iff.1 $
(nat_elim (const (some [])) (to₂ $
option_bind (snd.comp snd) $ to₂ $
option_map
(hg.comp (fst.comp fst) snd)
(to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $
λ a n, begin
simp, induction n with n IH, {refl},
simp [IH, H, list.range_succ]
end
end primrec
namespace primcodable
variables {α : Type*} {β : Type*}
variables [primcodable α] [primcodable β]
open primrec
def subtype {p : α → Prop} [decidable_pred p]
(hp : primrec_pred p) : primcodable (subtype p) :=
⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)),
from option_bind primrec.decode (option_guard (hp.comp snd) snd),
nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n,
show _ = encode ((decode α n).bind (λ a, _)), begin
cases decode α n with a, {refl},
dsimp [option.guard],
by_cases h : p a; simp [h]; refl
end⟩
instance fin {n} : primcodable (fin n) :=
@of_equiv _ _
(subtype $ nat_lt.comp primrec.id (const n))
(equiv.fin_equiv_subtype _)
instance vector {n} : primcodable (vector α n) :=
subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _))
instance fin_arrow {n} : primcodable (fin n → α) :=
of_equiv _ (equiv.vector_equiv_fin _ _).symm
instance array {n} : primcodable (array n α) :=
of_equiv _ (equiv.array_equiv_fin _ _)
section ulower
local attribute [instance, priority 100]
encodable.decidable_range_encode encodable.decidable_eq_of_encodable
instance ulower : primcodable (ulower α) :=
have primrec_pred (λ n, encodable.decode2 α n ≠ none),
from primrec.not (primrec.eq.comp (primrec.option_bind primrec.decode
(primrec.ite (primrec.eq.comp (primrec.encode.comp primrec.snd) primrec.fst)
(primrec.option_some.comp primrec.snd) (primrec.const _))) (primrec.const _)),
primcodable.subtype $
primrec_pred.of_eq this $
by simp [set.range, option.eq_none_iff_forall_not_mem, encodable.mem_decode2]
end ulower
end primcodable
namespace primrec
variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*}
variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ]
theorem subtype_val {p : α → Prop} [decidable_pred p]
{hp : primrec_pred p} :
by haveI := primcodable.subtype hp; exact
primrec (@subtype.val α p) :=
begin
letI := primcodable.subtype hp,
refine (primcodable.prim (subtype p)).of_eq (λ n, _),
rcases decode (subtype p) n with _|⟨a,h⟩; refl
end
theorem subtype_val_iff {p : β → Prop} [decidable_pred p]
{hp : primrec_pred p} {f : α → subtype p} :
by haveI := primcodable.subtype hp; exact
primrec (λ a, (f a).1) ↔ primrec f :=
begin
letI := primcodable.subtype hp,
refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩,
refine nat.primrec.of_eq h (λ n, _),
cases decode α n with a, {refl},
simp, cases f a; refl
end
theorem subtype_mk {p : β → Prop} [decidable_pred p] {hp : primrec_pred p}
{f : α → β} {h : ∀ a, p (f a)} (hf : primrec f) :
by haveI := primcodable.subtype hp; exact
primrec (λ a, @subtype.mk β p (f a) (h a)) :=
subtype_val_iff.1 hf
theorem option_get {f : α → option β} {h : ∀ a, (f a).is_some} :
primrec f → primrec (λ a, option.get (h a)) :=
begin
intro hf,
refine (nat.primrec.pred.comp hf).of_eq (λ n, _),
generalize hx : decode α n = x,
cases x; simp
end
theorem ulower_down : primrec (ulower.down : α → ulower α) :=
by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact
subtype_mk primrec.encode
theorem ulower_up : primrec (ulower.up : ulower α → α) :=
by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact
option_get (primrec.decode2.comp subtype_val)
theorem fin_val_iff {n} {f : α → fin n} :
primrec (λ a, (f a).1) ↔ primrec f :=
begin
let : primcodable {a//id a<n}, swap,
exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _)
end
theorem fin_val {n} : primrec (coe : fin n → ℕ) := fin_val_iff.2 primrec.id
theorem fin_succ {n} : primrec (@fin.succ n) :=
fin_val_iff.1 $ by simp [succ.comp fin_val]
theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val
theorem vector_to_list_iff {n} {f : α → vector β n} :
primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff
theorem vector_cons {n} : primrec₂ (@vector.cons α n) :=
vector_to_list_iff.1 $ by simp; exact
list_cons.comp fst (vector_to_list_iff.2 snd)
theorem vector_length {n} : primrec (@vector.length α n) := const _
theorem vector_head {n} : primrec (@vector.head α n) :=
option_some_iff.1 $
(list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl
theorem vector_tail {n} : primrec (@vector.tail α n) :=
vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $
λ ⟨l, h⟩, by cases l; refl
theorem vector_nth {n} : primrec₂ (@vector.nth α n) :=
option_some_iff.1 $
(list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $
λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth]
theorem list_of_fn : ∀ {n} {f : fin n → α → σ},
(∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a))
| 0 f hf := const []
| (n+1) f hf := by simp [list.of_fn_succ]; exact
list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ))
theorem vector_of_fn {n} {f : fin n → α → σ}
(hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) :=
vector_to_list_iff.1 $ by simp [list_of_fn hf]
theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm
theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv
theorem fin_app {n} : primrec₂ (@id (fin n → σ)) :=
(vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $
λ ⟨v, i⟩, by simp
theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) :=
⟨λ h i, h.comp (const i) primrec.id,
λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩
theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f :=
⟨λ h, fin_app.comp (h.comp fst) snd,
λ h, (vector_nth'.comp (vector_of_fn (λ i,
show primrec (λ a, f a i), from
h.comp primrec.id (const i)))).of_eq $
λ a, by funext i; simp⟩
end primrec
namespace nat
open vector
/-- An alternative inductive definition of `primrec` which
does not use the pairing function on ℕ, and so has to
work with n-ary functions on ℕ instead of unary functions.
We prove that this is equivalent to the regular notion
in `to_prim` and `of_prim`. -/
inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop
| zero : @primrec' 0 (λ _, 0)
| succ : @primrec' 1 (λ v, succ v.head)
| nth {n} (i : fin n) : primrec' (λ v, v.nth i)
| comp {m n f} (g : fin n → vector ℕ m → ℕ) :
primrec' f → (∀ i, primrec' (g i)) →
primrec' (λ a, f (of_fn (λ i, g i a)))
| prec {n f g} : @primrec' n f → @primrec' (n+2) g →
primrec' (λ v : vector ℕ (n+1),
v.head.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail)))
end nat
namespace nat.primrec'
open vector primrec nat (primrec') nat.primrec'
hide ite
theorem to_prim {n f} (pf : @primrec' n f) : primrec f :=
begin
induction pf,
case nat.primrec'.zero { exact const 0 },
case nat.primrec'.succ { exact primrec.succ.comp vector_head },
case nat.primrec'.nth : n i {
exact vector_nth.comp primrec.id (const i) },
case nat.primrec'.comp : m n f g _ _ hf hg {
exact hf.comp (vector_of_fn (λ i, hg i)) },
case nat.primrec'.prec : n f g _ _ hf hg {
exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $
vector_cons.comp (fst.comp snd) $
vector_cons.comp (snd.comp snd) $
(@vector_tail _ _ (n+1)).comp fst).to₂ },
end
theorem of_eq {n} {f g : vector ℕ n → ℕ}
(hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g :=
(funext H : f = g) ▸ hf
theorem const {n} : ∀ m, @primrec' n (λ v, m)
| 0 := zero.comp fin.elim0 (λ i, i.elim0)
| (m+1) := succ.comp _ (λ i, const m)
theorem head {n : ℕ} : @primrec' n.succ head :=
(nth 0).of_eq $ λ v, by simp [nth_zero]
theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) :=
(hf.comp _ (λ i, @nth _ i.succ)).of_eq $
λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp
def vec {n m} (f : vector ℕ n → vector ℕ m) :=
∀ i, primrec' (λ v, (f v).nth i)
protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0
protected theorem cons {n m f g}
(hf : @primrec' n f) (hg : @vec n m g) :
vec (λ v, (f v ::ᵥ g v)) :=
λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i
theorem idv {n} : @vec n n id := nth
theorem comp' {n m f g}
(hf : @primrec' m f) (hg : @vec n m g) :
primrec' (λ v, f (g v)) :=
(hf.comp _ hg).of_eq $ λ v, by simp
theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head))
{n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) :=
hf.comp _ (λ i, hg)
theorem comp₂ (f : ℕ → ℕ → ℕ)
(hf : @primrec' 2 (λ v, f v.head v.tail.head))
{n g h} (hg : @primrec' n g) (hh : @primrec' n h) :
primrec' (λ v, f (g v) (h v)) :=
by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil)
theorem prec' {n f g h}
(hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) :
@primrec' n (λ v, (f v).elim (g v)
(λ (y IH : ℕ), h (y ::ᵥ IH ::ᵥ v))) :=
by simpa using comp' (prec hg hh) (hf.cons idv)
theorem pred : @primrec' 1 (λ v, v.head.pred) :=
(prec' head (const 0) head).of_eq $
λ v, by simp; cases v.head; refl
theorem add : @primrec' 2 (λ v, v.head + v.tail.head) :=
(prec head (succ.comp₁ _ (tail head))).of_eq $
λ v, by simp; induction v.head; simp [*, nat.succ_add]
theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) :=
begin
suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head,
refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _),
simp, induction v.head; simp [*, nat.sub_succ]
end
theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) :=
(prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $
λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm
theorem if_lt {n a b f g}
(ha : @primrec' n a) (hb : @primrec' n b)
(hf : @primrec' n f) (hg : @primrec' n g) :
@primrec' n (λ v, if a v < b v then f v else g v) :=
(prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $
λ v, begin
cases e : b v - a v,
{ simp [not_lt.2 (nat.le_of_sub_eq_zero e)] },
{ simp [nat.lt_of_sub_eq_succ e] }
end
theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) :=
if_lt head (tail head)
(add.comp₂ _ (tail $ mul.comp₂ _ head head) head)
(add.comp₂ _ (add.comp₂ _
(mul.comp₂ _ head head) head) (tail head))
protected theorem encode : ∀ {n}, @primrec' n encode
| 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl)
| (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode)))
.of_eq $ λ ⟨a::l, e⟩, rfl
theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) :=
begin
suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y,
if x.succ < y.succ*y.succ then y else y.succ),
{ simp [H],
have := @prec' 1 _ _ (λ v,
by have x := v.head; have y := v.tail.head; from
if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _,
{ convert this, funext, congr, funext x y, congr; simp },
have x1 := succ.comp₁ _ head,
have y1 := succ.comp₁ _ (tail head),
exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 },
intro, symmetry,
induction n with n IH, {refl},
dsimp, rw IH, split_ifs,
{ exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _))
(nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) },
{ exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $
nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ },
end
theorem unpair₁ {n f} (hf : @primrec' n f) :
@primrec' n (λ v, (f v).unpair.1) :=
begin
have s := sqrt.comp₁ _ hf,
have fss := sub.comp₂ _ hf (mul.comp₂ _ s s),
refine (if_lt fss s fss s).of_eq (λ v, _),
simp [nat.unpair], split_ifs; refl
end
theorem unpair₂ {n f} (hf : @primrec' n f) :
@primrec' n (λ v, (f v).unpair.2) :=
begin
have s := sqrt.comp₁ _ hf,
have fss := sub.comp₂ _ hf (mul.comp₂ _ s s),
refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _),
simp [nat.unpair], split_ifs; refl
end
theorem of_prim : ∀ {n f}, primrec f → @primrec' n f :=
suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from
λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁
(λ m, encodable.encode $ (decode (vector ℕ n) m).map f)
primrec'.encode).of_eq (λ i, by simp [encodek]),
λ f hf, begin
induction hf,
case nat.primrec.zero { exact const 0 },
case nat.primrec.succ { exact succ },
case nat.primrec.left { exact unpair₁ head },
case nat.primrec.right { exact unpair₂ head },
case nat.primrec.pair : f g _ _ hf hg {
exact mkpair.comp₂ _ hf hg },
case nat.primrec.comp : f g _ _ hf hg {
exact hf.comp₁ _ hg },
case nat.primrec.prec : f g _ _ hf hg {
simpa using prec' (unpair₂ head)
(hf.comp₁ _ (unpair₁ head))
(hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head)
(mkpair.comp₂ _ head (tail head))) },
end
theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩
theorem prim_iff₁ {f : ℕ → ℕ} :
@primrec' 1 (λ v, f v.head) ↔ primrec f :=
prim_iff.trans ⟨
λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp),
λ h, h.comp vector_head⟩
theorem prim_iff₂ {f : ℕ → ℕ → ℕ} :
@primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f :=
prim_iff.trans ⟨
λ h, (h.comp $ vector_cons.comp fst $
vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp),
λ h, h.comp vector_head (vector_head.comp vector_tail)⟩
theorem vec_iff {m n f} :
@vec m n f ↔ primrec f :=
⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)),
λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩
end nat.primrec'
theorem primrec.nat_sqrt : primrec nat.sqrt :=
nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
|
87d88b1b5c13db4d46a9d050c72e8cfe1d15dd28 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/free_module/rank.lean | 0910b9caf26f99a071af20e54194ede8909c9cc9 | [
"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,000 | lean | /-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import linear_algebra.dimension
/-!
# Extra results about `module.rank`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains some extra results not in `linear_algebra.dimension`.
-/
universes u v w
variables (R : Type u) (M : Type v) (N : Type w)
open_locale tensor_product direct_sum big_operators cardinal
open cardinal
section ring
variables [ring R] [strong_rank_condition R]
variables [add_comm_group M] [module R M] [module.free R M]
variables [add_comm_group N] [module R N] [module.free R N]
open module.free
@[simp] lemma rank_finsupp (ι : Type w) :
module.rank R (ι →₀ M) = cardinal.lift.{v} #ι * cardinal.lift.{w} (module.rank R M) :=
begin
obtain ⟨⟨_, bs⟩⟩ := module.free.exists_basis R M,
rw [← bs.mk_eq_rank'', ← (finsupp.basis (λa:ι, bs)).mk_eq_rank'',
cardinal.mk_sigma, cardinal.sum_const]
end
lemma rank_finsupp' (ι : Type v) : module.rank R (ι →₀ M) = #ι * module.rank R M :=
by simp [rank_finsupp]
/-- The rank of `(ι →₀ R)` is `(# ι).lift`. -/
@[simp] lemma rank_finsupp_self (ι : Type w) : module.rank R (ι →₀ R) = (# ι).lift :=
by simp [rank_finsupp]
/-- If `R` and `ι` lie in the same universe, the rank of `(ι →₀ R)` is `# ι`. -/
lemma rank_finsupp_self' {ι : Type u} : module.rank R (ι →₀ R) = # ι := by simp
/-- The rank of the direct sum is the sum of the ranks. -/
@[simp] lemma rank_direct_sum {ι : Type v} (M : ι → Type w) [Π (i : ι), add_comm_group (M i)]
[Π (i : ι), module R (M i)] [Π (i : ι), module.free R (M i)] :
module.rank R (⨁ i, M i) = cardinal.sum (λ i, module.rank R (M i)) :=
begin
let B := λ i, choose_basis R (M i),
let b : basis _ R (⨁ i, M i) := dfinsupp.basis (λ i, B i),
simp [← b.mk_eq_rank'', λ i, (B i).mk_eq_rank''],
end
/-- If `m` and `n` are `fintype`, the rank of `m × n` matrices is `(# m).lift * (# n).lift`. -/
@[simp] lemma rank_matrix (m : Type v) (n : Type w) [finite m] [finite n] :
module.rank R (matrix m n R) = (lift.{(max v w u) v} (# m)) * (lift.{(max v w u) w} (# n)) :=
begin
casesI nonempty_fintype m,
casesI nonempty_fintype n,
have h := (matrix.std_basis R m n).mk_eq_rank,
rw [← lift_lift.{(max v w u) (max v w)}, lift_inj] at h,
simpa using h.symm,
end
/-- If `m` and `n` are `fintype` that lie in the same universe, the rank of `m × n` matrices is
`(# n * # m).lift`. -/
@[simp] lemma rank_matrix' (m n : Type v) [finite m] [finite n] :
module.rank R (matrix m n R) = (# m * # n).lift :=
by rw [rank_matrix, lift_mul, lift_umax]
/-- If `m` and `n` are `fintype` that lie in the same universe as `R`, the rank of `m × n` matrices
is `# m * # n`. -/
@[simp] lemma rank_matrix'' (m n : Type u) [finite m] [finite n] :
module.rank R (matrix m n R) = # m * # n := by simp
end ring
section comm_ring
variables [comm_ring R] [strong_rank_condition R]
variables [add_comm_group M] [module R M] [module.free R M]
variables [add_comm_group N] [module R N] [module.free R N]
open module.free
/-- The rank of `M ⊗[R] N` is `(module.rank R M).lift * (module.rank R N).lift`. -/
@[simp] lemma rank_tensor_product : module.rank R (M ⊗[R] N) = lift.{w v} (module.rank R M) *
lift.{v w} (module.rank R N) :=
begin
obtain ⟨⟨_, bM⟩⟩ := module.free.exists_basis R M,
obtain ⟨⟨_, bN⟩⟩ := module.free.exists_basis R N,
rw [← bM.mk_eq_rank'', ← bN.mk_eq_rank'', ← (bM.tensor_product bN).mk_eq_rank'', cardinal.mk_prod]
end
/-- If `M` and `N` lie in the same universe, the rank of `M ⊗[R] N` is
`(module.rank R M) * (module.rank R N)`. -/
lemma rank_tensor_product' (N : Type v) [add_comm_group N] [module R N] [module.free R N] :
module.rank R (M ⊗[R] N) = (module.rank R M) * (module.rank R N) := by simp
end comm_ring
|
257f264528e109a6ef240d5eb368a716c224a9cc | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/polynomial/integral_normalization.lean | e332b1b4ab84ddc60a6743e2e7fd8e01eaaff630 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,010 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.polynomial.algebra_map
import Mathlib.data.polynomial.monic
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# Theory of monic polynomials
We define `integral_normalization`, which relate arbitrary polynomials to monic ones.
-/
namespace polynomial
/-- If `f : polynomial R` is a nonzero polynomial with root `z`, `integral_normalization f` is
a monic polynomial with root `leading_coeff f * z`.
Moreover, `integral_normalization 0 = 0`.
-/
def integral_normalization {R : Type u} [semiring R] (f : polynomial R) : polynomial R :=
finsupp.on_finset (finsupp.support f)
(fun (i : ℕ) => ite (degree f = ↑i) 1 (coeff f i * leading_coeff f ^ (nat_degree f - 1 - i))) sorry
theorem integral_normalization_coeff_degree {R : Type u} [semiring R] {f : polynomial R} {i : ℕ} (hi : degree f = ↑i) : coeff (integral_normalization f) i = 1 :=
if_pos hi
theorem integral_normalization_coeff_nat_degree {R : Type u} [semiring R] {f : polynomial R} (hf : f ≠ 0) : coeff (integral_normalization f) (nat_degree f) = 1 :=
integral_normalization_coeff_degree (degree_eq_nat_degree hf)
theorem integral_normalization_coeff_ne_degree {R : Type u} [semiring R] {f : polynomial R} {i : ℕ} (hi : degree f ≠ ↑i) : coeff (integral_normalization f) i = coeff f i * leading_coeff f ^ (nat_degree f - 1 - i) :=
if_neg hi
theorem integral_normalization_coeff_ne_nat_degree {R : Type u} [semiring R] {f : polynomial R} {i : ℕ} (hi : i ≠ nat_degree f) : coeff (integral_normalization f) i = coeff f i * leading_coeff f ^ (nat_degree f - 1 - i) :=
integral_normalization_coeff_ne_degree (degree_ne_of_nat_degree_ne (ne.symm hi))
theorem monic_integral_normalization {R : Type u} [semiring R] {f : polynomial R} (hf : f ≠ 0) : monic (integral_normalization f) := sorry
@[simp] theorem support_integral_normalization {R : Type u} [integral_domain R] {f : polynomial R} (hf : f ≠ 0) : finsupp.support (integral_normalization f) = finsupp.support f := sorry
theorem integral_normalization_eval₂_eq_zero {R : Type u} {S : Type v} [integral_domain R] [comm_ring S] {p : polynomial R} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), coe_fn f x = 0 → x = 0) : eval₂ f (z * coe_fn f (leading_coeff p)) (integral_normalization p) = 0 := sorry
theorem integral_normalization_aeval_eq_zero {R : Type u} {S : Type v} [integral_domain R] [comm_ring S] [algebra R S] {f : polynomial R} (hf : f ≠ 0) {z : S} (hz : coe_fn (aeval z) f = 0) (inj : ∀ (x : R), coe_fn (algebra_map R S) x = 0 → x = 0) : coe_fn (aeval (z * coe_fn (algebra_map R S) (leading_coeff f))) (integral_normalization f) = 0 :=
integral_normalization_eval₂_eq_zero hf (algebra_map R S) hz inj
|
c53039814299ca72c00e55fb10c14b508b62d632 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/topology/metric_space/gromov_hausdorff.lean | 97bbc9eee0ab26d8183e9238b4852b9726d928c1 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 56,092 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
The Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry.
We introduces the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces X and Y, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of X and Y in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of ℓ^∞(ℝ) up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in ℓ^∞(ℝ). We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into ℓ^∞(ℝ), through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
import topology.metric_space.closeds set_theory.cardinal topology.metric_space.gromov_hausdorff_realized
topology.metric_space.completion
noncomputable theory
local attribute [instance, priority 0] classical.prop_decidable
universes u v w
open classical lattice set function topological_space filter metric quotient
open bounded_continuous_function nat Kuratowski_embedding
open sum (inl inr)
set_option class.instance_max_depth 50
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of ℓ^∞(ℝ) by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to GH_space. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λx y, nonempty (x.val ≃ᵢ y.val)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λx, ⟨isometric.refl _⟩, λx y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to GH_space -/
definition to_GH_space (α : Type u) [metric_space α] [compact_space α] [nonempty α] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding α⟧
/-- A metric space representative of any abstract point in GH_space -/
definition GH_space.rep (p : GH_space) : Type := (quot.out p).val
lemma eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [nonempty α] {p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space α ↔ ∃Ψ : α → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val :=
begin
simp only [to_GH_space, quotient.eq],
split,
{ assume h,
rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding_isometry α).isometric_on_range.trans e,
use λx, f x,
split,
{ apply f.isometry.comp isometry_subtype_val },
{ rw [range_comp, f.range_coe, set.image_univ, set.range_coe_subtype] } },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding_isometry α).isometric_on_range.symm.trans
isomΨ.isometric_on_range).symm,
have E : (range Ψ) ≃ᵢ (nonempty_compacts.Kuratowski_embedding α).val = (p.val ≃ᵢ range (Kuratowski_embedding α)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
have g := cast E f,
exact ⟨g⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val :=
begin
refine eq_to_GH_space_iff.2 ⟨((λx, x) : p.val → ℓ_infty_ℝ), _, subtype.val_range⟩,
apply isometry_subtype_val
end
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) :=
by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) :=
by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) :=
by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p :=
begin
change to_GH_space (quot.out p).val = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in GH_space if and only if they are isometric -/
lemma to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type u} [metric_space β] [compact_space β] [nonempty β] :
to_GH_space α = to_GH_space β ↔ nonempty (α ≃ᵢ β) :=
⟨begin
simp only [to_GH_space, quotient.eq],
assume h,
rcases h with e,
have I : ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val)
= ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have e' := cast I e,
have f := (Kuratowski_embedding_isometry α).isometric_on_range,
have g := (Kuratowski_embedding_isometry β).isometric_on_range.symm,
have h := (f.trans e').trans g,
exact ⟨h⟩
end,
begin
rintros ⟨e⟩,
simp only [to_GH_space, quotient.eq],
have f := (Kuratowski_embedding_isometry α).isometric_on_range.symm,
have g := (Kuratowski_embedding_isometry β).isometric_on_range,
have h := (f.trans e).trans g,
have I : ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))) =
((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have h' := cast I h,
exact ⟨h'⟩
end⟩
/-- Distance on GH_space : the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in ℓ^∞(ℝ), but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λx y, Inf ((λp : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) ''
(set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})) }
def GH_dist (α : Type u) (β : Type v) [metric_space α] [nonempty α] [compact_space α]
[metric_space β] [nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β]
{γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist α β ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed γ in ℓ^∞(ℝ), to say that the Hausdorff distance is realized
in ℓ^∞(ℝ) and therefore bounded below by the Gromov-Hausdorff-distance. However, γ is not
separable in general. We restrict to the union of the images of α and β in γ, which is
separable and therefore embeddable in ℓ^∞(ℝ). -/
rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
letI : inhabited α := ⟨xα⟩,
letI : inhabited β := classical.inhabited_of_nonempty (by assumption),
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : α → subtype s := λy, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : β → subtype s := λy, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λx y, ha x y,
have IΨ' : isometry Ψ' := λx y, hb x y,
have : compact s,
{ apply compact_union_of_compact,
{ rw ← image_univ,
apply compact_image compact_univ ha.continuous },
{ rw ← image_univ,
apply compact_image compact_univ hb.continuous } },
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xα⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_val) },
rw this,
-- Embed s in ℓ^∞(ℝ) through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') :=
Hausdorff_dist_image (Kuratowski_embedding_isometry _),
rw ← this,
-- Let A and B be the images of α and β under this embedding. They are in ℓ^∞(ℝ), and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨by simp, begin
rw [← range_comp, ← image_univ],
exact compact_image compact_univ
(IΦ'.continuous.comp (Kuratowski_embedding_isometry _).continuous),
end⟩⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨by simp, begin
rw [← range_comp, ← image_univ],
exact compact_image compact_univ
(IΨ'.continuous.comp (Kuratowski_embedding_isometry _).continuous),
end⟩⟩,
have Aα : ⟦A⟧ = to_GH_space α,
{ rw eq_to_GH_space_iff,
exact ⟨λx, F (Φ' x), ⟨IΦ'.comp (Kuratowski_embedding_isometry _), by rw range_comp⟩⟩ },
have Bβ : ⟦B⟧ = to_GH_space β,
{ rw eq_to_GH_space_iff,
exact ⟨λx, F (Ψ' x), ⟨IΨ'.comp (Kuratowski_embedding_isometry _), by rw range_comp⟩⟩ },
refine cInf_le ⟨0, begin simp, assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _,
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [Aα, Bβ]
end
local attribute [instance, priority 0] inhabited_of_nonempty'
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β] :
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) = GH_dist α β :=
begin
/- we only need to check the inequality ≤, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on α ⊕ β belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β →
Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β) →
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β),
{ rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
have : ∃y ∈ range Ψ, dist (Φ xα) y < diam (univ : set α) + 1 + diam (univ : set β),
{ rw Ψrange,
have : Φ xα ∈ p.val := begin rw ← Φrange, exact mem_range_self _ end,
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2)) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set α) :=
begin rw [← image_univ], apply metric.isometry.diam_image Φisom end,
have DΨ : diam (range Ψ) = diam (univ : set β) :=
begin rw [← image_univ], apply metric.isometry.diam_image Ψisom end,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xα) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set α) + (diam (univ : set α) + 1 + diam (univ : set β)) + diam (univ : set β) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) }
... = 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by ring },
let f : α ⊕ β → ℓ_infty_ℝ := λx, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (α ⊕ β) × (α ⊕ β) → ℝ := λp, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates α β,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λx y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq },
{ exact λx y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq },
{ exact λx y, dist_comm _ _ },
{ exact λx y z, dist_triangle _ _ _ },
{ exact λx y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀z : α ⊕ β, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact bounded_of_compact (compact_union_of_compact p.2.2 q.2.2),
end
... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λr hr, _)),
have I1 : ∀x : α, infi (λy:β, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2))
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc infi (λy:β, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux1 0)
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀y : β, infi (λx:α, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2))
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc infi (λx:α, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux2 0)
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp [HD, csupr_le I1, csupr_le I2] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β →
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq,
by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD (candidates_b_dist α β) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set α) + 1 + diam (univ : set β) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ rw ne_empty_iff_exists_mem,
simp only [set.mem_image, nonempty_of_inhabited, set.mem_set_of_eq, prod.exists],
existsi [Hausdorff_dist (nonempty_compacts.Kuratowski_embedding α).val (nonempty_compacts.Kuratowski_embedding β).val,
nonempty_compacts.Kuratowski_embedding α, nonempty_compacts.Kuratowski_embedding β],
simp [to_GH_space, -quotient.eq] },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl α β) (isometry_optimal_GH_injr α β) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in ℓ^∞(ℝ), by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [nonempty α]
(β : Type v) [metric_space β] [compact_space β] [nonempty β] :
∃Φ : α → ℓ_infty_ℝ, ∃Ψ : β → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist α β = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling α β),
let Φ := F ∘ optimal_GH_injl α β,
let Ψ := F ∘ optimal_GH_injr α β,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact isometry.comp (isometry_optimal_GH_injl α β) (Kuratowski_embedding_isometry _) },
{ exact isometry.comp (isometry_optimal_GH_injr α β) (Kuratowski_embedding_isometry _) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr α β),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding_isometry _)).symm },
end
-- without the next two lines, { exact closed_of_compact (range Φ) hΦ } in the next
-- proof is very slow, as the t2_space instance is very hard to find
local attribute [instance, priority 0] orderable_topology.t2_space
local attribute [instance, priority 0] ordered_topology.to_t2_space
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance GH_space_metric_space : metric_space GH_space :=
{ dist_self := λx, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp, existsi [y, y], simpa } },
{ apply le_cInf,
{ simp only [set.image_eq_empty, ne.def],
apply ne_empty_iff_exists_mem.2,
existsi (⟨y, y⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simpa },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λx y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) :=
by { congr, funext, simp, rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, prod.swap, image_swap_prod],
end,
eq_of_dist_eq_zero := λx y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : compact (range Φ) :=
by { rw [← image_univ], exact compact_image compact_univ Φisom.continuous },
have hΨ : compact (range Ψ) :=
by { rw [← image_univ], exact compact_image compact_univ Ψisom.continuous },
apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm),
{ exact closed_of_compact (range Φ) hΦ },
{ exact closed_of_compact (range Ψ) hΨ },
{ exact Hausdorff_edist_ne_top_of_ne_empty_of_bounded (by simp [-nonempty_subtype])
(by simp [-nonempty_subtype]) (bounded_of_compact hΦ) (bounded_of_compact hΨ) } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometric_on_range.symm,
have e := Φisom.isometric_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric],
exact ⟨e⟩
end,
dist_triangle := λx y z, begin
/- To show the triangular inequality between X, Y and Z, realize an optimal coupling
between X and Y in a space γ1, and an optimal coupling between Y and Z in a space γ2. Then,
glue these metric spaces along Y. We get a new space γ in which X and Y are optimally coupled,
as well as Y and Z. Apply the triangle inequality for the Hausdorff distance in γ to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) :=
to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
(isometry.comp (isometry_optimal_GH_injl X Y) (to_glue_l_isometry hΦ hΨ))
(isometry.comp (isometry_optimal_GH_injr Y Z) (to_glue_r_isometry hΦ hΨ))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_ne_empty_of_bounded
(by simp [-nonempty_subtype]) (by simp [-nonempty_subtype]) _ _),
{ rw [← image_univ],
exact bounded_of_compact (compact_image compact_univ (isometry.continuous
(isometry.comp (isometry_optimal_GH_injl X Y) (to_glue_l_isometry hΦ hΨ)))) },
{ rw [← image_univ],
exact bounded_of_compact (compact_image compact_univ (isometry.continuous
(isometry.comp (isometry_optimal_GH_injr X Y) (to_glue_l_isometry hΦ hΨ)))) }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [eq.symm range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to GH_space. We register this
in the topological_space namespace to take advantage of the notation p.to_GH_space -/
definition topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α]
(p : nonempty_compacts α) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {α : Type u} [metric_space α]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts α) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (subtype.val : p.val → α) := isometry_subtype_val,
have hb : isometry (subtype.val : q.val → α) := isometry_subtype_val,
have A : dist p q = Hausdorff_dist p.val q.val := rfl,
have I : p.val = range (subtype.val : p.val → α), by simp,
have J : q.val = range (subtype.val : q.val → α), by simp,
rw [I, J] at A,
rw A,
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) :=
⟨zero_le_one, by { simp, exact GH_dist_le_nonempty_compacts_dist } ⟩
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) :=
to_GH_space_lipschitz.to_continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to ε2, then their
Gromov-Hausdorff distance is bounded by ε2 / 2. More generally, if there are subsets which are
ε1-dense and ε3-dense in two spaces, and isometric up to ε2, then the Gromov-Hausdorff distance
between the spaces is bounded by ε1 + ε2/2 + ε3. For this, we construct a suitable coupling between
the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β]
/-- If there are subsets which are ε1-dense and ε3-dense in two spaces, and
isometric up to ε2, then the Gromov-Hausdorff distance between the spaces is bounded by
ε1 + ε2/2 + ε3. -/
theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε1 ε2 ε3 : ℝ}
(hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε1) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε3)
(H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε2) :
GH_dist α β ≤ ε1 + ε2 / 2 + ε3 :=
begin
refine real.le_of_forall_epsilon_le (λδ δ0, _),
rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
rcases hs xα with ⟨xs, hxs, Dxs⟩,
have sne : s ≠ ∅ := ne_empty_of_mem hxs,
letI : nonempty (subtype s) := ⟨⟨xs, hxs⟩⟩,
have : 0 ≤ ε2 := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε2/2 + δ) := λp q, calc
abs (dist p q - dist (Φ p) (Φ q)) ≤ ε2 : H p q
... ≤ 2 * (ε2/2 + δ) : by linarith,
-- glue α and β along the almost matching subsets
letI : metric_space (α ⊕ β) := glue_metric_approx (@subtype.val α s) (λx, Φ x) (ε2/2 + δ) (by linarith) this,
let Fl := @sum.inl α β,
let Fr := @sum.inr α β,
have Il : isometry Fl := isometry_emetric_iff_metric.2 (λx y, rfl),
have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λx y, rfl),
/- The proof goes as follows : the GH_dist is bounded by the Hausdorff distance of the images in the
coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances
of α and s (in the coupling or, equivalently in the original space), of s and Φ s, and of Φ s and β
(in the coupling or, equivalently, in the original space). The first term is bounded by ε1,
by ε1-density. The third one is bounded by ε3. And the middle one is bounded by ε2/2 as in the
coupling the points x and Φ x are at distance ε2/2 by construction of the coupling (in fact
ε2/2 + δ where δ is an arbitrarily small positive constant where positivity is used to ensure
that the coupling is really a metric space and not a premetric space on α ⊕ β). -/
have : GH_dist α β ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := bounded_of_compact (compact_range Il.continuous),
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_ne_empty_of_bounded (by simpa) (by simpa)
B (bounded.subset (image_subset_range _ _) B)) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := bounded_of_compact (compact_range Ir.continuous),
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_ne_empty_of_bounded
(by simpa [-nonempty_subtype]) (by simpa) (bounded.subset (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε1,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε1 := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λx hx, hs x)
(λx hx, ⟨x, mem_univ _, by simpa⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε2/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε2/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε2/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε3,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty β with ⟨xβ, _⟩,
rcases hs' xβ with ⟨xs', Dxs'⟩,
have : 0 ≤ ε3 := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λx hx, ⟨x, mem_univ _, by simpa⟩) (λx _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
lemma second_countable : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λδ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀p:GH_space, ∃s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λp, by simpa using finite_cover_balls_of_compact (@compact_univ (p.rep) _ _ _) εpos,
-- for each p, s p is a finite ε-dense subset of p (or rather the metric space
-- p.rep representing p)
choose s hs using this,
have : ∀p:GH_space, ∀t:set (p.rep), finite t → ∃n:ℕ, ∃e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
rcases fintype.exists_equiv_fin t with ⟨n, hn⟩,
rcases hn with e,
exact ⟨n, e, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset s p of p.rep, called N p
let N := λp:GH_space, N p (s p) (hs p).1,
-- equiv from s p, a nice finite subset of p.rep, to fin (N p), called E p
let E := λp:GH_space, e p (s p) (hs p).1,
-- A function F associating to p ∈ GH_space the data of all distances of points
-- in the ε-dense set s p.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λp, ⟨N p, λa b, floor (ε⁻¹ * dist ((E p).inv_fun a) ((E p).inv_fun b))⟩,
refine ⟨_, by apply_instance, F, λp q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
p and q with F p = F q are at distance ≤ δ.
For this, we construct a map Φ from s p ⊆ p.rep (representing p)
to q.rep (representing q) which is almost an isometry on s p, and
with image s q. For this, we compose the identification of s p with fin (N p)
and the inverse of the identification of s q with fin (N q). Together with
the fact that N p = N q, this constructs Ψ between s p and s q, and then
composing with the canonical inclusion we get Φ. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λx, (E q).inv_fun (fin.cast Npq ((E p).to_fun x)),
let Φ : s p → q.rep := λx, Ψ x,
-- Use the almost isometry Φ to show that p.rep and q.rep
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, s p is ε-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, s q is ε-dense, and it is the range of Φ
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩,
let i := ((E q).to_fun ⟨y, ys⟩).1,
let hi := ((E q).to_fun ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q).to_fun ⟨y, ys⟩, by rw fin.ext_iff,
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).inv_fun ⟨i, hip⟩,
use z,
have C1 : (E p).to_fun z = ⟨i, hip⟩ := (E p).right_inv ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).inv_fun ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).left_inv ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between x and y is encoded in F p, and the distance between
Φ x and Φ y (two points of s q) is encoded in F q, all this up to ε.
As F p = F q, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce i, that codes both x and Φ x in fin (N p) = fin (N q)
let i := ((E p).to_fun x).1,
have hip : i < N p := ((E p).to_fun x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q).to_fun (Ψ x)).1, by { simp [Ψ, (E q).right_inv _] },
-- introduce j, that codes both y and Φ y in fin (N p) = fin (N q)
let j := ((E p).to_fun y).1,
have hjp : j < N p := ((E p).to_fun y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q).to_fun (Ψ y)).1, by { simp [Ψ, (E q).right_inv _] },
-- Express dist x y in terms of F p
have : (F p).2 ((E p).to_fun x) ((E p).to_fun y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).left_inv _],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl },
-- Express dist (Φ x) (Φ y) in terms of F q
have : (F q).2 ((E q).to_fun (Ψ x)) ((E q).to_fun (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).left_inv _],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] },
-- use the equality between F p and F q to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant f
-- then subst
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to ε, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp [ε], ring }
end
/-- Compactness criterion : a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all ε the number of balls of radius ε required
to cover the space is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (nhds 0))
(hdiam : ∀p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀p ∈ t, ∀n:ℕ, ∃s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let δ>0, and ε = δ/5. For each p, we construct a finite subset s p of p, which
is ε-dense and has cardinality at most K n. Encoding the mutual distances of points in s p,
up to ε, we will get a map F associating to p finitely many data, and making it possible to
reconstruct p up to ε. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λδ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose n for which ε < u n
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n (le_refl _),
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset s p of p which is ε-dense and has cardinal ≤ K n
have : ∀p:GH_space, ∃s : set (p.rep), ∃N ≤ K n, ∃E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set (p.rep)) (fin 0)),
{ rw ← fintype.card_eq, simp },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp [hp, scover] } },
choose s N hN E hs using this,
-- Define a function F taking values in a finite type and associating to p enough data
-- to reconstruct it up to ε, namely the (discretized) distances between elements of s p.
let M := (floor (ε⁻¹ * max C 0)).to_nat,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λp, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λa b, ⟨min M (floor (ε⁻¹ * dist ((E p).inv_fun a) ((E p).inv_fun b))).to_nat,
lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, by apply_instance, (λp, F p), _⟩,
-- It remains to show that if F p = F q, then p and q are ε-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λx, (E q).inv_fun (fin.cast Npq ((E p).to_fun x)),
let Φ : s p → q.rep := λx, Ψ x,
have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that s p is ε-dense in p, and s q is ε-dense in q,
-- and s p and s q are almost isometric. Then closeness follows
-- from GH_dist_le_of_approx_subsets
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, s p is ε-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, s q is ε-dense, and it is the range of Φ
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩,
let i := ((E q).to_fun ⟨y, ys⟩).1,
let hi := ((E q).to_fun ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q).to_fun ⟨y, ys⟩, by rw fin.ext_iff,
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).inv_fun ⟨i, hip⟩,
use z,
have C1 : (E p).to_fun z = ⟨i, hip⟩ := (E p).right_inv ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).inv_fun ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).left_inv ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between x and y is encoded in F p, and the distance between
Φ x and Φ y (two points of s q) is encoded in F q, all this up to ε.
As F p = F q, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce i, that codes both x and Φ x in fin (N p) = fin (N q)
let i := ((E p).to_fun x).1,
have hip : i < N p := ((E p).to_fun x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q).to_fun (Ψ x)).1, by { simp [Ψ, (E q).right_inv _] },
-- introduce j, that codes both y and Φ y in fin (N p) = fin (N q)
let j := ((E p).to_fun y).1,
have hjp : j < N p := ((E p).to_fun y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q).to_fun (Ψ y)).1, by { simp [Ψ, (E q).right_inv _] },
-- Express dist x y in terms of F p
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p).to_fun x) ((E p).to_fun y)).1 :
by { congr; apply (fin.ext_iff _ _).2; refl }
... = min M (floor (ε⁻¹ * dist x y)).to_nat :
by simp only [F, (E p).left_inv _]
... = (floor (ε⁻¹ * dist x y)).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos εpos)),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express dist (Φ x) (Φ y) in terms of F q
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q).to_fun (Ψ x)) ((E q).to_fun (Ψ y))).1 :
by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }
... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
by simp only [F, (E q).left_inv _]
... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos εpos)),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between F p and F q to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant f
-- then subst
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
{ rw [Ap, Aq] at this,
have D : 0 ≤ floor (ε⁻¹ * dist x y) :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos εpos)) dist_nonneg),
have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] },
-- deduce that the distances coincide up to ε, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp [ε], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀n, metric_space (X n)] [∀n, compact_space (X n)] [∀n, nonempty (X n)]
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n
{ space := X 0,
metric := by apply_instance,
embed := id,
isom := λx y, rfl }
(λn a, by letI : metric_space a.space := a.metric; exact
{ space := glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)),
metric := metric.metric_space_glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)),
embed := (to_glue_r a.isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injr (X n) (X n.succ)),
isom := (isometry_optimal_GH_injr (X n) (X n.succ)).comp (to_glue_r_isometry _ _) })
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space (GH_space) :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply _root_.pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance 1/2^n of each other
refine metric.complete_of_convergent_controlled_sequences (λn, (1/2)^n) this (λu hu, _),
-- X n is a representative of u n
let X := λn, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces Y n
let Y := aux_gluing X,
letI : ∀n, metric_space (Y n).space := λn, (Y n).metric,
have E : ∀n:ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space :=
λn, by { simp [Y, aux_gluing], refl },
let c := λn, cast (E n),
have ic : ∀n, isometry (c n) := λn x y, rfl,
-- there is a canonical embedding of Y n in Y (n+1), by construction
let f : Πn, (Y n).space → (Y n.succ).space :=
λn, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))),
have I : ∀n, isometry (f n),
{ assume n,
apply isometry.comp,
{ apply to_glue_l_isometry },
{ assume x y, refl } },
-- consider the inductive limit Z0 of the Y n, and then its completion Z
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let X2 n be the image of X n in the space Z
let X2 := λn, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
apply isometry.comp _ completion.coe_isometry,
apply isometry.comp (Y n).isom _,
apply to_inductive_limit_isometry },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by 1/2^n
have D2 : ∀n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply isometry.comp _ completion.coe_isometry,
apply ((to_glue_r_isometry _ _).comp (ic n)).comp,
apply to_inductive_limit_isometry } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λn, ⟨X2 n,
⟨by { simp only [X2, set.range_eq_empty, not_not, ne.def], apply_instance },
compact_range (isom n).continuous ⟩⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by (1/2)^n
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λn, (X3 n).to_GH_space) at_top (nhds L.to_GH_space) :=
tendsto.comp hL (to_GH_space_continuous.tendsto _),
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometric],
exact ⟨(isom n).isometric_on_range.symm⟩
},
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.