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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fdb615cfc72a5790aa49a68f4095553aa6d72bcf | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/uniform_space/matrix.lean | 476be2d9ca9d335bcfb2a93c6855360b0edaf98b | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,337 | lean | /-
Copyright (c) 2022 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser, Heather Macbeth
-/
import topology.uniform_space.pi
import data.matrix.basic
/-!
# Uniform space structure on matrices
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
open_locale uniformity topology
variables (m n 𝕜 : Type*) [uniform_space 𝕜]
namespace matrix
instance : uniform_space (matrix m n 𝕜) :=
(by apply_instance : uniform_space (m → n → 𝕜))
lemma uniformity :
𝓤 (matrix m n 𝕜) = ⨅ (i : m) (j : n), (𝓤 𝕜).comap (λ a, (a.1 i j, a.2 i j)) :=
begin
erw [Pi.uniformity, Pi.uniformity],
simp_rw [filter.comap_infi, filter.comap_comap],
refl,
end
lemma uniform_continuous {β : Type*} [uniform_space β] {f : β → matrix m n 𝕜} :
uniform_continuous f ↔ ∀ i j, uniform_continuous (λ x, f x i j) :=
by simp only [uniform_continuous, matrix.uniformity, filter.tendsto_infi, filter.tendsto_comap_iff]
instance [complete_space 𝕜] : complete_space (matrix m n 𝕜) :=
(by apply_instance : complete_space (m → n → 𝕜))
instance [separated_space 𝕜] : separated_space (matrix m n 𝕜) :=
(by apply_instance : separated_space (m → n → 𝕜))
end matrix
|
90b5e439f182421a14e0cf352f56e9e09f1a428f | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/LCNF/Closure.lean | 788e99f61b6e3df33e55310a8850f35e52cdad4f | [
"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,712 | 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.ForEachExprWhere
import Lean.Compiler.LCNF.CompilerM
namespace Lean.Compiler.LCNF
namespace Closure
/-!
# Dependency collector for code specialization and lambda lifting.
During code specialization and lambda lifting, we have code `C` containing free variables. These free variables
are in a scope, and we say we are computing `C`'s closure.
This module is used to compute the closure.
-/
structure Context where
/--
`inScope x` returns `true` if `x` is a variable that is not in `C`.
-/
inScope : FVarId → Bool
/--
If `abstract x` returns `true`, we convert `x` into a closure parameter. Otherwise,
we collect the dependecies in the `let`/`fun`-declaration too, and include the declaration in the closure.
Remark: the lambda lifting pass abstracts all `let`/`fun`-declarations.
-/
abstract : FVarId → Bool
/--
State for the `ClosureM` monad.
-/
structure State where
/--
Set of already visited free variables.
-/
visited : FVarIdSet := {}
/--
Free variables that must become new parameters of the code being specialized.
-/
params : Array Param := #[]
/--
Let-declarations and local function declarations that are going to be "copied" to the code
being processed. For example, when this module is used in the code specializer, the let-declarations
often contain the instance values. In the current specialization heuristic all let-declarations are ground values
(i.e., they do not contain free-variables).
However, local function declarations may contain free variables.
All customers of this module try to avoid work duplication. If a let-declaration is a ground value,
it most likely will be computed during compilation time, and work duplication is not an issue.
-/
decls : Array CodeDecl := #[]
/--
Monad for implementing the dependency collector.
-/
abbrev ClosureM := ReaderT Context $ StateRefT State CompilerM
/--
Mark a free variable as already visited.
We perform a topological sort over the dependencies.
-/
def markVisited (fvarId : FVarId) : ClosureM Unit :=
modify fun s => { s with visited := s.visited.insert fvarId }
mutual
/--
Collect dependencies in parameters. We need this because parameters may
contain other type parameters.
-/
partial def collectParams (params : Array Param) : ClosureM Unit :=
params.forM (collectType ·.type)
partial def collectArg (arg : Arg) : ClosureM Unit :=
match arg with
| .erased => return ()
| .type e => collectType e
| .fvar fvarId => collectFVar fvarId
partial def collectLetValue (e : LetValue) : ClosureM Unit := do
match e with
| .erased | .value .. => return ()
| .proj _ _ fvarId => collectFVar fvarId
| .const _ _ args => args.forM collectArg
| .fvar fvarId args => collectFVar fvarId; args.forM collectArg
/--
Collect dependencies in the given code. We need this function to be able
to collect dependencies in a local function declaration.
-/
partial def collectCode (c : Code) : ClosureM Unit := do
match c with
| .let decl k => collectType decl.type; collectLetValue decl.value; collectCode k
| .fun decl k | .jp decl k => collectFunDecl decl; collectCode k
| .cases c =>
collectType c.resultType
collectFVar c.discr
c.alts.forM fun alt => do
match alt with
| .default k => collectCode k
| .alt _ ps k => collectParams ps; collectCode k
| .jmp _ args => args.forM collectArg
| .unreach type => collectType type
| .return fvarId => collectFVar fvarId
/-- Collect dependencies of a local function declaration. -/
partial def collectFunDecl (decl : FunDecl) : ClosureM Unit := do
collectType decl.type
collectParams decl.params
collectCode decl.value
/--
Process the given free variable.
If it has not already been visited and is in scope, we collect its dependencies.
-/
partial def collectFVar (fvarId : FVarId) : ClosureM Unit := do
unless (← get).visited.contains fvarId do
markVisited fvarId
if (← read).inScope fvarId then
/- We only collect the variables in the scope of the function application being specialized. -/
if let some funDecl ← findFunDecl? fvarId then
if (← read).abstract funDecl.fvarId then
modify fun s => { s with params := s.params.push <| { funDecl with borrow := false } }
else
collectFunDecl funDecl
modify fun s => { s with decls := s.decls.push <| .fun funDecl }
else if let some param ← findParam? fvarId then
collectType param.type
modify fun s => { s with params := s.params.push param }
else if let some letDecl ← findLetDecl? fvarId then
collectType letDecl.type
if (← read).abstract letDecl.fvarId then
modify fun s => { s with params := s.params.push <| { letDecl with borrow := false } }
else
collectLetValue letDecl.value
modify fun s => { s with decls := s.decls.push <| .let letDecl }
else
unreachable!
/-- Collect dependencies of the given expression. -/
partial def collectType (type : Expr) : ClosureM Unit := do
type.forEachWhere Expr.isFVar fun e => collectFVar e.fvarId!
end
def run (x : ClosureM α) (inScope : FVarId → Bool) (abstract : FVarId → Bool := fun _ => true) : CompilerM (α × Array Param × Array CodeDecl) := do
let (a, s) ← x { inScope, abstract } |>.run {}
return (a, s.params, s.decls)
end Closure
end Lean.Compiler.LCNF |
e03fb0e16eed6ddd25a7ff0179bdd154266d5772 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/real/irrational.lean | 47f2dbefdfa0e162b293ff45f4fd43153d8fe156 | [
"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,623 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov
-/
import data.real.sqrt
import data.rat.sqrt
import ring_theory.int.basic
import data.polynomial.eval
import data.polynomial.degree
import tactic.interval_cases
import ring_theory.algebraic
/-!
# Irrational real numbers
In this file we define a predicate `irrational` on `ℝ`, prove that the `n`-th root of an integer
number is irrational if it is not integer, and that `sqrt q` is irrational if and only if
`rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q`.
We also provide dot-style constructors like `irrational.add_rat`, `irrational.rat_sub` etc.
-/
open rat real multiplicity
/-- A real number is irrational if it is not equal to any rational number. -/
def irrational (x : ℝ) := x ∉ set.range (coe : ℚ → ℝ)
lemma irrational_iff_ne_rational (x : ℝ) : irrational x ↔ ∀ a b : ℤ, x ≠ a / b :=
by simp only [irrational, rat.forall, cast_mk, not_exists, set.mem_range, cast_coe_int, cast_div,
eq_comm]
/-- A transcendental real number is irrational. -/
lemma transcendental.irrational {r : ℝ} (tr : transcendental ℚ r) :
irrational r :=
by { rintro ⟨a, rfl⟩, exact tr (is_algebraic_algebra_map a) }
/-!
### Irrationality of roots of integer and rational numbers
-/
/-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then
`x` is irrational. -/
theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ)
(hxr : x ^ n = m) (hv : ¬ ∃ y : ℤ, x = y) (hnpos : 0 < n) :
irrational x :=
begin
rintros ⟨⟨N, D, P, C⟩, rfl⟩,
rw [← cast_pow] at hxr,
have c1 : ((D : ℤ) : ℝ) ≠ 0,
{ rw [int.cast_ne_zero, int.coe_nat_ne_zero], exact ne_of_gt P },
have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1,
rw [num_denom', cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2,
← int.cast_pow, ← int.cast_pow, ← int.cast_mul, int.cast_inj] at hxr,
have hdivn : ↑D ^ n ∣ N ^ n := dvd.intro_left m hxr,
rw [← int.dvd_nat_abs, ← int.coe_nat_pow, int.coe_nat_dvd, int.nat_abs_pow,
nat.pow_dvd_pow_iff hnpos] at hdivn,
have hD : D = 1 := by rw [← nat.gcd_eq_right hdivn, C.gcd_eq_one],
subst D,
refine hv ⟨N, _⟩,
rw [num_denom', int.coe_nat_one, mk_eq_div, int.cast_one, div_one, cast_coe_int]
end
/-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x`
is irrational. -/
theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ)
[hp : fact p.prime] (hxr : x ^ n = m)
(hv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.1.ne_one, hm⟩) % n ≠ 0) :
irrational x :=
begin
rcases nat.eq_zero_or_pos n with rfl | hnpos,
{ rw [eq_comm, pow_zero, ← int.cast_one, int.cast_inj] at hxr,
simpa [hxr, multiplicity.one_right (mt is_unit_iff_dvd_one.1
(mt int.coe_nat_dvd.1 hp.1.not_dvd_one)), nat.zero_mod] using hv },
refine irrational_nrt_of_notint_nrt _ _ hxr _ hnpos,
rintro ⟨y, rfl⟩,
rw [← int.cast_pow, int.cast_inj] at hxr, subst m,
have : y ≠ 0, { rintro rfl, rw zero_pow hnpos at hm, exact hm rfl },
erw [multiplicity.pow' (nat.prime_iff_prime_int.1 hp.1)
(finite_int_iff.2 ⟨hp.1.ne_one, this⟩), nat.mul_mod_right] at hv,
exact hv rfl
end
theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m)
(p : ℕ) [hp : fact p.prime]
(Hpv : (multiplicity (p : ℤ) m).get
(finite_int_iff.2 ⟨hp.1.ne_one, (ne_of_lt hm).symm⟩) % 2 = 1) :
irrational (sqrt m) :=
@irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (ne.symm (ne_of_lt hm)) p hp
(sq_sqrt (int.cast_nonneg.2 $ le_of_lt hm))
(by rw Hpv; exact one_ne_zero)
theorem nat.prime.irrational_sqrt {p : ℕ} (hp : nat.prime p) : irrational (sqrt p) :=
@irrational_sqrt_of_multiplicity_odd p (int.coe_nat_pos.2 hp.pos) p ⟨hp⟩ $
by simp [multiplicity_self (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one) : _)];
refl
theorem irrational_sqrt_two : irrational (sqrt 2) :=
by simpa using nat.prime_two.irrational_sqrt
theorem irrational_sqrt_rat_iff (q : ℚ) : irrational (sqrt q) ↔
rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q :=
if H1 : rat.sqrt q * rat.sqrt q = q
then iff_of_false (not_not_intro ⟨rat.sqrt q,
by rw [← H1, cast_mul, sqrt_mul_self (cast_nonneg.2 $ rat.sqrt_nonneg q),
sqrt_eq, abs_of_nonneg (rat.sqrt_nonneg q)]⟩) (λ h, h.1 H1)
else if H2 : 0 ≤ q
then iff_of_true (λ ⟨r, hr⟩, H1 $ (exists_mul_self _).1 ⟨r,
by rwa [eq_comm, sqrt_eq_iff_mul_self_eq (cast_nonneg.2 H2), ← cast_mul, rat.cast_inj] at hr;
rw [← hr]; exact real.sqrt_nonneg _⟩) ⟨H1, H2⟩
else iff_of_false (not_not_intro ⟨0,
by rw cast_zero; exact (sqrt_eq_zero_of_nonpos (rat.cast_nonpos.2 $ le_of_not_le H2)).symm⟩)
(λ h, H2 h.2)
instance (q : ℚ) : decidable (irrational (sqrt q)) :=
decidable_of_iff' _ (irrational_sqrt_rat_iff q)
/-!
### Adding/subtracting/multiplying by rational numbers
-/
lemma rat.not_irrational (q : ℚ) : ¬irrational q := λ h, h ⟨q, rfl⟩
namespace irrational
variables (q : ℚ) {x y : ℝ}
open_locale classical
theorem add_cases : irrational (x + y) → irrational x ∨ irrational y :=
begin
delta irrational,
contrapose!,
rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩,
exact ⟨rx + ry, cast_add rx ry⟩
end
theorem of_rat_add (h : irrational (q + x)) : irrational x :=
h.add_cases.elim (λ h, absurd h q.not_irrational) id
theorem rat_add (h : irrational x) : irrational (q + x) :=
of_rat_add (-q) $ by rwa [cast_neg, neg_add_cancel_left]
theorem of_add_rat : irrational (x + q) → irrational x :=
add_comm ↑q x ▸ of_rat_add q
theorem add_rat (h : irrational x) : irrational (x + q) :=
add_comm ↑q x ▸ h.rat_add q
theorem of_neg (h : irrational (-x)) : irrational x :=
λ ⟨q, hx⟩, h ⟨-q, by rw [cast_neg, hx]⟩
protected theorem neg (h : irrational x) : irrational (-x) :=
of_neg $ by rwa neg_neg
theorem sub_rat (h : irrational x) : irrational (x - q) :=
by simpa only [sub_eq_add_neg, cast_neg] using h.add_rat (-q)
theorem rat_sub (h : irrational x) : irrational (q - x) :=
by simpa only [sub_eq_add_neg] using h.neg.rat_add q
theorem of_sub_rat (h : irrational (x - q)) : irrational x :=
(of_add_rat (-q) $ by simpa only [cast_neg, sub_eq_add_neg] using h)
theorem of_rat_sub (h : irrational (q - x)) : irrational x :=
of_neg (of_rat_add q (by simpa only [sub_eq_add_neg] using h))
theorem mul_cases : irrational (x * y) → irrational x ∨ irrational y :=
begin
delta irrational,
contrapose!,
rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩,
exact ⟨rx * ry, cast_mul rx ry⟩
end
theorem of_mul_rat (h : irrational (x * q)) : irrational x :=
h.mul_cases.elim id (λ h, absurd h q.not_irrational)
theorem mul_rat (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (x * q) :=
of_mul_rat q⁻¹ $ by rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one]
theorem of_rat_mul : irrational (q * x) → irrational x :=
mul_comm x q ▸ of_mul_rat q
theorem rat_mul (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (q * x) :=
mul_comm x q ▸ h.mul_rat hq
theorem of_mul_self (h : irrational (x * x)) : irrational x :=
h.mul_cases.elim id id
theorem of_inv (h : irrational x⁻¹) : irrational x :=
λ ⟨q, hq⟩, h $ hq ▸ ⟨q⁻¹, q.cast_inv⟩
protected theorem inv (h : irrational x) : irrational x⁻¹ :=
of_inv $ by rwa inv_inv'
theorem div_cases (h : irrational (x / y)) : irrational x ∨ irrational y :=
h.mul_cases.imp id of_inv
theorem of_rat_div (h : irrational (q / x)) : irrational x :=
(h.of_rat_mul q).of_inv
theorem of_one_div (h : irrational (1 / x)) : irrational x :=
of_rat_div 1 $ by rwa [cast_one]
theorem of_pow : ∀ n : ℕ, irrational (x^n) → irrational x
| 0 := λ h, by { rw pow_zero at h, exact (h ⟨1, cast_one⟩).elim }
| (n+1) := λ h, by { rw pow_succ at h, exact h.mul_cases.elim id (of_pow n) }
theorem of_fpow : ∀ m : ℤ, irrational (x^m) → irrational x
| (n:ℕ) := of_pow n
| -[1+n] := λ h, by { rw gpow_neg_succ_of_nat at h, exact h.of_inv.of_pow _ }
end irrational
section polynomial
open polynomial
variables (x : ℝ) (p : polynomial ℤ)
lemma one_lt_nat_degree_of_irrational_root (hx : irrational x) (p_nonzero : p ≠ 0)
(x_is_root : aeval x p = 0) : 1 < p.nat_degree :=
begin
by_contra rid,
rcases exists_eq_X_add_C_of_nat_degree_le_one (not_lt.1 rid) with ⟨a, b, rfl⟩, clear rid,
have : (a : ℝ) * x = -b, by simpa [eq_neg_iff_add_eq_zero] using x_is_root,
rcases em (a = 0) with (rfl|ha),
{ obtain rfl : b = 0, by simpa,
simpa using p_nonzero },
{ rw [mul_comm, ← eq_div_iff_mul_eq, eq_comm] at this,
refine hx ⟨-b / a, _⟩,
assumption_mod_cast, assumption_mod_cast }
end
end polynomial
section
variables {q : ℚ} {x : ℝ}
open irrational
@[simp] theorem irrational_rat_add_iff : irrational (q + x) ↔ irrational x :=
⟨of_rat_add q, rat_add q⟩
@[simp] theorem irrational_add_rat_iff : irrational (x + q) ↔ irrational x :=
⟨of_add_rat q, add_rat q⟩
@[simp] theorem irrational_rat_sub_iff : irrational (q - x) ↔ irrational x :=
⟨of_rat_sub q, rat_sub q⟩
@[simp] theorem irrational_sub_rat_iff : irrational (x - q) ↔ irrational x :=
⟨of_sub_rat q, sub_rat q⟩
@[simp] theorem irrational_neg_iff : irrational (-x) ↔ irrational x :=
⟨of_neg, irrational.neg⟩
@[simp] theorem irrational_inv_iff : irrational x⁻¹ ↔ irrational x :=
⟨of_inv, irrational.inv⟩
end
|
f62f64793dd1b2572eea082ddd66b48dedf103bf | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/coe_univ_bug.lean | d947b33137fb4031d61bdd2eb1ecb3e78bf62170 | [
"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 | 431 | lean | open nat
def below (n : nat) : nat → Prop :=
λ i, i < n
def f {n : nat} (v : subtype (below n)) : nat :=
v + 1
universe variable u
instance pred2subtype {A : Type u} : has_coe_to_sort (A → Prop) :=
⟨Type u, (λ p : A → Prop, subtype p)⟩
instance coesubtype {A : Type u} {p : A → Prop} : has_coe (@coe_sort _ pred2subtype p) A :=
⟨λ s, subtype.elt_of s⟩
def g {n : nat} (v : below n) : nat :=
v + 1
print g
|
2382b6971d9d9dce024c59aa280b2347ca230486 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/number_theory/bernoulli.lean | dee63eb69cc3fe58f68529a84c708d5c446206cd | [
"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 | 16,861 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Kevin Buzzard
-/
import algebra.big_operators.nat_antidiagonal
import algebra.geom_sum
import data.fintype.card
import ring_theory.power_series.well_known
import tactic.field_simp
/-!
# Bernoulli numbers
The Bernoulli numbers are a sequence of rational numbers that frequently show up in
number theory.
## Mathematical overview
The Bernoulli numbers $(B_0, B_1, B_2, \ldots)=(1, -1/2, 1/6, 0, -1/30, \ldots)$ are
a sequence of rational numbers. They show up in the formula for the sums of $k$th
powers. They are related to the Taylor series expansions of $x/\tan(x)$ and
of $\coth(x)$, and also show up in the values that the Riemann Zeta function
takes both at both negative and positive integers (and hence in the
theory of modular forms). For example, if $1 \leq n$ is even then
$$\zeta(2n)=\sum_{t\geq1}t^{-2n}=(-1)^{n+1}\frac{(2\pi)^{2n}B_{2n}}{2(2n)!}.$$
Note however that this result is not yet formalised in Lean.
The Bernoulli numbers can be formally defined using the power series
$$\sum B_n\frac{t^n}{n!}=\frac{t}{1-e^{-t}}$$
although that happens to not be the definition in mathlib (this is an *implementation
detail* and need not concern the mathematician).
Note that $B_1=-1/2$, meaning that we are using the $B_n^-$ of
[from Wikipedia](https://en.wikipedia.org/wiki/Bernoulli_number).
## Implementation detail
The Bernoulli numbers are defined using well-founded induction, by the formula
$$B_n=1-\sum_{k\lt n}\frac{\binom{n}{k}}{n-k+1}B_k.$$
This formula is true for all $n$ and in particular $B_0=1$. Note that this is the definition
for positive Bernoulli numbers, which we call `bernoulli'`. The negative Bernoulli numbers are
then defined as `bernoulli := (-1)^n * bernoulli'`.
## Main theorems
`sum_bernoulli : ∑ k in finset.range n, (n.choose k : ℚ) * bernoulli k = 0`
-/
open_locale nat big_operators
open finset nat finset.nat power_series
variables (A : Type*) [comm_ring A] [algebra ℚ A]
/-! ### Definitions -/
/-- The Bernoulli numbers:
the $n$-th Bernoulli number $B_n$ is defined recursively via
$$B_n = 1 - \sum_{k < n} \binom{n}{k}\frac{B_k}{n+1-k}$$ -/
def bernoulli' : ℕ → ℚ :=
well_founded.fix lt_wf $
λ n bernoulli', 1 - ∑ k : fin n, n.choose k / (n - k + 1) * bernoulli' k k.2
lemma bernoulli'_def' (n : ℕ) :
bernoulli' n = 1 - ∑ k : fin n, n.choose k / (n - k + 1) * bernoulli' k :=
well_founded.fix_eq _ _ _
lemma bernoulli'_def (n : ℕ) :
bernoulli' n = 1 - ∑ k in range n, n.choose k / (n - k + 1) * bernoulli' k :=
by { rw [bernoulli'_def', ← fin.sum_univ_eq_sum_range], refl }
lemma bernoulli'_spec (n : ℕ) :
∑ k in range n.succ, (n.choose (n - k) : ℚ) / (n - k + 1) * bernoulli' k = 1 :=
begin
rw [sum_range_succ_comm, bernoulli'_def n, tsub_self],
conv in (n.choose (_ - _)) { rw choose_symm (mem_range.1 H).le },
simp only [one_mul, cast_one, sub_self, sub_add_cancel, choose_zero_right, zero_add, div_one],
end
lemma bernoulli'_spec' (n : ℕ) :
∑ k in antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli' k.1 = 1 :=
begin
refine ((sum_antidiagonal_eq_sum_range_succ_mk _ n).trans _).trans (bernoulli'_spec n),
refine sum_congr rfl (λ x hx, _),
simp only [add_tsub_cancel_of_le, mem_range_succ_iff.mp hx, cast_sub],
end
/-! ### Examples -/
section examples
@[simp] lemma bernoulli'_zero : bernoulli' 0 = 1 :=
by { rw bernoulli'_def, norm_num }
@[simp] lemma bernoulli'_one : bernoulli' 1 = 1/2 :=
by { rw bernoulli'_def, norm_num }
@[simp] lemma bernoulli'_two : bernoulli' 2 = 1/6 :=
by { rw bernoulli'_def, norm_num [sum_range_succ] }
@[simp] lemma bernoulli'_three : bernoulli' 3 = 0 :=
by { rw bernoulli'_def, norm_num [sum_range_succ] }
@[simp] lemma bernoulli'_four : bernoulli' 4 = -1/30 :=
have nat.choose 4 2 = 6 := dec_trivial, -- shrug
by { rw bernoulli'_def, norm_num [sum_range_succ, this] }
end examples
@[simp] lemma sum_bernoulli' (n : ℕ) :
∑ k in range n, (n.choose k : ℚ) * bernoulli' k = n :=
begin
cases n, { simp },
suffices : (n + 1 : ℚ) * ∑ k in range n, ↑(n.choose k) / (n - k + 1) * bernoulli' k =
∑ x in range n, ↑(n.succ.choose x) * bernoulli' x,
{ rw_mod_cast [sum_range_succ, bernoulli'_def, ← this, choose_succ_self_right], ring },
simp_rw [mul_sum, ← mul_assoc],
refine sum_congr rfl (λ k hk, _),
congr',
have : ((n - k : ℕ) : ℚ) + 1 ≠ 0 := by apply_mod_cast succ_ne_zero,
field_simp [← cast_sub (mem_range.1 hk).le, mul_comm],
rw_mod_cast [tsub_add_eq_add_tsub (mem_range.1 hk).le, choose_mul_succ_eq],
end
/-- The exponential generating function for the Bernoulli numbers `bernoulli' n`. -/
def bernoulli'_power_series := mk $ λ n, algebra_map ℚ A (bernoulli' n / n!)
theorem bernoulli'_power_series_mul_exp_sub_one :
bernoulli'_power_series A * (exp A - 1) = X * exp A :=
begin
ext n,
-- constant coefficient is a special case
cases n, { simp },
rw [bernoulli'_power_series, coeff_mul, mul_comm X, sum_antidiagonal_succ'],
suffices : ∑ p in antidiagonal n, (bernoulli' p.1 / p.1!) * ((p.2 + 1) * p.2!)⁻¹ = n!⁻¹,
{ simpa [ring_hom.map_sum] using congr_arg (algebra_map ℚ A) this },
apply eq_inv_of_mul_eq_one_left,
rw sum_mul,
convert bernoulli'_spec' n using 1,
apply sum_congr rfl,
simp_rw [mem_antidiagonal],
rintro ⟨i, j⟩ rfl,
have : (j + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero j,
have : (j + 1 : ℚ) * j! * i! ≠ 0 := by simpa [factorial_ne_zero],
have := factorial_mul_factorial_dvd_factorial_add i j,
field_simp [mul_comm _ (bernoulli' i), mul_assoc, add_choose],
rw_mod_cast [mul_comm (j + 1), mul_div_assoc, ← mul_assoc],
rw [cast_mul, cast_mul, mul_div_mul_right, cast_div_char_zero, cast_mul],
assumption',
end
/-- Odd Bernoulli numbers (greater than 1) are zero. -/
theorem bernoulli'_odd_eq_zero {n : ℕ} (h_odd : odd n) (hlt : 1 < n) : bernoulli' n = 0 :=
begin
let B := mk (λ n, bernoulli' n / n!),
suffices : (B - eval_neg_hom B) * (exp ℚ - 1) = X * (exp ℚ - 1),
{ cases mul_eq_mul_right_iff.mp this;
simp only [power_series.ext_iff, eval_neg_hom, coeff_X] at h,
{ apply eq_zero_of_neg_eq,
specialize h n,
split_ifs at h;
simp [h_odd.neg_one_pow, factorial_ne_zero, *] at * },
{ simpa using h 1 } },
have h : B * (exp ℚ - 1) = X * exp ℚ,
{ simpa [bernoulli'_power_series] using bernoulli'_power_series_mul_exp_sub_one ℚ },
rw [sub_mul, h, mul_sub X, sub_right_inj, ← neg_sub, mul_neg, neg_eq_iff_neg_eq],
suffices : eval_neg_hom (B * (exp ℚ - 1)) * exp ℚ = eval_neg_hom (X * exp ℚ) * exp ℚ,
{ simpa [mul_assoc, sub_mul, mul_comm (eval_neg_hom (exp ℚ)), exp_mul_exp_neg_eq_one, eq_comm] },
congr',
end
/-- The Bernoulli numbers are defined to be `bernoulli'` with a parity sign. -/
def bernoulli (n : ℕ) : ℚ := (-1)^n * bernoulli' n
lemma bernoulli'_eq_bernoulli (n : ℕ) : bernoulli' n = (-1)^n * bernoulli n :=
by simp [bernoulli, ← mul_assoc, ← sq, ← pow_mul, mul_comm n 2, pow_mul]
@[simp] lemma bernoulli_zero : bernoulli 0 = 1 := by simp [bernoulli]
@[simp] lemma bernoulli_one : bernoulli 1 = -1/2 :=
by norm_num [bernoulli]
theorem bernoulli_eq_bernoulli'_of_ne_one {n : ℕ} (hn : n ≠ 1) : bernoulli n = bernoulli' n :=
begin
by_cases h0 : n = 0, { simp [h0] },
rw [bernoulli, neg_one_pow_eq_pow_mod_two],
cases mod_two_eq_zero_or_one n, { simp [h] },
simp [bernoulli'_odd_eq_zero (odd_iff.mpr h) (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, hn⟩)],
end
@[simp] theorem sum_bernoulli (n : ℕ):
∑ k in range n, (n.choose k : ℚ) * bernoulli k = if n = 1 then 1 else 0 :=
begin
cases n, { simp },
cases n, { simp },
suffices : ∑ i in range n, ↑((n + 2).choose (i + 2)) * bernoulli (i + 2) = n / 2,
{ simp only [this, sum_range_succ', cast_succ, bernoulli_one, bernoulli_zero, choose_one_right,
mul_one, choose_zero_right, cast_zero, if_false, zero_add, succ_succ_ne_one], ring },
have f := sum_bernoulli' n.succ.succ,
simp_rw [sum_range_succ', bernoulli'_one, choose_one_right, cast_succ, ← eq_sub_iff_add_eq] at f,
convert f,
{ funext x, rw bernoulli_eq_bernoulli'_of_ne_one (succ_ne_zero x ∘ succ.inj) },
{ simp only [one_div, mul_one, bernoulli'_zero, cast_one, choose_zero_right, add_sub_cancel],
ring },
end
lemma bernoulli_spec' (n : ℕ) :
∑ k in antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli k.1 =
if n = 0 then 1 else 0 :=
begin
cases n, { simp },
rw if_neg (succ_ne_zero _),
-- algebra facts
have h₁ : (1, n) ∈ antidiagonal n.succ := by simp [mem_antidiagonal, add_comm],
have h₂ : (n : ℚ) + 1 ≠ 0 := by apply_mod_cast succ_ne_zero,
have h₃ : (1 + n).choose n = n + 1 := by simp [add_comm],
-- key equation: the corresponding fact for `bernoulli'`
have H := bernoulli'_spec' n.succ,
-- massage it to match the structure of the goal, then convert piece by piece
rw sum_eq_add_sum_diff_singleton h₁ at H ⊢,
apply add_eq_of_eq_sub',
convert eq_sub_of_add_eq' H using 1,
{ refine sum_congr rfl (λ p h, _),
obtain ⟨h', h''⟩ : p ∈ _ ∧ p ≠ _ := by rwa [mem_sdiff, mem_singleton] at h,
simp [bernoulli_eq_bernoulli'_of_ne_one ((not_congr (antidiagonal_congr h' h₁)).mp h'')] },
{ field_simp [h₃],
norm_num },
end
/-- The exponential generating function for the Bernoulli numbers `bernoulli n`. -/
def bernoulli_power_series := mk $ λ n, algebra_map ℚ A (bernoulli n / n!)
theorem bernoulli_power_series_mul_exp_sub_one :
bernoulli_power_series A * (exp A - 1) = X :=
begin
ext n,
-- constant coefficient is a special case
cases n, { simp },
simp only [bernoulli_power_series, coeff_mul, coeff_X, sum_antidiagonal_succ', one_div, coeff_mk,
coeff_one, coeff_exp, linear_map.map_sub, factorial, if_pos, cast_succ, cast_one, cast_mul,
sub_zero, ring_hom.map_one, add_eq_zero_iff, if_false, _root_.inv_one, zero_add, one_ne_zero,
mul_zero, and_false, sub_self, ← ring_hom.map_mul, ← ring_hom.map_sum],
cases n, { simp },
rw if_neg n.succ_succ_ne_one,
have hfact : ∀ m, (m! : ℚ) ≠ 0 := λ m, by exact_mod_cast factorial_ne_zero m,
have hite2 : ite (n.succ = 0) 1 0 = (0 : ℚ) := if_neg n.succ_ne_zero,
rw [←map_zero (algebra_map ℚ A), ←zero_div (n.succ! : ℚ), ←hite2, ← bernoulli_spec', sum_div],
refine congr_arg (algebra_map ℚ A) (sum_congr rfl $ λ x h, eq_div_of_mul_eq (hfact n.succ) _),
rw mem_antidiagonal at h,
have hj : (x.2.succ : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero _,
field_simp [← h, mul_ne_zero hj (hfact x.2), hfact x.1, mul_comm _ (bernoulli x.1), mul_assoc],
rw_mod_cast [mul_comm (x.2 + 1), mul_div_assoc, ← mul_assoc],
rw [cast_mul, cast_mul, mul_div_mul_right _ _ hj, add_choose, cast_div_char_zero],
apply factorial_mul_factorial_dvd_factorial_add,
end
section faulhaber
/-- **Faulhaber's theorem** relating the **sum of of p-th powers** to the Bernoulli numbers:
$$\sum_{k=0}^{n-1} k^p = \sum_{i=0}^p B_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$
See https://proofwiki.org/wiki/Faulhaber%27s_Formula and [orosi2018faulhaber] for
the proof provided here. -/
theorem sum_range_pow (n p : ℕ) :
∑ k in range n, (k : ℚ) ^ p =
∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1) :=
begin
have hne : ∀ m : ℕ, (m! : ℚ) ≠ 0 := λ m, by exact_mod_cast factorial_ne_zero m,
-- compute the Cauchy product of two power series
have h_cauchy : mk (λ p, bernoulli p / p!) * mk (λ q, coeff ℚ (q + 1) (exp ℚ ^ n))
= mk (λ p, ∑ i in range (p + 1),
bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!),
{ ext q : 1,
let f := λ a b, bernoulli a / a! * coeff ℚ (b + 1) (exp ℚ ^ n),
-- key step: use `power_series.coeff_mul` and then rewrite sums
simp only [coeff_mul, coeff_mk, cast_mul, sum_antidiagonal_eq_sum_range_succ f],
apply sum_congr rfl,
simp_intros m h only [finset.mem_range],
simp only [f, exp_pow_eq_rescale_exp, rescale, one_div, coeff_mk, ring_hom.coe_mk, coeff_exp,
ring_hom.id_apply, cast_mul, algebra_map_rat_rat],
-- manipulate factorials and binomial coefficients
rw [choose_eq_factorial_div_factorial h.le, eq_comm, div_eq_iff (hne q.succ), succ_eq_add_one,
mul_assoc _ _ ↑q.succ!, mul_comm _ ↑q.succ!, ← mul_assoc, div_mul_eq_mul_div,
mul_comm (↑n ^ (q - m + 1)), ← mul_assoc _ _ (↑n ^ (q - m + 1)), ← one_div, mul_one_div,
div_div, tsub_add_eq_add_tsub (le_of_lt_succ h), cast_div, cast_mul],
{ ring },
{ exact factorial_mul_factorial_dvd_factorial h.le },
{ simp [hne] } },
-- same as our goal except we pull out `p!` for convenience
have hps : ∑ k in range n, ↑k ^ p
= (∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!)
* p!,
{ suffices : mk (λ p, ∑ k in range n, ↑k ^ p * algebra_map ℚ ℚ p!⁻¹)
= mk (λ p, ∑ i in range (p + 1),
bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!),
{ rw [← div_eq_iff (hne p), div_eq_mul_inv, sum_mul],
rw power_series.ext_iff at this,
simpa using this p },
-- the power series `exp ℚ - 1` is non-zero, a fact we need in order to use `mul_right_inj'`
have hexp : exp ℚ - 1 ≠ 0,
{ simp only [exp, power_series.ext_iff, ne, not_forall],
use 1,
simp },
have h_r : exp ℚ ^ n - 1 = X * mk (λ p, coeff ℚ (p + 1) (exp ℚ ^ n)),
{ have h_const : C ℚ (constant_coeff ℚ (exp ℚ ^ n)) = 1 := by simp,
rw [← h_const, sub_const_eq_X_mul_shift] },
-- key step: a chain of equalities of power series
rw [← mul_right_inj' hexp, mul_comm, ← exp_pow_sum, ← geom_sum_def, geom_sum_mul, h_r,
← bernoulli_power_series_mul_exp_sub_one, bernoulli_power_series, mul_right_comm],
simp [h_cauchy, mul_comm] },
-- massage `hps` into our goal
rw [hps, sum_mul],
refine sum_congr rfl (λ x hx, _),
field_simp [mul_right_comm _ ↑p!, ← mul_assoc _ _ ↑p!, cast_add_one_ne_zero, hne],
end
/-- Alternate form of **Faulhaber's theorem**, relating the sum of p-th powers to the Bernoulli
numbers: $$\sum_{k=1}^{n} k^p = \sum_{i=0}^p (-1)^iB_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$
Deduced from `sum_range_pow`. -/
theorem sum_Ico_pow (n p : ℕ) :
∑ k in Ico 1 (n + 1), (k : ℚ) ^ p =
∑ i in range (p + 1), bernoulli' i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1) :=
begin
-- dispose of the trivial case
cases p, { simp },
let f := λ i, bernoulli i * p.succ.succ.choose i * n ^ (p.succ.succ - i) / p.succ.succ,
let f' := λ i, bernoulli' i * p.succ.succ.choose i * n ^ (p.succ.succ - i) / p.succ.succ,
suffices : ∑ k in Ico 1 n.succ, ↑k ^ p.succ = ∑ i in range p.succ.succ, f' i, { convert this },
-- prove some algebraic facts that will make things easier for us later on
have hle := nat.le_add_left 1 n,
have hne : (p + 1 + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero p.succ,
have h1 : ∀ r : ℚ, r * (p + 1 + 1) * n ^ p.succ / (p + 1 + 1 : ℚ) = r * n ^ p.succ :=
λ r, by rw [mul_div_right_comm, mul_div_cancel _ hne],
have h2 : f 1 + n ^ p.succ = 1 / 2 * n ^ p.succ,
{ simp_rw [f, bernoulli_one, choose_one_right, succ_sub_succ_eq_sub, cast_succ, tsub_zero, h1],
ring },
have : ∑ i in range p, bernoulli (i + 2) * (p + 2).choose (i + 2) * n ^ (p - i) / ↑(p + 2)
= ∑ i in range p, bernoulli' (i + 2) * (p + 2).choose (i + 2) * n ^ (p - i) / ↑(p + 2) :=
sum_congr rfl (λ i h, by rw bernoulli_eq_bernoulli'_of_ne_one (succ_succ_ne_one i)),
calc ∑ k in Ico 1 n.succ, ↑k ^ p.succ
-- replace sum over `Ico` with sum over `range` and simplify
= ∑ k in range n.succ, ↑k ^ p.succ : by simp [sum_Ico_eq_sub _ hle, succ_ne_zero]
-- extract the last term of the sum
... = ∑ k in range n, (k : ℚ) ^ p.succ + n ^ p.succ : by rw sum_range_succ
-- apply the key lemma, `sum_range_pow`
... = ∑ i in range p.succ.succ, f i + n ^ p.succ : by simp [f, sum_range_pow]
-- extract the first two terms of the sum
... = ∑ i in range p, f i.succ.succ + f 1 + f 0 + n ^ p.succ : by simp_rw [sum_range_succ']
... = ∑ i in range p, f i.succ.succ + (f 1 + n ^ p.succ) + f 0 : by ring
... = ∑ i in range p, f i.succ.succ + 1 / 2 * n ^ p.succ + f 0 : by rw h2
-- convert from `bernoulli` to `bernoulli'`
... = ∑ i in range p, f' i.succ.succ + f' 1 + f' 0 : by { simp only [f, f'], simpa [h1] }
-- rejoin the first two terms of the sum
... = ∑ i in range p.succ.succ, f' i : by simp_rw [sum_range_succ'],
end
end faulhaber
|
f218b566ef5988bc8301b2729707546fecba3615 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/number_theory/bernoulli.lean | 633157abe1c32c231ce41d75369d49fdf7bc3fd2 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 16,952 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Kevin Buzzard
-/
import data.rat
import data.fintype.card
import algebra.big_operators.nat_antidiagonal
import ring_theory.power_series.well_known
/-!
# Bernoulli numbers
The Bernoulli numbers are a sequence of rational numbers that frequently show up in
number theory.
## Mathematical overview
The Bernoulli numbers $(B_0, B_1, B_2, \ldots)=(1, -1/2, 1/6, 0, -1/30, \ldots)$ are
a sequence of rational numbers. They show up in the formula for the sums of $k$th
powers. They are related to the Taylor series expansions of $x/\tan(x)$ and
of $\coth(x)$, and also show up in the values that the Riemann Zeta function
takes both at both negative and positive integers (and hence in the
theory of modular forms). For example, if $1 \leq n$ is even then
$$\zeta(2n)=\sum_{t\geq1}t^{-2n}=(-1)^{n+1}\frac{(2\pi)^{2n}B_{2n}}{2(2n)!}.$$
Note however that this result is not yet formalised in Lean.
The Bernoulli numbers can be formally defined using the power series
$$\sum B_n\frac{t^n}{n!}=\frac{t}{1-e^{-t}}$$
although that happens to not be the definition in mathlib (this is an *implementation
detail* and need not concern the mathematician).
Note that $B_1=-1/2$, meaning that we are using the $B_n^-$ of
[from Wikipedia](https://en.wikipedia.org/wiki/Bernoulli_number).
## Implementation detail
The Bernoulli numbers are defined using well-founded induction, by the formula
$$B_n=1-\sum_{k\lt n}\frac{\binom{n}{k}}{n-k+1}B_k.$$
This formula is true for all $n$ and in particular $B_0=1$. Note that this is the definition
for positive Bernoulli numbers, which we call `bernoulli'`. The negative Bernoulli numbers are
then defined as `bernoulli := (-1)^n * bernoulli'`.
## Main theorems
`sum_bernoulli : ∑ k in finset.range n, (n.choose k : ℚ) * bernoulli k = 0`
-/
open_locale nat big_operators
open finset nat finset.nat power_series
variables (A : Type*) [comm_ring A] [algebra ℚ A]
/-! ### Definitions -/
/-- The Bernoulli numbers:
the $n$-th Bernoulli number $B_n$ is defined recursively via
$$B_n = 1 - \sum_{k < n} \binom{n}{k}\frac{B_k}{n+1-k}$$ -/
def bernoulli' : ℕ → ℚ :=
well_founded.fix lt_wf $
λ n bernoulli', 1 - ∑ k : fin n, n.choose k / (n - k + 1) * bernoulli' k k.2
lemma bernoulli'_def' (n : ℕ) :
bernoulli' n = 1 - ∑ k : fin n, n.choose k / (n - k + 1) * bernoulli' k :=
well_founded.fix_eq _ _ _
lemma bernoulli'_def (n : ℕ) :
bernoulli' n = 1 - ∑ k in range n, n.choose k / (n - k + 1) * bernoulli' k :=
by { rw [bernoulli'_def', ← fin.sum_univ_eq_sum_range], refl }
lemma bernoulli'_spec (n : ℕ) :
∑ k in range n.succ, (n.choose (n - k) : ℚ) / (n - k + 1) * bernoulli' k = 1 :=
begin
rw [sum_range_succ_comm, bernoulli'_def n, nat.sub_self],
conv in (n.choose (_ - _)) { rw choose_symm (mem_range.1 H).le },
simp only [one_mul, cast_one, sub_self, sub_add_cancel, choose_zero_right, zero_add, div_one],
end
lemma bernoulli'_spec' (n : ℕ) :
∑ k in antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli' k.1 = 1 :=
begin
refine ((sum_antidiagonal_eq_sum_range_succ_mk _ n).trans _).trans (bernoulli'_spec n),
refine sum_congr rfl (λ x hx, _),
simp only [nat.add_sub_cancel', mem_range_succ_iff.mp hx, cast_sub],
end
/-! ### Examples -/
section examples
@[simp] lemma bernoulli'_zero : bernoulli' 0 = 1 :=
by { rw bernoulli'_def, norm_num }
@[simp] lemma bernoulli'_one : bernoulli' 1 = 1/2 :=
by { rw bernoulli'_def, norm_num }
@[simp] lemma bernoulli'_two : bernoulli' 2 = 1/6 :=
by { rw bernoulli'_def, norm_num [sum_range_succ] }
@[simp] lemma bernoulli'_three : bernoulli' 3 = 0 :=
by { rw bernoulli'_def, norm_num [sum_range_succ] }
@[simp] lemma bernoulli'_four : bernoulli' 4 = -1/30 :=
have nat.choose 4 2 = 6 := dec_trivial, -- shrug
by { rw bernoulli'_def, norm_num [sum_range_succ, this] }
end examples
@[simp] lemma sum_bernoulli' (n : ℕ) :
∑ k in range n, (n.choose k : ℚ) * bernoulli' k = n :=
begin
cases n, { simp },
suffices : (n + 1 : ℚ) * ∑ k in range n, ↑(n.choose k) / (n - k + 1) * bernoulli' k =
∑ x in range n, ↑(n.succ.choose x) * bernoulli' x,
{ rw_mod_cast [sum_range_succ, bernoulli'_def, ← this, choose_succ_self_right], ring },
simp_rw [mul_sum, ← mul_assoc],
refine sum_congr rfl (λ k hk, _),
congr',
have : ((n - k : ℕ) : ℚ) + 1 ≠ 0 := by apply_mod_cast succ_ne_zero,
field_simp [← cast_sub (mem_range.1 hk).le, mul_comm],
rw_mod_cast [nat.sub_add_eq_add_sub (mem_range.1 hk).le, choose_mul_succ_eq],
end
/-- The exponential generating function for the Bernoulli numbers `bernoulli' n`. -/
def bernoulli'_power_series := mk $ λ n, algebra_map ℚ A (bernoulli' n / n!)
theorem bernoulli'_power_series_mul_exp_sub_one :
bernoulli'_power_series A * (exp A - 1) = X * exp A :=
begin
ext n,
-- constant coefficient is a special case
cases n, { simp },
rw [bernoulli'_power_series, coeff_mul, mul_comm X, sum_antidiagonal_succ'],
suffices : ∑ p in antidiagonal n, (bernoulli' p.1 / p.1!) * ((p.2 + 1) * p.2!)⁻¹ = n!⁻¹,
{ simpa [ring_hom.map_sum] using congr_arg (algebra_map ℚ A) this },
apply eq_inv_of_mul_left_eq_one,
rw sum_mul,
convert bernoulli'_spec' n using 1,
apply sum_congr rfl,
simp_rw [mem_antidiagonal],
rintro ⟨i, j⟩ rfl,
have : (j + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero j,
have : (j + 1 : ℚ) * j! * i! ≠ 0 := by simpa [factorial_ne_zero],
have := factorial_mul_factorial_dvd_factorial_add i j,
field_simp [mul_comm _ (bernoulli' i), mul_assoc, add_choose],
rw_mod_cast [mul_comm (j + 1), mul_div_assoc, ← mul_assoc],
rw [cast_mul, cast_mul, mul_div_mul_right, cast_dvd_char_zero, cast_mul],
assumption',
end
/-- Odd Bernoulli numbers (greater than 1) are zero. -/
theorem bernoulli'_odd_eq_zero {n : ℕ} (h_odd : odd n) (hlt : 1 < n) : bernoulli' n = 0 :=
begin
let B := mk (λ n, bernoulli' n / n!),
suffices : (B - eval_neg_hom B) * (exp ℚ - 1) = X * (exp ℚ - 1),
{ cases mul_eq_mul_right_iff.mp this;
simp only [power_series.ext_iff, eval_neg_hom, coeff_X] at h,
{ apply eq_zero_of_neg_eq,
specialize h n,
split_ifs at h;
simp [neg_one_pow_of_odd h_odd, factorial_ne_zero, *] at * },
{ simpa using h 1 } },
have h : B * (exp ℚ - 1) = X * exp ℚ,
{ simpa [bernoulli'_power_series] using bernoulli'_power_series_mul_exp_sub_one ℚ },
rw [sub_mul, h, mul_sub X, sub_right_inj, ← neg_sub, ← neg_mul_eq_mul_neg, neg_eq_iff_neg_eq],
suffices : eval_neg_hom (B * (exp ℚ - 1)) * exp ℚ = eval_neg_hom (X * exp ℚ) * exp ℚ,
{ simpa [mul_assoc, sub_mul, mul_comm (eval_neg_hom (exp ℚ)), exp_mul_exp_neg_eq_one, eq_comm] },
congr',
end
/-- The Bernoulli numbers are defined to be `bernoulli'` with a parity sign. -/
def bernoulli (n : ℕ) : ℚ := (-1)^n * bernoulli' n
lemma bernoulli'_eq_bernoulli (n : ℕ) : bernoulli' n = (-1)^n * bernoulli n :=
by simp [bernoulli, ← mul_assoc, ← sq, ← pow_mul, mul_comm n 2, pow_mul]
@[simp] lemma bernoulli_zero : bernoulli 0 = 1 := by simp [bernoulli]
@[simp] lemma bernoulli_one : bernoulli 1 = -1/2 :=
by norm_num [bernoulli]
theorem bernoulli_eq_bernoulli'_of_ne_one {n : ℕ} (hn : n ≠ 1) : bernoulli n = bernoulli' n :=
begin
by_cases h0 : n = 0, { simp [h0] },
rw [bernoulli, neg_one_pow_eq_pow_mod_two],
cases mod_two_eq_zero_or_one n, { simp [h] },
simp [bernoulli'_odd_eq_zero (odd_iff.mpr h) (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, hn⟩)],
end
@[simp] theorem sum_bernoulli (n : ℕ):
∑ k in range n, (n.choose k : ℚ) * bernoulli k = if n = 1 then 1 else 0 :=
begin
cases n, { simp },
cases n, { simp },
suffices : ∑ i in range n, ↑((n + 2).choose (i + 2)) * bernoulli (i + 2) = n / 2,
{ simp only [this, sum_range_succ', cast_succ, bernoulli_one, bernoulli_zero, choose_one_right,
mul_one, choose_zero_right, cast_zero, if_false, zero_add, succ_succ_ne_one], ring },
have f := sum_bernoulli' n.succ.succ,
simp_rw [sum_range_succ', bernoulli'_one, choose_one_right, cast_succ, ← eq_sub_iff_add_eq] at f,
convert f,
{ ext x, rw bernoulli_eq_bernoulli'_of_ne_one (succ_ne_zero x ∘ succ.inj) },
{ simp only [one_div, mul_one, bernoulli'_zero, cast_one, choose_zero_right, add_sub_cancel],
ring },
end
lemma bernoulli_spec' (n : ℕ) :
∑ k in antidiagonal n, ((k.1 + k.2).choose k.2 : ℚ) / (k.2 + 1) * bernoulli k.1 =
if n = 0 then 1 else 0 :=
begin
cases n, { simp },
rw if_neg (succ_ne_zero _),
-- algebra facts
have h₁ : (1, n) ∈ antidiagonal n.succ := by simp [mem_antidiagonal, add_comm],
have h₂ : (n : ℚ) + 1 ≠ 0 := by apply_mod_cast succ_ne_zero,
have h₃ : (1 + n).choose n = n + 1 := by simp [add_comm],
-- key equation: the corresponding fact for `bernoulli'`
have H := bernoulli'_spec' n.succ,
-- massage it to match the structure of the goal, then convert piece by piece
rw sum_eq_add_sum_diff_singleton h₁ at H ⊢,
apply add_eq_of_eq_sub',
convert eq_sub_of_add_eq' H using 1,
{ refine sum_congr rfl (λ p h, _),
obtain ⟨h', h''⟩ : p ∈ _ ∧ p ≠ _ := by rwa [mem_sdiff, mem_singleton] at h,
simp [bernoulli_eq_bernoulli'_of_ne_one ((not_congr (antidiagonal_congr h' h₁)).mp h'')] },
{ field_simp [h₃],
norm_num },
end
/-- The exponential generating function for the Bernoulli numbers `bernoulli n`. -/
def bernoulli_power_series := mk $ λ n, algebra_map ℚ A (bernoulli n / n!)
theorem bernoulli_power_series_mul_exp_sub_one :
bernoulli_power_series A * (exp A - 1) = X :=
begin
ext n,
-- constant coefficient is a special case
cases n, { simp },
simp only [bernoulli_power_series, coeff_mul, coeff_X, sum_antidiagonal_succ', one_div, coeff_mk,
coeff_one, coeff_exp, linear_map.map_sub, factorial, if_pos, cast_succ, cast_one, cast_mul,
sub_zero, ring_hom.map_one, add_eq_zero_iff, if_false, inv_one, zero_add, one_ne_zero, mul_zero,
and_false, sub_self, ← ring_hom.map_mul, ← ring_hom.map_sum],
suffices : ∑ x in antidiagonal n, bernoulli x.1 / x.1! * ((x.2 + 1) * x.2!)⁻¹
= if n.succ = 1 then 1 else 0, { split_ifs; simp [h, this] },
cases n, { simp },
have hfact : ∀ m, (m! : ℚ) ≠ 0 := λ m, by exact_mod_cast factorial_ne_zero m,
have hite1 : ite (n.succ.succ = 1) 1 0 = (0 / n.succ! : ℚ) := by simp,
have hite2 : ite (n.succ = 0) 1 0 = (0 : ℚ) := by simp [succ_ne_zero],
rw [hite1, eq_div_iff (hfact n.succ), ← hite2, ← bernoulli_spec', sum_mul],
apply sum_congr rfl,
rintro ⟨i, j⟩ h,
rw mem_antidiagonal at h,
have hj : (j.succ : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero j,
field_simp [← h, mul_ne_zero hj (hfact j), hfact i, mul_comm _ (bernoulli i), mul_assoc],
rw_mod_cast [mul_comm (j + 1), mul_div_assoc, ← mul_assoc],
rw [cast_mul, cast_mul, mul_div_mul_right _ _ hj, add_choose, cast_dvd_char_zero],
apply factorial_mul_factorial_dvd_factorial_add,
end
section faulhaber
/-- Faulhaber's theorem relating the sum of of p-th powers to the Bernoulli numbers:
$$\sum_{k=0}^{n-1} k^p = \sum_{i=0}^p B_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$
See https://proofwiki.org/wiki/Faulhaber%27s_Formula and [orosi2018faulhaber] for
the proof provided here. -/
theorem sum_range_pow (n p : ℕ) :
∑ k in range n, (k : ℚ) ^ p =
∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1) :=
begin
have hne : ∀ m : ℕ, (m! : ℚ) ≠ 0 := λ m, by exact_mod_cast factorial_ne_zero m,
-- compute the Cauchy product of two power series
have h_cauchy : mk (λ p, bernoulli p / p!) * mk (λ q, coeff ℚ (q + 1) (exp ℚ ^ n))
= mk (λ p, ∑ i in range (p + 1),
bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!),
{ ext q,
let f := λ a b, bernoulli a / a! * coeff ℚ (b + 1) (exp ℚ ^ n),
-- key step: use `power_series.coeff_mul` and then rewrite sums
simp only [coeff_mul, coeff_mk, cast_mul, sum_antidiagonal_eq_sum_range_succ f],
apply sum_congr rfl,
simp_intros m h only [finset.mem_range],
simp only [f, exp_pow_eq_rescale_exp, rescale, one_div, coeff_mk, ring_hom.coe_mk, coeff_exp,
ring_hom.id_apply, cast_mul, rat.algebra_map_rat_rat],
-- manipulate factorials and binomial coefficients
rw [choose_eq_factorial_div_factorial h.le, eq_comm, div_eq_iff (hne q.succ), succ_eq_add_one,
mul_assoc _ _ ↑q.succ!, mul_comm _ ↑q.succ!, ← mul_assoc, div_mul_eq_mul_div,
mul_comm (↑n ^ (q - m + 1)), ← mul_assoc _ _ (↑n ^ (q - m + 1)), ← one_div, mul_one_div,
div_div_eq_div_mul, ← nat.sub_add_comm (le_of_lt_succ h), cast_dvd, cast_mul],
{ ring },
{ exact factorial_mul_factorial_dvd_factorial h.le },
{ simp [hne] } },
-- same as our goal except we pull out `p!` for convenience
have hps : ∑ k in range n, ↑k ^ p
= (∑ i in range (p + 1), bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!)
* p!,
{ suffices : mk (λ p, ∑ k in range n, ↑k ^ p * algebra_map ℚ ℚ p!⁻¹)
= mk (λ p, ∑ i in range (p + 1),
bernoulli i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1)!),
{ rw [← div_eq_iff (hne p), div_eq_mul_inv, sum_mul],
rw power_series.ext_iff at this,
simpa using this p },
-- the power series `exp ℚ - 1` is non-zero, a fact we need in order to use `mul_right_inj'`
have hexp : exp ℚ - 1 ≠ 0,
{ simp only [exp, power_series.ext_iff, ne, not_forall],
use 1,
simp },
have h_r : exp ℚ ^ n - 1 = X * mk (λ p, coeff ℚ (p + 1) (exp ℚ ^ n)),
{ have h_const : C ℚ (constant_coeff ℚ (exp ℚ ^ n)) = 1 := by simp,
rw [← h_const, sub_const_eq_X_mul_shift] },
-- key step: a chain of equalities of power series
rw [← mul_right_inj' hexp, mul_comm, ← exp_pow_sum, ← geom_sum_def, geom_sum_mul, h_r,
← bernoulli_power_series_mul_exp_sub_one, bernoulli_power_series, mul_right_comm],
simp [h_cauchy, mul_comm] },
-- massage `hps` into our goal
rw [hps, sum_mul],
refine sum_congr rfl (λ x hx, _),
field_simp [mul_right_comm _ ↑p!, ← mul_assoc _ _ ↑p!, cast_add_one_ne_zero, hne],
end
/-- Alternate form of Faulhaber's theorem, relating the sum of p-th powers to the Bernoulli numbers:
$$\sum_{k=1}^{n} k^p = \sum_{i=0}^p (-1)^iB_i\binom{p+1}{i}\frac{n^{p+1-i}}{p+1}.$$
Deduced from `sum_range_pow`. -/
theorem sum_Ico_pow (n p : ℕ) :
∑ k in Ico 1 (n + 1), (k : ℚ) ^ p =
∑ i in range (p + 1), bernoulli' i * (p + 1).choose i * n ^ (p + 1 - i) / (p + 1) :=
begin
-- dispose of the trivial case
cases p, { simp },
let f := λ i, bernoulli i * p.succ.succ.choose i * n ^ (p.succ.succ - i) / p.succ.succ,
let f' := λ i, bernoulli' i * p.succ.succ.choose i * n ^ (p.succ.succ - i) / p.succ.succ,
suffices : ∑ k in Ico 1 n.succ, ↑k ^ p.succ = ∑ i in range p.succ.succ, f' i, { convert this },
-- prove some algebraic facts that will make things easier for us later on
have hle := le_add_left 1 n,
have hne : (p + 1 + 1 : ℚ) ≠ 0 := by exact_mod_cast succ_ne_zero p.succ,
have h1 : ∀ r : ℚ, r * (p + 1 + 1) * n ^ p.succ / (p + 1 + 1 : ℚ) = r * n ^ p.succ :=
λ r, by rw [mul_div_right_comm, mul_div_cancel _ hne],
have h2 : f 1 + n ^ p.succ = 1 / 2 * n ^ p.succ,
{ simp_rw [f, bernoulli_one, choose_one_right, succ_sub_succ_eq_sub, cast_succ, nat.sub_zero, h1],
ring },
have : ∑ i in range p, bernoulli (i + 2) * (p + 2).choose (i + 2) * n ^ (p - i) / ↑(p + 2)
= ∑ i in range p, bernoulli' (i + 2) * (p + 2).choose (i + 2) * n ^ (p - i) / ↑(p + 2) :=
sum_congr rfl (λ i h, by rw bernoulli_eq_bernoulli'_of_ne_one (succ_succ_ne_one i)),
calc ∑ k in Ico 1 n.succ, ↑k ^ p.succ
-- replace sum over `Ico` with sum over `range` and simplify
= ∑ k in range n.succ, ↑k ^ p.succ : by simp [sum_Ico_eq_sub _ hle, succ_ne_zero]
-- extract the last term of the sum
... = ∑ k in range n, (k : ℚ) ^ p.succ + n ^ p.succ : by rw sum_range_succ
-- apply the key lemma, `sum_range_pow`
... = ∑ i in range p.succ.succ, f i + n ^ p.succ : by simp [f, sum_range_pow]
-- extract the first two terms of the sum
... = ∑ i in range p, f i.succ.succ + f 1 + f 0 + n ^ p.succ : by simp_rw [sum_range_succ']
... = ∑ i in range p, f i.succ.succ + (f 1 + n ^ p.succ) + f 0 : by ring
... = ∑ i in range p, f i.succ.succ + 1 / 2 * n ^ p.succ + f 0 : by rw h2
-- convert from `bernoulli` to `bernoulli'`
... = ∑ i in range p, f' i.succ.succ + f' 1 + f' 0 : by { simp only [f, f'], simpa [h1] }
-- rejoin the first two terms of the sum
... = ∑ i in range p.succ.succ, f' i : by simp_rw [sum_range_succ'],
end
end faulhaber
|
15e63a0467464286ca964901d6681e1a173ed4a8 | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/ring_theory/roots_of_unity.lean | 1cc9929dbcca63e4fc8ea063008c782f4e0610d8 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 40,402 | 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.nat.parity
import data.polynomial.ring_division
import group_theory.specific_groups.cyclic
import ring_theory.integral_domain
import number_theory.divisors
import data.zmod.basic
import tactic.zify
import field_theory.separable
import field_theory.finite.basic
/-!
# Roots of unity and primitive roots of unity
We define roots of unity in the context of an arbitrary commutative monoid,
as a subgroup of the group of units. We also define a predicate `is_primitive_root` on commutative
monoids, expressing that an element is a primitive root of unity.
## Main definitions
* `roots_of_unity n M`, for `n : ℕ+` is the subgroup of the units of a commutative monoid `M`
consisting of elements `x` that satisfy `x ^ n = 1`.
* `is_primitive_root ζ k`: an element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`,
and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`.
* `primitive_roots k R`: the finset of primitive `k`-th roots of unity in an integral domain `R`.
## Main results
* `roots_of_unity.is_cyclic`: the roots of unity in an integral domain form a cyclic group.
* `is_primitive_root.zmod_equiv_gpowers`: `zmod k` is equivalent to
the subgroup generated by a primitive `k`-th root of unity.
* `is_primitive_root.gpowers_eq`: in an integral domain, the subgroup generated by
a primitive `k`-th root of unity is equal to the `k`-th roots of unity.
* `is_primitive_root.card_primitive_roots`: if an integral domain
has a primitive `k`-th root of unity, then it has `φ k` of them.
## Implementation details
It is desirable that `roots_of_unity` is a subgroup,
and it will mainly be applied to rings (e.g. the ring of integers in a number field) and fields.
We therefore implement it as a subgroup of the units of a commutative monoid.
We have chosen to define `roots_of_unity n` for `n : ℕ+`, instead of `n : ℕ`,
because almost all lemmas need the positivity assumption,
and in particular the type class instances for `fintype` and `is_cyclic`.
On the other hand, for primitive roots of unity, it is desirable to have a predicate
not just on units, but directly on elements of the ring/field.
For example, we want to say that `exp (2 * pi * I / n)` is a primitive `n`-th root of unity
in the complex numbers, without having to turn that number into a unit first.
This creates a little bit of friction, but lemmas like `is_primitive_root.is_unit` and
`is_primitive_root.coe_units_iff` should provide the necessary glue.
-/
open_locale classical big_operators
noncomputable theory
open polynomial
open finset
variables {M N G G₀ R S : Type*}
variables [comm_monoid M] [comm_monoid N] [comm_group G] [comm_group_with_zero G₀]
variables [integral_domain R] [integral_domain S]
section roots_of_unity
variables {k l : ℕ+}
/-- `roots_of_unity k M` is the subgroup of elements `m : units M` that satisfy `m ^ k = 1` -/
def roots_of_unity (k : ℕ+) (M : Type*) [comm_monoid M] : subgroup (units M) :=
{ carrier := { ζ | ζ ^ (k : ℕ) = 1 },
one_mem' := one_pow _,
mul_mem' := λ ζ ξ hζ hξ, by simp only [*, set.mem_set_of_eq, mul_pow, one_mul] at *,
inv_mem' := λ ζ hζ, by simp only [*, set.mem_set_of_eq, inv_pow, one_inv] at * }
@[simp] lemma mem_roots_of_unity (k : ℕ+) (ζ : units M) :
ζ ∈ roots_of_unity k M ↔ ζ ^ (k : ℕ) = 1 := iff.rfl
lemma roots_of_unity_le_of_dvd (h : k ∣ l) : roots_of_unity k M ≤ roots_of_unity l M :=
begin
obtain ⟨d, rfl⟩ := h,
intros ζ h,
simp only [mem_roots_of_unity, pnat.mul_coe, pow_mul, one_pow, *] at *,
end
lemma map_roots_of_unity (f : units M →* units N) (k : ℕ+) :
(roots_of_unity k M).map f ≤ roots_of_unity k N :=
begin
rintros _ ⟨ζ, h, rfl⟩,
simp only [←monoid_hom.map_pow, *, mem_roots_of_unity, set_like.mem_coe, monoid_hom.map_one] at *
end
lemma mem_roots_of_unity_iff_mem_nth_roots {ζ : units R} :
ζ ∈ roots_of_unity k R ↔ (ζ : R) ∈ nth_roots k (1 : R) :=
by simp only [mem_roots_of_unity, mem_nth_roots k.pos, units.ext_iff, units.coe_one, units.coe_pow]
variables (k R)
/-- Equivalence between the `k`-th roots of unity in `R` and the `k`-th roots of `1`.
This is implemented as equivalence of subtypes,
because `roots_of_unity` is a subgroup of the group of units,
whereas `nth_roots` is a multiset. -/
def roots_of_unity_equiv_nth_roots :
roots_of_unity k R ≃ {x // x ∈ nth_roots k (1 : R)} :=
begin
refine
{ to_fun := λ x, ⟨x, mem_roots_of_unity_iff_mem_nth_roots.mp x.2⟩,
inv_fun := λ x, ⟨⟨x, x ^ (k - 1 : ℕ), _, _⟩, _⟩,
left_inv := _,
right_inv := _ },
swap 4, { rintro ⟨x, hx⟩, ext, refl },
swap 4, { rintro ⟨x, hx⟩, ext, refl },
all_goals
{ rcases x with ⟨x, hx⟩, rw [mem_nth_roots k.pos] at hx,
simp only [subtype.coe_mk, ← pow_succ, ← pow_succ', hx,
nat.sub_add_cancel (show 1 ≤ (k : ℕ), from k.one_le)] },
{ show (_ : units R) ^ (k : ℕ) = 1,
simp only [units.ext_iff, hx, units.coe_mk, units.coe_one, subtype.coe_mk, units.coe_pow] }
end
variables {k R}
@[simp] lemma roots_of_unity_equiv_nth_roots_apply (x : roots_of_unity k R) :
(roots_of_unity_equiv_nth_roots R k x : R) = x :=
rfl
@[simp] lemma roots_of_unity_equiv_nth_roots_symm_apply (x : {x // x ∈ nth_roots k (1 : R)}) :
((roots_of_unity_equiv_nth_roots R k).symm x : R) = x :=
rfl
variables (k R)
instance roots_of_unity.fintype : fintype (roots_of_unity k R) :=
fintype.of_equiv {x // x ∈ nth_roots k (1 : R)} $ (roots_of_unity_equiv_nth_roots R k).symm
instance roots_of_unity.is_cyclic : is_cyclic (roots_of_unity k R) :=
is_cyclic_of_subgroup_integral_domain ((units.coe_hom R).comp (roots_of_unity k R).subtype)
(units.ext.comp subtype.val_injective)
lemma card_roots_of_unity : fintype.card (roots_of_unity k R) ≤ k :=
calc fintype.card (roots_of_unity k R)
= fintype.card {x // x ∈ nth_roots k (1 : R)} :
fintype.card_congr (roots_of_unity_equiv_nth_roots R k)
... ≤ (nth_roots k (1 : R)).attach.card : multiset.card_le_of_le (multiset.erase_dup_le _)
... = (nth_roots k (1 : R)).card : multiset.card_attach
... ≤ k : card_nth_roots k 1
variables {k R}
@[norm_cast]
lemma roots_of_unity.coe_pow (ζ : roots_of_unity k R) (m : ℕ) : ↑(ζ ^ m) = (ζ ^ m : R) :=
begin
change ↑(↑(ζ ^ m) : units R) = ↑(ζ : units R) ^ m,
rw [subgroup.coe_pow, units.coe_pow],
end
/-- Restrict a ring homomorphism between integral domains to the nth roots of unity -/
def ring_hom.restrict_roots_of_unity (σ : R →+* S) (n : ℕ+) :
roots_of_unity n R →* roots_of_unity n S :=
let h : ∀ ξ : roots_of_unity n R, (σ ξ) ^ (n : ℕ) = 1 := λ ξ, by
{ change (σ (ξ : units R)) ^ (n : ℕ) = 1,
rw [←σ.map_pow, ←units.coe_pow, show ((ξ : units R) ^ (n : ℕ) = 1), from ξ.2,
units.coe_one, σ.map_one] } in
{ to_fun := λ ξ, ⟨@unit_of_invertible _ _ _ (invertible_of_pow_eq_one _ _ (h ξ) n.2),
by { ext, rw units.coe_pow, exact h ξ }⟩,
map_one' := by { ext, exact σ.map_one },
map_mul' := λ ξ₁ ξ₂, by { ext, rw [subgroup.coe_mul, units.coe_mul], exact σ.map_mul _ _ } }
@[simp] lemma ring_hom.restrict_roots_of_unity_coe_apply (σ : R →+* S) (ζ : roots_of_unity k R) :
↑(σ.restrict_roots_of_unity k ζ) = σ ↑ζ :=
rfl
/-- Restrict a ring isomorphism between integral domains to the nth roots of unity -/
def ring_equiv.restrict_roots_of_unity (σ : R ≃+* S) (n : ℕ+) :
roots_of_unity n R ≃* roots_of_unity n S :=
{ to_fun := σ.to_ring_hom.restrict_roots_of_unity n,
inv_fun := σ.symm.to_ring_hom.restrict_roots_of_unity n,
left_inv := λ ξ, by { ext, exact σ.symm_apply_apply ξ },
right_inv := λ ξ, by { ext, exact σ.apply_symm_apply ξ },
map_mul' := (σ.to_ring_hom.restrict_roots_of_unity n).map_mul }
@[simp] lemma ring_equiv.restrict_roots_of_unity_coe_apply (σ : R ≃+* S) (ζ : roots_of_unity k R) :
↑(σ.restrict_roots_of_unity k ζ) = σ ↑ζ :=
rfl
@[simp] lemma ring_equiv.restrict_roots_of_unity_symm (σ : R ≃+* S) :
(σ.restrict_roots_of_unity k).symm = σ.symm.restrict_roots_of_unity k :=
rfl
lemma ring_hom.map_root_of_unity_eq_pow_self (σ : R →+* R) (ζ : roots_of_unity k R) :
∃ m : ℕ, σ ζ = ζ ^ m :=
begin
obtain ⟨m, hm⟩ := (σ.restrict_roots_of_unity k).map_cyclic,
rw [←σ.restrict_roots_of_unity_coe_apply, hm, gpow_eq_mod_order_of, ←int.to_nat_of_nonneg
(m.mod_nonneg (int.coe_nat_ne_zero.mpr (pos_iff_ne_zero.mp (order_of_pos ζ)))),
gpow_coe_nat, roots_of_unity.coe_pow],
exact ⟨(m % (order_of ζ)).to_nat, rfl⟩,
end
end roots_of_unity
/-- An element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`,
and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. -/
structure is_primitive_root (ζ : M) (k : ℕ) : Prop :=
(pow_eq_one : ζ ^ (k : ℕ) = 1)
(dvd_of_pow_eq_one : ∀ l : ℕ, ζ ^ l = 1 → k ∣ l)
section primitive_roots
variables {k : ℕ}
/-- `primitive_roots k R` is the finset of primitive `k`-th roots of unity
in the integral domain `R`. -/
def primitive_roots (k : ℕ) (R : Type*) [integral_domain R] : finset R :=
(nth_roots k (1 : R)).to_finset.filter (λ ζ, is_primitive_root ζ k)
@[simp] lemma mem_primitive_roots {ζ : R} (h0 : 0 < k) :
ζ ∈ primitive_roots k R ↔ is_primitive_root ζ k :=
begin
rw [primitive_roots, mem_filter, multiset.mem_to_finset, mem_nth_roots h0, and_iff_right_iff_imp],
exact is_primitive_root.pow_eq_one
end
end primitive_roots
namespace is_primitive_root
variables {k l : ℕ}
lemma iff_def (ζ : M) (k : ℕ) :
is_primitive_root ζ k ↔ (ζ ^ k = 1) ∧ (∀ l : ℕ, ζ ^ l = 1 → k ∣ l) :=
⟨λ ⟨h1, h2⟩, ⟨h1, h2⟩, λ ⟨h1, h2⟩, ⟨h1, h2⟩⟩
lemma mk_of_lt (ζ : M) (hk : 0 < k) (h1 : ζ ^ k = 1) (h : ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1) :
is_primitive_root ζ k :=
begin
refine ⟨h1, _⟩,
intros l hl,
apply dvd_trans _ (k.gcd_dvd_right l),
suffices : k.gcd l = k, { rw this },
rw eq_iff_le_not_lt,
refine ⟨nat.le_of_dvd hk (k.gcd_dvd_left l), _⟩,
intro h', apply h _ (nat.gcd_pos_of_pos_left _ hk) h',
exact pow_gcd_eq_one _ h1 hl
end
section comm_monoid
variables {ζ : M} (h : is_primitive_root ζ k)
lemma pow_eq_one_iff_dvd (l : ℕ) : ζ ^ l = 1 ↔ k ∣ l :=
⟨h.dvd_of_pow_eq_one l,
by { rintro ⟨i, rfl⟩, simp only [pow_mul, h.pow_eq_one, one_pow, pnat.mul_coe] }⟩
lemma is_unit (h : is_primitive_root ζ k) (h0 : 0 < k) : is_unit ζ :=
begin
apply is_unit_of_mul_eq_one ζ (ζ ^ (k - 1)),
rw [← pow_succ, nat.sub_add_cancel h0, h.pow_eq_one]
end
lemma pow_ne_one_of_pos_of_lt (h0 : 0 < l) (hl : l < k) : ζ ^ l ≠ 1 :=
mt (nat.le_of_dvd h0 ∘ h.dvd_of_pow_eq_one _) $ not_le_of_lt hl
lemma pow_inj (h : is_primitive_root ζ k) ⦃i j : ℕ⦄ (hi : i < k) (hj : j < k) (H : ζ ^ i = ζ ^ j) :
i = j :=
begin
wlog hij : i ≤ j,
apply le_antisymm hij,
rw ← nat.sub_eq_zero_iff_le,
apply nat.eq_zero_of_dvd_of_lt _ (lt_of_le_of_lt (nat.sub_le_self _ _) hj),
apply h.dvd_of_pow_eq_one,
rw [← ((h.is_unit (lt_of_le_of_lt (nat.zero_le _) hi)).pow i).mul_left_inj,
← pow_add, nat.sub_add_cancel hij, H, one_mul]
end
lemma one : is_primitive_root (1 : M) 1 :=
{ pow_eq_one := pow_one _,
dvd_of_pow_eq_one := λ l hl, one_dvd _ }
@[simp] lemma one_right_iff : is_primitive_root ζ 1 ↔ ζ = 1 :=
begin
split,
{ intro h, rw [← pow_one ζ, h.pow_eq_one] },
{ rintro rfl, exact one }
end
@[simp] lemma coe_units_iff {ζ : units M} :
is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k :=
by simp only [iff_def, units.ext_iff, units.coe_pow, units.coe_one]
lemma pow_of_coprime (h : is_primitive_root ζ k) (i : ℕ) (hi : i.coprime k) :
is_primitive_root (ζ ^ i) k :=
begin
by_cases h0 : k = 0,
{ subst k, simp only [*, pow_one, nat.coprime_zero_right] at * },
rcases h.is_unit (nat.pos_of_ne_zero h0) with ⟨ζ, rfl⟩,
rw [← units.coe_pow],
rw coe_units_iff at h ⊢,
refine
{ pow_eq_one := by rw [← pow_mul', pow_mul, h.pow_eq_one, one_pow],
dvd_of_pow_eq_one := _ },
intros l hl,
apply h.dvd_of_pow_eq_one,
rw [← pow_one ζ, ← gpow_coe_nat ζ, ← hi.gcd_eq_one, nat.gcd_eq_gcd_ab, gpow_add,
mul_pow, ← gpow_coe_nat, ← gpow_mul, mul_right_comm],
simp only [gpow_mul, hl, h.pow_eq_one, one_gpow, one_pow, one_mul, gpow_coe_nat]
end
lemma pow_of_prime (h : is_primitive_root ζ k) {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ k) :
is_primitive_root (ζ ^ p) k :=
h.pow_of_coprime p (hprime.coprime_iff_not_dvd.2 hdiv)
lemma pow_iff_coprime (h : is_primitive_root ζ k) (h0 : 0 < k) (i : ℕ) :
is_primitive_root (ζ ^ i) k ↔ i.coprime k :=
begin
refine ⟨_, h.pow_of_coprime i⟩,
intro hi,
obtain ⟨a, ha⟩ := i.gcd_dvd_left k,
obtain ⟨b, hb⟩ := i.gcd_dvd_right k,
suffices : b = k,
{ rwa [this, ← one_mul k, nat.mul_left_inj h0, eq_comm] at hb { occs := occurrences.pos [1] } },
rw [ha] at hi,
rw [mul_comm] at hb,
apply nat.dvd_antisymm ⟨i.gcd k, hb⟩ (hi.dvd_of_pow_eq_one b _),
rw [← pow_mul', ← mul_assoc, ← hb, pow_mul, h.pow_eq_one, one_pow]
end
end comm_monoid
section comm_group
variables {ζ : G}
lemma gpow_eq_one (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 :=
by { rw gpow_coe_nat, exact h.pow_eq_one }
lemma gpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) :
ζ ^ l = 1 ↔ (k : ℤ) ∣ l :=
begin
by_cases h0 : 0 ≤ l,
{ lift l to ℕ using h0, rw [gpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l },
{ have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 },
lift -l to ℕ using this with l' hl',
rw [← dvd_neg, ← hl'],
norm_cast,
rw [← h.pow_eq_one_iff_dvd, ← inv_inj, ← gpow_neg, ← hl', gpow_coe_nat, one_inv] }
end
lemma inv (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k :=
{ pow_eq_one := by simp only [h.pow_eq_one, one_inv, eq_self_iff_true, inv_pow],
dvd_of_pow_eq_one :=
begin
intros l hl,
apply h.dvd_of_pow_eq_one l,
rw [← inv_inj, ← inv_pow, hl, one_inv]
end }
@[simp] lemma inv_iff : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k :=
by { refine ⟨_, λ h, inv h⟩, intro h, rw [← inv_inv ζ], exact inv h }
lemma gpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) :
is_primitive_root (ζ ^ i) k :=
begin
by_cases h0 : 0 ≤ i,
{ lift i to ℕ using h0,
rw gpow_coe_nat,
exact h.pow_of_coprime i hi },
have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 },
lift -i to ℕ using this with i' hi',
rw [← inv_iff, ← gpow_neg, ← hi', gpow_coe_nat],
apply h.pow_of_coprime,
rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi,
exact hi
end
@[simp] lemma coe_subgroup_iff (H : subgroup G) {ζ : H} :
is_primitive_root (ζ : G) k ↔ is_primitive_root ζ k :=
by simp only [iff_def, ← subgroup.coe_pow, ← H.coe_one, ← subtype.ext_iff]
end comm_group
section comm_group_with_zero
variables {ζ : G₀}
lemma fpow_eq_one (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 :=
by { rw gpow_coe_nat, exact h.pow_eq_one }
lemma fpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) :
ζ ^ l = 1 ↔ (k : ℤ) ∣ l :=
begin
by_cases h0 : 0 ≤ l,
{ lift l to ℕ using h0, rw [gpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l },
{ have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 },
lift -l to ℕ using this with l' hl',
rw [← dvd_neg, ← hl'],
norm_cast,
rw [← h.pow_eq_one_iff_dvd, ← inv_inj', ← fpow_neg, ← hl', gpow_coe_nat, inv_one] }
end
lemma inv' (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k :=
{ pow_eq_one := by simp only [h.pow_eq_one, inv_one, eq_self_iff_true, inv_pow'],
dvd_of_pow_eq_one :=
begin
intros l hl,
apply h.dvd_of_pow_eq_one l,
rw [← inv_inj', ← inv_pow', hl, inv_one]
end }
@[simp] lemma inv_iff' : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k :=
by { refine ⟨_, λ h, inv' h⟩, intro h, rw [← inv_inv' ζ], exact inv' h }
lemma fpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) :
is_primitive_root (ζ ^ i) k :=
begin
by_cases h0 : 0 ≤ i,
{ lift i to ℕ using h0,
rw gpow_coe_nat,
exact h.pow_of_coprime i hi },
have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 },
lift -i to ℕ using this with i' hi',
rw [← inv_iff', ← fpow_neg, ← hi', gpow_coe_nat],
apply h.pow_of_coprime,
rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi,
exact hi
end
end comm_group_with_zero
section integral_domain
variables {ζ : R}
@[simp] lemma primitive_roots_zero : primitive_roots 0 R = ∅ :=
begin
rw [← finset.val_eq_zero, ← multiset.subset_zero, ← nth_roots_zero (1 : R), primitive_roots],
simp only [finset.not_mem_empty, forall_const, forall_prop_of_false, multiset.to_finset_zero,
finset.filter_true_of_mem, finset.empty_val, not_false_iff,
multiset.zero_subset, nth_roots_zero]
end
@[simp] lemma primitive_roots_one : primitive_roots 1 R = {(1 : R)} :=
begin
apply finset.eq_singleton_iff_unique_mem.2,
split,
{ simp only [is_primitive_root.one_right_iff, mem_primitive_roots zero_lt_one] },
{ intros x hx,
rw [mem_primitive_roots zero_lt_one, is_primitive_root.one_right_iff] at hx,
exact hx }
end
lemma neg_one (p : ℕ) [char_p R p] (hp : p ≠ 2) : is_primitive_root (-1 : R) 2 :=
mk_of_lt (-1 : R) dec_trivial (by simp only [one_pow, neg_sq]) $
begin
intros l hl0 hl2,
obtain rfl : l = 1,
{ unfreezingI { clear_dependent R p }, dec_trivial! },
simp only [pow_one, ne.def],
intro h,
suffices h2 : p ∣ 2,
{ have := char_p.char_ne_one R p,
unfreezingI { clear_dependent R },
have aux := nat.le_of_dvd dec_trivial h2,
revert this hp h2, revert p, dec_trivial },
simp only [← char_p.cast_eq_zero_iff R p, nat.cast_bit0, nat.cast_one],
rw [bit0, ← h, neg_add_self] { occs := occurrences.pos [1] }
end
lemma eq_neg_one_of_two_right (h : is_primitive_root ζ 2) : ζ = -1 :=
begin
apply (eq_or_eq_neg_of_sq_eq_sq ζ 1 _).resolve_left,
{ rw [← pow_one ζ], apply h.pow_ne_one_of_pos_of_lt; dec_trivial },
{ simp only [h.pow_eq_one, one_pow] }
end
end integral_domain
section integral_domain
variables {ζ : units R} (h : is_primitive_root ζ k)
protected
lemma mem_roots_of_unity {n : ℕ+} (h : is_primitive_root ζ n) : ζ ∈ roots_of_unity n R :=
h.pow_eq_one
/-- The (additive) monoid equivalence between `zmod k`
and the powers of a primitive root of unity `ζ`. -/
def zmod_equiv_gpowers (h : is_primitive_root ζ k) : zmod k ≃+ additive (subgroup.gpowers ζ) :=
add_equiv.of_bijective
(add_monoid_hom.lift_of_right_inverse (int.cast_add_hom $ zmod k) _ zmod.int_cast_right_inverse
⟨{ to_fun := λ i, additive.of_mul (⟨_, i, rfl⟩ : subgroup.gpowers ζ),
map_zero' := by { simp only [gpow_zero], refl },
map_add' := by { intros i j, simp only [gpow_add], refl } },
(λ i hi,
begin
simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k,
add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hi ⊢,
obtain ⟨i, rfl⟩ := hi,
simp only [gpow_mul, h.pow_eq_one, one_gpow, gpow_coe_nat],
refl
end)⟩)
begin
split,
{ rw add_monoid_hom.injective_iff,
intros i hi,
rw subtype.ext_iff at hi,
have := (h.gpow_eq_one_iff_dvd _).mp hi,
rw [← (char_p.int_cast_eq_zero_iff (zmod k) k _).mpr this, eq_comm],
exact zmod.int_cast_right_inverse i },
{ rintro ⟨ξ, i, rfl⟩,
refine ⟨int.cast_add_hom _ i, _⟩,
rw [add_monoid_hom.lift_of_right_inverse_comp_apply],
refl }
end
@[simp] lemma zmod_equiv_gpowers_apply_coe_int (i : ℤ) :
h.zmod_equiv_gpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ) :=
add_monoid_hom.lift_of_right_inverse_comp_apply _ _ zmod.int_cast_right_inverse _ _
@[simp] lemma zmod_equiv_gpowers_apply_coe_nat (i : ℕ) :
h.zmod_equiv_gpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ) :=
begin
have : (i : zmod k) = (i : ℤ), by norm_cast,
simp only [this, zmod_equiv_gpowers_apply_coe_int, gpow_coe_nat],
refl
end
@[simp] lemma zmod_equiv_gpowers_symm_apply_gpow (i : ℤ) :
h.zmod_equiv_gpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ)) = i :=
by rw [← h.zmod_equiv_gpowers.symm_apply_apply i, zmod_equiv_gpowers_apply_coe_int]
@[simp] lemma zmod_equiv_gpowers_symm_apply_gpow' (i : ℤ) :
h.zmod_equiv_gpowers.symm ⟨ζ ^ i, i, rfl⟩ = i :=
h.zmod_equiv_gpowers_symm_apply_gpow i
@[simp] lemma zmod_equiv_gpowers_symm_apply_pow (i : ℕ) :
h.zmod_equiv_gpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.gpowers ζ)) = i :=
by rw [← h.zmod_equiv_gpowers.symm_apply_apply i, zmod_equiv_gpowers_apply_coe_nat]
@[simp] lemma zmod_equiv_gpowers_symm_apply_pow' (i : ℕ) :
h.zmod_equiv_gpowers.symm ⟨ζ ^ i, i, rfl⟩ = i :=
h.zmod_equiv_gpowers_symm_apply_pow i
lemma gpowers_eq {k : ℕ+} {ζ : units R} (h : is_primitive_root ζ k) :
subgroup.gpowers ζ = roots_of_unity k R :=
begin
apply set_like.coe_injective,
haveI : fact (0 < (k : ℕ)) := ⟨k.pos⟩,
haveI F : fintype (subgroup.gpowers ζ) := fintype.of_equiv _ (h.zmod_equiv_gpowers).to_equiv,
refine @set.eq_of_subset_of_card_le (units R) (subgroup.gpowers ζ) (roots_of_unity k R)
F (roots_of_unity.fintype R k)
(subgroup.gpowers_subset $ show ζ ∈ roots_of_unity k R, from h.pow_eq_one) _,
calc fintype.card (roots_of_unity k R)
≤ k : card_roots_of_unity R k
... = fintype.card (zmod k) : (zmod.card k).symm
... = fintype.card (subgroup.gpowers ζ) : fintype.card_congr (h.zmod_equiv_gpowers).to_equiv
end
lemma eq_pow_of_mem_roots_of_unity {k : ℕ+} {ζ ξ : units R}
(h : is_primitive_root ζ k) (hξ : ξ ∈ roots_of_unity k R) :
∃ (i : ℕ) (hi : i < k), ζ ^ i = ξ :=
begin
obtain ⟨n, rfl⟩ : ∃ n : ℤ, ζ ^ n = ξ, by rwa [← h.gpowers_eq] at hξ,
have hk0 : (0 : ℤ) < k := by exact_mod_cast k.pos,
let i := n % k,
have hi0 : 0 ≤ i := int.mod_nonneg _ (ne_of_gt hk0),
lift i to ℕ using hi0 with i₀ hi₀,
refine ⟨i₀, _, _⟩,
{ zify, rw [hi₀], exact int.mod_lt_of_pos _ hk0 },
{ have aux := h.gpow_eq_one, rw [← coe_coe] at aux,
rw [← gpow_coe_nat, hi₀, ← int.mod_add_div n k, gpow_add, gpow_mul,
aux, one_gpow, mul_one] }
end
lemma eq_pow_of_pow_eq_one {k : ℕ} {ζ ξ : R}
(h : is_primitive_root ζ k) (hξ : ξ ^ k = 1) (h0 : 0 < k) :
∃ i < k, ζ ^ i = ξ :=
begin
obtain ⟨ζ, rfl⟩ := h.is_unit h0,
obtain ⟨ξ, rfl⟩ := is_unit_of_pow_eq_one ξ k hξ h0,
obtain ⟨k, rfl⟩ : ∃ k' : ℕ+, k = k' := ⟨⟨k, h0⟩, rfl⟩,
simp only [← units.coe_pow, ← units.ext_iff],
rw coe_units_iff at h,
apply h.eq_pow_of_mem_roots_of_unity,
rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, hξ, units.coe_one]
end
lemma is_primitive_root_iff' {k : ℕ+} {ζ ξ : units R} (h : is_primitive_root ζ k) :
is_primitive_root ξ k ↔ ∃ (i < (k : ℕ)) (hi : i.coprime k), ζ ^ i = ξ :=
begin
split,
{ intro hξ,
obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_mem_roots_of_unity hξ.pow_eq_one,
rw h.pow_iff_coprime k.pos at hξ,
exact ⟨i, hik, hξ, rfl⟩ },
{ rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi }
end
lemma is_primitive_root_iff {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (h0 : 0 < k) :
is_primitive_root ξ k ↔ ∃ (i < k) (hi : i.coprime k), ζ ^ i = ξ :=
begin
split,
{ intro hξ,
obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_pow_eq_one hξ.pow_eq_one h0,
rw h.pow_iff_coprime h0 at hξ,
exact ⟨i, hik, hξ, rfl⟩ },
{ rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi }
end
lemma card_roots_of_unity' {n : ℕ+} (h : is_primitive_root ζ n) :
fintype.card (roots_of_unity n R) = n :=
begin
haveI : fact (0 < ↑n) := ⟨n.pos⟩,
let e := h.zmod_equiv_gpowers,
haveI F : fintype (subgroup.gpowers ζ) := fintype.of_equiv _ e.to_equiv,
calc fintype.card (roots_of_unity n R)
= fintype.card (subgroup.gpowers ζ) : fintype.card_congr $ by rw h.gpowers_eq
... = fintype.card (zmod n) : fintype.card_congr e.to_equiv.symm
... = n : zmod.card n
end
lemma card_roots_of_unity {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) :
fintype.card (roots_of_unity n R) = n :=
begin
obtain ⟨ζ, hζ⟩ := h.is_unit n.pos,
rw [← hζ, is_primitive_root.coe_units_iff] at h,
exact h.card_roots_of_unity'
end
/-- The cardinality of the multiset `nth_roots ↑n (1 : R)` is `n`
if there is a primitive root of unity in `R`. -/
lemma card_nth_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) :
(nth_roots n (1 : R)).card = n :=
begin
cases nat.eq_zero_or_pos n with hzero hpos,
{ simp only [hzero, multiset.card_zero, nth_roots_zero] },
rw eq_iff_le_not_lt,
use card_nth_roots n 1,
{ rw [not_lt],
have hcard : fintype.card {x // x ∈ nth_roots n (1 : R)}
≤ (nth_roots n (1 : R)).attach.card := multiset.card_le_of_le (multiset.erase_dup_le _),
rw multiset.card_attach at hcard,
rw ← pnat.to_pnat'_coe hpos at hcard h ⊢,
set m := nat.to_pnat' n,
rw [← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at hcard,
exact hcard }
end
/-- The multiset `nth_roots ↑n (1 : R)` has no repeated elements
if there is a primitive root of unity in `R`. -/
lemma nth_roots_nodup {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).nodup :=
begin
cases nat.eq_zero_or_pos n with hzero hpos,
{ simp only [hzero, multiset.nodup_zero, nth_roots_zero] },
apply (@multiset.erase_dup_eq_self R _ _).1,
rw eq_iff_le_not_lt,
split,
{ exact multiset.erase_dup_le (nth_roots n (1 : R)) },
{ by_contra ha,
replace ha := multiset.card_lt_of_lt ha,
rw card_nth_roots h at ha,
have hrw : (nth_roots n (1 : R)).erase_dup.card =
fintype.card {x // x ∈ (nth_roots n (1 : R))},
{ set fs := (⟨(nth_roots n (1 : R)).erase_dup, multiset.nodup_erase_dup _⟩ : finset R),
rw [← finset.card_mk, ← fintype.card_of_subtype fs _],
intro x,
simp only [multiset.mem_erase_dup, finset.mem_mk] },
rw ← pnat.to_pnat'_coe hpos at h hrw ha,
set m := nat.to_pnat' n,
rw [hrw, ← fintype.card_congr (roots_of_unity_equiv_nth_roots R m),
card_roots_of_unity h] at ha,
exact nat.lt_asymm ha ha }
end
@[simp] lemma card_nth_roots_finset {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) :
(nth_roots_finset n R).card = n :=
by rw [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), card_mk, h.card_nth_roots]
open_locale nat
/-- If an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. -/
lemma card_primitive_roots {ζ : R} {k : ℕ} (h : is_primitive_root ζ k) (h0 : 0 < k) :
(primitive_roots k R).card = φ k :=
begin
symmetry,
refine finset.card_congr (λ i _, ζ ^ i) _ _ _,
{ simp only [true_and, and_imp, mem_filter, mem_range, mem_univ],
rintro i - hi,
rw mem_primitive_roots h0,
exact h.pow_of_coprime i hi.symm },
{ simp only [true_and, and_imp, mem_filter, mem_range, mem_univ],
rintro i j hi - hj - H,
exact h.pow_inj hi hj H },
{ simp only [exists_prop, true_and, mem_filter, mem_range, mem_univ],
intros ξ hξ,
rw [mem_primitive_roots h0, h.is_primitive_root_iff h0] at hξ,
rcases hξ with ⟨i, hin, hi, H⟩,
exact ⟨i, ⟨hin, hi.symm⟩, H⟩ }
end
/-- The sets `primitive_roots k R` are pairwise disjoint. -/
lemma disjoint {k l : ℕ} (hk : 0 < k) (hl : 0 < l) (h : k ≠ l) :
disjoint (primitive_roots k R) (primitive_roots l R) :=
begin
intro z,
simp only [finset.inf_eq_inter, finset.mem_inter, mem_primitive_roots, hk, hl, iff_def],
rintro ⟨⟨hzk, Hzk⟩, ⟨hzl, Hzl⟩⟩,
apply_rules [h, nat.dvd_antisymm, Hzk, Hzl, hzk, hzl]
end
/-- If there is a `n`-th primitive root of unity in `R` and `b` divides `n`,
then there is a `b`-th primitive root of unity in `R`. -/
lemma pow {ζ : R} {n : ℕ} {a b : ℕ}
(hn : 0 < n) (h : is_primitive_root ζ n) (hprod : n = a * b) :
is_primitive_root (ζ ^ a) b :=
begin
subst n,
simp only [iff_def, ← pow_mul, h.pow_eq_one, eq_self_iff_true, true_and],
intros l hl,
have ha0 : a ≠ 0, { rintro rfl, simpa only [nat.not_lt_zero, zero_mul] using hn },
rwa ← mul_dvd_mul_iff_left ha0,
exact h.dvd_of_pow_eq_one _ hl
end
/-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n`
if there is a primitive root of unity in `R`. -/
lemma nth_roots_one_eq_bUnion_primitive_roots' {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) :
nth_roots_finset n R = (nat.divisors ↑n).bUnion (λ i, (primitive_roots i R)) :=
begin
symmetry,
apply finset.eq_of_subset_of_card_le,
{ intros x,
simp only [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h),
exists_prop, finset.mem_bUnion, finset.mem_filter, finset.mem_range, mem_nth_roots,
finset.mem_mk, nat.mem_divisors, and_true, ne.def, pnat.ne_zero, pnat.pos, not_false_iff],
rintro ⟨a, ⟨d, hd⟩, ha⟩,
have hazero : 0 < a,
{ contrapose! hd with ha0,
simp only [nonpos_iff_eq_zero, zero_mul, *] at *,
exact n.ne_zero },
rw mem_primitive_roots hazero at ha,
rw [hd, pow_mul, ha.pow_eq_one, one_pow] },
{ apply le_of_eq,
rw [h.card_nth_roots_finset, finset.card_bUnion],
{ rw [← nat.sum_totient n, nat.filter_dvd_eq_divisors (pnat.ne_zero n), sum_congr rfl]
{ occs := occurrences.pos [1] },
simp only [finset.mem_filter, finset.mem_range, nat.mem_divisors],
rintro k ⟨H, hk⟩,
have hdvd := H,
rcases H with ⟨d, hd⟩,
rw mul_comm at hd,
rw (h.pow n.pos hd).card_primitive_roots (pnat.pos_of_div_pos hdvd) },
{ intros i hi j hj hdiff,
simp only [nat.mem_divisors, and_true, ne.def, pnat.ne_zero, not_false_iff] at hi hj,
exact disjoint (pnat.pos_of_div_pos hi) (pnat.pos_of_div_pos hj) hdiff } }
end
/-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n`
if there is a primitive root of unity in `R`. -/
lemma nth_roots_one_eq_bUnion_primitive_roots {ζ : R} {n : ℕ} (hpos : 0 < n)
(h : is_primitive_root ζ n) :
nth_roots_finset n R = (nat.divisors n).bUnion (λ i, (primitive_roots i R)) :=
@nth_roots_one_eq_bUnion_primitive_roots' _ _ _ ⟨n, hpos⟩ h
end integral_domain
section minpoly
open minpoly
variables {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n)
include n μ h hpos
/--`μ` is integral over `ℤ`. -/
lemma is_integral : is_integral ℤ μ :=
begin
use (X ^ n - 1),
split,
{ exact (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm) },
{ simp only [((is_primitive_root.iff_def μ n).mp h).left, eval₂_one, eval₂_X_pow, eval₂_sub,
sub_self] }
end
variables [char_zero K]
/--The minimal polynomial of a root of unity `μ` divides `X ^ n - 1`. -/
lemma minpoly_dvd_X_pow_sub_one : minpoly ℤ μ ∣ X ^ n - 1 :=
begin
apply integer_dvd (is_integral h hpos) (polynomial.monic.is_primitive
(monic_X_pow_sub_C 1 (ne_of_lt hpos).symm)),
simp only [((is_primitive_root.iff_def μ n).mp h).left, aeval_X_pow, ring_hom.eq_int_cast,
int.cast_one, aeval_one, alg_hom.map_sub, sub_self]
end
/-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is separable. -/
lemma separable_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬p ∣ n) :
separable (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) :=
begin
have hdvd : (map (int.cast_ring_hom (zmod p))
(minpoly ℤ μ)) ∣ X ^ n - 1,
{ simpa [map_pow, map_X, map_one, ring_hom.coe_of, map_sub] using
ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p))))
(minpoly_dvd_X_pow_sub_one h hpos) },
refine separable.of_dvd (separable_X_pow_sub_C 1 _ one_ne_zero) hdvd,
by_contra hzero,
exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 (not_not.1 hzero))
end
/-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is squarefree. -/
lemma squarefree_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬ p ∣ n) :
squarefree (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) :=
(separable_minpoly_mod h hpos hdiv).squarefree
/- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of
`μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `expand ℤ p Q`. -/
lemma minpoly_dvd_expand {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ n) :
minpoly ℤ μ ∣
expand ℤ p (minpoly ℤ (μ ^ p)) :=
begin
apply minpoly.integer_dvd (h.is_integral hpos),
{ apply monic.is_primitive,
rw [polynomial.monic, leading_coeff, nat_degree_expand, mul_comm, coeff_expand_mul'
(nat.prime.pos hprime), ← leading_coeff, ← polynomial.monic],
exact minpoly.monic (is_integral (pow_of_prime h hprime hdiv) hpos) },
{ rw [aeval_def, coe_expand, ← comp, eval₂_eq_eval_map, map_comp, map_pow, map_X, eval_comp,
eval_pow, eval_X, ← eval₂_eq_eval_map, ← aeval_def],
exact minpoly.aeval _ _ }
end
/- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of
`μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q ^ p` modulo `p`. -/
lemma minpoly_dvd_pow_mod {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) :
map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣
map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) ^ p :=
begin
set Q := minpoly ℤ (μ ^ p),
have hfrob : map (int.cast_ring_hom (zmod p)) Q ^ p =
map (int.cast_ring_hom (zmod p)) (expand ℤ p Q),
by rw [← zmod.expand_card, map_expand hprime.1.pos],
rw [hfrob],
apply ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p)))),
exact minpoly_dvd_expand h hpos hprime.1 hdiv
end
/- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of
`μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q` modulo `p`. -/
lemma minpoly_dvd_mod_p {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) :
map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣
map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) :=
(unique_factorization_monoid.dvd_pow_iff_dvd_of_squarefree (squarefree_minpoly_mod h
hpos hdiv) hprime.1.ne_zero).1 (minpoly_dvd_pow_mod h hpos hdiv)
/-- If `p` is a prime that does not divide `n`,
then the minimal polynomials of a primitive `n`-th root of unity `μ`
and of `μ ^ p` are the same. -/
lemma minpoly_eq_pow {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) :
minpoly ℤ μ = minpoly ℤ (μ ^ p) :=
begin
by_contra hdiff,
set P := minpoly ℤ μ,
set Q := minpoly ℤ (μ ^ p),
have Pmonic : P.monic := minpoly.monic (h.is_integral hpos),
have Qmonic : Q.monic := minpoly.monic ((h.pow_of_prime hprime.1 hdiv).is_integral hpos),
have Pirr : irreducible P := minpoly.irreducible (h.is_integral hpos),
have Qirr : irreducible Q :=
minpoly.irreducible ((h.pow_of_prime hprime.1 hdiv).is_integral hpos),
have PQprim : is_primitive (P * Q) := Pmonic.is_primitive.mul Qmonic.is_primitive,
have prod : P * Q ∣ X ^ n - 1,
{ rw [(is_primitive.int.dvd_iff_map_cast_dvd_map_cast (P * Q) (X ^ n - 1) PQprim
(monic_X_pow_sub_C (1 : ℤ) (ne_of_gt hpos)).is_primitive), map_mul],
refine is_coprime.mul_dvd _ _ _,
{ have aux := is_primitive.int.irreducible_iff_irreducible_map_cast Pmonic.is_primitive,
refine (dvd_or_coprime _ _ (aux.1 Pirr)).resolve_left _,
rw map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic,
intro hdiv,
refine hdiff (eq_of_monic_of_associated Pmonic Qmonic _),
exact associated_of_dvd_dvd hdiv (dvd_symm_of_irreducible Pirr Qirr hdiv) },
{ apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic).2,
exact minpoly_dvd_X_pow_sub_one h hpos },
{ apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Qmonic).2,
exact minpoly_dvd_X_pow_sub_one (pow_of_prime h hprime.1 hdiv) hpos } },
replace prod := ring_hom.map_dvd (ring_hom.of (map (int.cast_ring_hom (zmod p)))) prod,
rw [ring_hom.coe_of, map_mul, map_sub, map_one, map_pow, map_X] at prod,
obtain ⟨R, hR⟩ := minpoly_dvd_mod_p h hpos hdiv,
rw [hR, ← mul_assoc, ← map_mul, ← sq, map_pow] at prod,
have habs : map (int.cast_ring_hom (zmod p)) P ^ 2 ∣ map (int.cast_ring_hom (zmod p)) P ^ 2 * R,
{ use R },
replace habs := lt_of_lt_of_le (enat.coe_lt_coe.2 one_lt_two)
(multiplicity.le_multiplicity_of_pow_dvd (dvd_trans habs prod)),
have hfree : squarefree (X ^ n - 1 : polynomial (zmod p)),
{ refine squarefree_X_pow_sub_C 1 _ one_ne_zero,
by_contra hzero,
exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 (not_not.1 hzero)) },
cases (multiplicity.squarefree_iff_multiplicity_le_one (X ^ n - 1)).1 hfree
(map (int.cast_ring_hom (zmod p)) P) with hle hunit,
{ exact not_lt_of_le hle habs },
{ replace hunit := degree_eq_zero_of_is_unit hunit,
rw degree_map_eq_of_leading_coeff_ne_zero _ _ at hunit,
{ exact (ne_of_lt (minpoly.degree_pos (is_integral h hpos))).symm hunit },
simp only [Pmonic, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def,
not_false_iff, one_ne_zero] },
end
/-- If `m : ℕ` is coprime with `n`,
then the minimal polynomials of a primitive `n`-th root of unity `μ`
and of `μ ^ m` are the same. -/
lemma minpoly_eq_pow_coprime {m : ℕ} (hcop : nat.coprime m n) :
minpoly ℤ μ = minpoly ℤ (μ ^ m) :=
begin
revert n hcop,
refine unique_factorization_monoid.induction_on_prime m _ _ _,
{ intros n hn h hpos,
congr,
simpa [(nat.coprime_zero_left n).mp hn] using h },
{ intros u hunit n hcop h hpos,
congr,
simp [nat.is_unit_iff.mp hunit] },
{ intros a p ha hprime hind n hcop h hpos,
rw hind (nat.coprime.coprime_mul_left hcop) h hpos, clear hind,
replace hprime := nat.prime_iff_prime.2 hprime,
have hdiv := (nat.prime.coprime_iff_not_dvd hprime).1 (nat.coprime.coprime_mul_right hcop),
haveI := fact.mk hprime,
rw [minpoly_eq_pow
(h.pow_of_coprime a (nat.coprime.coprime_mul_left hcop)) hpos hdiv],
congr' 1,
ring_exp }
end
/-- If `m : ℕ` is coprime with `n`,
then the minimal polynomial of a primitive `n`-th root of unity `μ`
has `μ ^ m` as root. -/
lemma pow_is_root_minpoly {m : ℕ} (hcop : nat.coprime m n) :
is_root (map (int.cast_ring_hom K) (minpoly ℤ μ)) (μ ^ m) :=
by simpa [minpoly_eq_pow_coprime h hpos hcop, eval_map, aeval_def (μ ^ m) _]
using minpoly.aeval ℤ (μ ^ m)
/-- `primitive_roots n K` is a subset of the roots of the minimal polynomial of a primitive
`n`-th root of unity `μ`. -/
lemma is_roots_of_minpoly : primitive_roots n K ⊆ (map (int.cast_ring_hom K)
(minpoly ℤ μ)).roots.to_finset :=
begin
intros x hx,
obtain ⟨m, hle, hcop, rfl⟩ := (is_primitive_root_iff h hpos).1 ((mem_primitive_roots hpos).1 hx),
simpa [multiset.mem_to_finset,
mem_roots (map_monic_ne_zero $ minpoly.monic $ is_integral h hpos)]
using pow_is_root_minpoly h hpos hcop
end
/-- The degree of the minimal polynomial of `μ` is at least `totient n`. -/
lemma totient_le_degree_minpoly : nat.totient n ≤ (minpoly ℤ μ).nat_degree :=
let P : polynomial ℤ := minpoly ℤ μ,-- minimal polynomial of `μ`
P_K : polynomial K := map (int.cast_ring_hom K) P -- minimal polynomial of `μ` sent to `K[X]`
in calc
n.totient = (primitive_roots n K).card : (h.card_primitive_roots hpos).symm
... ≤ P_K.roots.to_finset.card : finset.card_le_of_subset (is_roots_of_minpoly h hpos)
... ≤ P_K.roots.card : multiset.to_finset_card_le _
... ≤ P_K.nat_degree : (card_roots' $ map_monic_ne_zero
(minpoly.monic $ is_integral h hpos))
... ≤ P.nat_degree : nat_degree_map_le _
end minpoly
end is_primitive_root
|
3ea946c31c75d842738917d3750fb079672d8895 | 0851884047bb567d19e188e8f1ad959c5ae9c5ce | /src/M1P2/sheet-4.lean | 39eb534e0283a5de6688dee46226fbdcb3aa6053 | [
"Apache-2.0"
] | permissive | yz5216/xena-UROP-2018 | 00d3f71a831324966d40d302544ed2cbbec3fd0f | 5e9da9dc64dc51897677f8b73ab9f94061a8d977 | refs/heads/master | 1,584,922,436,989 | 1,531,487,250,000 | 1,531,487,250,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,924 | lean | import algebra.group algebra.group_power init.algebra data.real.basic group_theory.subgroup data.complex.basic group_theory.coset
universes u v w x
variables {G : Type u} {G₂ : Type v} {G₃ : Type w} {G₄ : Type x}
variables [group G] [comm_group G₂] [add_group G₃] [add_comm_group G₄]
-- sheet 4
-- 4. Let S be the two-element set {a, b}. Show that there are precisely 16 distinct binary operations on S. How many of them make S a group? Find a formula for the total number of binary operations on a set of n elements.
--def S' := {}
--theorem sheet04_q4:
-- 5. Prove that multiplication of ℂ numbers is associative.
theorem sheet04_q05 (z z₁ z₂ : ℂ) : z * z₁ * z₂ = z * (z₁ * z₂) := by apply mul_assoc z z₁ z₂
-- 6. Which of the following are groups? Prove one, delete another.
--(a)
--theorem sheet04_q6a_is_T:
--theorem sheet04_q6a_is_F:
-- Let S be the set of all real numbers except −1. For a, b ∈ S define a ∗ b = ab + a + b. Show that (S, ∗) is a group.
def s := {x : ℝ | x ≠ -1}
--theorem q7 (a b : set s)
-- 8. Let G be a group, and let a, b, c ∈ G. Prove the following facts.
--(a) If ab=ac then b=c.
theorem sheet04_q8a (a b c : G) : a * b = a * c ↔ b = c := by apply mul_left_inj a
--(b) The equation axb = c has a unique solution for x ∈ G.
theorem sheet04_q8b (a b c : G) : ∃! x : G, a * x * b = c :=
begin
intros,
existsi (a⁻¹ * c * b⁻¹),simp [mul_assoc],
assume y h,
rw ← h,
simp [mul_assoc],
end
--(c) (a^{−1})^{−1} = a.
theorem sheet04_q8c (a : G) : a⁻¹⁻¹ = a := by apply inv_inv a
--(d) (ab)^{−1} = b^{-1}a^{−1}.
theorem sheet04_q8d (a b : G) : (a*b)⁻¹ = b⁻¹*a⁻¹ := by apply mul_inv_rev a b
-- 9. Let G be a group, and let e be the identity of G. Suppose that x∗x=e for all x∈G. Show that y ∗ z = z ∗ y for all y, z ∈ G.
theorem sheet04_q9 (y z : G) (hp : ∀x : G, x*x = 1) : y * z = z * y := sorry
|
86bcded517665c50febaf879e51afdeb22ed854b | 367134ba5a65885e863bdc4507601606690974c1 | /src/analysis/calculus/fderiv.lean | 1db60e4a925dca94c88d312a71f71e8318e873ed | [
"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 | 121,947 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov
-/
import analysis.calculus.tangent_cone
import analysis.normed_space.units
import analysis.asymptotics.asymptotic_equivalent
import analysis.analytic.basic
/-!
# The Fréchet derivative
Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a
continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then
`has_fderiv_within_at f f' s x`
says that `f` has derivative `f'` at `x`, where the domain of interest
is restricted to `s`. We also have
`has_fderiv_at f f' x := has_fderiv_within_at f f' x univ`
Finally,
`has_strict_fderiv_at f f' x`
means that `f : E → F` has derivative `f' : E →L[𝕜] F` in the sense of strict differentiability,
i.e., `f y - f z - f'(y - z) = o(y - z)` as `y, z → x`. This notion is used in the inverse
function theorem, and is defined here only to avoid proving theorems like
`is_bounded_bilinear_map.has_fderiv_at` twice: first for `has_fderiv_at`, then for
`has_strict_fderiv_at`.
## Main results
In addition to the definition and basic properties of the derivative, this file contains the
usual formulas (and existence assertions) for the derivative of
* constants
* the identity
* bounded linear maps
* bounded bilinear maps
* sum of two functions
* sum of finitely many functions
* multiplication of a function by a scalar constant
* negative of a function
* subtraction of two functions
* multiplication of a function by a scalar function
* multiplication of two scalar functions
* composition of functions (the chain rule)
* inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`)
For most binary operations we also define `const_op` and `op_const` theorems for the cases when
the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier,
and they more frequently lead to the desired result.
One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying
a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are
translated to this more elementary point of view on the derivative in the file `deriv.lean`. The
derivative of polynomials is handled there, as it is naturally one-dimensional.
The simplifier is set up to prove automatically that some functions are differentiable, or
differentiable at a point (but not differentiable on a set or within a set at a point, as checking
automatically that the good domains are mapped one to the other when using composition is not
something the simplifier can easily do). This means that one can write
`example (x : ℝ) : differentiable ℝ (λ x, sin (exp (3 + x^2)) - 5 * cos x) := by simp`.
If there are divisions, one needs to supply to the simplifier proofs that the denominators do
not vanish, as in
```lean
example (x : ℝ) (h : 1 + sin x ≠ 0) : differentiable_at ℝ (λ x, exp x / (1 + sin x)) x :=
by simp [h]
```
Of course, these examples only work once `exp`, `cos` and `sin` have been shown to be
differentiable, in `analysis.special_functions.trigonometric`.
The simplifier is not set up to compute the Fréchet derivative of maps (as these are in general
complicated multidimensional linear maps), but it will compute one-dimensional derivatives,
see `deriv.lean`.
## Implementation details
The derivative is defined in terms of the `is_o` relation, but also
characterized in terms of the `tendsto` relation.
We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field,
`f` the function to be differentiated, `x` the point at which the derivative is asserted to exist,
and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`,
`differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative.
To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x`
for some choice of a derivative if it exists, and the zero function otherwise. This choice only
behaves well along sets for which the derivative is unique, i.e., those for which the tangent
directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and
`unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed
they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular
for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very
beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever.
To make sure that the simplifier can prove automatically that functions are differentiable, we tag
many lemmas with the `simp` attribute, for instance those saying that the sum of differentiable
functions is differentiable, as well as their product, their cartesian product, and so on. A notable
exception is the chain rule: we do not mark as a simp lemma the fact that, if `f` and `g` are
differentiable, then their composition also is: `simp` would always be able to match this lemma,
by taking `f` or `g` to be the identity. Instead, for every reasonable function (say, `exp`),
we add a lemma that if `f` is differentiable then so is `(λ x, exp (f x))`. This means adding
some boilerplate lemmas, but these can also be useful in their own right.
Tests for this ability of the simplifier (with more examples) are provided in
`tests/differentiable.lean`.
## Tags
derivative, differentiable, Fréchet, calculus
-/
open filter asymptotics continuous_linear_map set metric
open_locale topological_space classical nnreal asymptotics filter ennreal
noncomputable theory
section
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
variables {G : Type*} [normed_group G] [normed_space 𝕜 G]
variables {G' : Type*} [normed_group G'] [normed_space 𝕜 G']
/-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition
is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion
of Fréchet derivative, and for `L = 𝓝[s] x` (in `has_fderiv_within_at`), giving rise to
the notion of Fréchet derivative along the set `s`. -/
def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) :=
is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L
/-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/
def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) :=
has_fderiv_at_filter f f' x (𝓝[s] x)
/-- A function `f` has the continuous linear map `f'` as derivative at `x` if
`f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/
def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) :=
has_fderiv_at_filter f f' x (𝓝 x)
/-- A function `f` has derivative `f'` at `a` in the sense of *strict differentiability*
if `f x - f y - f' (x - y) = o(x - y)` as `x, y → a`. This form of differentiability is required,
e.g., by the inverse function theorem. Any `C^1` function on a vector space over `ℝ` is strictly
differentiable but this definition works, e.g., for vector spaces over `p`-adic numbers. -/
def has_strict_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) :=
is_o (λ p : E × E, f p.1 - f p.2 - f' (p.1 - p.2)) (λ p : E × E, p.1 - p.2) (𝓝 (x, x))
variables (𝕜)
/-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative
there (possibly non-unique). -/
def differentiable_within_at (f : E → F) (s : set E) (x : E) :=
∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x
/-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly
non-unique). -/
def differentiable_at (f : E → F) (x : E) :=
∃f' : E →L[𝕜] F, has_fderiv_at f f' x
/-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative.
Otherwise, it is set to `0`. -/
def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F :=
if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0
/-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is
set to `0`. -/
def fderiv (f : E → F) (x : E) : E →L[𝕜] F :=
if h : ∃f', has_fderiv_at f f' x then classical.some h else 0
/-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/
def differentiable_on (f : E → F) (s : set E) :=
∀x ∈ s, differentiable_within_at 𝕜 f s x
/-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/
def differentiable (f : E → F) :=
∀x, differentiable_at 𝕜 f x
variables {𝕜}
variables {f f₀ f₁ g : E → F}
variables {f' f₀' f₁' g' : E →L[𝕜] F}
variables (e : E →L[𝕜] F)
variables {x : E}
variables {s t : set E}
variables {L L₁ L₂ : filter E}
lemma fderiv_within_zero_of_not_differentiable_within_at
(h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 :=
have ¬ ∃ f', has_fderiv_within_at f f' s x, from h,
by simp [fderiv_within, this]
lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 :=
have ¬ ∃ f', has_fderiv_at f f' x, from h,
by simp [fderiv, this]
section derivative_uniqueness
/- In this section, we discuss the uniqueness of the derivative.
We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the
uniqueness of the derivative. -/
/-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f',
i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity
and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses
this fact, for functions having a derivative within a set. Its specific formulation is useful for
tangent cone related discussions. -/
theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α)
{c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s)
(clim : tendsto (λ n, ∥c n∥) l at_top)
(cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) :
tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) :=
begin
have tendsto_arg : tendsto (λ n, x + d n) l (𝓝[s] x),
{ conv in (𝓝[s] x) { rw ← add_zero x },
rw [nhds_within, tendsto_inf],
split,
{ apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) },
{ rwa tendsto_principal } },
have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (𝓝[s] x) := h,
have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l :=
this.comp_tendsto tendsto_arg,
have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'],
have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l :=
(is_O_refl c l).smul_is_o this,
have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l :=
this.trans_is_O (is_O_one_of_tendsto ℝ cdlim),
have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) :=
(is_o_one_iff ℝ).1 this,
have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) :=
tendsto.comp f'.cont.continuous_at cdlim,
have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n)))
l (𝓝 (0 + f' v)) :=
L1.add L2,
have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n)))
= (λn, c n • (f (x + d n) - f x)),
by { ext n, simp [smul_add, smul_sub] },
rwa [this, zero_add] at L3
end
/-- If `f'` and `f₁'` are two derivatives of `f` within `s` at `x`, then they are equal on the
tangent cone to `s` at `x` -/
theorem has_fderiv_within_at.unique_on (hf : has_fderiv_within_at f f' s x)
(hg : has_fderiv_within_at f f₁' s x) :
eq_on f' f₁' (tangent_cone_at 𝕜 s x) :=
λ y ⟨c, d, dtop, clim, cdlim⟩,
tendsto_nhds_unique (hf.lim at_top dtop clim cdlim) (hg.lim at_top dtop clim cdlim)
/-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/
theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x)
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
continuous_linear_map.ext_on H.1 (hf.unique_on hg)
theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s)
(h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
(H x hx).eq h h₁
end derivative_uniqueness
section fderiv_properties
/-! ### Basic properties of the derivative -/
theorem has_fderiv_at_filter_iff_tendsto :
has_fderiv_at_filter f f' x L ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) :=
have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx',
by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp },
begin
unfold has_fderiv_at_filter,
rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h],
exact tendsto_congr (λ _, div_eq_inv_mul),
end
theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝[s] x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔
tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) :=
has_fderiv_at_filter_iff_tendsto
theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔
is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) :=
begin
rw [has_fderiv_at, has_fderiv_at_filter, ← map_add_left_nhds_zero x, is_o_map],
simp [(∘)]
end
/-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz
on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`. -/
lemma has_fderiv_at.le_of_lip {f : E → F} {f' : E →L[𝕜] F} {x₀ : E} (hf : has_fderiv_at f f' x₀)
{s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥f'∥ ≤ C :=
begin
refine le_of_forall_pos_le_add (λ ε ε0, op_norm_le_of_nhds_zero _ _),
exact add_nonneg C.coe_nonneg ε0.le,
have hs' := hs, rw [← map_add_left_nhds_zero x₀, mem_map] at hs',
filter_upwards [is_o_iff.1 (has_fderiv_at_iff_is_o_nhds_zero.1 hf) ε0, hs'], intros y hy hys,
have := hlip.norm_sub_le hys (mem_of_nhds hs), rw add_sub_cancel' at this,
calc ∥f' y∥ ≤ ∥f (x₀ + y) - f x₀∥ + ∥f (x₀ + y) - f x₀ - f' y∥ : norm_le_insert _ _
... ≤ C * ∥y∥ + ε * ∥y∥ : add_le_add this hy
... = (C + ε) * ∥y∥ : (add_mul _ _ _).symm
end
theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) :
has_fderiv_at_filter f f' x L₁ :=
h.mono hst
theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) :
has_fderiv_within_at f f' s x :=
h.mono (nhds_within_mono _ hst)
theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) :
has_fderiv_at_filter f f' x L :=
h.mono hL
theorem has_fderiv_at.has_fderiv_within_at
(h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x :=
h.has_fderiv_at_filter inf_le_left
lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) :
differentiable_within_at 𝕜 f s x :=
⟨f', h⟩
lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x :=
⟨f', h⟩
@[simp] lemma has_fderiv_within_at_univ :
has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x :=
by { simp only [has_fderiv_within_at, nhds_within_univ], refl }
lemma has_strict_fderiv_at.is_O_sub (hf : has_strict_fderiv_at f f' x) :
is_O (λ p : E × E, f p.1 - f p.2) (λ p : E × E, p.1 - p.2) (𝓝 (x, x)) :=
hf.is_O.congr_of_sub.2 (f'.is_O_comp _ _)
lemma has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) :
is_O (λ x', f x' - f x) (λ x', x' - x) L :=
h.is_O.congr_of_sub.2 (f'.is_O_sub _ _)
protected lemma has_strict_fderiv_at.has_fderiv_at (hf : has_strict_fderiv_at f f' x) :
has_fderiv_at f f' x :=
begin
rw [has_fderiv_at, has_fderiv_at_filter, is_o_iff],
exact (λ c hc, tendsto_id.prod_mk_nhds tendsto_const_nhds (is_o_iff.1 hf hc))
end
protected lemma has_strict_fderiv_at.differentiable_at (hf : has_strict_fderiv_at f f' x) :
differentiable_at 𝕜 f x :=
hf.has_fderiv_at.differentiable_at
/-- Directional derivative agrees with `has_fderiv`. -/
lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜}
{l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) :
tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) :=
begin
refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _,
assume U hU,
refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _),
convert mem_of_nhds hU,
dsimp only,
rw [← mul_smul, mul_inv_cancel hy, one_smul]
end
theorem has_fderiv_at.unique
(h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' :=
begin
rw ← has_fderiv_within_at_univ at h₀ h₁,
exact unique_diff_within_at_univ.eq h₀ h₁
end
lemma has_fderiv_within_at_inter' (h : t ∈ 𝓝[s] x) :
has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x :=
by simp [has_fderiv_within_at, nhds_within_restrict'' s h]
lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) :
has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x :=
by simp [has_fderiv_within_at, nhds_within_restrict' s h]
lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x)
(ht : has_fderiv_within_at f f' t x) :
has_fderiv_within_at f f' (s ∪ t) x :=
begin
simp only [has_fderiv_within_at, nhds_within_union],
exact hs.join ht,
end
lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x)
(ht : s ∈ 𝓝[t] x) : has_fderiv_within_at f f' t x :=
(has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) :
has_fderiv_at f f' x :=
by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h
lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) :
has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x :=
begin
dunfold fderiv_within,
dunfold differentiable_within_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) :
has_fderiv_at f (fderiv 𝕜 f x) x :=
begin
dunfold fderiv,
dunfold differentiable_at at h,
rw dif_pos h,
exact classical.some_spec h
end
lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' :=
by { ext, rw h.unique h.differentiable_at.has_fderiv_at }
/-- Converse to the mean value inequality: if `f` is differentiable at `x₀` and `C`-lipschitz
on a neighborhood of `x₀` then it its derivative at `x₀` has norm bounded by `C`.
Version using `fderiv`. -/
lemma fderiv_at.le_of_lip {f : E → F} {x₀ : E} (hf : differentiable_at 𝕜 f x₀)
{s : set E} (hs : s ∈ 𝓝 x₀) {C : ℝ≥0} (hlip : lipschitz_on_with C f s) : ∥fderiv 𝕜 f x₀∥ ≤ C :=
hf.has_fderiv_at.le_of_lip hs hlip
lemma has_fderiv_within_at.fderiv_within
(h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f s x = f' :=
(hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm
/-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`,
as this statement is empty. -/
lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) :
has_fderiv_within_at f f' s x :=
begin
simp only [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, ne.def, not_not] at h,
simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with],
end
lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) :
differentiable_within_at 𝕜 f s x :=
begin
rcases h with ⟨f', hf'⟩,
exact ⟨f', hf'.mono st⟩
end
lemma differentiable_within_at_univ :
differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x :=
by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at]
lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) :
differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter,
nhds_within_restrict' s ht]
lemma differentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) :
differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter,
nhds_within_restrict'' s ht]
lemma differentiable_at.differentiable_within_at
(h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x :=
(differentiable_within_at_univ.2 h).mono (subset_univ _)
lemma differentiable.differentiable_at (h : differentiable 𝕜 f) :
differentiable_at 𝕜 f x :=
h x
lemma differentiable_within_at.differentiable_at
(h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x :=
h.imp (λ f' hf', hf'.has_fderiv_at hs)
lemma differentiable_at.fderiv_within
(h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact h.has_fderiv_at.has_fderiv_within_at
end
lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) :
differentiable_on 𝕜 f s :=
λx hx, (h x (st hx)).mono st
lemma differentiable_on_univ :
differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f :=
by { simp [differentiable_on, differentiable_within_at_univ], refl }
lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s :=
(differentiable_on_univ.2 h).mono (subset_univ _)
lemma differentiable_on_of_locally_differentiable_on
(h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s :=
begin
assume x xs,
rcases h x xs with ⟨t, t_open, xt, ht⟩,
exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩)
end
lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f t x) :
fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x :=
((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht
@[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f :=
begin
ext x : 1,
by_cases h : differentiable_at 𝕜 f x,
{ apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ,
rw has_fderiv_within_at_univ,
apply h.has_fderiv_at },
{ have : ¬ differentiable_within_at 𝕜 f univ x,
by contrapose! h; rwa ← differentiable_within_at_univ,
rw [fderiv_zero_of_not_differentiable_at h,
fderiv_within_zero_of_not_differentiable_within_at this] }
end
lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x :=
begin
by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x,
{ apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h),
apply hs.inter ht },
{ have : ¬ differentiable_within_at 𝕜 f s x,
by contrapose! h; rw differentiable_within_at_inter; assumption,
rw [fderiv_within_zero_of_not_differentiable_within_at h,
fderiv_within_zero_of_not_differentiable_within_at this] }
end
lemma fderiv_within_of_mem_nhds (h : s ∈ 𝓝 x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
begin
have : s = univ ∩ s, by simp only [univ_inter],
rw [this, ← fderiv_within_univ],
exact fderiv_within_inter h (unique_diff_on_univ _ (mem_univ _))
end
lemma fderiv_within_of_open (hs : is_open s) (hx : x ∈ s) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
fderiv_within_of_mem_nhds (mem_nhds_sets hs hx)
lemma fderiv_within_eq_fderiv (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_at 𝕜 f x) :
fderiv_within 𝕜 f s x = fderiv 𝕜 f x :=
begin
rw ← fderiv_within_univ,
exact fderiv_within_subset (subset_univ _) hs h.differentiable_within_at
end
lemma fderiv_mem_iff {f : E → F} {s : set (E →L[𝕜] F)} {x : E} :
fderiv 𝕜 f x ∈ s ↔ (differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s) ∨
(0 : E →L[𝕜] F) ∈ s ∧ ¬differentiable_at 𝕜 f x :=
begin
split,
{ intro hfx,
by_cases hx : differentiable_at 𝕜 f x,
{ exact or.inl ⟨hx, hfx⟩ },
{ rw [fderiv_zero_of_not_differentiable_at hx] at hfx,
exact or.inr ⟨hfx, hx⟩ } },
{ rintro (⟨hf, hf'⟩|⟨h₀, hx⟩),
{ exact hf' },
{ rwa [fderiv_zero_of_not_differentiable_at hx] } }
end
end fderiv_properties
section continuous
/-! ### Deducing continuity from differentiability -/
theorem has_fderiv_at_filter.tendsto_nhds
(hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) :
tendsto f L (𝓝 (f x)) :=
begin
have : tendsto (λ x', f x' - f x) L (𝓝 0),
{ refine h.is_O_sub.trans_tendsto (tendsto.mono_left _ hL),
rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds },
have := tendsto.add this tendsto_const_nhds,
rw zero_add (f x) at this,
exact this.congr (by simp)
end
theorem has_fderiv_within_at.continuous_within_at
(h : has_fderiv_within_at f f' s x) : continuous_within_at f s x :=
has_fderiv_at_filter.tendsto_nhds inf_le_left h
theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) :
continuous_at f x :=
has_fderiv_at_filter.tendsto_nhds (le_refl _) h
lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) :
continuous_within_at f s x :=
let ⟨f', hf'⟩ := h in hf'.continuous_within_at
lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x :=
let ⟨f', hf'⟩ := h in hf'.continuous_at
lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s :=
λx hx, (h x hx).continuous_within_at
lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f :=
continuous_iff_continuous_at.2 $ λx, (h x).continuous_at
protected lemma has_strict_fderiv_at.continuous_at (hf : has_strict_fderiv_at f f' x) :
continuous_at f x :=
hf.has_fderiv_at.continuous_at
lemma has_strict_fderiv_at.is_O_sub_rev {f' : E ≃L[𝕜] F}
(hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) x) :
is_O (λ p : E × E, p.1 - p.2) (λ p : E × E, f p.1 - f p.2) (𝓝 (x, x)) :=
((f'.is_O_comp_rev _ _).trans (hf.trans_is_O (f'.is_O_comp_rev _ _)).right_is_O_add).congr
(λ _, rfl) (λ _, sub_add_cancel _ _)
lemma has_fderiv_at_filter.is_O_sub_rev {f' : E ≃L[𝕜] F}
(hf : has_fderiv_at_filter f (f' : E →L[𝕜] F) x L) :
is_O (λ x', x' - x) (λ x', f x' - f x) L :=
((f'.is_O_sub_rev _ _).trans (hf.trans_is_O (f'.is_O_sub_rev _ _)).right_is_O_add).congr
(λ _, rfl) (λ _, sub_add_cancel _ _)
end continuous
section congr
/-! ### congr properties of the derivative -/
theorem filter.eventually_eq.has_strict_fderiv_at_iff
(h : f₀ =ᶠ[𝓝 x] f₁) (h' : ∀ y, f₀' y = f₁' y) :
has_strict_fderiv_at f₀ f₀' x ↔ has_strict_fderiv_at f₁ f₁' x :=
begin
refine is_o_congr ((h.prod_mk_nhds h).mono _) (eventually_of_forall $ λ _, rfl),
rintros p ⟨hp₁, hp₂⟩,
simp only [*]
end
theorem has_strict_fderiv_at.congr_of_eventually_eq (h : has_strict_fderiv_at f f' x)
(h₁ : f =ᶠ[𝓝 x] f₁) : has_strict_fderiv_at f₁ f' x :=
(h₁.has_strict_fderiv_at_iff (λ _, rfl)).1 h
theorem filter.eventually_eq.has_fderiv_at_filter_iff
(h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L :=
is_o_congr (h₀.mono $ λ y hy, by simp only [hy, h₁, hx]) (eventually_of_forall $ λ _, rfl)
lemma has_fderiv_at_filter.congr_of_eventually_eq (h : has_fderiv_at_filter f f' x L)
(hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L :=
(hL.has_fderiv_at_filter_iff hx $ λ _, rfl).2 h
lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x)
(hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x :=
has_fderiv_at_filter.congr_of_eventually_eq (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx
lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x)
(hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x :=
h.congr_mono hs hx (subset.refl _)
lemma has_fderiv_within_at.congr_of_eventually_eq (h : has_fderiv_within_at f f' s x)
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x :=
has_fderiv_at_filter.congr_of_eventually_eq h h₁ hx
lemma has_fderiv_at.congr_of_eventually_eq (h : has_fderiv_at f f' x)
(h₁ : f₁ =ᶠ[𝓝 x] f) : has_fderiv_at f₁ f' x :=
has_fderiv_at_filter.congr_of_eventually_eq h h₁ (mem_of_nhds h₁ : _)
lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x)
(ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at
lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x)
(ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x :=
differentiable_within_at.congr_mono h ht hx (subset.refl _)
lemma differentiable_within_at.congr_of_eventually_eq
(h : differentiable_within_at 𝕜 f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f)
(hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x :=
(h.has_fderiv_within_at.congr_of_eventually_eq h₁ hx).differentiable_within_at
lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x)
(h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t :=
λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁
lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) :
differentiable_on 𝕜 f₁ s :=
λ x hx, (h x hx).congr h' (h' x hx)
lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) :
differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s :=
⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm),
λ h, differentiable_on.congr h h'⟩
lemma differentiable_at.congr_of_eventually_eq (h : differentiable_at 𝕜 f x) (hL : f₁ =ᶠ[𝓝 x] f) :
differentiable_at 𝕜 f₁ x :=
has_fderiv_at.differentiable_at
(has_fderiv_at_filter.congr_of_eventually_eq h.has_fderiv_at hL (mem_of_nhds hL : _))
lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x)
(hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) :
fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x :=
(has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt
lemma filter.eventually_eq.fderiv_within_eq (hs : unique_diff_within_at 𝕜 s x)
(hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
if h : differentiable_within_at 𝕜 f s x
then has_fderiv_within_at.fderiv_within (h.has_fderiv_within_at.congr_of_eventually_eq hL hx) hs
else
have h' : ¬ differentiable_within_at 𝕜 f₁ s x,
from mt (λ h, h.congr_of_eventually_eq (hL.mono $ λ x, eq.symm) hx.symm) h,
by rw [fderiv_within_zero_of_not_differentiable_within_at h,
fderiv_within_zero_of_not_differentiable_within_at h']
lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x)
(hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
begin
apply filter.eventually_eq.fderiv_within_eq hs _ hx,
apply mem_sets_of_superset self_mem_nhds_within,
exact hL
end
lemma filter.eventually_eq.fderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) :
fderiv 𝕜 f₁ x = fderiv 𝕜 f x :=
begin
have A : f₁ x = f x := hL.eq_of_nhds,
rw [← fderiv_within_univ, ← fderiv_within_univ],
rw ← nhds_within_univ at hL,
exact hL.fderiv_within_eq unique_diff_within_at_univ A
end
end congr
section id
/-! ### Derivative of the identity -/
theorem has_strict_fderiv_at_id (x : E) :
has_strict_fderiv_at id (id 𝕜 E) x :=
(is_o_zero _ _).congr_left $ by simp
theorem has_fderiv_at_filter_id (x : E) (L : filter E) :
has_fderiv_at_filter id (id 𝕜 E) x L :=
(is_o_zero _ _).congr_left $ by simp
theorem has_fderiv_within_at_id (x : E) (s : set E) :
has_fderiv_within_at id (id 𝕜 E) s x :=
has_fderiv_at_filter_id _ _
theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id 𝕜 E) x :=
has_fderiv_at_filter_id _ _
@[simp] lemma differentiable_at_id : differentiable_at 𝕜 id x :=
(has_fderiv_at_id x).differentiable_at
@[simp] lemma differentiable_at_id' : differentiable_at 𝕜 (λ x, x) x :=
(has_fderiv_at_id x).differentiable_at
lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x :=
differentiable_at_id.differentiable_within_at
@[simp] lemma differentiable_id : differentiable 𝕜 (id : E → E) :=
λx, differentiable_at_id
@[simp] lemma differentiable_id' : differentiable 𝕜 (λ (x : E), x) :=
λx, differentiable_at_id
lemma differentiable_on_id : differentiable_on 𝕜 id s :=
differentiable_id.differentiable_on
lemma fderiv_id : fderiv 𝕜 id x = id 𝕜 E :=
has_fderiv_at.fderiv (has_fderiv_at_id x)
@[simp] lemma fderiv_id' : fderiv 𝕜 (λ (x : E), x) x = continuous_linear_map.id 𝕜 E :=
fderiv_id
lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 id s x = id 𝕜 E :=
begin
rw differentiable_at.fderiv_within (differentiable_at_id) hxs,
exact fderiv_id
end
lemma fderiv_within_id' (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λ (x : E), x) s x = continuous_linear_map.id 𝕜 E :=
fderiv_within_id hxs
end id
section const
/-! ### derivative of a constant function -/
theorem has_strict_fderiv_at_const (c : F) (x : E) :
has_strict_fderiv_at (λ _, c) (0 : E →L[𝕜] F) x :=
(is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self]
theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) :
has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L :=
(is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self]
theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) :
has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x :=
has_fderiv_at_filter_const _ _ _
theorem has_fderiv_at_const (c : F) (x : E) :
has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x :=
has_fderiv_at_filter_const _ _ _
@[simp] lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x :=
⟨0, has_fderiv_at_const c x⟩
lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x :=
differentiable_at.differentiable_within_at (differentiable_at_const _)
lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 :=
has_fderiv_at.fderiv (has_fderiv_at_const c x)
@[simp] lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 :=
by { ext m, rw fderiv_const_apply, refl }
lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λy, c) s x = 0 :=
begin
rw differentiable_at.fderiv_within (differentiable_at_const _) hxs,
exact fderiv_const_apply _
end
@[simp] lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) :=
λx, differentiable_at_const _
lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s :=
(differentiable_const _).differentiable_on
end const
section continuous_linear_map
/-!
### Continuous linear maps
There are currently two variants of these in mathlib, the bundled version
(named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a
predicate `is_bounded_linear_map`). We give statements for both versions. -/
protected theorem continuous_linear_map.has_strict_fderiv_at {x : E} :
has_strict_fderiv_at e e x :=
(is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self]
protected lemma continuous_linear_map.has_fderiv_at_filter :
has_fderiv_at_filter e e x L :=
(is_o_zero _ _).congr_left $ λ x, by simp only [e.map_sub, sub_self]
protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x :=
e.has_fderiv_at_filter
protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x :=
e.has_fderiv_at_filter
@[simp] protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x :=
e.has_fderiv_at.differentiable_at
protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x :=
e.differentiable_at.differentiable_within_at
@[simp] protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e :=
e.has_fderiv_at.fderiv
protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 e s x = e :=
begin
rw differentiable_at.fderiv_within e.differentiable_at hxs,
exact e.fderiv
end
@[simp] protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e :=
λx, e.differentiable_at
protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s :=
e.differentiable.differentiable_on
lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_at_filter f h.to_continuous_linear_map x L :=
h.to_continuous_linear_map.has_fderiv_at_filter
lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_within_at f h.to_continuous_linear_map s x :=
h.has_fderiv_at_filter
lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) :
has_fderiv_at f h.to_continuous_linear_map x :=
h.has_fderiv_at_filter
lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) :
differentiable_at 𝕜 f x :=
h.has_fderiv_at.differentiable_at
lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) :
differentiable_within_at 𝕜 f s x :=
h.differentiable_at.differentiable_within_at
lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) :
fderiv 𝕜 f x = h.to_continuous_linear_map :=
has_fderiv_at.fderiv (h.has_fderiv_at)
lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f)
(hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map :=
begin
rw differentiable_at.fderiv_within h.differentiable_at hxs,
exact h.fderiv
end
lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) :
differentiable 𝕜 f :=
λx, h.differentiable_at
lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) :
differentiable_on 𝕜 f s :=
h.differentiable.differentiable_on
end continuous_linear_map
section analytic
variables {p : formal_multilinear_series 𝕜 E F} {r : ℝ≥0∞}
lemma has_fpower_series_at.has_strict_fderiv_at (h : has_fpower_series_at f p x) :
has_strict_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x :=
begin
refine h.is_O_image_sub_norm_mul_norm_sub.trans_is_o (is_o.of_norm_right _),
refine is_o_iff_exists_eq_mul.2 ⟨λ y, ∥y - (x, x)∥, _, eventually_eq.rfl⟩,
refine (continuous_id.sub continuous_const).norm.tendsto' _ _ _,
rw [_root_.id, sub_self, norm_zero]
end
lemma has_fpower_series_at.has_fderiv_at (h : has_fpower_series_at f p x) :
has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p 1)) x :=
h.has_strict_fderiv_at.has_fderiv_at
lemma has_fpower_series_at.differentiable_at (h : has_fpower_series_at f p x) :
differentiable_at 𝕜 f x :=
h.has_fderiv_at.differentiable_at
lemma analytic_at.differentiable_at : analytic_at 𝕜 f x → differentiable_at 𝕜 f x
| ⟨p, hp⟩ := hp.differentiable_at
lemma analytic_at.differentiable_within_at (h : analytic_at 𝕜 f x) :
differentiable_within_at 𝕜 f s x :=
h.differentiable_at.differentiable_within_at
lemma has_fpower_series_at.fderiv (h : has_fpower_series_at f p x) :
fderiv 𝕜 f x = continuous_multilinear_curry_fin1 𝕜 E F (p 1) :=
h.has_fderiv_at.fderiv
lemma has_fpower_series_on_ball.differentiable_on [complete_space F]
(h : has_fpower_series_on_ball f p x r) :
differentiable_on 𝕜 f (emetric.ball x r) :=
λ y hy, (h.analytic_at_of_mem hy).differentiable_within_at
end analytic
section composition
/-!
### Derivative of the composition of two functions
For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to
get confused since there are too many possibilities for composition -/
variable (x)
theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at_filter g g' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (g ∘ f) (g'.comp f') x L :=
let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in
let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in
by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp }
/- A readable version of the previous theorem,
a general form of the chain rule. -/
example {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at_filter g g' (f x) (L.map f))
(hf : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (g ∘ f) (g'.comp f') x L :=
begin
unfold has_fderiv_at_filter at hg,
have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L,
from hg.comp_tendsto (le_refl _),
have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L,
from this.trans_is_O hf.is_O_sub,
have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L,
from hf,
have : is_O
(λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L,
from g'.is_O_comp _ _,
have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L,
from this.trans_is_o eq₂,
have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L,
by { refine this.congr_left _, simp},
exact eq₁.triangle eq₃
end
theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F}
(hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x)
(hst : s ⊆ f ⁻¹' t) :
has_fderiv_within_at (g ∘ f) (g'.comp f') s x :=
begin
apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf,
calc map f (𝓝[s] x)
≤ 𝓝[f '' s] (f x) : hf.continuous_within_at.tendsto_nhds_within_image
... ≤ 𝓝[t] (f x) : nhds_within_mono _ (image_subset_iff.mpr hst)
end
/-- The chain rule. -/
theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) :
has_fderiv_at (g ∘ f) (g'.comp f') x :=
(hg.mono hf.continuous_at).comp x hf
theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G}
(hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (g ∘ f) (g'.comp f') s x :=
begin
rw ← has_fderiv_within_at_univ at hg,
exact has_fderiv_within_at.comp x hg hf subset_preimage_univ
end
lemma differentiable_within_at.comp {g : F → G} {t : set F}
(hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x :=
begin
rcases hf with ⟨f', hf'⟩,
rcases hg with ⟨g', hg'⟩,
exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩
end
lemma differentiable_within_at.comp' {g : F → G} {t : set F}
(hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (g ∘ f) (s ∩ f⁻¹' t) x :=
hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _)
lemma differentiable_at.comp {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (g ∘ f) x :=
(hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at
lemma differentiable_at.comp_differentiable_within_at {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (g ∘ f) s x :=
(differentiable_within_at_univ.2 hg).comp x hf (by simp)
lemma fderiv_within.comp {g : F → G} {t : set F}
(hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x)
(h : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h
end
lemma fderiv.comp {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) :
fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) :=
begin
apply has_fderiv_at.fderiv,
exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at
end
lemma fderiv.comp_fderiv_within {g : F → G}
(hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x)
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at)
end
lemma differentiable_on.comp {g : F → G} {t : set F}
(hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) :
differentiable_on 𝕜 (g ∘ f) s :=
λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st
lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) :
differentiable 𝕜 (g ∘ f) :=
λx, differentiable_at.comp x (hg (f x)) (hf x)
lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g)
(hf : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (g ∘ f) s :=
(differentiable_on_univ.2 hg).comp hf (by simp)
/-- The chain rule for derivatives in the sense of strict differentiability. -/
protected lemma has_strict_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G}
(hg : has_strict_fderiv_at g g' (f x)) (hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, g (f x)) (g'.comp f') x :=
((hg.comp_tendsto (hf.continuous_at.prod_map' hf.continuous_at)).trans_is_O hf.is_O_sub).triangle $
by simpa only [g'.map_sub, f'.coe_comp'] using (g'.is_O_comp _ _).trans_is_o hf
protected lemma differentiable.iterate {f : E → E} (hf : differentiable 𝕜 f) (n : ℕ) :
differentiable 𝕜 (f^[n]) :=
nat.rec_on n differentiable_id (λ n ihn, ihn.comp hf)
protected lemma differentiable_on.iterate {f : E → E} (hf : differentiable_on 𝕜 f s)
(hs : maps_to f s s) (n : ℕ) :
differentiable_on 𝕜 (f^[n]) s :=
nat.rec_on n differentiable_on_id (λ n ihn, ihn.comp hf hs)
variable {x}
protected lemma has_fderiv_at_filter.iterate {f : E → E} {f' : E →L[𝕜] E}
(hf : has_fderiv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) :
has_fderiv_at_filter (f^[n]) (f'^n) x L :=
begin
induction n with n ihn,
{ exact has_fderiv_at_filter_id x L },
{ change has_fderiv_at_filter (f^[n] ∘ f) (f'^(n+1)) x L,
rw [pow_succ'],
refine has_fderiv_at_filter.comp x _ hf,
rw hx,
exact ihn.mono hL }
end
protected lemma has_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E}
(hf : has_fderiv_at f f' x) (hx : f x = x) (n : ℕ) :
has_fderiv_at (f^[n]) (f'^n) x :=
begin
refine hf.iterate _ hx n,
convert hf.continuous_at,
exact hx.symm
end
protected lemma has_fderiv_within_at.iterate {f : E → E} {f' : E →L[𝕜] E}
(hf : has_fderiv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
has_fderiv_within_at (f^[n]) (f'^n) s x :=
begin
refine hf.iterate _ hx n,
convert tendsto_inf.2 ⟨hf.continuous_within_at, _⟩,
exacts [hx.symm, (tendsto_principal_principal.2 hs).mono_left inf_le_right]
end
protected lemma has_strict_fderiv_at.iterate {f : E → E} {f' : E →L[𝕜] E}
(hf : has_strict_fderiv_at f f' x) (hx : f x = x) (n : ℕ) :
has_strict_fderiv_at (f^[n]) (f'^n) x :=
begin
induction n with n ihn,
{ exact has_strict_fderiv_at_id x },
{ change has_strict_fderiv_at (f^[n] ∘ f) (f'^(n+1)) x,
rw [pow_succ'],
refine has_strict_fderiv_at.comp x _ hf,
rwa hx }
end
protected lemma differentiable_at.iterate {f : E → E} (hf : differentiable_at 𝕜 f x)
(hx : f x = x) (n : ℕ) :
differentiable_at 𝕜 (f^[n]) x :=
exists.elim hf $ λ f' hf, (hf.iterate hx n).differentiable_at
protected lemma differentiable_within_at.iterate {f : E → E} (hf : differentiable_within_at 𝕜 f s x)
(hx : f x = x) (hs : maps_to f s s) (n : ℕ) :
differentiable_within_at 𝕜 (f^[n]) s x :=
exists.elim hf $ λ f' hf, (hf.iterate hx hs n).differentiable_within_at
end composition
section cartesian_product
/-! ### Derivative of the cartesian product of two functions -/
section prod
variables {f₂ : E → G} {f₂' : E →L[𝕜] G}
protected lemma has_strict_fderiv_at.prod
(hf₁ : has_strict_fderiv_at f₁ f₁' x) (hf₂ : has_strict_fderiv_at f₂ f₂' x) :
has_strict_fderiv_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x :=
hf₁.prod_left hf₂
lemma has_fderiv_at_filter.prod
(hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) :
has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') x L :=
hf₁.prod_left hf₂
lemma has_fderiv_within_at.prod
(hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) :
has_fderiv_within_at (λx, (f₁ x, f₂ x)) (f₁'.prod f₂') s x :=
hf₁.prod hf₂
lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) :
has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x :=
hf₁.prod hf₂
lemma differentiable_within_at.prod
(hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) :
differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x :=
(hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at
@[simp]
lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) :
differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x :=
(hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at
lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) :
differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s :=
λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx)
@[simp]
lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) :
differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) :=
λ x, differentiable_at.prod (hf₁ x) (hf₂ x)
lemma differentiable_at.fderiv_prod
(hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) :
fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = (fderiv 𝕜 f₁ x).prod (fderiv 𝕜 f₂ x) :=
(hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).fderiv
lemma differentiable_at.fderiv_within_prod
(hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x)
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x =
(fderiv_within 𝕜 f₁ s x).prod (fderiv_within 𝕜 f₂ s x) :=
begin
apply has_fderiv_within_at.fderiv_within _ hxs,
exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at
end
end prod
section fst
variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F}
lemma has_strict_fderiv_at_fst : has_strict_fderiv_at prod.fst (fst 𝕜 E F) p :=
(fst 𝕜 E F).has_strict_fderiv_at
protected lemma has_strict_fderiv_at.fst (h : has_strict_fderiv_at f₂ f₂' x) :
has_strict_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x :=
has_strict_fderiv_at_fst.comp x h
lemma has_fderiv_at_filter_fst {L : filter (E × F)} :
has_fderiv_at_filter prod.fst (fst 𝕜 E F) p L :=
(fst 𝕜 E F).has_fderiv_at_filter
protected lemma has_fderiv_at_filter.fst (h : has_fderiv_at_filter f₂ f₂' x L) :
has_fderiv_at_filter (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x L :=
has_fderiv_at_filter_fst.comp x h
lemma has_fderiv_at_fst : has_fderiv_at prod.fst (fst 𝕜 E F) p :=
has_fderiv_at_filter_fst
protected lemma has_fderiv_at.fst (h : has_fderiv_at f₂ f₂' x) :
has_fderiv_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') x :=
h.fst
lemma has_fderiv_within_at_fst {s : set (E × F)} :
has_fderiv_within_at prod.fst (fst 𝕜 E F) s p :=
has_fderiv_at_filter_fst
protected lemma has_fderiv_within_at.fst (h : has_fderiv_within_at f₂ f₂' s x) :
has_fderiv_within_at (λ x, (f₂ x).1) ((fst 𝕜 F G).comp f₂') s x :=
h.fst
lemma differentiable_at_fst : differentiable_at 𝕜 prod.fst p :=
has_fderiv_at_fst.differentiable_at
@[simp] protected lemma differentiable_at.fst (h : differentiable_at 𝕜 f₂ x) :
differentiable_at 𝕜 (λ x, (f₂ x).1) x :=
differentiable_at_fst.comp x h
lemma differentiable_fst : differentiable 𝕜 (prod.fst : E × F → E) :=
λ x, differentiable_at_fst
@[simp] protected lemma differentiable.fst (h : differentiable 𝕜 f₂) :
differentiable 𝕜 (λ x, (f₂ x).1) :=
differentiable_fst.comp h
lemma differentiable_within_at_fst {s : set (E × F)} : differentiable_within_at 𝕜 prod.fst s p :=
differentiable_at_fst.differentiable_within_at
protected lemma differentiable_within_at.fst (h : differentiable_within_at 𝕜 f₂ s x) :
differentiable_within_at 𝕜 (λ x, (f₂ x).1) s x :=
differentiable_at_fst.comp_differentiable_within_at x h
lemma differentiable_on_fst {s : set (E × F)} : differentiable_on 𝕜 prod.fst s :=
differentiable_fst.differentiable_on
protected lemma differentiable_on.fst (h : differentiable_on 𝕜 f₂ s) :
differentiable_on 𝕜 (λ x, (f₂ x).1) s :=
differentiable_fst.comp_differentiable_on h
lemma fderiv_fst : fderiv 𝕜 prod.fst p = fst 𝕜 E F := has_fderiv_at_fst.fderiv
lemma fderiv.fst (h : differentiable_at 𝕜 f₂ x) :
fderiv 𝕜 (λ x, (f₂ x).1) x = (fst 𝕜 F G).comp (fderiv 𝕜 f₂ x) :=
h.has_fderiv_at.fst.fderiv
lemma fderiv_within_fst {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) :
fderiv_within 𝕜 prod.fst s p = fst 𝕜 E F :=
has_fderiv_within_at_fst.fderiv_within hs
lemma fderiv_within.fst (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) :
fderiv_within 𝕜 (λ x, (f₂ x).1) s x = (fst 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) :=
h.has_fderiv_within_at.fst.fderiv_within hs
end fst
section snd
variables {f₂ : E → F × G} {f₂' : E →L[𝕜] F × G} {p : E × F}
lemma has_strict_fderiv_at_snd : has_strict_fderiv_at prod.snd (snd 𝕜 E F) p :=
(snd 𝕜 E F).has_strict_fderiv_at
protected lemma has_strict_fderiv_at.snd (h : has_strict_fderiv_at f₂ f₂' x) :
has_strict_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x :=
has_strict_fderiv_at_snd.comp x h
lemma has_fderiv_at_filter_snd {L : filter (E × F)} :
has_fderiv_at_filter prod.snd (snd 𝕜 E F) p L :=
(snd 𝕜 E F).has_fderiv_at_filter
protected lemma has_fderiv_at_filter.snd (h : has_fderiv_at_filter f₂ f₂' x L) :
has_fderiv_at_filter (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x L :=
has_fderiv_at_filter_snd.comp x h
lemma has_fderiv_at_snd : has_fderiv_at prod.snd (snd 𝕜 E F) p :=
has_fderiv_at_filter_snd
protected lemma has_fderiv_at.snd (h : has_fderiv_at f₂ f₂' x) :
has_fderiv_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') x :=
h.snd
lemma has_fderiv_within_at_snd {s : set (E × F)} :
has_fderiv_within_at prod.snd (snd 𝕜 E F) s p :=
has_fderiv_at_filter_snd
protected lemma has_fderiv_within_at.snd (h : has_fderiv_within_at f₂ f₂' s x) :
has_fderiv_within_at (λ x, (f₂ x).2) ((snd 𝕜 F G).comp f₂') s x :=
h.snd
lemma differentiable_at_snd : differentiable_at 𝕜 prod.snd p :=
has_fderiv_at_snd.differentiable_at
@[simp] protected lemma differentiable_at.snd (h : differentiable_at 𝕜 f₂ x) :
differentiable_at 𝕜 (λ x, (f₂ x).2) x :=
differentiable_at_snd.comp x h
lemma differentiable_snd : differentiable 𝕜 (prod.snd : E × F → F) :=
λ x, differentiable_at_snd
@[simp] protected lemma differentiable.snd (h : differentiable 𝕜 f₂) :
differentiable 𝕜 (λ x, (f₂ x).2) :=
differentiable_snd.comp h
lemma differentiable_within_at_snd {s : set (E × F)} : differentiable_within_at 𝕜 prod.snd s p :=
differentiable_at_snd.differentiable_within_at
protected lemma differentiable_within_at.snd (h : differentiable_within_at 𝕜 f₂ s x) :
differentiable_within_at 𝕜 (λ x, (f₂ x).2) s x :=
differentiable_at_snd.comp_differentiable_within_at x h
lemma differentiable_on_snd {s : set (E × F)} : differentiable_on 𝕜 prod.snd s :=
differentiable_snd.differentiable_on
protected lemma differentiable_on.snd (h : differentiable_on 𝕜 f₂ s) :
differentiable_on 𝕜 (λ x, (f₂ x).2) s :=
differentiable_snd.comp_differentiable_on h
lemma fderiv_snd : fderiv 𝕜 prod.snd p = snd 𝕜 E F := has_fderiv_at_snd.fderiv
lemma fderiv.snd (h : differentiable_at 𝕜 f₂ x) :
fderiv 𝕜 (λ x, (f₂ x).2) x = (snd 𝕜 F G).comp (fderiv 𝕜 f₂ x) :=
h.has_fderiv_at.snd.fderiv
lemma fderiv_within_snd {s : set (E × F)} (hs : unique_diff_within_at 𝕜 s p) :
fderiv_within 𝕜 prod.snd s p = snd 𝕜 E F :=
has_fderiv_within_at_snd.fderiv_within hs
lemma fderiv_within.snd (hs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f₂ s x) :
fderiv_within 𝕜 (λ x, (f₂ x).2) s x = (snd 𝕜 F G).comp (fderiv_within 𝕜 f₂ s x) :=
h.has_fderiv_within_at.snd.fderiv_within hs
end snd
section prod_map
variables {f₂ : G → G'} {f₂' : G →L[𝕜] G'} {y : G} (p : E × G)
-- TODO (Lean 3.8): use `prod.map f f₂``
protected theorem has_strict_fderiv_at.prod_map (hf : has_strict_fderiv_at f f' p.1)
(hf₂ : has_strict_fderiv_at f₂ f₂' p.2) :
has_strict_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p :=
(hf.comp p has_strict_fderiv_at_fst).prod (hf₂.comp p has_strict_fderiv_at_snd)
protected theorem has_fderiv_at.prod_map (hf : has_fderiv_at f f' p.1)
(hf₂ : has_fderiv_at f₂ f₂' p.2) :
has_fderiv_at (λ p : E × G, (f p.1, f₂ p.2)) (f'.prod_map f₂') p :=
(hf.comp p has_fderiv_at_fst).prod (hf₂.comp p has_fderiv_at_snd)
@[simp] protected theorem differentiable_at.prod_map (hf : differentiable_at 𝕜 f p.1)
(hf₂ : differentiable_at 𝕜 f₂ p.2) :
differentiable_at 𝕜 (λ p : E × G, (f p.1, f₂ p.2)) p :=
(hf.comp p differentiable_at_fst).prod (hf₂.comp p differentiable_at_snd)
end prod_map
end cartesian_product
section const_smul
/-! ### Derivative of a function multiplied by a constant -/
theorem has_strict_fderiv_at.const_smul (h : has_strict_fderiv_at f f' x) (c : 𝕜) :
has_strict_fderiv_at (λ x, c • f x) (c • f') x :=
(c • (1 : F →L[𝕜] F)).has_strict_fderiv_at.comp x h
theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) :
has_fderiv_at_filter (λ x, c • f x) (c • f') x L :=
(c • (1 : F →L[𝕜] F)).has_fderiv_at_filter.comp x h
theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) :
has_fderiv_within_at (λ x, c • f x) (c • f') s x :=
h.const_smul c
theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) :
has_fderiv_at (λ x, c • f x) (c • f') x :=
h.const_smul c
lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) :
differentiable_within_at 𝕜 (λy, c • f y) s x :=
(h.has_fderiv_within_at.const_smul c).differentiable_within_at
lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) :
differentiable_at 𝕜 (λy, c • f y) x :=
(h.has_fderiv_at.const_smul c).differentiable_at
lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) :
differentiable_on 𝕜 (λy, c • f y) s :=
λx hx, (h x hx).const_smul c
lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) :
differentiable 𝕜 (λy, c • f y) :=
λx, (h x).const_smul c
lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f s x) (c : 𝕜) :
fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x :=
(h.has_fderiv_within_at.const_smul c).fderiv_within hxs
lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) :
fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x :=
(h.has_fderiv_at.const_smul c).fderiv
end const_smul
section add
/-! ### Derivative of the sum of two functions -/
theorem has_strict_fderiv_at.add (hf : has_strict_fderiv_at f f' x)
(hg : has_strict_fderiv_at g g' x) :
has_strict_fderiv_at (λ y, f y + g y) (f' + g') x :=
(hf.add hg).congr_left $ λ y, by simp; abel
theorem has_fderiv_at_filter.add
(hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) :
has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L :=
(hf.add hg).congr_left $ λ _, by simp; abel
theorem has_fderiv_within_at.add
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ y, f y + g y) (f' + g') s x :=
hf.add hg
theorem has_fderiv_at.add
(hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ x, f x + g x) (f' + g') x :=
hf.add hg
lemma differentiable_within_at.add
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
differentiable_within_at 𝕜 (λ y, f y + g y) s x :=
(hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at
@[simp] lemma differentiable_at.add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
differentiable_at 𝕜 (λ y, f y + g y) x :=
(hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at
lemma differentiable_on.add
(hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) :
differentiable_on 𝕜 (λy, f y + g y) s :=
λx hx, (hf x hx).add (hg x hx)
@[simp] lemma differentiable.add
(hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) :
differentiable 𝕜 (λy, f y + g y) :=
λx, (hf x).add (hg x)
lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x :=
(hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_add
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x :=
(hf.has_fderiv_at.add hg.has_fderiv_at).fderiv
theorem has_strict_fderiv_at.add_const (hf : has_strict_fderiv_at f f' x) (c : F) :
has_strict_fderiv_at (λ y, f y + c) f' x :=
add_zero f' ▸ hf.add (has_strict_fderiv_at_const _ _)
theorem has_fderiv_at_filter.add_const
(hf : has_fderiv_at_filter f f' x L) (c : F) :
has_fderiv_at_filter (λ y, f y + c) f' x L :=
add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _)
theorem has_fderiv_within_at.add_const
(hf : has_fderiv_within_at f f' s x) (c : F) :
has_fderiv_within_at (λ y, f y + c) f' s x :=
hf.add_const c
theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F):
has_fderiv_at (λ x, f x + c) f' x :=
hf.add_const c
lemma differentiable_within_at.add_const
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
differentiable_within_at 𝕜 (λ y, f y + c) s x :=
(hf.has_fderiv_within_at.add_const c).differentiable_within_at
@[simp] lemma differentiable_within_at_add_const_iff (c : F) :
differentiable_within_at 𝕜 (λ y, f y + c) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩
lemma differentiable_at.add_const
(hf : differentiable_at 𝕜 f x) (c : F) :
differentiable_at 𝕜 (λ y, f y + c) x :=
(hf.has_fderiv_at.add_const c).differentiable_at
@[simp] lemma differentiable_at_add_const_iff (c : F) :
differentiable_at 𝕜 (λ y, f y + c) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩
lemma differentiable_on.add_const
(hf : differentiable_on 𝕜 f s) (c : F) :
differentiable_on 𝕜 (λy, f y + c) s :=
λx hx, (hf x hx).add_const c
@[simp] lemma differentiable_on_add_const_iff (c : F) :
differentiable_on 𝕜 (λ y, f y + c) s ↔ differentiable_on 𝕜 f s :=
⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩
lemma differentiable.add_const
(hf : differentiable 𝕜 f) (c : F) :
differentiable 𝕜 (λy, f y + c) :=
λx, (hf x).add_const c
@[simp] lemma differentiable_add_const_iff (c : F) :
differentiable 𝕜 (λ y, f y + c) ↔ differentiable 𝕜 f :=
⟨λ h, by simpa using h.add_const (-c), λ h, h.add_const c⟩
lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x :=
if hf : differentiable_within_at 𝕜 f s x
then (hf.has_fderiv_within_at.add_const c).fderiv_within hxs
else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf,
fderiv_within_zero_of_not_differentiable_within_at], simpa }
lemma fderiv_add_const (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x :=
by simp only [← fderiv_within_univ, fderiv_within_add_const unique_diff_within_at_univ]
theorem has_strict_fderiv_at.const_add (hf : has_strict_fderiv_at f f' x) (c : F) :
has_strict_fderiv_at (λ y, c + f y) f' x :=
zero_add f' ▸ (has_strict_fderiv_at_const _ _).add hf
theorem has_fderiv_at_filter.const_add
(hf : has_fderiv_at_filter f f' x L) (c : F) :
has_fderiv_at_filter (λ y, c + f y) f' x L :=
zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf
theorem has_fderiv_within_at.const_add
(hf : has_fderiv_within_at f f' s x) (c : F) :
has_fderiv_within_at (λ y, c + f y) f' s x :=
hf.const_add c
theorem has_fderiv_at.const_add
(hf : has_fderiv_at f f' x) (c : F):
has_fderiv_at (λ x, c + f x) f' x :=
hf.const_add c
lemma differentiable_within_at.const_add
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
differentiable_within_at 𝕜 (λ y, c + f y) s x :=
(hf.has_fderiv_within_at.const_add c).differentiable_within_at
@[simp] lemma differentiable_within_at_const_add_iff (c : F) :
differentiable_within_at 𝕜 (λ y, c + f y) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩
lemma differentiable_at.const_add
(hf : differentiable_at 𝕜 f x) (c : F) :
differentiable_at 𝕜 (λ y, c + f y) x :=
(hf.has_fderiv_at.const_add c).differentiable_at
@[simp] lemma differentiable_at_const_add_iff (c : F) :
differentiable_at 𝕜 (λ y, c + f y) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩
lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) :
differentiable_on 𝕜 (λy, c + f y) s :=
λx hx, (hf x hx).const_add c
@[simp] lemma differentiable_on_const_add_iff (c : F) :
differentiable_on 𝕜 (λ y, c + f y) s ↔ differentiable_on 𝕜 f s :=
⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩
lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) :
differentiable 𝕜 (λy, c + f y) :=
λx, (hf x).const_add c
@[simp] lemma differentiable_const_add_iff (c : F) :
differentiable 𝕜 (λ y, c + f y) ↔ differentiable 𝕜 f :=
⟨λ h, by simpa using h.const_add (-c), λ h, h.const_add c⟩
lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x :=
by simpa only [add_comm] using fderiv_within_add_const hxs c
lemma fderiv_const_add (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x :=
by simp only [add_comm c, fderiv_add_const]
end add
section sum
/-! ### Derivative of a finite sum of functions -/
open_locale big_operators
variables {ι : Type*} {u : finset ι} {A : ι → (E → F)} {A' : ι → (E →L[𝕜] F)}
theorem has_strict_fderiv_at.sum (h : ∀ i ∈ u, has_strict_fderiv_at (A i) (A' i) x) :
has_strict_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
begin
dsimp [has_strict_fderiv_at] at *,
convert is_o.sum h,
simp [finset.sum_sub_distrib, continuous_linear_map.sum_apply]
end
theorem has_fderiv_at_filter.sum (h : ∀ i ∈ u, has_fderiv_at_filter (A i) (A' i) x L) :
has_fderiv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L :=
begin
dsimp [has_fderiv_at_filter] at *,
convert is_o.sum h,
simp [continuous_linear_map.sum_apply]
end
theorem has_fderiv_within_at.sum (h : ∀ i ∈ u, has_fderiv_within_at (A i) (A' i) s x) :
has_fderiv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x :=
has_fderiv_at_filter.sum h
theorem has_fderiv_at.sum (h : ∀ i ∈ u, has_fderiv_at (A i) (A' i) x) :
has_fderiv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x :=
has_fderiv_at_filter.sum h
theorem differentiable_within_at.sum (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
differentiable_within_at 𝕜 (λ y, ∑ i in u, A i y) s x :=
has_fderiv_within_at.differentiable_within_at $ has_fderiv_within_at.sum $
λ i hi, (h i hi).has_fderiv_within_at
@[simp] theorem differentiable_at.sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
differentiable_at 𝕜 (λ y, ∑ i in u, A i y) x :=
has_fderiv_at.differentiable_at $ has_fderiv_at.sum $ λ i hi, (h i hi).has_fderiv_at
theorem differentiable_on.sum (h : ∀ i ∈ u, differentiable_on 𝕜 (A i) s) :
differentiable_on 𝕜 (λ y, ∑ i in u, A i y) s :=
λ x hx, differentiable_within_at.sum $ λ i hi, h i hi x hx
@[simp] theorem differentiable.sum (h : ∀ i ∈ u, differentiable 𝕜 (A i)) :
differentiable 𝕜 (λ y, ∑ i in u, A i y) :=
λ x, differentiable_at.sum $ λ i hi, h i hi x
theorem fderiv_within_sum (hxs : unique_diff_within_at 𝕜 s x)
(h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) :
fderiv_within 𝕜 (λ y, ∑ i in u, A i y) s x = (∑ i in u, fderiv_within 𝕜 (A i) s x) :=
(has_fderiv_within_at.sum (λ i hi, (h i hi).has_fderiv_within_at)).fderiv_within hxs
theorem fderiv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) :
fderiv 𝕜 (λ y, ∑ i in u, A i y) x = (∑ i in u, fderiv 𝕜 (A i) x) :=
(has_fderiv_at.sum (λ i hi, (h i hi).has_fderiv_at)).fderiv
end sum
section pi
/-!
### Derivatives of functions `f : E → Π i, F' i`
In this section we formulate `has_*fderiv*_pi` theorems as `iff`s, and provide two versions of each
theorem:
* the version without `'` deals with `φ : Π i, E → F' i` and `φ' : Π i, E →L[𝕜] F' i`
and is designed to deduce differentiability of `λ x i, φ i x` from differentiability
of each `φ i`;
* the version with `'` deals with `Φ : E → Π i, F' i` and `Φ' : E →L[𝕜] Π i, F' i`
and is designed to deduce differentiability of the components `λ x, Φ x i` from
differentiability of `Φ`.
-/
variables {ι : Type*} [fintype ι] {F' : ι → Type*} [Π i, normed_group (F' i)]
[Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {φ' : Π i, E →L[𝕜] F' i}
{Φ : E → Π i, F' i} {Φ' : E →L[𝕜] Π i, F' i}
@[simp] lemma has_strict_fderiv_at_pi' :
has_strict_fderiv_at Φ Φ' x ↔
∀ i, has_strict_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x :=
begin
simp only [has_strict_fderiv_at, continuous_linear_map.coe_pi],
exact is_o_pi
end
@[simp] lemma has_strict_fderiv_at_pi :
has_strict_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔
∀ i, has_strict_fderiv_at (φ i) (φ' i) x :=
has_strict_fderiv_at_pi'
@[simp] lemma has_fderiv_at_filter_pi' :
has_fderiv_at_filter Φ Φ' x L ↔
∀ i, has_fderiv_at_filter (λ x, Φ x i) ((proj i).comp Φ') x L :=
begin
simp only [has_fderiv_at_filter, continuous_linear_map.coe_pi],
exact is_o_pi
end
lemma has_fderiv_at_filter_pi :
has_fderiv_at_filter (λ x i, φ i x) (continuous_linear_map.pi φ') x L ↔
∀ i, has_fderiv_at_filter (φ i) (φ' i) x L :=
has_fderiv_at_filter_pi'
@[simp] lemma has_fderiv_at_pi' :
has_fderiv_at Φ Φ' x ↔
∀ i, has_fderiv_at (λ x, Φ x i) ((proj i).comp Φ') x :=
has_fderiv_at_filter_pi'
lemma has_fderiv_at_pi :
has_fderiv_at (λ x i, φ i x) (continuous_linear_map.pi φ') x ↔
∀ i, has_fderiv_at (φ i) (φ' i) x :=
has_fderiv_at_filter_pi
@[simp] lemma has_fderiv_within_at_pi' :
has_fderiv_within_at Φ Φ' s x ↔
∀ i, has_fderiv_within_at (λ x, Φ x i) ((proj i).comp Φ') s x :=
has_fderiv_at_filter_pi'
lemma has_fderiv_within_at_pi :
has_fderiv_within_at (λ x i, φ i x) (continuous_linear_map.pi φ') s x ↔
∀ i, has_fderiv_within_at (φ i) (φ' i) s x :=
has_fderiv_at_filter_pi
@[simp] lemma differentiable_within_at_pi :
differentiable_within_at 𝕜 Φ s x ↔
∀ i, differentiable_within_at 𝕜 (λ x, Φ x i) s x :=
⟨λ h i, (has_fderiv_within_at_pi'.1 h.has_fderiv_within_at i).differentiable_within_at,
λ h, (has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).differentiable_within_at⟩
@[simp] lemma differentiable_at_pi :
differentiable_at 𝕜 Φ x ↔ ∀ i, differentiable_at 𝕜 (λ x, Φ x i) x :=
⟨λ h i, (has_fderiv_at_pi'.1 h.has_fderiv_at i).differentiable_at,
λ h, (has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).differentiable_at⟩
lemma differentiable_on_pi :
differentiable_on 𝕜 Φ s ↔ ∀ i, differentiable_on 𝕜 (λ x, Φ x i) s :=
⟨λ h i x hx, differentiable_within_at_pi.1 (h x hx) i,
λ h x hx, differentiable_within_at_pi.2 (λ i, h i x hx)⟩
lemma differentiable_pi :
differentiable 𝕜 Φ ↔ ∀ i, differentiable 𝕜 (λ x, Φ x i) :=
⟨λ h i x, differentiable_at_pi.1 (h x) i, λ h x, differentiable_at_pi.2 (λ i, h i x)⟩
-- TODO: find out which version (`φ` or `Φ`) works better with `rw`/`simp`
lemma fderiv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (φ i) s x)
(hs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λ x i, φ i x) s x = pi (λ i, fderiv_within 𝕜 (φ i) s x) :=
(has_fderiv_within_at_pi.2 (λ i, (h i).has_fderiv_within_at)).fderiv_within hs
lemma fderiv_pi (h : ∀ i, differentiable_at 𝕜 (φ i) x) :
fderiv 𝕜 (λ x i, φ i x) x = pi (λ i, fderiv 𝕜 (φ i) x) :=
(has_fderiv_at_pi.2 (λ i, (h i).has_fderiv_at)).fderiv
end pi
section neg
/-! ### Derivative of the negative of a function -/
theorem has_strict_fderiv_at.neg (h : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ x, -f x) (-f') x :=
(-1 : F →L[𝕜] F).has_strict_fderiv_at.comp x h
theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) :
has_fderiv_at_filter (λ x, -f x) (-f') x L :=
(-1 : F →L[𝕜] F).has_fderiv_at_filter.comp x h
theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ x, -f x) (-f') s x :=
h.neg
theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) :
has_fderiv_at (λ x, -f x) (-f') x :=
h.neg
lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (λy, -f y) s x :=
h.has_fderiv_within_at.neg.differentiable_within_at
@[simp] lemma differentiable_within_at_neg_iff :
differentiable_within_at 𝕜 (λy, -f y) s x ↔ differentiable_within_at 𝕜 f s x :=
⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩
lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (λy, -f y) x :=
h.has_fderiv_at.neg.differentiable_at
@[simp] lemma differentiable_at_neg_iff :
differentiable_at 𝕜 (λy, -f y) x ↔ differentiable_at 𝕜 f x :=
⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩
lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (λy, -f y) s :=
λx hx, (h x hx).neg
@[simp] lemma differentiable_on_neg_iff :
differentiable_on 𝕜 (λy, -f y) s ↔ differentiable_on 𝕜 f s :=
⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩
lemma differentiable.neg (h : differentiable 𝕜 f) :
differentiable 𝕜 (λy, -f y) :=
λx, (h x).neg
@[simp] lemma differentiable_neg_iff : differentiable 𝕜 (λy, -f y) ↔ differentiable 𝕜 f :=
⟨λ h, by simpa only [neg_neg] using h.neg, λ h, h.neg⟩
lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x :=
if h : differentiable_within_at 𝕜 f s x
then h.has_fderiv_within_at.neg.fderiv_within hxs
else by { rw [fderiv_within_zero_of_not_differentiable_within_at h,
fderiv_within_zero_of_not_differentiable_within_at, neg_zero], simpa }
@[simp] lemma fderiv_neg : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x :=
by simp only [← fderiv_within_univ, fderiv_within_neg unique_diff_within_at_univ]
end neg
section sub
/-! ### Derivative of the difference of two functions -/
theorem has_strict_fderiv_at.sub
(hf : has_strict_fderiv_at f f' x) (hg : has_strict_fderiv_at g g' x) :
has_strict_fderiv_at (λ x, f x - g x) (f' - g') x :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
theorem has_fderiv_at_filter.sub
(hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) :
has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
theorem has_fderiv_within_at.sub
(hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) :
has_fderiv_within_at (λ x, f x - g x) (f' - g') s x :=
hf.sub hg
theorem has_fderiv_at.sub
(hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) :
has_fderiv_at (λ x, f x - g x) (f' - g') x :=
hf.sub hg
lemma differentiable_within_at.sub
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
differentiable_within_at 𝕜 (λ y, f y - g y) s x :=
(hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at
@[simp] lemma differentiable_at.sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
differentiable_at 𝕜 (λ y, f y - g y) x :=
(hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at
lemma differentiable_on.sub
(hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) :
differentiable_on 𝕜 (λy, f y - g y) s :=
λx hx, (hf x hx).sub (hg x hx)
@[simp] lemma differentiable.sub
(hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) :
differentiable 𝕜 (λy, f y - g y) :=
λx, (hf x).sub (hg x)
lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x)
(hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) :
fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x :=
(hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_sub
(hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) :
fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x :=
(hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv
theorem has_strict_fderiv_at.sub_const
(hf : has_strict_fderiv_at f f' x) (c : F) :
has_strict_fderiv_at (λ x, f x - c) f' x :=
by simpa only [sub_eq_add_neg] using hf.add_const (-c)
theorem has_fderiv_at_filter.sub_const
(hf : has_fderiv_at_filter f f' x L) (c : F) :
has_fderiv_at_filter (λ x, f x - c) f' x L :=
by simpa only [sub_eq_add_neg] using hf.add_const (-c)
theorem has_fderiv_within_at.sub_const
(hf : has_fderiv_within_at f f' s x) (c : F) :
has_fderiv_within_at (λ x, f x - c) f' s x :=
hf.sub_const c
theorem has_fderiv_at.sub_const
(hf : has_fderiv_at f f' x) (c : F) :
has_fderiv_at (λ x, f x - c) f' x :=
hf.sub_const c
lemma differentiable_within_at.sub_const
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
differentiable_within_at 𝕜 (λ y, f y - c) s x :=
(hf.has_fderiv_within_at.sub_const c).differentiable_within_at
@[simp] lemma differentiable_within_at_sub_const_iff (c : F) :
differentiable_within_at 𝕜 (λ y, f y - c) s x ↔ differentiable_within_at 𝕜 f s x :=
by simp only [sub_eq_add_neg, differentiable_within_at_add_const_iff]
lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) :
differentiable_at 𝕜 (λ y, f y - c) x :=
(hf.has_fderiv_at.sub_const c).differentiable_at
@[simp] lemma differentiable_at_sub_const_iff (c : F) :
differentiable_at 𝕜 (λ y, f y - c) x ↔ differentiable_at 𝕜 f x :=
by simp only [sub_eq_add_neg, differentiable_at_add_const_iff]
lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) :
differentiable_on 𝕜 (λy, f y - c) s :=
λx hx, (hf x hx).sub_const c
@[simp] lemma differentiable_on_sub_const_iff (c : F) :
differentiable_on 𝕜 (λ y, f y - c) s ↔ differentiable_on 𝕜 f s :=
by simp only [sub_eq_add_neg, differentiable_on_add_const_iff]
lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) :
differentiable 𝕜 (λy, f y - c) :=
λx, (hf x).sub_const c
@[simp] lemma differentiable_sub_const_iff (c : F) :
differentiable 𝕜 (λ y, f y - c) ↔ differentiable 𝕜 f :=
by simp only [sub_eq_add_neg, differentiable_add_const_iff]
lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x :=
by simp only [sub_eq_add_neg, fderiv_within_add_const hxs]
lemma fderiv_sub_const (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x :=
by simp only [sub_eq_add_neg, fderiv_add_const]
theorem has_strict_fderiv_at.const_sub
(hf : has_strict_fderiv_at f f' x) (c : F) :
has_strict_fderiv_at (λ x, c - f x) (-f') x :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_fderiv_at_filter.const_sub
(hf : has_fderiv_at_filter f f' x L) (c : F) :
has_fderiv_at_filter (λ x, c - f x) (-f') x L :=
by simpa only [sub_eq_add_neg] using hf.neg.const_add c
theorem has_fderiv_within_at.const_sub
(hf : has_fderiv_within_at f f' s x) (c : F) :
has_fderiv_within_at (λ x, c - f x) (-f') s x :=
hf.const_sub c
theorem has_fderiv_at.const_sub
(hf : has_fderiv_at f f' x) (c : F) :
has_fderiv_at (λ x, c - f x) (-f') x :=
hf.const_sub c
lemma differentiable_within_at.const_sub
(hf : differentiable_within_at 𝕜 f s x) (c : F) :
differentiable_within_at 𝕜 (λ y, c - f y) s x :=
(hf.has_fderiv_within_at.const_sub c).differentiable_within_at
@[simp] lemma differentiable_within_at_const_sub_iff (c : F) :
differentiable_within_at 𝕜 (λ y, c - f y) s x ↔ differentiable_within_at 𝕜 f s x :=
by simp [sub_eq_add_neg]
lemma differentiable_at.const_sub
(hf : differentiable_at 𝕜 f x) (c : F) :
differentiable_at 𝕜 (λ y, c - f y) x :=
(hf.has_fderiv_at.const_sub c).differentiable_at
@[simp] lemma differentiable_at_const_sub_iff (c : F) :
differentiable_at 𝕜 (λ y, c - f y) x ↔ differentiable_at 𝕜 f x :=
by simp [sub_eq_add_neg]
lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) :
differentiable_on 𝕜 (λy, c - f y) s :=
λx hx, (hf x hx).const_sub c
@[simp] lemma differentiable_on_const_sub_iff (c : F) :
differentiable_on 𝕜 (λ y, c - f y) s ↔ differentiable_on 𝕜 f s :=
by simp [sub_eq_add_neg]
lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) :
differentiable 𝕜 (λy, c - f y) :=
λx, (hf x).const_sub c
@[simp] lemma differentiable_const_sub_iff (c : F) :
differentiable 𝕜 (λ y, c - f y) ↔ differentiable 𝕜 f :=
by simp [sub_eq_add_neg]
lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) :
fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x :=
by simp only [sub_eq_add_neg, fderiv_within_const_add, fderiv_within_neg, hxs]
lemma fderiv_const_sub (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x :=
by simp only [← fderiv_within_univ, fderiv_within_const_sub unique_diff_within_at_univ]
end sub
section bilinear_map
/-! ### Derivative of a bounded bilinear map -/
variables {b : E × F → G} {u : set (E × F) }
open normed_field
lemma is_bounded_bilinear_map.has_strict_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_strict_fderiv_at b (h.deriv p) p :=
begin
rw has_strict_fderiv_at,
set T := (E × F) × (E × F),
have : is_o (λ q : T, b (q.1 - q.2)) (λ q : T, ∥q.1 - q.2∥ * 1) (𝓝 (p, p)),
{ refine (h.is_O'.comp_tendsto le_top).trans_is_o _,
simp only [(∘)],
refine (is_O_refl (λ q : T, ∥q.1 - q.2∥) _).mul_is_o (is_o.norm_left $ (is_o_one_iff _).2 _),
rw [← sub_self p],
exact continuous_at_fst.sub continuous_at_snd },
simp only [mul_one, is_o_norm_right] at this,
refine (is_o.congr_of_sub _).1 this, clear this,
convert_to is_o (λ q : T, h.deriv (p - q.2) (q.1 - q.2)) (λ q : T, q.1 - q.2) (𝓝 (p, p)),
{ ext ⟨⟨x₁, y₁⟩, ⟨x₂, y₂⟩⟩, rcases p with ⟨x, y⟩,
simp only [is_bounded_bilinear_map_deriv_coe, prod.mk_sub_mk, h.map_sub_left, h.map_sub_right],
abel },
have : is_o (λ q : T, p - q.2) (λ q, (1:ℝ)) (𝓝 (p, p)),
from (is_o_one_iff _).2 (sub_self p ▸ tendsto_const_nhds.sub continuous_at_snd),
apply is_bounded_bilinear_map_apply.is_O_comp.trans_is_o,
refine is_o.trans_is_O _ (is_O_const_mul_self 1 _ _).of_norm_right,
refine is_o.mul_is_O _ (is_O_refl _ _),
exact (((h.is_bounded_linear_map_deriv.is_O_id ⊤).comp_tendsto le_top : _).trans_is_o
this).norm_left
end
lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_fderiv_at b (h.deriv p) p :=
(h.has_strict_fderiv_at p).has_fderiv_at
lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_fderiv_within_at b (h.deriv p) u p :=
(h.has_fderiv_at p).has_fderiv_within_at
lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
differentiable_at 𝕜 b p :=
(h.has_fderiv_at p).differentiable_at
lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b)
(p : E × F) :
differentiable_within_at 𝕜 b u p :=
(h.differentiable_at p).differentiable_within_at
lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
fderiv 𝕜 b p = h.deriv p :=
has_fderiv_at.fderiv (h.has_fderiv_at p)
lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F)
(hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p :=
begin
rw differentiable_at.fderiv_within (h.differentiable_at p) hxs,
exact h.fderiv p
end
lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) :
differentiable 𝕜 b :=
λx, h.differentiable_at x
lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) :
differentiable_on 𝕜 b u :=
h.differentiable.differentiable_on
lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) :
continuous b :=
h.differentiable.continuous
lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} :
continuous (λe, b (e, f)) :=
h.continuous.comp (continuous_id.prod_mk continuous_const)
lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} :
continuous (λf, b (e, f)) :=
h.continuous.comp (continuous_const.prod_mk continuous_id)
end bilinear_map
namespace continuous_linear_equiv
/-!
### The set of continuous linear equivalences between two Banach spaces is open
In this section we establish that the set of continuous linear equivalences between two Banach
spaces is an open subset of the space of linear maps between them. These facts are placed here
because the proof uses `is_bounded_bilinear_map.continuous_left`, proved just above as a consequence
of its differentiability.
-/
protected lemma is_open [complete_space E] : is_open (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) :=
begin
nontriviality E,
rw [is_open_iff_mem_nhds, forall_range_iff],
refine λ e, mem_nhds_sets _ (mem_range_self _),
let O : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : F →L[𝕜] E).comp f,
have h_O : continuous O := is_bounded_bilinear_map_comp.continuous_left,
convert units.is_open.preimage h_O using 1,
ext f',
split,
{ rintros ⟨e', rfl⟩,
exact ⟨(e'.trans e.symm).to_unit, rfl⟩ },
{ rintros ⟨w, hw⟩,
use (units_equiv 𝕜 E w).trans e,
ext x,
simp [hw] }
end
protected lemma nhds [complete_space E] (e : E ≃L[𝕜] F) :
(range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) ∈ 𝓝 (e : E →L[𝕜] F) :=
mem_nhds_sets continuous_linear_equiv.is_open (by simp)
end continuous_linear_equiv
section smul
/-! ### Derivative of the product of a scalar-valued function and a vector-valued function
If `c` is a differentiable scalar-valued function and `f` is a differentiable vector-valued
function, then `λ x, c x • f x` is differentiable as well. Lemmas in this section works for
function `c` taking values in the base field, as well as in a normed algebra over the base
field: e.g., they work for `c : E → ℂ` and `f : E → F` provided that `F` is a complex
normed vector space.
-/
variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
[normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F]
variables {c : E → 𝕜'} {c' : E →L[𝕜] 𝕜'}
theorem has_strict_fderiv_at.smul (hc : has_strict_fderiv_at c c' x)
(hf : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x :=
(is_bounded_bilinear_map_smul.has_strict_fderiv_at (c x, f x)).comp x $
hc.prod hf
theorem has_fderiv_within_at.smul
(hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) :
has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x :=
(is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp_has_fderiv_within_at x $
hc.prod hf
theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) :
has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x :=
(is_bounded_bilinear_map_smul.has_fderiv_at (c x, f x)).comp x $
hc.prod hf
lemma differentiable_within_at.smul
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
differentiable_within_at 𝕜 (λ y, c y • f y) s x :=
(hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at
@[simp] lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (λ y, c y • f y) x :=
(hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at
lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (λ y, c y • f y) s :=
λx hx, (hc x hx).smul (hf x hx)
@[simp] lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) :
differentiable 𝕜 (λ y, c y • f y) :=
λx, (hc x).smul (hf x)
lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) :
fderiv_within 𝕜 (λ y, c y • f y) s x =
c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) :=
(hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) :
fderiv 𝕜 (λ y, c y • f y) x =
c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) :=
(hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv
theorem has_strict_fderiv_at.smul_const (hc : has_strict_fderiv_at c c' x) (f : F) :
has_strict_fderiv_at (λ y, c y • f) (c'.smul_right f) x :=
by simpa only [smul_zero, zero_add] using hc.smul (has_strict_fderiv_at_const f x)
theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) :
has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x :=
by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_within_at_const f x s)
theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) :
has_fderiv_at (λ y, c y • f) (c'.smul_right f) x :=
by simpa only [smul_zero, zero_add] using hc.smul (has_fderiv_at_const f x)
lemma differentiable_within_at.smul_const
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
differentiable_within_at 𝕜 (λ y, c y • f) s x :=
(hc.has_fderiv_within_at.smul_const f).differentiable_within_at
lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
differentiable_at 𝕜 (λ y, c y • f) x :=
(hc.has_fderiv_at.smul_const f).differentiable_at
lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) :
differentiable_on 𝕜 (λ y, c y • f) s :=
λx hx, (hc x hx).smul_const f
lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) :
differentiable 𝕜 (λ y, c y • f) :=
λx, (hc x).smul_const f
lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (f : F) :
fderiv_within 𝕜 (λ y, c y • f) s x =
(fderiv_within 𝕜 c s x).smul_right f :=
(hc.has_fderiv_within_at.smul_const f).fderiv_within hxs
lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) :
fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f :=
(hc.has_fderiv_at.smul_const f).fderiv
end smul
section mul
/-! ### Derivative of the product of two scalar-valued functions -/
variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜}
theorem has_strict_fderiv_at.mul
(hc : has_strict_fderiv_at c c' x) (hd : has_strict_fderiv_at d d' x) :
has_strict_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x :=
by { convert hc.smul hd, ext z, apply mul_comm }
theorem has_fderiv_within_at.mul
(hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) :
has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x :=
by { convert hc.smul hd, ext z, apply mul_comm }
theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) :
has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x :=
by { convert hc.smul hd, ext z, apply mul_comm }
lemma differentiable_within_at.mul
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
differentiable_within_at 𝕜 (λ y, c y * d y) s x :=
(hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at
@[simp] lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
differentiable_at 𝕜 (λ y, c y * d y) x :=
(hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at
lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) :
differentiable_on 𝕜 (λ y, c y * d y) s :=
λx hx, (hc x hx).mul (hd x hx)
@[simp] lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) :
differentiable 𝕜 (λ y, c y * d y) :=
λx, (hc x).mul (hd x)
lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) :
fderiv_within 𝕜 (λ y, c y * d y) s x =
c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x :=
(hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs
lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) :
fderiv 𝕜 (λ y, c y * d y) x =
c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x :=
(hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv
theorem has_strict_fderiv_at.mul_const (hc : has_strict_fderiv_at c c' x) (d : 𝕜) :
has_strict_fderiv_at (λ y, c y * d) (d • c') x :=
by simpa only [smul_zero, zero_add] using hc.mul (has_strict_fderiv_at_const d x)
theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) :
has_fderiv_within_at (λ y, c y * d) (d • c') s x :=
by simpa only [smul_zero, zero_add] using hc.mul (has_fderiv_within_at_const d x s)
theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) :
has_fderiv_at (λ y, c y * d) (d • c') x :=
begin
rw [← has_fderiv_within_at_univ] at *,
exact hc.mul_const d
end
lemma differentiable_within_at.mul_const
(hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) :
differentiable_within_at 𝕜 (λ y, c y * d) s x :=
(hc.has_fderiv_within_at.mul_const d).differentiable_within_at
lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) :
differentiable_at 𝕜 (λ y, c y * d) x :=
(hc.has_fderiv_at.mul_const d).differentiable_at
lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) :
differentiable_on 𝕜 (λ y, c y * d) s :=
λx hx, (hc x hx).mul_const d
lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) :
differentiable 𝕜 (λ y, c y * d) :=
λx, (hc x).mul_const d
lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) :
fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x :=
(hc.has_fderiv_within_at.mul_const d).fderiv_within hxs
lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) :
fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x :=
(hc.has_fderiv_at.mul_const d).fderiv
theorem has_strict_fderiv_at.const_mul (hc : has_strict_fderiv_at c c' x) (d : 𝕜) :
has_strict_fderiv_at (λ y, d * c y) (d • c') x :=
begin
simp only [mul_comm d],
exact hc.mul_const d,
end
theorem has_fderiv_within_at.const_mul
(hc : has_fderiv_within_at c c' s x) (d : 𝕜) :
has_fderiv_within_at (λ y, d * c y) (d • c') s x :=
begin
simp only [mul_comm d],
exact hc.mul_const d,
end
theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) :
has_fderiv_at (λ y, d * c y) (d • c') x :=
begin
simp only [mul_comm d],
exact hc.mul_const d,
end
lemma differentiable_within_at.const_mul
(hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) :
differentiable_within_at 𝕜 (λ y, d * c y) s x :=
(hc.has_fderiv_within_at.const_mul d).differentiable_within_at
lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) :
differentiable_at 𝕜 (λ y, d * c y) x :=
(hc.has_fderiv_at.const_mul d).differentiable_at
lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) :
differentiable_on 𝕜 (λ y, d * c y) s :=
λx hx, (hc x hx).const_mul d
lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) :
differentiable 𝕜 (λ y, d * c y) :=
λx, (hc x).const_mul d
lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x)
(hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) :
fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x :=
(hc.has_fderiv_within_at.const_mul d).fderiv_within hxs
lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) :
fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x :=
(hc.has_fderiv_at.const_mul d).fderiv
end mul
section algebra_inverse
variables {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] [complete_space R]
open normed_ring continuous_linear_map ring
/-- At an invertible element `x` of a normed algebra `R`, the Fréchet derivative of the inversion
operation is the linear map `λ t, - x⁻¹ * t * x⁻¹`. -/
lemma has_fderiv_at_ring_inverse (x : units R) :
has_fderiv_at ring.inverse (-lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹) x :=
begin
have h_is_o : is_o (λ (t : R), inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹)
(λ (t : R), t) (𝓝 0),
{ refine (inverse_add_norm_diff_second_order x).trans_is_o ((is_o_norm_norm).mp _),
simp only [normed_field.norm_pow, norm_norm],
have h12 : 1 < 2 := by norm_num,
convert (asymptotics.is_o_pow_pow h12).comp_tendsto tendsto_norm_zero,
ext, simp },
have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0),
{ refine tendsto_zero_iff_norm_tendsto_zero.mpr _,
exact tendsto_iff_norm_tendsto_zero.mp tendsto_id },
simp only [has_fderiv_at, has_fderiv_at_filter],
convert h_is_o.comp_tendsto h_lim,
ext y,
simp only [coe_comp', function.comp_app, lmul_left_right_apply, neg_apply, inverse_unit x,
units.inv_mul, add_sub_cancel'_right, mul_sub, sub_mul, one_mul, sub_neg_eq_add]
end
lemma differentiable_at_inverse (x : units R) : differentiable_at 𝕜 (@ring.inverse R _) x :=
(has_fderiv_at_ring_inverse x).differentiable_at
lemma fderiv_inverse (x : units R) :
fderiv 𝕜 (@ring.inverse R _) x = - lmul_left_right 𝕜 R ↑x⁻¹ ↑x⁻¹ :=
(has_fderiv_at_ring_inverse x).fderiv
end algebra_inverse
namespace continuous_linear_equiv
/-! ### Differentiability of linear equivs, and invariance of differentiability -/
variable (iso : E ≃L[𝕜] F)
protected lemma has_strict_fderiv_at :
has_strict_fderiv_at iso (iso : E →L[𝕜] F) x :=
iso.to_continuous_linear_map.has_strict_fderiv_at
protected lemma has_fderiv_within_at :
has_fderiv_within_at iso (iso : E →L[𝕜] F) s x :=
iso.to_continuous_linear_map.has_fderiv_within_at
protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x :=
iso.to_continuous_linear_map.has_fderiv_at_filter
protected lemma differentiable_at : differentiable_at 𝕜 iso x :=
iso.has_fderiv_at.differentiable_at
protected lemma differentiable_within_at :
differentiable_within_at 𝕜 iso s x :=
iso.differentiable_at.differentiable_within_at
protected lemma fderiv : fderiv 𝕜 iso x = iso :=
iso.has_fderiv_at.fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 iso s x = iso :=
iso.to_continuous_linear_map.fderiv_within hxs
protected lemma differentiable : differentiable 𝕜 iso :=
λx, iso.differentiable_at
protected lemma differentiable_on : differentiable_on 𝕜 iso s :=
iso.differentiable.differentiable_on
lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} :
differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x :=
begin
refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩,
have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x :=
iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H,
rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this,
end
lemma comp_differentiable_at_iff {f : G → E} {x : G} :
differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x :=
by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ,
iso.comp_differentiable_within_at_iff]
lemma comp_differentiable_on_iff {f : G → E} {s : set G} :
differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s :=
begin
rw [differentiable_on, differentiable_on],
simp only [iso.comp_differentiable_within_at_iff],
end
lemma comp_differentiable_iff {f : G → E} :
differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f :=
begin
rw [← differentiable_on_univ, ← differentiable_on_univ],
exact iso.comp_differentiable_on_iff
end
lemma comp_has_fderiv_within_at_iff
{f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} :
has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x :=
begin
refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩,
have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl },
have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'),
by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe,
continuous_linear_map.id_comp],
rw [A, B],
exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H
end
lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} :
has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x :=
begin
refine ⟨λ H, _, λ H, iso.has_strict_fderiv_at.comp x H⟩,
convert iso.symm.has_strict_fderiv_at.comp x H; ext z; apply (iso.symm_apply_apply _).symm
end
lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} :
has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x :=
by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff]
lemma comp_has_fderiv_within_at_iff'
{f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} :
has_fderiv_within_at (iso ∘ f) f' s x ↔
has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x :=
by rw [← iso.comp_has_fderiv_within_at_iff, ← continuous_linear_map.comp_assoc,
iso.coe_comp_coe_symm, continuous_linear_map.id_comp]
lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} :
has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x :=
by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff']
lemma comp_fderiv_within {f : G → E} {s : set G} {x : G}
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) :=
begin
by_cases h : differentiable_within_at 𝕜 f s x,
{ rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] },
{ have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x,
from mt iso.comp_differentiable_within_at_iff.1 h,
rw [fderiv_within_zero_of_not_differentiable_within_at h,
fderiv_within_zero_of_not_differentiable_within_at this,
continuous_linear_map.comp_zero] }
end
lemma comp_fderiv {f : G → E} {x : G} :
fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) :=
begin
rw [← fderiv_within_univ, ← fderiv_within_univ],
exact iso.comp_fderiv_within unique_diff_within_at_univ,
end
end continuous_linear_equiv
namespace linear_isometry_equiv
/-! ### Differentiability of linear isometry equivs, and invariance of differentiability -/
variable (iso : E ≃ₗᵢ[𝕜] F)
protected lemma has_strict_fderiv_at : has_strict_fderiv_at iso (iso : E →L[𝕜] F) x :=
(iso : E ≃L[𝕜] F).has_strict_fderiv_at
protected lemma has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x :=
(iso : E ≃L[𝕜] F).has_fderiv_within_at
protected lemma has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x :=
(iso : E ≃L[𝕜] F).has_fderiv_at
protected lemma differentiable_at : differentiable_at 𝕜 iso x :=
iso.has_fderiv_at.differentiable_at
protected lemma differentiable_within_at :
differentiable_within_at 𝕜 iso s x :=
iso.differentiable_at.differentiable_within_at
protected lemma fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv
protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 iso s x = iso :=
(iso : E ≃L[𝕜] F).fderiv_within hxs
protected lemma differentiable : differentiable 𝕜 iso :=
λx, iso.differentiable_at
protected lemma differentiable_on : differentiable_on 𝕜 iso s :=
iso.differentiable.differentiable_on
lemma comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} :
differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x :=
(iso : E ≃L[𝕜] F).comp_differentiable_within_at_iff
lemma comp_differentiable_at_iff {f : G → E} {x : G} :
differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x :=
(iso : E ≃L[𝕜] F).comp_differentiable_at_iff
lemma comp_differentiable_on_iff {f : G → E} {s : set G} :
differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s :=
(iso : E ≃L[𝕜] F).comp_differentiable_on_iff
lemma comp_differentiable_iff {f : G → E} :
differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f :=
(iso : E ≃L[𝕜] F).comp_differentiable_iff
lemma comp_has_fderiv_within_at_iff
{f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} :
has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x :=
(iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff
lemma comp_has_strict_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} :
has_strict_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_strict_fderiv_at f f' x :=
(iso : E ≃L[𝕜] F).comp_has_strict_fderiv_at_iff
lemma comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} :
has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x :=
(iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff
lemma comp_has_fderiv_within_at_iff'
{f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} :
has_fderiv_within_at (iso ∘ f) f' s x ↔
has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x :=
(iso : E ≃L[𝕜] F).comp_has_fderiv_within_at_iff'
lemma comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} :
has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x :=
(iso : E ≃L[𝕜] F).comp_has_fderiv_at_iff'
lemma comp_fderiv_within {f : G → E} {s : set G} {x : G}
(hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) :=
(iso : E ≃L[𝕜] F).comp_fderiv_within hxs
lemma comp_fderiv {f : G → E} {x : G} :
fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) :=
(iso : E ≃L[𝕜] F).comp_fderiv
end linear_isometry_equiv
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a`
in the strict sense.
This is one of the easy parts of the inverse function theorem: it assumes that we already have an
inverse function. -/
theorem has_strict_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F}
(hg : continuous_at g a) (hf : has_strict_fderiv_at f (f' : E →L[𝕜] F) (g a))
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_strict_fderiv_at g (f'.symm : F →L[𝕜] E) a :=
begin
replace hg := hg.prod_map' hg,
replace hfg := hfg.prod_mk_nhds hfg,
have : is_O (λ p : F × F, g p.1 - g p.2 - f'.symm (p.1 - p.2))
(λ p : F × F, f' (g p.1 - g p.2) - (p.1 - p.2)) (𝓝 (a, a)),
{ refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl),
simp },
refine this.trans_is_o _, clear this,
refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _)
(eventually_of_forall $ λ _, rfl)).trans_is_O _,
{ rintros p ⟨hp1, hp2⟩,
simp [hp1, hp2] },
{ refine (hf.is_O_sub_rev.comp_tendsto hg).congr'
(eventually_of_forall $ λ _, rfl) (hfg.mono _),
rintros p ⟨hp1, hp2⟩,
simp only [(∘), hp1, hp2] }
end
/-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an
invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
theorem has_fderiv_at.of_local_left_inverse {f : E → F} {f' : E ≃L[𝕜] F} {g : F → E} {a : F}
(hg : continuous_at g a) (hf : has_fderiv_at f (f' : E →L[𝕜] F) (g a))
(hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) :
has_fderiv_at g (f'.symm : F →L[𝕜] E) a :=
begin
have : is_O (λ x : F, g x - g a - f'.symm (x - a)) (λ x : F, f' (g x - g a) - (x - a)) (𝓝 a),
{ refine ((f'.symm : F →L[𝕜] E).is_O_comp _ _).congr (λ x, _) (λ _, rfl),
simp },
refine this.trans_is_o _, clear this,
refine ((hf.comp_tendsto hg).symm.congr' (hfg.mono _)
(eventually_of_forall $ λ _, rfl)).trans_is_O _,
{ rintros p hp,
simp [hp, hfg.self_of_nhds] },
{ refine (hf.is_O_sub_rev.comp_tendsto hg).congr'
(eventually_of_forall $ λ _, rfl) (hfg.mono _),
rintros p hp,
simp only [(∘), hp, hfg.self_of_nhds] }
end
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an
invertible derivative `f'` in the sense of strict differentiability at `f.symm a`, then `f.symm` has
the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
lemma local_homeomorph.has_strict_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F}
(ha : a ∈ f.target) (htff' : has_strict_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) :
has_strict_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha)
/-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an
invertible derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`.
This is one of the easy parts of the inverse function theorem: it assumes that we already have
an inverse function. -/
lemma local_homeomorph.has_fderiv_at_symm (f : local_homeomorph E F) {f' : E ≃L[𝕜] F} {a : F}
(ha : a ∈ f.target) (htff' : has_fderiv_at f (f' : E →L[𝕜] F) (f.symm a)) :
has_fderiv_at f.symm (f'.symm : F →L[𝕜] E) a :=
htff'.of_local_left_inverse (f.symm.continuous_at ha) (f.eventually_right_inverse ha)
lemma has_fderiv_within_at.eventually_ne (h : has_fderiv_within_at f f' s x)
(hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) :
∀ᶠ z in 𝓝[s \ {x}] x, f z ≠ f x :=
begin
rw [nhds_within, diff_eq, ← inf_principal, ← inf_assoc, eventually_inf_principal],
have A : is_O (λ z, z - x) (λ z, f' (z - x)) (𝓝[s] x) :=
(is_O_iff.2 $ hf'.imp $ λ C hC, eventually_of_forall $ λ z, hC _),
have : (λ z, f z - f x) ~[𝓝[s] x] (λ z, f' (z - x)) := h.trans_is_O A,
simpa [not_imp_not, sub_eq_zero] using (A.trans this.is_O_symm).eq_zero_imp
end
lemma has_fderiv_at.eventually_ne (h : has_fderiv_at f f' x) (hf' : ∃ C, ∀ z, ∥z∥ ≤ C * ∥f' z∥) :
∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x :=
by simpa only [compl_eq_univ_diff] using (has_fderiv_within_at_univ.2 h).eventually_ne hf'
end
section
/-
In the special case of a normed space over the reals,
we can use scalar multiplication in the `tendsto` characterization
of the Fréchet derivative.
-/
variables {E : Type*} [normed_group E] [normed_space ℝ E]
variables {F : Type*} [normed_group F] [normed_space ℝ F]
variables {f : E → F} {f' : E →L[ℝ] F} {x : E}
theorem has_fderiv_at_filter_real_equiv {L : filter E} :
tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔
tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) :=
begin
symmetry,
rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _),
have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _),
simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this]
end
lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) :
tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) :=
begin
apply hf.lim v,
rw tendsto_at_top_at_top,
exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩
end
end
section tangent_cone
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
{f : E → F} {s : set E} {f' : E →L[𝕜] F}
/-- The image of a tangent cone under the differential of a map is included in the tangent cone to
the image. -/
lemma has_fderiv_within_at.maps_to_tangent_cone {x : E} (h : has_fderiv_within_at f f' s x) :
maps_to f' (tangent_cone_at 𝕜 s x) (tangent_cone_at 𝕜 (f '' s) (f x)) :=
begin
rintros v ⟨c, d, dtop, clim, cdlim⟩,
refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim,
h.lim at_top dtop clim cdlim⟩,
simp [-mem_image, mem_image_of_mem] {contextual := tt}
end
/-- If a set has the unique differentiability property at a point x, then the image of this set
under a map with onto derivative has also the unique differentiability property at the image point.
-/
lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x)
(hs : unique_diff_within_at 𝕜 s x) (h' : dense_range f') :
unique_diff_within_at 𝕜 (f '' s) (f x) :=
begin
refine ⟨h'.dense_of_maps_to f'.continuous hs.1 _,
h.continuous_within_at.mem_closure_image hs.2⟩,
show submodule.span 𝕜 (tangent_cone_at 𝕜 s x) ≤
(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))).comap f',
rw [submodule.span_le],
exact h.maps_to_tangent_cone.mono (subset.refl _) submodule.subset_span
end
lemma unique_diff_on.image {f' : E → E →L[𝕜] F} (hs : unique_diff_on 𝕜 s)
(hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hd : ∀ x ∈ s, dense_range (f' x)) :
unique_diff_on 𝕜 (f '' s) :=
ball_image_iff.2 $ λ x hx, (hf' x hx).unique_diff_within_at (hs x hx) (hd x hx)
lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv
{x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x)
(hs : unique_diff_within_at 𝕜 s x) :
unique_diff_within_at 𝕜 (f '' s) (f x) :=
h.unique_diff_within_at hs e'.surjective.dense_range
lemma continuous_linear_equiv.unique_diff_on_image (e : E ≃L[𝕜] F) (h : unique_diff_on 𝕜 s) :
unique_diff_on 𝕜 (e '' s) :=
h.image (λ x _, e.has_fderiv_within_at) (λ x hx, e.surjective.dense_range)
@[simp] lemma continuous_linear_equiv.unique_diff_on_image_iff (e : E ≃L[𝕜] F) :
unique_diff_on 𝕜 (e '' s) ↔ unique_diff_on 𝕜 s :=
⟨λ h, e.symm_image_image s ▸ e.symm.unique_diff_on_image h, e.unique_diff_on_image⟩
@[simp] lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) :
unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s :=
by rw [← e.image_symm_eq_preimage, e.symm.unique_diff_on_image_iff]
end tangent_cone
section restrict_scalars
/-!
### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜`
If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph,
we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced
respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`.
-/
variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜]
variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E]
variables [is_scalar_tower 𝕜 𝕜' E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [normed_space 𝕜' F]
variables [is_scalar_tower 𝕜 𝕜' F]
variables {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E}
lemma has_strict_fderiv_at.restrict_scalars (h : has_strict_fderiv_at f f' x) :
has_strict_fderiv_at f (f'.restrict_scalars 𝕜) x := h
lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) :
has_fderiv_at f (f'.restrict_scalars 𝕜) x := h
lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) :
has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h
lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) :
differentiable_at 𝕜 f x :=
(h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at
lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) :
differentiable_within_at 𝕜 f s x :=
(h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at
lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) :
differentiable_on 𝕜 f s :=
λx hx, (h x hx).restrict_scalars 𝕜
lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) :
differentiable 𝕜 f :=
λx, (h x).restrict_scalars 𝕜
end restrict_scalars
|
9aecf898d94158b5c6a38c262c60c97b1c0b6a59 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/errorRecoveryBug.lean | f4f7465c2a5e203a04819266310905c537ed5079 | [
"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 | 21 | lean | inductive A | b (c :
|
8dbf1c73e6c577e5bf262787569d5b7bc7efaa25 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/algebra/ordered_field.lean | 96eb8de4ad067c8ee33d327694948529681a8469 | [
"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 | 23,372 | lean | /-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis
-/
import algebra.ordered_ring algebra.field
open eq
structure linear_ordered_field [class] (A : Type) extends linear_ordered_ring A, field A
section linear_ordered_field
variable {A : Type}
variables [s : linear_ordered_field A] {a b c d : A}
include s
-- helpers for following
theorem mul_zero_lt_mul_inv_of_pos (H : 0 < a) : a * 0 < a * (1 / a) :=
sorry
/-
calc
a * 0 = 0 : by rewrite mul_zero
... < 1 : !zero_lt_one
... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne.symm (ne_of_lt H)))
... = a * (1 / a) : by rewrite inv_eq_one_div
-/
theorem mul_zero_lt_mul_inv_of_neg (H : a < 0) : a * 0 < a * (1 / a) :=
sorry
/-
calc
a * 0 = 0 : by rewrite mul_zero
... < 1 : !zero_lt_one
... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne_of_lt H))
... = a * (1 / a) : by rewrite inv_eq_one_div
-/
theorem one_div_pos_of_pos (H : 0 < a) : 0 < 1 / a :=
lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos H) (le_of_lt H)
theorem one_div_neg_of_neg (H : a < 0) : 1 / a < 0 :=
gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg H) (le_of_lt H)
theorem le_mul_of_ge_one_right (Hb : b ≥ 0) (H : a ≥ 1) : b ≤ b * a :=
mul_one _ ▸ (mul_le_mul_of_nonneg_left H Hb)
theorem lt_mul_of_gt_one_right (Hb : b > 0) (H : a > 1) : b < b * a :=
mul_one _ ▸ (mul_lt_mul_of_pos_left H Hb)
theorem one_le_div_iff_le (a : A) {b : A} (Hb : b > 0) : 1 ≤ a / b ↔ b ≤ a :=
have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb),
iff.intro
(assume H : 1 ≤ a / b,
calc
b = b : rfl
... ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt Hb) H
... = a : mul_div_cancel' Hb')
(assume H : b ≤ a,
have Hbinv : 1 / b > 0, from one_div_pos_of_pos Hb, calc
1 = b * (1 / b) : eq.symm (mul_one_div_cancel Hb')
... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt Hbinv)
... = a / b : eq.symm $ div_eq_mul_one_div a b)
theorem le_of_one_le_div (Hb : b > 0) (H : 1 ≤ a / b) : b ≤ a :=
iff.mp (one_le_div_iff_le a Hb) H
theorem one_le_div_of_le (Hb : b > 0) (H : b ≤ a) : 1 ≤ a / b :=
iff.mpr (one_le_div_iff_le a Hb) H
theorem one_lt_div_iff_lt (a : A) {b : A} (Hb : b > 0) : 1 < a / b ↔ b < a :=
have Hb' : b ≠ 0, from ne.symm (ne_of_lt Hb),
iff.intro
(assume H : 1 < a / b,
calc
b < b * (a / b) : lt_mul_of_gt_one_right Hb H
... = a : mul_div_cancel' Hb')
(assume H : b < a,
have Hbinv : 1 / b > 0, from one_div_pos_of_pos Hb, calc
1 = b * (1 / b) : eq.symm (mul_one_div_cancel Hb')
... < a * (1 / b) : mul_lt_mul_of_pos_right H Hbinv
... = a / b : eq.symm $ div_eq_mul_one_div a b)
theorem lt_of_one_lt_div (Hb : b > 0) (H : 1 < a / b) : b < a :=
iff.mp (one_lt_div_iff_lt a Hb) H
theorem one_lt_div_of_lt (Hb : b > 0) (H : b < a) : 1 < a / b :=
iff.mpr (one_lt_div_iff_lt a Hb) H
theorem exists_lt (a : A) : ∃ x, x < a :=
have H : a - 1 < a, from add_lt_of_le_of_neg (le.refl _) zero_gt_neg_one,
exists.intro _ H
theorem exists_gt (a : A) : ∃ x, x > a :=
have H : a + 1 > a, from lt_add_of_le_of_pos (le.refl _) zero_lt_one,
exists.intro _ H
-- the following theorems amount to four iffs, for <, ≤, ≥, >.
theorem mul_le_of_le_div (Hc : 0 < c) (H : a ≤ b / c) : a * c ≤ b :=
div_mul_cancel b (ne.symm (ne_of_lt Hc)) ▸ mul_le_mul_of_nonneg_right H (le_of_lt Hc)
theorem le_div_of_mul_le (Hc : 0 < c) (H : a * c ≤ b) : a ≤ b / c :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt Hc))
... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hc))
... = b / c : eq.symm $ div_eq_mul_one_div b c
theorem mul_lt_of_lt_div (Hc : 0 < c) (H : a < b / c) : a * c < b :=
div_mul_cancel b (ne.symm (ne_of_lt Hc)) ▸ mul_lt_mul_of_pos_right H Hc
theorem lt_div_of_mul_lt (Hc : 0 < c) (H : a * c < b) : a < b / c :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt Hc))
... < b * (1 / c) : mul_lt_mul_of_pos_right H (one_div_pos_of_pos Hc)
... = b / c : eq.symm $ div_eq_mul_one_div b c
theorem mul_le_of_div_le_of_neg (Hc : c < 0) (H : b / c ≤ a) : a * c ≤ b :=
div_mul_cancel b (ne_of_lt Hc) ▸ mul_le_mul_of_nonpos_right H (le_of_lt Hc)
theorem div_le_of_mul_le_of_neg (Hc : c < 0) (H : a * c ≤ b) : b / c ≤ a :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne_of_lt Hc)
... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right H (le_of_lt (one_div_neg_of_neg Hc))
... = b / c : eq.symm $ div_eq_mul_one_div b c
theorem mul_lt_of_gt_div_of_neg (Hc : c < 0) (H : a > b / c) : a * c < b :=
div_mul_cancel b (ne_of_lt Hc) ▸ mul_lt_mul_of_neg_right H Hc
theorem div_lt_of_mul_lt_of_pos (Hc : c > 0) (H : b < a * c) : b / c < a :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne_of_gt Hc)
... > b * (1 / c) : mul_lt_mul_of_pos_right H (one_div_pos_of_pos Hc)
... = b / c : eq.symm $ div_eq_mul_one_div b c
theorem div_lt_of_mul_gt_of_neg (Hc : c < 0) (H : a * c < b) : b / c < a :=
calc
a = a * c * (1 / c) : mul_mul_div a (ne_of_lt Hc)
... > b * (1 / c) : mul_lt_mul_of_neg_right H (one_div_neg_of_neg Hc)
... = b / c : eq.symm $ div_eq_mul_one_div b c
theorem div_le_of_le_mul (Hb : b > 0) (H : a ≤ b * c) : a / b ≤ c :=
calc
a / b = a * (1 / b) : div_eq_mul_one_div a b
... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hb))
... = (b * c) / b : eq.symm $ div_eq_mul_one_div (b * c) b
... = c : mul_div_cancel_left (ne.symm (ne_of_lt Hb))
theorem le_mul_of_div_le (Hc : c > 0) (H : a / c ≤ b) : a ≤ b * c :=
sorry
/-
calc
a = a / c * c : by rewrite (!div_mul_cancel (ne.symm (ne_of_lt Hc)))
... ≤ b * c : mul_le_mul_of_nonneg_right H (le_of_lt Hc)
-/
-- following these in the isabelle file, there are 8 biconditionals for the above with - signs
-- skipping for now
theorem mul_sub_mul_div_mul_neg (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c < b / d) :
(a * d - b * c) / (c * d) < 0 :=
sorry
/-
have H1 : a / c - b / d < 0, from calc
a / c - b / d < b / d - b / d : sub_lt_sub_right H _
... = 0 : !sub_self,
calc
0 > a / c - b / d : H1
... = (a * d - c * b) / (c * d) : !div_sub_div Hc Hd
... = (a * d - b * c) / (c * d) : by rewrite (mul.comm b c)
-/
theorem mul_sub_mul_div_mul_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0) (H : a / c ≤ b / d) :
(a * d - b * c) / (c * d) ≤ 0 :=
sorry
/-
have H1 : a / c - b / d ≤ 0, from calc
a / c - b / d ≤ b / d - b / d : sub_le_sub_right H _
... = 0 : !sub_self,
calc
0 ≥ a / c - b / d : H1
... = (a * d - c * b) / (c * d) : !div_sub_div Hc Hd
... = (a * d - b * c) / (c * d) : by rewrite (mul.comm b c)
-/
theorem div_lt_div_of_mul_sub_mul_div_neg (Hc : c ≠ 0) (Hd : d ≠ 0)
(H : (a * d - b * c) / (c * d) < 0) : a / c < b / d :=
sorry
/-
have H1 : (a * d - c * b) / (c * d) < 0, by rewrite [mul.comm c b]; exact H,
have H2 : a / c - b / d < 0, by rewrite [!div_sub_div Hc Hd]; exact H1,
have H3 : a / c - b / d + b / d < 0 + b / d, from add_lt_add_right H2 _,
begin rewrite [zero_add at H3, sub_eq_add_neg at H3, neg_add_cancel_right at H3], exact H3 end
-/
theorem div_le_div_of_mul_sub_mul_div_nonpos (Hc : c ≠ 0) (Hd : d ≠ 0)
(H : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d :=
sorry
/-
have H1 : (a * d - c * b) / (c * d) ≤ 0, by rewrite [mul.comm c b]; exact H,
have H2 : a / c - b / d ≤ 0, by rewrite [!div_sub_div Hc Hd]; exact H1,
have H3 : a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right H2 _,
begin rewrite [zero_add at H3, sub_eq_add_neg at H3, neg_add_cancel_right at H3], exact H3 end
-/
theorem div_pos_of_pos_of_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a / b :=
sorry
/-
begin
rewrite div_eq_mul_one_div,
apply mul_pos,
exact Ha,
apply one_div_pos_of_pos,
exact Hb
end
-/
theorem div_nonneg_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 ≤ a / b :=
sorry
/-
begin
rewrite div_eq_mul_one_div,
apply mul_nonneg,
exact Ha,
apply le_of_lt,
apply one_div_pos_of_pos,
exact Hb
end
-/
theorem div_neg_of_neg_of_pos (Ha : a < 0) (Hb : 0 < b) : a / b < 0:=
sorry
/-
begin
rewrite div_eq_mul_one_div,
apply mul_neg_of_neg_of_pos,
exact Ha,
apply one_div_pos_of_pos,
exact Hb
end
-/
theorem div_nonpos_of_nonpos_of_pos (Ha : a ≤ 0) (Hb : 0 < b) : a / b ≤ 0 :=
sorry
/-
begin
rewrite div_eq_mul_one_div,
apply mul_nonpos_of_nonpos_of_nonneg,
exact Ha,
apply le_of_lt,
apply one_div_pos_of_pos,
exact Hb
end
-/
theorem div_neg_of_pos_of_neg (Ha : 0 < a) (Hb : b < 0) : a / b < 0 :=
sorry
/-
begin
rewrite div_eq_mul_one_div,
apply mul_neg_of_pos_of_neg,
exact Ha,
apply one_div_neg_of_neg,
exact Hb
end
-/
theorem div_nonpos_of_nonneg_of_neg (Ha : 0 ≤ a) (Hb : b < 0) : a / b ≤ 0 :=
sorry
/-
begin
rewrite div_eq_mul_one_div,
apply mul_nonpos_of_nonneg_of_nonpos,
exact Ha,
apply le_of_lt,
apply one_div_neg_of_neg,
exact Hb
end
-/
theorem div_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a / b :=
sorry
/-
begin
rewrite div_eq_mul_one_div,
apply mul_pos_of_neg_of_neg,
exact Ha,
apply one_div_neg_of_neg,
exact Hb
end
-/
theorem div_nonneg_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : 0 ≤ a / b :=
sorry
/-
begin
rewrite div_eq_mul_one_div,
apply mul_nonneg_of_nonpos_of_nonpos,
exact Ha,
apply le_of_lt,
apply one_div_neg_of_neg,
exact Hb
end
-/
theorem div_lt_div_of_lt_of_pos (H : a < b) (Hc : 0 < c) : a / c < b / c :=
sorry
/-
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_lt_mul_of_pos_right H (one_div_pos_of_pos Hc)
end
-/
theorem div_le_div_of_le_of_pos (H : a ≤ b) (Hc : 0 < c) : a / c ≤ b / c :=
sorry
/-
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_le_mul_of_nonneg_right H (le_of_lt (one_div_pos_of_pos Hc))
end
-/
theorem div_lt_div_of_lt_of_neg (H : b < a) (Hc : c < 0) : a / c < b / c :=
sorry
/-
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_lt_mul_of_neg_right H (one_div_neg_of_neg Hc)
end
-/
theorem div_le_div_of_le_of_neg (H : b ≤ a) (Hc : c < 0) : a / c ≤ b / c :=
sorry
/-
begin
rewrite [{a/c}div_eq_mul_one_div, {b/c}div_eq_mul_one_div],
exact mul_le_mul_of_nonpos_right H (le_of_lt (one_div_neg_of_neg Hc))
end
-/
theorem two_pos : (1 : A) + 1 > 0 :=
add_pos zero_lt_one zero_lt_one
theorem one_add_one_ne_zero : 1 + 1 ≠ (0:A) :=
ne.symm (ne_of_lt two_pos)
theorem two_ne_zero : 2 ≠ (0:A) :=
sorry -- by unfold bit0; apply one_add_one_ne_zero
theorem add_halves (a : A) : a / 2 + a / 2 = a :=
sorry
/-
calc
a / 2 + a / 2 = (a + a) / 2 : by rewrite div_add_div_same
... = (a * 1 + a * 1) / 2 : by rewrite mul_one
... = (a * (1 + 1)) / 2 : by rewrite left_distrib
... = (a * 2) / 2 : by rewrite one_add_one_eq_two
... = a : by rewrite [@mul_div_cancel A _ _ _ two_ne_zero]
-/
theorem sub_self_div_two (a : A) : a - a / 2 = a / 2 :=
sorry -- by rewrite [-{a}add_halves at {1}, add_sub_cancel]
theorem add_midpoint {a b : A} (H : a < b) : a + (b - a) / 2 < b :=
sorry
/-
begin
rewrite [-div_sub_div_same, sub_eq_add_neg, {b / 2 + _}add.comm, -add.assoc, -sub_eq_add_neg],
apply add_lt_of_lt_sub_right,
rewrite *sub_self_div_two,
apply div_lt_div_of_lt_of_pos H two_pos
end
-/
theorem div_two_sub_self (a : A) : a / 2 - a = - (a / 2) :=
sorry -- by rewrite [-{a}add_halves at {2}, sub_add_eq_sub_sub, sub_self, zero_sub]
theorem add_self_div_two (a : A) : (a + a) / 2 = a :=
sorry
/-
symm (iff.mpr (!eq_div_iff_mul_eq (ne_of_gt (add_pos zero_lt_one zero_lt_one)))
(by krewrite [left_distrib, *mul_one]))
-/
theorem two_gt_one : (2:A) > 1 :=
calc (2:A) = 1+1 : one_add_one_eq_two
... > 1+0 : add_lt_add_left zero_lt_one _
... = 1 : add_zero 1
theorem two_ge_one : (2:A) ≥ 1 :=
le_of_lt two_gt_one
theorem four_pos : (4 : A) > 0 := add_pos two_pos two_pos
theorem mul_le_mul_of_mul_div_le (H : a * (b / c) ≤ d) (Hc : c > 0) : b * a ≤ d * c :=
sorry
/-
begin
rewrite [-mul_div_assoc at H, mul.comm b],
apply le_mul_of_div_le Hc H
end
-/
theorem div_two_lt_of_pos (H : a > 0) : a / (1 + 1) < a :=
have Ha : a / (1 + 1) > 0, from div_pos_of_pos_of_pos H (add_pos zero_lt_one zero_lt_one),
calc
a / (1 + 1) < a / (1 + 1) + a / (1 + 1) : lt_add_of_pos_left Ha
... = a : add_halves a
theorem div_mul_le_div_mul_of_div_le_div_pos {e : A} (Hb : b ≠ 0) (Hd : d ≠ 0) (H : a / b ≤ c / d)
(He : e > 0) : a / (b * e) ≤ c / (d * e) :=
sorry
/-
begin
rewrite [!field.div_mul_eq_div_mul_one_div Hb (ne_of_gt He),
!field.div_mul_eq_div_mul_one_div Hd (ne_of_gt He)],
apply mul_le_mul_of_nonneg_right H,
apply le_of_lt,
apply one_div_pos_of_pos He
end
-/
theorem exists_add_lt_and_pos_of_lt (H : b < a) : ∃ c : A, b + c < a ∧ c > 0 :=
sorry
/-
exists.intro ((a - b) / (1 + 1))
(and.intro (have H2 : a + a > (b + b) + (a - b), from calc
a + a > b + a : add_lt_add_right H _
... = b + a + b - b : by rewrite add_sub_cancel
... = b + b + a - b : by rewrite add.right_comm
... = (b + b) + (a - b) : by rewrite add_sub,
have H3 : (a + a) / 2 > ((b + b) + (a - b)) / 2,
from div_lt_div_of_lt_of_pos H2 two_pos,
by rewrite [one_add_one_eq_two, sub_eq_add_neg, add_self_div_two at H3, -div_add_div_same at H3, add_self_div_two at H3];
exact H3)
(div_pos_of_pos_of_pos (iff.mpr !sub_pos_iff_lt H) two_pos))
-/
theorem ge_of_forall_ge_sub {a b : A} (H : ∀ ε : A, ε > 0 → a ≥ b - ε) : a ≥ b :=
sorry
/-
begin
apply le_of_not_gt,
intro Hb,
cases exists_add_lt_and_pos_of_lt Hb with [c, Hc],
let Hc' := H c (and.right Hc),
apply (not_le_of_gt (and.left Hc)) (iff.mpr !le_add_iff_sub_right_le Hc')
end
-/
end linear_ordered_field
structure discrete_linear_ordered_field [class] (A : Type) extends linear_ordered_field A,
decidable_linear_ordered_comm_ring A :=
(inv_zero : inv zero = zero)
section discrete_linear_ordered_field
variable {A : Type}
variables [s : discrete_linear_ordered_field A] {a b c : A}
include s
definition dec_eq_of_dec_lt : ∀ x y : A, decidable (x = y) :=
take x y,
decidable.by_cases
(assume H : x < y, decidable.ff (ne_of_lt H))
(assume H : ¬ x < y,
decidable.by_cases
(assume H' : y < x, decidable.ff (ne.symm (ne_of_lt H')))
(assume H' : ¬ y < x,
decidable.tt (le.antisymm (le_of_not_gt H') (le_of_not_gt H))))
attribute [instance]
definition discrete_linear_ordered_field.to_discrete_field : discrete_field A :=
⦃ discrete_field, s, has_decidable_eq := dec_eq_of_dec_lt⦄
theorem pos_of_one_div_pos (H : 0 < 1 / a) : 0 < a :=
have H1 : 0 < 1 / (1 / a), from one_div_pos_of_pos H,
have H2 : 1 / a ≠ 0, from
(assume H3 : 1 / a = 0,
have H4 : 1 / (1 / a) = 0, from symm H3 ▸ div_zero 1,
absurd H4 (ne.symm (ne_of_lt H1))),
(division_ring.one_div_one_div (ne_zero_of_one_div_ne_zero H2)) ▸ H1
theorem neg_of_one_div_neg (H : 1 / a < 0) : a < 0 :=
have H1 : 0 < - (1 / a), from neg_pos_of_neg H,
have Ha : a ≠ 0, from ne_zero_of_one_div_ne_zero (ne_of_lt H),
have H2 : 0 < 1 / (-a), from symm (division_ring.one_div_neg_eq_neg_one_div Ha) ▸ H1,
have H3 : 0 < -a, from pos_of_one_div_pos H2,
neg_of_neg_pos H3
theorem le_of_one_div_le_one_div (H : 0 < a) (Hl : 1 / a ≤ 1 / b) : b ≤ a :=
have Hb : 0 < b, from pos_of_one_div_pos (calc
0 < 1 / a : one_div_pos_of_pos H
... ≤ 1 / b : Hl),
have H' : 1 ≤ a / b, from (calc
1 = a / a : eq.symm (div_self (ne.symm (ne_of_lt H)))
... = a * (1 / a) : div_eq_mul_one_div a a
... ≤ a * (1 / b) : mul_le_mul_of_nonneg_left Hl (le_of_lt H)
... = a / b : eq.symm $ div_eq_mul_one_div a b
), le_of_one_le_div Hb H'
theorem le_of_one_div_le_one_div_of_neg (H : b < 0) (Hl : 1 / a ≤ 1 / b) : b ≤ a :=
sorry
/-
have Ha : a ≠ 0, from ne_of_lt (neg_of_one_div_neg (calc
1 / a ≤ 1 / b : Hl
... < 0 : one_div_neg_of_neg H)),
have H' : -b > 0, from neg_pos_of_neg H,
have Hl' : - (1 / b) ≤ - (1 / a), from neg_le_neg Hl,
have Hl'' : 1 / - b ≤ 1 / - a, from calc
1 / -b = - (1 / b) : by rewrite [division_ring.one_div_neg_eq_neg_one_div (ne_of_lt H)]
... ≤ - (1 / a) : Hl'
... = 1 / -a : by rewrite [division_ring.one_div_neg_eq_neg_one_div Ha],
le_of_neg_le_neg (le_of_one_div_le_one_div H' Hl'')
-/
theorem lt_of_one_div_lt_one_div (H : 0 < a) (Hl : 1 / a < 1 / b) : b < a :=
have Hb : 0 < b, from pos_of_one_div_pos (calc
0 < 1 / a : one_div_pos_of_pos H
... < 1 / b : Hl),
have H : 1 < a / b, from (calc
1 = a / a : eq.symm (div_self (ne.symm (ne_of_lt H)))
... = a * (1 / a) : div_eq_mul_one_div a a
... < a * (1 / b) : mul_lt_mul_of_pos_left Hl H
... = a / b : eq.symm $ div_eq_mul_one_div a b),
lt_of_one_lt_div Hb H
theorem lt_of_one_div_lt_one_div_of_neg (H : b < 0) (Hl : 1 / a < 1 / b) : b < a :=
have H1 : b ≤ a, from le_of_one_div_le_one_div_of_neg H (le_of_lt Hl),
have Hn : b ≠ a, from
(assume Hn' : b = a,
have Hl' : 1 / a = 1 / b, from Hn' ▸ refl _,
absurd Hl' (ne_of_lt Hl)),
lt_of_le_of_ne H1 Hn
theorem one_div_lt_one_div_of_lt (Ha : 0 < a) (H : a < b) : 1 / b < 1 / a :=
lt_of_not_ge
(assume H',
absurd H (not_lt_of_ge (le_of_one_div_le_one_div Ha H')))
theorem one_div_le_one_div_of_le (Ha : 0 < a) (H : a ≤ b) : 1 / b ≤ 1 / a :=
le_of_not_gt
(assume H',
absurd H (not_le_of_gt (lt_of_one_div_lt_one_div Ha H')))
theorem one_div_lt_one_div_of_lt_of_neg (Hb : b < 0) (H : a < b) : 1 / b < 1 / a :=
lt_of_not_ge
(assume H',
absurd H (not_lt_of_ge (le_of_one_div_le_one_div_of_neg Hb H')))
theorem one_div_le_one_div_of_le_of_neg (Hb : b < 0) (H : a ≤ b) : 1 / b ≤ 1 / a :=
le_of_not_gt
(assume H',
absurd H (not_le_of_gt (lt_of_one_div_lt_one_div_of_neg Hb H')))
theorem one_div_le_of_one_div_le_of_pos (Ha : a > 0) (H : 1 / a ≤ b) : 1 / b ≤ a :=
sorry
/-
begin
rewrite -(one_div_one_div a),
apply one_div_le_one_div_of_le,
apply one_div_pos_of_pos,
repeat assumption
end
-/
theorem one_div_le_of_one_div_le_of_neg (Ha : b < 0) (H : 1 / a ≤ b) : 1 / b ≤ a :=
sorry
/-
begin
rewrite -(one_div_one_div a),
apply one_div_le_one_div_of_le_of_neg,
repeat assumption
end
-/
theorem one_lt_one_div (H1 : 0 < a) (H2 : a < 1) : 1 < 1 / a :=
one_div_one ▸ one_div_lt_one_div_of_lt H1 H2
theorem one_le_one_div (H1 : 0 < a) (H2 : a ≤ 1) : 1 ≤ 1 / a :=
one_div_one ▸ one_div_le_one_div_of_le H1 H2
theorem one_div_lt_neg_one (H1 : a < 0) (H2 : -1 < a) : 1 / a < -1 :=
one_div_neg_one_eq_neg_one ▸ one_div_lt_one_div_of_lt_of_neg H1 H2
theorem one_div_le_neg_one (H1 : a < 0) (H2 : -1 ≤ a) : 1 / a ≤ -1 :=
one_div_neg_one_eq_neg_one ▸ one_div_le_one_div_of_le_of_neg H1 H2
theorem div_lt_div_of_pos_of_lt_of_pos (Hb : 0 < b) (H : b < a) (Hc : 0 < c) : c / a < c / b :=
sorry
/-
begin
apply iff.mp !sub_neg_iff_lt,
rewrite [div_eq_mul_one_div, {c / b}div_eq_mul_one_div, -mul_sub_left_distrib],
apply mul_neg_of_pos_of_neg,
exact Hc,
apply iff.mpr !sub_neg_iff_lt,
apply one_div_lt_one_div_of_lt,
repeat assumption
end
-/
theorem div_mul_le_div_mul_of_div_le_div_pos' {d e : A} (H : a / b ≤ c / d)
(He : e > 0) : a / (b * e) ≤ c / (d * e) :=
sorry
/-
begin
rewrite [2 div_mul_eq_div_mul_one_div],
apply mul_le_mul_of_nonneg_right H,
apply le_of_lt,
apply one_div_pos_of_pos He
end
-/
theorem abs_div (a b : A) : abs (a / b) = abs a / abs b :=
sorry
/-
decidable.by_cases
(suppose b = 0, by rewrite [this, abs_zero, *div_zero, abs_zero])
(suppose b ≠ 0,
have abs b ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H),
eq_div_of_mul_eq _ _ this
(show abs (a / b) * abs b = abs a, by rewrite [-abs_mul, div_mul_cancel _ `b ≠ 0`]))
-/
theorem abs_one_div (a : A) : abs (1 / a) = 1 / abs a :=
sorry -- by rewrite [abs_div, abs_of_nonneg (zero_le_one : 1 ≥ (0 : A))]
theorem sign_eq_div_abs (a : A) : sign a = a / (abs a) :=
sorry
/-
decidable.by_cases
(suppose a = 0, by subst a; rewrite [zero_div, sign_zero])
(suppose a ≠ 0,
have abs a ≠ 0, from assume H, this (eq_zero_of_abs_eq_zero H),
!eq_div_of_mul_eq this !eq_sign_mul_abs⁻¹)
-/
theorem add_quarters (a : A) : a / 4 + a / 4 = a / 2 :=
sorry
/-
have H4 : (4 : A) = 2 * 2, by norm_num,
calc
a / 4 + a / 4 = (a + a) / (2 * 2) : by rewrite [-H4, div_add_div_same]
... = (a * 1 + a * 1) / (2 * 2) : by rewrite mul_one
... = (a * (1 + 1)) / (2 * 2) : by rewrite left_distrib
... = (a * 2) / (2 * 2) : rfl
... = ((a * 2) / 2) / 2 : by rewrite -div_div_eq_div_mul
... = a / 2 : by rewrite (mul_div_cancel a two_ne_zero)
-/
lemma div_two_add_div_four_lt {a : A} (H : a > 0) : a / 2 + a / 4 < a :=
sorry
/-
begin
replace (4 : A) with (2 : A) + 2,
have Hne : (2 + 2 : A) ≠ 0, from ne_of_gt four_pos,
krewrite (div_add_div _ _ two_ne_zero Hne),
have Hnum : (2 + 2 + 2) / (2 * (2 + 2)) = (3 : A) / 4, by norm_num,
rewrite [{2 * a}mul.comm, -left_distrib, mul_div_assoc, -mul_one a at {2}], krewrite Hnum,
apply mul_lt_mul_of_pos_left,
apply div_lt_of_mul_lt_of_pos,
apply four_pos,
rewrite one_mul,
replace (3 : A) with (2 : A) + 1,
replace (4 : A) with (2 : A) + 2,
apply add_lt_add_left,
apply two_gt_one,
exact H
end
-/
end discrete_linear_ordered_field
|
698c0b3e106b910bd6756a69762efe6e0dd41552 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/group_theory/schur_zassenhaus.lean | ee6187eab14d43296302a0631c5b45d8f570c376 | [
"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 | 17,554 | lean | /-
Copyright (c) 2021 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import group_theory.complement
import group_theory.group_action.basic
import group_theory.sylow
/-!
# The Schur-Zassenhaus Theorem
In this file we prove the Schur-Zassenhaus theorem.
## Main results
- `exists_right_complement'_of_coprime` : The **Schur-Zassenhaus** theorem:
If `H : subgroup G` is normal and has order coprime to its index,
then there exists a subgroup `K` which is a (right) complement of `H`.
- `exists_left_complement'_of_coprime` The **Schur-Zassenhaus** theorem:
If `H : subgroup G` is normal and has order coprime to its index,
then there exists a subgroup `K` which is a (left) complement of `H`.
-/
open_locale big_operators
namespace subgroup
section schur_zassenhaus_abelian
variables {G : Type*} [group G] {H : subgroup G}
@[to_additive] instance : mul_action G (left_transversals (H : set G)) :=
{ smul := λ g T, ⟨left_coset g T, mem_left_transversals_iff_exists_unique_inv_mul_mem.mpr (λ g', by
{ obtain ⟨t, ht1, ht2⟩ := mem_left_transversals_iff_exists_unique_inv_mul_mem.mp T.2 (g⁻¹ * g'),
simp_rw [←mul_assoc, ←mul_inv_rev] at ht1 ht2,
refine ⟨⟨g * t, mem_left_coset g t.2⟩, ht1, _⟩,
rintros ⟨_, t', ht', rfl⟩ h,
exact subtype.ext ((mul_right_inj g).mpr (subtype.ext_iff.mp (ht2 ⟨t', ht'⟩ h))) })⟩,
one_smul := λ T, subtype.ext (one_left_coset T),
mul_smul := λ g g' T, subtype.ext (left_coset_assoc ↑T g g').symm }
lemma smul_symm_apply_eq_mul_symm_apply_inv_smul
(g : G) (α : left_transversals (H : set G)) (q : G ⧸ H) :
↑((equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp (g • α).2)).symm q) =
g * ((equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)).symm
(g⁻¹ • q : G ⧸ H)) :=
begin
let w := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)),
let y := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp (g • α).2)),
change ↑(y.symm q) = ↑(⟨_, mem_left_coset g (subtype.mem _)⟩ : (g • α).1),
refine subtype.ext_iff.mp (y.symm_apply_eq.mpr _),
change q = g • (w (w.symm (g⁻¹ • q : G ⧸ H))),
rw [equiv.apply_symm_apply, ←mul_smul, mul_inv_self, one_smul],
end
variables [is_commutative H] [fintype (G ⧸ H)]
variables (α β γ : left_transversals (H : set G))
/-- The difference of two left transversals -/
@[to_additive "The difference of two left transversals"]
noncomputable def diff [hH : normal H] : H :=
let α' := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)).symm,
β' := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp β.2)).symm in
∏ (q : G ⧸ H), ⟨(α' q) * (β' q)⁻¹,
hH.mem_comm (quotient.exact' ((β'.symm_apply_apply q).trans (α'.symm_apply_apply q).symm))⟩
@[to_additive] lemma diff_mul_diff [normal H] : diff α β * diff β γ = diff α γ :=
finset.prod_mul_distrib.symm.trans (finset.prod_congr rfl (λ x hx, subtype.ext
(by rw [coe_mul, coe_mk, coe_mk, coe_mk, mul_assoc, inv_mul_cancel_left])))
@[to_additive] lemma diff_self [normal H] : diff α α = 1 :=
mul_right_eq_self.mp (diff_mul_diff α α α)
@[to_additive] lemma diff_inv [normal H]: (diff α β)⁻¹ = diff β α :=
inv_eq_of_mul_eq_one ((diff_mul_diff α β α).trans (diff_self α))
lemma smul_diff_smul [hH : normal H] (g : G) :
diff (g • α) (g • β) = ⟨g * diff α β * g⁻¹, hH.conj_mem (diff α β).1 (diff α β).2 g⟩ :=
begin
let ϕ : H →* H :=
{ to_fun := λ h, ⟨g * h * g⁻¹, hH.conj_mem h.1 h.2 g⟩,
map_one' := subtype.ext (by rw [coe_mk, coe_one, mul_one, mul_inv_self]),
map_mul' := λ h₁ h₂, subtype.ext (by rw [coe_mk, coe_mul, coe_mul, coe_mk, coe_mk, mul_assoc,
mul_assoc, mul_assoc, mul_assoc, mul_assoc, inv_mul_cancel_left]) },
refine eq.trans (finset.prod_bij' (λ q _, (↑g)⁻¹ * q) (λ _ _, finset.mem_univ _)
(λ q _, subtype.ext _) (λ q _, ↑g * q) (λ _ _, finset.mem_univ _)
(λ q _, mul_inv_cancel_left g q) (λ q _, inv_mul_cancel_left g q)) (ϕ.map_prod _ _).symm,
change _ * _ = g * (_ * _) * g⁻¹,
simp_rw [smul_symm_apply_eq_mul_symm_apply_inv_smul, mul_inv_rev, mul_assoc],
refl,
end
lemma smul_diff [H.normal] (h : H) :
diff (h • α) β = h ^ H.index * diff α β :=
begin
rw [diff, diff, index_eq_card, ←finset.card_univ, ←finset.prod_const, ←finset.prod_mul_distrib],
refine finset.prod_congr rfl (λ q _, _),
rw [subtype.ext_iff, coe_mul, coe_mk, coe_mk, ←mul_assoc, mul_right_cancel_iff],
rw [show h • α = (h : G) • α, from rfl, smul_symm_apply_eq_mul_symm_apply_inv_smul],
rw [mul_left_cancel_iff, ←subtype.ext_iff, equiv.apply_eq_iff_eq, inv_smul_eq_iff],
exact self_eq_mul_left.mpr ((quotient_group.eq_one_iff _).mpr h.2),
end
variables (H)
instance setoid_diff [H.normal] : setoid (left_transversals (H : set G)) :=
setoid.mk (λ α β, diff α β = 1) ⟨λ α, diff_self α, λ α β h₁,
by rw [←diff_inv, h₁, one_inv], λ α β γ h₁ h₂, by rw [←diff_mul_diff, h₁, h₂, one_mul]⟩
/-- The quotient of the transversals of an abelian normal `N` by the `diff` relation -/
def quotient_diff [H.normal] :=
quotient H.setoid_diff
instance [H.normal] : inhabited H.quotient_diff :=
quotient.inhabited
variables {H}
instance [H.normal] : mul_action G H.quotient_diff :=
{ smul := λ g, quotient.map (λ α, g • α) (λ α β h, (smul_diff_smul α β g).trans
(subtype.ext (mul_inv_eq_one.mpr (mul_right_eq_self.mpr (subtype.ext_iff.mp h))))),
mul_smul := λ g₁ g₂ q, quotient.induction_on q (λ α, congr_arg quotient.mk (mul_smul g₁ g₂ α)),
one_smul := λ q, quotient.induction_on q (λ α, congr_arg quotient.mk (one_smul G α)) }
variables [fintype H]
lemma exists_smul_eq [H.normal] (α β : H.quotient_diff)
(hH : nat.coprime (fintype.card H) H.index) :
∃ h : H, h • α = β :=
quotient.induction_on α (quotient.induction_on β
(λ β α, exists_imp_exists (λ n, quotient.sound)
⟨(pow_coprime hH).symm (diff α β)⁻¹, by
{ change diff ((_ : H) • _) _ = 1,
rw smul_diff,
change pow_coprime hH ((pow_coprime hH).symm (diff α β)⁻¹) * (diff α β) = 1,
rw [equiv.apply_symm_apply, inv_mul_self] }⟩))
lemma smul_left_injective [H.normal] (α : H.quotient_diff)
(hH : nat.coprime (fintype.card H) H.index) :
function.injective (λ h : H, h • α) :=
λ h₁ h₂, begin
refine quotient.induction_on α (λ α hα, _),
replace hα : diff (h₁ • α) (h₂ • α) = 1 := quotient.exact hα,
rw [smul_diff, ←diff_inv, smul_diff, diff_self, mul_one, mul_inv_eq_one] at hα,
exact (pow_coprime hH).injective hα,
end
lemma is_complement'_stabilizer_of_coprime [fintype G] [H.normal] {α : H.quotient_diff}
(hH : nat.coprime (fintype.card H) H.index) :
is_complement' H (mul_action.stabilizer G α) :=
begin
classical,
let ϕ : H ≃ mul_action.orbit G α := equiv.of_bijective (λ h, ⟨h • α, h, rfl⟩)
⟨λ h₁ h₂ hh, smul_left_injective α hH (subtype.ext_iff.mp hh),
λ β, exists_imp_exists (λ h hh, subtype.ext hh) (exists_smul_eq α β hH)⟩,
have key := card_eq_card_quotient_mul_card_subgroup (mul_action.stabilizer G α),
rw ← fintype.card_congr (ϕ.trans (mul_action.orbit_equiv_quotient_stabilizer G α)) at key,
apply is_complement'_of_coprime key.symm,
rw [card_eq_card_quotient_mul_card_subgroup H, mul_comm, mul_right_inj'] at key,
{ rwa [←key, ←index_eq_card] },
{ rw [←pos_iff_ne_zero, fintype.card_pos_iff],
apply_instance },
end
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
private lemma exists_right_complement'_of_coprime_aux [fintype G] [H.normal]
(hH : nat.coprime (fintype.card H) H.index) :
∃ K : subgroup G, is_complement' H K :=
nonempty_of_inhabited.elim
(λ α : H.quotient_diff, ⟨mul_action.stabilizer G α, is_complement'_stabilizer_of_coprime hH⟩)
end schur_zassenhaus_abelian
open_locale classical
universe u
namespace schur_zassenhaus_induction
/-! ## Proof of the Schur-Zassenhaus theorem
In this section, we prove the Schur-Zassenhaus theorem.
The proof is by contradiction. We assume that `G` is a minimal counterexample to the theorem.
-/
variables {G : Type u} [group G] [fintype G] {N : subgroup G} [normal N]
(h1 : nat.coprime (fintype.card N) N.index)
(h2 : ∀ (G' : Type u) [group G'] [fintype G'], by exactI
∀ (hG'3 : fintype.card G' < fintype.card G)
{N' : subgroup G'} [N'.normal] (hN : nat.coprime (fintype.card N') N'.index),
∃ H' : subgroup G', is_complement' N' H')
(h3 : ∀ H : subgroup G, ¬ is_complement' N H)
include h1 h2 h3
/-! We will arrive at a contradiction via the following steps:
* step 0: `N` (the normal Hall subgroup) is nontrivial.
* step 1: If `K` is a subgroup of `G` with `K ⊔ N = ⊤`, then `K = ⊤`.
* step 2: `N` is a minimal normal subgroup, phrased in terms of subgroups of `G`.
* step 3: `N` is a minimal normal subgroup, phrased in terms of subgroups of `N`.
* step 4: `p` (`min_fact (fintype.card N)`) is prime (follows from step0).
* step 5: `P` (a Sylow `p`-subgroup of `N`) is nontrivial.
* step 6: `N` is a `p`-group (applies step 1 to the normalizer of `P` in `G`).
* step 7: `N` is abelian (applies step 3 to the center of `N`).
-/
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
@[nolint unused_arguments] private lemma step0 : N ≠ ⊥ :=
begin
unfreezingI { rintro rfl },
exact h3 ⊤ is_complement'_bot_top,
end
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
private lemma step1 (K : subgroup G) (hK : K ⊔ N = ⊤) : K = ⊤ :=
begin
contrapose! h3,
have h4 : (N.comap K.subtype).index = N.index,
{ rw [←N.relindex_top_right, ←hK],
exact relindex_eq_relindex_sup K N },
have h5 : fintype.card K < fintype.card G,
{ rw ← K.index_mul_card,
exact lt_mul_of_one_lt_left fintype.card_pos (one_lt_index_of_ne_top h3) },
have h6 : nat.coprime (fintype.card (N.comap K.subtype)) (N.comap K.subtype).index,
{ rw h4,
exact h1.coprime_dvd_left (card_comap_dvd_of_injective N K.subtype subtype.coe_injective) },
obtain ⟨H, hH⟩ := h2 K h5 h6,
replace hH : fintype.card (H.map K.subtype) = N.index :=
((set.card_image_of_injective _ subtype.coe_injective).trans (nat.mul_left_injective
fintype.card_pos (hH.symm.card_mul.trans (N.comap K.subtype).index_mul_card.symm))).trans h4,
have h7 : fintype.card N * fintype.card (H.map K.subtype) = fintype.card G,
{ rw [hH, ←N.index_mul_card, mul_comm] },
have h8 : (fintype.card N).coprime (fintype.card (H.map K.subtype)),
{ rwa hH },
exact ⟨H.map K.subtype, is_complement'_of_coprime h7 h8⟩,
end
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
private lemma step2 (K : subgroup G) [K.normal] (hK : K ≤ N) : K = ⊥ ∨ K = N :=
begin
have : function.surjective (quotient_group.mk' K) := quotient.surjective_quotient_mk',
have h4 := step1 h1 h2 h3,
contrapose! h4,
have h5 : fintype.card (G ⧸ K) < fintype.card G,
{ rw [←index_eq_card, ←K.index_mul_card],
refine lt_mul_of_one_lt_right (nat.pos_of_ne_zero index_ne_zero_of_fintype)
(K.one_lt_card_iff_ne_bot.mpr h4.1) },
have h6 : nat.coprime (fintype.card (N.map (quotient_group.mk' K)))
(N.map (quotient_group.mk' K)).index,
{ have index_map := N.index_map_eq this (by rwa quotient_group.ker_mk),
have index_pos : 0 < N.index := nat.pos_of_ne_zero index_ne_zero_of_fintype,
rw index_map,
refine h1.coprime_dvd_left _,
rw [←nat.mul_dvd_mul_iff_left index_pos, index_mul_card, ←index_map, index_mul_card],
exact K.card_quotient_dvd_card },
obtain ⟨H, hH⟩ := h2 (G ⧸ K) h5 h6,
refine ⟨H.comap (quotient_group.mk' K), _, _⟩,
{ have key : (N.map (quotient_group.mk' K)).comap (quotient_group.mk' K) = N,
{ refine comap_map_eq_self _,
rwa quotient_group.ker_mk },
rwa [←key, comap_sup_eq, hH.symm.sup_eq_top, comap_top] },
{ rw ← comap_top (quotient_group.mk' K),
intro hH',
rw [comap_injective this hH', is_complement'_top_right,
map_eq_bot_iff, quotient_group.ker_mk] at hH,
{ exact h4.2 (le_antisymm hK hH) } },
end
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
private lemma step3 (K : subgroup N) [(K.map N.subtype).normal] : K = ⊥ ∨ K = ⊤ :=
begin
have key := step2 h1 h2 h3 (K.map N.subtype) K.map_subtype_le,
rw ← map_bot N.subtype at key,
conv at key { congr, skip, to_rhs, rw [←N.subtype_range, N.subtype.range_eq_map] },
have inj := map_injective (show function.injective N.subtype, from subtype.coe_injective),
rwa [inj.eq_iff, inj.eq_iff] at key,
end
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
private lemma step4 : (fintype.card N).min_fac.prime :=
(nat.min_fac_prime (N.one_lt_card_iff_ne_bot.mpr (step0 h1 h2 h3)).ne')
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
private lemma step5 {P : sylow (fintype.card N).min_fac N} : P.1 ≠ ⊥ :=
begin
haveI : fact ((fintype.card N).min_fac.prime) := ⟨step4 h1 h2 h3⟩,
exact P.ne_bot_of_dvd_card (fintype.card N).min_fac_dvd,
end
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
private lemma step6 : is_p_group (fintype.card N).min_fac N :=
begin
haveI : fact ((fintype.card N).min_fac.prime) := ⟨step4 h1 h2 h3⟩,
refine sylow.nonempty.elim (λ P, P.2.of_surjective P.1.subtype _),
rw [←monoid_hom.range_top_iff_surjective, subtype_range],
haveI : (P.1.map N.subtype).normal := normalizer_eq_top.mp
(step1 h1 h2 h3 (P.1.map N.subtype).normalizer P.normalizer_sup_eq_top),
exact (step3 h1 h2 h3 P.1).resolve_left (step5 h1 h2 h3),
end
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
lemma step7 : is_commutative N :=
begin
haveI := N.bot_or_nontrivial.resolve_left (step0 h1 h2 h3),
haveI : fact ((fintype.card N).min_fac.prime) := ⟨step4 h1 h2 h3⟩,
exact ⟨⟨λ g h, eq_top_iff.mp ((step3 h1 h2 h3 N.center).resolve_left
(step6 h1 h2 h3).bot_lt_center.ne') (mem_top h) g⟩⟩,
end
end schur_zassenhaus_induction
variables {n : ℕ} {G : Type u} [group G]
/-- Do not use this lemma: It is made obsolete by `exists_right_complement'_of_coprime` -/
private lemma exists_right_complement'_of_coprime_aux' [fintype G] (hG : fintype.card G = n)
{N : subgroup G} [N.normal] (hN : nat.coprime (fintype.card N) N.index) :
∃ H : subgroup G, is_complement' N H :=
begin
unfreezingI { revert G },
apply nat.strong_induction_on n,
rintros n ih G _ _ rfl N _ hN,
refine not_forall_not.mp (λ h3, _),
haveI := by exactI
schur_zassenhaus_induction.step7 hN (λ G' _ _ hG', by { apply ih _ hG', refl }) h3,
exact not_exists_of_forall_not h3 (exists_right_complement'_of_coprime_aux hN),
end
/-- **Schur-Zassenhaus** for normal subgroups:
If `H : subgroup G` is normal, and has order coprime to its index, then there exists a
subgroup `K` which is a (right) complement of `H`. -/
theorem exists_right_complement'_of_coprime_of_fintype [fintype G]
{N : subgroup G} [N.normal] (hN : nat.coprime (fintype.card N) N.index) :
∃ H : subgroup G, is_complement' N H :=
exists_right_complement'_of_coprime_aux' rfl hN
/-- **Schur-Zassenhaus** for normal subgroups:
If `H : subgroup G` is normal, and has order coprime to its index, then there exists a
subgroup `K` which is a (right) complement of `H`. -/
theorem exists_right_complement'_of_coprime
{N : subgroup G} [N.normal] (hN : nat.coprime (nat.card N) N.index) :
∃ H : subgroup G, is_complement' N H :=
begin
by_cases hN1 : nat.card N = 0,
{ rw [hN1, nat.coprime_zero_left, index_eq_one] at hN,
rw hN,
exact ⟨⊥, is_complement'_top_bot⟩ },
by_cases hN2 : N.index = 0,
{ rw [hN2, nat.coprime_zero_right] at hN,
haveI := (cardinal.to_nat_eq_one_iff_unique.mp hN).1,
rw N.eq_bot_of_subsingleton,
exact ⟨⊤, is_complement'_bot_top⟩ },
have hN3 : nat.card G ≠ 0,
{ rw ← N.card_mul_index,
exact mul_ne_zero hN1 hN2 },
haveI := (cardinal.lt_omega_iff_fintype.mp
(lt_of_not_ge (mt cardinal.to_nat_apply_of_omega_le hN3))).some,
rw nat.card_eq_fintype_card at hN,
exact exists_right_complement'_of_coprime_of_fintype hN,
end
/-- **Schur-Zassenhaus** for normal subgroups:
If `H : subgroup G` is normal, and has order coprime to its index, then there exists a
subgroup `K` which is a (left) complement of `H`. -/
theorem exists_left_complement'_of_coprime_of_fintype
[fintype G] {N : subgroup G} [N.normal] (hN : nat.coprime (fintype.card N) N.index) :
∃ H : subgroup G, is_complement' H N :=
Exists.imp (λ _, is_complement'.symm) (exists_right_complement'_of_coprime_of_fintype hN)
/-- **Schur-Zassenhaus** for normal subgroups:
If `H : subgroup G` is normal, and has order coprime to its index, then there exists a
subgroup `K` which is a (left) complement of `H`. -/
theorem exists_left_complement'_of_coprime
{N : subgroup G} [N.normal] (hN : nat.coprime (nat.card N) N.index) :
∃ H : subgroup G, is_complement' H N :=
Exists.imp (λ _, is_complement'.symm) (exists_right_complement'_of_coprime hN)
end subgroup
|
24f808b0bd24b06b182373c167b0a42270185e74 | 32da3d0f92cab08875472ef6cacc1931c2b3eafa | /src/data/list/basic.lean | 12ccc86ced2ee674e444e22db590ea9ec78d0dd0 | [
"Apache-2.0"
] | permissive | karthiknadig/mathlib | b6073c3748860bfc9a3e55da86afcddba62dc913 | 33a86cfff12d7f200d0010cd03b95e9b69a6c1a5 | refs/heads/master | 1,676,389,371,851 | 1,610,061,127,000 | 1,610,061,127,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 186,355 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import algebra.order_functions
import control.monad.basic
import data.nat.choose.basic
import order.rel_classes
/-!
# Basic properties of lists
-/
open function nat
namespace list
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
attribute [inline] list.head
instance : is_left_id (list α) has_append.append [] :=
⟨ nil_append ⟩
instance : is_right_id (list α) has_append.append [] :=
⟨ append_nil ⟩
instance : is_associative (list α) has_append.append :=
⟨ append_assoc ⟩
theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem cons_ne_self (a : α) (l : list α) : a::l ≠ l :=
mt (congr_arg length) (nat.succ_ne_self _)
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)
@[simp] theorem cons_injective {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
cons_injective.eq_iff
theorem exists_cons_of_ne_nil {l : list α} (h : l ≠ nil) : ∃ b L, l = b :: L :=
by { induction l with c l', contradiction, use [c,l'], }
/-! ### mem -/
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, or.inl⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] :=
by intro e; rw e at h; cases h
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih, {cases h}, rcases h with rfl | h,
{ exact ⟨[], l, rfl⟩ },
{ rcases ih h with ⟨s, t, rfl⟩,
exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{cases h},
{rcases h with rfl | h,
{exact or.inl rfl},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) :
∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{cases h},
{cases (eq_or_mem_of_mem_cons h) with h h,
{exact ⟨c, mem_cons_self _ _, h.symm⟩},
{rcases ih h with ⟨a, ha₁, ha₂⟩,
exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} :
(∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) :=
begin
split,
{ assume H j hj,
exact H (f j) (mem_map_of_mem f hj) },
{ assume H i hi,
rcases mem_map.1 hi with ⟨j, hj, ji⟩,
rw ← ji,
exact H j hj }
end
@[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] :=
⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff],
λ h, h.symm ▸ rfl⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right,
exists_or_distrib, exists_eq_left]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp]
theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} :
b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) :
b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
lemma bind_map {g : α → list β} {f : β → γ} :
∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f)
| [] := rfl
| (a::l) := by simp only [cons_bind, map_append, bind_map l]
/-! ### length -/
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
@[simp] lemma length_singleton (a : α) : length [a] = 1 := rfl
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] :=
λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1)
theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l :=
λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0
theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] :=
⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩
theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] :=
⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩
lemma exists_of_length_succ {n} :
∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t
| [] H := absurd H.symm $ succ_ne_zero n
| (h :: t) H := ⟨h, t, rfl⟩
@[simp] lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α :=
begin
split,
{ intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl },
{ intros hα l1 l2 hl, induction l1 generalizing l2; cases l2,
{ refl }, { cases hl }, { cases hl },
congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl }
end
@[simp] lemma length_injective [subsingleton α] : injective (length : list α → ℕ) :=
length_injective_iff.mpr $ by apply_instance
/-! ### set-theoretic notation of lists -/
lemma empty_eq : (∅ : list α) = [] := by refl
lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl
lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) :
has_insert.insert x l = x :: l :=
if_neg h
lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) :
has_insert.insert x l = l :=
if_pos h
lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] :=
by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] }
/-! ### bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
theorem forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : list α},
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
ball_cons
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a :=
by simp only [mem_singleton, forall_eq]
theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_append, or_imp_distrib, forall_and_distrib]
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x.
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (mem_cons_self _ _) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, left, exact px end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
/-! ### list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
@[simp] theorem append_subset_iff {l₁ l₂ l : list α} :
l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l :=
begin
split,
{ intro h, simp only [subset_def] at *, split; intros; simp* },
{ rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 }
end
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ :=
λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩
theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) :
map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ :=
begin
refine ⟨_, map_subset f⟩, intros h2 x hx,
rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩,
cases h hxx', exact hx'
end
/-! ### append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
@[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: l := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and]
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true,
true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left']
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { rw nil_append, split,
{ rintro rfl, left, exact ⟨_, rfl, rfl⟩ },
{ rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } },
case cons : a as ih {
cases c,
{ simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'],
exact eq_comm },
{ simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left,
exists_and_distrib_left] } }
end
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj :
∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) :
s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_right h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_left' h rfl
theorem append_right_injective (s : list α) : function.injective (λ t, s ++ t) :=
λ t₁ t₂, append_left_cancel
theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
(append_right_injective s).eq_iff
theorem append_left_injective (t : list α) : function.injective (λ s, s ++ t) :=
λ s₁ s₂, append_right_cancel
theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
(append_left_injective t).eq_iff
theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β}
(h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ :=
begin
have := h, rw [← take_append_drop (length s₁) l] at this ⊢,
rw map_append at this,
refine ⟨_, _, rfl, append_inj this _⟩,
rw [length_map, length_take, min_eq_left],
rw [← length_map f l, h, length_append],
apply nat.le_add_right
end
/-! ### repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂;
unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n :=
by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) :
b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
@[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n :=
by induction n; [refl, simp only [*, repeat, map]]; split; refl
@[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred :=
by cases n; refl
@[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α :=
by induction n; [refl, simp only [*, repeat, join, append_nil]]
/-! ### pure -/
@[simp] theorem mem_pure {α} (x y : α) :
x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret]
/-! ### bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
@[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
@[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x :=
append_nil (f x)
/-! ### concat -/
theorem concat_nil (a : α) : concat [] a = [a] := rfl
theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp only [*, concat]; split; refl
theorem init_eq_of_concat_eq {a : α} {l₁ l₂ : list α} : concat l₁ a = concat l₂ a → l₁ = l₂ :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact append_right_cancel h
end
theorem last_eq_of_concat_eq {a b : α} {l : list α} : concat l a = concat l b → a = b :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact head_eq_of_cons_eq (append_left_cancel h)
end
theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by simp
theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by simp
theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp only [concat_eq_append, length_append, length]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by simp
/-! ### reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]],
(aux l nil).symm
theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ :=
by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]];
refl
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
by simp only [reverse_cons, concat_eq_append]
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; [rw [nil_append, reverse_nil, append_nil],
simp only [*, cons_append, reverse_cons, append_assoc]]
theorem reverse_concat (l : list α) (a : α) : reverse (concat l a) = a :: reverse l :=
by rw [concat_eq_append, reverse_append, reverse_singleton, singleton_append]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
@[simp] theorem reverse_involutive : involutive (@reverse α) :=
λ l, reverse_reverse l
@[simp] theorem reverse_injective : injective (@reverse α) :=
reverse_involutive.injective
@[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)⟩
/-! ### is_nil -/
lemma is_nil_iff_eq_nil {l : list α} : l.is_nil ↔ l = [] :=
list.cases_on l (by simp [is_nil]) (by simp [is_nil])
/-! ### init -/
@[simp] theorem length_init : ∀ (l : list α), length (init l) = length l - 1
| [] := rfl
| [a] := rfl
| (a :: b :: l) :=
begin
rw init,
simp only [add_left_inj, length, succ_add_sub_one],
exact length_init (b :: l)
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 init_append_last : ∀ {l : list α} (h : l ≠ []), init l ++ [last l h] = l
| [] h := absurd rfl h
| [a] h := rfl
| (a::b::l) h :=
begin
rw [init, cons_append, last_cons (cons_ne_nil _ _) (cons_ne_nil _ _)],
congr,
exact init_append_last (cons_ne_nil b l)
end
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l
| [] h := absurd rfl h
| [a] h := or.inl rfl
| (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) }
lemma last_repeat_succ (a m : ℕ) :
(repeat a m.succ).last (ne_nil_of_length_eq_succ
(show (repeat a m.succ).length = m.succ, by rw length_repeat)) = a :=
begin
induction m with k IH,
{ simp },
{ simpa only [repeat_succ, last] }
end
/-! ### last' -/
@[simp] theorem last'_is_none :
∀ {l : list α}, (last' l).is_none ↔ l = []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_none (b::l)]
@[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_some (b::l)]
theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h
| [] x hx := false.elim $ by simpa using hx
| [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩
| (a::b::l) x hx :=
begin
rw last' at hx,
rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩,
use cons_ne_nil _ _,
rwa [last_cons]
end
theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l :=
let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _
theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l
| [] a ha := (option.not_mem_none a ha).elim
| [a] _ rfl := rfl
| (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] }
theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget
| [] := by simp [ilast, arbitrary]
| [a] := rfl
| [a, b] := rfl
| [a, b, c] := rfl
| (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)]
@[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α),
last' (l₁ ++ a :: l₂) = last' (a :: l₂)
| [] a l₂ := rfl
| [b] a l₂ := rfl
| (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons]
theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []),
last' (l₁ ++ l₂) = last' l₂
| [] hl₂ := by contradiction
| (b::l₂) _ := last'_append_cons l₁ b l₂
/-! ### head(') and tail -/
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l
| [] h := (option.not_mem_none _ h).elim
| (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl }
@[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) :
head (s ++ t) = head s :=
by {induction s, contradiction, refl}
theorem tail_append_singleton_of_ne_nil {a : α} {l : list α} (h : l ≠ nil) :
tail (l ++ [a]) = tail l ++ [a] :=
by { induction l, contradiction, rw [tail,cons_append,tail], }
theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l
| [] a h := by contradiction
| (b::l) a h := by { simp at h, simp [h] }
theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l
| [] h := by contradiction
| (a::l) h := rfl
theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
cons_head'_tail (head_mem_head' h)
@[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl
/-! ### Induction from the right -/
/-- Induction principle from the right for lists: if a property holds for the empty list, and
for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
@[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ rw reverse_cons, exact H1 _ _ ih }
end
/-- Bidirectional induction principle for lists: if a property holds for the empty list, the
singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to
prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it
can also be used to construct data. -/
def bidirectional_rec {C : list α → Sort*}
(H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : ∀ l, C l
| [] := H0
| [a] := H1 a
| (a :: b :: l) :=
let l' := init (b :: l), b' := last (b :: l) (cons_ne_nil _ _) in
have length l' < length (a :: b :: l), by { change _ < length l + 2, simp },
begin
rw ←init_append_last (cons_ne_nil b l),
have : C l', from bidirectional_rec l',
exact Hn a l' b' ‹C l'›
end
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] }
/-- Like `bidirectional_rec`, but with the list parameter placed first. -/
@[elab_as_eliminator] def bidirectional_rec_on {C : list α → Sort*}
(l : list α) (H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : C l :=
bidirectional_rec H0 H1 Hn l
/-! ### sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) :
l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih, {refl},
{ rw reverse_cons, exact sublist_append_of_sublist_left ih },
{ rw [reverse_cons, reverse_cons], exact ih.append_right [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff]
using h.reverse,
λ h, h.append_right l⟩
theorem sublist.append {l₁ l₂ r₁ r₂ : list α}
(hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ :=
(hl.append_right _).trans ((append_sublist_append_left _).2 hr)
theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (sublist.subset s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, h.subset (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ s.subset
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h,
λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) :
l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/-! ### index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) :
index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp, priority 990]
theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih,
{ exact iff_of_true rfl (not_mem_nil _) },
simp only [length, mem_cons_iff, index_of_cons], split_ifs,
{ exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) },
{ simp only [h, false_or], rw ← ih, exact succ_inj' }
end
@[simp, priority 980]
theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih, {refl},
simp only [length, index_of_cons],
by_cases h : a = b, {rw if_pos h, exact nat.zero_le _},
rw if_neg h, exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/-! ### nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_len_le hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
@[simp]
theorem nth_eq_none_iff : ∀ {l : list α} {n}, nth l n = none ↔ length l ≤ n :=
begin
intros, split,
{ intro h, by_contradiction h',
have h₂ : ∃ h, l.nth_le n h = l.nth_le n (lt_of_not_ge h') := ⟨lt_of_not_ge h', rfl⟩,
rw [← nth_eq_some, h] at h₂, cases h₂ },
{ solve_by_elim [nth_len_le] },
end
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
lemma nth_zero (l : list α) : l.nth 0 = l.head' := by cases l; refl
lemma nth_injective {α : Type u} {xs : list α} {i j : ℕ}
(h₀ : i < xs.length)
(h₁ : nodup xs)
(h₂ : xs.nth i = xs.nth j) : i = j :=
begin
induction xs with x xs generalizing i j,
{ cases h₀ },
{ cases i; cases j,
case nat.zero nat.zero
{ refl },
case nat.succ nat.succ
{ congr, cases h₁,
apply xs_ih;
solve_by_elim [lt_of_succ_lt_succ] },
iterate 2
{ dsimp at h₂,
cases h₁ with _ _ h h',
cases h x _ rfl,
rw mem_iff_nth,
exact ⟨_, h₂.symm⟩ <|>
exact ⟨_, h₂⟩ } },
end
@[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f
| [] n := rfl
| (a :: l) 0 := rfl
| (a :: l) (n+1) := nth_map l n
theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) :=
option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl
/-- A version of `nth_le_map` that can be used for rewriting. -/
theorem nth_le_map_rev (f : α → β) {l n} (H) :
f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) :=
(nth_le_map f _ _).symm
@[simp] theorem nth_le_map' (f : α → β) {l n} (H) :
nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f _ _
/-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as
`hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make
such a rewrite, with `rw (nth_le_of_eq h)`. -/
lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) :
nth_le L i hi = nth_le L' i (h ▸ hi) :=
by { congr, exact h}
@[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) :
nth_le [a] n hn = a :=
have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn),
by subst hn0; refl
lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) :
L.nth_le 0 h = L.head :=
by { cases L, cases h, simp, }
lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂),
(l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂
| [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim
| (a::l) _ 0 hn₁ hn₂ := rfl
| (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append];
exact nth_le_append _ _
lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ}
(h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length :=
begin
rw list.length_append at h₂,
convert (nat.sub_lt_sub_right_iff h₁).mpr h₂,
simp,
end
lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂),
(l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂)
| [] _ n h₁ h₂ := rfl
| (a :: l) _ (n+1) h₁ h₂ :=
begin
dsimp,
conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], },
rw nth_le_append_right (nat.lt_succ_iff.mp h₁),
end
@[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) :
(list.repeat a n).nth_le m h = a :=
eq_of_mem_repeat (nth_le_mem _ _ _)
lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) :
(l₁ ++ l₂).nth n = l₁.nth n :=
have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn
(by rw length_append; exact le_add_right _ _),
by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append]
lemma nth_append_right {l₁ l₂ : list α} {n : ℕ} (hn : l₁.length ≤ n) :
(l₁ ++ l₂).nth n = l₂.nth (n - l₁.length) :=
begin
by_cases hl : n < (l₁ ++ l₂).length,
{ rw [nth_le_nth hl, nth_le_nth, nth_le_append_right hn] },
{ rw [nth_len_le (le_of_not_lt hl), nth_len_le],
rw [not_lt, length_append] at hl,
exact nat.le_sub_left_of_add_le hl }
end
lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []),
last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos)
| [] h := rfl
| [a] h := by rw [last_singleton, nth_le_singleton]
| (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)],
refl, exact cons_ne_nil b l }
@[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a
| [] a := rfl
| (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length]
@[ext]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa;
simp only [aa, ext (λn, h (n+1))]; split; refl
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂)
(h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], }
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} :
∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b;
simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l]
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 :
∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i :=
by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1);
exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
lemma index_of_inj [decidable_eq α] {l : list α} {x y : α}
(hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y :=
⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) =
nth_le l (index_of y l) (index_of_lt_length.2 hy),
by simp only [h],
by simpa only [index_of_nth_le],
λ h, by subst h⟩
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) :
l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] :=
begin
refine ext_le (by convert h) (λ n h₁ h₂, _),
simp only [nth_le_singleton],
congr,
exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂)
end
lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) :
∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) =
l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l)
lemma modify_nth_tail_modify_nth_tail_le
{f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) :
(l.modify_nth_tail f n).modify_nth_tail g m =
l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n :=
begin
rcases le_iff_exists_add.1 h with ⟨m, rfl⟩,
rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail]
end
lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) :
(l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n :=
by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl
lemma modify_nth_tail_id :
∀n (l:list α), l.modify_nth_tail id n = l
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m;
simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj,
not_false_iff]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp only [update_nth_eq_modify_nth, modify_nth_length]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp only [nth_modify_nth, if_pos]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp only [nth_modify_nth, if_neg h, id_map']
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h]
@[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α)
(h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a :=
by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at *
@[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α)
(hj : j < (l.update_nth i a).length) :
(l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) :=
by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth]
lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α}
(h : a ∈ l.update_nth n b), a ∈ l ∨ a = b
| [] n a b h := false.elim h
| (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim
or.inr (or.inl ∘ mem_cons_of_mem _)
| (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim
(λ h, h ▸ or.inl (mem_cons_self _ _))
(λ h, (mem_or_eq_of_mem_update_nth h).elim
(or.inl ∘ mem_cons_of_mem _) or.inr)
section insert_nth
variable {a : α}
@[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl
@[simp] lemma insert_nth_succ_nil (n : ℕ) (a : α) : insert_nth (n + 1) 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 → n ≤ m →
insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n
| 0 0 [] has _ := (lt_irrefl _ has).elim
| 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth]
| 0 (m+1) (a::as) has hmn := rfl
| (n+1) (m+1) (a::as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1)
| n 0 (a :: as) has hmn := rfl
| (n + 1) (m + 1) (a :: as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_comm (a b : α) :
∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l),
(l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a
| 0 j l := by simp [insert_nth]
| (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim
| (i + 1) (j+1) [] := by simp
| (i + 1) (j+1) (c::l) :=
assume h₀ h₁,
by simp [insert_nth];
exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁)
lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length),
a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l
| 0 as h := iff.rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := begin
dsimp [list.insert_nth],
erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff,
← or.assoc, or_comm (a = a'), or.assoc]
end
end insert_nth
/-! ### map -/
@[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl
theorem map_eq_foldr (f : α → β) (l : list α) :
map f l = foldr (λ a bs, f a :: bs) [] l :=
by induction l; simp *
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in
by rw [map, map, h₁, map_congr h₂]
lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) :=
begin
refine ⟨_, map_congr⟩, intros h x hx,
rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩,
rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h
end
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; [refl, simp only [*, join, map, map_append]]
theorem bind_ret_eq_map (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *];
split; refl
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl
@[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) :=
by cases l; refl
@[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f :=
begin
split; intros h x y hxy,
{ suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] },
{ induction y generalizing x, simpa using hxy,
cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] }
end
/--
A single `list.map` of a composition of functions is equal to
composing a `list.map` with another `list.map`, fully applied.
This is the reverse direction of `list.map_map`.
-/
lemma comp_map (h : β → γ) (g : α → β) (l : list α) :
map (h ∘ g) l = map h (map g l) := (map_map _ _ _).symm
/--
Composing a `list.map` with another `list.map` is equal to
a single `list.map` of composed functions.
-/
@[simp] lemma map_comp_map (g : β → γ) (f : α → β) :
map g ∘ map f = map (g ∘ f) :=
by { ext l, rw comp_map }
theorem map_filter_eq_foldr (f : α → β) (p : α → Prop) [decidable_pred p] (as : list α) :
map f (filter p as) = foldr (λ a bs, if p a then f a :: bs else bs) [] as :=
by { induction as, { refl }, { simp! [*, apply_ite (map f)] } }
lemma last_map (f : α → β) {l : list α} (hl : l ≠ []) :
(l.map f).last (mt eq_nil_of_map_eq_nil hl) = f (l.last hl) :=
begin
induction l with l_ih l_tl l_ih,
{ apply (hl rfl).elim },
{ cases l_tl,
{ simp },
{ simpa using l_ih } }
end
/-! ### map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
@[simp] theorem map₂_flip (f : α → β → γ) :
∀ as bs, map₂ (flip f) bs as = map₂ f as bs
| [] [] := rfl
| [] (b :: bs) := rfl
| (a :: as) [] := rfl
| (a :: as) (b :: bs) := by { simp! [map₂_flip], refl }
/-! ### take, drop -/
@[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
@[simp] theorem take_length : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end
theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_le (le_of_succ_le_succ h)]
end
@[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁
| [] l₂ := rfl
| (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂)
theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take_left
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [min_zero, take_zero, take_nil]
| 0 m l := by rw [zero_min, take_zero, take_zero]
| (succ n) (succ m) nil := by simp only [take_nil]
| (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl
theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m)
| n 0 := by simp
| 0 m := by simp
| (succ n) (succ m) := by simp [min_succ_succ, take_repeat]
lemma map_take {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_take], }
lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ},
n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)]
/-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first
`i` elements of `l₂` to `l₁`. -/
lemma take_append {l₁ l₂ : list α} (i : ℕ) :
take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) :=
begin
induction l₁, { simp },
have : length l₁_tl + 1 + i = (length l₁_tl + i).succ,
by { rw nat.succ_eq_add_one, exact succ_add _ _ },
simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self]
end
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) :
nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) :=
by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ }
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) :
nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) :=
by { simp at hi, rw nth_le_take L _ hi.1 }
lemma nth_take {l : list α} {n m : ℕ} (h : m < n) :
(l.take n).nth m = l.nth m :=
begin
induction n with n hn generalizing l m,
{ simp only [nat.nat_zero_eq_zero] at h,
exact absurd h (not_lt_of_le m.zero_le) },
{ cases l with hd tl,
{ simp only [take_nil] },
{ cases m,
{ simp only [nth, take] },
{ simpa only using hn (nat.lt_of_succ_lt_succ h) } } },
end
@[simp] lemma nth_take_of_succ {l : list α} {n : ℕ} :
(l.take (n + 1)).nth n = l.nth n :=
nth_take (nat.lt_succ_self n)
lemma take_succ {l : list α} {n : ℕ} :
l.take (n + 1) = l.take n ++ (l.nth n).to_list :=
begin
induction l with hd tl hl generalizing n,
{ simp only [option.to_list, nth, take_nil, append_nil]},
{ cases n,
{ simp only [option.to_list, nth, eq_self_iff_true, and_self, take, nil_append] },
{ simp only [hl, cons_append, nth, eq_self_iff_true, and_self, take] } }
end
@[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
lemma mem_of_mem_drop {α} {n : ℕ} {l : list α} {x : α}
(h : x ∈ l.drop n) :
x ∈ l :=
begin
induction l generalizing n,
case list.nil : n h
{ simpa using h },
case list.cons : l_hd l_tl l_ih n h
{ cases n; simp only [mem_cons_iff, drop] at h ⊢,
{ exact h },
right, apply l_ih h },
end
@[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l
| [] := rfl
| (a :: l) := rfl
theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l)
| m 0 l := rfl
| m (n+1) [] := (drop_nil _).symm
| m (n+1) (a::l) := drop_add m n _
@[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂
| [] l₂ := rfl
| (a::l₁) l₂ := drop_left l₁ l₂
theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
drop n (l₁ ++ l₂) = l₂ :=
by rw ← h; apply drop_left
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
@[simp] lemma drop_length (l : list α) : l.drop l.length = [] :=
calc l.drop l.length = (l ++ []).drop l.length : by simp
... = [] : drop_left _ _
lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length →
(l₁ ++ l₂).drop n = l₁.drop n ++ l₂
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)]
/-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements
up to `i` in `l₂`. -/
lemma drop_append {l₁ l₂ : list α} (i : ℕ) :
drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ :=
begin
induction l₁, { simp },
have : length l₁_tl + 1 + i = (length l₁_tl + i).succ,
by { rw nat.succ_eq_add_one, exact succ_add _ _ },
simp only [cons_append, length, this, drop, l₁_ih]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) :
nth_le L (i + j) h = nth_le (L.drop i) j
begin
have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h,
rw (take_append_drop i L).symm at h,
simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h
end :=
begin
have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)],
rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right];
simp [A]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) :
nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) :=
by rw nth_le_drop
@[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l
| m [] := by simp
| 0 l := by simp
| (m+1) (a::l) :=
calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl
... = drop (n + m) l : drop_drop m l
... = drop (n + (m + 1)) (a :: l) : rfl
theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α),
drop m (take (m + n) l) = take n (drop m l)
| 0 n _ := by simp
| (m+1) n nil := by simp
| (m+1) n (_::l) :=
have h: m + 1 + n = (m+n) + 1, by ac_refl,
by simpa [take_cons, h] using drop_take m n l
lemma map_drop {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_drop], }
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
lemma reverse_take {α} {xs : list α} (n : ℕ)
(h : n ≤ xs.length) :
xs.reverse.take n = (xs.drop (xs.length - n)).reverse :=
begin
induction xs generalizing n; simp only [reverse_cons, drop, reverse_nil, nat.zero_sub, length, take_nil],
cases decidable.lt_or_eq_of_le h with h' h',
{ replace h' := le_of_succ_le_succ h',
rwa [take_append_of_le_length, xs_ih _ h'],
rw [show xs_tl.length + 1 - n = succ (xs_tl.length - n), from _, drop],
{ rwa [succ_eq_add_one, nat.sub_add_comm] },
{ rwa length_reverse } },
{ subst h', rw [length, nat.sub_self, drop],
rw [show xs_tl.length + 1 = (xs_tl.reverse ++ [xs_hd]).length, from _, take_length, reverse_cons],
rw [length_append, length_reverse], refl }
end
@[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
@[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_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldl f' (g a) (l.map g) = g (list.foldl f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldr_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldr f' (g a) (l.map g) = g (list.foldr f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α)
(h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) :=
eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] }
theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α)
(h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) :=
by { revert a, induction l; intros; [refl, simp only [*, foldr]] }
lemma injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α}
(hl : ∀ f ∈ l, function.injective f) (hf : function.injective f):
function.injective (@list.foldl (α → α) (α → α) function.comp f l) :=
begin
induction l generalizing f,
{ exact hf },
{ apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)),
apply function.injective.comp hf,
apply hl _ (list.mem_cons_self _ _) }
end
/- scanl -/
section scanl
variables {f : β → α → β} {b : β} {a : α} {l : list α}
lemma length_scanl :
∀ a l, length (scanl f a l) = l.length + 1
| a [] := rfl
| a (x :: l) := by erw [length_cons, length_cons, length_scanl]
@[simp] lemma scanl_nil (b : β) : scanl f b nil = [b] := rfl
@[simp] lemma scanl_cons :
scanl f b (a :: l) = [b] ++ scanl f (f b a) l :=
by simp only [scanl, eq_self_iff_true, singleton_append, and_self]
@[simp] lemma nth_zero_scanl : (scanl f b l).nth 0 = some b :=
begin
cases l,
{ simp only [nth, scanl_nil] },
{ simp only [nth, scanl_cons, singleton_append] }
end
@[simp] lemma nth_le_zero_scanl {h : 0 < (scanl f b l).length} :
(scanl f b l).nth_le 0 h = b :=
begin
cases l,
{ simp only [nth_le, scanl_nil] },
{ simp only [nth_le, scanl_cons, singleton_append] }
end
lemma nth_succ_scanl {i : ℕ} :
(scanl f b l).nth (i + 1) = ((scanl f b l).nth i).bind (λ x, (l.nth i).map (λ y, f x y)) :=
begin
induction l with hd tl hl generalizing b i,
{ symmetry,
simp only [option.bind_eq_none', nth, forall_2_true_iff, not_false_iff, option.map_none',
scanl_nil, option.not_mem_none, forall_true_iff] },
{ simp only [nth, scanl_cons, singleton_append],
cases i,
{ simp only [option.map_some', nth_zero_scanl, nth, option.some_bind'] },
{ simp only [hl, nth] } }
end
lemma nth_le_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} :
(scanl f b l).nth_le (i + 1) h =
f ((scanl f b l).nth_le i (nat.lt_of_succ_lt h))
(l.nth_le i (nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) :=
begin
induction i with i hi generalizing b l,
{ cases l,
{ simp only [length, zero_add, scanl_nil] at h,
exact absurd h (lt_irrefl 1) },
{ simp only [scanl_cons, singleton_append, nth_le_zero_scanl, nth_le] } },
{ cases l,
{ simp only [length, add_lt_iff_neg_right, scanl_nil] at h,
exact absurd h (not_lt_of_lt nat.succ_pos') },
{ simp_rw scanl_cons,
rw nth_le_append_right _,
{ simpa only [hi, length, succ_add_sub_one] },
{ simp only [length, nat.zero_le, le_add_iff_nonneg_left] } } }
end
end scanl
/- scanr -/
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp only [scanr, scanr_aux, t, foldr_cons]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) :=
by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp only [foldl_cons];
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section foldl_eq_foldlr'
variables {f : α → β → α}
variables hf : ∀ a b c, f (f a b) c = f (f a c) b
include hf
theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b
| a b [] := rfl
| a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf]
theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l
| a [] := rfl
| a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl
end foldl_eq_foldlr'
section foldl_eq_foldlr'
variables {f : α → β → β}
variables hf : ∀ a b c, f a (f b c) = f b (f a c)
include hf
theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l
| a b [] := rfl
| a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl
end foldl_eq_foldlr'
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons]
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc];
rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/-! ### mfoldl, mfoldr, mmap -/
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
theorem mfoldr_eq_foldr (f : α → β → m β) (b l) :
mfoldr f b l = foldr (λ a mb, mb >>= f a) (pure b) l :=
by induction l; simp *
attribute [simp] mmap mmap'
variables [is_lawful_monad m]
theorem mfoldl_eq_foldl (f : β → α → m β) (b l) :
mfoldl f b l = foldl (λ mb a, mb >>= λ b, f b a) (pure b) l :=
begin
suffices h : ∀ (mb : m β),
(mb >>= λ b, mfoldl f b l) = foldl (λ mb a, mb >>= λ b, f b a) mb l,
by simp [←h (pure b)],
induction l; intro,
{ simp },
{ simp only [mfoldl, foldl, ←l_ih] with monad_norm }
end
@[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂},
mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂
| _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind]
| _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc]
@[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂},
mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁
| _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure]
| _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc]
end mfoldl_mfoldr
/-! ### prod and sum -/
-- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet.
attribute [to_additive] list.prod
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[to_additive]
theorem prod_singleton : [a].prod = a := one_mul a
@[simp, to_additive]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, to_additive]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
theorem prod_ne_zero {R : Type*} [domain R] {L : list R} :
(∀ x ∈ L, (x : _) ≠ 0) → L.prod ≠ 0 :=
list.rec_on L (λ _, one_ne_zero) $ λ hd tl ih H,
by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) }
@[to_additive]
theorem prod_eq_foldr : l.prod = foldr (*) 1 l :=
list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl]
@[to_additive]
theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (l.map f).prod (l.map g).prod :=
list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl])
@[to_additive]
theorem prod_hom [monoid β] (l : list α) (f : α →* β) :
(l.map f).prod = f l.prod :=
by { simp only [prod, foldl_map, f.map_one.symm],
exact l.foldl_hom _ _ _ 1 f.map_mul }
-- `to_additive` chokes on the next few lemmas, so we do them by hand below
@[simp]
lemma prod_take_mul_prod_drop :
∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], }
@[simp]
lemma prod_take_succ :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], }
/-- A list with product not one must have positive length. -/
lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
lemma prod_update_nth : ∀ (L : list α) (n : ℕ) (a : α),
(L.update_nth n a).prod =
(L.take n).prod * (if n < L.length then a else 1) * (L.drop (n + 1)).prod
| (x::xs) 0 a := by simp [update_nth]
| (x::xs) (i+1) a := by simp [update_nth, prod_update_nth xs i a, mul_assoc]
| [] _ _ := by simp [update_nth, (nat.zero_le _).not_lt]
end monoid
section group
variables [group α]
/-- This is the `list.prod` version of `mul_inv_rev` -/
@[to_additive "This is the `list.sum` version of `add_neg_rev`"]
lemma prod_inv_reverse : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).reverse.prod
| [] := by simp
| (x :: xs) := by simp [prod_inv_reverse xs]
/-- A non-commutative variant of `list.prod_reverse` -/
@[to_additive "A non-commutative variant of `list.sum_reverse`"]
lemma prod_reverse_noncomm : ∀ (L : list α), L.reverse.prod = (L.map (λ x, x⁻¹)).prod⁻¹ :=
by simp [prod_inv_reverse]
end group
section comm_group
variables [comm_group α]
/-- This is the `list.prod` version of `mul_inv` -/
@[to_additive "This is the `list.sum` version of `add_neg`"]
lemma prod_inv : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).prod
| [] := by simp
| (x :: xs) := by simp [mul_comm, prod_inv xs]
end comm_group
@[simp]
lemma sum_take_add_sum_drop [add_monoid α] :
∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], }
@[simp]
lemma sum_take_succ [add_monoid α] :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], }
lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length)
(h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' :=
begin
apply ext_le h (λ i h₁ h₂, _),
have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁),
rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this,
exact add_left_cancel this
end
lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) :
monotone (λ i, (L.take i).sum) :=
begin
apply monotone_of_monotone_nat (λ n, _),
by_cases h : n < L.length,
{ rw sum_take_succ _ _ h,
exact le_add_right (le_refl _) },
{ push_neg at h,
simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] }
end
@[to_additive sum_nonneg]
lemma one_le_prod_of_one_le [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
1 ≤ l.prod :=
begin
induction l with hd tl ih,
{ simp },
rw prod_cons,
exact one_le_mul (hl₁ hd (mem_cons_self hd tl)) (ih (λ x h, hl₁ x (mem_cons_of_mem hd h))),
end
@[to_additive]
lemma single_le_prod [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) :
∀ x ∈ l, x ≤ l.prod :=
begin
induction l,
{ simp },
simp_rw [prod_cons, forall_mem_cons] at ⊢ hl₁,
split,
{ exact le_mul_of_one_le_right' (one_le_prod_of_one_le hl₁.2) },
{ exact λ x H, le_mul_of_one_le_of_le hl₁.1 (l_ih hl₁.right x H) },
end
@[to_additive all_zero_of_le_zero_le_of_sum_eq_zero]
lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α]
{l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) (hl₂ : l.prod = 1) :
∀ x ∈ l, x = (1 : α) :=
λ x hx, le_antisymm (hl₂ ▸ single_le_prod hl₁ _ hx) (hl₁ x hx)
lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] (l : list α) :
l.sum = 0 ↔ ∀ x ∈ l, x = (0 : α) :=
⟨all_zero_of_le_zero_le_of_sum_eq_zero (λ _ _, zero_le _),
begin
induction l,
{ simp },
{ intro h,
rw [sum_cons, add_eq_zero_iff],
rw forall_mem_cons at h,
exact ⟨h.1, l_ih h.2⟩ },
end⟩
/-- A list with sum not zero must have positive length. -/
lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
/-- If all elements in a list are bounded below by `1`, then the length of the list is bounded
by the sum of the elements. -/
lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum :=
begin
induction L with j L IH h, { simp },
rw [sum_cons, length, add_comm],
exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi)))
end
-- Now we tie those lemmas back to their multiplicative versions.
attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one
/-- A list with positive sum must have positive length. -/
-- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications.
lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) :
0 < L.length :=
length_pos_of_sum_ne_zero L (ne_of_gt h)
@[simp, to_additive]
theorem prod_erase [decidable_eq α] [comm_monoid α] {a} :
Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b::l) h :=
begin
rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_monoid α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum :=
begin
induction l with x l ih,
{ exact dvd_zero _ },
{ rw [list.sum_cons],
exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) }
end
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; [refl, simp only [*, join, map, sum_cons, length_append]]
@[simp] theorem length_bind (l : list α) (f : α → list β) :
length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
lemma exists_lt_of_sum_lt [linear_ordered_cancel_add_comm_monoid β] {l : list α}
(f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x :=
begin
induction l with x l,
{ exfalso, exact lt_irrefl _ h },
{ by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) }
end
lemma exists_le_of_sum_le [linear_ordered_cancel_add_comm_monoid β] {l : list α}
(hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x :=
begin
cases l with x l,
{ contradiction },
{ by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩,
exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) }
end
-- Several lemmas about sum/head/tail for `list ℕ`.
-- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`.
-- We'd like to state this as `L.head * L.tail.prod = L.prod`,
-- but because `L.head` relies on an inhabited instances and
-- returns a garbage value for the empty list, this is not possible.
-- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`,
-- and below, restate the lemma just for `ℕ`.
@[to_additive]
lemma head_mul_tail_prod' [monoid α] (L : list α) :
(L.nth 0).get_or_else 1 * L.tail.prod = L.prod :=
by { cases L, { simp, refl, }, { simp, }, }
lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum :=
by { cases L, { simp, refl, }, { simp, }, }
lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum :=
nat.le.intro (head_add_tail_sum L)
lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head :=
by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel]
section
variables {G : Type*} [comm_group G]
attribute [to_additive] alternating_prod
@[simp, to_additive] lemma alternating_prod_nil :
alternating_prod ([] : list G) = 1 := rfl
@[simp, to_additive] lemma alternating_prod_singleton (g : G) :
alternating_prod [g] = g := rfl
@[simp, to_additive alternating_sum_cons_cons']
lemma alternating_prod_cons_cons (g h : G) (l : list G) :
alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl
lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) :
alternating_sum (g :: h :: l) = g - h + alternating_sum l :=
by rw [sub_eq_add_neg, alternating_sum]
end
/-! ### join -/
attribute [simp] join
theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = []
| [] := iff_of_true rfl (forall_mem_nil _)
| (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]]
lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join :=
by { induction l, simp, simp [l_ih] }
/-- In a join, taking the first elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join of the first `i` sublists. -/
lemma take_sum_join (L : list (list α)) (i : ℕ) :
L.join.take ((L.map length).take i).sum = (L.take i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [take_append, L_ih]
end
/-- In a join, dropping all the elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/
lemma drop_sum_join (L : list (list α)) (i : ℕ) :
L.join.drop ((L.map length).take i).sum = (L.drop i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [drop_append, L_ih],
end
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) :
(L.take (i+1)).drop i = [nth_le L i hi] :=
begin
induction L generalizing i,
{ simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim },
cases i, { simp },
have : i < L_tl.length,
{ simp at hi,
exact nat.lt_of_succ_lt_succ hi },
simp [L_ih this],
refl
end
/-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the
original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and
`B` is the sum of the lengths of sublists of index `≤ i`. -/
lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) :
(L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi :=
begin
have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take],
simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi]
end
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum :=
by simp [hi, sum_take_succ, hj]
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < L.join.length :=
begin
convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi),
have : L.length = (L.map length).length, by simp,
simp [this, -length_map]
end
/-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist,
where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists
of index `< i`, and adding `j`. -/
lemma nth_le_join (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) =
nth_le (nth_le L i hi) j hj :=
by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj),
nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)]
/-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the
sublists. -/
theorem eq_iff_join_eq (L L' : list (list α)) :
L = L' ↔ L.join = L'.join ∧ map length L = map length L' :=
begin
refine ⟨λ H, by simp [H], _⟩,
rintros ⟨join_eq, length_eq⟩,
apply ext_le,
{ have : length (map length L) = length (map length L'), by rw length_eq,
simpa using this },
{ assume n h₁ h₂,
rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] }
end
/-! ### lexicographic ordering -/
/-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which
`[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`.
The definition is given for any relation `r`, not only strict orders. -/
inductive lex (r : α → α → Prop) : list α → list α → Prop
| nil {a l} : lex [] (a :: l)
| cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂)
| rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂)
namespace lex
theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} :
lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ :=
⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h;
[exact h, exact (irrefl_of r a h).elim], lex.cons⟩
@[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l [].
instance is_order_connected (r : α → α → Prop)
[is_order_connected α r] [is_trichotomous α r] :
is_order_connected (list α) (lex r) :=
⟨λ l₁, match l₁ with
| _, [], c::l₃, nil := or.inr nil
| _, [], c::l₃, rel _ := or.inr nil
| _, [], c::l₃, cons _ := or.inr nil
| _, b::l₂, c::l₃, nil := or.inl nil
| a::l₁, b::l₂, c::l₃, rel h :=
(is_order_connected.conn _ b _ h).imp rel rel
| a::l₁, b::l₂, _::l₃, cons h := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match _ l₂ _ h).imp cons cons },
{ exact or.inr (rel ab) }
end
end⟩
instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] :
is_trichotomous (list α) (lex r) :=
⟨λ l₁, match l₁ with
| [], [] := or.inr (or.inl rfl)
| [], b::l₂ := or.inl nil
| a::l₁, [] := or.inr (or.inr nil)
| a::l₁, b::l₂ := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match l₁ l₂).imp cons
(or.imp (congr_arg _) cons) },
{ exact or.inr (or.inr (rel ab)) }
end
end⟩
instance is_asymm (r : α → α → Prop)
[is_asymm α r] : is_asymm (list α) (lex r) :=
⟨λ l₁, match l₁ with
| a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂
| a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁
| a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂
| a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ :=
by exact _match _ _ h₁ h₂
end⟩
instance is_strict_total_order (r : α → α → Prop)
[is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) :=
{..is_strict_weak_order_of_is_order_connected}
instance decidable_rel [decidable_eq α] (r : α → α → Prop)
[decidable_rel r] : decidable_rel (lex r)
| l₁ [] := is_false $ λ h, by cases h
| [] (b::l₂) := is_true lex.nil
| (a::l₁) (b::l₂) := begin
haveI := decidable_rel l₁ l₂,
refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩,
{ rcases h with h | ⟨rfl, h⟩,
{ exact lex.rel h },
{ exact lex.cons h } },
{ rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩,
{ exact or.inr ⟨rfl, h⟩ },
{ exact or.inl h } }
end
theorem append_right (r : α → α → Prop) :
∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t)
| _ _ t nil := nil
| _ _ t (cons h) := cons (append_right _ h)
| _ _ t (rel r) := rel r
theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) :
∀ s, lex R (s ++ t₁) (s ++ t₂)
| [] := h
| (a::l) := cons (append_left l)
theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) :
∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂
| _ _ nil := nil
| _ _ (cons h) := cons (imp _ _ h)
| _ _ (rel r) := rel (H _ _ r)
theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂
| _ _ (cons h) e := to_ne h (list.cons.inj e).2
| _ _ (rel r) e := r (list.cons.inj e).1
theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) :
lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨to_ne, λ h, begin
induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂,
{ contradiction },
{ apply nil },
{ exact (not_lt_of_ge H).elim (succ_pos _) },
{ cases classical.em (a = b) with ab ab,
{ subst b, apply cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact rel ab } }
end⟩
end lex
--Note: this overrides an instance in core lean
instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩
theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l :=
lex.nil
instance [linear_order α] : linear_order (list α) :=
linear_order_of_STO' (lex (<))
--Note: this overrides an instance in core lean
instance has_le' [linear_order α] : has_le (list α) :=
preorder.to_has_le _
/-! ### 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 sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {l : list α} (hx : x ∈ l) :
sizeof x < sizeof l :=
begin
induction l with h t ih; cases hx,
{ rw hx, exact lt_add_of_lt_of_nonneg (lt_one_add _) (nat.zero_le _) },
{ exact lt_add_of_pos_of_le (zero_lt_one_add _) (le_of_lt (ih hx)) }
end
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_map {p : β → Prop} (g : ∀ b, p b → γ) (f : α → β)
(l H) : pmap g (map f l) H = pmap (λ a h, g (f a) h) l (λ a h, H _ (mem_map_of_mem _ 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
@[simp] lemma pmap_eq_nil {p : α → Prop} {f : Π a, p a → β}
{l H} : pmap f l H = [] ↔ l = [] :=
by rw [← length_eq_zero, length_pmap, length_eq_zero]
@[simp] lemma attach_eq_nil (l : list α) : l.attach = [] ↔ l = [] := pmap_eq_nil
lemma last_pmap {α β : Type*} (p : α → Prop) (f : Π a, p a → β)
(l : list α) (hl₁ : ∀ a ∈ l, p a) (hl₂ : l ≠ []) :
(l.pmap f hl₁).last (mt list.pmap_eq_nil.1 hl₂) = f (l.last hl₂) (hl₁ _ (list.last_mem hl₂)) :=
begin
induction l with l_hd l_tl l_ih,
{ apply (hl₂ rfl).elim },
{ cases l_tl,
{ simp },
{ apply l_ih } }
end
/-! ### find -/
section find
variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α}
@[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases h : p a,
{ simp only [find_cons_of_pos _ h, h, not_true, false_and] },
{ rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] }
end
theorem find_some (H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, exact h },
{ rw find_cons_of_neg _ h at H, exact IH H }
end
@[simp] theorem find_mem (H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self },
{ rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) }
end
end find
/-! ### lookmap -/
section lookmap
variables (f : α → option α)
@[simp] theorem lookmap_nil : [].lookmap f = [] := rfl
@[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) :
(a :: l).lookmap f = a :: l.lookmap f :=
by simp [lookmap, h]
@[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) :
(a :: l).lookmap f = b :: l :=
by simp [lookmap, h]
theorem lookmap_some : ∀ l : list α, l.lookmap some = l
| [] := rfl
| (a::l) := rfl
theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l
| [] := rfl
| (a::l) := congr_arg (cons a) (lookmap_none l)
theorem lookmap_congr {f g : α → option α} :
∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g
| [] H := rfl
| (a::l) H := begin
cases forall_mem_cons.1 H with H₁ H₂,
cases h : g a with b,
{ simp [h, H₁.trans h, lookmap_congr H₂] },
{ simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] }
end
theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l :=
(lookmap_congr H).trans (lookmap_none l)
theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) :
∀ l : list α, map g (l.lookmap f) = map g l
| [] := rfl
| (a::l) := begin
cases h' : f a with b,
{ simp [h', lookmap_map_eq] },
{ simp [lookmap_cons_some _ _ h', h _ _ h'] }
end
theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l :=
by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h
theorem length_lookmap (l : list α) : length (l.lookmap f) = length l :=
by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp
end lookmap
/-! ### filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp only [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp only [filter_map, h]; split; refl
lemma filter_map_append {α β : Type*} (l l' : list α) (f : α → option β) :
filter_map f (l ++ l') = filter_map f l ++ filter_map f l' :=
begin
induction l with hd tl hl generalizing l',
{ simp },
{ rw [cons_append, filter_map, filter_map],
cases f hd;
simp only [filter_map, hl, cons_append, eq_self_iff_true, and_self] }
end
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {refl},
simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {refl},
by_cases pa : p a,
{ simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl },
{ simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] }
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp only [h, option.none_bind'] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp only [h, h', option.some_bind']
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases h : p x,
{ simp only [option.guard, if_pos h, option.some_bind'] },
{ simp only [option.guard, if_neg h, option.none_bind'] }
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH,
{ split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } },
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, this, exists_eq_left] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp only [map_filter_map, H, filter_map_some]
theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp only [filter_map]; cases f a with b;
simp only [filter_map, IH, sublist.cons, sublist.cons2]
theorem sublist.map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
filter_map_eq_map f ▸ s.filter_map _
/-! ### reduce_option -/
@[simp] lemma reduce_option_cons_of_some (x : α) (l : list (option α)) :
reduce_option (some x :: l) = x :: l.reduce_option :=
by simp only [reduce_option, filter_map, id.def, eq_self_iff_true, and_self]
@[simp] lemma reduce_option_cons_of_none (l : list (option α)) :
reduce_option (none :: l) = l.reduce_option :=
by simp only [reduce_option, filter_map, id.def]
@[simp] lemma reduce_option_nil : @reduce_option α [] = [] := rfl
@[simp] lemma reduce_option_map {l : list (option α)} {f : α → β} :
reduce_option (map (option.map f) l) = map f (reduce_option l) :=
begin
induction l with hd tl hl,
{ simp only [reduce_option_nil, map_nil] },
{ cases hd;
simpa only [true_and, option.map_some', map, eq_self_iff_true,
reduce_option_cons_of_some] using hl },
end
lemma reduce_option_append (l l' : list (option α)) :
(l ++ l').reduce_option = l.reduce_option ++ l'.reduce_option :=
filter_map_append l l' id
lemma reduce_option_length_le (l : list (option α)) :
l.reduce_option.length ≤ l.length :=
begin
induction l with hd tl hl,
{ simp only [reduce_option_nil, length] },
{ cases hd,
{ exact nat.le_succ_of_le hl },
{ simpa only [length, add_le_add_iff_right, reduce_option_cons_of_some] using hl} }
end
lemma reduce_option_length_eq_iff {l : list (option α)} :
l.reduce_option.length = l.length ↔ ∀ x ∈ l, option.is_some x :=
begin
induction l with hd tl hl,
{ simp only [forall_const, reduce_option_nil, not_mem_nil,
forall_prop_of_false, eq_self_iff_true, length, not_false_iff] },
{ cases hd,
{ simp only [mem_cons_iff, forall_eq_or_imp, bool.coe_sort_ff, false_and,
reduce_option_cons_of_none, length, option.is_some_none, iff_false],
intro H,
have := reduce_option_length_le tl,
rw H at this,
exact absurd (nat.lt_succ_self _) (not_lt_of_le this) },
{ simp only [hl, true_and, mem_cons_iff, forall_eq_or_imp, add_left_inj,
bool.coe_sort_tt, length, option.is_some_some, reduce_option_cons_of_some] } }
end
lemma reduce_option_length_lt_iff {l : list (option α)} :
l.reduce_option.length < l.length ↔ none ∈ l :=
begin
convert not_iff_not.mpr reduce_option_length_eq_iff;
simp [lt_iff_le_and_ne, reduce_option_length_le l, option.is_none_iff_eq_none]
end
lemma reduce_option_singleton (x : option α) :
[x].reduce_option = x.to_list :=
by cases x; refl
lemma reduce_option_concat (l : list (option α)) (x : option α) :
(l.concat x).reduce_option = l.reduce_option ++ x.to_list :=
begin
induction l with hd tl hl generalizing x,
{ cases x;
simp [option.to_list] },
{ simp only [concat_eq_append, reduce_option_append] at hl,
cases hd;
simp [hl, reduce_option_append] }
end
lemma reduce_option_concat_of_some (l : list (option α)) (x : α) :
(l.concat (some x)).reduce_option = l.reduce_option.concat x :=
by simp only [reduce_option_nil, concat_eq_append, reduce_option_append, reduce_option_cons_of_some]
lemma reduce_option_mem_iff {l : list (option α)} {x : α} :
x ∈ l.reduce_option ↔ (some x) ∈ l :=
by simp only [reduce_option, id.def, mem_filter_map, exists_eq_right]
lemma reduce_option_nth_iff {l : list (option α)} {x : α} :
(∃ i, l.nth i = some (some x)) ↔ ∃ i, l.reduce_option.nth i = some x :=
by rw [←mem_iff_nth, ←mem_iff_nth, reduce_option_mem_iff]
/-! ### filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
theorem filter_eq_foldr (p : α → Prop) [decidable_pred p] (l : list α) :
filter p l = foldr (λ a out, if p a then a :: out else out) [] l :=
by induction l; simp [*, filter]
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
: ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l
| [] _ := rfl
| (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a;
[simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2],
simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]];
split; refl
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
(filter_sublist l).subset
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self
| (b::l) (or.inr ain) pa := if pb : p b
then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa
else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases p a,
{ rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] },
{ rw [filter_cons_of_neg _ h],
refine iff_of_false _ (mt and.left h), intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) }
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and]
variable (p)
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
filter_map_eq_filter p ▸ s.filter_map _
theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) :=
by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl
@[simp] theorem filter_filter (q) [decidable_pred q] : ∀ l,
filter p (filter q l) = filter (λ a, p a ∧ q a) l
| [] := rfl
| (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false,
true_and, false_and, filter_filter l, eq_self_iff_true]
@[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) :
@filter α (λ _, true) h l = l :=
by convert filter_eq_self.2 (λ _ _, trivial)
@[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) :
@filter α (λ _, false) h l = [] :=
by convert filter_eq_nil.2 (λ _ _, id)
@[simp] theorem span_eq_take_drop : ∀ (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 : ∀ (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 : 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 p s)
@[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) :
countp p (filter q l) = countp (λ a, p a ∧ q a) l :=
by simp only [countp_eq_length_filter, filter_filter]
end filter
/-! ### count -/
section count
variable [decidable_eq α]
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
begin rw count_cons, split_ifs; refl end
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length),
l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0
| (_ :: _) a h := by { rw [count_cons], split_ifs; simp }
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist _
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append _
theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by simp [-add_comm]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp only [count, countp_pos, exists_prop, exists_eq_right']
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} :
n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩
theorem repeat_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) :
repeat a (count a l) = l :=
eq_of_sublist_of_length_eq (le_count_iff_repeat_sublist.mp (le_refl (count a l)))
(eq.trans (length_repeat a (count a l)) h)
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {l : list α} (h : p a) : count a (filter p l) = count a l :=
by simp only [count, countp_filter]; congr; exact
set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h))
end count
/-! ### prefix, suffix, infix -/
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
@[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) :=
by rw ← list.append_assoc; apply infix_append
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp only [reverse_reverse]
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_right_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_right_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix
theorem tail_subset (l : list α) : tail l ⊆ l := (sublist_of_suffix (tail_suffix l)).subset
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} :
l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
lemma prefix_take_le_iff {L : list (list (option α))} {m n : ℕ} (hm : m < L.length) :
(take m L) <+: (take n L) ↔ m ≤ n :=
begin
simp only [prefix_iff_eq_take, length_take],
induction m with m IH generalizing L n,
{ simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] },
{ cases n,
{ simp only [nat.nat_zero_eq_zero, le_zero_iff_eq, take, take_nil],
split,
{ cases L,
{ exact absurd hm (not_lt_of_le m.succ.zero_le) },
{ simp only [forall_prop_of_false, not_false_iff, take] } },
{ intro h,
contradiction } },
{ cases L with l ls,
{ exact absurd hm (not_lt_of_le m.succ.zero_le) },
{ simp only [length] at hm,
specialize @IH ls n (nat.lt_of_succ_lt_succ hm),
simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH,
simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take],
exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ } } },
end
lemma cons_prefix_iff {l l' : list α} {x y : α} :
x :: l <+: y :: l' ↔ x = y ∧ l <+: l' :=
begin
split,
{ rintro ⟨L, hL⟩,
simp only [cons_append] at hL,
exact ⟨hL.left, ⟨L, hL.right⟩⟩ },
{ rintro ⟨rfl, h⟩,
rwa [prefix_cons_inj] },
end
lemma map_prefix {l l' : list α} (f : α → β) (h : l <+: l') :
l.map f <+: l'.map f :=
begin
induction l with hd tl hl generalizing l',
{ simp only [nil_prefix, map_nil] },
{ cases l' with hd' tl',
{ simpa only using eq_nil_of_prefix_nil h },
{ rw cons_prefix_iff at h,
simp only [h, prefix_cons_inj, hl, map] } },
end
lemma is_prefix.filter_map {l l' : list α} (h : l <+: l') (f : α → option β) :
l.filter_map f <+: l'.filter_map f :=
begin
induction l with hd tl hl generalizing l',
{ simp only [nil_prefix, filter_map_nil] },
{ cases l' with hd' tl',
{ simpa only using eq_nil_of_prefix_nil h },
{ rw cons_prefix_iff at h,
rw [←@singleton_append _ hd _, ←@singleton_append _ hd' _, filter_map_append,
filter_map_append, h.left, prefix_append_right_inj],
exact hl h.right } },
end
lemma is_prefix.reduce_option {l l' : list (option α)} (h : l <+: l') :
l.reduce_option <+: l'.reduce_option :=
h.filter_map id
@[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⟩
lemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) :=
by simp
lemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails :=
by simp
@[simp]
lemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l)
| [] [] := by simp
| [] (a::t) := by simp
| (a::s) t := by simp [inits_append s t]
@[simp]
lemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail
| [] [] := by simp
| [] (a::t) := by simp
| (a::s) t := by simp [tails_append s t]
-- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'`
lemma inits_eq_tails :
∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l)
| [] := by simp
| (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff]
lemma tails_eq_inits :
∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l)
| [] := by simp
| (a :: l) := by simp [tails_eq_inits l, append_left_inj]
lemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) :=
by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], }
lemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) :=
by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], }
lemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) :=
by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], }
lemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) :=
by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], }
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/-! ### sublists -/
@[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl
@[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl
theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) :
map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) :
sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_eq_sublists' (l f r) :
@sublists'_aux α β l f r = map f (sublists' l) ++ r :=
by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl
@[simp] theorem sublists'_cons (a : α) (l : list α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) :=
by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl
@[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t :=
begin
induction t with a t IH generalizing s,
{ simp only [sublists'_nil, mem_singleton],
exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ },
simp only [sublists'_cons, mem_append, IH, mem_map],
split; intro h, rcases h with h | ⟨s, h, rfl⟩,
{ exact sublist_cons_of_sublist _ h },
{ exact cons_sublist_cons _ h },
{ cases h with _ _ _ h s _ _ h,
{ exact or.inl h },
{ exact or.inr ⟨s, h, rfl⟩ } }
end
@[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l
| [] := rfl
| (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map,
length, pow_succ', mul_succ, mul_zero, zero_add]
@[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl
@[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl
theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β),
sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r)
| [] f := rfl
| (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc]
theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) :
sublists_aux l cons = sublists_aux₁ l (λ x, [x]) :=
by rw [sublists_aux₁_eq_sublists_aux]; refl
theorem sublists_aux_eq_foldr.aux {a : α} {l : list α}
(IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons))
(IH₂ : ∀ (f : list α → list (list α) → list (list α)),
sublists_aux l f = foldr f [] (sublists_aux l cons))
(f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) :=
begin
simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1,
induction sublists_aux l cons with _ _ ih, {refl},
simp only [ih, foldr_cons]
end
theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons) :=
suffices _ ∧ ∀ f : list α → list (list α) → list (list α),
sublists_aux l f = foldr f [] (sublists_aux l cons),
from this.1,
begin
induction l with a l IH, {split; intro; refl},
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2,
sublists_aux_eq_foldr.aux IH.2 IH.2⟩
end
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldr]; refl
theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β),
sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++
sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x)))
| [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil]
| (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc];
refl
theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) :
sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++
f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) :=
by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil]
theorem sublists_aux₁_bind : ∀ (l : list α)
(f : list α → list β) (g : β → list γ),
(sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g)
| [] f g := rfl
| (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l]
theorem sublists_aux_cons_append (l₁ l₂ : list α) :
sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++
(do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) :=
begin
simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind,
sublists_aux₁_bind],
congr, funext x, apply congr_arg _,
rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm
end
theorem sublists_append (l₁ l₂ : list α) :
sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) :=
by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind,
cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl
@[simp] theorem sublists_concat (l : list α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) :=
by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind,
map_eq_map, map_eq_map, map_id' (append_nil), append_nil]
theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) :=
by induction l with hd tl ih; [refl,
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]]
theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) :=
by rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) :=
by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)]
theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) :=
by rw [← sublists'_reverse, reverse_reverse]
theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons
| [] := id
| (a::l) := begin
rw [sublists_aux_cons_cons],
refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _,
have := sublists_aux_ne_nil l, revert this,
induction sublists_aux l cons; intro, {rwa foldr},
simp only [foldr, mem_cons_iff, false_or, not_or_distrib],
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
end
@[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t :=
by rw [← reverse_sublist_iff, ← mem_sublists',
sublists'_reverse, mem_map_of_injective reverse_injective]
@[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l :=
by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l :=
reverse_rec_on l (nil_sublist _) $
λ l a IH, by simp only [map, map_append, sublists_concat]; exact
((append_sublist_append_left _).2 $ singleton_sublist.2 $
mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans
((append_sublist_append_right _).2 IH)
/-! ### sublists_len -/
/-- Auxiliary function to construct the list of all sublists of a given length. Given an
integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of
of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/
def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β
| 0 l f r := f [] :: r
| (n+1) [] f r := r
| (n+1) (a::l) f r := sublists_len_aux (n + 1) l f
(sublists_len_aux n l (f ∘ list.cons a) r)
/-- The list of all sublists of a list `l` that are of length `n`. For instance, for
`l = [0, 1, 2, 3]` and `n = 2`, one gets
`[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/
def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) :=
sublists_len_aux n l id []
lemma sublists_len_aux_append {α β γ : Type*} :
∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ),
sublists_len_aux n l (g ∘ f) (r.map g ++ s) =
(sublists_len_aux n l f r).map g ++ s
| 0 l f g r s := rfl
| (n+1) [] f g r s := rfl
| (n+1) (a::l) f g r s := begin
unfold sublists_len_aux,
rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl,
sublists_len_aux_append, sublists_len_aux_append]
end
lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) :
sublists_len_aux n l f r = (sublists_len n l).map f ++ r :=
by rw [sublists_len, ← sublists_len_aux_append]; refl
lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) :
sublists_len_aux 0 l f r = f [] :: r := by cases l; refl
@[simp] lemma sublists_len_zero {α : Type*} (l : list α) :
sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _
@[simp] lemma sublists_len_succ_nil {α : Type*} (n) :
sublists_len (n+1) (@nil α) = [] := rfl
@[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) :
sublists_len (n + 1) (a::l) =
sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) :=
by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq,
sublists_len_aux_eq, map_id, append_nil]; refl
@[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α),
length (sublists_len n l) = nat.choose (length l) n
| 0 l := by simp
| (n+1) [] := by simp
| (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm
lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α),
sublists_len n l <+ sublists' l
| 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _))
| (n+1) [] := nil_sublist _
| (n+1) (a::l) := begin
rw [sublists_len_succ_cons, sublists'_cons],
exact (sublists_len_sublist_sublists' _ _).append
((sublists_len_sublist_sublists' _ _).map _)
end
lemma sublists_len_sublist_of_sublist
{α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl},
{ refine IH.trans _,
rw sublists_len_succ_cons,
apply sublist_append_left },
{ simp [sublists_len_succ_cons],
exact IH.append ((IHn s).map _) }
end
lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α},
l' ∈ sublists_len n l → length l' = n
| 0 l l' (or.inl rfl) := rfl
| (n+1) (a::l) l' h := begin
rw [sublists_len_succ_cons, mem_append, mem_map] at h,
rcases h with h | ⟨l', h, rfl⟩,
{ exact length_of_sublists_len h },
{ exact congr_arg (+1) (length_of_sublists_len h) },
end
lemma mem_sublists_len_self {α : Type*} {l l' : list α}
(h : l' <+ l) : l' ∈ sublists_len (length l') l :=
begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH,
{ exact or.inl rfl },
{ cases l₁ with b l₁,
{ exact or.inl rfl },
{ rw [length, sublists_len_succ_cons],
exact mem_append_left _ IH } },
{ rw [length, sublists_len_succ_cons],
exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) }
end
@[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} :
l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n :=
⟨λ h, ⟨mem_sublists'.1
((sublists_len_sublist_sublists' _ _).subset h),
length_of_sublists_len h⟩,
λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩
/-! ### permutations -/
section permutations
@[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by rw [permutations_aux, permutations_aux.rec]
@[simp] theorem permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by rw [permutations_aux, permutations_aux.rec]; refl
end permutations
/-! ### insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp, priority 980]
theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp only [insert.def, if_pos h]
@[simp, priority 970]
theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp only [insert.def, if_neg h]; split; refl
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l,
{ simp only [insert_of_mem h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h' },
simp only [insert_of_not_mem h', mem_cons_iff]
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by rw insert_of_mem h
@[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by rw insert_of_not_mem h; refl
end insert
/-! ### erasep -/
section erasep
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem erasep_nil : [].erasep p = [] := rfl
theorem erasep_cons (a : α) (l : list α) :
(a :: l).erasep p = if p a then l else a :: l.erasep p := rfl
@[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l :=
by simp [erasep_cons, h]
@[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) :
(a::l).erasep p = a :: l.erasep p :=
by simp [erasep_cons, h]
theorem erasep_of_forall_not {l : list α}
(h : ∀ a ∈ l, ¬ p a) : l.erasep p = l :=
by induction l with _ _ ih; [refl,
simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]]
theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) :
∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
induction l with b l IH, {cases al},
by_cases pb : p b,
{ exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ },
{ rcases al with rfl | al, {exact pb.elim pa},
rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩,
h₂, by rw h₃; refl, by simp [pb, h₄]⟩ }
end
theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) :
l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
by_cases h : ∃ a ∈ l, p a,
{ rcases h with ⟨a, ha, pa⟩,
exact or.inr (exists_of_erasep ha pa) },
{ simp at h, exact or.inl (erasep_of_forall_not h) }
end
@[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) :
length (l.erasep p) = pred (length l) :=
by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩;
rw e₂; simp [-add_comm, e₁]; refl
theorem erasep_append_left {a : α} (pa : p a) :
∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : p x; simp [h'],
rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h),
rintro rfl, exact pa
end
theorem erasep_append_right :
∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1,
erasep_append_right _ (forall_mem_cons.1 h).2]
theorem erasep_sublist (l : list α) : l.erasep p <+ l :=
by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩;
[rw h, {rw [h₄, h₃], simp}]
theorem erasep_subset (l : list α) : l.erasep p ⊆ l :=
(erasep_sublist l).subset
theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p :=
begin
induction s,
case list.sublist.slnil { refl },
case list.sublist.cons : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] },
case list.sublist.cons2 : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [s, IH.cons2 _ _ _] }
end
theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l :=
@erasep_subset _ _ _ _ _
@[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l :=
⟨mem_of_mem_erasep, λ al, begin
rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
{ rwa h },
{ rw h₄, rw h₃ at al,
have : a ≠ c, {rintro rfl, exact pa.elim h₂},
simpa [this] using al }
end⟩
theorem erasep_map (f : β → α) :
∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f))
| [] := rfl
| (b::l) := by by_cases p (f b); simp [h, erasep_map l]
@[simp] theorem extractp_eq_find_erasep :
∀ l : list α, extractp p l = (find p l, erasep p l)
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l]
end erasep
/-! ### erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) :
(b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp only [erase_cons, if_pos rfl]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) :
(b::l).erase a = b :: l.erase a :=
by simp only [erase_cons, if_neg h]; split; refl
theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) :=
by { induction l with b l, {refl},
by_cases a = b; [simp [h], simp [h, ne.symm h, *]] }
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h'
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩;
rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (l.erase a) = pred (length l) :=
by rw erase_eq_erasep; exact length_erasep_of_mem h rfl
theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) :
(l₁++l₂).erase a = l₁.erase a ++ l₂ :=
by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h
theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) :
(l₁++l₂).erase a = l₁ ++ l₂.erase a :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right];
rintro b h' rfl; exact h h'
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
by rw erase_eq_erasep; apply erasep_sublist
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
(erase_sublist a l).subset
theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a :=
by simp [erase_eq_erasep]; exact sublist.erasep h
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by rw ab else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)]
else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)]
theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α}
(l : list α) : map f (l.erase a) = (map f l).erase (f a) :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr;
ext b; simp [finj.eq_iff]
theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ :=
by induction l₂ generalizing l₁; [refl,
simp only [foldl_cons, map_erase finj, *]]
@[simp] theorem count_erase_self (a : α) :
∀ (s : list α), count a (list.erase s a) = pred (count a s)
| [] := by simp
| (h :: t) :=
begin
rw erase_cons,
by_cases p : h = a,
{ rw [if_pos p, count_cons', if_pos p.symm], simp },
{ rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self],
simp, }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) :
∀ (s : list α), count a (list.erase s b) = count a s
| [] := by simp
| (x :: xs) :=
begin
rw erase_cons,
split_ifs with h,
{ rw [count_cons', h, if_neg ab], simp },
{ rw [count_cons', count_cons', count_erase_of_ne] }
end
end erase
/-! ### diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
if h : a ∈ l₁ then by simp only [list.diff, if_pos h]
else by simp only [list.diff, if_neg h, erase_of_not_mem h]
@[simp] theorem nil_diff (l : list α) : [].diff l = [] :=
by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp only [diff_eq_foldl, foldl_append]
@[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) :=
by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁
| l₁ [] := sublist.refl _
| l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _
... <+ l₁.erase a : diff_sublist _ _
... <+ l₁ : list.erase_sublist _ _
theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ :=
(diff_sublist _ _).subset
theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂
| l₁ [] h₁ h₂ := h₁
| l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact
mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂)
theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃
| l₁ l₂ [] h := h
| l₁ l₂ (a::l₃) h := by simp only
[diff_cons, (h.erase _).diff_right]
theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α},
l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [] l₂ h := erase_sublist _ _
| (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]
else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons,
erase_comm a b l₂]
using erase_diff_erase_sublist_of_sublist (h.erase b)
end diff
/-! ### enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp only [enum, enum_from_nth, zero_add]; intros; refl
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
theorem mem_enum_from {x : α} {i : ℕ} :
∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs
| j [] := by simp [enum_from]
| j (y :: ys) :=
suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys →
j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys),
by simpa [enum_from, mem_enum_from ys],
begin
rintro (h|h),
{ refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩,
apply nat.lt_add_of_pos_right; simp },
{ obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h,
refine ⟨_, _, _⟩,
{ exact le_trans (nat.le_succ _) hji },
{ convert hijlen using 1, ac_refl },
{ simp [hmem] } }
end
/-! ### product -/
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; [exact (zero_mul _).symm,
simp only [length, product_cons, length_append, IH,
right_distrib, one_mul, length_map, add_comm]]
/-! ### sigma -/
section
variable {σ : α → Type*}
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left,
and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; [refl,
simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]]
end
/-! ### disjoint -/
section disjoint
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) :
disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) :
disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] :=
by rw disjoint_comm; exact disjoint_nil_left _
@[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp only [disjoint, mem_singleton, forall_eq]; refl
@[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp only [singleton_disjoint]
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint]
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₂ :=
(disjoint_append_right.1 d).2
theorem disjoint_take_drop {l : list α} {m n : ℕ} (hl : l.nodup) (h : m ≤ n) :
disjoint (l.take m) (l.drop n) :=
begin
induction l generalizing m n,
case list.nil : m n
{ simp },
case list.cons : x xs xs_ih m n
{ cases m; cases n; simp only [disjoint_cons_left, mem_cons_iff, disjoint_cons_right, drop,
true_or, eq_self_iff_true, not_true, false_and,
disjoint_nil_left, take],
{ cases h },
cases hl with _ _ h₀ h₁, split,
{ intro h, exact h₀ _ (mem_of_mem_drop h) rfl, },
solve_by_elim [le_of_succ_le_succ] { max_depth := 4 } },
end
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
@[simp] lemma inter_reverse {xs ys : list α} :
xs.inter ys.reverse = xs.inter ys :=
by simp only [list.inter, mem_reverse]; congr
end inter
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
/-! ### map₂_left' -/
section map₂_left'
-- The definitional equalities for `map₂_left'` can already be used by the
-- simplifie because `map₂_left'` is marked `@[simp]`.
@[simp] theorem map₂_left'_nil_right (f : α → option β → γ) (as) :
map₂_left' f as [] = (as.map (λ a, f a none), []) :=
by cases as; refl
end map₂_left'
/-! ### map₂_right' -/
section map₂_right'
variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem map₂_right'_nil_left :
map₂_right' f [] bs = (bs.map (f none), []) :=
by cases bs; refl
@[simp] theorem map₂_right'_nil_right :
map₂_right' f as [] = ([], as) :=
rfl
@[simp] theorem map₂_right'_nil_cons :
map₂_right' f [] (b :: bs) = (f none b :: bs.map (f none), []) :=
rfl
@[simp] theorem map₂_right'_cons_cons :
map₂_right' f (a :: as) (b :: bs) =
let rec := map₂_right' f as bs in
(f (some a) b :: rec.fst, rec.snd) :=
rfl
end map₂_right'
/-! ### zip_left' -/
section zip_left'
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_left'_nil_right :
zip_left' as ([] : list β) = (as.map (λ a, (a, none)), []) :=
by cases as; refl
@[simp] theorem zip_left'_nil_left :
zip_left' ([] : list α) bs = ([], bs) :=
rfl
@[simp] theorem zip_left'_cons_nil :
zip_left' (a :: as) ([] : list β) = ((a, none) :: as.map (λ a, (a, none)), []) :=
rfl
@[simp] theorem zip_left'_cons_cons :
zip_left' (a :: as) (b :: bs) =
let rec := zip_left' as bs in
((a, some b) :: rec.fst, rec.snd) :=
rfl
end zip_left'
/-! ### zip_right' -/
section zip_right'
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_right'_nil_left :
zip_right' ([] : list α) bs = (bs.map (λ b, (none, b)), []) :=
by cases bs; refl
@[simp] theorem zip_right'_nil_right :
zip_right' as ([] : list β) = ([], as) :=
rfl
@[simp] theorem zip_right'_nil_cons :
zip_right' ([] : list α) (b :: bs) = ((none, b) :: bs.map (λ b, (none, b)), []) :=
rfl
@[simp] theorem zip_right'_cons_cons :
zip_right' (a :: as) (b :: bs) =
let rec := zip_right' as bs in
((some a, b) :: rec.fst, rec.snd) :=
rfl
end zip_right'
/-! ### map₂_left -/
section map₂_left
variables (f : α → option β → γ) (as : list α)
-- The definitional equalities for `map₂_left` can already be used by the
-- simplifier because `map₂_left` is marked `@[simp]`.
@[simp] theorem map₂_left_nil_right :
map₂_left f as [] = as.map (λ a, f a none) :=
by cases as; refl
theorem map₂_left_eq_map₂_left' : ∀ as bs,
map₂_left f as bs = (map₂_left' f as bs).fst
| [] bs := by simp!
| (a :: as) [] := by simp!
| (a :: as) (b :: bs) := by simp! [*]
theorem map₂_left_eq_map₂ : ∀ as bs,
length as ≤ length bs →
map₂_left f as bs = map₂ (λ a b, f a (some b)) as bs
| [] [] h := by simp!
| [] (b :: bs) h := by simp!
| (a :: as) [] h := by { simp at h, contradiction }
| (a :: as) (b :: bs) h := by { simp at h, simp! [*] }
end map₂_left
/-! ### map₂_right -/
section map₂_right
variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem map₂_right_nil_left :
map₂_right f [] bs = bs.map (f none) :=
by cases bs; refl
@[simp] theorem map₂_right_nil_right :
map₂_right f as [] = [] :=
rfl
@[simp] theorem map₂_right_nil_cons :
map₂_right f [] (b :: bs) = f none b :: bs.map (f none) :=
rfl
@[simp] theorem map₂_right_cons_cons :
map₂_right f (a :: as) (b :: bs) = f (some a) b :: map₂_right f as bs :=
rfl
theorem map₂_right_eq_map₂_right' :
map₂_right f as bs = (map₂_right' f as bs).fst :=
by simp only [map₂_right, map₂_right', map₂_left_eq_map₂_left']
theorem map₂_right_eq_map₂ (h : length bs ≤ length as) :
map₂_right f as bs = map₂ (λ a b, f (some a) b) as bs :=
begin
have : (λ a b, flip f a (some b)) = (flip (λ a b, f (some a) b)) := rfl,
simp only [map₂_right, map₂_left_eq_map₂, map₂_flip, *]
end
end map₂_right
/-! ### zip_left -/
section zip_left
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_left_nil_right :
zip_left as ([] : list β) = as.map (λ a, (a, none)) :=
by cases as; refl
@[simp] theorem zip_left_nil_left :
zip_left ([] : list α) bs = [] :=
rfl
@[simp] theorem zip_left_cons_nil :
zip_left (a :: as) ([] : list β) = (a, none) :: as.map (λ a, (a, none)) :=
rfl
@[simp] theorem zip_left_cons_cons :
zip_left (a :: as) (b :: bs) = (a, some b) :: zip_left as bs :=
rfl
theorem zip_left_eq_zip_left' :
zip_left as bs = (zip_left' as bs).fst :=
by simp only [zip_left, zip_left', map₂_left_eq_map₂_left']
end zip_left
/-! ### zip_right -/
section zip_right
variables (a : α) (as : list α) (b : β) (bs : list β)
@[simp] theorem zip_right_nil_left :
zip_right ([] : list α) bs = bs.map (λ b, (none, b)) :=
by cases bs; refl
@[simp] theorem zip_right_nil_right :
zip_right as ([] : list β) = [] :=
rfl
@[simp] theorem zip_right_nil_cons :
zip_right ([] : list α) (b :: bs) = (none, b) :: bs.map (λ b, (none, b)) :=
rfl
@[simp] theorem zip_right_cons_cons :
zip_right (a :: as) (b :: bs) = (some a, b) :: zip_right as bs :=
rfl
theorem zip_right_eq_zip_right' :
zip_right as bs = (zip_right' as bs).fst :=
by simp only [zip_right, zip_right', map₂_right_eq_map₂_right']
end zip_right
/-! ### Miscellaneous lemmas -/
theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l
| a [] := or.inl rfl
| a (b::l) := or.inr (ilast'_mem b l)
@[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) :
(L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) :=
calc (L.attach.nth_le i H).1
= (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map'
... = L.nth_le i _ : by congr; apply attach_map_val
end list
@[to_additive]
theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) :
f l.prod = (l.map f).prod :=
(l.prod_hom f).symm
namespace list
@[to_additive]
theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) :
(L.map (g ∘ f)).prod = g ((L.map f).prod) :=
by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm}
theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, r * f b)).sum = r * (L.map f).sum :=
sum_map_hom L f $ add_monoid_hom.mul_left r
theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, f b * r)).sum = (L.map f).sum * r :=
sum_map_hom L f $ add_monoid_hom.mul_right r
universes u v
@[simp]
theorem mem_map_swap {α : Type u} {β : Type v} (x : α) (y : β) (xs : list (α × β)) :
(y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs :=
begin
induction xs with x xs,
{ simp only [not_mem_nil, map_nil] },
{ cases x with a b,
simp only [mem_cons_iff, prod.mk.inj_iff, map, prod.swap_prod_mk, prod.exists, xs_ih],
tauto! },
end
lemma slice_eq {α} (xs : list α) (n m : ℕ) :
slice n m xs = xs.take n ++ xs.drop (n+m) :=
begin
induction n generalizing xs,
{ simp [slice] },
{ cases xs; simp [slice, *, nat.succ_add], }
end
lemma sizeof_slice_lt {α} [has_sizeof α] (i j : ℕ) (hj : 0 < j) (xs : list α) (hi : i < xs.length) :
sizeof (list.slice i j xs) < sizeof xs :=
begin
induction xs generalizing i j,
case list.nil : i j h
{ cases hi },
case list.cons : x xs xs_ih i j h
{ cases i; simp only [-slice_eq, list.slice],
{ cases j, cases h,
dsimp only [drop], unfold_wf,
apply @lt_of_le_of_lt _ _ _ xs.sizeof,
{ clear_except,
induction xs generalizing j; unfold_wf,
case list.nil : j
{ refl },
case list.cons : xs_hd xs_tl xs_ih j
{ cases j; unfold_wf, refl,
transitivity, apply xs_ih,
simp }, },
unfold_wf, apply zero_lt_one_add, },
{ unfold_wf, apply xs_ih _ _ h,
apply lt_of_succ_lt_succ hi, } },
end
end list
|
6c0b2589886dcdce14cc0c92374ae26a71af78bb | 9babf6e38f1e4fb489366639dfb71b020165dd0e | /sphinx/hanoi_project/anhbui_homework.lean | 1e8eb360cc8b4072c10b5061d0e645f568ab0318 | [
"CC-BY-4.0"
] | permissive | Zugor/formalabstracts | 626617cc363cab8a4088d612802bf39583ef767f | 9d96418c4c386e46c5e50ac2646680f454218a99 | refs/heads/master | 1,584,609,262,244 | 1,528,707,279,000 | 1,528,708,097,000 | 136,271,321 | 0 | 0 | null | 1,528,258,863,000 | 1,528,258,863,000 | null | UTF-8 | Lean | false | false | 788 | lean | -- Twin Prime Conjecture: There are infinitely many pairs of prime s p and p + 2
definition isInfinite (s : set ℕ) :=
-- for every k in N, s must be unbounded, so there must be a k' with k' > k
∀ k : ℕ, ∃ k' ∈ s, k' > k
definition isPrime (p : ℕ) : Prop :=
-- Require p >= 2, for every k | p, k = 1 or k = p,
p >= 2 ∧ (∀ k, k ∣ p → (k = 1 ∨ k = p))
theorem twin_primes_conjecture: Prop := ∀ n, ∃ p > n, isPrime p ∧ isPrime (p + 2)
def isEven (n:nat) : Prop := n> 1 ∧ (2 ∣ n)
theorem Goldbach : Prop := ∀ n > 2, isEven n → ∃ p q, isPrime p ∧ isPrime q ∧ n = p + q
theorem Polignac :Prop := ∀ n, ∃p > n, ∀ m, isPrime m → (m = p ∨ m = (p + 2*n))
theorem Opperman :Prop := ∀ m :ℕ, isPrime m → ∃ n, m ≥ n^2 ∧ m ≤ (n+1)^2 |
aec202727f9fe5a84b618bc18d5a5cb7e48aa338 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/data/fintype/basic.lean | 638a9482cdf118890e89f042fd43418fb6c3b54c | [
"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 | 83,326 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.array.lemmas
import data.finset.option
import data.finset.pi
import data.finset.powerset
import data.finset.prod
import data.sym.basic
import data.ulift
import group_theory.perm.basic
import order.well_founded
import tactic.wlog
/-!
# Finite types
This file defines a typeclass to state that a type is finite.
## Main declarations
* `fintype α`: Typeclass saying that a type is finite. It takes as fields a `finset` and a proof
that all terms of type `α` are in it.
* `finset.univ`: The finset of all elements of a fintype.
* `fintype.card α`: Cardinality of a fintype. Equal to `finset.univ.card`.
* `perms_of_finset s`: The finset of permutations of the finset `s`.
* `fintype.trunc_equiv_fin`: A fintype `α` is computably equivalent to `fin (card α)`. The
`trunc`-free, noncomputable version is `fintype.equiv_fin`.
* `fintype.trunc_equiv_of_card_eq` `fintype.equiv_of_card_eq`: Two fintypes of same cardinality are
equivalent. See above.
* `fin.equiv_iff_eq`: `fin m ≃ fin n` iff `m = n`.
* `infinite α`: Typeclass saying that a type is infinite. Defined as `fintype α → false`.
* `not_fintype`: No `fintype` has an `infinite` instance.
* `infinite.nat_embedding`: An embedding of `ℕ` into an infinite type.
We also provide the following versions of the pigeonholes principle.
* `fintype.exists_ne_map_eq_of_card_lt` and `is_empty_of_card_lt`: Finitely many pigeons and
pigeonholes. Weak formulation.
* `fintype.exists_ne_map_eq_of_infinite`: Infinitely many pigeons in finitely many pigeonholes.
Weak formulation.
* `fintype.exists_infinite_fiber`: Infinitely many pigeons in finitely many pigeonholes. Strong
formulation.
Some more pigeonhole-like statements can be found in `data.fintype.card_embedding`.
## Instances
Among others, we provide `fintype` instances for
* A `subtype` of a fintype. See `fintype.subtype`.
* The `option` of a fintype.
* The product of two fintypes.
* The sum of two fintypes.
* `Prop`.
and `infinite` instances for
* specific types: `ℕ`, `ℤ`
* type constructors: `set α`, `finset α`, `multiset α`, `list α`, `α ⊕ β`, `α × β`
along with some machinery
* Types which have a surjection from/an injection to a `fintype` are themselves fintypes. See
`fintype.of_injective` and `fintype.of_surjective`.
* Types which have an injection from/a surjection to an `infinite` type are themselves `infinite`.
See `infinite.of_injective` and `infinite.of_surjective`.
-/
open_locale nat
universes u v
variables {α β γ : Type*}
/-- `fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class fintype (α : Type*) :=
(elems [] : finset α)
(complete : ∀ x : α, x ∈ elems)
namespace finset
variable [fintype α]
/-- `univ` is the universal finite set of type `finset α` implied from
the assumption `fintype α`. -/
def univ : finset α := fintype.elems α
@[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) :=
fintype.complete x
@[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ
@[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) :=
by ext; simp
lemma univ_nonempty_iff : (univ : finset α).nonempty ↔ nonempty α :=
by rw [← coe_nonempty, coe_univ, set.nonempty_iff_univ_nonempty]
lemma univ_nonempty [nonempty α] : (univ : finset α).nonempty :=
univ_nonempty_iff.2 ‹_›
lemma univ_eq_empty_iff : (univ : finset α) = ∅ ↔ is_empty α :=
by rw [← not_nonempty_iff, ← univ_nonempty_iff, not_nonempty_iff_eq_empty]
lemma univ_eq_empty [is_empty α] : (univ : finset α) = ∅ :=
univ_eq_empty_iff.2 ‹_›
@[simp] theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a
instance : order_top (finset α) :=
{ top := univ,
le_top := subset_univ,
.. finset.partial_order }
instance [decidable_eq α] : boolean_algebra (finset α) :=
{ compl := λ s, univ \ s,
inf_compl_le_bot := λ s x hx, by simpa using hx,
top_le_sup_compl := λ s x hx, by simp,
sdiff_eq := λ s t, by simp [ext_iff, compl],
..finset.order_top,
..finset.generalized_boolean_algebra }
lemma compl_eq_univ_sdiff [decidable_eq α] (s : finset α) : sᶜ = univ \ s := rfl
@[simp] lemma mem_compl [decidable_eq α] {s : finset α} {x : α} : x ∈ sᶜ ↔ x ∉ s :=
by simp [compl_eq_univ_sdiff]
@[simp, norm_cast] lemma coe_compl [decidable_eq α] (s : finset α) : ↑(sᶜ) = (↑s : set α)ᶜ :=
set.ext $ λ x, mem_compl
@[simp] theorem union_compl [decidable_eq α] (s : finset α) : s ∪ sᶜ = finset.univ :=
sup_compl_eq_top
@[simp] theorem insert_compl_self [decidable_eq α] (x : α) : insert x ({x}ᶜ : finset α) = univ :=
by { ext y, simp [eq_or_ne] }
@[simp] lemma compl_filter [decidable_eq α] (p : α → Prop) [decidable_pred p]
[Π x, decidable (¬p x)] :
(univ.filter p)ᶜ = univ.filter (λ x, ¬p x) :=
(filter_not _ _).symm
theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s :=
by simp [ext_iff]
lemma compl_ne_univ_iff_nonempty [decidable_eq α] (s : finset α) : sᶜ ≠ univ ↔ s.nonempty :=
by simp [eq_univ_iff_forall, finset.nonempty]
lemma compl_singleton [decidable_eq α] (a : α) : ({a} : finset α)ᶜ = univ.erase a :=
by rw [compl_eq_univ_sdiff, sdiff_singleton_eq_erase]
@[simp] lemma univ_inter [decidable_eq α] (s : finset α) :
univ ∩ s = s := ext $ λ a, by simp
@[simp] lemma inter_univ [decidable_eq α] (s : finset α) :
s ∩ univ = s :=
by rw [inter_comm, univ_inter]
@[simp] lemma piecewise_univ [Π i : α, decidable (i ∈ (univ : finset α))]
{δ : α → Sort*} (f g : Π i, δ i) : univ.piecewise f g = f :=
by { ext i, simp [piecewise] }
lemma piecewise_compl [decidable_eq α] (s : finset α) [Π i : α, decidable (i ∈ s)]
[Π i : α, decidable (i ∈ sᶜ)] {δ : α → Sort*} (f g : Π i, δ i) :
sᶜ.piecewise f g = s.piecewise g f :=
by { ext i, simp [piecewise] }
@[simp] lemma piecewise_erase_univ {δ : α → Sort*} [decidable_eq α] (a : α) (f g : Π a, δ a) :
(finset.univ.erase a).piecewise f g = function.update f a (g a) :=
by rw [←compl_singleton, piecewise_compl, piecewise_singleton]
lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) :
univ.map e.to_embedding = univ :=
eq_univ_iff_forall.mpr (λ b, mem_map.mpr ⟨e.symm b, mem_univ _, by simp⟩)
@[simp] lemma univ_filter_exists (f : α → β) [fintype β]
[decidable_pred (λ y, ∃ x, f x = y)] [decidable_eq β] :
finset.univ.filter (λ y, ∃ x, f x = y) = finset.univ.image f :=
by { ext, simp }
/-- Note this is a special case of `(finset.image_preimage f univ _).symm`. -/
lemma univ_filter_mem_range (f : α → β) [fintype β]
[decidable_pred (λ y, y ∈ set.range f)] [decidable_eq β] :
finset.univ.filter (λ y, y ∈ set.range f) = finset.univ.image f :=
univ_filter_exists f
/-- A special case of `finset.sup_eq_supr` that omits the useless `x ∈ univ` binder. -/
lemma sup_univ_eq_supr [complete_lattice β] (f : α → β) : finset.univ.sup f = supr f :=
(sup_eq_supr _ f).trans $ congr_arg _ $ funext $ λ a, supr_pos (mem_univ _)
/-- A special case of `finset.inf_eq_infi` that omits the useless `x ∈ univ` binder. -/
lemma inf_univ_eq_infi [complete_lattice β] (f : α → β) : finset.univ.inf f = infi f :=
sup_univ_eq_supr (by exact f : α → order_dual β)
end finset
open finset function
namespace fintype
instance decidable_pi_fintype {α} {β : α → Type*} [∀ a, decidable_eq (β a)] [fintype α] :
decidable_eq (Π a, β a) :=
λ f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a)
(by simp [function.funext_iff, fintype.complete])
instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] :
decidable (∀ a, p a) :=
decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp)
instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] :
decidable (∃ a, p a) :=
decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp)
instance decidable_mem_range_fintype [fintype α] [decidable_eq β] (f : α → β) :
decidable_pred (∈ set.range f) :=
λ x, fintype.decidable_exists_fintype
section bundled_homs
instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] :
decidable_eq (α ≃ β) :=
λ a b, decidable_of_iff (a.1 = b.1) equiv.coe_fn_injective.eq_iff
instance decidable_eq_embedding_fintype [decidable_eq β] [fintype α] :
decidable_eq (α ↪ β) :=
λ a b, decidable_of_iff ((a : α → β) = b) function.embedding.coe_injective.eq_iff
@[to_additive]
instance decidable_eq_one_hom_fintype [decidable_eq β] [fintype α] [has_one α] [has_one β]:
decidable_eq (one_hom α β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff one_hom.coe_inj)
@[to_additive]
instance decidable_eq_mul_hom_fintype [decidable_eq β] [fintype α] [has_mul α] [has_mul β]:
decidable_eq (mul_hom α β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff mul_hom.coe_inj)
@[to_additive]
instance decidable_eq_monoid_hom_fintype [decidable_eq β] [fintype α]
[mul_one_class α] [mul_one_class β]:
decidable_eq (α →* β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff monoid_hom.coe_inj)
instance decidable_eq_monoid_with_zero_hom_fintype [decidable_eq β] [fintype α]
[mul_zero_one_class α] [mul_zero_one_class β]:
decidable_eq (monoid_with_zero_hom α β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff monoid_with_zero_hom.coe_inj)
instance decidable_eq_ring_hom_fintype [decidable_eq β] [fintype α]
[semiring α] [semiring β]:
decidable_eq (α →+* β) :=
λ a b, decidable_of_iff ((a : α → β) = b) (injective.eq_iff ring_hom.coe_inj)
end bundled_homs
instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] :
decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance
instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] :
decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance
instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] :
decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance
instance decidable_right_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) :
decidable (function.right_inverse f g) :=
show decidable (∀ x, g (f x) = x), by apply_instance
instance decidable_left_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) :
decidable (function.left_inverse f g) :=
show decidable (∀ x, f (g x) = x), by apply_instance
lemma exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) :
∃ x₀ : α, ∀ x, f x ≤ f x₀ :=
by simpa using exists_max_image univ f univ_nonempty
lemma exists_min [fintype α] [nonempty α]
{β : Type*} [linear_order β] (f : α → β) :
∃ x₀ : α, ∀ x, f x₀ ≤ f x :=
by simpa using exists_min_image univ f univ_nonempty
/-- Construct a proof of `fintype α` from a universal multiset -/
def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) :
fintype α :=
⟨s.to_finset, by simpa using H⟩
/-- Construct a proof of `fintype α` from a universal list -/
def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) :
fintype α :=
⟨l.to_finset, by simpa using H⟩
theorem exists_univ_list (α) [fintype α] :
∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l :=
let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in
by have := and.intro univ.2 mem_univ_val;
exact ⟨_, by rwa ←e at this⟩
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α) [fintype α] : ℕ := (@univ α _).card
/-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/
def equiv_fin_of_forall_mem_list {α} [decidable_eq α]
{l : list α} (h : ∀ x : α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) :=
⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩,
λ i, l.nth_le i.1 i.2,
λ a, by simp,
λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _
(list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩
/-- There is (computably) a bijection between `α` and `fin (card α)`.
Since it is not unique, and depends on which permutation
of the universe list is used, the bijection is wrapped in `trunc` to
preserve computability.
See `fintype.equiv_fin` for the noncomputable version,
and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq`
for an equiv `α ≃ fin n` given `fintype.card α = n`.
-/
def trunc_equiv_fin (α) [decidable_eq α] [fintype α] : trunc (α ≃ fin (card α)) :=
by unfold card finset.card; exact
quot.rec_on_subsingleton (@univ α _).1
(λ l (h : ∀ x : α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd))
mem_univ_val univ.2
/-- There is a (noncomputable) bijection between `α` and `fin (card α)`.
See `fintype.trunc_equiv_fin` for the computable version,
and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq`
for an equiv `α ≃ fin n` given `fintype.card α = n`.
-/
noncomputable def equiv_fin (α) [fintype α] : α ≃ fin (card α) :=
by { letI := classical.dec_eq α, exact (trunc_equiv_fin α).out }
instance (α : Type*) : subsingleton (fintype α) :=
⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩
/-- Given a predicate that can be represented by a finset, the subtype
associated to the predicate is a fintype. -/
protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) :
fintype {x // p x} :=
⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1),
multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩,
λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩
theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) :
@card {x // p x} (fintype.subtype s H) = s.card :=
multiset.card_pmap _ _ _
theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x)
[fintype {x // p x}] :
card {x // p x} = s.card :=
by { rw ← subtype_card s H, congr }
/-- Construct a fintype from a finset with the same elements. -/
def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p :=
fintype.subtype s H
@[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) :
@fintype.card p (of_finset s H) = s.card :=
fintype.subtype_card s H
theorem card_of_finset' {p : set α} (s : finset α)
(H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card :=
by rw ←card_of_finset s H; congr
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β :=
⟨univ.map ⟨f, H.1⟩,
λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def of_surjective [decidable_eq β] [fintype α] (f : α → β) (H : function.surjective f) :
fintype β :=
⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩
end fintype
section inv
namespace function
variables [fintype α] [decidable_eq β]
namespace injective
variables {f : α → β} (hf : function.injective f)
/--
The inverse of an `hf : injective` function `f : α → β`, of the type `↥(set.range f) → α`.
This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`,
or the function version of applying `(equiv.of_injective f hf).symm`.
This function should not usually be used for actual computation because for most cases,
an explicit inverse can be stated that has better computational properties.
This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where
`N = fintype.card α`.
-/
def inv_of_mem_range : set.range f → α :=
λ b, finset.choose (λ a, f a = b) finset.univ ((exists_unique_congr (by simp)).mp
(hf.exists_unique_of_mem_range b.property))
lemma left_inv_of_inv_of_mem_range (b : set.range f) :
f (hf.inv_of_mem_range b) = b :=
(finset.choose_spec (λ a, f a = b) _ _).right
@[simp] lemma right_inv_of_inv_of_mem_range (a : α) :
hf.inv_of_mem_range (⟨f a, set.mem_range_self a⟩) = a :=
hf (finset.choose_spec (λ a', f a' = f a) _ _).right
lemma inv_fun_restrict [nonempty α] :
(set.range f).restrict (inv_fun f) = hf.inv_of_mem_range :=
begin
ext ⟨b, h⟩,
apply hf,
simp [hf.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)]
end
lemma inv_of_mem_range_surjective : function.surjective hf.inv_of_mem_range :=
λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩
end injective
namespace embedding
variables (f : α ↪ β) (b : set.range f)
/--
The inverse of an embedding `f : α ↪ β`, of the type `↥(set.range f) → α`.
This is the computable version of `function.inv_fun` that requires `fintype α` and `decidable_eq β`,
or the function version of applying `(equiv.of_injective f f.injective).symm`.
This function should not usually be used for actual computation because for most cases,
an explicit inverse can be stated that has better computational properties.
This function computes by checking all terms `a : α` to find the `f a = b`, so it is O(N) where
`N = fintype.card α`.
-/
def inv_of_mem_range : α :=
f.injective.inv_of_mem_range b
@[simp] lemma left_inv_of_inv_of_mem_range :
f (f.inv_of_mem_range b) = b :=
f.injective.left_inv_of_inv_of_mem_range b
@[simp] lemma right_inv_of_inv_of_mem_range (a : α) :
f.inv_of_mem_range ⟨f a, set.mem_range_self a⟩ = a :=
f.injective.right_inv_of_inv_of_mem_range a
lemma inv_fun_restrict [nonempty α] :
(set.range f).restrict (inv_fun f) = f.inv_of_mem_range :=
begin
ext ⟨b, h⟩,
apply f.injective,
simp [f.left_inv_of_inv_of_mem_range, @inv_fun_eq _ _ _ f b (set.mem_range.mp h)]
end
lemma inv_of_mem_range_surjective : function.surjective f.inv_of_mem_range :=
λ a, ⟨⟨f a, set.mem_range_self a⟩, by simp⟩
end embedding
end function
end inv
namespace fintype
/-- Given an injective function to a fintype, the domain is also a
fintype. This is noncomputable because injectivity alone cannot be
used to construct preimages. -/
noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α :=
by letI := classical.dec; exact
if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα;
exact of_surjective (inv_fun f) (inv_fun_surjective H)
else ⟨∅, λ x, (hα ⟨x⟩).elim⟩
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective
theorem of_equiv_card [fintype α] (f : α ≃ β) :
@card β (of_equiv α f) = card α :=
multiset.card_map _ _
theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β :=
by rw ← of_equiv_card f; congr
section
variables [fintype α] [fintype β]
/-- If the cardinality of `α` is `n`, there is computably a bijection between `α` and `fin n`.
See `fintype.equiv_fin_of_card_eq` for the noncomputable definition,
and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`.
-/
def trunc_equiv_fin_of_card_eq [decidable_eq α] {n : ℕ} (h : fintype.card α = n) :
trunc (α ≃ fin n) :=
(trunc_equiv_fin α).map (λ e, e.trans (fin.cast h).to_equiv)
/-- If the cardinality of `α` is `n`, there is noncomputably a bijection between `α` and `fin n`.
See `fintype.trunc_equiv_fin_of_card_eq` for the computable definition,
and `fintype.trunc_equiv_fin` and `fintype.equiv_fin` for the bijection `α ≃ fin (card α)`.
-/
noncomputable def equiv_fin_of_card_eq {n : ℕ} (h : fintype.card α = n) :
α ≃ fin n :=
by { letI := classical.dec_eq α, exact (trunc_equiv_fin_of_card_eq h).out }
/-- Two `fintype`s with the same cardinality are (computably) in bijection.
See `fintype.equiv_of_card_eq` for the noncomputable version,
and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for
the specialization to `fin`.
-/
def trunc_equiv_of_card_eq [decidable_eq α] [decidable_eq β] (h : card α = card β) :
trunc (α ≃ β) :=
(trunc_equiv_fin_of_card_eq h).bind (λ e, (trunc_equiv_fin β).map (λ e', e.trans e'.symm))
/-- Two `fintype`s with the same cardinality are (noncomputably) in bijection.
See `fintype.trunc_equiv_of_card_eq` for the computable version,
and `fintype.trunc_equiv_fin_of_card_eq` and `fintype.equiv_fin_of_card_eq` for
the specialization to `fin`.
-/
noncomputable def equiv_of_card_eq (h : card α = card β) : α ≃ β :=
by { letI := classical.dec_eq α, letI := classical.dec_eq β,
exact (trunc_equiv_of_card_eq h).out }
end
theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) :=
⟨λ h, by { haveI := classical.prop_decidable, exact (trunc_equiv_of_card_eq h).nonempty },
λ ⟨f⟩, card_congr f⟩
/-- Any subsingleton type with a witness is a fintype (with one term). -/
def of_subsingleton (a : α) [subsingleton α] : fintype α :=
⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩
@[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] :
@univ _ (of_subsingleton a) = {a} := rfl
/-- Note: this lemma is specifically about `fintype.of_subsingleton`. For a statement about
arbitrary `fintype` instances, use either `fintype.card_le_one_iff_subsingleton` or
`fintype.card_unique`. -/
@[simp] theorem card_of_subsingleton (a : α) [subsingleton α] :
@fintype.card _ (of_subsingleton a) = 1 := rfl
@[simp] theorem card_unique [unique α] [h : fintype α] :
fintype.card α = 1 :=
subsingleton.elim (of_subsingleton $ default α) h ▸ card_of_subsingleton _
@[priority 100] -- see Note [lower instance priority]
instance of_is_empty [is_empty α] : fintype α := ⟨∅, is_empty_elim⟩
/-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about
arbitrary `fintype` instances, use `fintype.univ_is_empty`. -/
-- no-lint since while `fintype.of_is_empty` can prove this, it isn't applicable for `dsimp`.
@[simp, nolint simp_nf] theorem univ_of_is_empty [is_empty α] : @univ α _ = ∅ := rfl
/-- Note: this lemma is specifically about `fintype.of_is_empty`. For a statement about
arbitrary `fintype` instances, use `fintype.card_eq_zero_iff`. -/
@[simp] theorem card_of_is_empty [is_empty α] : fintype.card α = 0 := rfl
open_locale classical
variables (α)
/-- Any subsingleton type is (noncomputably) a fintype (with zero or one term). -/
@[priority 5] -- see Note [lower instance priority]
noncomputable instance of_subsingleton' [subsingleton α] : fintype α :=
if h : nonempty α then
of_subsingleton (nonempty.some h)
else
@fintype.of_is_empty _ $ not_nonempty_iff.mp h
end fintype
namespace set
/-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/
def to_finset (s : set α) [fintype s] : finset α :=
⟨(@finset.univ s _).1.map subtype.val,
multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩
@[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s :=
by simp [to_finset]
@[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s :=
mem_to_finset
-- We use an arbitrary `[fintype s]` instance here,
-- not necessarily coming from a `[fintype α]`.
@[simp]
lemma to_finset_card {α : Type*} (s : set α) [fintype s] :
s.to_finset.card = fintype.card s :=
multiset.card_map subtype.val finset.univ.val
@[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s :=
set.ext $ λ _, mem_to_finset
@[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] :
s.to_finset = t.to_finset ↔ s = t :=
⟨λ h, by rw [←s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩
@[simp, mono] theorem to_finset_mono {s t : set α} [fintype s] [fintype t] :
s.to_finset ⊆ t.to_finset ↔ s ⊆ t :=
by simp [finset.subset_iff, set.subset_def]
@[simp, mono] theorem to_finset_strict_mono {s t : set α} [fintype s] [fintype t] :
s.to_finset ⊂ t.to_finset ↔ s ⊂ t :=
begin
rw [←lt_eq_ssubset, ←finset.lt_iff_ssubset, lt_iff_le_and_ne, lt_iff_le_and_ne],
simp
end
@[simp] theorem to_finset_disjoint_iff [decidable_eq α] {s t : set α} [fintype s] [fintype t] :
disjoint s.to_finset t.to_finset ↔ disjoint s t :=
⟨λ h x hx, h (by simpa using hx), λ h x hx, h (by simpa using hx)⟩
end set
lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α :=
rfl
lemma finset.eq_univ_of_card [fintype α] (s : finset α) (hs : s.card = fintype.card α) :
s = univ :=
eq_of_subset_of_card_le (subset_univ _) $ by rw [hs, finset.card_univ]
lemma finset.card_eq_iff_eq_univ [fintype α] (s : finset α) :
s.card = fintype.card α ↔ s = finset.univ :=
⟨s.eq_univ_of_card, by { rintro rfl, exact finset.card_univ, }⟩
lemma finset.card_le_univ [fintype α] (s : finset α) :
s.card ≤ fintype.card α :=
card_le_of_subset (subset_univ s)
lemma finset.card_lt_univ_of_not_mem [fintype α] {s : finset α} {x : α} (hx : x ∉ s) :
s.card < fintype.card α :=
card_lt_card ⟨subset_univ s, not_forall.2 ⟨x, λ hx', hx (hx' $ mem_univ x)⟩⟩
lemma finset.card_lt_iff_ne_univ [fintype α] (s : finset α) :
s.card < fintype.card α ↔ s ≠ finset.univ :=
s.card_le_univ.lt_iff_ne.trans (not_iff_not_of_iff s.card_eq_iff_eq_univ)
lemma finset.card_compl_lt_iff_nonempty [fintype α] [decidable_eq α] (s : finset α) :
sᶜ.card < fintype.card α ↔ s.nonempty :=
sᶜ.card_lt_iff_ne_univ.trans s.compl_ne_univ_iff_nonempty
lemma finset.card_univ_diff [decidable_eq α] [fintype α] (s : finset α) :
(finset.univ \ s).card = fintype.card α - s.card :=
finset.card_sdiff (subset_univ s)
lemma finset.card_compl [decidable_eq α] [fintype α] (s : finset α) :
sᶜ.card = fintype.card α - s.card :=
finset.card_univ_diff s
instance (n : ℕ) : fintype (fin n) :=
⟨finset.fin_range n, finset.mem_fin_range⟩
lemma fin.univ_def (n : ℕ) : (univ : finset (fin n)) = finset.fin_range n := rfl
@[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n :=
list.length_fin_range n
@[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n :=
by rw [finset.card_univ, fintype.card_fin]
/-- The cardinality of `fin (bit0 k)` is even, `fact` version.
This `fact` is needed as an instance by `matrix.special_linear_group.has_neg`. -/
lemma fintype.card_fin_even {k : ℕ} : fact (even (fintype.card (fin (bit0 k)))) :=
⟨by { rw [fintype.card_fin], exact even_bit0 k }⟩
lemma card_finset_fin_le {n : ℕ} (s : finset (fin n)) : s.card ≤ n :=
by simpa only [fintype.card_fin] using s.card_le_univ
lemma fin.equiv_iff_eq {m n : ℕ} : nonempty (fin m ≃ fin n) ↔ m = n :=
⟨λ ⟨h⟩, by simpa using fintype.card_congr h, λ h, ⟨equiv.cast $ h ▸ rfl ⟩ ⟩
@[simp] lemma fin.image_succ_above_univ {n : ℕ} (i : fin (n + 1)) :
univ.image i.succ_above = {i}ᶜ :=
by { ext m, simp }
@[simp] lemma fin.image_succ_univ (n : ℕ) : (univ : finset (fin n)).image fin.succ = {0}ᶜ :=
by rw [← fin.succ_above_zero, fin.image_succ_above_univ]
@[simp] lemma fin.image_cast_succ (n : ℕ) :
(univ : finset (fin n)).image fin.cast_succ = {fin.last n}ᶜ :=
by rw [← fin.succ_above_last, fin.image_succ_above_univ]
/-- Embed `fin n` into `fin (n + 1)` by prepending zero to the `univ` -/
lemma fin.univ_succ (n : ℕ) :
(univ : finset (fin (n + 1))) = insert 0 (univ.image fin.succ) :=
by simp
/-- Embed `fin n` into `fin (n + 1)` by appending a new `fin.last n` to the `univ` -/
lemma fin.univ_cast_succ (n : ℕ) :
(univ : finset (fin (n + 1))) = insert (fin.last n) (univ.image fin.cast_succ) :=
by simp
/-- Embed `fin n` into `fin (n + 1)` by inserting
around a specified pivot `p : fin (n + 1)` into the `univ` -/
lemma fin.univ_succ_above (n : ℕ) (p : fin (n + 1)) :
(univ : finset (fin (n + 1))) = insert p (univ.image (fin.succ_above p)) :=
by simp
@[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α :=
fintype.of_subsingleton (default α)
/-- Short-circuit instance to decrease search for `unique.fintype`,
since that relies on a subsingleton elimination for `unique`. -/
instance fintype.subtype_eq (y : α) : fintype {x // x = y} :=
fintype.subtype {y} (by simp)
/-- Short-circuit instance to decrease search for `unique.fintype`,
since that relies on a subsingleton elimination for `unique`. -/
instance fintype.subtype_eq' (y : α) : fintype {x // y = x} :=
fintype.subtype {y} (by simp [eq_comm])
@[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} :=
by rw [subsingleton.elim f (@unique.fintype α _)]; refl
@[simp] lemma univ_is_empty {α : Type*} [is_empty α] [fintype α] : @finset.univ α _ = ∅ :=
finset.ext is_empty_elim
@[simp] lemma fintype.card_subtype_eq (y : α) [fintype {x // x = y}] :
fintype.card {x // x = y} = 1 :=
fintype.card_unique
@[simp] lemma fintype.card_subtype_eq' (y : α) [fintype {x // y = x}] :
fintype.card {x // y = x} = 1 :=
fintype.card_unique
@[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl
@[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl
@[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl
@[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl
instance : fintype unit := fintype.of_subsingleton ()
theorem fintype.univ_unit : @univ unit _ = {()} := rfl
theorem fintype.card_unit : fintype.card unit = 1 := rfl
instance : fintype punit := fintype.of_subsingleton punit.star
@[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl
@[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl
instance : fintype bool := ⟨⟨tt ::ₘ ff ::ₘ 0, by simp⟩, λ x, by cases x; simp⟩
@[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl
instance units_int.fintype : fintype (units ℤ) :=
⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩
@[simp] lemma units_int.univ : (finset.univ : finset (units ℤ)) = {1, -1} := rfl
instance additive.fintype : Π [fintype α], fintype (additive α) := id
instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id
@[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl
@[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl
instance {α : Type*} [fintype α] : fintype (option α) :=
⟨univ.insert_none, λ a, by simp⟩
@[simp] theorem fintype.card_option {α : Type*} [fintype α] :
fintype.card (option α) = fintype.card α + 1 :=
(finset.card_cons _).trans $ congr_arg2 _ (card_map _) rfl
instance {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] : fintype (sigma β) :=
⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩
@[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] :
(univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl
instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) :=
⟨univ.product univ, λ ⟨a, b⟩, by simp⟩
@[simp] lemma finset.univ_product_univ {α β : Type*} [fintype α] [fintype β] :
(univ : finset α).product (univ : finset β) = univ :=
rfl
@[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] :
fintype.card (α × β) = fintype.card α * fintype.card β :=
card_product _ _
/-- Given that `α × β` is a fintype, `α` is also a fintype. -/
def fintype.prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α :=
⟨(fintype.elems (α × β)).image prod.fst,
λ a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩
/-- Given that `α × β` is a fintype, `β` is also a fintype. -/
def fintype.prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β :=
⟨(fintype.elems (α × β)).image prod.snd,
λ b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩
instance (α : Type*) [fintype α] : fintype (ulift α) :=
fintype.of_equiv _ equiv.ulift.symm
@[simp] theorem fintype.card_ulift (α : Type*) [fintype α] :
fintype.card (ulift α) = fintype.card α :=
fintype.of_equiv_card _
instance (α : Type*) [fintype α] : fintype (plift α) :=
fintype.of_equiv _ equiv.plift.symm
@[simp] theorem fintype.card_plift (α : Type*) [fintype α] :
fintype.card (plift α) = fintype.card α :=
fintype.of_equiv_card _
lemma univ_sum_type {α β : Type*} [fintype α] [fintype β] [fintype (α ⊕ β)] [decidable_eq (α ⊕ β)] :
(univ : finset (α ⊕ β)) = map function.embedding.inl univ ∪ map function.embedding.inr univ :=
begin
rw [eq_comm, eq_univ_iff_forall], simp only [mem_union, mem_map, exists_prop, mem_univ, true_and],
rintro (x|y), exacts [or.inl ⟨x, rfl⟩, or.inr ⟨y, rfl⟩]
end
instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) :=
@fintype.of_equiv _ _ (@sigma.fintype _
(λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _
(λ b, by cases b; apply ulift.fintype))
((equiv.sum_equiv_sigma_bool _ _).symm.trans
(equiv.sum_congr equiv.ulift equiv.ulift))
/-- Given that `α ⊕ β` is a fintype, `α` is also a fintype. This is non-computable as it uses
that `sum.inl` is an injection, but there's no clear inverse if `α` is empty. -/
noncomputable def fintype.sum_left {α β} [fintype (α ⊕ β)] : fintype α :=
fintype.of_injective (sum.inl : α → α ⊕ β) sum.inl_injective
/-- Given that `α ⊕ β` is a fintype, `β` is also a fintype. This is non-computable as it uses
that `sum.inr` is an injection, but there's no clear inverse if `β` is empty. -/
noncomputable def fintype.sum_right {α β} [fintype (α ⊕ β)] : fintype β :=
fintype.of_injective (sum.inr : β → α ⊕ β) sum.inr_injective
@[simp] theorem fintype.card_sum [fintype α] [fintype β] :
fintype.card (α ⊕ β) = fintype.card α + fintype.card β :=
begin
classical,
rw [←finset.card_univ, univ_sum_type, finset.card_union_eq],
{ simp [finset.card_univ] },
{ intros x hx,
suffices : (∃ (a : α), sum.inl a = x) ∧ ∃ (b : β), sum.inr b = x,
{ obtain ⟨⟨a, rfl⟩, ⟨b, hb⟩⟩ := this,
simpa using hb },
simpa using hx }
end
/-- If the subtype of all-but-one elements is a `fintype` then the type itself is a `fintype`. -/
def fintype_of_fintype_ne (a : α) [decidable_pred (= a)] (h : fintype {b // b ≠ a}) : fintype α :=
fintype.of_equiv _ $ equiv.sum_compl (= a)
section finset
/-! ### `fintype (s : finset α)` -/
instance finset.fintype_coe_sort {α : Type u} (s : finset α) : fintype s :=
⟨s.attach, s.mem_attach⟩
@[simp] lemma finset.univ_eq_attach {α : Type u} (s : finset α) :
(univ : finset s) = s.attach :=
rfl
end finset
namespace fintype
variables [fintype α] [fintype β]
lemma card_le_of_injective (f : α → β) (hf : function.injective f) : card α ≤ card β :=
finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h)
lemma card_le_of_embedding (f : α ↪ β) : card α ≤ card β := card_le_of_injective f f.2
lemma card_lt_of_injective_of_not_mem (f : α → β) (h : function.injective f)
{b : β} (w : b ∉ set.range f) : card α < card β :=
calc card α = (univ.map ⟨f, h⟩).card : (card_map _).symm
... < card β : finset.card_lt_univ_of_not_mem $
by rwa [← mem_coe, coe_map, coe_univ, set.image_univ]
lemma card_lt_of_injective_not_surjective (f : α → β) (h : function.injective f)
(h' : ¬function.surjective f) : card α < card β :=
let ⟨y, hy⟩ := not_forall.1 h' in card_lt_of_injective_of_not_mem f h hy
lemma card_le_of_surjective (f : α → β) (h : function.surjective f) : card β ≤ card α :=
card_le_of_injective _ (function.injective_surj_inv h)
/--
The pigeonhole principle for finitely many pigeons and pigeonholes.
This is the `fintype` version of `finset.exists_ne_map_eq_of_card_lt_of_maps_to`.
-/
lemma exists_ne_map_eq_of_card_lt (f : α → β) (h : fintype.card β < fintype.card α) :
∃ x y, x ≠ y ∧ f x = f y :=
let ⟨x, _, y, _, h⟩ := finset.exists_ne_map_eq_of_card_lt_of_maps_to h (λ x _, mem_univ (f x))
in ⟨x, y, h⟩
lemma card_eq_one_iff : card α = 1 ↔ (∃ x : α, ∀ y, y = x) :=
by rw [←card_unit, card_eq]; exact
⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩,
λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm,
λ _, subsingleton.elim _ _⟩⟩⟩
lemma card_eq_zero_iff : card α = 0 ↔ is_empty α :=
by rw [card, finset.card_eq_zero, univ_eq_empty_iff]
lemma card_eq_zero [is_empty α] : card α = 0 := card_eq_zero_iff.2 ‹_›
lemma card_eq_one_iff_nonempty_unique : card α = 1 ↔ nonempty (unique α) :=
⟨λ h, let ⟨d, h⟩ := fintype.card_eq_one_iff.mp h in ⟨{ default := d, uniq := h}⟩,
λ ⟨h⟩, by exactI fintype.card_unique⟩
/-- A `fintype` with cardinality zero is equivalent to `empty`. -/
def card_eq_zero_equiv_equiv_empty : card α = 0 ≃ (α ≃ empty) :=
(equiv.of_iff card_eq_zero_iff).trans (equiv.equiv_empty_equiv α).symm
lemma card_pos_iff : 0 < card α ↔ nonempty α :=
pos_iff_ne_zero.trans $ not_iff_comm.mp $ not_nonempty_iff.trans card_eq_zero_iff.symm
lemma card_pos [h : nonempty α] : 0 < card α :=
card_pos_iff.mpr h
lemma card_ne_zero [nonempty α] : card α ≠ 0 :=
ne_of_gt card_pos
lemma card_le_one_iff : card α ≤ 1 ↔ (∀ a b : α, a = b) :=
let n := card α in
have hn : n = card α := rfl,
match n, hn with
| 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm).elim a, λ _, ha ▸ nat.le_succ _⟩
| 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in
by rw [hx a, hx b],
λ _, ha ▸ le_refl _⟩
| (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial,
(λ h, card_unit ▸ card_le_of_injective (λ _, ())
(λ _ _ _, h _ _))⟩
end
lemma card_le_one_iff_subsingleton : card α ≤ 1 ↔ subsingleton α :=
card_le_one_iff.trans subsingleton_iff.symm
lemma one_lt_card_iff_nontrivial : 1 < card α ↔ nontrivial α :=
begin
classical,
rw ←not_iff_not,
push_neg,
rw [not_nontrivial_iff_subsingleton, card_le_one_iff_subsingleton]
end
lemma exists_ne_of_one_lt_card (h : 1 < card α) (a : α) : ∃ b : α, b ≠ a :=
by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_ne a }
lemma exists_pair_of_one_lt_card (h : 1 < card α) : ∃ (a b : α), a ≠ b :=
by { haveI : nontrivial α := one_lt_card_iff_nontrivial.1 h, exact exists_pair_ne α }
lemma card_eq_one_of_forall_eq {i : α} (h : ∀ j, j = i) : card α = 1 :=
fintype.card_eq_one_iff.2 ⟨i,h⟩
lemma one_lt_card [h : nontrivial α] : 1 < fintype.card α :=
fintype.one_lt_card_iff_nontrivial.mpr h
lemma injective_iff_surjective {f : α → α} : injective f ↔ surjective f :=
by haveI := classical.prop_decidable; exact
have ∀ {f : α → α}, injective f → surjective f,
from λ f hinj x,
have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _)
((card_image_of_injective univ hinj).symm ▸ le_refl _),
have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _,
exists_of_bex (mem_image.1 h₂),
⟨this,
λ hsurj, has_left_inverse.injective
⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse
(this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩
lemma injective_iff_bijective {f : α → α} : injective f ↔ bijective f :=
by simp [bijective, injective_iff_surjective]
lemma surjective_iff_bijective {f : α → α} : surjective f ↔ bijective f :=
by simp [bijective, injective_iff_surjective]
lemma injective_iff_surjective_of_equiv {β : Type*} {f : α → β} (e : α ≃ β) :
injective f ↔ surjective f :=
have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from injective_iff_surjective,
⟨λ hinj, by simpa [function.comp] using
e.surjective.comp (this.1 (e.symm.injective.comp hinj)),
λ hsurj, by simpa [function.comp] using
e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩
lemma card_of_bijective {f : α → β} (hf : bijective f) : card α = card β :=
card_congr (equiv.of_bijective f hf)
lemma bijective_iff_injective_and_card (f : α → β) :
bijective f ↔ injective f ∧ card α = card β :=
begin
split,
{ intro h, exact ⟨h.1, card_of_bijective h⟩ },
{ rintro ⟨hf, h⟩,
refine ⟨hf, _⟩,
rwa ←injective_iff_surjective_of_equiv (equiv_of_card_eq h) }
end
lemma bijective_iff_surjective_and_card (f : α → β) :
bijective f ↔ surjective f ∧ card α = card β :=
begin
split,
{ intro h, exact ⟨h.2, card_of_bijective h⟩ },
{ rintro ⟨hf, h⟩,
refine ⟨_, hf⟩,
rwa injective_iff_surjective_of_equiv (equiv_of_card_eq h) }
end
lemma right_inverse_of_left_inverse_of_card_le {f : α → β} {g : β → α}
(hfg : left_inverse f g) (hcard : card α ≤ card β) :
right_inverse f g :=
have hsurj : surjective f, from surjective_iff_has_right_inverse.2 ⟨g, hfg⟩,
right_inverse_of_injective_of_left_inverse
((bijective_iff_surjective_and_card _).2
⟨hsurj, le_antisymm hcard (card_le_of_surjective f hsurj)⟩ ).1
hfg
lemma left_inverse_of_right_inverse_of_card_le {f : α → β} {g : β → α}
(hfg : right_inverse f g) (hcard : card β ≤ card α) :
left_inverse f g :=
right_inverse_of_left_inverse_of_card_le hfg hcard
end fintype
lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} :
↑(finset.image f finset.univ) = set.range f :=
by { ext x, simp }
instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} :=
fintype.of_list l.attach l.mem_attach
instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} :=
fintype.of_multiset s.attach s.mem_attach
instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} :=
⟨s.attach, s.mem_attach⟩
instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) :=
finset.subtype.fintype s
@[simp] lemma fintype.card_coe (s : finset α) :
fintype.card s = s.card := card_attach
lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl
instance plift.fintype_Prop (p : Prop) [decidable p] : fintype (plift p) :=
⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩
instance Prop.fintype : fintype Prop :=
⟨⟨true ::ₘ false ::ₘ 0, by simp [true_ne_false]⟩,
classical.cases (by simp) (by simp)⟩
instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} :=
fintype.subtype (univ.filter p) (by simp)
/-- A set on a fintype, when coerced to a type, is a fintype. -/
def set_fintype {α} [fintype α] (s : set α) [decidable_pred (∈ s)] : fintype s :=
subtype.fintype (λ x, x ∈ s)
lemma set_fintype_card_le_univ {α : Type*} [fintype α] (s : set α) [fintype ↥s] :
fintype.card ↥s ≤ fintype.card α :=
fintype.card_le_of_embedding (function.embedding.subtype s)
section
variables (α)
/-- The `units α` type is equivalent to a subtype of `α × α`. -/
@[simps]
def _root_.units_equiv_prod_subtype [monoid α] :
units α ≃ {p : α × α // p.1 * p.2 = 1 ∧ p.2 * p.1 = 1} :=
{ to_fun := λ u, ⟨(u, ↑u⁻¹), u.val_inv, u.inv_val⟩,
inv_fun := λ p, units.mk (p : α × α).1 (p : α × α).2 p.prop.1 p.prop.2,
left_inv := λ u, units.ext rfl,
right_inv := λ p, subtype.ext $ prod.ext rfl rfl}
/-- In a `group_with_zero` `α`, the unit group `units α` is equivalent to the subtype of nonzero
elements. -/
@[simps]
def _root_.units_equiv_ne_zero [group_with_zero α] : units α ≃ {a : α // a ≠ 0} :=
⟨λ a, ⟨a, a.ne_zero⟩, λ a, units.mk0 _ a.prop, λ _, units.ext rfl, λ _, subtype.ext rfl⟩
end
instance [monoid α] [fintype α] [decidable_eq α] : fintype (units α) :=
fintype.of_equiv _ (units_equiv_prod_subtype α).symm
lemma fintype.card_units [group_with_zero α] [fintype α] [fintype (units α)] :
fintype.card (units α) = fintype.card α - 1 :=
begin
classical,
rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : α)⟩),
fintype.card_congr (units_equiv_ne_zero α)],
have := fintype.card_congr (equiv.sum_compl (= (0 : α))).symm,
rwa [fintype.card_sum, add_comm, fintype.card_subtype_eq] at this,
end
namespace function.embedding
/-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/
noncomputable def equiv_of_fintype_self_embedding [fintype α] (e : α ↪ α) : α ≃ α :=
equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2)
@[simp]
lemma equiv_of_fintype_self_embedding_to_embedding [fintype α] (e : α ↪ α) :
e.equiv_of_fintype_self_embedding.to_embedding = e :=
by { ext, refl, }
/-- If `‖β‖ < ‖α‖` there are no embeddings `α ↪ β`.
This is a formulation of the pigeonhole principle.
Note this cannot be an instance as it needs `h`. -/
@[simp] lemma is_empty_of_card_lt [fintype α] [fintype β]
(h : fintype.card β < fintype.card α) : is_empty (α ↪ β) :=
⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_card_lt f h in ne $ f.injective feq⟩
/-- A constructive embedding of a fintype `α` in another fintype `β` when `card α ≤ card β`. -/
def trunc_of_card_le [fintype α] [fintype β] [decidable_eq α] [decidable_eq β]
(h : fintype.card α ≤ fintype.card β) : trunc (α ↪ β) :=
(fintype.trunc_equiv_fin α).bind $ λ ea,
(fintype.trunc_equiv_fin β).map $ λ eb,
ea.to_embedding.trans ((fin.cast_le h).to_embedding.trans eb.symm.to_embedding)
lemma nonempty_of_card_le [fintype α] [fintype β]
(h : fintype.card α ≤ fintype.card β) : nonempty (α ↪ β) :=
by { classical, exact (trunc_of_card_le h).nonempty }
lemma exists_of_card_le_finset [fintype α] {s : finset β} (h : fintype.card α ≤ s.card) :
∃ (f : α ↪ β), set.range f ⊆ s :=
begin
rw ← fintype.card_coe at h,
rcases nonempty_of_card_le h with ⟨f⟩,
exact ⟨f.trans (embedding.subtype _), by simp [set.range_subset_iff]⟩
end
end function.embedding
@[simp]
lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) :
univ.map e = univ :=
by rw [←e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding]
namespace fintype
lemma card_lt_of_surjective_not_injective [fintype α] [fintype β] (f : α → β)
(h : function.surjective f) (h' : ¬function.injective f) : card β < card α :=
card_lt_of_injective_not_surjective _ (function.injective_surj_inv h) $ λ hg,
have w : function.bijective (function.surj_inv h) := ⟨function.injective_surj_inv h, hg⟩,
h' $ (injective_iff_surjective_of_equiv (equiv.of_bijective _ w).symm).mpr h
variables [decidable_eq α] [fintype α] {δ : α → Type*}
/-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the
analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as
there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/
def pi_finset (t : Π a, finset (δ a)) : finset (Π a, δ a) :=
(finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩
@[simp] lemma mem_pi_finset {t : Π a, finset (δ a)} {f : Π a, δ a} :
f ∈ pi_finset t ↔ (∀ a, f a ∈ t a) :=
begin
split,
{ simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ,
exists_imp_distrib, mem_pi],
rintro g hg hgf a,
rw ← hgf,
exact hg a },
{ simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi],
exact λ hf, ⟨λ a ha, f a, hf, rfl⟩ }
end
lemma pi_finset_subset (t₁ t₂ : Π a, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) :
pi_finset t₁ ⊆ pi_finset t₂ :=
λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a
lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)]
(t₁ t₂ : Π a, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) :
disjoint (pi_finset t₁) (pi_finset t₂) :=
disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂,
disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a)
end fintype
/-! ### pi -/
/-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/
instance pi.fintype {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀ a, fintype (β a)] : fintype (Π a, β a) :=
⟨fintype.pi_finset (λ _, univ), by simp⟩
@[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀ a, fintype (β a)] :
fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) :=
rfl
instance d_array.fintype {n : ℕ} {α : fin n → Type*}
[∀ n, fintype (α n)] : fintype (d_array n α) :=
fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm
instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) :=
d_array.fintype
instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) :=
fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm
instance quotient.fintype [fintype α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) :=
fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
instance finset.fintype [fintype α] : fintype (finset α) :=
⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩
-- irreducible due to this conversation on Zulip:
-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/
-- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115
@[irreducible] instance function.embedding.fintype {α β} [fintype α] [fintype β]
[decidable_eq α] [decidable_eq β] : fintype (α ↪ β) :=
fintype.of_equiv _ (equiv.subtype_injective_equiv_embedding α β)
instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym.sym' α n) :=
quotient.fintype _
instance [decidable_eq α] [fintype α] {n : ℕ} : fintype (sym α n) :=
fintype.of_equiv _ sym.sym_equiv_sym'.symm
@[simp] lemma fintype.card_finset [fintype α] :
fintype.card (finset α) = 2 ^ (fintype.card α) :=
finset.card_powerset finset.univ
@[simp] lemma finset.univ_filter_card_eq (α : Type*) [fintype α] (k : ℕ) :
(finset.univ : finset (finset α)).filter (λ s, s.card = k) = finset.univ.powerset_len k :=
by { ext, simp [finset.mem_powerset_len] }
@[simp] lemma fintype.card_finset_len [fintype α] (k : ℕ) :
fintype.card {s : finset α // s.card = k} = nat.choose (fintype.card α) k :=
by simp [fintype.subtype_card, finset.card_univ]
@[simp] lemma set.to_finset_univ [fintype α] :
(set.univ : set α).to_finset = finset.univ :=
by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] }
@[simp] lemma set.to_finset_eq_empty_iff {s : set α} [fintype s] :
s.to_finset = ∅ ↔ s = ∅ :=
by simp [ext_iff, set.ext_iff]
@[simp] lemma set.to_finset_empty :
(∅ : set α).to_finset = ∅ :=
set.to_finset_eq_empty_iff.mpr rfl
@[simp] lemma set.to_finset_range [decidable_eq α] [fintype β] (f : β → α) [fintype (set.range f)] :
(set.range f).to_finset = finset.univ.image f :=
by simp [ext_iff]
theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] :
fintype.card {x // p x} ≤ fintype.card α :=
fintype.card_le_of_embedding (function.embedding.subtype _)
theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p]
{x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α :=
fintype.card_lt_of_injective_of_not_mem coe subtype.coe_injective $ by rwa subtype.range_coe_subtype
lemma fintype.card_subtype [fintype α] (p : α → Prop) [decidable_pred p] :
fintype.card {x // p x} = ((finset.univ : finset α).filter p).card :=
begin
refine fintype.card_of_subtype _ _,
simp
end
lemma fintype.card_subtype_or (p q : α → Prop)
[fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] :
fintype.card {x // p x ∨ q x} ≤ fintype.card {x // p x} + fintype.card {x // q x} :=
begin
classical,
convert fintype.card_le_of_embedding (subtype_or_left_embedding p q),
rw fintype.card_sum
end
lemma fintype.card_subtype_or_disjoint (p q : α → Prop) (h : disjoint p q)
[fintype {x // p x}] [fintype {x // q x}] [fintype {x // p x ∨ q x}] :
fintype.card {x // p x ∨ q x} = fintype.card {x // p x} + fintype.card {x // q x} :=
begin
classical,
convert fintype.card_congr (subtype_or_equiv p q h),
simp
end
theorem fintype.card_quotient_le [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] :
fintype.card (quotient s) ≤ fintype.card α :=
fintype.card_le_of_surjective _ (surjective_quotient_mk _)
theorem fintype.card_quotient_lt [fintype α] {s : setoid α} [decidable_rel ((≈) : α → α → Prop)]
{x y : α} (h1 : x ≠ y) (h2 : x ≈ y) : fintype.card (quotient s) < fintype.card α :=
fintype.card_lt_of_surjective_not_injective _ (surjective_quotient_mk _) $ λ w,
h1 (w $ quotient.eq.mpr h2)
instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] :
fintype (Σ' a, β a) :=
fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm
instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] :
fintype (Σ' a, β a) :=
if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩
else ⟨∅, λ x, h x.1⟩
instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] :
fintype (Σ' a, β a) :=
fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩
instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] :
fintype (Σ' a, β a) :=
if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩
instance set.fintype [fintype α] : fintype (set α) :=
⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin
classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩,
apply (coe_filter _ _).trans, rw [coe_univ, set.sep_univ], refl
end⟩
@[simp] lemma fintype.card_set [fintype α] : fintype.card (set α) = 2 ^ fintype.card α :=
(finset.card_map _).trans (finset.card_powerset _)
instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) :=
if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩
else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩
@[simp] lemma finset.univ_pi_univ {α : Type*} {β : α → Type*}
[decidable_eq α] [fintype α] [∀ a, fintype (β a)] :
finset.univ.pi (λ a : α, (finset.univ : finset (β a))) = finset.univ :=
by { ext, simp }
lemma mem_image_univ_iff_mem_range
{α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} :
b ∈ univ.image f ↔ b ∈ set.range f :=
by simp
/-- An auxiliary function for `quotient.fin_choice`. Given a
collection of setoids indexed by a type `ι`, a (finite) list `l` of
indices, and a function that for each `i ∈ l` gives a term of the
corresponding quotient type, then there is a corresponding term in the
quotient of the product of the setoids indexed by `l`. -/
def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
Π (l : list ι), (Π i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance)
| [] f := ⟦λ i, false.elim⟧
| (i :: l) f := begin
refine quotient.lift_on₂ (f i (list.mem_cons_self _ _))
(quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h)))
_ _,
exact λ a l, ⟦λ j h,
if e : j = i then by rw e; exact a else
l _ (h.resolve_left e)⟧,
refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
{ subst j, exact h₁ },
{ exact h₂ _ _ }
end
theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι) (f : Π i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧
| [] f := quotient.sound (λ i h, h.elim)
| (i :: l) f := begin
simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l],
refine quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
subst j, refl
end
/-- Given a collection of setoids indexed by a fintype `ι` and a
function that for each `i : ι` gives a term of the corresponding
quotient type, then there is corresponding term in the quotient of the
product of the setoids. -/
def quotient.fin_choice {ι : Type*} [decidable_eq ι] [fintype ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι,
@quotient (Π i ∈ l, α i) (by apply_instance))
finset.univ.1
(λ l, quotient.fin_choice_aux l (λ i _, f i))
(λ a b h, begin
have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)),
simp [quotient.out_eq] at this,
simp [this],
let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧,
refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)),
congr' 1, exact quotient.sound h,
end))
(λ f, ⟦λ i, f i (finset.mem_univ _)⟧)
(λ a b h, quotient.sound $ λ i, h _ _)
theorem quotient.fin_choice_eq {ι : Type*} [decidable_eq ι] [fintype ι]
{α : ι → Type*} [∀ i, setoid (α i)]
(f : Π i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
begin
let q, swap, change quotient.lift_on q _ _ = _,
have : q = ⟦λ i h, f i⟧,
{ dsimp [q],
exact quotient.induction_on
(@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) },
simp [this], exact setoid.refl _
end
section equiv
open list equiv equiv.perm
variables [decidable_eq α] [decidable_eq β]
/-- Given a list, produce a list of all permutations of its elements. -/
def perms_of_list : list α → list (perm α)
| [] := [1]
| (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f))
lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length!
| [] := rfl
| (a :: l) :=
begin
rw [length_cons, nat.factorial_succ],
simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul],
cc
end
lemma mem_perms_of_list_of_mem {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l) :
f ∈ perms_of_list l :=
begin
induction l with a l IH generalizing f h,
{ exact list.mem_singleton.2 (equiv.ext $ λ x, decidable.by_contradiction $ h _) },
by_cases hfa : f a = a,
{ refine mem_append_left _ (IH (λ x hx, mem_of_ne_of_mem _ (h x hx))),
rintro rfl, exact hx hfa },
have hfa' : f (f a) ≠ f a := mt (λ h, f.injective h) hfa,
have : ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l,
{ intros x hx,
have hxa : x ≠ a,
{ rintro rfl, apply hx, simp only [mul_apply, swap_apply_right] },
refine list.mem_of_ne_of_mem hxa (h x (λ h, _)),
simp only [h, mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq] at hx;
split_ifs at hx, exacts [hxa (h.symm.trans h_1), hx h] },
suffices : f ∈ perms_of_list l ∨ ∃ (b ∈ l) (g ∈ perms_of_list l), swap a b * g = f,
{ simpa only [perms_of_list, exists_prop, list.mem_map, mem_append, list.mem_bind] },
refine or_iff_not_imp_left.2 (λ hfl, ⟨f a, _, swap a (f a) * f, IH this, _⟩),
{ by_cases hffa : f (f a) = a,
{ exact mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) },
{ apply this,
simp only [mul_apply, swap_apply_def, mul_apply, ne.def, apply_eq_iff_eq],
split_ifs; cc } },
{ rw [←mul_assoc, mul_def (swap a (f a)) (swap a (f a)),
swap_swap, ←perm.one_def, one_mul] }
end
lemma mem_of_mem_perms_of_list :
∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l
| [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp
| (a :: l) f h :=
(mem_append.1 h).elim
(λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx))
(λ h x hx,
let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in
let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in
if hxa : x = a then by simp [hxa]
else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy
else mem_cons_of_mem _ $
mem_of_mem_perms_of_list hg₁ $
by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def];
split_ifs; cc)
lemma mem_perms_of_list_iff {l : list α} {f : perm α} :
f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩
lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup
| [] hl := by simp [perms_of_list]
| (a :: l) hl :=
have hl' : l.nodup, from nodup_of_nodup_cons hl,
have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl',
have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a,
from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1),
by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact
⟨hln', ⟨λ _ _, nodup_map (λ _ _, mul_left_cancel) hln',
λ i j hj hij x hx₁ hx₂,
let ⟨f, hf⟩ := list.mem_map.1 hx₁ in
let ⟨g, hg⟩ := list.mem_map.1 hx₂ in
have hix : x a = nth_le l i (lt_trans hij hj),
by rw [←hf.2, mul_apply, hmeml hf.1, swap_apply_left],
have hiy : x a = nth_le l j hj,
by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left],
absurd (hf.2.trans (hg.2.symm)) $
λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $
by rw [← hix, hiy]⟩,
λ f hf₁ hf₂,
let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in
let ⟨g, hg⟩ := list.mem_map.1 hx' in
have hgxa : g⁻¹ x = a, from f.injective $
by rw [hmeml hf₁, ← hg.2]; simp,
have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx),
(list.nodup_cons.1 hl).1 $
hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩
/-- Given a finset, produce the finset of all permutations of its elements. -/
def perms_of_finset (s : finset α) : finset (perm α) :=
quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩)
(λ a b hab, hfunext (congr_arg _ (quotient.sound hab))
(λ ha hb _, heq_of_eq $ finset.ext $
by simp [mem_perms_of_list_iff, hab.mem_iff]))
s.2
lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α},
f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s :=
by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff
lemma card_perms_of_finset : ∀ (s : finset α),
(perms_of_finset s).card = s.card! :=
by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l
/-- The collection of permutations of a fintype is a fintype. -/
def fintype_perm [fintype α] : fintype (perm α) :=
⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
instance [fintype α] [fintype β] : fintype (α ≃ β) :=
if h : fintype.card β = fintype.card α
then trunc.rec_on_subsingleton (fintype.trunc_equiv_fin α)
(λ eα, trunc.rec_on_subsingleton (fintype.trunc_equiv_fin β)
(λ eβ, @fintype.of_equiv _ (perm α) fintype_perm
(equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β))))
else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩
lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α)! :=
subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸
card_perms_of_finset _
lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) :
fintype.card (α ≃ β) = (fintype.card α)! :=
fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) :
(univ : finset α) = {x} :=
begin
symmetry,
apply eq_of_subset_of_card_le (subset_univ ({x})),
apply le_of_eq,
simp [h, finset.card_univ]
end
end equiv
namespace fintype
section choose
open fintype equiv
variables [fintype α] (p : α → Prop) [decidable_pred p]
/-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of
`α` satisfying `p` this unique element, as an element of the corresponding subtype. -/
def choose_x (hp : ∃! a : α, p a) : {a // p a} :=
⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩
/-- Given a fintype `α` and a predicate `p`, associate to a proof that there is a unique element of
`α` satisfying `p` this unique element, as an element of `α`. -/
def choose (hp : ∃! a, p a) : α := choose_x p hp
lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) :=
(choose_x p hp).property
@[simp] lemma choose_subtype_eq {α : Type*} (p : α → Prop) [fintype {a : α // p a}]
[decidable_eq α] (x : {a : α // p a})
(h : ∃! (a : {a // p a}), (a : α) = x := ⟨x, rfl, λ y hy, by simpa [subtype.ext_iff] using hy⟩) :
fintype.choose (λ (y : {a : α // p a}), (y : α) = x) h = x :=
by rw [subtype.ext_iff, fintype.choose_spec (λ (y : {a : α // p a}), (y : α) = x) _]
end choose
section bijection_inverse
open function
variables [fintype α] [decidable_eq β] {f : α → β}
/--
`bij_inv f` is the unique inverse to a bijection `f`. This acts
as a computable alternative to `function.inv_fun`. -/
def bij_inv (f_bij : bijective f) (b : β) : α :=
fintype.choose (λ a, f a = b)
begin
rcases f_bij.right b with ⟨a', fa_eq_b⟩,
rw ← fa_eq_b,
exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩
end
lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f :=
λ a, f_bij.left (choose_spec (λ a', f a' = f a) _)
lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f :=
λ b, choose_spec (λ a', f a' = b) _
lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) :=
⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩
end bijection_inverse
lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop)
[is_trans α r] [is_irrefl α r] : well_founded r :=
by classical; exact
have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card,
from λ x y hxy, finset.card_lt_card $
by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le,
finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy];
exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩,
subrelation.wf this (measure_wf _)
lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) :=
well_founded_of_trans_of_irrefl _
@[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] :
is_well_order α (<) :=
{ wf := preorder.well_founded }
end fintype
/-- A type is said to be infinite if it has no fintype instance.
Note that `infinite α` is equivalent to `is_empty (fintype α)`. -/
class infinite (α : Type*) : Prop :=
(not_fintype : fintype α → false)
lemma not_fintype (α : Type*) [h1 : infinite α] [h2 : fintype α] : false :=
infinite.not_fintype h2
protected lemma fintype.false {α : Type*} [infinite α] (h : fintype α) : false :=
not_fintype α
protected lemma infinite.false {α : Type*} [fintype α] (h : infinite α) : false :=
not_fintype α
@[simp] lemma is_empty_fintype {α : Type*} : is_empty (fintype α) ↔ infinite α :=
⟨λ ⟨x⟩, ⟨x⟩, λ ⟨x⟩, ⟨x⟩⟩
/-- A non-infinite type is a fintype. -/
noncomputable def fintype_of_not_infinite {α : Type*} (h : ¬ infinite α) : fintype α :=
nonempty.some $ by rwa [← not_is_empty_iff, is_empty_fintype]
section
open_locale classical
/--
Any type is (classically) either a `fintype`, or `infinite`.
One can obtain the relevant typeclasses via `cases fintype_or_infinite α; resetI`.
-/
noncomputable def fintype_or_infinite (α : Type*) : psum (fintype α) (infinite α) :=
if h : infinite α then psum.inr h else psum.inl (fintype_of_not_infinite h)
end
lemma finset.exists_minimal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) :
∃ m ∈ s, ∀ x ∈ s, ¬ (x < m) :=
begin
obtain ⟨c, hcs : c ∈ s⟩ := h,
have : well_founded (@has_lt.lt {x // x ∈ s} _) := fintype.well_founded_of_trans_of_irrefl _,
obtain ⟨⟨m, hms : m ∈ s⟩, -, H⟩ := this.has_min set.univ ⟨⟨c, hcs⟩, trivial⟩,
exact ⟨m, hms, λ x hx hxm, H ⟨x, hx⟩ trivial hxm⟩,
end
lemma finset.exists_maximal {α : Type*} [preorder α] (s : finset α) (h : s.nonempty) :
∃ m ∈ s, ∀ x ∈ s, ¬ (m < x) :=
@finset.exists_minimal (order_dual α) _ s h
namespace infinite
lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s :=
not_forall.1 $ λ h, fintype.false ⟨s, h⟩
@[priority 100] -- see Note [lower instance priority]
instance (α : Type*) [H : infinite α] : nontrivial α :=
⟨let ⟨x, hx⟩ := exists_not_mem_finset (∅ : finset α) in
let ⟨y, hy⟩ := exists_not_mem_finset ({x} : finset α) in
⟨y, x, by simpa only [mem_singleton] using hy⟩⟩
protected lemma nonempty (α : Type*) [infinite α] : nonempty α :=
by apply_instance
lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α :=
⟨λ I, by exactI (fintype.of_injective f hf).false⟩
lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α :=
⟨λ I, by { classical, exactI (fintype.of_surjective f hf).false }⟩
instance : infinite ℕ :=
⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩
instance : infinite ℤ :=
infinite.of_injective int.of_nat (λ _ _, int.of_nat.inj)
instance [infinite α] : infinite (set α) :=
of_injective singleton (λ a b, set.singleton_eq_singleton_iff.1)
instance [infinite α] : infinite (finset α) := of_injective singleton finset.singleton_injective
instance [nonempty α] : infinite (multiset α) :=
begin
inhabit α,
exact of_injective (multiset.repeat (default α)) (multiset.repeat_injective _),
end
instance [nonempty α] : infinite (list α) :=
of_surjective (coe : list α → multiset α) (surjective_quot_mk _)
instance sum_of_left [infinite α] : infinite (α ⊕ β) :=
of_injective sum.inl sum.inl_injective
instance sum_of_right [infinite β] : infinite (α ⊕ β) :=
of_injective sum.inr sum.inr_injective
instance prod_of_right [nonempty α] [infinite β] : infinite (α × β) :=
of_surjective prod.snd prod.snd_surjective
instance prod_of_left [infinite α] [nonempty β] : infinite (α × β) :=
of_surjective prod.fst prod.fst_surjective
private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α
| n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset
((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m)
(λ _, multiset.mem_range.1)).to_finset)
private lemma nat_embedding_aux_injective (α : Type*) [infinite α] :
function.injective (nat_embedding_aux α) :=
begin
rintro m n h,
letI := classical.dec_eq α,
wlog hmlen : m ≤ n using m n,
by_contradiction hmn,
have hmn : m < n, from lt_of_le_of_ne hmlen hmn,
refine (classical.some_spec (exists_not_mem_finset
((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m)
(λ _, multiset.mem_range.1)).to_finset)) _,
refine multiset.mem_to_finset.2 (multiset.mem_pmap.2
⟨m, multiset.mem_range.2 hmn, _⟩),
rw [h, nat_embedding_aux]
end
/-- Embedding of `ℕ` into an infinite type. -/
noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α :=
⟨_, nat_embedding_aux_injective α⟩
lemma exists_subset_card_eq (α : Type*) [infinite α] (n : ℕ) :
∃ s : finset α, s.card = n :=
⟨(range n).map (nat_embedding α), by rw [card_map, card_range]⟩
end infinite
@[simp] lemma infinite_sum : infinite (α ⊕ β) ↔ infinite α ∨ infinite β :=
begin
refine ⟨λ H, _, λ H, H.elim (@infinite.sum_of_left α β) (@infinite.sum_of_right α β)⟩,
contrapose! H, haveI := fintype_of_not_infinite H.1, haveI := fintype_of_not_infinite H.2,
exact infinite.false
end
@[simp] lemma infinite_prod :
infinite (α × β) ↔ infinite α ∧ nonempty β ∨ nonempty α ∧ infinite β :=
begin
refine ⟨λ H, _, λ H, H.elim (and_imp.2 $ @infinite.prod_of_left α β)
(and_imp.2 $ @infinite.prod_of_right α β)⟩,
rw and.comm, contrapose! H, introI H',
rcases infinite.nonempty (α × β) with ⟨a, b⟩,
haveI := fintype_of_not_infinite (H.1 ⟨b⟩), haveI := fintype_of_not_infinite (H.2 ⟨a⟩),
exact H'.false
end
/-- If every finset in a type has bounded cardinality, that type is finite. -/
noncomputable def fintype_of_finset_card_le {ι : Type*} (n : ℕ)
(w : ∀ s : finset ι, s.card ≤ n) : fintype ι :=
begin
apply fintype_of_not_infinite,
introI i,
obtain ⟨s, c⟩ := infinite.exists_subset_card_eq ι (n+1),
specialize w s,
rw c at w,
exact nat.not_succ_le_self n w,
end
lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) :
¬ injective f :=
λ hf, (fintype.of_injective f hf).false
/--
The pigeonhole principle for infinitely many pigeons in finitely many pigeonholes. If there are
infinitely many pigeons in finitely many pigeonholes, then there are at least two pigeons in the
same pigeonhole.
See also: `fintype.exists_ne_map_eq_of_card_lt`, `fintype.exists_infinite_fiber`.
-/
lemma fintype.exists_ne_map_eq_of_infinite [infinite α] [fintype β] (f : α → β) :
∃ x y : α, x ≠ y ∧ f x = f y :=
begin
classical, by_contra hf, push_neg at hf,
apply not_injective_infinite_fintype f,
intros x y, contrapose, apply hf,
end
-- irreducible due to this conversation on Zulip:
-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/
-- topic/.60simp.60.20ignoring.20lemmas.3F/near/241824115
@[irreducible]
instance function.embedding.is_empty {α β} [infinite α] [fintype β] : is_empty (α ↪ β) :=
⟨λ f, let ⟨x, y, ne, feq⟩ := fintype.exists_ne_map_eq_of_infinite f in ne $ f.injective feq⟩
@[priority 100]
noncomputable instance function.embedding.fintype' {α β : Type*} [fintype β] : fintype (α ↪ β) :=
begin
by_cases h : infinite α,
{ resetI, apply_instance },
{ have := fintype_of_not_infinite h, classical, apply_instance }
-- the `classical` generates `decidable_eq α/β` instances, and resets instance cache
end
/--
The strong pigeonhole principle for infinitely many pigeons in
finitely many pigeonholes. If there are infinitely many pigeons in
finitely many pigeonholes, then there is a pigeonhole with infinitely
many pigeons.
See also: `fintype.exists_ne_map_eq_of_infinite`
-/
lemma fintype.exists_infinite_fiber [infinite α] [fintype β] (f : α → β) :
∃ y : β, infinite (f ⁻¹' {y}) :=
begin
classical,
by_contra hf,
push_neg at hf,
haveI := λ y, fintype_of_not_infinite $ hf y,
let key : fintype α :=
{ elems := univ.bUnion (λ (y : β), (f ⁻¹' {y}).to_finset),
complete := by simp },
exact key.false,
end
lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) :
¬ surjective f :=
assume (hf : surjective f),
have H : infinite α := infinite.of_surjective f hf,
by exactI not_fintype α
section trunc
/--
For `s : multiset α`, we can lift the existential statement that `∃ x, x ∈ s` to a `trunc α`.
-/
def trunc_of_multiset_exists_mem {α} (s : multiset α) : (∃ x, x ∈ s) → trunc α :=
quotient.rec_on_subsingleton s $ λ l h,
match l, h with
| [], _ := false.elim (by tauto)
| (a :: _), _ := trunc.mk a
end
/--
A `nonempty` `fintype` constructively contains an element.
-/
def trunc_of_nonempty_fintype (α) [nonempty α] [fintype α] : trunc α :=
trunc_of_multiset_exists_mem finset.univ.val (by simp)
/--
A `fintype` with positive cardinality constructively contains an element.
-/
def trunc_of_card_pos {α} [fintype α] (h : 0 < fintype.card α) : trunc α :=
by { letI := (fintype.card_pos_iff.mp h), exact trunc_of_nonempty_fintype α }
/--
By iterating over the elements of a fintype, we can lift an existential statement `∃ a, P a`
to `trunc (Σ' a, P a)`, containing data.
-/
def trunc_sigma_of_exists {α} [fintype α] {P : α → Prop} [decidable_pred P] (h : ∃ a, P a) :
trunc (Σ' a, P a) :=
@trunc_of_nonempty_fintype (Σ' a, P a) (exists.elim h $ λ a ha, ⟨⟨a, ha⟩⟩) _
end trunc
namespace multiset
variables [fintype α] [decidable_eq α]
@[simp] lemma count_univ (a : α) :
count a finset.univ.val = 1 :=
count_eq_one_of_mem finset.univ.nodup (finset.mem_univ _)
end multiset
namespace fintype
/-- A recursor principle for finite types, analogous to `nat.rec`. It effectively says
that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/
def trunc_rec_empty_option {P : Type u → Sort v}
(of_equiv : ∀ {α β}, α ≃ β → P α → P β)
(h_empty : P pempty)
(h_option : ∀ {α} [fintype α] [decidable_eq α], P α → P (option α))
(α : Type u) [fintype α] [decidable_eq α] : trunc (P α) :=
begin
suffices : ∀ n : ℕ, trunc (P (ulift $ fin n)),
{ apply trunc.bind (this (fintype.card α)),
intro h,
apply trunc.map _ (fintype.trunc_equiv_fin α),
intro e,
exact of_equiv (equiv.ulift.trans e.symm) h },
intro n,
induction n with n ih,
{ have : card pempty = card (ulift (fin 0)),
{ simp only [card_fin, card_pempty, card_ulift] },
apply trunc.bind (trunc_equiv_of_card_eq this),
intro e,
apply trunc.mk,
refine of_equiv e h_empty, },
{ have : card (option (ulift (fin n))) = card (ulift (fin n.succ)),
{ simp only [card_fin, card_option, card_ulift] },
apply trunc.bind (trunc_equiv_of_card_eq this),
intro e,
apply trunc.map _ ih,
intro ih,
refine of_equiv e (h_option ih), },
end
/-- An induction principle for finite types, analogous to `nat.rec`. It effectively says
that every `fintype` is either `empty` or `option α`, up to an `equiv`. -/
lemma induction_empty_option {P : Type u → Prop}
(of_equiv : ∀ {α β}, α ≃ β → P α → P β)
(h_empty : P pempty)
(h_option : ∀ {α} [fintype α], P α → P (option α))
(α : Type u) [fintype α] : P α :=
begin
haveI := classical.dec_eq α,
obtain ⟨p⟩ := trunc_rec_empty_option @of_equiv h_empty (λ _ _ _, by exactI h_option) α,
exact p,
end
end fintype
/-- Auxiliary definition to show `exists_seq_of_forall_finset_exists`. -/
noncomputable def seq_of_forall_finset_exists_aux
{α : Type*} [decidable_eq α] (P : α → Prop) (r : α → α → Prop)
(h : ∀ (s : finset α), ∃ y, (∀ x ∈ s, P x) → (P y ∧ (∀ x ∈ s, r x y))) : ℕ → α
| n := classical.some (h (finset.image (λ (i : fin n), seq_of_forall_finset_exists_aux i)
(finset.univ : finset (fin n))))
using_well_founded {dec_tac := `[exact i.2]}
/-- Induction principle to build a sequence, by adding one point at a time satisfying a given
relation with respect to all the previously chosen points.
More precisely, Assume that, for any finite set `s`, one can find another point satisfying
some relation `r` with respect to all the points in `s`. Then one may construct a
function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m < n`.
We also ensure that all constructed points satisfy a given predicate `P`. -/
lemma exists_seq_of_forall_finset_exists {α : Type*} (P : α → Prop) (r : α → α → Prop)
(h : ∀ (s : finset α), (∀ x ∈ s, P x) → ∃ y, P y ∧ (∀ x ∈ s, r x y)) :
∃ (f : ℕ → α), (∀ n, P (f n)) ∧ (∀ m n, m < n → r (f m) (f n)) :=
begin
classical,
haveI : nonempty α,
{ rcases h ∅ (by simp) with ⟨y, hy⟩,
exact ⟨y⟩ },
choose! F hF using h,
have h' : ∀ (s : finset α), ∃ y, (∀ x ∈ s, P x) → (P y ∧ (∀ x ∈ s, r x y)) := λ s, ⟨F s, hF s⟩,
set f := seq_of_forall_finset_exists_aux P r h' with hf,
have A : ∀ (n : ℕ), P (f n),
{ assume n,
induction n using nat.strong_induction_on with n IH,
have IH' : ∀ (x : fin n), P (f x) := λ n, IH n.1 n.2,
rw [hf, seq_of_forall_finset_exists_aux],
exact (classical.some_spec (h' (finset.image (λ (i : fin n), f i)
(finset.univ : finset (fin n)))) (by simp [IH'])).1 },
refine ⟨f, A, λ m n hmn, _⟩,
nth_rewrite 1 hf,
rw seq_of_forall_finset_exists_aux,
apply (classical.some_spec (h' (finset.image (λ (i : fin n), f i)
(finset.univ : finset (fin n)))) (by simp [A])).2,
exact finset.mem_image.2 ⟨⟨m, hmn⟩, finset.mem_univ _, rfl⟩,
end
/-- Induction principle to build a sequence, by adding one point at a time satisfying a given
symmetric relation with respect to all the previously chosen points.
More precisely, Assume that, for any finite set `s`, one can find another point satisfying
some relation `r` with respect to all the points in `s`. Then one may construct a
function `f : ℕ → α` such that `r (f m) (f n)` holds whenever `m ≠ n`.
We also ensure that all constructed points satisfy a given predicate `P`. -/
lemma exists_seq_of_forall_finset_exists' {α : Type*} (P : α → Prop) (r : α → α → Prop)
[is_symm α r]
(h : ∀ (s : finset α), (∀ x ∈ s, P x) → ∃ y, P y ∧ (∀ x ∈ s, r x y)) :
∃ (f : ℕ → α), (∀ n, P (f n)) ∧ (∀ m n, m ≠ n → r (f m) (f n)) :=
begin
rcases exists_seq_of_forall_finset_exists P r h with ⟨f, hf, hf'⟩,
refine ⟨f, hf, λ m n hmn, _⟩,
rcases lt_trichotomy m n with h|rfl|h,
{ exact hf' m n h },
{ exact (hmn rfl).elim },
{ apply symm,
exact hf' n m h }
end
|
eb5d9c63bc1d33fb0eef395da18cbfd929c061ad | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /src/Std/Data/HashSet.lean | e050c309ca0793f4081e4443854ad7ca5c72230e | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,072 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
namespace Std
universes u v w
def HashSetBucket (α : Type u) :=
{ b : Array (List α) // b.size > 0 }
def HashSetBucket.update {α : Type u} (data : HashSetBucket α) (i : USize) (d : List α) (h : i.toNat < data.val.size) : HashSetBucket α :=
⟨ data.val.uset i d h,
by erw [Array.sizeSetEq]; exact data.property ⟩
structure HashSetImp (α : Type u) where
size : Nat
buckets : HashSetBucket α
def mkHashSetImp {α : Type u} (nbuckets := 8) : HashSetImp α :=
let n := if nbuckets = 0 then 8 else nbuckets
{ size := 0,
buckets :=
⟨ mkArray n [],
by rw [Array.sizeMkArrayEq]; cases nbuckets; decide!; apply Nat.zeroLtSucc ⟩ }
namespace HashSetImp
variable {α : Type u}
def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } :=
⟨u % n, USize.modnLt _ h⟩
@[inline] def reinsertAux (hashFn : α → USize) (data : HashSetBucket α) (a : α) : HashSetBucket α :=
let ⟨i, h⟩ := mkIdx data.property (hashFn a)
data.update i (a :: data.val.uget i h) h
@[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashSetBucket α) (d : δ) (f : δ → α → m δ) : m δ :=
data.val.foldlM (init := d) fun d as => as.foldlM f d
@[inline] def foldBuckets {δ : Type w} (data : HashSetBucket α) (d : δ) (f : δ → α → δ) : δ :=
Id.run $ foldBucketsM data d f
@[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (d : δ) (h : HashSetImp α) : m δ :=
foldBucketsM h.buckets d f
@[inline] def fold {δ : Type w} (f : δ → α → δ) (d : δ) (m : HashSetImp α) : δ :=
foldBuckets m.buckets d f
def find? [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : Option α :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a)
(buckets.val.uget i h).find? (fun a' => a == a')
def contains [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : Bool :=
match m with
| ⟨_, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a)
(buckets.val.uget i h).contains a
-- TODO: remove `partial` by using well-founded recursion
partial def moveEntries [Hashable α] (i : Nat) (source : Array (List α)) (target : HashSetBucket α) : HashSetBucket α :=
if h : i < source.size then
let idx : Fin source.size := ⟨i, h⟩
let es : List α := source.get idx
-- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl
let source := source.set idx []
let target := es.foldl (reinsertAux hash) target
moveEntries (i+1) source target
else target
def expand [Hashable α] (size : Nat) (buckets : HashSetBucket α) : HashSetImp α :=
let nbuckets := buckets.val.size * 2
have nbuckets > 0 from Nat.mulPos buckets.property (decide! : 2 > 0)
let new_buckets : HashSetBucket α := ⟨mkArray nbuckets [], by rw [Array.sizeMkArrayEq]; assumption⟩
{ size := size,
buckets := moveEntries 0 buckets.val new_buckets }
def insert [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α :=
match m with
| ⟨size, buckets⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a)
let bkt := buckets.val.uget i h
if bkt.contains a
then ⟨size, buckets.update i (bkt.replace a a) h⟩
else
let size' := size + 1
let buckets' := buckets.update i (a :: bkt) h
if size' ≤ buckets.val.size
then { size := size', buckets := buckets' }
else expand size' buckets'
def erase [BEq α] [Hashable α] (m : HashSetImp α) (a : α) : HashSetImp α :=
match m with
| ⟨ size, buckets ⟩ =>
let ⟨i, h⟩ := mkIdx buckets.property (hash a)
let bkt := buckets.val.uget i h
if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩
else m
inductive WellFormed [BEq α] [Hashable α] : HashSetImp α → Prop where
| mkWff : ∀ n, WellFormed (mkHashSetImp n)
| insertWff : ∀ m a, WellFormed m → WellFormed (insert m a)
| eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a)
end HashSetImp
def HashSet (α : Type u) [BEq α] [Hashable α] :=
{ m : HashSetImp α // m.WellFormed }
open HashSetImp
def mkHashSet {α : Type u} [BEq α] [Hashable α] (nbuckets := 8) : HashSet α :=
⟨ mkHashSetImp nbuckets, WellFormed.mkWff nbuckets ⟩
namespace HashSet
variable {α : Type u} [BEq α] [Hashable α]
instance : Inhabited (HashSet α) where
default := mkHashSet
instance : EmptyCollection (HashSet α) := ⟨mkHashSet⟩
@[inline] def insert (m : HashSet α) (a : α) : HashSet α :=
match m with
| ⟨ m, hw ⟩ => ⟨ m.insert a, WellFormed.insertWff m a hw ⟩
@[inline] def erase (m : HashSet α) (a : α) : HashSet α :=
match m with
| ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩
@[inline] def find? (m : HashSet α) (a : α) : Option α :=
match m with
| ⟨ m, _ ⟩ => m.find? a
@[inline] def contains (m : HashSet α) (a : α) : Bool :=
match m with
| ⟨ m, _ ⟩ => m.contains a
@[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → m δ) (init : δ) (h : HashSet α) : m δ :=
match h with
| ⟨ h, _ ⟩ => h.foldM f init
@[inline] def fold {δ : Type w} (f : δ → α → δ) (init : δ) (m : HashSet α) : δ :=
match m with
| ⟨ m, _ ⟩ => m.fold f init
@[inline] def size (m : HashSet α) : Nat :=
match m with
| ⟨ {size := sz, ..}, _ ⟩ => sz
@[inline] def isEmpty (m : HashSet α) : Bool :=
m.size = 0
@[inline] def empty : HashSet α :=
mkHashSet
def toList (m : HashSet α) : List α :=
m.fold (init := []) fun r a => a::r
def toArray (m : HashSet α) : Array α :=
m.fold (init := #[]) fun r a => r.push a
def numBuckets (m : HashSet α) : Nat :=
m.val.buckets.val.size
end HashSet
end Std
|
73e5d77a0f8a1cfa09bd274ca46c84969029e0f5 | bb31430994044506fa42fd667e2d556327e18dfe | /src/data/zmod/defs.lean | 3a91f1a2e5f378e2e51f1afe0a4e2a2e6786646f | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 6,649 | lean | /-
Copyright (c) 2022 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez
-/
import algebra.ne_zero
import data.nat.modeq
import data.fintype.lattice
/-!
# Definition of `zmod n` + basic results.
This file provides the basic details of `zmod n`, including its commutative ring structure.
## Implementation details
This used to be inlined into data/zmod/basic.lean. This file imports `char_p/basic`, which is an
issue; all `char_p` instances create an `algebra (zmod p) R` instance; however, this instance may
not be definitionally equal to other `algebra` instances (for example, `galois_field` also has an
`algebra` instance as it is defined as a `splitting_field`). The way to fix this is to use the
forgetful inheritance pattern, and make `char_p` carry the data of what the `smul` should be (so
for example, the `smul` on the `galois_field` `char_p` instance should be equal to the `smul` from
its `splitting_field` structure); there is only one possible `zmod p` algebra for any `p`, so this
is not an issue mathematically. For this to be possible, however, we need `char_p/basic` to be
able to import some part of `zmod`.
-/
namespace fin
/-!
## Ring structure on `fin n`
We define a commutative ring structure on `fin n`, but we do not register it as instance.
Afterwords, when we define `zmod n` in terms of `fin n`, we use these definitions
to register the ring structure on `zmod n` as type class instance.
-/
open nat.modeq int
/-- Multiplicative commutative semigroup structure on `fin n`. -/
instance (n : ℕ) : comm_semigroup (fin n) :=
{ mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc ((a * b) % n * c) ≡ a * b * c [MOD n] : (nat.mod_modeq _ _).mul_right _
... ≡ a * (b * c) [MOD n] : by rw mul_assoc
... ≡ a * (b * c % n) [MOD n] : (nat.mod_modeq _ _).symm.mul_left _),
mul_comm := fin.mul_comm,
..fin.has_mul }
private lemma left_distrib_aux (n : ℕ) : ∀ a b c : fin n, a * (b + c) = a * b + a * c :=
λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq
(calc a * ((b + c) % n) ≡ a * (b + c) [MOD n] : (nat.mod_modeq _ _).mul_left _
... ≡ a * b + a * c [MOD n] : by rw mul_add
... ≡ (a * b) % n + (a * c) % n [MOD n] :
(nat.mod_modeq _ _).symm.add (nat.mod_modeq _ _).symm)
/-- Commutative ring structure on `fin n`. -/
instance (n : ℕ) [ne_zero n] : comm_ring (fin n) :=
{ one_mul := fin.one_mul,
mul_one := fin.mul_one,
left_distrib := left_distrib_aux n,
right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl,
..fin.add_monoid_with_one,
..fin.add_comm_group n,
..fin.comm_semigroup n }
end fin
/-- The integers modulo `n : ℕ`. -/
def zmod : ℕ → Type
| 0 := ℤ
| (n+1) := fin (n+1)
instance zmod.decidable_eq : Π (n : ℕ), decidable_eq (zmod n)
| 0 := int.decidable_eq
| (n+1) := fin.decidable_eq _
instance zmod.has_repr : Π (n : ℕ), has_repr (zmod n)
| 0 := int.has_repr
| (n+1) := fin.has_repr _
namespace zmod
instance fintype : Π (n : ℕ) [ne_zero n], fintype (zmod n)
| 0 h := by exactI (ne_zero.ne 0 rfl).elim
| (n+1) _ := fin.fintype (n+1)
instance infinite : infinite (zmod 0) :=
int.infinite
@[simp] lemma card (n : ℕ) [fintype (zmod n)] : fintype.card (zmod n) = n :=
begin
casesI n,
{ exact (not_finite (zmod 0)).elim },
{ convert fintype.card_fin (n+1) }
end
/- We define each field by cases, to ensure that the eta-expanded `zmod.comm_ring` is defeq to the
original, this helps avoid diamonds with instances coming from classes extending `comm_ring` such as
field. -/
instance comm_ring (n : ℕ) : comm_ring (zmod n) :=
{ add := nat.cases_on n ((@has_add.add) int _) (λ n, @has_add.add (fin n.succ) _),
add_assoc := nat.cases_on n (@add_assoc int _) (λ n, @add_assoc (fin n.succ) _),
zero := nat.cases_on n (0 : int) (λ n, (0 : fin n.succ)),
zero_add := nat.cases_on n (@zero_add int _) (λ n, @zero_add (fin n.succ) _),
add_zero := nat.cases_on n (@add_zero int _) (λ n, @add_zero (fin n.succ) _),
neg := nat.cases_on n ((@has_neg.neg) int _) (λ n, @has_neg.neg (fin n.succ) _),
sub := nat.cases_on n ((@has_sub.sub) int _) (λ n, @has_sub.sub (fin n.succ) _),
sub_eq_add_neg := nat.cases_on n (@sub_eq_add_neg int _) (λ n, @sub_eq_add_neg (fin n.succ) _),
zsmul := nat.cases_on n ((@comm_ring.zsmul) int _) (λ n, @comm_ring.zsmul (fin n.succ) _),
zsmul_zero' := nat.cases_on n (@comm_ring.zsmul_zero' int _)
(λ n, @comm_ring.zsmul_zero' (fin n.succ) _),
zsmul_succ' := nat.cases_on n (@comm_ring.zsmul_succ' int _)
(λ n, @comm_ring.zsmul_succ' (fin n.succ) _),
zsmul_neg' := nat.cases_on n (@comm_ring.zsmul_neg' int _)
(λ n, @comm_ring.zsmul_neg' (fin n.succ) _),
nsmul := nat.cases_on n ((@comm_ring.nsmul) int _) (λ n, @comm_ring.nsmul (fin n.succ) _),
nsmul_zero' := nat.cases_on n (@comm_ring.nsmul_zero' int _)
(λ n, @comm_ring.nsmul_zero' (fin n.succ) _),
nsmul_succ' := nat.cases_on n (@comm_ring.nsmul_succ' int _)
(λ n, @comm_ring.nsmul_succ' (fin n.succ) _),
add_left_neg := by { cases n, exacts [@add_left_neg int _, @add_left_neg (fin n.succ) _] },
add_comm := nat.cases_on n (@add_comm int _) (λ n, @add_comm (fin n.succ) _),
mul := nat.cases_on n ((@has_mul.mul) int _) (λ n, @has_mul.mul (fin n.succ) _),
mul_assoc := nat.cases_on n (@mul_assoc int _) (λ n, @mul_assoc (fin n.succ) _),
one := nat.cases_on n (1 : int) (λ n, (1 : fin n.succ)),
one_mul := nat.cases_on n (@one_mul int _) (λ n, @one_mul (fin n.succ) _),
mul_one := nat.cases_on n (@mul_one int _) (λ n, @mul_one (fin n.succ) _),
nat_cast := nat.cases_on n (coe : ℕ → ℤ) (λ n, (coe : ℕ → fin n.succ)),
nat_cast_zero := nat.cases_on n (@nat.cast_zero int _) (λ n, @nat.cast_zero (fin n.succ) _),
nat_cast_succ := nat.cases_on n (@nat.cast_succ int _) (λ n, @nat.cast_succ (fin n.succ) _),
int_cast := nat.cases_on n (coe : ℤ → ℤ) (λ n, (coe : ℤ → fin n.succ)),
int_cast_of_nat := nat.cases_on n (@int.cast_of_nat int _) (λ n, @int.cast_of_nat (fin n.succ) _),
int_cast_neg_succ_of_nat := nat.cases_on n (@int.cast_neg_succ_of_nat int _)
(λ n, @int.cast_neg_succ_of_nat (fin n.succ) _),
left_distrib := nat.cases_on n (@left_distrib int _ _ _) (λ n, @left_distrib (fin n.succ) _ _ _),
right_distrib :=
nat.cases_on n (@right_distrib int _ _ _) (λ n, @right_distrib (fin n.succ) _ _ _),
mul_comm := nat.cases_on n (@mul_comm int _) (λ n, @mul_comm (fin n.succ) _) }
instance inhabited (n : ℕ) : inhabited (zmod n) := ⟨0⟩
end zmod
|
38fd43ff2418c30e441e161a6769068144b03545 | 4a092885406df4e441e9bb9065d9405dacb94cd8 | /src/for_mathlib/with_zero.lean | bdb39002f03d6be3518b083af0093d85e0c51736 | [
"Apache-2.0"
] | permissive | semorrison/lean-perfectoid-spaces | 78c1572cedbfae9c3e460d8aaf91de38616904d8 | bb4311dff45791170bcb1b6a983e2591bee88a19 | refs/heads/master | 1,588,841,765,494 | 1,554,805,620,000 | 1,554,805,620,000 | 180,353,546 | 0 | 1 | null | 1,554,809,880,000 | 1,554,809,880,000 | null | UTF-8 | Lean | false | false | 5,710 | lean | import data.equiv.basic
import group_theory.subgroup
import for_mathlib.option_inj
universes u v
-- this should be in order.bounded_lattice with with_bot.partial_order
instance {α : Type*} [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];
split; try {exact id}; 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⟩,
}
namespace with_zero
instance {α : Type*} [preorder α] : preorder (with_zero α) :=
show preorder (with_bot α), by apply_instance
variables {α : Type u} {β : Type v}
@[simp] theorem zero_le [preorder α] {x : with_zero α} : 0 ≤ x :=
begin
intros y hy, cases hy
end
@[simp] theorem none_le [preorder α] {x : with_zero α} :
@has_le.le (with_zero α) _ none x := zero_le
@[simp] theorem none_lt_some [preorder α] {a : α} :
(0 : with_zero α) < some a :=
begin
use a, use rfl,
intros y hy, cases hy,
end
@[simp] theorem zero_lt_some [preorder α] {a : α} :
@has_lt.lt (with_zero α) _ 0 (some a : with_zero α) := none_lt_some
@[simp] theorem not_some_le_zero [preorder α] {x : α} :
¬ @has_le.le (with_zero α) _ (some x) 0 :=
λ h, by rcases h x rfl with ⟨y, hy, h⟩; cases hy
@[simp] theorem not_some_le_none [preorder α] {x : α} :
¬ @has_le.le (with_zero α) _ (some x) none := not_some_le_zero
@[simp] theorem not_some_eq_zero [preorder α] {x : α} :
¬ (some x : with_zero α) = (0 : with_zero α) := by apply option.no_confusion
@[simp] theorem not_some_eq_none [preorder α] {x : α} :
¬ (some x : with_zero α) = none := by apply option.no_confusion
theorem some_le_some_of_le [preorder α] {x y : α} (h : x ≤ y) :
(x : with_zero α) ≤ y :=
λ a ha, ⟨y, rfl, by cases ha; assumption⟩
@[simp] theorem some_le_some' [preorder α] {x y : α} : (x : with_zero α) ≤ (y : with_zero α) ↔ x ≤ y :=
⟨λ h, by rcases (h x rfl) with ⟨z, ⟨h2⟩, h3⟩; exact h3, some_le_some_of_le⟩
@[simp] theorem some_le_some [preorder α] {x y : α} :
@has_le.le (with_zero α) _ (some x) (some y) ↔ x ≤ y := some_le_some'
@[simp] theorem le_zero_iff_eq_zero [partial_order α] {x : with_zero α} : x ≤ 0 ↔ x = 0 :=
by cases x; simp; try {refl}; {intro h, exact option.no_confusion h}
def map (f : α → β) : with_zero α → with_zero β := option.map f
@[simp] lemma map_zero {f : α → β} : map f 0 = 0 := option.map_none'
@[simp] lemma map_none {f : α → β} : map f none = 0 := option.map_none'
@[simp] lemma map_some {f : α → β} {a : α} : map f (some a) = some (f a) := option.map_some'
lemma map_id {α : Type*} : map (id : α → α) = id := option.map_id
lemma map_comp {α β γ : Type*} (f : α → β) (g : β → γ) (r : with_zero α) :
with_zero.map (g ∘ f) r = (with_zero.map g) ((with_zero.map f) r) :=
by cases r; refl
lemma map_eq_zero_iff {f : α → β} {a : with_zero α} : map f a = 0 ↔ a = 0 :=
begin
split; intro h,
{ cases a, {refl}, rw map_some at h, revert h, exact dec_trivial },
{ rw h, exact map_zero }
end
theorem map_inj {f : α → β} (H : function.injective f) :
function.injective (map f) := option.map_inj H
theorem map_monotone [preorder α] [preorder β] {f : α → β} (H : monotone f) :
monotone (map f) :=
begin
intros x y,
cases x; cases y,
{simp},
{simp},
{simp},
{simpa using @H _ _}
end
theorem map_strict_mono [linear_order α] [partial_order β] {f : α → β}
(H : ∀ a b, a < b → f a < f b) :
∀ a b, a < b → (map f) a < (map f) b :=
begin
intros x y,
cases x; cases y,
{simp},
{simp},
{simp},
{simpa using H _ _ }
end
theorem map_le [preorder α] [preorder β] {f : α → β}
(H : ∀ a b : α, a ≤ b ↔ f a ≤ f b) (x y : with_zero α) :
x ≤ y ↔ map f x ≤ map f y :=
begin
cases x; cases y,
{ convert iff.refl true; rw eq_true; show none ≤ _; simp},
{ convert iff.refl true; simp},
{ convert iff.refl false; simp},
{ simp [H x y]}
end
lemma coe_min (x y : α) [decidable_linear_order α]: ((min x y : α) : with_zero α) = min (x: with_zero α) (y : with_zero α) :=
begin
by_cases h: x ≤ y,
{ simp [min_eq_left, h] },
{ replace h : y ≤ x := le_of_not_le h,
simp [min_eq_right, h] }
end
section group
variables [group α]
lemma mul_left_cancel : ∀ {x : with_zero α} (h : x ≠ 0) {y z : with_zero α} ,
x * y = x * z → y = z
| 0 h := false.elim $ h rfl
| (a : α) h := λ y z h2, begin
have h3 : (a⁻¹ : with_zero α) * (a * y) = a⁻¹ * (a * z) := by rw h2,
rwa [←mul_assoc, ←mul_assoc, with_zero.mul_left_inv _ h, one_mul, one_mul] at h3,
end
lemma mul_right_cancel : ∀ {x : with_zero α} (h : x ≠ 0) {y z : with_zero α} ,
y * x = z * x → y = z
| 0 h := false.elim $ h rfl
| (a : α) h := λ y z h2, begin
have h3 : (y * a) * a⁻¹ = (z * a) * a⁻¹ := by rw h2,
rwa [mul_assoc, mul_assoc, with_zero.mul_right_inv _ h, mul_one, mul_one] at h3,
end
lemma mul_inv_eq_of_eq_mul : ∀ {x : with_zero α} (h : x ≠ 0) {y z : with_zero α} ,
y = z * x → y * x⁻¹ = z
| 0 h := false.elim $ h rfl
| (x : α) h := λ y z h2, begin
apply with_zero.mul_right_cancel h,
rwa [mul_assoc, with_zero.mul_left_inv _ h, mul_one]
end
lemma eq_mul_inv_of_mul_eq {x : with_zero α} (h : x ≠ 0) {y z : with_zero α}
(h2 : z * x = y) : z = y * x⁻¹ := eq.symm $ mul_inv_eq_of_eq_mul h h2.symm
end group
end with_zero
|
8318418bbccb97d6971e7f8974bfe254d4428c96 | b70447c014d9e71cf619ebc9f539b262c19c2e0b | /hott/homotopy/connectedness.hlean | f25d4a71bd321a65e5dd603fecede199a0916e14 | [
"Apache-2.0"
] | permissive | ia0/lean2 | c20d8da69657f94b1d161f9590a4c635f8dc87f3 | d86284da630acb78fa5dc3b0b106153c50ffccd0 | refs/heads/master | 1,611,399,322,751 | 1,495,751,007,000 | 1,495,751,007,000 | 93,104,167 | 0 | 0 | null | 1,496,355,488,000 | 1,496,355,487,000 | null | UTF-8 | Lean | false | false | 16,772 | hlean | /-
Copyright (c) 2015 Ulrik Buchholtz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ulrik Buchholtz, Floris van Doorn
Connectedness of types and functions
-/
import types.trunc types.arrow_2 types.lift
open eq is_trunc is_equiv nat equiv trunc function fiber funext pi pointed
definition is_conn [reducible] (n : ℕ₋₂) (A : Type) : Type :=
is_contr (trunc n A)
definition is_conn_fun [reducible] (n : ℕ₋₂) {A B : Type} (f : A → B) : Type :=
Πb : B, is_conn n (fiber f b)
definition is_conn_inf [reducible] (A : Type) : Type := Πn, is_conn n A
definition is_conn_fun_inf [reducible] {A B : Type} (f : A → B) : Type := Πn, is_conn_fun n f
namespace is_conn
definition is_conn_equiv_closed (n : ℕ₋₂) {A B : Type}
: A ≃ B → is_conn n A → is_conn n B :=
begin
intros H C,
fapply @is_contr_equiv_closed (trunc n A) _,
apply trunc_equiv_trunc,
assumption
end
theorem is_conn_of_le (A : Type) {n k : ℕ₋₂} (H : n ≤ k) [is_conn k A] : is_conn n A :=
begin
apply is_contr_equiv_closed,
apply trunc_trunc_equiv_left _ H
end
theorem is_conn_fun_of_le {A B : Type} (f : A → B) {n k : ℕ₋₂} (H : n ≤ k)
[is_conn_fun k f] : is_conn_fun n f :=
λb, is_conn_of_le _ H
definition is_conn_of_is_conn_succ (n : ℕ₋₂) (A : Type) [is_conn (n.+1) A] : is_conn n A :=
is_trunc_trunc_of_le A -2 (trunc_index.self_le_succ n)
namespace is_conn_fun
section
parameters (n : ℕ₋₂) {A B : Type} {h : A → B}
(H : is_conn_fun n h) (P : B → Type) [Πb, is_trunc n (P b)]
private definition rec.helper : (Πa : A, P (h a)) → Πb : B, trunc n (fiber h b) → P b :=
λt b, trunc.rec (λx, point_eq x ▸ t (point x))
private definition rec.g : (Πa : A, P (h a)) → (Πb : B, P b) :=
λt b, rec.helper t b (@center (trunc n (fiber h b)) (H b))
-- induction principle for n-connected maps (Lemma 7.5.7)
protected definition rec : is_equiv (λs : Πb : B, P b, λa : A, s (h a)) :=
adjointify (λs a, s (h a)) rec.g
begin
intro t, apply eq_of_homotopy, intro a, unfold rec.g, unfold rec.helper,
rewrite [@center_eq _ (H (h a)) (tr (fiber.mk a idp))],
end
begin
intro k, apply eq_of_homotopy, intro b, unfold rec.g,
generalize (@center _ (H b)), apply trunc.rec, apply fiber.rec,
intros a p, induction p, reflexivity
end
protected definition elim : (Πa : A, P (h a)) → (Πb : B, P b) :=
@is_equiv.inv _ _ (λs a, s (h a)) rec
protected definition elim_β : Πf : (Πa : A, P (h a)), Πa : A, elim f (h a) = f a :=
λf, apd10 (@is_equiv.right_inv _ _ (λs a, s (h a)) rec f)
end
section
parameters (n k : ℕ₋₂) {A B : Type} {f : A → B}
(H : is_conn_fun n f) (P : B → Type) [HP : Πb, is_trunc (n +2+ k) (P b)]
include H HP
-- Lemma 8.6.1
proposition elim_general : is_trunc_fun k (pi_functor_left f P) :=
begin
revert P HP,
induction k with k IH: intro P HP t,
{ apply is_contr_fiber_of_is_equiv, apply is_conn_fun.rec, exact H, exact HP},
{ apply is_trunc_succ_intro,
intros x y, cases x with g p, cases y with h q,
have e : fiber (λr : g ~ h, (λa, r (f a))) (apd10 (p ⬝ q⁻¹))
≃ (fiber.mk g p = fiber.mk h q
:> fiber (λs : (Πb, P b), (λa, s (f a))) t),
begin
apply equiv.trans !fiber.sigma_char,
have e' : Πr : g ~ h,
((λa, r (f a)) = apd10 (p ⬝ q⁻¹))
≃ (ap (λv, (λa, v (f a))) (eq_of_homotopy r) ⬝ q = p),
begin
intro r,
refine equiv.trans _ (eq_con_inv_equiv_con_eq q p
(ap (λv a, v (f a)) (eq_of_homotopy r))),
rewrite [-(ap (λv a, v (f a)) (apd10_eq_of_homotopy r))],
rewrite [-(apd10_ap_precompose_dependent f (eq_of_homotopy r))],
apply equiv.symm,
apply eq_equiv_fn_eq (@apd10 A (λa, P (f a)) (λa, g (f a)) (λa, h (f a)))
end,
apply equiv.trans (sigma.sigma_equiv_sigma_right e'), clear e',
apply equiv.trans (equiv.symm (sigma.sigma_equiv_sigma_left
eq_equiv_homotopy)),
apply equiv.symm, apply equiv.trans !fiber_eq_equiv,
apply sigma.sigma_equiv_sigma_right, intro r,
apply eq_equiv_eq_symm
end,
apply @is_trunc_equiv_closed _ _ k e, clear e,
apply IH (λb : B, (g b = h b)) (λb, @is_trunc_eq (P b) (n +2+ k) (HP b) (g b) (h b))}
end
end
section
universe variables u v
parameters (n : ℕ₋₂) {A : Type.{u}} {B : Type.{v}} {h : A → B}
parameter sec : ΠP : B → trunctype.{max u v} n,
is_retraction (λs : (Πb : B, P b), λ a, s (h a))
private definition s := sec (λb, trunctype.mk' n (trunc n (fiber h b)))
include sec
-- the other half of Lemma 7.5.7
definition intro : is_conn_fun n h :=
begin
intro b,
apply is_contr.mk (@is_retraction.sect _ _ _ s (λa, tr (fiber.mk a idp)) b),
esimp, apply trunc.rec, apply fiber.rec, intros a p,
apply transport
(λz : (Σy, h a = y), @sect _ _ _ s (λa, tr (mk a idp)) (sigma.pr1 z) =
tr (fiber.mk a (sigma.pr2 z)))
(@center_eq _ (is_contr_sigma_eq (h a)) (sigma.mk b p)),
exact apd10 (@right_inverse _ _ _ s (λa, tr (fiber.mk a idp))) a
end
end
end is_conn_fun
-- Connectedness is related to maps to and from the unit type, first to
section
parameters (n : ℕ₋₂) (A : Type)
definition is_conn_of_map_to_unit
: is_conn_fun n (const A unit.star) → is_conn n A :=
begin
intro H, unfold is_conn_fun at H,
exact is_conn_equiv_closed n (fiber.fiber_star_equiv A) _,
end
definition is_conn_fun_to_unit_of_is_conn [H : is_conn n A] :
is_conn_fun n (const A unit.star) :=
begin
intro u, induction u,
exact is_conn_equiv_closed n (fiber.fiber_star_equiv A)⁻¹ᵉ _,
end
-- now maps from unit
definition is_conn_of_map_from_unit (a₀ : A) (H : is_conn_fun n (const unit a₀))
: is_conn n .+1 A :=
is_contr.mk (tr a₀)
begin
apply trunc.rec, intro a,
exact trunc.elim (λz : fiber (const unit a₀) a, ap tr (point_eq z))
(@center _ (H a))
end
definition is_conn_fun_from_unit (a₀ : A) [H : is_conn n .+1 A]
: is_conn_fun n (const unit a₀) :=
begin
intro a,
apply is_conn_equiv_closed n (equiv.symm (fiber_const_equiv A a₀ a)),
apply @is_contr_equiv_closed _ _ (tr_eq_tr_equiv n a₀ a),
end
end
-- as special case we get elimination principles for pointed connected types
namespace is_conn
open pointed unit
section
parameters (n : ℕ₋₂) {A : Type*}
[H : is_conn n .+1 A] (P : A → Type) [Πa, is_trunc n (P a)]
include H
protected definition rec : is_equiv (λs : Πa : A, P a, s (Point A)) :=
@is_equiv_compose
(Πa : A, P a) (unit → P (Point A)) (P (Point A))
(λf, f unit.star) (λs x, s (Point A))
(is_conn_fun.rec n (is_conn_fun_from_unit n A (Point A)) P)
(to_is_equiv (arrow_unit_left (P (Point A))))
protected definition elim : P (Point A) → (Πa : A, P a) :=
@is_equiv.inv _ _ (λs, s (Point A)) rec
protected definition elim_β (p : P (Point A)) : elim p (Point A) = p :=
@is_equiv.right_inv _ _ (λs, s (Point A)) rec p
end
section
parameters (n k : ℕ₋₂) {A : Type*}
[H : is_conn n .+1 A] (P : A → Type) [Πa, is_trunc (n +2+ k) (P a)]
include H
proposition elim_general (p : P (Point A))
: is_trunc k (fiber (λs : (Πa : A, P a), s (Point A)) p) :=
@is_trunc_equiv_closed
(fiber (λs x, s (Point A)) (λx, p))
(fiber (λs, s (Point A)) p)
k
(equiv.symm (fiber.equiv_postcompose _ (arrow_unit_left (P (Point A))) _))
(is_conn_fun.elim_general n k (is_conn_fun_from_unit n A (Point A)) P (λx, p))
end
end is_conn
-- Lemma 7.5.2
definition minus_one_conn_of_surjective {A B : Type} (f : A → B)
: is_surjective f → is_conn_fun -1 f :=
begin
intro H, intro b,
exact @is_contr_of_inhabited_prop (∥fiber f b∥) (is_trunc_trunc -1 (fiber f b)) (H b),
end
definition is_surjection_of_minus_one_conn {A B : Type} (f : A → B)
: is_conn_fun -1 f → is_surjective f :=
begin
intro H, intro b,
exact @center (∥fiber f b∥) (H b),
end
definition merely_of_minus_one_conn {A : Type} : is_conn -1 A → ∥A∥ :=
λH, @center (∥A∥) H
definition minus_one_conn_of_merely {A : Type} : ∥A∥ → is_conn -1 A :=
@is_contr_of_inhabited_prop (∥A∥) (is_trunc_trunc -1 A)
section
open arrow
variables {f g : arrow}
-- Lemma 7.5.4
definition retract_of_conn_is_conn [instance] (r : arrow_hom f g) [H : is_retraction r]
(n : ℕ₋₂) [K : is_conn_fun n f] : is_conn_fun n g :=
begin
intro b, unfold is_conn,
apply is_contr_retract (trunc_functor n (retraction_on_fiber r b)),
exact K (on_cod (arrow.is_retraction.sect r) b)
end
end
-- Corollary 7.5.5
definition is_conn_homotopy (n : ℕ₋₂) {A B : Type} {f g : A → B}
(p : f ~ g) (H : is_conn_fun n f) : is_conn_fun n g :=
@retract_of_conn_is_conn _ _
(arrow.arrow_hom_of_homotopy p) (arrow.is_retraction_arrow_hom_of_homotopy p) n H
-- all types are -2-connected
definition is_conn_minus_two (A : Type) : is_conn -2 A :=
_
-- merely inhabited types are -1-connected
definition is_conn_minus_one (A : Type) (a : ∥ A ∥) : is_conn -1 A :=
is_contr.mk a (is_prop.elim _)
definition is_conn_trunc [instance] (A : Type) (n k : ℕ₋₂) [H : is_conn n A]
: is_conn n (trunc k A) :=
begin
apply is_trunc_equiv_closed, apply trunc_trunc_equiv_trunc_trunc
end
definition is_conn_eq [instance] (n : ℕ₋₂) {A : Type} (a a' : A) [is_conn (n.+1) A] :
is_conn n (a = a') :=
begin
apply is_trunc_equiv_closed, apply tr_eq_tr_equiv,
end
definition is_conn_loop [instance] (n : ℕ₋₂) (A : Type*) [is_conn (n.+1) A] : is_conn n (Ω A) :=
!is_conn_eq
open pointed
definition is_conn_ptrunc [instance] (A : Type*) (n k : ℕ₋₂) [H : is_conn n A]
: is_conn n (ptrunc k A) :=
is_conn_trunc A n k
-- the following trivial cases are solved by type class inference
definition is_conn_of_is_contr (k : ℕ₋₂) (A : Type) [is_contr A] : is_conn k A := _
definition is_conn_fun_of_is_equiv (k : ℕ₋₂) {A B : Type} (f : A → B) [is_equiv f] :
is_conn_fun k f :=
_
-- Lemma 7.5.14
theorem is_equiv_trunc_functor_of_is_conn_fun [instance] {A B : Type} (n : ℕ₋₂) (f : A → B)
[H : is_conn_fun n f] : is_equiv (trunc_functor n f) :=
begin
fapply adjointify,
{ intro b, induction b with b, exact trunc_functor n point (center (trunc n (fiber f b)))},
{ intro b, induction b with b, esimp, generalize center (trunc n (fiber f b)), intro v,
induction v with v, induction v with a p, esimp, exact ap tr p},
{ intro a, induction a with a, esimp, rewrite [center_eq (tr (fiber.mk a idp))]}
end
theorem trunc_equiv_trunc_of_is_conn_fun {A B : Type} (n : ℕ₋₂) (f : A → B)
[H : is_conn_fun n f] : trunc n A ≃ trunc n B :=
equiv.mk (trunc_functor n f) (is_equiv_trunc_functor_of_is_conn_fun n f)
definition is_conn_fun_trunc_functor_of_le {n k : ℕ₋₂} {A B : Type} (f : A → B) (H : k ≤ n)
[H2 : is_conn_fun k f] : is_conn_fun k (trunc_functor n f) :=
begin
apply is_conn_fun.intro,
intro P, have Πb, is_trunc n (P b), from (λb, is_trunc_of_le _ H),
fconstructor,
{ intro f' b,
induction b with b,
refine is_conn_fun.elim k H2 _ _ b, intro a, exact f' (tr a)},
{ intro f', apply eq_of_homotopy, intro a,
induction a with a, esimp, rewrite [is_conn_fun.elim_β]}
end
definition is_conn_fun_trunc_functor_of_ge {n k : ℕ₋₂} {A B : Type} (f : A → B) (H : n ≤ k)
[H2 : is_conn_fun k f] : is_conn_fun k (trunc_functor n f) :=
begin
apply is_conn_fun_of_is_equiv,
apply is_equiv_trunc_functor_of_le f H
end
-- Exercise 7.18
definition is_conn_fun_trunc_functor {n k : ℕ₋₂} {A B : Type} (f : A → B)
[H2 : is_conn_fun k f] : is_conn_fun k (trunc_functor n f) :=
begin
eapply algebra.le_by_cases k n: intro H,
{ exact is_conn_fun_trunc_functor_of_le f H},
{ exact is_conn_fun_trunc_functor_of_ge f H}
end
open lift
definition is_conn_fun_lift_functor (n : ℕ₋₂) {A B : Type} (f : A → B) [is_conn_fun n f] :
is_conn_fun n (lift_functor f) :=
begin
intro b, cases b with b, apply is_trunc_equiv_closed_rev,
{ apply trunc_equiv_trunc, apply fiber_lift_functor}
end
open trunc_index
definition is_conn_fun_inf.mk_nat {A B : Type} {f : A → B} (H : Π(n : ℕ), is_conn_fun n f)
: is_conn_fun_inf f :=
begin
intro n,
cases n with n, { exact _},
cases n with n, { have -1 ≤ of_nat 0, from dec_star, apply is_conn_fun_of_le f this},
rewrite -of_nat_add_two, exact _
end
definition is_conn_inf.mk_nat {A : Type} (H : Π(n : ℕ), is_conn n A) : is_conn_inf A :=
begin
intro n,
cases n with n, { exact _},
cases n with n, { have -1 ≤ of_nat 0, from dec_star, apply is_conn_of_le A this},
rewrite -of_nat_add_two, exact _
end
end is_conn
/-
(bundled) connected types, possibly also truncated or with a point
The notation is n-Type*[k] for k-connected n-truncated pointed types, and you can remove
`n-`, `[k]` or `*` in any combination to remove some conditions
-/
structure conntype (n : ℕ₋₂) : Type :=
(carrier : Type)
(struct : is_conn n carrier)
notation `Type[`:95 n:0 `]`:0 := conntype n
attribute conntype.carrier [coercion]
attribute conntype.struct [instance] [priority 1300]
section
universe variable u
structure pconntype (n : ℕ₋₂) extends conntype.{u} n, pType.{u}
notation `Type*[`:95 n:0 `]`:0 := pconntype n
/-
There are multiple coercions from pconntype to Type. Type class inference doesn't recognize
that all of them are definitionally equal (for performance reasons). One instance is
automatically generated, and we manually add the missing instances.
-/
definition is_conn_pconntype [instance] {n : ℕ₋₂} (X : Type*[n]) : is_conn n X :=
conntype.struct X
structure truncconntype (n k : ℕ₋₂) extends trunctype.{u} n,
conntype.{u} k renaming struct→conn_struct
notation n `-Type[`:95 k:0 `]`:0 := truncconntype n k
definition is_conn_truncconntype [instance] {n k : ℕ₋₂} (X : n-Type[k]) :
is_conn k (truncconntype._trans_of_to_trunctype X) :=
conntype.struct X
definition is_trunc_truncconntype [instance] {n k : ℕ₋₂} (X : n-Type[k]) : is_trunc n X :=
trunctype.struct X
structure ptruncconntype (n k : ℕ₋₂) extends ptrunctype.{u} n,
pconntype.{u} k renaming struct→conn_struct
notation n `-Type*[`:95 k:0 `]`:0 := ptruncconntype n k
attribute ptruncconntype._trans_of_to_pconntype ptruncconntype._trans_of_to_ptrunctype
ptruncconntype._trans_of_to_pconntype_1 ptruncconntype._trans_of_to_ptrunctype_1
ptruncconntype._trans_of_to_pconntype_2 ptruncconntype._trans_of_to_ptrunctype_2
ptruncconntype.to_pconntype ptruncconntype.to_ptrunctype
truncconntype._trans_of_to_conntype truncconntype._trans_of_to_trunctype
truncconntype.to_conntype truncconntype.to_trunctype [unfold 3]
attribute pconntype._trans_of_to_conntype pconntype._trans_of_to_pType
pconntype.to_pType pconntype.to_conntype [unfold 2]
definition is_conn_ptruncconntype [instance] {n k : ℕ₋₂} (X : n-Type*[k]) :
is_conn k (ptruncconntype._trans_of_to_ptrunctype X) :=
conntype.struct X
definition is_trunc_ptruncconntype [instance] {n k : ℕ₋₂} (X : n-Type*[k]) :
is_trunc n (ptruncconntype._trans_of_to_pconntype X) :=
trunctype.struct X
definition ptruncconntype_eq {n k : ℕ₋₂} {X Y : n-Type*[k]} (p : X ≃* Y) : X = Y :=
begin
induction X with X Xt Xp Xc, induction Y with Y Yt Yp Yc,
note q := pType_eq_elim (eq_of_pequiv p),
cases q with r s, esimp at *, induction r,
exact ap0111 (ptruncconntype.mk X) !is_prop.elim (eq_of_pathover_idp s) !is_prop.elim
end
end
|
b9ac60a67ed6daf0f039a62aa421a44e13756e0a | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Elab/Macro.lean | 890db271f6186e765960bdc5702681d3249b167a | [
"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 | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 2,123 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.MacroArgUtil
namespace Lean.Elab.Command
open Lean.Syntax
open Lean.Parser.Term hiding macroArg
open Lean.Parser.Command
@[builtin_command_elab Lean.Parser.Command.macro] def elabMacro : CommandElab
| `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind
macro%$tk$[:$prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $args:macroArg* : $cat => $rhs) =>
-- exclude command prefix from synthetic position used for e.g. jumping to the macro definition
withRef (mkNullNode #[tk, rhs]) do
let prio ← liftMacroM <| evalOptPrio prio?
let (stxParts, patArgs) := (← args.mapM expandMacroArg).unzip
-- name
let name ← match name? with
| some name => pure name.getId
| none => liftMacroM <| mkNameFromParserSyntax cat.getId (mkNullNode stxParts)
/- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind.
So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/
let pat := ⟨mkNode ((← getCurrNamespace) ++ name) patArgs⟩
let stxCmd ← `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind
syntax$[:$prec?]?
(name := $(name?.getD (mkIdentFrom tk name (canonical := true))))
(priority := $(quote prio):num)
$[$stxParts]* : $cat)
let rhs := rhs.raw
let macroRulesCmd ← if rhs.getArgs.size == 1 then
-- `rhs` is a `term`
let rhs := ⟨rhs[0]⟩
`($[$doc?:docComment]? macro_rules | `($pat) => Functor.map (@TSyntax.raw $(quote cat.getId.eraseMacroScopes)) $rhs)
else
-- TODO(gabriel): remove after bootstrap
-- `rhs` is of the form `` `( $body ) ``
let rhsBody := ⟨rhs[1]⟩
`($[$doc?:docComment]? macro_rules | `($pat) => `($rhsBody))
elabCommand <| mkNullNode #[stxCmd, macroRulesCmd]
| _ => throwUnsupportedSyntax
end Lean.Elab.Command
|
1dbd5a86c10d2cfb020957c27cfddf4bb5c1b7d8 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/run/dunfold3.lean | a5d7e45e15efb8f41f621aa92426313e3cdc509c | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 893 | lean | open tactic
def g : nat → nat := λ x, x + 5
example (a b : nat) (p : nat → Prop) (h : p (g (nat.succ (nat.succ a)))) : p (g (a + 2)) :=
begin
unfold g at h,
do { h ← get_local `h >>= infer_type, t ← to_expr ```(p (nat.succ (nat.succ a) + 5)), guard (h = t) },
unfold has_add.add bit0 has_one.one nat.add,
unfold g,
do { t ← target, h ← get_local `h >>= infer_type, guard (t = h) },
assumption
end
meta def check_expected (p : pexpr) : tactic unit :=
do t ← target, ex ← to_expr p, guard (t = ex)
example (a b c : nat) (f : nat → nat → nat) (h : false) : f (g a) (g b) = (g c) :=
begin
unfold_occs g [2],
check_expected ```(f (g a) (b + 5) = g c),
contradiction
end
example (a b c : nat) (f : nat → nat → nat) (h : false) : f (g a) (g b) = (g c) :=
begin
unfold_occs g [1, 3],
check_expected ```(f (a + 5) (g b) = c + 5),
contradiction
end
|
58f48f5cdf00e69439c668a14385be54dfeadfdc | 367134ba5a65885e863bdc4507601606690974c1 | /src/analysis/seminorm.lean | b76716585e3d96cc7d9c7668ca327b7653ffd852 | [
"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 | 7,173 | lean | /-
Copyright (c) 2019 Jean Lo. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jean Lo
-/
import algebra.pointwise
import analysis.normed_space.basic
/-!
# Seminorms and Local Convexity
This file introduces the following notions, defined for a vector space
over a normed field:
- the subset properties of being `absorbent` and `balanced`,
- a `seminorm`, a function to the reals that is positive-semidefinite,
absolutely homogeneous, and subadditive.
We prove related properties.
## TODO
Define and show equivalence of two notions of local convexity for a
topological vector space over ℝ or ℂ: that it has a local base of
balanced convex absorbent sets, and that it carries the initial
topology induced by a family of seminorms.
## References
* [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966]
-/
/-!
### Subset Properties
Absorbent and balanced sets in a vector space over a
nondiscrete normed field.
-/
section
variables
(𝕜 : Type*) [nondiscrete_normed_field 𝕜]
{E : Type*} [add_comm_group E] [vector_space 𝕜 E]
open set normed_field
open_locale topological_space
/-- A set `A` absorbs another set `B` if `B` is contained in scaling
`A` by elements of sufficiently large norms. -/
def absorbs (A B : set E) := ∃ r > 0, ∀ a : 𝕜, r ≤ ∥a∥ → B ⊆ a • A
/-- A set is absorbent if it absorbs every singleton. -/
def absorbent (A : set E) := ∀ x, ∃ r > 0, ∀ a : 𝕜, r ≤ ∥a∥ → x ∈ a • A
/-- A set `A` is balanced if `a • A` is contained in `A` whenever `a`
has norm no greater than one. -/
def balanced (A : set E) := ∀ a : 𝕜, ∥a∥ ≤ 1 → a • A ⊆ A
variables {𝕜} (a : 𝕜) {A : set E}
/-- A balanced set absorbs itself. -/
lemma balanced.absorbs_self (hA : balanced 𝕜 A) : absorbs 𝕜 A A :=
begin
use [1, zero_lt_one],
intros a ha x hx,
rw mem_smul_set_iff_inv_smul_mem,
{ apply hA a⁻¹,
{ rw norm_inv, exact inv_le_one ha },
{ rw mem_smul_set, use [x, hx] }},
{ rw ←norm_pos_iff, calc 0 < 1 : zero_lt_one ... ≤ ∥a∥ : ha, }
end
/-!
Properties of balanced and absorbing sets in a topological vector space:
-/
variables [topological_space E] [topological_vector_space 𝕜 E]
/-- Every neighbourhood of the origin is absorbent. -/
lemma absorbent_nhds_zero (hA : A ∈ 𝓝 (0 : E)) : absorbent 𝕜 A :=
begin
intro x,
rcases mem_nhds_sets_iff.mp hA with ⟨w, hw₁, hw₂, hw₃⟩,
have hc : continuous (λ t : 𝕜, t • x), from continuous_id.smul continuous_const,
rcases metric.is_open_iff.mp (hw₂.preimage hc) 0 (by rwa [mem_preimage, zero_smul])
with ⟨r, hr₁, hr₂⟩,
have hr₃, from inv_pos.mpr (half_pos hr₁),
use [(r/2)⁻¹, hr₃],
intros a ha₁,
have ha₂ : 0 < ∥a∥, from calc 0 < _ : hr₃ ... ≤ _ : ha₁,
have ha₃ : a ⁻¹ • x ∈ w, begin
apply hr₂,
rw [metric.mem_ball, dist_eq_norm, sub_zero, norm_inv],
calc ∥a∥⁻¹ ≤ r/2 : (inv_le (half_pos hr₁) ha₂).mp ha₁
... < r : half_lt_self hr₁,
end,
rw [mem_smul_set_iff_inv_smul_mem (norm_pos_iff.mp ha₂)],
exact hw₁ ha₃,
end
/-- The union of `{0}` with the interior of a balanced set
is balanced. -/
lemma balanced_zero_union_interior (hA : balanced 𝕜 A) :
balanced 𝕜 ({(0 : E)} ∪ interior A) :=
begin
intros a ha, by_cases a = 0,
{ rw [h, zero_smul_set],
apply subset_union_left _,
exact union_nonempty.mpr (or.intro_left _ $ singleton_nonempty _) },
{ rw [←image_smul, image_union, union_subset_iff], split,
{ rw [image_singleton, smul_zero], exact subset_union_left _ _ },
{ apply subset_union_of_subset_right,
apply interior_maximal,
rw image_subset_iff,
calc _ ⊆ A : interior_subset
... ⊆ _ : by { rw ←image_subset_iff, exact hA _ ha},
exact is_open_map_smul_of_ne_zero h _ is_open_interior }},
end
/-- The interior of a balanced set is balanced if it contains the origin. -/
lemma balanced.interior (hA : balanced 𝕜 A) (h : (0 : E) ∈ interior A) :
balanced 𝕜 (interior A) :=
begin
rw ←singleton_subset_iff at h,
rw [←union_eq_self_of_subset_left h],
exact balanced_zero_union_interior hA,
end
/-- The closure of a balanced set is balanced. -/
lemma balanced.closure (hA : balanced 𝕜 A) : balanced 𝕜 (closure A) :=
begin
intros a ha,
calc _ ⊆ closure (a • A) :
by { simp_rw ←image_smul,
exact image_closure_subset_closure_image
(continuous_const.smul continuous_id) }
... ⊆ _ : closure_mono (hA _ ha),
end
end
/-!
### Seminorms
-/
/-- A seminorm on a vector space over a normed field is a function to
the reals that is positive semidefinite, positive homogeneous, and
subadditive. -/
structure seminorm (𝕜 : Type*) (E : Type*)
[normed_field 𝕜] [add_comm_group E] [vector_space 𝕜 E] :=
(to_fun : E → ℝ)
(smul' : ∀ (a : 𝕜) (x : E), to_fun (a • x) = ∥a∥ * to_fun x)
(triangle' : ∀ x y : E, to_fun (x + y) ≤ to_fun x + to_fun y)
variables
{𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [add_comm_group E] [vector_space 𝕜 E]
instance : inhabited (seminorm 𝕜 E) :=
⟨{ to_fun := λ _, 0,
smul' := λ _ _, (mul_zero _).symm,
triangle' := λ x y, by rw add_zero }⟩
instance : has_coe_to_fun (seminorm 𝕜 E) := ⟨_, λ p, p.to_fun⟩
namespace seminorm
variables (p : seminorm 𝕜 E) (c : 𝕜) (x y : E) (r : ℝ)
protected lemma smul : p (c • x) = ∥c∥ * p x := p.smul' _ _
protected lemma triangle : p (x + y) ≤ p x + p y := p.triangle' _ _
@[simp]
protected lemma zero : p 0 = 0 :=
calc p 0 = p ((0 : 𝕜) • 0) : by rw zero_smul
... = 0 : by rw [p.smul, norm_zero, zero_mul]
@[simp]
protected lemma neg : p (-x) = p x :=
calc p (-x) = p ((-1 : 𝕜) • x) : by rw neg_one_smul
... = p x : by rw [p.smul, norm_neg, norm_one, one_mul]
lemma nonneg : 0 ≤ p x :=
have h: 0 ≤ 2 * p x, from
calc 0 = p (x + (- x)) : by rw [add_neg_self, p.zero]
... ≤ p x + p (-x) : p.triangle _ _
... = 2 * p x : by rw [p.neg, two_mul],
nonneg_of_mul_nonneg_left h zero_lt_two
lemma sub_rev : p (x - y) = p (y - x) :=
by rw [←neg_sub, p.neg]
/-- The ball of radius `r` at `x` with respect to seminorm `p`
is the set of elements `y` with `p (y - x) < `r`. -/
def ball (p : seminorm 𝕜 E) (x : E) (r : ℝ) := { y : E | p (y - x) < r }
lemma mem_ball : y ∈ ball p x r ↔ p (y - x) < r :=
iff.rfl
lemma mem_ball_zero : y ∈ ball p 0 r ↔ p y < r :=
by rw [mem_ball, sub_zero]
lemma ball_zero_eq : ball p 0 r = { y : E | p y < r } :=
set.ext $ λ x,by { rw mem_ball_zero, exact iff.rfl }
/-- Seminorm-balls at the origin are balanced. -/
lemma balanced_ball_zero : balanced 𝕜 (ball p 0 r) :=
begin
rintro a ha x ⟨y, hy, hx⟩,
rw [mem_ball_zero, ←hx, p.smul],
calc _ ≤ p y : mul_le_of_le_one_left (p.nonneg _) ha
... < r : by rwa mem_ball_zero at hy,
end
-- TODO: convexity and absorbent/balanced sets in vector spaces over ℝ
end seminorm
-- TODO: the minkowski functional, topology induced by family of
-- seminorms, local convexity.
|
930ff4e0a4ec79ffd1a954425ed3b1106968fa67 | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/init/data/setoid.lean | be744475a3ba77b483dc4a42f06e3a85539b23a3 | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 849 | 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
-/
prelude
import init.logic
universes u
class setoid (α : Sort u) :=
(r : α → α → Prop) (iseqv : equivalence r)
instance setoid_has_equiv {α : Sort u} [setoid α] : has_equiv α :=
⟨setoid.r⟩
namespace setoid
variables {α : Sort u} [setoid α]
@[refl] lemma refl (a : α) : a ≈ a :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_refl a
end
@[symm] lemma symm {a b : α} (hab : a ≈ b) : b ≈ a :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_symm hab
end
@[trans] lemma trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_trans hab hbc
end
end setoid
|
ef377791305de87802822872f845bc5b430ce106 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/group_theory/solvable.lean | 32a39b4b8e698fcecd0469099b268b8164803a8d | [
"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,617 | lean | /-
Copyright (c) 2021 Jordan Brown, Thomas Browning, Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jordan Brown, Thomas Browning, Patrick Lutz
-/
import data.fin.vec_notation
import group_theory.abelianization
import set_theory.cardinal.basic
/-!
# Solvable Groups
In this file we introduce the notion of a solvable group. We define a solvable group as one whose
derived series is eventually trivial. This requires defining the commutator of two subgroups and
the derived series of a group.
## Main definitions
* `derived_series G n` : the `n`th term in the derived series of `G`, defined by iterating
`general_commutator` starting with the top subgroup
* `is_solvable G` : the group `G` is solvable
-/
open subgroup
variables {G G' : Type*} [group G] [group G'] {f : G →* G'}
section derived_series
variables (G)
/-- The derived series of the group `G`, obtained by starting from the subgroup `⊤` and repeatedly
taking the commutator of the previous subgroup with itself for `n` times. -/
def derived_series : ℕ → subgroup G
| 0 := ⊤
| (n + 1) := ⁅(derived_series n), (derived_series n)⁆
@[simp] lemma derived_series_zero : derived_series G 0 = ⊤ := rfl
@[simp] lemma derived_series_succ (n : ℕ) :
derived_series G (n + 1) = ⁅(derived_series G n), (derived_series G n)⁆ := rfl
lemma derived_series_normal (n : ℕ) : (derived_series G n).normal :=
begin
induction n with n ih,
{ exact (⊤ : subgroup G).normal_of_characteristic },
{ exactI subgroup.commutator_normal (derived_series G n) (derived_series G n) }
end
@[simp] lemma derived_series_one : derived_series G 1 = commutator G :=
rfl
end derived_series
section commutator_map
section derived_series_map
variables (f)
lemma map_derived_series_le_derived_series (n : ℕ) :
(derived_series G n).map f ≤ derived_series G' n :=
begin
induction n with n ih,
{ exact le_top },
{ simp only [derived_series_succ, map_commutator, commutator_mono, ih] }
end
variables {f}
lemma derived_series_le_map_derived_series (hf : function.surjective f) (n : ℕ) :
derived_series G' n ≤ (derived_series G n).map f :=
begin
induction n with n ih,
{ exact (map_top_of_surjective f hf).ge },
{ exact commutator_le_map_commutator ih ih }
end
lemma map_derived_series_eq (hf : function.surjective f) (n : ℕ) :
(derived_series G n).map f = derived_series G' n :=
le_antisymm (map_derived_series_le_derived_series f n) (derived_series_le_map_derived_series hf n)
end derived_series_map
end commutator_map
section solvable
variables (G)
/-- A group `G` is solvable if its derived series is eventually trivial. We use this definition
because it's the most convenient one to work with. -/
class is_solvable : Prop :=
(solvable : ∃ n : ℕ, derived_series G n = ⊥)
lemma is_solvable_def : is_solvable G ↔ ∃ n : ℕ, derived_series G n = ⊥ :=
⟨λ h, h.solvable, λ h, ⟨h⟩⟩
@[priority 100]
instance comm_group.is_solvable {G : Type*} [comm_group G] : is_solvable G :=
⟨⟨1, le_bot_iff.mp (abelianization.commutator_subset_ker (monoid_hom.id G))⟩⟩
lemma is_solvable_of_comm {G : Type*} [hG : group G]
(h : ∀ a b : G, a * b = b * a) : is_solvable G :=
begin
letI hG' : comm_group G := { mul_comm := h .. hG },
casesI hG,
exact comm_group.is_solvable,
end
lemma is_solvable_of_top_eq_bot (h : (⊤ : subgroup G) = ⊥) : is_solvable G :=
⟨⟨0, h⟩⟩
@[priority 100]
instance is_solvable_of_subsingleton [subsingleton G] : is_solvable G :=
is_solvable_of_top_eq_bot G (by ext; simp at *)
variables {G}
lemma solvable_of_ker_le_range {G' G'' : Type*} [group G'] [group G''] (f : G' →* G)
(g : G →* G'') (hfg : g.ker ≤ f.range) [hG' : is_solvable G'] [hG'' : is_solvable G''] :
is_solvable G :=
begin
obtain ⟨n, hn⟩ := id hG'',
obtain ⟨m, hm⟩ := id hG',
refine ⟨⟨n + m, le_bot_iff.mp (map_bot f ▸ (hm ▸ _))⟩⟩,
clear hm,
induction m with m hm,
{ exact f.range_eq_map ▸ ((derived_series G n).map_eq_bot_iff.mp (le_bot_iff.mp
((map_derived_series_le_derived_series g n).trans hn.le))).trans hfg },
{ exact commutator_le_map_commutator hm hm },
end
lemma solvable_of_solvable_injective (hf : function.injective f) [h : is_solvable G'] :
is_solvable G :=
solvable_of_ker_le_range (1 : G' →* G) f ((f.ker_eq_bot_iff.mpr hf).symm ▸ bot_le)
instance subgroup_solvable_of_solvable (H : subgroup G) [h : is_solvable G] : is_solvable H :=
solvable_of_solvable_injective (show function.injective (subtype H), from subtype.val_injective)
lemma solvable_of_surjective (hf : function.surjective f) [h : is_solvable G] :
is_solvable G' :=
solvable_of_ker_le_range f (1 : G' →* G) ((f.range_top_of_surjective hf).symm ▸ le_top)
instance solvable_quotient_of_solvable (H : subgroup G) [H.normal] [h : is_solvable G] :
is_solvable (G ⧸ H) :=
solvable_of_surjective (quotient_group.mk'_surjective H)
instance solvable_prod {G' : Type*} [group G'] [h : is_solvable G] [h' : is_solvable G'] :
is_solvable (G × G') :=
solvable_of_ker_le_range (monoid_hom.inl G G') (monoid_hom.snd G G')
(λ x hx, ⟨x.1, prod.ext rfl hx.symm⟩)
end solvable
section is_simple_group
variable [is_simple_group G]
lemma is_simple_group.derived_series_succ {n : ℕ} : derived_series G n.succ = commutator G :=
begin
induction n with n ih,
{ exact derived_series_one G },
rw [derived_series_succ, ih],
cases (commutator.normal G).eq_bot_or_eq_top with h h,
{ rw [h, commutator_bot_left] },
{ rwa h },
end
lemma is_simple_group.comm_iff_is_solvable :
(∀ a b : G, a * b = b * a) ↔ is_solvable G :=
⟨is_solvable_of_comm, λ ⟨⟨n, hn⟩⟩, begin
cases n,
{ intros a b,
refine (mem_bot.1 _).trans (mem_bot.1 _).symm;
{ rw ← hn,
exact mem_top _ } },
{ rw is_simple_group.derived_series_succ at hn,
intros a b,
rw [← mul_inv_eq_one, mul_inv_rev, ← mul_assoc, ← mem_bot, ← hn, commutator_eq_closure],
exact subset_closure ⟨a, b, rfl⟩ }
end⟩
end is_simple_group
section perm_not_solvable
lemma not_solvable_of_mem_derived_series {g : G} (h1 : g ≠ 1)
(h2 : ∀ n : ℕ, g ∈ derived_series G n) : ¬ is_solvable G :=
mt (is_solvable_def _).mp (not_exists_of_forall_not
(λ n h, h1 (subgroup.mem_bot.mp ((congr_arg (has_mem.mem g) h).mp (h2 n)))))
lemma equiv.perm.fin_5_not_solvable : ¬ is_solvable (equiv.perm (fin 5)) :=
begin
let x : equiv.perm (fin 5) := ⟨![1, 2, 0, 3, 4], ![2, 0, 1, 3, 4], dec_trivial, dec_trivial⟩,
let y : equiv.perm (fin 5) := ⟨![3, 4, 2, 0, 1], ![3, 4, 2, 0, 1], dec_trivial, dec_trivial⟩,
let z : equiv.perm (fin 5) := ⟨![0, 3, 2, 1, 4], ![0, 3, 2, 1, 4], dec_trivial, dec_trivial⟩,
have key : x = z * ⁅x, y * x * y⁻¹⁆ * z⁻¹ := by dec_trivial,
refine not_solvable_of_mem_derived_series (show x ≠ 1, by dec_trivial) (λ n, _),
induction n with n ih,
{ exact mem_top x },
{ rw [key, (derived_series_normal _ _).mem_comm_iff, inv_mul_cancel_left],
exact commutator_mem_commutator ih ((derived_series_normal _ _).conj_mem _ ih _) },
end
lemma equiv.perm.not_solvable (X : Type*) (hX : 5 ≤ cardinal.mk X) :
¬ is_solvable (equiv.perm X) :=
begin
introI h,
have key : nonempty (fin 5 ↪ X),
{ rwa [←cardinal.lift_mk_le, cardinal.mk_fin, cardinal.lift_nat_cast,
nat.cast_bit1, nat.cast_bit0, nat.cast_one, cardinal.lift_id] },
exact equiv.perm.fin_5_not_solvable (solvable_of_solvable_injective
(equiv.perm.via_embedding_hom_injective (nonempty.some key))),
end
end perm_not_solvable
|
6a5365f1327fe7a217ca4c9254e15cfb155d2ea1 | 964a8bb66c2eb89b920fe65d0ec2f77eab0d5f65 | /src/hanoitactics.lean | a2bd8c0673afc0c90b8fcb6eb450ba4a248905a2 | [
"MIT"
] | permissive | SnobbyDragon/leanhanoi | 9990a7b586f1d843d39c3c7aab7ac0b5eefbe653 | a42811ce5ab55e0451880a8c111c75b082936d39 | refs/heads/master | 1,675,735,182,689 | 1,609,387,288,000 | 1,609,387,288,000 | 284,167,126 | 8 | 1 | MIT | 1,609,262,129,000 | 1,596,247,349,000 | Lean | UTF-8 | Lean | false | false | 1,648 | lean | import hanoi
open hanoi hanoi.tower
open tactic
namespace hanoitactics
-- moves curr tower to a new position if valid, otherwise fails
meta def move_disk (s d : tower) : tactic unit :=
do { `(can_get_to' %%t₁ %%t₂) ← tactic.target,
tactic.apply `(@fmove' %%t₁ %%t₂ %%(reflect s) %%(reflect d)),
tactic.applyc ``and.intro,
`[simp only [valid_move, list.range', false_or, eq_self_iff_true, not_true, ne.def, not_false_iff, and_self, false_and]],
`[dsimp [move]]
} <|> tactic.fail "failed to move disk :("
-- sometimes needs to finish to verify valid_move
meta def move_disk' (s d : tower) : tactic unit :=
do { move_disk s d,
`[finish],
`[dsimp [move]]
} <|> move_disk s d
meta def start_game : tactic unit :=
do { `(game' %%d) ← tactic.target,
dunfold_target [``game']
} <|> tactic.fail "not a game"
-- if two towers are the same then we win
meta def finish_game : tactic unit :=
do { `(can_get_to' %%t₁ %%t₂) ← tactic.target,
tactic.exact `(@can_get_to'.can_get_to_self' %%t₁)
} <|> tactic.fail "we haven't won yet"
-- automatically starts the game if not started
meta def md (s d : tower) : tactic unit :=
do { start_game,
move_disk' s d
} <|> move_disk' s d
meta def get_start_position : tactic position :=
do { `(game' %%d) ← tactic.target,
d' ← (eval_expr ℕ) d,
return ⟨list.range' 1 d', [], []⟩
}
meta def get_position : tactic position :=
do { `(can_get_to' {A := %%A, B := %%B, C := %%C} %%t₂) ← tactic.target,
[A', B', C'] ← list.mmap (eval_expr (list ℕ)) [A, B, C],
return ⟨A', B', C'⟩
} <|> get_start_position
end hanoitactics |
6e3cd954f880a64b4f8315149ed11f7ac95bdeab | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/quot_abuse1.lean | 3bdfd8314f7182f73c80c0cd6e9a0409ffffb1ff | [
"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 | 130 | lean | prelude
init_quotient
/- definit eq as the empty type -/
inductive {u} eq {α : Sort u} (a : α) : α → Sort 0
init_quotient
|
0c0b091dabfb7b12bbdc778f62221ccfca939b05 | 4727251e0cd73359b15b664c3170e5d754078599 | /test/ring_exp.lean | 04905ce9685f88c7d5b2a8e27fb1bed72f6a31ab | [
"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,070 | lean | import tactic.ring_exp
import tactic.zify
import algebra.group_with_zero.power
import tactic.field_simp
universes u
section addition
/-!
### `addition` section
Test associativity and commutativity of `(+)`.
-/
example (a b : ℚ) : a = a := by ring_exp
example (a b : ℚ) : a + b = a + b := by ring_exp
example (a b : ℚ) : b + a = a + b := by ring_exp
example (a b : ℤ) : a + b + b = b + (a + b) := by ring_exp
example (a b c : ℕ) : a + b + b + (c + c) = c + (b + c) + (a + b) := by ring_exp
end addition
section numerals
/-!
### `numerals` section
Test that numerals behave like rational numbers.
-/
example (a : ℕ) : a + 5 + 5 = 0 + a + 10 := by ring_exp
example (a : ℤ) : a + 5 + 5 = 0 + a + 10 := by ring_exp
example (a : ℚ) : (1/2) * a + (1/2) * a = a := by ring_exp
end numerals
section multiplication
/-!
### `multiplication section`
Test that multiplication is associative and commutative.
Also test distributivity of `(+)` and `(*)`.
-/
example (a : ℕ) : 0 = a * 0 := by ring_exp_eq
example (a : ℕ) : a = a * 1 := by ring_exp
example (a : ℕ) : a + a = a * 2 := by ring_exp
example (a b : ℤ) : a * b = b * a := by ring_exp
example (a b : ℕ) : a * 4 * b + a = a * (4 * b + 1) := by ring_exp
end multiplication
section exponentiation
/-!
### `exponentiation` section
Test that exponentiation has the correct distributivity properties.
-/
example : 0 ^ 1 = 0 := by ring_exp
example : 0 ^ 2 = 0 := by ring_exp
example (a : ℕ) : a ^ 0 = 1 := by ring_exp
example (a : ℕ) : a ^ 1 = a := by ring_exp
example (a : ℕ) : a ^ 2 = a * a := by ring_exp
example (a b : ℕ) : a ^ b = a ^ b := by ring_exp
example (a b : ℕ) : a ^ (b + 1) = a * a ^ b := by ring_exp
example (n : ℕ) (a m : ℕ) : a * a^n * m = a^(n+1) * m := by ring_exp
example (n : ℕ) (a m : ℕ) : m * a^n * a = a^(n+1) * m := by ring_exp
example (n : ℕ) (a m : ℤ) : a * a^n * m = a^(n+1) * m := by ring_exp
example (n : ℕ) (m : ℤ) : 2 * 2^n * m = 2^(n+1) * m := by ring_exp
example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp
example (n m : ℕ) (a : ℤ) : (a ^ n)^m = a^(n * m) := by ring_exp
example (n m : ℕ) (a : ℤ) : a^(n^0) = a^1 := by ring_exp
example (n : ℕ) : 0^(n + 1) = 0 := by ring_exp
example {α} [comm_ring α] (x : α) (k : ℕ) : x ^ (k + 2) = x * x * x^k := by ring_exp
example {α} [comm_ring α] (k : ℕ) (x y z : α) :
x * (z * (x - y)) + (x * (y * y ^ k) - y * (y * y ^ k)) = (z * x + y * y ^ k) * (x - y)
:= by ring_exp
-- We can represent a large exponent `n` more efficiently than just `n` multiplications:
example (a b : ℚ) : (a * b) ^ 1000000 = (b * a) ^ 1000000 := by ring_exp
example (n : ℕ) : 2 ^ (n + 1 + 1) = 2 * 2 ^ (n + 1) :=
by ring_exp_eq
end exponentiation
section power_of_sum
/-!
### `power_of_sum` section
Test that raising a sum to a power behaves like repeated multiplication,
if needed.
-/
example (a b : ℤ) : (a + b)^2 = a^2 + b^2 + a * b + b * a := by ring_exp
example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp
end power_of_sum
section negation
/-!
### `negation` section
Test that negation and subtraction satisfy the expected properties,
also in semirings such as `ℕ`.
-/
example {α} [comm_ring α] (a : α) : a - a = 0 := by ring_exp_eq
example (a : ℤ) : a - a = 0 := by ring_exp
example (a : ℤ) : a + - a = 0 := by ring_exp
example (a : ℤ) : - a = (-1) * a := by ring_exp
-- Here, (a - b) is treated as an atom.
example (a b : ℕ) : a - b + a + a = a - b + 2 * a := by ring_exp
example (n : ℕ) : n + 1 - 1 = n := by ring_exp! -- But we can force a bit of evaluation anyway.
end negation
constant f {α} : α → α
section complicated
/-!
### `complicated` section
Test that complicated, real-life expressions also get normalized.
-/
example {α : Type} [linear_ordered_field α] (x : α) :
2 * x + 1 * 1 - (2 * f (x + 1 / 2) + 2 * 1) + (1 * 1 - (2 * x - 2 * f (x + 1 / 2))) = 0
:= by ring_exp_eq
example {α : Type u} [linear_ordered_field α] (x : α) :
f (x + 1 / 2) ^ 1 * -2 + (f (x + 1 / 2) ^ 1 * 2 + 0) = 0
:= by ring_exp_eq
example (x y : ℕ) : x + id y = y + id x := by ring_exp!
-- Here, we check that `n - s` is not treated as `n + additive_inverse s`,
-- if `s` doesn't have an additive inverse.
example (B s n : ℕ) : B * (f s * ((n - s) * f (n - s - 1))) = B * (n - s) * (f s * f (n - s - 1)) :=
by ring_exp
-- This is a somewhat subtle case: `-c/b` is parsed as `(-c)/b`,
-- so we can't simply treat both sides of the division as atoms.
-- Instead, we follow the `ring` tactic in interpreting `-c / b` as `-c * b⁻¹`,
-- with only `b⁻¹` an atom.
example {α} [linear_ordered_field α] (a b c : α) : a*(-c/b)*(-c/b) = a*((c/b)*(c/b)) := by ring_exp
-- test that `field_simp` works fine with powers and `ring_exp`.
example (x y : ℚ) (n : ℕ) (hx : x ≠ 0) (hy : y ≠ 0) :
1/ (2/(x / y))^(2 * n) + y / y^(n+1) - (x/y)^n * (x/(2 * y))^n / 2 ^n = 1/y^n :=
begin
field_simp,
ring_exp
end
end complicated
-- Test that `nat.succ d` gets handled as `d + 1`.
example (d : ℕ) : 2 * (2 ^ d - 1) + 1 = 2 ^ d.succ - 1 :=
begin
zify [nat.one_le_pow'],
ring_exp,
end
-- Simplified instance of a bug reported by Patrick Massot:
-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/ring_exp.20bug
example (l : ℤ) : l - l = 0 :=
begin
tactic.replace_at (tactic.ring_exp.normalize tactic.transparency.reducible) [] tt >> pure (),
refl
end
-- Normalizing also works on more complicated expressions:
example (a b : ℤ) : (a^2 - b - b) + (2 * id b - a^2) = 0 :=
begin
tactic.replace_at (tactic.ring_exp.normalize tactic.transparency.semireducible) [] tt >> pure (),
refl
end
section conv
/-!
### `conv` section
Test that `ring_exp` works inside of `conv`, both with and without `!`.
-/
example (n : ℕ) : (2^n * 2 + 1)^10 = (2^(n+1) + 1)^10 :=
begin
conv_rhs
{ congr,
ring_exp, },
conv_lhs
{ congr,
ring_exp, },
end
example (x y : ℤ) : x + id y - y + id x = x * 2 := begin
conv_lhs { ring_exp!, },
end
end conv
section benchmark
/-!
### `benchmark` section
The `ring_exp` tactic shouldn't be too slow.
-/
-- This last example was copied from `data/polynomial.lean`, because it timed out.
-- After some optimization, it doesn't.
variables {α : Type} [comm_ring α]
def pow_sub_pow_factor (x y : α) : Π {i : ℕ},{z // x^i - y^i = z*(x - y)}
| 0 := ⟨0, by simp⟩
| 1 := ⟨1, by simp⟩
| (k+2) :=
begin
cases @pow_sub_pow_factor (k+1) with z hz,
existsi z*x + y^(k+1),
rw [pow_succ x, pow_succ y, ←sub_add_sub_cancel (x*x^(k+1)) (x*y^(k+1)),
←mul_sub x, hz],
ring_exp_eq
end
-- Another benchmark: bound the growth of the complexity somewhat.
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 4 = (1 + x) ^ 4 := by try_for 5000 {ring_exp}
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 10000 {ring_exp}
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 8 = (1 + x) ^ 8 := by try_for 15000 {ring_exp}
end benchmark
|
547ace910106f6d6dee0d6cca401fb562a586422 | 0c1546a496eccfb56620165cad015f88d56190c5 | /library/init/data/setoid.lean | 2d537e1f42196ff79b98efce6cd3ee585b4dea93 | [
"Apache-2.0"
] | permissive | Solertis/lean | 491e0939957486f664498fbfb02546e042699958 | 84188c5aa1673fdf37a082b2de8562dddf53df3f | refs/heads/master | 1,610,174,257,606 | 1,486,263,620,000 | 1,486,263,620,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 821 | 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
-/
prelude
import init.logic
universe variables u
class setoid (α : Type u) :=
(r : α → α → Prop) (iseqv : equivalence r)
namespace setoid
infix ` ≈ ` := setoid.r
variable {α : Type u}
variable [s : setoid α]
include s
@[refl] lemma refl (a : α) : a ≈ a :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_refl a
end
@[symm] lemma symm {a b : α} (hab : a ≈ b) : b ≈ a :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_symm hab
end
@[trans] lemma trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
match setoid.iseqv α with
| ⟨h_refl, h_symm, h_trans⟩ := h_trans hab hbc
end
end setoid
|
5191a093dcead73094d15129fb24bdb2e6d7fe08 | d1bbf1801b3dcb214451d48214589f511061da63 | /src/data/complex/is_R_or_C.lean | 474ca4c66a80b7db3df8fea25e9f3197b6ff0814 | [
"Apache-2.0"
] | permissive | cheraghchi/mathlib | 5c366f8c4f8e66973b60c37881889da8390cab86 | f29d1c3038422168fbbdb2526abf7c0ff13e86db | refs/heads/master | 1,676,577,831,283 | 1,610,894,638,000 | 1,610,894,638,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 30,066 | lean | /-
Copyright (c) 2020 Frédéric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Frédéric Dupuis
-/
import analysis.normed_space.basic
import analysis.complex.basic
/-!
# `is_R_or_C`: a typeclass for ℝ or ℂ
This file defines the typeclass `is_R_or_C` intended to have only two instances:
ℝ and ℂ. It is meant for definitions and theorems which hold for both the real and the complex case,
and in particular when the real case follows directly from the complex case by setting `re` to `id`,
`im` to zero and so on. Its API follows closely that of ℂ.
Possible applications include defining inner products and Hilbert spaces for both the real and
complex case. One would produce the definitions and proof for an arbitrary field of this
typeclass, which basically amounts to doing the complex case, and the two cases then fall out
immediately from the two instances of the class.
## Implementation notes
The coercion from reals into an `is_R_or_C` field is done by registering `algebra_map ℝ K` as
a `has_coe_t`. For this to work, we must proceed carefully to avoid problems involving circular
coercions in the case `K=ℝ`; in particular, we cannot use the plain `has_coe` and must set
priorities carefully. This problem was already solved for `ℕ`, and we copy the solution detailed
in `data/nat/cast`. See also Note [coercion into rings] for more details.
In addition, several lemmas need to be set at priority 900 to make sure that they do not override
their counterparts in `complex.lean` (which causes linter errors).
-/
open_locale big_operators
section
local notation `𝓚` := algebra_map ℝ _
/--
This typeclass captures properties shared by ℝ and ℂ, with an API that closely matches that of ℂ.
-/
class is_R_or_C (K : Type*)
extends nondiscrete_normed_field K, normed_algebra ℝ K, complete_space K :=
(re : K →+ ℝ)
(im : K →+ ℝ)
(conj : K →+* K)
(I : K) -- Meant to be set to 0 for K=ℝ
(I_re_ax : re I = 0)
(I_mul_I_ax : I = 0 ∨ I * I = -1)
(re_add_im_ax : ∀ (z : K), 𝓚 (re z) + 𝓚 (im z) * I = z)
(of_real_re_ax : ∀ r : ℝ, re (𝓚 r) = r)
(of_real_im_ax : ∀ r : ℝ, im (𝓚 r) = 0)
(mul_re_ax : ∀ z w : K, re (z * w) = re z * re w - im z * im w)
(mul_im_ax : ∀ z w : K, im (z * w) = re z * im w + im z * re w)
(conj_re_ax : ∀ z : K, re (conj z) = re z)
(conj_im_ax : ∀ z : K, im (conj z) = -(im z))
(conj_I_ax : conj I = -I)
(norm_sq_eq_def_ax : ∀ (z : K), ∥z∥^2 = (re z) * (re z) + (im z) * (im z))
(mul_im_I_ax : ∀ (z : K), (im z) * im I = im z)
(inv_def_ax : ∀ (z : K), z⁻¹ = conj z * 𝓚 ((∥z∥^2)⁻¹))
(div_I_ax : ∀ (z : K), z / I = -(z * I))
end
namespace is_R_or_C
variables {K : Type*} [is_R_or_C K]
local postfix `†`:100 := @is_R_or_C.conj K _
/- The priority must be set at 900 to ensure that coercions are tried in the right order.
See Note [coercion into rings], or `data/nat/cast.lean` for more details. -/
@[priority 900] noncomputable instance algebra_map_coe : has_coe_t ℝ K := ⟨algebra_map ℝ K⟩
lemma of_real_alg (x : ℝ) : (x : K) = x • (1 : K) :=
algebra.algebra_map_eq_smul_one x
lemma algebra_map_eq_of_real : ⇑(algebra_map ℝ K) = coe := rfl
@[simp] lemma re_add_im (z : K) : ((re z) : K) + (im z) * I = z := is_R_or_C.re_add_im_ax z
@[simp, norm_cast] lemma of_real_re : ∀ r : ℝ, re (r : K) = r := is_R_or_C.of_real_re_ax
@[simp, norm_cast] lemma of_real_im : ∀ r : ℝ, im (r : K) = 0 := is_R_or_C.of_real_im_ax
@[simp] lemma mul_re : ∀ z w : K, re (z * w) = re z * re w - im z * im w :=
is_R_or_C.mul_re_ax
@[simp] lemma mul_im : ∀ z w : K, im (z * w) = re z * im w + im z * re w :=
is_R_or_C.mul_im_ax
theorem inv_def (z : K) : z⁻¹ = conj z * ((∥z∥^2)⁻¹:ℝ) :=
is_R_or_C.inv_def_ax z
theorem ext_iff : ∀ {z w : K}, z = w ↔ re z = re w ∧ im z = im w :=
λ z w, { mp := by { rintro rfl, cc },
mpr := by { rintro ⟨h₁,h₂⟩, rw [←re_add_im z, ←re_add_im w, h₁, h₂] } }
theorem ext : ∀ {z w : K}, re z = re w → im z = im w → z = w :=
by { simp_rw ext_iff, cc }
@[simp, norm_cast, priority 900] lemma of_real_zero : ((0 : ℝ) : K) = 0 :=
by rw [of_real_alg, zero_smul]
@[simp] lemma zero_re' : re (0 : K) = (0 : ℝ) := re.map_zero
@[simp, norm_cast, priority 900] lemma of_real_one : ((1 : ℝ) : K) = 1 :=
by rw [of_real_alg, one_smul]
@[simp] lemma one_re : re (1 : K) = 1 := by rw [←of_real_one, of_real_re]
@[simp] lemma one_im : im (1 : K) = 0 := by rw [←of_real_one, of_real_im]
@[simp, norm_cast, priority 900] theorem of_real_inj {z w : ℝ} : (z : K) = (w : K) ↔ z = w :=
{ mp := λ h, by { convert congr_arg re h; simp only [of_real_re] },
mpr := λ h, by rw h }
@[simp] lemma bit0_re (z : K) : re (bit0 z) = bit0 (re z) := by simp [bit0]
@[simp] lemma bit1_re (z : K) : re (bit1 z) = bit1 (re z) :=
by simp only [bit1, add_monoid_hom.map_add, bit0_re, add_right_inj, one_re]
@[simp] lemma bit0_im (z : K) : im (bit0 z) = bit0 (im z) := by simp [bit0]
@[simp] lemma bit1_im (z : K) : im (bit1 z) = bit0 (im z) :=
by simp only [bit1, add_right_eq_self, add_monoid_hom.map_add, bit0_im, one_im]
@[simp, priority 900] theorem of_real_eq_zero {z : ℝ} : (z : K) = 0 ↔ z = 0 :=
by rw [←of_real_zero]; exact of_real_inj
@[simp, norm_cast, priority 900] lemma of_real_add ⦃r s : ℝ⦄ : ((r + s : ℝ) : K) = r + s :=
by { apply (@is_R_or_C.ext_iff K _ ((r + s : ℝ) : K) (r + s)).mpr, simp }
@[simp, norm_cast, priority 900] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : K) = bit0 (r : K) :=
ext_iff.2 $ by simp [bit0]
@[simp, norm_cast, priority 900] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : K) = bit1 (r : K) :=
ext_iff.2 $ by simp [bit1]
/- Note: This can be proven by `norm_num` once K is proven to be of characteristic zero below. -/
lemma two_ne_zero : (2 : K) ≠ 0 :=
begin
intro h, rw [(show (2 : K) = ((2 : ℝ) : K), by norm_num), ←of_real_zero, of_real_inj] at h,
linarith,
end
@[simp, norm_cast, priority 900] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : K) = -r :=
ext_iff.2 $ by simp
@[simp, norm_cast, priority 900] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : K) = r * s :=
ext_iff.2 $ by simp
lemma of_real_mul_re (r : ℝ) (z : K) : re (↑r * z) = r * re z :=
by simp only [mul_re, of_real_im, zero_mul, of_real_re, sub_zero]
lemma smul_re (r : ℝ) (z : K) : re (↑r * z) = r * (re z) :=
by simp only [of_real_im, zero_mul, of_real_re, sub_zero, mul_re]
lemma smul_im (r : ℝ) (z : K) : im (↑r * z) = r * (im z) :=
by simp only [add_zero, of_real_im, zero_mul, of_real_re, mul_im]
lemma smul_re' : ∀ (r : ℝ) (z : K), re (r • z) = r * (re z) :=
λ r z, by { rw algebra.smul_def, apply smul_re }
lemma smul_im' : ∀ (r : ℝ) (z : K), im (r • z) = r * (im z) :=
λ r z, by { rw algebra.smul_def, apply smul_im }
/-- The real part in a `is_R_or_C` field, as a linear map. -/
noncomputable def re_lm : K →ₗ[ℝ] ℝ :=
{ map_smul' := smul_re', .. re }
@[simp] lemma re_lm_coe : (re_lm : K → ℝ) = re := rfl
/-! ### The imaginary unit, `I` -/
/-- The imaginary unit. -/
@[simp] lemma I_re : re (I : K) = 0 := I_re_ax
@[simp] lemma I_im (z : K) : im z * im (I : K) = im z := mul_im_I_ax z
@[simp] lemma I_im' (z : K) : im (I : K) * im z = im z :=
by rw [mul_comm, I_im _]
lemma I_mul_I : (I : K) = 0 ∨ (I : K) * I = -1 := I_mul_I_ax
@[simp] lemma conj_re (z : K) : re (conj z) = re z := is_R_or_C.conj_re_ax z
@[simp] lemma conj_im (z : K) : im (conj z) = -(im z) := is_R_or_C.conj_im_ax z
@[simp] lemma conj_of_real (r : ℝ) : conj (r : K) = (r : K) :=
by { rw ext_iff, simp only [of_real_im, conj_im, eq_self_iff_true, conj_re, and_self, neg_zero] }
@[simp] lemma conj_bit0 (z : K) : conj (bit0 z) = bit0 (conj z) := by simp [bit0, ext_iff]
@[simp] lemma conj_bit1 (z : K) : conj (bit1 z) = bit1 (conj z) := by simp [bit0, ext_iff]
@[simp] lemma conj_neg_I : conj (-I) = (I : K) := by simp [ext_iff]
@[simp] lemma conj_conj (z : K) : conj (conj z) = z := by simp [ext_iff]
lemma conj_involutive : @function.involutive K is_R_or_C.conj := conj_conj
lemma conj_bijective : @function.bijective K K is_R_or_C.conj := conj_involutive.bijective
lemma conj_inj (z w : K) : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff
lemma conj_eq_zero {z : K} : conj z = 0 ↔ z = 0 :=
ring_hom.map_eq_zero conj
lemma eq_conj_iff_real {z : K} : conj z = z ↔ ∃ r : ℝ, z = (r : K) :=
begin
split,
{ intro h,
suffices : im z = 0,
{ use (re z),
rw ← add_zero (coe _),
convert (re_add_im z).symm, simp [this] },
contrapose! h,
rw ← re_add_im z,
simp only [conj_of_real, ring_hom.map_add, ring_hom.map_mul, conj_I_ax],
rw [add_left_cancel_iff, ext_iff],
simpa [neg_eq_iff_add_eq_zero, add_self_eq_zero] },
{ rintros ⟨r, rfl⟩, apply conj_of_real }
end
variables (K)
/-- Conjugation as a ring equivalence. This is used to convert the inner product into a
sesquilinear product. -/
def conj_to_ring_equiv : K ≃+* Kᵒᵖ :=
{ to_fun := opposite.op ∘ conj,
inv_fun := conj ∘ opposite.unop,
left_inv := λ x, by simp only [conj_conj, function.comp_app, opposite.unop_op],
right_inv := λ x, by simp only [conj_conj, opposite.op_unop, function.comp_app],
map_mul' := λ x y, by simp [mul_comm],
map_add' := λ x y, by simp }
variables {K}
@[simp] lemma ring_equiv_apply {x : K} : (conj_to_ring_equiv K x).unop = x† := rfl
lemma eq_conj_iff_re {z : K} : conj z = z ↔ ((re z) : K) = z :=
eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩
/-- The norm squared function. -/
def norm_sq : monoid_with_zero_hom K ℝ :=
{ to_fun := λ z, re z * re z + im z * im z,
map_zero' := by simp,
map_one' := by simp,
map_mul' := λ z w, by { simp, ring } }
lemma norm_sq_eq_def {z : K} : ∥z∥^2 = (re z) * (re z) + (im z) * (im z) := norm_sq_eq_def_ax z
lemma norm_sq_eq_def' (z : K) : norm_sq z = ∥z∥^2 := by { rw norm_sq_eq_def, refl }
@[simp] lemma norm_sq_of_real (r : ℝ) : ∥(r : K)∥^2 = r * r :=
by simp [norm_sq_eq_def]
lemma norm_sq_zero : norm_sq (0 : K) = 0 := norm_sq.map_zero
lemma norm_sq_one : norm_sq (1 : K) = 1 := norm_sq.map_one
lemma norm_sq_nonneg (z : K) : 0 ≤ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
@[simp] lemma norm_sq_eq_zero {z : K} : norm_sq z = 0 ↔ z = 0 :=
by { rw [norm_sq_eq_def'], simp [pow_two] }
@[simp] lemma norm_sq_pos {z : K} : 0 < norm_sq z ↔ z ≠ 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg]
@[simp] lemma norm_sq_neg (z : K) : norm_sq (-z) = norm_sq z :=
by simp [norm_sq_eq_def']
@[simp] lemma norm_sq_conj (z : K) : norm_sq (conj z) = norm_sq z := by simp [norm_sq]
@[simp] lemma norm_sq_mul (z w : K) : norm_sq (z * w) = norm_sq z * norm_sq w :=
norm_sq.map_mul z w
lemma norm_sq_add (z w : K) :
norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (re (z * conj w)) :=
by simp [norm_sq, pow_two]; ring
lemma re_sq_le_norm_sq (z : K) : re z * re z ≤ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : K) : im z * im z ≤ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : K) : z * conj z = ((norm_sq z) : K) :=
by simp [ext_iff, norm_sq, mul_comm, sub_eq_neg_add, add_comm]
theorem add_conj (z : K) : z + conj z = 2 * (re z) :=
by simp [ext_iff, two_mul]
/-- The pseudo-coercion `of_real` as a `ring_hom`. -/
noncomputable def of_real_hom : ℝ →+* K := algebra_map ℝ K
/-- The coercion from reals as a `ring_hom`. -/
noncomputable def coe_hom : ℝ →+* K := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩
@[simp, norm_cast, priority 900] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : K) = r - s :=
ext_iff.2 $ by simp
@[simp, norm_cast, priority 900] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : K) = r ^ n :=
by induction n; simp [*, of_real_mul, pow_succ]
theorem sub_conj (z : K) : z - conj z = (2 * im z) * I :=
by simp [ext_iff, two_mul, sub_eq_add_neg, add_mul, mul_im_I_ax]
lemma norm_sq_sub (z w : K) : norm_sq (z - w) =
norm_sq z + norm_sq w - 2 * re (z * conj w) :=
by simp [-mul_re, norm_sq_add, add_comm, add_left_comm, sub_eq_add_neg]
lemma sqrt_norm_sq_eq_norm {z : K} : real.sqrt (norm_sq z) = ∥z∥ :=
begin
have h₂ : ∥z∥ = real.sqrt (∥z∥^2) := (real.sqrt_sqr (norm_nonneg z)).symm,
rw [h₂],
exact congr_arg real.sqrt (norm_sq_eq_def' z)
end
/-! ### Inversion -/
@[simp] lemma inv_re (z : K) : re (z⁻¹) = re z / norm_sq z :=
by simp [inv_def, norm_sq_eq_def, norm_sq, division_def]
@[simp] lemma inv_im (z : K) : im (z⁻¹) = im (-z) / norm_sq z :=
by simp [inv_def, norm_sq_eq_def, norm_sq, division_def]
@[simp, norm_cast, priority 900] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : K) = r⁻¹ :=
begin
rw ext_iff, by_cases r = 0, { simp [h] },
{ simp; field_simp [h, norm_sq] },
end
protected lemma inv_zero : (0⁻¹ : K) = 0 :=
by rw [← of_real_zero, ← of_real_inv, inv_zero]
protected theorem mul_inv_cancel {z : K} (h : z ≠ 0) : z * z⁻¹ = 1 :=
by rw [inv_def, ←mul_assoc, mul_conj, ←of_real_mul, ←norm_sq_eq_def',
mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one]
lemma div_re (z w : K) : re (z / w) = re z * re w / norm_sq w + im z * im w / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg]
lemma div_im (z w : K) : im (z / w) = im z * re w / norm_sq w - re z * im w / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm]
@[simp, norm_cast, priority 900] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : K) = r / s :=
(@is_R_or_C.coe_hom K _).map_div r s
lemma div_re_of_real {z : K} {r : ℝ} : re (z / r) = re z / r :=
begin
by_cases h : r = 0,
{ simp [h, of_real_zero] },
{ change r ≠ 0 at h,
rw [div_eq_mul_inv, ←of_real_inv, div_eq_mul_inv],
simp [norm_sq, div_mul_eq_div_mul_one_div, div_self h] }
end
@[simp, norm_cast, priority 900] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : K) = r ^ n :=
(@is_R_or_C.coe_hom K _).map_fpow r n
lemma I_mul_I_of_nonzero : (I : K) ≠ 0 → (I : K) * I = -1 :=
by { have := I_mul_I_ax, tauto }
@[simp] lemma div_I (z : K) : z / I = -(z * I) :=
begin
by_cases h : (I : K) = 0,
{ simp [h] },
{ field_simp [h], simp [mul_assoc, I_mul_I_of_nonzero h] }
end
@[simp] lemma inv_I : (I : K)⁻¹ = -I :=
by { by_cases h : (I : K) = 0; field_simp [h] }
@[simp] lemma norm_sq_inv (z : K) : norm_sq z⁻¹ = (norm_sq z)⁻¹ :=
(@norm_sq K _).map_inv' z
@[simp] lemma norm_sq_div (z w : K) : norm_sq (z / w) = norm_sq z / norm_sq w :=
(@norm_sq K _).map_div z w
lemma norm_conj {z : K} : ∥conj z∥ = ∥z∥ :=
by simp only [←sqrt_norm_sq_eq_norm, norm_sq_conj]
lemma conj_inv {z : K} : conj (z⁻¹) = (conj z)⁻¹ :=
by simp only [inv_def, norm_conj, ring_hom.map_mul, conj_of_real]
lemma conj_div {z w : K} : conj (z / w) = (conj z) / (conj w) :=
by rw [div_eq_inv_mul, div_eq_inv_mul, ring_hom.map_mul]; simp only [conj_inv]
/-! ### Cast lemmas -/
@[simp, norm_cast, priority 900] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : K) = n :=
of_real_hom.map_nat_cast n
@[simp, norm_cast] lemma nat_cast_re (n : ℕ) : re (n : K) = n :=
by rw [← of_real_nat_cast, of_real_re]
@[simp, norm_cast] lemma nat_cast_im (n : ℕ) : im (n : K) = 0 :=
by rw [← of_real_nat_cast, of_real_im]
@[simp, norm_cast, priority 900] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : K) = n :=
of_real_hom.map_int_cast n
@[simp, norm_cast] lemma int_cast_re (n : ℤ) : re (n : K) = n :=
by rw [← of_real_int_cast, of_real_re]
@[simp, norm_cast] lemma int_cast_im (n : ℤ) : im (n : K) = 0 :=
by rw [← of_real_int_cast, of_real_im]
@[simp, norm_cast, priority 900] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : K) = n :=
(@is_R_or_C.of_real_hom K _).map_rat_cast n
@[simp, norm_cast] lemma rat_cast_re (q : ℚ) : re (q : K) = q :=
by rw [← of_real_rat_cast, of_real_re]
@[simp, norm_cast] lemma rat_cast_im (q : ℚ) : im (q : K) = 0 :=
by rw [← of_real_rat_cast, of_real_im]
/-! ### Characteristic zero -/
-- TODO: I think this can be instance, because it is a `Prop`
/--
ℝ and ℂ are both of characteristic zero.
Note: This is not registered as an instance to avoid having multiple instances on ℝ and ℂ.
-/
lemma char_zero_R_or_C : char_zero K :=
char_zero_of_inj_zero $ λ n h,
by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h
theorem re_eq_add_conj (z : K) : ↑(re z) = (z + conj z) / 2 :=
begin
haveI : char_zero K := char_zero_R_or_C,
rw [add_conj, mul_div_cancel_left ((re z):K) two_ne_zero'],
end
/-! ### Absolute value -/
/-- The complex absolute value function, defined as the square root of the norm squared. -/
@[pp_nodot] noncomputable def abs (z : K) : ℝ := (norm_sq z).sqrt
local notation `abs'` := _root_.abs
local notation `absK` := @abs K _
@[simp, norm_cast] lemma abs_of_real (r : ℝ) : absK r = abs' r :=
by simp [abs, norm_sq, norm_sq_of_real, real.sqrt_mul_self_eq_abs]
lemma norm_eq_abs (z : K) : ∥z∥ = absK z := by simp [abs, norm_sq_eq_def']
lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : absK r = r :=
(abs_of_real _).trans (abs_of_nonneg h)
lemma abs_of_nat (n : ℕ) : absK n = n :=
by { rw [← of_real_nat_cast], exact abs_of_nonneg (nat.cast_nonneg n) }
lemma mul_self_abs (z : K) : abs z * abs z = norm_sq z :=
real.mul_self_sqrt (norm_sq_nonneg _)
@[simp] lemma abs_zero : absK 0 = 0 := by simp [abs]
@[simp] lemma abs_one : absK 1 = 1 := by simp [abs]
@[simp] lemma abs_two : absK 2 = 2 :=
calc absK 2 = absK (2 : ℝ) : by rw [of_real_bit0, of_real_one]
... = (2 : ℝ) : abs_of_nonneg (by norm_num)
lemma abs_nonneg (z : K) : 0 ≤ absK z :=
real.sqrt_nonneg _
@[simp] lemma abs_eq_zero {z : K} : absK z = 0 ↔ z = 0 :=
(real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero
lemma abs_ne_zero {z : K} : abs z ≠ 0 ↔ z ≠ 0 :=
not_congr abs_eq_zero
@[simp] lemma abs_conj (z : K) : abs (conj z) = abs z :=
by simp [abs]
@[simp] lemma abs_mul (z w : K) : abs (z * w) = abs z * abs w :=
by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl
lemma abs_re_le_abs (z : K) : abs' (re z) ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (re z)) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply re_sq_le_norm_sq
lemma abs_im_le_abs (z : K) : abs' (im z) ≤ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (im z)) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply im_sq_le_norm_sq
lemma re_le_abs (z : K) : re z ≤ abs z :=
(abs_le.1 (abs_re_le_abs _)).2
lemma im_le_abs (z : K) : im z ≤ abs z :=
(abs_le.1 (abs_im_le_abs _)).2
lemma im_eq_zero_of_le {a : K} (h : abs a ≤ re a) : im a = 0 :=
begin
rw ← zero_eq_mul_self,
have : re a * re a = re a * re a + im a * im a,
{ convert is_R_or_C.mul_self_abs a;
linarith [re_le_abs a] },
linarith
end
lemma re_eq_self_of_le {a : K} (h : abs a ≤ re a) : (re a : K) = a :=
by { rw ← re_add_im a, simp [im_eq_zero_of_le h] }
lemma abs_add (z w : K) : abs (z + w) ≤ abs z + abs w :=
(mul_self_le_mul_self_iff (abs_nonneg _)
(add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $
begin
rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs,
add_right_comm, norm_sq_add, add_le_add_iff_left,
mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)],
simpa [-mul_re] using re_le_abs (z * conj w)
end
instance : is_absolute_value absK :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
@[simp] lemma abs_abs (z : K) : abs' (abs z) = abs z :=
_root_.abs_of_nonneg (abs_nonneg _)
@[simp] lemma abs_pos {z : K} : 0 < abs z ↔ z ≠ 0 := abv_pos abs
@[simp] lemma abs_neg : ∀ z : K, abs (-z) = abs z := abv_neg abs
lemma abs_sub : ∀ z w : K, abs (z - w) = abs (w - z) := abv_sub abs
lemma abs_sub_le : ∀ a b c : K, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs
@[simp] theorem abs_inv : ∀ z : K, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs
@[simp] theorem abs_div : ∀ z w : K, abs (z / w) = abs z / abs w := abv_div abs
lemma abs_abs_sub_le_abs_sub : ∀ z w : K, abs' (abs z - abs w) ≤ abs (z - w) :=
abs_abv_sub_le_abv_sub abs
lemma abs_re_div_abs_le_one (z : K) : abs' (re z / abs z) ≤ 1 :=
begin
by_cases hz : z = 0,
{ simp [hz, zero_le_one] },
{ simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] }
end
lemma abs_im_div_abs_le_one (z : K) : abs' (im z / abs z) ≤ 1 :=
begin
by_cases hz : z = 0,
{ simp [hz, zero_le_one] },
{ simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] }
end
@[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : K) = n :=
by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)]
lemma norm_sq_eq_abs (x : K) : norm_sq x = abs x ^ 2 :=
by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)]
lemma re_eq_abs_of_mul_conj (x : K) : re (x * (conj x)) = abs (x * (conj x)) :=
by rw [mul_conj, of_real_re, abs_of_real, norm_sq_eq_abs, pow_two, _root_.abs_mul, abs_abs]
lemma abs_sqr_re_add_conj (x : K) : (abs (x + x†))^2 = (re (x + x†))^2 :=
by simp [pow_two, ←norm_sq_eq_abs, norm_sq]
lemma abs_sqr_re_add_conj' (x : K) : (abs (x† + x))^2 = (re (x† + x))^2 :=
by simp [pow_two, ←norm_sq_eq_abs, norm_sq]
lemma conj_mul_eq_norm_sq_left (x : K) : x† * x = ((norm_sq x) : K) :=
begin
rw ext_iff,
refine ⟨by simp [of_real_re, mul_re, conj_re, conj_im, norm_sq],_⟩,
simp [of_real_im, mul_im, conj_im, conj_re, mul_comm],
end
/-- The real part in a `is_R_or_C` field, as a continuous linear map. -/
noncomputable def re_clm : K →L[ℝ] ℝ :=
re_lm.mk_continuous 1 $ by { simp only [norm_eq_abs, re_lm_coe, one_mul], exact abs_re_le_abs }
@[simp] lemma norm_re_clm : ∥(re_clm : K →L[ℝ] ℝ)∥ = 1 :=
begin
apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _),
convert continuous_linear_map.ratio_le_op_norm _ (1 : K),
simp,
end
@[simp, norm_cast] lemma re_clm_coe : ((re_clm : K →L[ℝ] ℝ) : K →ₗ[ℝ] ℝ) = re_lm := rfl
@[simp] lemma re_clm_apply : ((re_clm : K →L[ℝ] ℝ) : K → ℝ) = re := rfl
/-! ### Cauchy sequences -/
theorem is_cau_seq_re (f : cau_seq K abs) : is_cau_seq abs' (λ n, re (f n)) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij)
theorem is_cau_seq_im (f : cau_seq K abs) : is_cau_seq abs' (λ n, im (f n)) :=
λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij,
lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij)
/-- The real part of a K Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_re (f : cau_seq K abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_re f⟩
/-- The imaginary part of a K Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_im (f : cau_seq K abs) : cau_seq ℝ abs' :=
⟨_, is_cau_seq_im f⟩
lemma is_cau_seq_abs {f : ℕ → K} (hf : is_cau_seq abs f) :
is_cau_seq abs' (abs ∘ f) :=
λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in
⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩
@[simp, norm_cast, priority 900] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) :
((∏ i in s, f i : ℝ) : K) = ∏ i in s, (f i : K) :=
ring_hom.map_prod _ _ _
@[simp, norm_cast, priority 900] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) :
((∑ i in s, f i : ℝ) : K) = ∑ i in s, (f i : K) :=
ring_hom.map_sum _ _ _
@[simp, norm_cast] lemma of_real_finsupp_sum
{α M : Type*} [has_zero M] (f : α →₀ M) (g : α → M → ℝ) :
((f.sum (λ a b, g a b) : ℝ) : K) = f.sum (λ a b, ((g a b) : K)) :=
ring_hom.map_finsupp_sum _ f g
@[simp, norm_cast] lemma of_real_finsupp_prod
{α M : Type*} [has_zero M] (f : α →₀ M) (g : α → M → ℝ) :
((f.prod (λ a b, g a b) : ℝ) : K) = f.prod (λ a b, ((g a b) : K)) :=
ring_hom.map_finsupp_prod _ f g
end is_R_or_C
namespace finite_dimensional
variables {K : Type*} [is_R_or_C K]
open_locale classical
open is_R_or_C
/-- This instance generates a type-class problem with a metavariable `?m` that should satisfy
`is_R_or_C ?m`. Since this can only be satisfied by `ℝ` or `ℂ`, this does not cause problems. -/
library_note "is_R_or_C instance"
/-- An `is_R_or_C` field is finite-dimensional over `ℝ`, since it is spanned by `{1, I}`. -/
@[nolint dangerous_instance] instance is_R_or_C_to_real : finite_dimensional ℝ K :=
finite_dimensional.iff_fg.mpr ⟨{1, I},
begin
rw eq_top_iff,
intros a _,
rw [finset.coe_insert, finset.coe_singleton, submodule.mem_span_insert],
refine ⟨re a, (im a) • I, _, _⟩,
{ rw submodule.mem_span_singleton,
use im a },
simp [re_add_im a, algebra.smul_def, algebra_map_eq_of_real]
end⟩
/-- Over an `is_R_or_C` field, we can register the properness of finite-dimensional normed spaces as
an instance. -/
@[priority 900, nolint dangerous_instance] instance proper_is_R_or_C -- note [is_R_or_C instance]
{E : Type*} [normed_group E] [normed_space K E] [finite_dimensional K E] :
proper_space E :=
begin
letI : normed_space ℝ E := restrict_scalars.normed_space ℝ K E,
letI : is_scalar_tower ℝ K E := restrict_scalars.is_scalar_tower _ _ _,
letI : finite_dimensional ℝ E := finite_dimensional.trans ℝ K E,
apply_instance
end
end finite_dimensional
section instances
noncomputable instance real.is_R_or_C : is_R_or_C ℝ :=
{ re := add_monoid_hom.id ℝ,
im := 0,
conj := ring_hom.id ℝ,
I := 0,
I_re_ax := by simp only [add_monoid_hom.map_zero],
I_mul_I_ax := or.intro_left _ rfl,
re_add_im_ax := λ z, by unfold_coes; simp [add_zero, id.def, mul_zero],
of_real_re_ax := λ r, by simp only [add_monoid_hom.id_apply, algebra.id.map_eq_self],
of_real_im_ax := λ r, by simp only [add_monoid_hom.zero_apply],
mul_re_ax := λ z w,
by simp only [sub_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply],
mul_im_ax := λ z w, by simp only [add_zero, zero_mul, mul_zero, add_monoid_hom.zero_apply],
conj_re_ax := λ z, by simp only [ring_hom.id_apply],
conj_im_ax := λ z, by simp only [neg_zero, add_monoid_hom.zero_apply],
conj_I_ax := by simp only [ring_hom.map_zero, neg_zero],
norm_sq_eq_def_ax := λ z, by simp only [pow_two, norm, ←abs_mul, abs_mul_self z, add_zero, mul_zero,
add_monoid_hom.zero_apply, add_monoid_hom.id_apply],
mul_im_I_ax := λ z, by simp only [mul_zero, add_monoid_hom.zero_apply],
inv_def_ax := λ z, by simp [pow_two, real.norm_eq_abs, abs_mul_abs_self, ← div_eq_mul_inv],
div_I_ax := λ z, by simp only [div_zero, mul_zero, neg_zero]}
noncomputable instance complex.is_R_or_C : is_R_or_C ℂ :=
{ re := ⟨complex.re, complex.zero_re, complex.add_re⟩,
im := ⟨complex.im, complex.zero_im, complex.add_im⟩,
conj := complex.conj,
I := complex.I,
I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re],
I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true],
re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im,
complex.coe_algebra_map, complex.of_real_eq_coe],
of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re,
complex.coe_algebra_map, complex.of_real_eq_coe],
of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im,
complex.coe_algebra_map, complex.of_real_eq_coe],
mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk],
mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im],
conj_re_ax := λ z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re],
conj_im_ax := λ z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk],
conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk],
norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply,
add_monoid_hom.coe_mk, complex.norm_eq_abs],
mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im],
inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map,
complex.of_real_eq_coe, complex.norm_eq_abs],
div_I_ax := complex.div_I }
end instances
namespace is_R_or_C
section cleanup_lemmas
local notation `reR` := @is_R_or_C.re ℝ _
local notation `imR` := @is_R_or_C.im ℝ _
local notation `conjR` := @is_R_or_C.conj ℝ _
local notation `IR` := @is_R_or_C.I ℝ _
local notation `absR` := @is_R_or_C.abs ℝ _
local notation `norm_sqR` := @is_R_or_C.norm_sq ℝ _
local notation `reC` := @is_R_or_C.re ℂ _
local notation `imC` := @is_R_or_C.im ℂ _
local notation `conjC` := @is_R_or_C.conj ℂ _
local notation `IC` := @is_R_or_C.I ℂ _
local notation `absC` := @is_R_or_C.abs ℂ _
local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _
@[simp] lemma re_to_real {x : ℝ} : reR x = x := rfl
@[simp] lemma im_to_real {x : ℝ} : imR x = 0 := rfl
@[simp] lemma conj_to_real {x : ℝ} : conjR x = x := rfl
@[simp] lemma I_to_real : IR = 0 := rfl
@[simp] lemma norm_sq_to_real {x : ℝ} : norm_sqR x = x*x := by simp [is_R_or_C.norm_sq]
@[simp] lemma abs_to_real {x : ℝ} : absR x = _root_.abs x :=
by simp [is_R_or_C.abs, abs, real.sqrt_mul_self_eq_abs]
@[simp] lemma coe_real_eq_id : @coe ℝ ℝ _ = id := rfl
@[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl
@[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl
@[simp] lemma conj_to_complex {x : ℂ} : conjC x = x.conj := rfl
@[simp] lemma I_to_complex : IC = complex.I := rfl
@[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x :=
by simp [is_R_or_C.norm_sq, complex.norm_sq]
@[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x :=
by simp [is_R_or_C.abs, complex.abs]
end cleanup_lemmas
end is_R_or_C
|
d17168ae22460748ff22f7e1fe4b937f37cf5764 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/order/filter/bases.lean | c4b3da27a123a5e07af86b3e497ee4c89f1e4a5c | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 30,750 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import order.filter.basic
import data.set.countable
/-!
# Filter bases
A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α`
such that the intersection of two elements of this collection contains some element of
the collection. Compared to filters, filter bases do not require that any set containing
an element of `B` belongs to `B`.
A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs
to `B.filter` if and only if it contains an element of `B`.
Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`,
the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p`
(ie. `s '' set_of p`) defines a filter basis `h.filter_basis`.
If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop`
and `s : ι → set α` as above) means that a set belongs to `l` if and
only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and
`l = h.filter_basis.filter`. The point of this definition is that checking statements
involving elements of `l` often reduces to checking them on the basis elements.
This file also introduces more restricted classes of bases, involving monotonicity or
countability. In particular, for `l : filter α`, `l.is_countably_generated` means
there is a countable set of sets which generates `s`. This is reformulated in term of bases,
and consequences are derived.
## Main statements
* `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms
of a basis;
* `basis_sets` : all sets of a filter form a basis;
* `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`,
`has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`,
`l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively;
* `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms
of bases.
* `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate
`tendsto f l l'` in terms of bases.
* `is_countably_generated_iff_exists_antimono_basis` : proves a filter is
countably generated if and only if it admis a basis parametrized by a
decreasing sequence of sets indexed by `ℕ`.
* `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous".
## Implementation notes
As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases:
* `has_basis l s`, `s : set (set α)`;
* `has_basis l s`, `s : ι → set α`;
* `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`.
We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis
of this form. The other two can be emulated using `s = id` or `p = λ _, true`.
With this approach sometimes one needs to `simp` the statement provided by the `has_basis`
machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help
with the case `p = λ _, true`.
-/
open set filter
open_locale filter
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} {ι' : Type*}
/-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α`
such that the intersection of two elements of this collection contains some element
of the collection. -/
structure filter_basis (α : Type*) :=
(sets : set (set α))
(nonempty : sets.nonempty)
(inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y)
instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype
/-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/
@[reducible]
instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩
-- For illustration purposes, the filter basis defining (at_top : filter ℕ)
instance : inhabited (filter_basis ℕ) :=
⟨{ sets := range Ici,
nonempty := ⟨Ici 0, mem_range_self 0⟩,
inter_sets := begin
rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
refine ⟨Ici (max n m), mem_range_self _, _⟩,
rintros p p_in,
split ; rw mem_Ici at *,
exact le_of_max_le_left p_in,
exact le_of_max_le_right p_in,
end }⟩
/-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/
protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop :=
(nonempty : ∃ i, p i)
(inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j)
namespace filter
namespace is_basis
/-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/
protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α :=
{ sets := s '' set_of p,
nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, mem_image_of_mem s hi⟩,
inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩,
rcases h.inter hi hj with ⟨k, hk, hk'⟩,
exact ⟨_, mem_image_of_mem s hk, hk'⟩ } }
variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s)
lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U :=
iff.rfl
end is_basis
end filter
namespace filter_basis
/-- The filter associated to a filter basis. -/
protected def filter (B : filter_basis α) : filter α :=
{ sets := {s | ∃ t ∈ B, t ⊆ s},
univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩,
sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩,
inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩,
let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in
⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ }
lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U :=
iff.rfl
lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:=
λ U_in, ⟨U, U_in, subset.refl _⟩
lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s :=
begin
have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)),
{ rintros ⟨U, U_in⟩ ⟨V, V_in⟩,
rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩,
use [W, W_in],
finish },
ext U,
simp [mem_filter_iff, mem_infi this]
end
protected lemma generate (B : filter_basis α) : generate B.sets = B.filter :=
begin
apply le_antisymm,
{ intros U U_in,
rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩,
exact generate_sets.superset (generate_sets.basic V_in) h },
{ rw sets_iff_generate,
apply mem_filter_of_mem }
end
end filter_basis
namespace filter
namespace is_basis
variables {p : ι → Prop} {s : ι → set α}
/-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/
protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter
protected lemma mem_filter_iff (h : is_basis p s) {U : set α} :
U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U :=
begin
erw [h.filter_basis.mem_filter_iff],
simp only [mem_filter_basis_iff h, exists_prop],
split,
{ rintros ⟨_, ⟨i, pi, rfl⟩, h⟩,
tauto },
{ tauto }
end
lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} :=
by erw h.filter_basis.generate ; refl
end is_basis
/-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/
protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop :=
(mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t)
section same_type
variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι}
{p' : ι' → Prop} {s' : ι' → set α} {i' : ι'}
lemma has_basis_generate (s : set (set α)) :
(generate s).has_basis (λ t, finite t ∧ t ⊆ s) (λ t, ⋂₀ t) :=
⟨begin
intro U,
rw mem_generate_iff,
apply exists_congr,
tauto
end⟩
/-- The smallest filter basis containing a given collection of sets. -/
def filter_basis.of_sets (s : set (set α)) : filter_basis α :=
{ sets := sInter '' { t | finite t ∧ t ⊆ s},
nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩,
inter_sets := begin
rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩,
exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩,
by rw sInter_union⟩,
end }
/-- Definition of `has_basis` unfolded with implicit set argument. -/
lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t :=
hl.mem_iff' t
lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t :=
⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩
lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i :=
let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, pi⟩
protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s :=
⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩
lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l :=
(hl.mem_iff).2 ⟨i, hi, ht⟩
lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l :=
hl.mem_of_superset hi $ subset.refl _
lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s :=
{ nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, hi⟩,
inter := λ i j hi hj, by simpa [h.mem_iff] using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) }
lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l :=
by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] }
lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } :=
by rw [← h.is_basis.filter_eq_generate, h.filter_eq]
lemma generate_eq_generate_inter (s : set (set α)) : generate s = generate (sInter '' { t | finite t ∧ t ⊆ s}) :=
by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl
lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s :=
by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl
lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i)
(h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' :=
begin
constructor,
intro t,
rw hl.mem_iff,
split,
{ rintros ⟨i, pi, hi⟩,
rcases h i pi with ⟨i', pi', hi'⟩,
use [i', pi'],
tauto },
{ rintros ⟨i', pi', hi'⟩,
rcases h' i' pi' with ⟨i, pi, hi⟩,
use [i, pi],
tauto },
end
lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} :
(∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x :=
by simpa using hl.mem_iff
lemma has_basis.forall_nonempty_iff_ne_bot (hl : l.has_basis p s) :
(∀ {i}, p i → (s i).nonempty) ↔ ne_bot l :=
⟨λ H, forall_sets_nonempty_iff_ne_bot.1 $
λ s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in (H hi).mono his,
λ H i hi, H.nonempty_of_mem (hl.mem_of_mem hi)⟩
lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id :=
⟨λ t, exists_sets_subset_iff.symm⟩
lemma has_basis_self {l : filter α} {P : set α → Prop} :
has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t, (t ∈ l ↔ ∃ r ∈ l, P r ∧ r ⊆ t) :=
by simp only [has_basis_iff, exists_prop, id, and_assoc]
/-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that
`p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/
lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop}
(hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) :
l.has_basis (λ i, p i ∧ q i) s :=
begin
refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩,
rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩,
rcases hq i hpi with ⟨j, hpj, hqj, hji⟩,
exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩
end
/-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}`
is a basis of `l`. -/
lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) :
l.has_basis (λ i, p i ∧ s i ⊆ V) s :=
h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem_sets hV (h.mem_of_mem hi))).imp $
λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩
lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id)
{V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id :=
by simpa only [and_assoc] using h.restrict_subset hV
theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l :=
⟨λ h i' hi', h $ hl'.mem_of_mem hi',
λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_sets_of_superset (h _ hi') hs⟩
theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t :=
by simp only [le_def, hl.mem_iff]
theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' :=
by simp only [hl'.ge_iff, hl.mem_iff]
lemma has_basis.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s')
(h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i)
(h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' :=
begin
apply le_antisymm,
{ rw hl.le_basis_iff hl',
simpa using h' },
{ rw hl'.le_basis_iff hl,
simpa using h },
end
lemma has_basis.inf (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
(l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) :=
⟨begin
intro t,
simp only [mem_inf_sets, exists_prop, hl.mem_iff, hl'.mem_iff],
split,
{ rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, H⟩,
use [(i, i'), ⟨hi, hi'⟩, subset.trans (inter_subset_inter ht ht') H] },
{ rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩,
use [s i, i, hi, subset.refl _, s' i', i', hi', subset.refl _, H] }
end⟩
lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) :=
⟨λ U, by simp⟩
lemma has_basis.sup (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
(l ⊔ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) :=
⟨begin
intros t,
simp only [mem_sup_sets, hl.mem_iff, hl'.mem_iff, prod.exists, union_subset_iff, exists_prop,
and_assoc, exists_and_distrib_left],
simp only [← and_assoc, exists_and_distrib_right, and_comm]
end⟩
lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) :
(l ⊓ 𝓟 s').has_basis p (λ i, s i ∩ s') :=
⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq,
mem_inter_iff, and_imp]⟩
lemma has_basis.eq_binfi (h : l.has_basis p s) :
l = ⨅ i (_ : p i), 𝓟 (s i) :=
eq_binfi_of_mem_sets_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal_sets]
lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) :
l = ⨅ i, 𝓟 (s i) :=
by simpa only [infi_true] using h.eq_binfi
lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] :
(⨅ i, 𝓟 (s i)).has_basis (λ _, true) s :=
⟨begin
refine λ t, (mem_infi (h.mono_comp _ _) t).trans $
by simp only [exists_prop, true_and, mem_principal_sets],
exact λ _ _, principal_mono.2
end⟩
/-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis
of `⨅ i, 𝓟 (s i)`. -/
lemma has_basis_infi_principal_finite (s : ι → set α) :
(⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, finite t) (λ t, ⋂ i ∈ t, s i) :=
begin
refine ⟨λ U, (mem_infi_finite _).trans _⟩,
simp only [infi_principal_finset, mem_Union, mem_principal_sets, exists_prop,
exists_finite_iff_finset, finset.bInter_coe]
end
lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S)
(ne : S.nonempty) :
(⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s :=
⟨begin
refine λ t, (mem_binfi _ ne).trans $ by simp only [mem_principal_sets],
rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢,
apply h.mono_comp _ _,
exact λ _ _, principal_mono.2
end⟩
lemma has_basis_binfi_principal'
(h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) :
(⨅ i (h : p i), 𝓟 (s i)).has_basis p s :=
filter.has_basis_binfi_principal h ne
lemma has_basis.map (f : α → β) (hl : l.has_basis p s) :
(l.map f).has_basis p (λ i, f '' (s i)) :=
⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩
lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) :
(l.comap f).has_basis p (λ i, f ⁻¹' (s i)) :=
⟨begin
intro t,
simp only [mem_comap_sets, exists_prop, hl.mem_iff],
split,
{ rintros ⟨t', ⟨i, hi, ht'⟩, H⟩,
exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ },
{ rintros ⟨i, hi, H⟩,
exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ }
end⟩
lemma comap_has_basis (f : α → β) (l : filter β) :
has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) :=
⟨λ t, mem_comap_sets⟩
lemma has_basis.prod_self (hl : l.has_basis p s) :
(l ×ᶠ l).has_basis p (λ i, (s i).prod (s i)) :=
⟨begin
intro t,
apply mem_prod_iff.trans,
split,
{ rintros ⟨t₁, ht₁, t₂, ht₂, H⟩,
rcases hl.mem_iff.1 (inter_mem_sets ht₁ ht₂) with ⟨i, hi, ht⟩,
exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ },
{ rintros ⟨i, hi, H⟩,
exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ }
end⟩
lemma mem_prod_self_iff {s} : s ∈ l ×ᶠ l ↔ ∃ t ∈ l, set.prod t t ⊆ s :=
l.basis_sets.prod_self.mem_iff
lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop}
(mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) :
(∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) :=
⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩,
λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩
lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop}
(mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) :
(∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) :=
⟨λ H i hi, H (s i) $ hl.mem_of_mem hi,
λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩
lemma has_basis.sInter_sets (h : has_basis l p s) :
⋂₀ l.sets = ⋂ i ∈ set_of p, s i :=
begin
ext x,
suffices : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i,
by simpa only [mem_Inter, mem_set_of_eq, mem_sInter],
simp_rw h.mem_iff,
split,
{ intros h i hi,
exact h (s i) ⟨i, hi, subset.refl _⟩ },
{ rintros h _ ⟨i, hi, sub⟩,
exact sub (h i hi) },
end
variables [preorder ι] (l p s)
/-- `is_antimono_basis p s` means the image of `s` bounded by `p` is a filter basis
such that `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/
structure is_antimono_basis extends is_basis p s : Prop :=
(decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i)
(mono : monotone p)
/-- We say that a filter `l` has a antimono basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`,
and `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/
structure has_antimono_basis [preorder ι] (l : filter α) (p : ι → Prop) (s : ι → set α)
extends has_basis l p s : Prop :=
(decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i)
(mono : monotone p)
end same_type
section two_types
variables {la : filter α} {pa : ι → Prop} {sa : ι → set α}
{lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β}
lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) :
tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t :=
by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl }
lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) :
tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i :=
by simp only [tendsto, hlb.ge_iff, mem_map, filter.eventually]
lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) :
tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib :=
by simp [hlb.tendsto_right_iff, hla.eventually_iff]
lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) :
∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t :=
hla.tendsto_left_iff.1 H
lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) :
∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i :=
hlb.tendsto_right_iff.1 H
lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa)
(hlb : lb.has_basis pb sb) :
∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib :=
(hla.tendsto_iff hlb).1 H
lemma has_basis.prod (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) :
(la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) :=
(hla.comap prod.fst).inf (hlb.comap prod.snd)
lemma has_basis.prod' {la : filter α} {lb : filter β} {ι : Type*} {p : ι → Prop}
{sa : ι → set α} {sb : ι → set β}
(hla : la.has_basis p sa) (hlb : lb.has_basis p sb)
(h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) :
(la ×ᶠ lb).has_basis p (λ i, (sa i).prod (sb i)) :=
⟨begin
intros t,
rw mem_prod_iff,
split,
{ rintros ⟨u, u_in, v, v_in, huv⟩,
rcases hla.mem_iff.mp u_in with ⟨i, hi, si⟩,
rcases hlb.mem_iff.mp v_in with ⟨j, hj, sj⟩,
rcases h_dir hi hj with ⟨k, hk, ki, kj⟩,
use [k, hk],
calc
(sa k).prod (sb k) ⊆ (sa i).prod (sb j) : set.prod_mono ki kj
... ⊆ u.prod v : set.prod_mono si sj
... ⊆ t : huv, },
{ rintro ⟨i, hi, h⟩,
exact ⟨sa i, hla.mem_of_mem hi, sb i, hlb.mem_of_mem hi, h⟩ },
end⟩
end two_types
/-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/
def is_countably_generated (f : filter α) : Prop :=
∃ s : set (set α), countable s ∧ f = generate s
/-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/
structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop :=
(countable : countable $ set_of p)
/-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set
defined by `p` is countable. -/
structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop :=
(countable : countable $ set_of p)
/-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α`
such that the intersection of two elements of this collection contains some element
of the collection. -/
structure countable_filter_basis (α : Type*) extends filter_basis α :=
(countable : countable sets)
-- For illustration purposes, the countable filter basis defining (at_top : filter ℕ)
instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) :=
⟨{ countable := countable_range (λ n, Ici n),
..(default $ filter_basis ℕ),}⟩
lemma antimono_seq_of_seq (s : ℕ → set α) :
∃ t : ℕ → set α, (∀ i j, i ≤ j → t j ⊆ t i) ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) :=
begin
use λ n, ⋂ m ≤ n, s m, split,
{ intros i j hij a, simp, intros h i' hi'i, apply h, transitivity; assumption },
apply le_antisymm; rw le_infi_iff; intro i,
{ rw le_principal_iff, apply Inter_mem_sets (finite_le_nat _),
intros j hji, rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ },
{ apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl },
end
lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : countable B)
(Bne : B.nonempty) (f : ι → α) :
∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) :=
begin
rw countable_iff_exists_surjective_to_subtype Bne at Bcbl,
rcases Bcbl with ⟨g, gsurj⟩,
rw infi_subtype',
use (λ n, g n), apply le_antisymm; rw le_infi_iff,
{ intro i, apply infi_le_of_le (g i) _, apply le_refl _ },
{ intros a, rcases gsurj a with ⟨i, rfl⟩, apply infi_le }
end
lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : countable B) (f : ι → α)
{i₀ : ι} (h : f i₀ = ⊤) :
∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) :=
begin
cases B.eq_empty_or_nonempty with hB Bnonempty,
{ rw [hB, infi_emptyset],
use λ n, i₀,
simp [h] },
{ exact countable_binfi_eq_infi_seq Bcbl Bnonempty f }
end
lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : countable B) :
∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) :=
countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ
namespace is_countably_generated
/-- A set generating a countably generated filter. -/
def generating_set {f : filter α} (h : is_countably_generated f) :=
classical.some h
lemma countable_generating_set {f : filter α} (h : is_countably_generated f) :
countable h.generating_set :=
(classical.some_spec h).1
lemma eq_generate {f : filter α} (h : is_countably_generated f) :
f = generate h.generating_set :=
(classical.some_spec h).2
/-- A countable filter basis for a countably generated filter. -/
def countable_filter_basis {l : filter α} (h : is_countably_generated l) :
countable_filter_basis α :=
{ countable := (countable_set_of_finite_subset h.countable_generating_set).image _,
..filter_basis.of_sets (h.generating_set) }
lemma filter_basis_filter {l : filter α} (h : is_countably_generated l) :
h.countable_filter_basis.to_filter_basis.filter = l :=
begin
conv_rhs { rw h.eq_generate },
apply of_sets_filter_eq_generate,
end
lemma has_countable_basis {l : filter α} (h : is_countably_generated l) :
l.has_countable_basis (λ t, finite t ∧ t ⊆ h.generating_set) (λ t, ⋂₀ t) :=
⟨by convert has_basis_generate _ ; exact h.eq_generate,
countable_set_of_finite_subset h.countable_generating_set⟩
lemma exists_countable_infi_principal {f : filter α} (h : f.is_countably_generated) :
∃ s : set (set α), countable s ∧ f = ⨅ t ∈ s, 𝓟 t :=
begin
let B := h.countable_filter_basis,
use [B.sets, B.countable],
rw ← h.filter_basis_filter,
rw B.to_filter_basis.eq_infi_principal,
rw infi_subtype''
end
lemma exists_seq {f : filter α} (cblb : f.is_countably_generated) :
∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i) :=
begin
rcases cblb.exists_countable_infi_principal with ⟨B, Bcbl, rfl⟩,
exact countable_binfi_principal_eq_seq_infi Bcbl,
end
lemma exists_antimono_seq {f : filter α} (cblb : f.is_countably_generated) :
∃ x : ℕ → set α, (∀ ⦃i j⦄, i ≤ j → x j ⊆ x i) ∧ f = ⨅ i, 𝓟 (x i) :=
begin
rcases cblb.exists_seq with ⟨x', hx'⟩,
let x := λ n, ⋂ m ≤ n, x' m,
use x, split,
{ intros i j hij a, simp [x], intros h i' hi'i, apply h, transitivity; assumption },
subst hx', apply le_antisymm; rw le_infi_iff; intro i,
{ rw le_principal_iff, apply Inter_mem_sets (finite_le_nat _),
intros j hji, rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ },
{ apply infi_le_of_le i _, rw principal_mono, intro a, simp [x], intro h, apply h, refl },
end
lemma has_antimono_basis {f : filter α} (h : f.is_countably_generated) :
∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x :=
begin
rcases h.exists_antimono_seq with ⟨x, x_dec, rfl⟩,
refine ⟨x, has_basis_infi_principal _, _, monotone_const⟩,
exacts [directed_of_sup x_dec, λ i j _ _ h, x_dec h]
end
end is_countably_generated
lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α}
(h : f.has_countable_basis p s) :
f.is_countably_generated :=
⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩
lemma is_countably_generated_seq (x : ℕ → set α) : is_countably_generated (⨅ i, 𝓟 $ x i) :=
begin
rcases antimono_seq_of_seq x with ⟨y, am, h⟩,
rw h,
use [range y, countable_range _],
rw (has_basis_infi_principal _).eq_generate,
{ simp [range] },
{ exact directed_of_sup am },
{ use 0 },
end
lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) :
f.is_countably_generated :=
let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq
lemma is_countably_generated_binfi_principal {B : set $ set α} (h : countable B) :
is_countably_generated (⨅ (s ∈ B), 𝓟 s) :=
is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h)
lemma is_countably_generated_iff_exists_antimono_basis {f : filter α} : is_countably_generated f ↔
∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x :=
begin
split,
{ intro h,
exact h.has_antimono_basis },
{ rintros ⟨x, h⟩,
rw h.to_has_basis.eq_infi,
exact is_countably_generated_seq x },
end
namespace is_countably_generated
lemma exists_antimono_seq' {f : filter α} (cblb : f.is_countably_generated) :
∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) :=
let ⟨x, hx⟩ := is_countably_generated_iff_exists_antimono_basis.mp cblb in
⟨x, λ i j, hx.decreasing trivial trivial, λ s, by simp [hx.to_has_basis.mem_iff]⟩
protected lemma comap {l : filter β} (h : l.is_countably_generated) (f : α → β) :
(comap f l).is_countably_generated :=
begin
rcases h.exists_seq with ⟨x, hx⟩,
apply is_countably_generated_of_seq,
use λ i, f ⁻¹' x i,
calc
comap f l = comap f (⨅ i, 𝓟 (x i)) : by rw hx
... = (⨅ i, comap f $ 𝓟 $ x i) : comap_infi
... = (⨅ i, 𝓟 $ f ⁻¹' x i) : by simp_rw comap_principal,
end
end is_countably_generated
end filter
|
49c8e612c368071addd6b68fbf27e473d7f85255 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/localization/construction.lean | 6d2353242076ce70aee75d3ea0fad808da60394e | [
"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 | 13,805 | lean | /-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import category_theory.morphism_property
import category_theory.category.Quiv
/-!
# Construction of the localized category
This file constructs the localized category, obtained by formally inverting
a class of maps `W : morphism_property C` in a category `C`.
We first construct a quiver `loc_quiver W` whose objects are the same as those
of `C` and whose maps are the maps in `C` and placeholders for the formal
inverses of the maps in `W`.
The localized category `W.localization` is obtained by taking the quotient
of the path category of `loc_quiver W` by the congruence generated by four
types of relations.
The obvious functor `Q W : C ⥤ W.localization` satisfies the universal property
of the localization. Indeed, if `G : C ⥤ D` sends morphisms in `W` to isomorphisms
in `D` (i.e. we have `hG : W.is_inverted_by G`), then there exists a unique functor
`G' : W.localization ⥤ D` such that `Q W ≫ G' = G`. This `G'` is `lift G hG`.
The expected property of `lift G hG` if expressed by the lemma `fac` and the
uniqueness is expressed by `uniq`.
## References
* [P. Gabriel, M. Zisman, *Calculus of fractions and homotopy theory*][gabriel-zisman-1967]
-/
noncomputable theory
open category_theory.category
namespace category_theory
variables {C : Type*} [category C] (W : morphism_property C) {D : Type*} [category D]
namespace localization
namespace construction
/-- If `W : morphism_property C`, `loc_quiver W` is a quiver with the same objects
as `C`, and whose morphisms are those in `C` and placeholders for formal
inverses of the morphisms in `W`. -/
@[nolint has_nonempty_instance]
structure loc_quiver (W : morphism_property C) := (obj : C)
instance : quiver (loc_quiver W) :=
{ hom := λ A B, (A.obj ⟶ B.obj) ⊕ { f : B.obj ⟶ A.obj // W f} }
/-- The object in the path category of `loc_quiver W` attached to an object in
the category `C` -/
def ι_paths (X : C) : paths (loc_quiver W) := ⟨X⟩
/-- The morphism in the path category associated to a morphism in the original category. -/
@[simp]
def ψ₁ {X Y : C} (f : X ⟶ Y) : ι_paths W X ⟶ ι_paths W Y := paths.of.map (sum.inl f)
/-- The morphism in the path category corresponding to a formal inverse. -/
@[simp]
def ψ₂ {X Y : C} (w : X ⟶ Y) (hw : W w) : ι_paths W Y ⟶ ι_paths W X :=
paths.of.map (sum.inr ⟨w, hw⟩)
/-- The relations by which we take the quotient in order to get the localized category. -/
inductive relations : hom_rel (paths (loc_quiver W))
| id (X : C) :
relations (ψ₁ W (𝟙 X)) (𝟙 _)
| comp {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) :
relations (ψ₁ W (f ≫ g)) (ψ₁ W f ≫ ψ₁ W g)
| Winv₁ {X Y : C} (w : X ⟶ Y) (hw : W w) :
relations (ψ₁ W w ≫ ψ₂ W w hw) (𝟙 _)
| Winv₂ {X Y : C} (w : X ⟶ Y) (hw : W w) :
relations (ψ₂ W w hw ≫ ψ₁ W w) (𝟙 _)
end construction
end localization
namespace morphism_property
open localization.construction
/-- The localized category obtained by formally inverting the morphisms
in `W : morphism_property C` -/
@[derive category, nolint has_nonempty_instance]
def localization := category_theory.quotient (localization.construction.relations W)
/-- The obvious functor `C ⥤ W.localization` -/
def Q : C ⥤ W.localization :=
{ obj := λ X, (quotient.functor _).obj (paths.of.obj ⟨X⟩),
map := λ X Y f, (quotient.functor _).map (ψ₁ W f),
map_id' := λ X, quotient.sound _ (relations.id X),
map_comp' := λ X Z Y f g, quotient.sound _ (relations.comp f g), }
end morphism_property
namespace localization
namespace construction
variable {W}
/-- The isomorphism in `W.localization` associated to a morphism `w` in W -/
def Wiso {X Y : C} (w : X ⟶ Y) (hw : W w) : iso (W.Q.obj X) (W.Q.obj Y) :=
{ hom := W.Q.map w,
inv := (quotient.functor _).map (paths.of.map (sum.inr ⟨w, hw⟩)),
hom_inv_id' := quotient.sound _ (relations.Winv₁ w hw),
inv_hom_id' := quotient.sound _ (relations.Winv₂ w hw), }
/-- The formal inverse in `W.localization` of a morphism `w` in `W`. -/
abbreviation Winv {X Y : C} (w : X ⟶ Y) (hw : W w) := (Wiso w hw).inv
variable (W)
lemma _root_.category_theory.morphism_property.Q_inverts : W.is_inverted_by W.Q :=
λ X Y w hw, is_iso.of_iso (localization.construction.Wiso w hw)
variables {W} (G : C ⥤ D) (hG : W.is_inverted_by G)
include G hG
/-- The lifting of a functor to the path category of `loc_quiver W` -/
@[simps]
def lift_to_path_category : paths (loc_quiver W) ⥤ D :=
Quiv.lift
{ obj := λ X, G.obj X.obj,
map := λ X Y, begin
rintro (f|⟨g, hg⟩),
{ exact G.map f, },
{ haveI := hG g hg,
exact inv (G.map g), },
end, }
/-- The lifting of a functor `C ⥤ D` inverting `W` as a functor `W.localization ⥤ D` -/
@[simps]
def lift : W.localization ⥤ D :=
quotient.lift (relations W) (lift_to_path_category G hG)
begin
rintro ⟨X⟩ ⟨Y⟩ f₁ f₂ r,
rcases r,
tidy,
end
@[simp]
lemma fac : W.Q ⋙ lift G hG = G :=
functor.ext (λ X, rfl)
begin
intros X Y f,
simp only [functor.comp_map, eq_to_hom_refl, comp_id, id_comp],
dsimp [lift, lift_to_path_category, morphism_property.Q],
rw compose_path_to_path,
end
omit G hG
lemma uniq (G₁ G₂ : W.localization ⥤ D) (h : W.Q ⋙ G₁ = W.Q ⋙ G₂) :
G₁ = G₂ :=
begin
suffices h' : quotient.functor _ ⋙ G₁ = quotient.functor _ ⋙ G₂,
{ refine functor.ext _ _,
{ rintro ⟨⟨X⟩⟩,
apply functor.congr_obj h, },
{ rintros ⟨⟨X⟩⟩ ⟨⟨Y⟩⟩ ⟨f⟩,
apply functor.congr_hom h', }, },
{ refine paths.ext_functor _ _,
{ ext X,
cases X,
apply functor.congr_obj h, },
{ rintro ⟨X⟩ ⟨Y⟩ (f|⟨w, hw⟩),
{ simpa only using functor.congr_hom h f, },
{ have hw : W.Q.map w = (Wiso w hw).hom := rfl,
have hw' := functor.congr_hom h w,
simp only [functor.comp_map, hw] at hw',
refine functor.congr_inv_of_congr_hom _ _ _ _ _ hw',
all_goals
{ apply functor.congr_obj h, }, }, }, },
end
variable (W)
/-- The canonical bijection between objects in a category and its
localization with respect to a morphism_property `W` -/
@[simps]
def obj_equiv : C ≃ W.localization :=
{ to_fun := W.Q.obj,
inv_fun := λ X, X.as.obj,
left_inv := λ X, rfl,
right_inv := by { rintro ⟨⟨X⟩⟩, refl, }, }
variable {W}
/-- A `morphism_property` in `W.localization` is satisfied by all
morphisms in the localized category if it contains the image of the
morphisms in the original category, the inverses of the morphisms
in `W` and if it is stable under composition -/
lemma morphism_property_is_top
(P : morphism_property W.localization)
(hP₁ : ∀ ⦃X Y : C⦄ (f : X ⟶ Y), P (W.Q.map f))
(hP₂ : ∀ ⦃X Y : C⦄ (w : X ⟶ Y) (hw : W w), P (Winv w hw))
(hP₃ : P.stable_under_composition) : P = ⊤ :=
begin
ext X Y f,
split,
{ intro hf,
simp only [pi.top_apply], },
{ intro hf, clear hf,
let G : _ ⥤ W.localization := quotient.functor _,
suffices : ∀ (X₁ X₂ : C) (p : localization.construction.ι_paths W X₁ ⟶
localization.construction.ι_paths W X₂), P (G.map p),
{ rcases X with ⟨⟨X⟩⟩,
rcases Y with ⟨⟨Y⟩⟩,
simpa only [functor.image_preimage] using this _ _ (G.preimage f), },
intros X₁ X₂ p,
induction p with X₂ X₃ p g hp,
{ simpa only [functor.map_id] using hP₁ (𝟙 X₁), },
{ cases X₂,
cases X₃,
let p' : ι_paths W X₁ ⟶ ι_paths W X₂ := p,
rw [show p.cons g = p' ≫ quiver.hom.to_path g, by refl, G.map_comp],
refine hP₃ _ _ hp _,
rcases g with (g | ⟨g, hg⟩),
{ apply hP₁, },
{ apply hP₂, }, }, },
end
/-- A `morphism_property` in `W.localization` is satisfied by all
morphisms in the localized category if it contains the image of the
morphisms in the original category, if is stable under composition
and if the property is stable by passing to inverses. -/
lemma morphism_property_is_top'
(P : morphism_property W.localization)
(hP₁ : ∀ ⦃X Y : C⦄ (f : X ⟶ Y), P (W.Q.map f))
(hP₂ : ∀ ⦃X Y : W.localization⦄ (e : X ≅ Y) (he : P e.hom), P e.inv)
(hP₃ : P.stable_under_composition) : P = ⊤ :=
morphism_property_is_top P hP₁ (λ X Y w hw, hP₂ _ (by exact hP₁ w)) hP₃
namespace nat_trans_extension
variables {F₁ F₂ : W.localization ⥤ D} (τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂)
include τ
/-- If `F₁` and `F₂` are functors `W.localization ⥤ D` and if we have
`τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂`, we shall define a natural transformation `F₁ ⟶ F₂`.
This is the `app` field of this natural transformation. -/
def app (X : W.localization) : F₁.obj X ⟶ F₂.obj X :=
eq_to_hom (congr_arg F₁.obj ((obj_equiv W).right_inv X).symm) ≫
τ.app ((obj_equiv W).inv_fun X) ≫ eq_to_hom (congr_arg F₂.obj ((obj_equiv W).right_inv X))
@[simp]
lemma app_eq (X : C) : (app τ) (W.Q.obj X) = τ.app X :=
by simpa only [app, eq_to_hom_refl, comp_id, id_comp]
end nat_trans_extension
/-- If `F₁` and `F₂` are functors `W.localization ⥤ D`, a natural transformation `F₁ ⟶ F₂`
can be obtained from a natural transformation `W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂`. -/
@[simps]
def nat_trans_extension {F₁ F₂ : W.localization ⥤ D} (τ : W.Q ⋙ F₁ ⟶ W.Q ⋙ F₂) :
F₁ ⟶ F₂ :=
{ app := nat_trans_extension.app τ,
naturality' := λ X Y f, begin
have h := morphism_property_is_top'
(morphism_property.naturality_property (nat_trans_extension.app τ)) _
(morphism_property.naturality_property.is_stable_under_inverse _)
(morphism_property.naturality_property.is_stable_under_composition _), swap,
{ intros X Y f,
simpa only [morphism_property.naturality_property, nat_trans_extension.app_eq]
using τ.naturality f, },
have hf : (⊤ : morphism_property _) f := by simp only [pi.top_apply],
simpa only [← h] using hf,
end, }
@[simp]
lemma nat_trans_extension_hcomp {F G : W.localization ⥤ D} (τ : W.Q ⋙ F ⟶ W.Q ⋙ G) :
(𝟙 W.Q) ◫ nat_trans_extension τ = τ :=
begin
ext X,
simp only [nat_trans.hcomp_app, nat_trans.id_app, G.map_id, comp_id,
nat_trans_extension_app, nat_trans_extension.app_eq],
end
lemma nat_trans_hcomp_injective {F G : W.localization ⥤ D} {τ₁ τ₂ : F ⟶ G}
(h : 𝟙 W.Q ◫ τ₁ = 𝟙 W.Q ◫ τ₂) : τ₁ = τ₂ :=
begin
ext X,
have eq := (obj_equiv W).right_inv X,
simp only [obj_equiv] at eq,
rw [← eq, ← nat_trans.id_hcomp_app, ← nat_trans.id_hcomp_app, h],
end
variables (W D)
namespace whiskering_left_equivalence
/-- The functor `(W.localization ⥤ D) ⥤ (W.functors_inverting D)` induced by the
composition with `W.Q : C ⥤ W.localization`. -/
@[simps]
def functor : (W.localization ⥤ D) ⥤ (W.functors_inverting D) :=
full_subcategory.lift _ ((whiskering_left _ _ D).obj W.Q)
(λ F, morphism_property.is_inverted_by.of_comp W W.Q W.Q_inverts _)
/-- The function `(W.functors_inverting D) ⥤ (W.localization ⥤ D)` induced by
`construction.lift`. -/
@[simps]
def inverse : (W.functors_inverting D) ⥤ (W.localization ⥤ D) :=
{ obj := λ G, lift G.obj G.property,
map := λ G₁ G₂ τ, nat_trans_extension (eq_to_hom (by rw fac) ≫ τ ≫ eq_to_hom (by rw fac)),
map_id' := λ G, nat_trans_hcomp_injective begin
rw nat_trans_extension_hcomp,
ext X,
simpa only [nat_trans.comp_app, eq_to_hom_app, eq_to_hom_refl, comp_id, id_comp,
nat_trans.hcomp_id_app, nat_trans.id_app, functor.map_id],
end,
map_comp' := λ G₁ G₂ G₃ τ₁ τ₂, nat_trans_hcomp_injective begin
ext X,
simpa only [nat_trans_extension_hcomp, nat_trans.comp_app, eq_to_hom_app, eq_to_hom_refl,
id_comp, comp_id, nat_trans.hcomp_app, nat_trans.id_app, functor.map_id,
nat_trans_extension_app, nat_trans_extension.app_eq],
end, }
/-- The unit isomorphism of the equivalence of categories `whiskering_left_equivalence W D`. -/
@[simps]
def unit_iso : 𝟭 (W.localization ⥤ D) ≅ functor W D ⋙ inverse W D := eq_to_iso
begin
refine functor.ext (λ G, _) (λ G₁ G₂ τ, _),
{ apply uniq,
dsimp [functor],
rw fac, },
{ apply nat_trans_hcomp_injective,
ext X,
simp only [functor.id_map, nat_trans.hcomp_app, comp_id, functor.comp_map,
inverse_map, nat_trans.comp_app, eq_to_hom_app, eq_to_hom_refl, nat_trans_extension_app,
nat_trans_extension.app_eq, functor_map_app, id_comp], },
end
/-- The counit isomorphism of the equivalence of categories `whiskering_left_equivalence W D`. -/
@[simps]
def counit_iso : inverse W D ⋙ functor W D ≅ 𝟭 (W.functors_inverting D) := eq_to_iso
begin
refine functor.ext _ _,
{ rintro ⟨G, hG⟩,
ext1,
apply fac, },
{ rintros ⟨G₁, hG₁⟩ ⟨G₂, hG₂⟩ f,
ext X,
apply nat_trans_extension.app_eq, },
end
end whiskering_left_equivalence
/-- The equivalence of categories `(W.localization ⥤ D) ≌ (W.functors_inverting D)`
induced by the composition with `W.Q : C ⥤ W.localization`. -/
def whiskering_left_equivalence : (W.localization ⥤ D) ≌ W.functors_inverting D :=
{ functor := whiskering_left_equivalence.functor W D,
inverse := whiskering_left_equivalence.inverse W D,
unit_iso := whiskering_left_equivalence.unit_iso W D,
counit_iso := whiskering_left_equivalence.counit_iso W D,
functor_unit_iso_comp' := λ F, begin
ext X,
simpa only [eq_to_hom_app, whiskering_left_equivalence.unit_iso_hom,
whiskering_left_equivalence.counit_iso_hom, eq_to_hom_map, eq_to_hom_trans,
eq_to_hom_refl],
end, }
end construction
end localization
end category_theory
|
4a451fcc7a6aea135b6cb2a2fa651999e21a3fdc | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/sheaves/limits_auto.lean | fcf66e4b82b81e05ed80a6c69414c9fde1c6e7c0 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,015 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.sheaves.presheaf
import Mathlib.category_theory.limits.functor_category
import Mathlib.PostPort
universes v u
namespace Mathlib
/-!
# Presheaves in `C` have limits and colimits when `C` does.
-/
namespace Top
protected instance presheaf.category_theory.limits.has_limits {C : Type u}
[category_theory.category C] [category_theory.limits.has_limits C] (X : Top) :
category_theory.limits.has_limits (presheaf C X) :=
id category_theory.limits.functor_category_has_limits
protected instance presheaf.category_theory.limits.has_colimits {C : Type u}
[category_theory.category C] [category_theory.limits.has_colimits C] (X : Top) :
category_theory.limits.has_colimits (presheaf C X) :=
id category_theory.limits.functor_category_has_colimits
end Mathlib |
2bbcb4409480d5bee217fcb7b8fd51072b8fb60f | 2caa8cd2737f8e6ea2ec83101247ef95d28a4406 | /src/chapter1.lean | 54f1a395c097c6bba2794ec2d5207c7e1f777e11 | [] | no_license | ruler501/DescriptiveSetTheory | 1a079368bf2b06fbcba6864f31f4d3ff2a89195c | 08a91bcd1533a88a28c2fac45d26ff223de2e9e6 | refs/heads/master | 1,676,123,700,591 | 1,610,658,976,000 | 1,610,658,976,000 | 327,178,014 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,302 | lean | import topology.basic
import topology.metric_space.basic
import topology.separation
noncomputable theory
open set classical topological_space
open_locale classical
universes u
variables {α : Type u}
def metric_space.to_topological_space {α : Type u} (m : metric_space α) : topological_space α :=
m.to_uniform_space.to_topological_space
class metrizable_space (α : Type u) [t : topological_space α] : Prop :=
(metrizable : ∃(m : metric_space α), m.to_topological_space = t)
instance metrizable_space.to_metric_space {α : Type u} [t : topological_space α] : has_coe (metrizable_space α) (metric_space α) :=
⟨λ (m : metrizable_space α), classical.some m.metrizable⟩
instance metrizable_space.to_uniform_space {α : Type u} [t : topological_space α] : has_coe (metrizable_space α) (uniform_space α) :=
⟨λ (m : metrizable_space α), (classical.some m.metrizable).to_uniform_space⟩
class completely_metrizable_space (α : Type u) [t : topological_space α]: Prop :=
(to_metrizable_space : @metrizable_space α t)
(to_complete_space : @complete_space α to_metrizable_space)
class polish_space (α : Type u) [t : topological_space α] : Prop :=
(to_completely_metrizable : completely_metrizable_space α)
(to_second_countable : second_countable_topology α) |
8bb6824a6052ea7ed617aa7ca58936f760be92dc | cabd1ea95170493667c024ef2045eb86d981b133 | /src/super/simp.lean | 8fcfd9b4c97b917fc6a4adcce548ab13db10ffe2 | [] | no_license | semorrison/super | 31db4b5aa5ef4c2313dc5803b8c79a95f809815b | 0c6c03ba9c7470f801eb4d055294f424ff090308 | refs/heads/master | 1,630,272,140,541 | 1,511,054,739,000 | 1,511,054,756,000 | 114,317,807 | 0 | 0 | null | 1,513,304,776,000 | 1,513,304,775,000 | null | UTF-8 | Lean | false | false | 1,502 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .clause_ops .prover_state
open tactic monad
namespace super
meta def prove_using_assumption : tactic unit := do
tgt ← target,
ass ← mk_local_def `h tgt,
exact ass
meta def simplify_capturing_assumptions (type : expr) : tactic (expr × expr × list expr) := do
S ← simp_lemmas.mk_default,
(type', heq) ← simplify S [] type,
hyps ← return $ contained_lconsts type,
hyps' ← return $ contained_lconsts_list [type', heq],
add_hyps ← return $ list.filter (λn : expr, ¬hyps.contains n.local_uniq_name) hyps'.values,
return (type', heq, add_hyps)
meta def try_simplify_left (c : clause) (i : ℕ) : tactic (list clause) :=
on_left_at c i $ λtype, do
(type', heq, add_hyps) ← simplify_capturing_assumptions type,
hyp ← mk_local_def `h type',
prf ← mk_eq_mpr heq hyp,
return [(hyp::add_hyps, prf)]
meta def try_simplify_right (c : clause) (i : ℕ) : tactic (list clause) :=
on_right_at' c i $ λhyp, do
(type', heq, add_hyps) ← simplify_capturing_assumptions hyp.local_type,
heqtype ← infer_type heq,
heqsymm ← mk_eq_symm heq,
prf ← mk_eq_mpr heqsymm hyp,
return [(add_hyps, prf)]
meta def simp_inf : inf_decl := inf_decl.mk 40 $ assume given, sequence' $ do
r ← [try_simplify_right, try_simplify_left],
i ← list.range given.c.num_lits,
[inf_if_successful 2 given (r given.c i)]
end super
|
20add835fdb326749f7cc480d279cd8442c00091 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Init/Data/ByteArray/Basic.lean | 23af8ec4d898097a62c23b132cf7376b64fef55b | [
"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,675 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Data.Array.Basic
import Init.Data.Array.Subarray
import Init.Data.UInt
import Init.Data.Option.Basic
universe u
structure ByteArray where
data : Array UInt8
attribute [extern "lean_byte_array_mk"] ByteArray.mk
attribute [extern "lean_byte_array_data"] ByteArray.data
namespace ByteArray
@[extern "lean_mk_empty_byte_array"]
def mkEmpty (c : @& Nat) : ByteArray :=
{ data := #[] }
def empty : ByteArray := mkEmpty 0
instance : Inhabited ByteArray := ⟨empty⟩
@[extern "lean_byte_array_push"]
def push : ByteArray → UInt8 → ByteArray
| ⟨bs⟩, b => ⟨bs.push b⟩
@[extern "lean_byte_array_size"]
def size : (@& ByteArray) → Nat
| ⟨bs⟩ => bs.size
@[extern "lean_byte_array_get"]
def get! : (@& ByteArray) → (@& Nat) → UInt8
| ⟨bs⟩, i => bs.get! i
@[extern "lean_byte_array_set"]
def set! : ByteArray → (@& Nat) → UInt8 → ByteArray
| ⟨bs⟩, i, b => ⟨bs.set! i b⟩
def isEmpty (s : ByteArray) : Bool :=
s.size == 0
/--
Copy the slice at `[srcOff, srcOff + len)` in `src` to `[destOff, destOff + len)` in `dest`, growing `dest` if necessary.
If `exact` is `false`, the capacity will be doubled when grown. -/
@[extern "lean_byte_array_copy_slice"]
def copySlice (src : @& ByteArray) (srcOff : Nat) (dest : ByteArray) (destOff len : Nat) (exact : Bool := true) : ByteArray :=
⟨dest.data.extract 0 destOff ++ src.data.extract srcOff len ++ dest.data.extract (destOff + len) dest.data.size⟩
def extract (a : ByteArray) (b e : Nat) : ByteArray :=
a.copySlice b empty 0 (e - b)
protected def append (a : ByteArray) (b : ByteArray) : ByteArray :=
-- we assume that `append`s may be repeated, so use asymptotic growing; use `copySlice` directly to customize
b.copySlice 0 a a.size b.size false
instance : Append ByteArray := ⟨ByteArray.append⟩
partial def toList (bs : ByteArray) : List UInt8 :=
let rec loop (i : Nat) (r : List UInt8) :=
if i < bs.size then
loop (i+1) (bs.get! i :: r)
else
r.reverse
loop 0 []
@[inline] partial def findIdx? (a : ByteArray) (p : UInt8 → Bool) (start := 0) : Option Nat :=
let rec @[specialize] loop (i : Nat) :=
if i < a.size then
if p (a.get! i) then some i else loop (i+1)
else
none
loop start
end ByteArray
def List.toByteArray (bs : List UInt8) : ByteArray :=
let rec loop
| [], r => r
| b::bs, r => loop bs (r.push b)
loop bs ByteArray.empty
instance : ToString ByteArray := ⟨fun bs => bs.toList.toString⟩
|
05bd74e3f610a0b6d88ba86fbb4e9fc2459c9f49 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/analysis/box_integral/partition/additive.lean | e16b9a790d099a14e40aff0d7d9e3dbd8131309a | [
"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 | 9,752 | 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 analysis.box_integral.partition.split
import analysis.normed_space.operator_norm
import data.set.intervals.proj_Icc
/-!
# Box additive functions
We say that a function `f : box ι → M` from boxes in `ℝⁿ` to a commutative additive monoid `M` is
*box additive* on subboxes of `I₀ : with_top (box ι)` if for any box `J`, `↑J ≤ I₀`, and a partition
`π` of `J`, `f J = ∑ J' in π.boxes, f J'`. We use `I₀ : with_top (box ι)` instead of `I₀ : box ι` to
use the same definition for functions box additive on subboxes of a box and for functions box
additive on all boxes.
Examples of box-additive functions include the measure of a box and the integral of a fixed
integrable function over a box.
In this file we define box-additive functions and prove that a function such that
`f J = f (J ∩ {x | x i < y}) + f (J ∩ {x | y ≤ x i})` is box-additive.
### Tags
rectangular box, additive function
-/
noncomputable theory
open_locale classical big_operators
open function set
namespace box_integral
variables {ι M : Type*} {n : ℕ}
/-- A function on `box ι` is called box additive if for every box `J` and a partition `π` of `J`
we have `f J = ∑ Ji in π.boxes, f Ji`. A function is called box additive on subboxes of `I : box ι`
if the same property holds for `J ≤ I`. We formalize these two notions in the same definition
using `I : with_bot (box ι)`: the value `I = ⊤` corresponds to functions box additive on the whole
space. -/
structure box_additive_map (ι M : Type*) [add_comm_monoid M] (I : with_top (box ι)) :=
(to_fun : box ι → M)
(sum_partition_boxes' : ∀ J : box ι, ↑J ≤ I → ∀ π : prepartition J, π.is_partition →
∑ Ji in π.boxes, to_fun Ji = to_fun J)
localized "notation ι ` →ᵇᵃ `:25 M := box_integral.box_additive_map ι M ⊤" in box_integral
localized "notation ι ` →ᵇᵃ[`:25 I `] ` M := box_integral.box_additive_map ι M I" in box_integral
namespace box_additive_map
open box prepartition finset
variables {N : Type*} [add_comm_monoid M] [add_comm_monoid N] {I₀ : with_top (box ι)}
{I J : box ι} {i : ι}
instance : has_coe_to_fun (ι →ᵇᵃ[I₀] M) (λ _, box ι → M) := ⟨to_fun⟩
initialize_simps_projections box_integral.box_additive_map (to_fun → apply)
@[simp] lemma to_fun_eq_coe (f : ι →ᵇᵃ[I₀] M) : f.to_fun = f := rfl
@[simp] lemma coe_mk (f h) : ⇑(mk f h : ι →ᵇᵃ[I₀] M) = f := rfl
lemma coe_injective : injective (λ (f : ι →ᵇᵃ[I₀] M) x, f x) :=
by { rintro ⟨f, hf⟩ ⟨g, hg⟩ (rfl : f = g), refl }
@[simp] lemma coe_inj {f g : ι →ᵇᵃ[I₀] M} : (f : box ι → M) = g ↔ f = g :=
coe_injective.eq_iff
lemma sum_partition_boxes (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π : prepartition I}
(h : π.is_partition) :
∑ J in π.boxes, f J = f I :=
f.sum_partition_boxes' I hI π h
@[simps { fully_applied := ff }] instance : has_zero (ι →ᵇᵃ[I₀] M) :=
⟨⟨0, λ I hI π hπ, sum_const_zero⟩⟩
instance : inhabited (ι →ᵇᵃ[I₀] M) := ⟨0⟩
instance : has_add (ι →ᵇᵃ[I₀] M) :=
⟨λ f g, ⟨f + g, λ I hI π hπ,
by simp only [pi.add_apply, sum_add_distrib, sum_partition_boxes _ hI hπ]⟩⟩
instance {R} [monoid R] [distrib_mul_action R M] : has_smul R (ι →ᵇᵃ[I₀] M) :=
⟨λ r f, ⟨r • f, λ I hI π hπ,
by simp only [pi.smul_apply, ←smul_sum, sum_partition_boxes _ hI hπ]⟩⟩
instance : add_comm_monoid (ι →ᵇᵃ[I₀] M) :=
function.injective.add_comm_monoid _ coe_injective rfl (λ _ _, rfl) (λ _ _, rfl)
@[simp] lemma map_split_add (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) (i : ι) (x : ℝ) :
(I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I :=
by rw [← f.sum_partition_boxes hI (is_partition_split I i x), sum_split_boxes]
/-- If `f` is box-additive on subboxes of `I₀`, then it is box-additive on subboxes of any
`I ≤ I₀`. -/
@[simps] def restrict (f : ι →ᵇᵃ[I₀] M) (I : with_top (box ι)) (hI : I ≤ I₀) : ι →ᵇᵃ[I] M :=
⟨f, λ J hJ, f.2 J (hJ.trans hI)⟩
/-- If `f : box ι → M` is box additive on partitions of the form `split I i x`, then it is box
additive. -/
def of_map_split_add [fintype ι] (f : box ι → M) (I₀ : with_top (box ι))
(hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ {i x}, x ∈ Ioo (I.lower i) (I.upper i) →
(I.split_lower i x).elim 0 f + (I.split_upper i x).elim 0 f = f I) :
ι →ᵇᵃ[I₀] M :=
begin
refine ⟨f, _⟩,
replace hf : ∀ I : box ι, ↑I ≤ I₀ → ∀ s, ∑ J in (split_many I s).boxes, f J = f I,
{ intros I hI s,
induction s using finset.induction_on with a s ha ihs, { simp },
rw [split_many_insert, inf_split, ← ihs, bUnion_boxes, sum_bUnion_boxes],
refine finset.sum_congr rfl (λ J' hJ', _),
by_cases h : a.2 ∈ Ioo (J'.lower a.1) (J'.upper a.1),
{ rw sum_split_boxes,
exact hf _ ((with_top.coe_le_coe.2 $ le_of_mem _ hJ').trans hI) h },
{ rw [split_of_not_mem_Ioo h, top_boxes, finset.sum_singleton] } },
intros I hI π hπ,
have Hle : ∀ J ∈ π, ↑J ≤ I₀, from λ J hJ, (with_top.coe_le_coe.2 $ π.le_of_mem hJ).trans hI,
rcases hπ.exists_split_many_le with ⟨s, hs⟩,
rw [← hf _ hI, ← inf_of_le_right hs, inf_split_many, bUnion_boxes, sum_bUnion_boxes],
exact finset.sum_congr rfl (λ J hJ, (hf _ (Hle _ hJ) _).symm)
end
/-- If `g : M → N` is an additive map and `f` is a box additive map, then `g ∘ f` is a box additive
map. -/
@[simps { fully_applied := ff }] def map (f : ι →ᵇᵃ[I₀] M) (g : M →+ N) :
ι →ᵇᵃ[I₀] N :=
{ to_fun := g ∘ f,
sum_partition_boxes' := λ I hI π hπ, by rw [← g.map_sum, f.sum_partition_boxes hI hπ] }
/-- If `f` is a box additive function on subboxes of `I` and `π₁`, `π₂` are two prepartitions of
`I` that cover the same part of `I`, then `∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J`. -/
lemma sum_boxes_congr [fintype ι] (f : ι →ᵇᵃ[I₀] M) (hI : ↑I ≤ I₀) {π₁ π₂ : prepartition I}
(h : π₁.Union = π₂.Union) :
∑ J in π₁.boxes, f J = ∑ J in π₂.boxes, f J :=
begin
rcases exists_split_many_inf_eq_filter_of_finite {π₁, π₂} ((finite_singleton _).insert _)
with ⟨s, hs⟩, simp only [inf_split_many] at hs,
rcases ⟨hs _ (or.inl rfl), hs _ (or.inr rfl)⟩ with ⟨h₁, h₂⟩, clear hs,
rw h at h₁,
calc ∑ J in π₁.boxes, f J = ∑ J in π₁.boxes, ∑ J' in (split_many J s).boxes, f J' :
finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _)).symm)
... = ∑ J in (π₁.bUnion (λ J, split_many J s)).boxes, f J : (sum_bUnion_boxes _ _ _).symm
... = ∑ J in (π₂.bUnion (λ J, split_many J s)).boxes, f J : by rw [h₁, h₂]
... = ∑ J in π₂.boxes, ∑ J' in (split_many J s).boxes, f J' : sum_bUnion_boxes _ _ _
... = ∑ J in π₂.boxes, f J :
finset.sum_congr rfl (λ J hJ, (f.sum_partition_boxes _ (is_partition_split_many _ _))),
exacts [(with_top.coe_le_coe.2 $ π₁.le_of_mem hJ).trans hI,
(with_top.coe_le_coe.2 $ π₂.le_of_mem hJ).trans hI]
end
section to_smul
variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E]
/-- If `f` is a box-additive map, then so is the map sending `I` to the scalar multiplication
by `f I` as a continuous linear map from `E` to itself. -/
def to_smul (f : ι →ᵇᵃ[I₀] ℝ) : ι →ᵇᵃ[I₀] (E →L[ℝ] E) :=
f.map (continuous_linear_map.lsmul ℝ ℝ).to_linear_map.to_add_monoid_hom
@[simp] lemma to_smul_apply (f : ι →ᵇᵃ[I₀] ℝ) (I : box ι) (x : E) : f.to_smul I x = f I • x := rfl
end to_smul
/-- Given a box `I₀` in `ℝⁿ⁺¹`, `f x : box (fin n) → G` is a family of functions indexed by a real
`x` and for `x ∈ [I₀.lower i, I₀.upper i]`, `f x` is box-additive on subboxes of the `i`-th face of
`I₀`, then `λ J, f (J.upper i) (J.face i) - f (J.lower i) (J.face i)` is box-additive on subboxes of
`I₀`. -/
@[simps] def {u} upper_sub_lower {G : Type u} [add_comm_group G]
(I₀ : box (fin (n + 1))) (i : fin (n + 1)) (f : ℝ → box (fin n) → G)
(fb : Icc (I₀.lower i) (I₀.upper i) → fin n →ᵇᵃ[I₀.face i] G)
(hf : ∀ x (hx : x ∈ Icc (I₀.lower i) (I₀.upper i)) J, f x J = fb ⟨x, hx⟩ J) :
fin (n + 1) →ᵇᵃ[I₀] G :=
of_map_split_add
(λ J : box (fin (n + 1)), f (J.upper i) (J.face i) - f (J.lower i) (J.face i)) I₀
begin
intros J hJ j,
rw with_top.coe_le_coe at hJ,
refine i.succ_above_cases _ _ j,
{ intros x hx,
simp only [box.split_lower_def hx, box.split_upper_def hx, update_same,
← with_bot.some_eq_coe, option.elim, box.face, (∘), update_noteq (fin.succ_above_ne _ _)],
abel },
{ clear j, intros j x hx,
have : (J.face i : with_top (box (fin n))) ≤ I₀.face i,
from with_top.coe_le_coe.2 (face_mono hJ i),
rw [le_iff_Icc, @box.Icc_eq_pi _ I₀] at hJ,
rw [hf _ (hJ J.upper_mem_Icc _ trivial), hf _ (hJ J.lower_mem_Icc _ trivial),
← (fb _).map_split_add this j x, ← (fb _).map_split_add this j x],
have hx' : x ∈ Ioo ((J.face i).lower j) ((J.face i).upper j) := hx,
simp only [box.split_lower_def hx, box.split_upper_def hx,
box.split_lower_def hx', box.split_upper_def hx',
← with_bot.some_eq_coe, option.elim, box.face_mk,
update_noteq (fin.succ_above_ne _ _).symm, sub_add_sub_comm,
update_comp_eq_of_injective _ i.succ_above.injective j x, ← hf],
simp only [box.face] }
end
end box_additive_map
end box_integral
|
597f9c31b53e20a2d07fc79237bb9432371e5d21 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/prime.lean | 2775d519b98f9c338846bc447a27a03ac0505d23 | [
"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 | 2,697 | lean | /-
Copyright (c) 2020 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import algebra.associated
import algebra.big_operators.basic
/-!
# Prime elements in rings
This file contains lemmas about prime elements of commutative rings.
-/
variables {R : Type*} [comm_cancel_monoid_with_zero R]
open finset
open_locale big_operators
/-- If `x * y = a * ∏ i in s, p i` where `p i` is always prime, then
`x` and `y` can both be written as a divisor of `a` multiplied by
a product over a subset of `s` -/
lemma mul_eq_mul_prime_prod {α : Type*} [decidable_eq α] {x y a : R} {s : finset α}
{p : α → R} (hp : ∀ i ∈ s, prime (p i)) (hx : x * y = a * ∏ i in s, p i) :
∃ (t u : finset α) (b c : R),
t ∪ u = s
∧ disjoint t u
∧ a = b * c
∧ x = b * ∏ i in t, p i
∧ y = c * ∏ i in u, p i :=
begin
induction s using finset.induction with i s his ih generalizing x y a,
{ exact ⟨∅, ∅, x, y, by simp [hx]⟩ },
{ rw [prod_insert his, ← mul_assoc] at hx,
have hpi : prime (p i), { exact hp i (mem_insert_self _ _) },
rcases ih (λ i hi, hp i (mem_insert_of_mem hi)) hx with
⟨t, u, b, c, htus, htu, hbc, rfl, rfl⟩,
have hit : i ∉ t, from λ hit, his (htus ▸ mem_union_left _ hit),
have hiu : i ∉ u, from λ hiu, his (htus ▸ mem_union_right _ hiu),
obtain ⟨d, rfl⟩ | ⟨d, rfl⟩ : p i ∣ b ∨ p i ∣ c,
from hpi.dvd_or_dvd ⟨a, by rw [← hbc, mul_comm]⟩,
{ rw [mul_assoc, mul_comm a, mul_right_inj' hpi.ne_zero] at hbc,
exact ⟨insert i t, u, d, c, by rw [insert_union, htus],
disjoint_insert_left.2 ⟨hiu, htu⟩,
by simp [hbc, prod_insert hit, mul_assoc, mul_comm, mul_left_comm]⟩ },
{ rw [← mul_assoc, mul_right_comm b, mul_left_inj' hpi.ne_zero] at hbc,
exact ⟨t, insert i u, b, d, by rw [union_insert, htus],
disjoint_insert_right.2 ⟨hit, htu⟩,
by simp [← hbc, prod_insert hiu, mul_assoc, mul_comm, mul_left_comm]⟩ } }
end
/-- If ` x * y = a * p ^ n` where `p` is prime, then `x` and `y` can both be written
as the product of a power of `p` and a divisor of `a`. -/
lemma mul_eq_mul_prime_pow {x y a p : R} {n : ℕ} (hp : prime p) (hx : x * y = a * p ^ n) :
∃ (i j : ℕ) (b c : R),
i + j = n
∧ a = b * c
∧ x = b * p ^ i
∧ y = c * p ^ j :=
begin
rcases mul_eq_mul_prime_prod (λ _ _, hp)
(show x * y = a * (range n).prod (λ _, p), by simpa) with
⟨t, u, b, c, htus, htu, rfl, rfl, rfl⟩,
exact ⟨t.card, u.card, b, c, by rw [← card_disjoint_union htu, htus, card_range], by simp⟩,
end
|
4cd091c7043e95c6b674c2cb70a0c758c543e6f1 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/real/pointwise.lean | 98e07256f07b97615e5013fe7824f0fe88119020 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,208 | 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, Eric Wieser
-/
import algebra.order.module
import data.real.basic
/-!
# Pointwise operations on sets of reals
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file relates `Inf (a • s)`/`Sup (a • s)` with `a • Inf s`/`a • Sup s` for `s : set ℝ`.
From these, it relates `⨅ i, a • f i` / `⨆ i, a • f i` with `a • (⨅ i, f i)` / `a • (⨆ i, f i)`,
and provides lemmas about distributing `*` over `⨅` and `⨆`.
# TODO
This is true more generally for conditionally complete linear order whose default value is `0`. We
don't have those yet.
-/
open set
open_locale pointwise
variables {ι : Sort*} {α : Type*} [linear_ordered_field α]
section mul_action_with_zero
variables [mul_action_with_zero α ℝ] [ordered_smul α ℝ] {a : α}
lemma real.Inf_smul_of_nonneg (ha : 0 ≤ a) (s : set ℝ) : Inf (a • s) = a • Inf s :=
begin
obtain rfl | hs := s.eq_empty_or_nonempty,
{ rw [smul_set_empty, real.Inf_empty, smul_zero] },
obtain rfl | ha' := ha.eq_or_lt,
{ rw [zero_smul_set hs, zero_smul],
exact cInf_singleton 0 },
by_cases bdd_below s,
{ exact ((order_iso.smul_left ℝ ha').map_cInf' hs h).symm },
{ rw [real.Inf_of_not_bdd_below (mt (bdd_below_smul_iff_of_pos ha').1 h),
real.Inf_of_not_bdd_below h, smul_zero] }
end
lemma real.smul_infi_of_nonneg (ha : 0 ≤ a) (f : ι → ℝ) :
a • (⨅ i, f i) = ⨅ i, a • f i :=
(real.Inf_smul_of_nonneg ha _).symm.trans $ congr_arg Inf $ (range_comp _ _).symm
lemma real.Sup_smul_of_nonneg (ha : 0 ≤ a) (s : set ℝ) : Sup (a • s) = a • Sup s :=
begin
obtain rfl | hs := s.eq_empty_or_nonempty,
{ rw [smul_set_empty, real.Sup_empty, smul_zero] },
obtain rfl | ha' := ha.eq_or_lt,
{ rw [zero_smul_set hs, zero_smul],
exact cSup_singleton 0 },
by_cases bdd_above s,
{ exact ((order_iso.smul_left ℝ ha').map_cSup' hs h).symm },
{ rw [real.Sup_of_not_bdd_above (mt (bdd_above_smul_iff_of_pos ha').1 h),
real.Sup_of_not_bdd_above h, smul_zero] }
end
lemma real.smul_supr_of_nonneg (ha : 0 ≤ a) (f : ι → ℝ) :
a • (⨆ i, f i) = ⨆ i, a • f i :=
(real.Sup_smul_of_nonneg ha _).symm.trans $ congr_arg Sup $ (range_comp _ _).symm
end mul_action_with_zero
section module
variables [module α ℝ] [ordered_smul α ℝ] {a : α}
lemma real.Inf_smul_of_nonpos (ha : a ≤ 0) (s : set ℝ) : Inf (a • s) = a • Sup s :=
begin
obtain rfl | hs := s.eq_empty_or_nonempty,
{ rw [smul_set_empty, real.Inf_empty, real.Sup_empty, smul_zero] },
obtain rfl | ha' := ha.eq_or_lt,
{ rw [zero_smul_set hs, zero_smul],
exact cInf_singleton 0 },
by_cases bdd_above s,
{ exact ((order_iso.smul_left_dual ℝ ha').map_cSup' hs h).symm },
{ rw [real.Inf_of_not_bdd_below (mt (bdd_below_smul_iff_of_neg ha').1 h),
real.Sup_of_not_bdd_above h, smul_zero] }
end
lemma real.smul_supr_of_nonpos (ha : a ≤ 0) (f : ι → ℝ) :
a • (⨆ i, f i) = ⨅ i, a • f i :=
(real.Inf_smul_of_nonpos ha _).symm.trans $ congr_arg Inf $ (range_comp _ _).symm
lemma real.Sup_smul_of_nonpos (ha : a ≤ 0) (s : set ℝ) : Sup (a • s) = a • Inf s :=
begin
obtain rfl | hs := s.eq_empty_or_nonempty,
{ rw [smul_set_empty, real.Sup_empty, real.Inf_empty, smul_zero] },
obtain rfl | ha' := ha.eq_or_lt,
{ rw [zero_smul_set hs, zero_smul],
exact cSup_singleton 0 },
by_cases bdd_below s,
{ exact ((order_iso.smul_left_dual ℝ ha').map_cInf' hs h).symm },
{ rw [real.Sup_of_not_bdd_above (mt (bdd_above_smul_iff_of_neg ha').1 h),
real.Inf_of_not_bdd_below h, smul_zero] }
end
lemma real.smul_infi_of_nonpos (ha : a ≤ 0) (f : ι → ℝ) :
a • (⨅ i, f i) = ⨆ i, a • f i :=
(real.Sup_smul_of_nonpos ha _).symm.trans $ congr_arg Sup $ (range_comp _ _).symm
end module
/-! ## Special cases for real multiplication -/
section mul
variables {r : ℝ}
lemma real.mul_infi_of_nonneg (ha : 0 ≤ r) (f : ι → ℝ) : r * (⨅ i, f i) = ⨅ i, r * f i :=
real.smul_infi_of_nonneg ha f
lemma real.mul_supr_of_nonneg (ha : 0 ≤ r) (f : ι → ℝ) : r * (⨆ i, f i) = ⨆ i, r * f i :=
real.smul_supr_of_nonneg ha f
lemma real.mul_infi_of_nonpos (ha : r ≤ 0) (f : ι → ℝ) : r * (⨅ i, f i) = ⨆ i, r * f i :=
real.smul_infi_of_nonpos ha f
lemma real.mul_supr_of_nonpos (ha : r ≤ 0) (f : ι → ℝ) : r * (⨆ i, f i) = ⨅ i, r * f i :=
real.smul_supr_of_nonpos ha f
lemma real.infi_mul_of_nonneg (ha : 0 ≤ r) (f : ι → ℝ) : (⨅ i, f i) * r = ⨅ i, f i * r :=
by simp only [real.mul_infi_of_nonneg ha, mul_comm]
lemma real.supr_mul_of_nonneg (ha : 0 ≤ r) (f : ι → ℝ) : (⨆ i, f i) * r = ⨆ i, f i * r :=
by simp only [real.mul_supr_of_nonneg ha, mul_comm]
lemma real.infi_mul_of_nonpos (ha : r ≤ 0) (f : ι → ℝ) : (⨅ i, f i) * r = ⨆ i, f i * r :=
by simp only [real.mul_infi_of_nonpos ha, mul_comm]
lemma real.supr_mul_of_nonpos (ha : r ≤ 0) (f : ι → ℝ) : (⨆ i, f i) * r = ⨅ i, f i * r :=
by simp only [real.mul_supr_of_nonpos ha, mul_comm]
end mul
|
f71d1cd5d76da943bd168b6ca78fae0708c40e97 | 562dafcca9e8bf63ce6217723b51f32e89cdcc80 | /src/super/selection.lean | 30a233c94df72dead5c4b40b3e096850410e206d | [] | no_license | digama0/super | 660801ef3edab2c046d6a01ba9bbce53e41523e8 | 976957fe46128e6ef057bc771f532c27cce5a910 | refs/heads/master | 1,606,987,814,510 | 1,498,621,778,000 | 1,498,621,778,000 | 95,626,306 | 0 | 0 | null | 1,498,621,692,000 | 1,498,621,692,000 | null | UTF-8 | Lean | false | false | 2,954 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
import .prover_state
namespace super
meta def simple_selection_strategy (f : (expr → expr → bool) → clause → list ℕ) : selection_strategy :=
take dc, do gt ← get_term_order, return $
if dc.selected.empty ∧ dc.c.num_lits > 0
then { dc with selected := f gt dc.c }
else dc
meta def dumb_selection : selection_strategy :=
simple_selection_strategy $ λgt c,
match c.lits_where clause.literal.is_neg with
| [] := list.range c.num_lits
| neg_lit::_ := [neg_lit]
end
meta def selection21 : selection_strategy :=
simple_selection_strategy $ λgt c,
let maximal_lits := list.filter_maximal (λi j,
gt (c.get_lit i).formula (c.get_lit j).formula) (list.range c.num_lits) in
if list.length maximal_lits = 1 then maximal_lits else
let neg_lits := list.filter (λi, (c.get_lit i).is_neg) (list.range c.num_lits),
maximal_neg_lits := list.filter_maximal (λi j,
gt (c.get_lit i).formula (c.get_lit j).formula) neg_lits in
if ¬maximal_neg_lits.empty then
list.taken 1 maximal_neg_lits
else
maximal_lits
meta def selection22 : selection_strategy :=
simple_selection_strategy $ λgt c,
let maximal_lits := list.filter_maximal (λi j,
gt (c.get_lit i).formula (c.get_lit j).formula) (list.range c.num_lits),
maximal_lits_neg := list.filter (λi, (c.get_lit i).is_neg) maximal_lits in
if ¬maximal_lits_neg.empty then
list.taken 1 maximal_lits_neg
else
maximal_lits
meta def clause_weight (c : derived_clause) : nat :=
(c.c.get_lits.for (λl, expr_size l.formula + if l.is_pos then 10 else 1)).sum
meta def find_minimal_by (passive : rb_map clause_id derived_clause)
{A} [has_ordering A]
(f : derived_clause → A) : clause_id :=
match rb_map.min $ rb_map.of_list $ passive.values.map $ λc, (f c, c.id) with
| some id := id
| none := nat.zero
end
meta def age_of_clause_id : name → ℕ
| (name.mk_numeral i _) := unsigned.to_nat i
| _ := 0
meta def find_minimal_weight (passive : rb_map clause_id derived_clause) : clause_id :=
find_minimal_by passive $ λc, (c.sc.priority, clause_weight c + c.sc.cost, c.sc.age, c.id)
meta def find_minimal_age (passive : rb_map clause_id derived_clause) : clause_id :=
find_minimal_by passive $ λc, (c.sc.priority, c.sc.age, c.id)
meta def weight_clause_selection : clause_selection_strategy :=
take iter, do state ← state_t.read, return $ find_minimal_weight state.passive
meta def oldest_clause_selection : clause_selection_strategy :=
take iter, do state ← state_t.read, return $ find_minimal_age state.passive
meta def age_weight_clause_selection (thr mod : ℕ) : clause_selection_strategy :=
take iter, if iter % mod < thr then
weight_clause_selection iter
else
oldest_clause_selection iter
end super
|
9d0ecaf643e978367c31ee3f7697206bc48ac448 | 1789ef53372ad44b5ce5db2341556f91c8c31395 | /src/test2.lean | 7d76689dbbe6c903d51fe214cd00bbc778eaeef7 | [] | no_license | iceplant/Mermin_Peres | d0a0f4c9f27111b3fee4e0ab5119ef1eafc59dc2 | d7ea59b5767157420b0fae9dfc09f22ad2826564 | refs/heads/master | 1,609,583,206,767 | 1,582,220,678,000 | 1,582,220,678,000 | 239,577,114 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 2,348 | lean | import data.nat.basic
import data.nat.parity
-- open_locale classical
decidable theory
-- --Do I want these to be bools or Props?
def myIsEven := nat.even
def myIsOdd (n : ℕ) := ¬ (myIsEven n)
#reduce myIsEven 2
--#eval myIsEven 2
--Alice only sees r and Bob only sees c. The strategy isn't (r,c) → (...) but two maps, r→(r1 r2 r3) and c → (c1 c2 c3)
--I'm using 0 and 1 instead of Green and Red as the two options to fill squares. This makes checking parity of strategies easier
------------METHOD 1: enumerate all the constraints as concisely as possible and reduce to show we get a contraditcion----------------------------------
def checkStrategyrc (r c : ℕ) (strategy : ((ℕ → ℕ × ℕ × ℕ) × (ℕ → ℕ × ℕ × ℕ))) : bool :=
let r1 := (strategy.1 r).1,
r2 := (strategy.1 r).2.1,
r3 := (strategy.1 r).2.2,
c1 := (strategy.2 c).1,
c2 := (strategy.2 c).2.1,
c3 := (strategy.2 c).2.2
in myIsEven(r1 + r2 + r3) ∧ myIsOdd(c1 + c2 + c3) ∧
((r = 1 ∧ c = 1 ∧ r1 = c1) ∨ (r = 1 ∧ c = 2 ∧ r2 = c1) ∨ (r = 1 ∧ c = 3 ∧ r3 = c1)
∨(r = 2 ∧ c = 1 ∧ r1 = c2) ∨ (r = 2 ∧ c = 2 ∧ r2 = c2) ∨ (r = 2 ∧ c = 3 ∧ r3 = c2)
∨(r = 3 ∧ c = 1 ∧ r1 = c3) ∨ (r = 3 ∧ c = 2 ∧ r2 = c3) ∨ (r = 3 ∧ c = 3 ∧ r3 = c3))
--checks all three conditions are met for the strategy
def checkStrategy (strategy : ((ℕ → ℕ × ℕ × ℕ) × (ℕ → ℕ × ℕ × ℕ))) : bool :=
(checkStrategyrc 1 1 strategy) ∧ (checkStrategyrc 1 2 strategy) ∧ (checkStrategyrc 1 3 strategy) ∧
(checkStrategyrc 2 1 strategy) ∧ (checkStrategyrc 2 2 strategy) ∧ (checkStrategyrc 2 3 strategy) ∧
(checkStrategyrc 3 1 strategy) ∧ (checkStrategyrc 3 2 strategy) ∧ (checkStrategyrc 3 3 strategy)
--given a strategy, we can't have it satisfy all the conditions
theorem noStrategy2 (strategy : ((ℕ → ℕ × ℕ × ℕ) × (ℕ → ℕ × ℕ × ℕ))) (r c : ℕ) : ¬ (checkStrategy (strategy)) :=
begin
intro s,
rw checkStrategy at s,
repeat {rw checkStrategyrc at s},
simp at s,
--every case here has a false equality and-ed with something else. How do I replace them with false and reduce?
--how do I tell it that we only care about the cases where r,c ∈ {1,2,3} and then do cases on those?
end |
261bae10ca7bedd94b0acba13c299e108f6c90f2 | f20db13587f4dd28a4b1fbd31953afd491691fa0 | /library/init/data/list/instances.lean | 3f97970844b26e5412628ac7303d8a35b939b057 | [
"Apache-2.0"
] | permissive | AHartNtkn/lean | 9a971edfc6857c63edcbf96bea6841b9a84cf916 | 0d83a74b26541421fc1aa33044c35b03759710ed | refs/heads/master | 1,620,592,591,236 | 1,516,749,881,000 | 1,516,749,881,000 | 118,697,288 | 1 | 0 | null | 1,516,759,470,000 | 1,516,759,470,000 | null | UTF-8 | Lean | false | false | 1,319 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.list.lemmas
import init.meta.mk_dec_eq_instance
open list
universes u v
local attribute [simp] join ret
instance : monad list :=
{pure := @list.ret, bind := @list.bind,
id_map := begin
intros _ xs, induction xs with x xs ih,
{ refl },
{ dsimp [function.comp] at ih, dsimp [function.comp], simp [*] }
end,
pure_bind := by simp_intros,
bind_assoc := begin
intros _ _ _ xs _ _, induction xs,
{ refl },
{ simp [*] }
end}
instance : alternative list :=
{ failure := @list.nil,
orelse := @list.append,
..list.monad }
namespace list
variables {α β : Type u} (p : α → Prop) [decidable_pred p]
instance bin_tree_to_list : has_coe (bin_tree α) (list α) :=
⟨bin_tree.to_list⟩
instance decidable_bex : ∀ (l : list α), decidable (∃ x ∈ l, p x)
| [] := is_false (by simp)
| (x::xs) := by simp; have := decidable_bex xs; apply_instance
instance decidable_ball (l : list α) : decidable (∀ x ∈ l, p x) :=
if h : ∃ x ∈ l, ¬ p x then
is_false $ let ⟨x, h, np⟩ := h in λ al, np (al x h)
else
is_true $ λ x hx, if h' : p x then h' else false.elim $ h ⟨x, hx, h'⟩
end list
|
69a22a5d38c95efa2f99c5b89c5a1412e8c06229 | 958488bc7f3c2044206e0358e56d7690b6ae696c | /lean/options.lean | 3723cd67072974428f972e1d582faf3ed4812384 | [] | no_license | possientis/Prog | a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4 | d4b3debc37610a88e0dac3ac5914903604fd1d1f | refs/heads/master | 1,692,263,717,723 | 1,691,757,179,000 | 1,691,757,179,000 | 40,361,602 | 3 | 0 | null | 1,679,896,438,000 | 1,438,953,859,000 | Coq | UTF-8 | Lean | false | false | 248 | lean |
set_option pp.implicit true
set_option pp.universes true
set_option pp.notation false
set_option pp.numerals false
#check 2 + 2 = 4
#reduce (λ x, x + 2) = (λ x, x + 3)
#check (λ x, x + 1) 1
set_option pp.beta true
#check (λ x, x + 1) 1
|
d7a36ce0a81c59b951f5e20f1c4b7ce4b49bd849 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/geometry/manifold/real_instances.lean | 83e4ed78543a1ce2acea238204a4df911158ee0d | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 16,175 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import geometry.manifold.smooth_manifold_with_corners
import linear_algebra.finite_dimensional
import analysis.normed_space.real_inner_product
/-!
# Constructing examples of manifolds over ℝ
We introduce the necessary bits to be able to define manifolds modelled over `ℝ^n`, boundaryless
or with boundary or with corners. As a concrete example, we construct explicitly the manifold with
boundary structure on the real interval `[x, y]`.
More specifically, we introduce
* `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n)` for the model space used
to define `n`-dimensional real manifolds with boundary
* `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_quadrant n)` for the model space used
to define `n`-dimensional real manifolds with corners
## Notations
In the locale `manifold`, we introduce the notations
* `𝓡 n` for the identity model with corners on `euclidean_space (fin n)`
* `𝓡∂ n` for `model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n)`.
For instance, if a manifold `M` is boundaryless, smooth and modelled on `euclidean_space (fin m)`,
and `N` is smooth with boundary modelled on `euclidean_half_space n`, and `f : M → N` is a smooth
map, then the derivative of `f` can be written simply as `mfderiv (𝓡 m) (𝓡∂ n) f` (as to why the
model with corners can not be implicit, see the discussion in `smooth_manifold_with_corners.lean`).
## Implementation notes
The manifold structure on the interval `[x, y] = Icc x y` requires the assumption `x < y` as a
typeclass. We provide it as `[fact (x < y)]`.
-/
noncomputable theory
open set
open_locale manifold
/--
The half-space in `ℝ^n`, used to model manifolds with boundary. We only define it when
`1 ≤ n`, as the definition only makes sense in this case.
-/
def euclidean_half_space (n : ℕ) [has_zero (fin n)] : Type :=
{x : euclidean_space (fin n) // 0 ≤ x 0}
/--
The quadrant in `ℝ^n`, used to model manifolds with corners, made of all vectors with nonnegative
coordinates.
-/
def euclidean_quadrant (n : ℕ) : Type := {x : euclidean_space (fin n) // ∀i:fin n, 0 ≤ x i}
section
/- Register class instances for euclidean half-space and quadrant, that can not be noticed
without the following reducibility attribute (which is only set in this section). -/
local attribute [reducible] euclidean_half_space euclidean_quadrant
variable {n : ℕ}
instance [has_zero (fin n)] : topological_space (euclidean_half_space n) := by apply_instance
instance : topological_space (euclidean_quadrant n) := by apply_instance
instance [has_zero (fin n)] : inhabited (euclidean_half_space n) := ⟨⟨0, le_refl _⟩⟩
instance : inhabited (euclidean_quadrant n) := ⟨⟨0, λ i, le_refl _⟩⟩
lemma range_half_space (n : ℕ) [has_zero (fin n)] :
range (λx : euclidean_half_space n, x.val) = {y | 0 ≤ y 0} :=
by simp
lemma range_quadrant (n : ℕ) :
range (λx : euclidean_quadrant n, x.val) = {y | ∀i:fin n, 0 ≤ y i} :=
by simp
end
/--
Definition of the model with corners `(euclidean_space (fin n), euclidean_half_space n)`, used as a
model for manifolds with boundary. In the locale `manifold`, use the shortcut `𝓡∂ n`.
-/
def model_with_corners_euclidean_half_space (n : ℕ) [has_zero (fin n)] :
model_with_corners ℝ (euclidean_space (fin n)) (euclidean_half_space n) :=
{ to_fun := λx, x.val,
inv_fun := λx, ⟨λi, if h : i = 0 then max (x i) 0 else x i, by simp [le_refl]⟩,
source := univ,
target := range (λx : euclidean_half_space n, x.val),
map_source' := λx hx, by simpa only [subtype.range_val] using x.property,
map_target' := λx hx, mem_univ _,
left_inv' := λ⟨xval, xprop⟩ hx, begin
rw subtype.mk_eq_mk,
ext1 i,
by_cases hi : i = 0,
{ rw hi, simp only [xprop, dif_pos, max_eq_left] },
{ simp only [hi, dif_neg, not_false_iff] }
end,
right_inv' := λx hx, begin
simp only [mem_set_of_eq, subtype.range_val_subtype] at hx,
ext1 i,
by_cases hi : i = 0,
{ rw hi, simp only [hx, dif_pos, max_eq_left] } ,
{ simp only [hi, dif_neg, not_false_iff] }
end,
source_eq := rfl,
unique_diff' := begin
/- To check that the half-space has the unique differentiability property, we use the criterion
`unique_diff_on_convex`: it suffices to check that it is convex and with nonempty interior. -/
rw range_half_space,
apply unique_diff_on_convex,
show convex {y : euclidean_space (fin n) | 0 ≤ y 0},
{ assume x y hx hy a b ha hb hab,
simpa only [add_zero] using add_le_add (mul_nonneg ha hx) (mul_nonneg hb hy) },
show (interior {y : euclidean_space (fin n) | 0 ≤ y 0}).nonempty,
{ use (λi, 1),
rw mem_interior,
refine ⟨(pi (univ : set (fin n)) (λi, (Ioi 0 : set ℝ))), _,
is_open_set_pi finite_univ (λa ha, is_open_Ioi), _⟩,
{ assume x hx,
simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi] at hx,
exact le_of_lt (hx 0) },
{ simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi],
assume i,
exact zero_lt_one } }
end,
continuous_to_fun := continuous_subtype_val,
continuous_inv_fun := begin
apply continuous_subtype_mk,
apply continuous_pi,
assume i,
by_cases h : i = 0,
{ rw h,
simp only [dif_pos],
have : continuous (λx:ℝ, max x 0) := continuous_id.max continuous_const,
exact this.comp (continuous_apply 0) },
{ simp only [h, dif_neg, not_false_iff],
exact continuous_apply i }
end }
/--
Definition of the model with corners `(euclidean_space (fin n), euclidean_quadrant n)`, used as a
model for manifolds with corners -/
def model_with_corners_euclidean_quadrant (n : ℕ) :
model_with_corners ℝ (euclidean_space (fin n)) (euclidean_quadrant n) :=
{ to_fun := λx, x.val,
inv_fun := λx, ⟨λi, max (x i) 0, λi, by simp only [le_refl, or_true, le_max_iff]⟩,
source := univ,
target := range (λx : euclidean_quadrant n, x.val),
map_source' := λx hx, by simpa only [subtype.range_val] using x.property,
map_target' := λx hx, mem_univ _,
left_inv' := λ⟨xval, xprop⟩ hx, begin
rw subtype.mk_eq_mk,
ext1 i,
simp only [xprop i, max_eq_left]
end,
right_inv' := λx hx, begin
rw range_quadrant at hx,
ext1 i,
simp only [hx i, max_eq_left]
end,
source_eq := rfl,
unique_diff' := begin
/- To check that the quadrant has the unique differentiability property, we use the criterion
`unique_diff_on_convex`: it suffices to check that it is convex and with nonempty interior. -/
rw range_quadrant,
apply unique_diff_on_convex,
show convex {y : euclidean_space (fin n) | ∀ (i : fin n), 0 ≤ y i},
{ assume x y hx hy a b ha hb hab i,
simpa only [add_zero] using add_le_add (mul_nonneg ha (hx i)) (mul_nonneg hb (hy i)) },
show (interior {y : euclidean_space (fin n) | ∀ (i : fin n), 0 ≤ y i}).nonempty,
{ use (λi, 1),
rw mem_interior,
refine ⟨(pi (univ : set (fin n)) (λi, (Ioi 0 : set ℝ))), _,
is_open_set_pi finite_univ (λa ha, is_open_Ioi), _⟩,
{ assume x hx i,
simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi] at hx,
exact le_of_lt (hx i) },
{ simp only [pi, forall_prop_of_true, mem_univ, mem_Ioi],
assume i,
exact zero_lt_one } }
end,
continuous_to_fun := continuous_subtype_val,
continuous_inv_fun := begin
apply continuous_subtype_mk,
apply continuous_pi,
assume i,
have : continuous (λx:ℝ, max x 0) := continuous.max continuous_id continuous_const,
exact this.comp (continuous_apply i)
end }
localized "notation `𝓡 `n := model_with_corners_self ℝ (euclidean_space (fin n))" in manifold
localized "notation `𝓡∂ `n := model_with_corners_euclidean_half_space n" in manifold
/--
The left chart for the topological space `[x, y]`, defined on `[x,y)` and sending `x` to `0` in
`euclidean_half_space 1`.
-/
def Icc_left_chart (x y : ℝ) [fact (x < y)] :
local_homeomorph (Icc x y) (euclidean_half_space 1) :=
{ source := {z : Icc x y | z.val < y},
target := {z : euclidean_half_space 1 | z.val 0 < y - x},
to_fun := λ(z : Icc x y), ⟨λi, z.val - x, sub_nonneg.mpr z.property.1⟩,
inv_fun := λz, ⟨min (z.val 0 + x) y, by simp [le_refl, z.prop, le_of_lt ‹x < y›]⟩,
map_source' := by simp only [imp_self, sub_lt_sub_iff_right, mem_set_of_eq, forall_true_iff],
map_target' :=
by { simp only [min_lt_iff, mem_set_of_eq], assume z hz, left,
dsimp [-subtype.val_eq_coe] at hz, linarith },
left_inv' := begin
rintros ⟨z, hz⟩ h'z,
simp only [mem_set_of_eq, mem_Icc] at hz h'z,
simp only [hz, min_eq_left, sub_add_cancel]
end,
right_inv' := begin
rintros ⟨z, hz⟩ h'z,
rw subtype.mk_eq_mk,
funext,
dsimp at hz h'z,
have A : x + z 0 ≤ y, by linarith,
rw subsingleton.elim i 0,
simp only [A, add_comm, add_sub_cancel', min_eq_left],
end,
open_source := begin
have : is_open {z : ℝ | z < y} := is_open_Iio,
exact continuous_subtype_val _ this
end,
open_target := begin
have : is_open {z : ℝ | z < y - x} := is_open_Iio,
have : is_open {z : euclidean_space (fin 1) | z 0 < y - x} :=
@continuous_apply (fin 1) (λ _, ℝ) _ 0 _ this,
exact continuous_subtype_val _ this
end,
continuous_to_fun := begin
apply continuous.continuous_on,
apply continuous_subtype_mk,
have : continuous (λ (z : ℝ) (i : fin 1), z - x) :=
continuous.sub (continuous_pi $ λi, continuous_id) continuous_const,
exact this.comp continuous_subtype_val,
end,
continuous_inv_fun := begin
apply continuous.continuous_on,
apply continuous_subtype_mk,
have A : continuous (λ z : ℝ, min (z + x) y) :=
(continuous_id.add continuous_const).min continuous_const,
have B : continuous (λz : euclidean_space (fin 1), z 0) := continuous_apply 0,
exact (A.comp B).comp continuous_subtype_val
end }
/--
The right chart for the topological space `[x, y]`, defined on `(x,y]` and sending `y` to `0` in
`euclidean_half_space 1`.
-/
def Icc_right_chart (x y : ℝ) [fact (x < y)] :
local_homeomorph (Icc x y) (euclidean_half_space 1) :=
{ source := {z : Icc x y | x < z.val},
target := {z : euclidean_half_space 1 | z.val 0 < y - x},
to_fun := λ(z : Icc x y), ⟨λi, y - z.val, sub_nonneg.mpr z.property.2⟩,
inv_fun := λz,
⟨max (y - z.val 0) x, by simp [le_refl, z.prop, le_of_lt ‹x < y›, sub_eq_add_neg]⟩,
map_source' := by simp only [imp_self, mem_set_of_eq, sub_lt_sub_iff_left, forall_true_iff],
map_target' :=
by { simp only [lt_max_iff, mem_set_of_eq], assume z hz, left,
dsimp [-subtype.val_eq_coe] at hz, linarith },
left_inv' := begin
rintros ⟨z, hz⟩ h'z,
simp only [mem_set_of_eq, mem_Icc] at hz h'z,
simp only [hz, sub_eq_add_neg, max_eq_left, add_add_neg_cancel'_right, neg_add_rev, neg_neg]
end,
right_inv' := begin
rintros ⟨z, hz⟩ h'z,
rw subtype.mk_eq_mk,
funext,
dsimp at hz h'z,
have A : x ≤ y - z 0, by linarith,
rw subsingleton.elim i 0,
simp only [A, sub_sub_cancel, max_eq_left],
end,
open_source := begin
have : is_open {z : ℝ | x < z} := is_open_Ioi,
exact continuous_subtype_val _ this
end,
open_target := begin
have : is_open {z : ℝ | z < y - x} := is_open_Iio,
have : is_open {z : euclidean_space (fin 1) | z 0 < y - x} :=
@continuous_apply (fin 1) (λ _, ℝ) _ 0 _ this,
exact continuous_subtype_val _ this
end,
continuous_to_fun := begin
apply continuous.continuous_on,
apply continuous_subtype_mk,
have : continuous (λ (z : ℝ) (i : fin 1), y - z) :=
continuous_const.sub (continuous_pi (λi, continuous_id)),
exact this.comp continuous_subtype_val,
end,
continuous_inv_fun := begin
apply continuous.continuous_on,
apply continuous_subtype_mk,
have A : continuous (λ z : ℝ, max (y - z) x) :=
(continuous_const.sub continuous_id).max continuous_const,
have B : continuous (λz : euclidean_space (fin 1), z 0) := continuous_apply 0,
exact (A.comp B).comp continuous_subtype_val
end }
/--
Charted space structure on `[x, y]`, using only two charts taking values in `euclidean_half_space 1`.
-/
instance Icc_manifold (x y : ℝ) [fact (x < y)] : charted_space (euclidean_half_space 1) (Icc x y) :=
{ atlas := {Icc_left_chart x y, Icc_right_chart x y},
chart_at := λz, if z.val < y then Icc_left_chart x y else Icc_right_chart x y,
mem_chart_source := λz, begin
by_cases h' : z.val < y,
{ simp only [h', if_true],
exact h' },
{ simp only [h', if_false],
apply lt_of_lt_of_le ‹x < y›,
simpa only [not_lt] using h'}
end,
chart_mem_atlas := λz, by { by_cases h' : z.val < y; simp [h'] } }
/--
The manifold structure on `[x, y]` is smooth.
-/
instance Icc_smooth_manifold (x y : ℝ) [fact (x < y)] :
smooth_manifold_with_corners (𝓡∂ 1) (Icc x y) :=
begin
have M : times_cont_diff_on ℝ ∞ (λz : euclidean_space (fin 1), - z + (λi, y - x)) univ,
{ rw times_cont_diff_on_univ,
exact times_cont_diff_id.neg.add times_cont_diff_const },
haveI : has_groupoid (Icc x y) (times_cont_diff_groupoid ∞ (𝓡∂ 1)) :=
begin
apply has_groupoid_of_pregroupoid,
assume e e' he he',
simp only [atlas, mem_singleton_iff, mem_insert_iff] at he he',
/- We need to check that any composition of two charts gives a `C^∞` function. Each chart can be
either the left chart or the right chart, leaving 4 possibilities that we handle successively.
-/
rcases he with rfl | rfl; rcases he' with rfl | rfl,
{ -- `e = left chart`, `e' = left chart`
refine (mem_groupoid_of_pregroupoid.mpr _).1,
exact symm_trans_mem_times_cont_diff_groupoid _ _ _ },
{ -- `e = left chart`, `e' = right chart`
apply M.congr_mono _ (subset_univ _),
assume z hz,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, dif_pos,
lt_add_iff_pos_left, max_lt_iff, lt_min_iff, sub_pos, lt_max_iff, subtype.range_val]
with mfld_simps at hz,
have A : 0 ≤ z 0 := hz.2,
have B : z 0 + x ≤ y, by { have := hz.1.1.1, linarith },
ext i,
rw subsingleton.elim i 0,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, A, B,
pi_Lp.add_apply, dif_pos, min_eq_left, max_eq_left, pi_Lp.neg_apply] with mfld_simps,
ring },
{ -- `e = right chart`, `e' = left chart`
apply M.congr_mono _ (subset_univ _),
assume z hz,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, dif_pos,
max_lt_iff, sub_pos, subtype.range_val] with mfld_simps at hz,
have A : 0 ≤ z 0 := hz.2,
have B : x ≤ y - z 0, by { have := hz.1.1.1, dsimp at this, linarith },
ext i,
rw subsingleton.elim i 0,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, A, B,
pi_Lp.add_apply, dif_pos, max_eq_left, pi_Lp.neg_apply] with mfld_simps,
ring },
{ -- `e = right chart`, `e' = right chart`
refine (mem_groupoid_of_pregroupoid.mpr _).1,
exact symm_trans_mem_times_cont_diff_groupoid _ _ _ }
end,
constructor
end
/-! Register the manifold structure on `Icc 0 1`, and also its zero and one. -/
section
lemma fact_zero_lt_one : fact ((0 : ℝ) < 1) := zero_lt_one
local attribute [instance] fact_zero_lt_one
instance : charted_space (euclidean_half_space 1) (Icc (0 : ℝ) 1) := by apply_instance
instance : smooth_manifold_with_corners (𝓡∂ 1) (Icc (0 : ℝ) 1) := by apply_instance
instance : has_zero (Icc (0 : ℝ) 1) := ⟨⟨(0 : ℝ), ⟨le_refl _, zero_le_one⟩⟩⟩
instance : has_one (Icc (0 : ℝ) 1) := ⟨⟨(1 : ℝ), ⟨zero_le_one, le_refl _⟩⟩⟩
end
|
54c6809ce9dcaef7e5010e3967f1607436f783ab | 9cba98daa30c0804090f963f9024147a50292fa0 | /time_series/definitions.lean | 04d71e34f745da5fb9230517e2d103b0c9542f50 | [] | no_license | kevinsullivan/phys | dcb192f7b3033797541b980f0b4a7e75d84cea1a | ebc2df3779d3605ff7a9b47eeda25c2a551e011f | refs/heads/master | 1,637,490,575,500 | 1,629,899,064,000 | 1,629,899,064,000 | 168,012,884 | 0 | 3 | null | 1,629,644,436,000 | 1,548,699,832,000 | Lean | UTF-8 | Lean | false | false | 21,182 | lean | import ..time.time
import tactic.ext
universes u
variables {tf : time_frame} (ts : time_space tf) (V : Type u)
[inhabited V] /-Questionable whether to use inhabited.default as a default value-/
/-
structure timestamped :=
(timestamp : time ts)
@[class]
structure has_timestamp (V : Type u) :=
(get_timestamp : V → time ts)
instance : has_timestamp ts (timestamped ts) := ⟨λts, ts.timestamp⟩
-/
structure timestamped :=
(timestamp : time ts)
(value : V)
@[simp]
noncomputable def mk_default_timestamped : timestamped ts V :=
⟨inhabited.default (time ts), inhabited.default V⟩
noncomputable instance : inhabited (timestamped ts V) := ⟨mk_default_timestamped ts V⟩
@[simp]
lemma nathelper : ∀ (a b : ℕ), a + b < a → false :=
begin
intros a b c,
cases b,
suffices : ¬a < a, from by contradiction, exact irrefl _,
let h1 : 0 < b.succ := by simp *,
let h2 : a + 0 < a + b.succ := by simp *,
let h3 : a + 0 < a := by exact lt_trans h2 c,
suffices : ¬a < a, from by contradiction, exact irrefl _,
end
@[simp]
lemma nathelper2 : ∀ (a b : ℕ), b + a < a → false :=
begin
intros a b c,
rw ←(nat.add_comm a b) at c,
exact nathelper _ _ c,
end
/-
let ht : i_val + 1 = i_val.succ := by repeat { apply nat.add_one _ },
rw ←ht at i_property,
let : false := by exact eznat2 _ _ i_property,
contradiction,
-/
instance timelt : has_lt (time ts) := ⟨
λt1 t2, t1.coord < t2.coord
⟩
instance timele : has_le (time ts) := ⟨
λt1 t2, t1.coord ≤ t2.coord
⟩
instance durationlt : has_lt (duration ts) := ⟨
λt1 t2, t1.coord < t2.coord
⟩
instance durationle : has_le (duration ts) := ⟨
λt1 t2, t1.coord ≤ t2.coord
⟩
instance [has_le (time ts)] [has_lt (time ts)]: preorder (time ts) := ⟨
--has_le.le, has_lt.lt,
λt1 t2, t1.coord ≤ t2.coord,
λt1 t2, t1.coord < t2.coord,
begin
intros,
simp *,
end,
begin
simp *,
intros a b c d e,
transitivity,
apply d,
apply e,
--simp
end,
begin
simp *,
intros a b,
split,
assume h,
split,
exact (le_not_le_of_lt h).1,
apply h,
assume h,
exact h.2,
end
⟩
noncomputable instance eqd {t1 t2 : time ts} : decidable (t1 = t2) :=
if eqc:t1.coord=t2.coord then
begin
--cases t1, cases t2, cases t1, cases t2,
unfold time.coord at eqc,
cases t1,cases t2,
let h : ∀i, t1.coords i = t2.coords i := begin
intros,
cases i,
cases i_val,
ext,
exact eqc,
let ht : i_val + 1 = i_val.succ := by repeat { apply nat.add_one _ },rw ←ht at i_property,
let : false := by exact nathelper2 _ _ i_property,
contradiction,
end,
let h1 : t1 = t2 := begin ext,
let h := h x,
simp [h],
end,
simp [h1],
exact decidable.is_true true.intro,
end
else
begin
--cases t1, cases t2, cases t1, cases t2,
unfold time.coord at eqc,
cases t1,cases t2,
let h : ∀i, ¬t1.coords i = t2.coords i := begin
intros,
cases i,
cases i_val,
cases (t1.coords ⟨0, i_property⟩),
cases (t2.coords ⟨0, i_property⟩),
simp [eqc],
--ext,
let ht : i_val + 1 = i_val.succ := by repeat { apply nat.add_one _ },rw ←ht at i_property,
let : false := by exact nathelper2 _ _ i_property,
contradiction,
end,
let h1 : ¬t1 = t2 := begin assume teq,
let : (({to_point := t1} : time _).to_point.coords 0).coord =
(({to_point := t2} : time _).to_point.coords 0).coord :=
by rw ←teq,
contradiction
end,
--simp [h1],
exact decidable.is_false (by simp [h1]),
end
--instance ltd {t1 t2 : time ts} : decidable (t1 < t2) := sorry
--instance leqd {t1 t2 : time ts} : decidable (t1 ≤ t2) := sorry
abbreviation time_series := time ts → V
abbreviation time_series.Icc (min_t max_t : time ts) :=
set.Icc min_t max_t → V
abbreviation time_series.Ici (min_t : time ts) :=
set.Ici min_t → V
def time_series.mk_empty {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V]
: time_series ts V := λi, inhabited.default V
noncomputable def time_series.update {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] :
time_series ts V → time ts → V → time_series ts V
| ser t_ val_ := --λt, if t = t_ then val_ else ser t
function.update ser t_ val_
def time_series.sample {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V]
: time_series ts V → time ts → V :=
λser tm , ser tm
def time_series.Icc.sample
{tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
: time_series.Icc ts V min_t max_t → set.Icc min_t max_t → V :=
λser tm , ser tm
def time_series.Ici.sample
{tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
: time_series.Ici ts V min_t → set.Ici min_t → V :=
λser tm , ser tm
abbreviation discrete_series {tf : time_frame} (ts : time_space tf) (V : Type u) [inhabited V] :=
list (timestamped ts V)
def discrete_series.mk_empty {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] : discrete_series ts V := []
#check list.range
#check set.mem
def discrete_series.domain {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] :
discrete_series ts V → list (time ts) :=
λser, list.map (λtsv : timestamped ts V, tsv.timestamp) ser
def discrete_series.update {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] :
discrete_series ts V → timestamped ts V → discrete_series ts V
--| [] ts_ val_ := [(ts_, val_)]
--| (h::t) ts_ val_ := (h::t ++ [(ts_, val_)] : list (timestamped ts V))
| ser tsv := ser.cons tsv
@[simp, reducible]
noncomputable def discrete_series.latest_helper {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] :
discrete_series ts V → (timestamped ts V) → (timestamped ts V)
| (h::t) v := if h.timestamp > v.timestamp then discrete_series.latest_helper t h else discrete_series.latest_helper t v
| [] v := v
@[simp, reducible]
noncomputable def discrete_series.latest {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] :
discrete_series ts V → (timestamped ts V)
| (h::t) := discrete_series.latest_helper t h
| [] := ⟨inhabited.default (time ts), inhabited.default V⟩
abbreviation discrete_series.Icc {tf : time_frame} (ts : time_space tf) (V : Type u) [inhabited V]
(min_t max_t : time ts) :=
list (set.Icc min_t max_t × V)
abbreviation discrete_series.Ici {tf : time_frame} (ts : time_space tf) (V : Type u) [inhabited V]
(min_t : time ts) :=
list (set.Ici min_t × V)
noncomputable def discrete_series.sample {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V]
: discrete_series ts V → time ts → V
| [] t_ := inhabited.default V
| (h::t) t_ := if h.timestamp = t_ then h.value else discrete_series.sample t t_
noncomputable def discrete_series.sample_floor_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V]
(v : time ts) : discrete_series ts V → option (timestamped ts V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if t_.timestamp < h.timestamp ∧ h.timestamp ≤ v
then discrete_series.sample_floor_helper t (some h)
else discrete_series.sample_floor_helper t (some t_)
| (h::t) (none) :=
if h.timestamp ≤ v
then discrete_series.sample_floor_helper t (some h)
else discrete_series.sample_floor_helper t none
noncomputable def discrete_series.sample_floor {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V]
: discrete_series ts V → time ts → V :=
λser t, discrete_series.sample_floor_helper t ser none
noncomputable def discrete_series.sample_ceil_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V]
(v : time ts) : discrete_series ts V → option (timestamped ts V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if h.timestamp < t_.timestamp ∧ v ≤ h.timestamp
then discrete_series.sample_ceil_helper t (some h)
else discrete_series.sample_ceil_helper t (some t_)
| (h::t) (none) :=
if v ≤ h.timestamp
then discrete_series.sample_ceil_helper t (some h)
else discrete_series.sample_ceil_helper t none
noncomputable def discrete_series.sample_ceil {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V]
: discrete_series ts V → time ts → V :=
λser t, discrete_series.sample_ceil_helper t ser none
noncomputable def discrete_series.Icc.sample {min_t max_t : time ts}
: discrete_series.Icc ts V min_t max_t → time ts → V
| [] t_ := inhabited.default V
| (h::t) t_ := if h.timestamp.1 = t_ then h.value else discrete_series.Icc.sample t t_
noncomputable def discrete_series.Icc.sample_floor_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
(v : set.Icc min_t max_t) : discrete_series.Icc ts V min_t max_t → option (set.Icc min_t max_t × V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if t_.timestamp.val < h.timestamp ∧ h.timestamp.val ≤ v
then discrete_series.Icc.sample_floor_helper t (some h)
else discrete_series.Icc.sample_floor_helper t (some t_)
| (h::t) (none) :=
if h.timestamp.val ≤ v
then discrete_series.Icc.sample_floor_helper t (some h)
else discrete_series.Icc.sample_floor_helper t none
def discrete_series.Icc.sample_floor
{tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
: discrete_series.Icc ts V min_t max_t → set.Icc min_t max_t → V :=
λser t, discrete_series.Icc.sample_floor_helper t ser none
def discrete_series.Icc.sample_ceil_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
(v : set.Icc min_t max_t) : discrete_series.Icc ts V min_t max_t → option (set.Icc min_t max_t × V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if h.timestamp.val < t_.timestamp.val ∧ v.val ≤ h.timestamp.val
then discrete_series.Icc.sample_ceil_helper t (some h)
else discrete_series.Icc.sample_ceil_helper t (some t_)
| (h::t) (none) :=
if v.val ≤ h.timestamp.val
then discrete_series.Icc.sample_ceil_helper t (some h)
else discrete_series.Icc.sample_ceil_helper t none
def discrete_series.Icc.sample_ceil {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
: discrete_series.Icc ts V min_t max_t → set.Icc min_t max_t → V :=
λser t, discrete_series.Icc.sample_ceil_helper t ser none
def discrete_series.Ici.sample {min_t : time ts}
: discrete_series.Ici ts V min_t → time ts → V
| [] t_ := inhabited.default V
| (h::t) t_ := if h.timestamp.1 = t_ then h.value else discrete_series.Ici.sample t t_
def discrete_series.Ici.sample_floor_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
(v : set.Ici min_t) : discrete_series.Ici ts V min_t → option (set.Ici min_t × V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if t_.timestamp.val < h.timestamp ∧ h.timestamp.val ≤ v
then discrete_series.Ici.sample_floor_helper t (some h)
else discrete_series.Ici.sample_floor_helper t (some t_)
| (h::t) (none) :=
if h.timestamp.val ≤ v
then discrete_series.Ici.sample_floor_helper t (some h)
else discrete_series.Ici.sample_floor_helper t none
def discrete_series.Ici.sample_floor
{tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
: discrete_series.Ici ts V min_t → set.Ici min_t → V :=
λser t, discrete_series.Ici.sample_floor_helper t ser none
def discrete_series.Ici.sample_ceil_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
(v : set.Ici min_t) : discrete_series.Ici ts V min_t → option (set.Ici min_t × V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if h.timestamp.val < t_.timestamp.val ∧ v.val ≤ h.timestamp.val
then discrete_series.Ici.sample_ceil_helper t (some h)
else discrete_series.Ici.sample_ceil_helper t (some t_)
| (h::t) (none) :=
if v.val ≤ h.timestamp.val
then discrete_series.Ici.sample_ceil_helper t (some h)
else discrete_series.Ici.sample_ceil_helper t none
def discrete_series.Ici.sample_ceil {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
: discrete_series.Ici ts V min_t → set.Ici min_t → V :=
λser t, discrete_series.Ici.sample_ceil_helper t ser none
/-
abbreviation discrete_timestamped_series {tf : time_frame} (ts : time_space tf) (V : Type u) [inhabited V] :=
list (timestamped ts V)
def discrete_timestamped_series.mk_empty {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] : discrete_timestamped_series ts V := []
def discrete_timestamped_series.update {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] :
discrete_timestamped_series ts V → time ts → V → discrete_timestamped_series ts V
--| [] ts_ val_ := [(ts_, val_)]
--| (h::t) ts_ val_ := (h::t ++ [(ts_, val_)] : list (timestamped ts V))
| ser ts_ val_ := ser.cons (ts_, val_)
def discrete_timestamped_series.latest_helper {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] :
discrete_timestamped_series ts V → (timestamped ts V) → V
| (h::t) v := if h.timestamp > v.timestamp then discrete_timestamped_series.latest_helper t h else discrete_timestamped_series.latest_helper t v
| [] v := v.value
def discrete_timestamped_series.latest {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V] :
discrete_timestamped_series ts V → V
| (h::t) := discrete_timestamped_series.latest_helper t h
| [] := inhabited.default V
abbreviation discrete_timestamped_series.Icc {tf : time_frame} (ts : time_space tf) (V : Type u) [inhabited V]
(min_t max_t : time ts) :=
list (set.Icc min_t max_t × V)
abbreviation discrete_timestamped_series.Ici {tf : time_frame} (ts : time_space tf) (V : Type u) [inhabited V]
(min_t : time ts) :=
list (set.Ici min_t × V)
def discrete_timestamped_series.sample {tf : time_frame} {ts : time_space tf} {V : Type u}
[inhabited V]
: discrete_timestamped_series ts V → time ts → V
| [] t_ := inhabited.default V
| (h::t) t_ := if h.timestamp = t_ then h.value else discrete_timestamped_series.sample t t_
def discrete_timestamped_series.sample_floor_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V]
(v : time ts) : discrete_timestamped_series ts V → option (timestamped ts V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if t_.timestamp < h.timestamp ∧ h.timestamp ≤ v
then discrete_timestamped_series.sample_floor_helper t (some h)
else discrete_timestamped_series.sample_floor_helper t (some t_)
| (h::t) (none) :=
if h.timestamp ≤ v
then discrete_timestamped_series.sample_floor_helper t (some h)
else discrete_timestamped_series.sample_floor_helper t none
def discrete_timestamped_series.sample_floor {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V]
: discrete_timestamped_series ts V → time ts → V :=
λser t, discrete_timestamped_series.sample_floor_helper t ser none
def discrete_timestamped_series.sample_ceil_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V]
(v : time ts) : discrete_timestamped_series ts V → option (timestamped ts V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if h.timestamp < t_.timestamp ∧ v ≤ h.timestamp
then discrete_timestamped_series.sample_ceil_helper t (some h)
else discrete_timestamped_series.sample_ceil_helper t (some t_)
| (h::t) (none) :=
if v ≤ h.timestamp
then discrete_timestamped_series.sample_ceil_helper t (some h)
else discrete_timestamped_series.sample_ceil_helper t none
def discrete_timestamped_series.sample_ceil {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V]
: discrete_timestamped_series ts V → time ts → V :=
λser t, discrete_timestamped_series.sample_ceil_helper t ser none
def discrete_timestamped_series.Icc.sample {min_t max_t : time ts}
: discrete_timestamped_series.Icc ts V min_t max_t → time ts → V
| [] t_ := inhabited.default V
| (h::t) t_ := if h.timestamp.1 = t_ then h.value else discrete_timestamped_series.Icc.sample t t_
def discrete_timestamped_series.Icc.sample_floor_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
(v : set.Icc min_t max_t) : discrete_timestamped_series.Icc ts V min_t max_t → option (set.Icc min_t max_t × V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if t_.timestamp.val < h.timestamp ∧ h.timestamp.val ≤ v
then discrete_timestamped_series.Icc.sample_floor_helper t (some h)
else discrete_timestamped_series.Icc.sample_floor_helper t (some t_)
| (h::t) (none) :=
if h.timestamp.val ≤ v
then discrete_timestamped_series.Icc.sample_floor_helper t (some h)
else discrete_timestamped_series.Icc.sample_floor_helper t none
def discrete_timestamped_series.Icc.sample_floor
{tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
: discrete_timestamped_series.Icc ts V min_t max_t → set.Icc min_t max_t → V :=
λser t, discrete_timestamped_series.Icc.sample_floor_helper t ser none
def discrete_timestamped_series.Icc.sample_ceil_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
(v : set.Icc min_t max_t) : discrete_timestamped_series.Icc ts V min_t max_t → option (set.Icc min_t max_t × V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if h.timestamp.val < t_.timestamp.val ∧ v.val ≤ h.timestamp.val
then discrete_timestamped_series.Icc.sample_ceil_helper t (some h)
else discrete_timestamped_series.Icc.sample_ceil_helper t (some t_)
| (h::t) (none) :=
if v.val ≤ h.timestamp.val
then discrete_timestamped_series.Icc.sample_ceil_helper t (some h)
else discrete_timestamped_series.Icc.sample_ceil_helper t none
def discrete_timestamped_series.Icc.sample_ceil {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t max_t : time ts}
: discrete_timestamped_series.Icc ts V min_t max_t → set.Icc min_t max_t → V :=
λser t, discrete_timestamped_series.Icc.sample_ceil_helper t ser none
def discrete_timestamped_series.Ici.sample {min_t : time ts}
: discrete_timestamped_series.Ici ts V min_t → time ts → V
| [] t_ := inhabited.default V
| (h::t) t_ := if h.timestamp.1 = t_ then h.value else discrete_timestamped_series.Ici.sample t t_
def discrete_timestamped_series.Ici.sample_floor_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
(v : set.Ici min_t) : discrete_timestamped_series.Ici ts V min_t → option (set.Ici min_t × V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if t_.timestamp.val < h.timestamp ∧ h.timestamp.val ≤ v
then discrete_timestamped_series.Ici.sample_floor_helper t (some h)
else discrete_timestamped_series.Ici.sample_floor_helper t (some t_)
| (h::t) (none) :=
if h.timestamp.val ≤ v
then discrete_timestamped_series.Ici.sample_floor_helper t (some h)
else discrete_timestamped_series.Ici.sample_floor_helper t none
def discrete_timestamped_series.Ici.sample_floor
{tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
: discrete_timestamped_series.Ici ts V min_t → set.Ici min_t → V :=
λser t, discrete_timestamped_series.Ici.sample_floor_helper t ser none
def discrete_timestamped_series.Ici.sample_ceil_helper {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
(v : set.Ici min_t) : discrete_timestamped_series.Ici ts V min_t → option (set.Ici min_t × V) → V
| [] (none) := inhabited.default V
| [] (some t_) := t_.value
| (h::t) (some t_) :=
if h.timestamp.val < t_.timestamp.val ∧ v.val ≤ h.timestamp.val
then discrete_timestamped_series.Ici.sample_ceil_helper t (some h)
else discrete_timestamped_series.Ici.sample_ceil_helper t (some t_)
| (h::t) (none) :=
if v.val ≤ h.timestamp.val
then discrete_timestamped_series.Ici.sample_ceil_helper t (some h)
else discrete_timestamped_series.Ici.sample_ceil_helper t none
def discrete_timestamped_series.Ici.sample_ceil {tf : time_frame} {ts : time_space tf} {V : Type u} [inhabited V] {min_t : time ts}
: discrete_timestamped_series.Ici ts V min_t → set.Ici min_t → V :=
λser t, discrete_timestamped_series.Ici.sample_ceil_helper t ser none
-/ |
b0af312b013e80d8668867674faf1ec6f93e63ad | abd85493667895c57a7507870867b28124b3998f | /src/data/real/nnreal.lean | 231244439cf28acecdcc1c827610bf7eac556ee3 | [
"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 | 25,470 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
Nonnegative real numbers.
-/
import data.real.basic
noncomputable theory
open_locale classical big_operators
/-- Nonnegative real numbers. -/
def nnreal := {r : ℝ // 0 ≤ r}
localized "notation ` ℝ≥0 ` := nnreal" in nnreal
namespace nnreal
instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩
/- Simp lemma to put back `n.val` into the normal form given by the coercion. -/
@[simp] lemma val_eq_coe (n : nnreal) : n.val = n := rfl
instance : can_lift ℝ nnreal :=
{ coe := coe,
cond := λ r, r ≥ 0,
prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ }
protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq
protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m :=
iff.intro nnreal.eq (congr_arg coe)
lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y :=
not_iff_not_of_iff $ nnreal.eq_iff
protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩
lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r :=
max_eq_left hr
lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r :=
le_max_left r 0
lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≤ r := r.2
@[norm_cast]
theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl
instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩
instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩
instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩
instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩
instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩
instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩
instance : has_div ℝ≥0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩
instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩
instance : has_bot ℝ≥0 := ⟨0⟩
instance : inhabited ℝ≥0 := ⟨0⟩
@[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ :=
subtype.ext.symm
@[simp, norm_cast] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl
@[simp, norm_cast] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl
@[simp, norm_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl
@[simp, norm_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl
@[simp, norm_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl
@[simp, norm_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl
@[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl
@[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl
@[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) :
((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ :=
max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h]
-- TODO: setup semifield!
@[simp] protected lemma zero_div (r : ℝ≥0) : 0 / r = 0 := nnreal.eq (zero_div _)
@[simp] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by norm_cast
lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast
instance : comm_semiring ℝ≥0 :=
begin
refine { zero := 0, add := (+), one := 1, mul := (*), ..};
{ intros;
apply nnreal.eq;
simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib,
add_comm_monoid.zero, add_comm, add_left_comm] }
end
/-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/
def to_real_hom : ℝ≥0 →+* ℝ :=
⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩
@[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl
instance : comm_group_with_zero ℝ≥0 :=
{ zero_ne_one := assume h, zero_ne_one $ nnreal.eq_iff.2 h,
inv_zero := nnreal.eq $ show (0⁻¹ : ℝ) = 0, from inv_zero,
mul_inv_cancel := assume x h, nnreal.eq $ mul_inv_cancel $ ne_iff.2 h,
.. (by apply_instance : has_inv ℝ≥0),
.. (_ : comm_semiring ℝ≥0),
.. (_ : semiring ℝ≥0) }
@[norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n :=
to_real_hom.map_pow r n
@[norm_cast] lemma coe_list_sum (l : list ℝ≥0) :
((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum :=
to_real_hom.map_list_sum l
@[norm_cast] lemma coe_list_prod (l : list ℝ≥0) :
((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod :=
to_real_hom.map_list_prod l
@[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) :
((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum :=
to_real_hom.map_multiset_sum s
@[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) :
((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod :=
to_real_hom.map_multiset_prod s
@[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} :
↑(s.sum f) = s.sum (λa, (f a : ℝ)) :=
to_real_hom.map_sum _ _
@[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} :
↑(s.prod f) = s.prod (λa, (f a : ℝ)) :=
to_real_hom.map_prod _ _
@[norm_cast] lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n •ℕ r) = n •ℕ (r:ℝ) :=
to_real_hom.to_add_monoid_hom.map_nsmul _ _
@[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n :=
to_real_hom.map_nat_cast n
instance : decidable_linear_order ℝ≥0 :=
decidable_linear_order.lift (coe : ℝ≥0 → ℝ) subtype.val_injective (by apply_instance)
@[norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl
@[norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl
protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl
protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2
protected lemma of_real_mono : monotone nnreal.of_real :=
λ x y h, max_le_max h (le_refl 0)
@[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r :=
nnreal.eq $ max_eq_left r.2
/-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/
protected def gi : galois_insertion nnreal.of_real coe :=
galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono
le_coe_of_real (λ _, of_real_coe)
instance : order_bot ℝ≥0 :=
{ bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order }
instance : canonically_ordered_add_monoid ℝ≥0 :=
{ add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c,
lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c,
le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩,
iff.intro
(assume h : a ≤ b,
⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩,
nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩)
(assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc),
..nnreal.comm_semiring,
..nnreal.order_bot,
..nnreal.decidable_linear_order }
instance : distrib_lattice ℝ≥0 := by apply_instance
instance : semilattice_inf_bot ℝ≥0 :=
{ .. nnreal.order_bot, .. nnreal.distrib_lattice }
instance : semilattice_sup_bot ℝ≥0 :=
{ .. nnreal.order_bot, .. nnreal.distrib_lattice }
instance : linear_ordered_semiring ℝ≥0 :=
{ add_left_cancel := assume a b c h, nnreal.eq $
@add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h),
add_right_cancel := assume a b c h, nnreal.eq $
@add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h),
le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c,
mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c,
mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c,
zero_lt_one := @zero_lt_one ℝ _,
.. nnreal.decidable_linear_order,
.. nnreal.canonically_ordered_add_monoid,
.. nnreal.comm_semiring }
instance : canonically_ordered_comm_semiring ℝ≥0 :=
{ zero_ne_one := assume h, zero_ne_one $ congr_arg subtype.val $ h,
mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp,
.. nnreal.linear_ordered_semiring,
.. nnreal.canonically_ordered_add_monoid,
.. nnreal.comm_semiring }
instance : densely_ordered ℝ≥0 :=
⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in
⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩
instance : no_top_order ℝ≥0 :=
⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩
lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s :=
iff.intro
(assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from
le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩)
(assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩)
lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) :=
⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩
instance : has_Sup ℝ≥0 :=
⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s),
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, set.image_empty, real.Sup_empty] },
rcases h with ⟨⟨b, hb⟩, hbs⟩,
by_cases h' : bdd_above s,
{ exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb },
{ rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] }
end⟩⟩
instance : has_Inf ℝ≥0 :=
⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s),
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, set.image_empty, real.Inf_empty] },
exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2)
end⟩⟩
lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl
lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl
instance : conditionally_complete_linear_order_bot ℝ≥0 :=
{ Sup := Sup,
Inf := Inf,
le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha),
cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from
cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb,
cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has),
le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from
le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb,
cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl,
decidable_le := begin assume x y, apply classical.dec end,
.. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order,
.. nnreal.order_bot }
instance : archimedean nnreal :=
⟨ assume x y pos_y,
let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in
⟨n, show (x:ℝ) ≤ (n •ℕ y : nnreal), by simp [*, -nsmul_eq_mul, nsmul_coe]⟩ ⟩
lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense $ assume x hxb,
begin
rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩,
exact h _ ((lt_add_iff_pos_right b).1 hxb)
end
lemma lt_iff_exists_rat_btwn (a b : nnreal) :
a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) :=
iff.intro
(assume (h : (↑a:ℝ) < (↑b:ℝ)),
let ⟨q, haq, hqb⟩ := exists_rat_btwn h in
have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq,
⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩)
(assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb)
lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl
lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) :=
begin
cases le_total b c with h h,
{ simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] },
{ simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] },
end
lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) :
r * s.sup f = s.sup (λa, r * f a) :=
begin
refine s.induction_on _ _,
{ simp [bot_eq_zero] },
{ assume a s has ih, simp [has, ih, mul_sup], }
end
@[simp, norm_cast] lemma coe_max (x y : nnreal) :
((max x y : nnreal) : ℝ) = max (x : ℝ) (y : ℝ) :=
by { delta max, split_ifs; refl }
@[simp, norm_cast] lemma coe_min (x y : nnreal) :
((min x y : nnreal) : ℝ) = min (x : ℝ) (y : ℝ) :=
by { delta min, split_ifs; refl }
section of_real
@[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2
@[simp] lemma of_real_zero : nnreal.of_real 0 = 0 :=
by simp [nnreal.of_real]; refl
@[simp] lemma of_real_one : nnreal.of_real 1 = 1 :=
by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl
@[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r :=
by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl]
@[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 :=
by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r))
lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 :=
of_real_eq_zero.2
@[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) :
nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p :=
by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp]
@[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} :
nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p :=
by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl]
lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) :
nnreal.of_real r < nnreal.of_real p ↔ r < p :=
of_real_lt_of_real_iff'.trans (and_iff_left h)
lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) :
nnreal.of_real r < nnreal.of_real p ↔ r < p :=
of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩
@[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p :=
nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg]
lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) :=
(of_real_add hr hp).symm
lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p :=
nnreal.of_real_mono h
lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p :=
nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe
lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≤ p ↔ r ≤ ↑p :=
nnreal.gi.gc r p
lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : p ≥ 0) : r ≤ nnreal.of_real p ↔ ↑r ≤ p :=
by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp]
lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : r ≥ 0) : nnreal.of_real r < p ↔ r < ↑p :=
by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha]
lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p :=
begin
cases le_total 0 p,
{ rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] },
{ rw [of_real_eq_zero.2 h], split,
intro, have := not_lt_of_le (zero_le r), contradiction,
intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction }
end
end of_real
section mul
lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) :=
begin
rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split,
{ exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) },
{ assume h, rw [h] }
end
lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) :
nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q :=
begin
cases le_total 0 q with hq hq,
{ apply nnreal.eq,
have := max_eq_left (mul_nonneg hp hq),
simpa [nnreal.of_real, hp, hq, max_eq_left] },
{ have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq,
rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] }
end
@[field_simps] theorem mul_ne_zero' {a b : nnreal} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 :=
mul_ne_zero'' h₁ h₂
end mul
section sub
lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl
lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 :=
nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h
@[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r
@[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r :=
by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe]
lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r :=
of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe
protected lemma sub_lt_self {r p : nnreal} : 0 < r → 0 < p → r - p < r :=
assume hr hp,
begin
cases le_total r p,
{ rwa [sub_eq_zero h] },
{ rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp }
end
@[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p :=
match le_total p r with
| or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add,
sub_le_iff_le_add]
| or.inr h :=
have r ≤ p + q, from le_add_right h,
by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm]
end
@[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r :=
sub_le_iff_le_add.2 $ le_add_right $ le_refl r
lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p :=
nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _)
lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p :=
by rw [add_comm, add_sub_cancel]
@[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a :=
nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel]
lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r :=
by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h,
sub_sub_cancel, nnreal.of_real_coe]
lemma lt_sub_iff_add_lt {p q r : nnreal} : p < q - r ↔ p + r < q :=
begin
split,
{ assume H,
have : (((q - r) : nnreal) : ℝ) = (q : ℝ) - (r : ℝ) :=
nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))),
rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H },
{ assume H,
have : r ≤ q := le_trans (le_add_left (le_refl _)) (le_of_lt H),
rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] }
end
end sub
section inv
lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl
lemma sum_div {ι} (s : finset ι) (f : ι → ℝ≥0) (b : ℝ≥0) :
(∑ i in s, f i) / b = ∑ i in s, (f i / b) :=
by simp only [nnreal.div_def, finset.sum_mul]
@[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero
@[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 :=
inv_eq_zero
@[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r :=
by simp [zero_lt_iff_ne_zero]
lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p :=
mul_pos hr (inv_pos.2 hp)
@[simp] lemma inv_one : (1:ℝ≥0)⁻¹ = 1 := nnreal.eq $ inv_one
@[simp] lemma div_one {r : ℝ≥0} : r / 1 = r := by rw [div_def, inv_one, mul_one]
protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv' _ _
protected lemma inv_pow {r : ℝ≥0} {n : ℕ} : (r^n)⁻¹ = (r⁻¹)^n :=
nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm }
@[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 :=
nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h
@[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 :=
by rw [mul_comm, inv_mul_cancel h]
@[simp] lemma div_self {r : ℝ≥0} (h : r ≠ 0) : r / r = 1 :=
mul_inv_cancel h
@[simp] lemma div_mul_cancel {r p : ℝ≥0} (h : p ≠ 0) : r / p * p = r :=
by rw [div_def, mul_assoc, inv_mul_cancel h, mul_one]
@[simp] lemma mul_div_cancel {r p : ℝ≥0} (h : p ≠ 0) : r * p / p = r :=
by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one]
@[simp] lemma mul_div_cancel' {r p : ℝ≥0} (h : r ≠ 0) : r * (p / r) = p :=
by rw [mul_comm, div_mul_cancel h]
@[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq (inv_inv' _)
@[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p :=
by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h]
lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p :=
by by_cases r = 0; simp [*, inv_le]
@[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) :=
by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm]
@[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) :=
by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm]
lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b :=
have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm,
by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul]
lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b :=
by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm]
lemma div_le_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r :=
@div_le_iff ℝ _ a r b $ zero_lt_iff_ne_zero.2 hr
lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y :=
le_of_forall_ge_of_dense $ assume a ha,
have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha),
have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero],
have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv],
have (a * x⁻¹) * x ≤ y, from h _ this,
by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this
lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (c⁻¹)
lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two
lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a)
lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a :=
by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact
half_lt_self (bot_lt_iff_ne_bot.2 h)
lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 :=
by simpa [div_def] using half_lt_self zero_ne_one.symm
lemma div_lt_iff {a b c : ℝ≥0} (hc : c ≠ 0) : b / c < a ↔ b < a * c :=
begin
rw [← nnreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_div, nnreal.coe_mul],
exact div_lt_iff (zero_lt_iff_ne_zero.mpr hc)
end
lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 :=
begin
rwa [div_lt_iff, one_mul],
exact ne_of_gt (lt_of_le_of_lt (zero_le _) h)
end
@[field_simps] theorem div_pow {a b : ℝ≥0} (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n :=
div_pow _ _ _
@[field_simps] lemma mul_div_assoc' (a b c : ℝ≥0) : a * (b / c) = (a * b) / c :=
by rw [div_def, div_def, mul_assoc]
@[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0}
(hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) :=
begin
rw ← nnreal.eq_iff,
simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul],
exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd)
end
@[field_simps] lemma inv_eq_one_div (a : ℝ≥0) : a⁻¹ = 1/a :=
by rw [div_def, one_mul]
@[field_simps] lemma div_mul_eq_mul_div (a b c : ℝ≥0) : (a / b) * c = (a * c) / b :=
by { rw [div_def, div_def], ac_refl }
@[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) :
b + a / c = (b * c + a) / c :=
by simpa using div_add_div b a one_ne_zero hc
@[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) :
a / c + b = (a + b * c) / c :=
by rwa [add_comm, add_div', add_comm]
lemma one_div_eq_inv (a : ℝ≥0) : 1 / a = a⁻¹ :=
one_mul a⁻¹
lemma one_div_div (a b : ℝ≥0) : 1 / (a / b) = b / a :=
by { rw ← nnreal.eq_iff, simp [one_div_div] }
lemma div_eq_mul_one_div (a b : ℝ≥0) : a / b = a * (1 / b) :=
by rw [div_def, div_def, one_mul]
@[field_simps] lemma div_div_eq_mul_div (a b c : ℝ≥0) : a / (b / c) = (a * c) / b :=
by { rw ← nnreal.eq_iff, simp [div_div_eq_mul_div] }
@[field_simps] lemma div_div_eq_div_mul (a b c : ℝ≥0) : (a / b) / c = a / (b * c) :=
by { rw ← nnreal.eq_iff, simp [div_div_eq_div_mul] }
@[field_simps] lemma div_eq_div_iff {a b c d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) :
a / b = c / d ↔ a * d = c * b :=
div_eq_div_iff hb hd
@[field_simps] lemma div_eq_iff {a b c : ℝ≥0} (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
by simpa using @div_eq_div_iff a b c 1 hb one_ne_zero
@[field_simps] lemma eq_div_iff {a b c : ℝ≥0} (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
by simpa using @div_eq_div_iff c 1 a b one_ne_zero hb
end inv
section pow
theorem pow_eq_zero {a : ℝ≥0} {n : ℕ} (h : a^n = 0) : a = 0 :=
begin
rw ← nnreal.eq_iff,
rw [← nnreal.eq_iff, coe_pow] at h,
exact pow_eq_zero h
end
@[field_simps] theorem pow_ne_zero {a : ℝ≥0} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
mt pow_eq_zero h
end pow
end nnreal
|
277e7a15a753b92b03f521d7724495bd35b5329a | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/topology/instances/real.lean | fd0a7463250d229bf5aa49fedb264c854c2a1db6 | [
"Apache-2.0"
] | permissive | cipher1024/mathlib | fee56b9954e969721715e45fea8bcb95f9dc03fe | d077887141000fefa5a264e30fa57520e9f03522 | refs/heads/master | 1,651,806,490,504 | 1,573,508,694,000 | 1,573,508,694,000 | 107,216,176 | 0 | 0 | Apache-2.0 | 1,647,363,136,000 | 1,508,213,014,000 | Lean | UTF-8 | Lean | false | false | 19,143 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
The real numbers ℝ.
They are constructed as the topological completion of ℚ. With the following steps:
(1) prove that ℚ forms a uniform space.
(2) subtraction and addition are uniform continuous functions in this space
(3) for multiplication and inverse this only holds on bounded subsets
(4) ℝ is defined as separated Cauchy filters over ℚ (the separation requires a quotient construction)
(5) extend the uniform continuous functions along the completion
(6) proof field properties using the principle of extension of identities
TODO
generalizations:
* topological groups & rings
* order topologies
* Archimedean fields
-/
import topology.metric_space.basic topology.algebra.uniform_group
topology.algebra.ring tactic.linarith
noncomputable theory
open classical set lattice filter topological_space metric
open_locale classical
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
instance : metric_space ℚ :=
metric_space.induced coe rat.cast_injective real.metric_space
theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl
@[elim_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl
instance : metric_space ℤ :=
begin
letI M := metric_space.induced coe int.cast_injective real.metric_space,
refine @metric_space.replace_uniformity _ int.uniform_space M
(le_antisymm refl_le_uniformity $ λ r ru,
mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h,
mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩),
simpa using (@int.cast_le ℝ _ _ 0).2 (int.lt_add_one_iff.1 $
(@int.cast_lt ℝ _ (abs (a - b)) 1).1 $ by simpa using h)
end
theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl
@[elim_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl
@[elim_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y :=
by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast
theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) :=
uniform_continuous_comap
theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) :=
uniform_embedding_comap rat.cast_injective
theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) :=
uniform_embedding_of_rat.dense_embedding $
λ x, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in
let ⟨q, h⟩ := exists_rat_near x ε0 in
ne_empty_iff_exists_mem.2 ⟨_, hε (mem_ball'.2 h), q, rfl⟩
theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding
theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous
theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in
⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩
-- TODO(Mario): Find a way to use rat_add_continuous_lemma
theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) :=
uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact
real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk
(uniform_continuous_of_rat.comp uniform_continuous_snd))
theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) :=
metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [real.dist_eq] using h⟩
theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) :=
metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [rat.dist_eq] using h⟩
instance : uniform_add_group ℝ :=
uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg
instance : uniform_add_group ℚ :=
uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg
instance : topological_add_group ℝ := by apply_instance
instance : topological_add_group ℚ := by apply_instance
instance : orderable_topology ℚ :=
induced_orderable_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _)
lemma real.is_topological_basis_Ioo_rat :
@is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) :=
is_topological_basis_of_open_of_nhds
(by simp [is_open_Ioo] {contextual:=tt})
(assume a v hav hv,
let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav),
⟨q, hlq, hqa⟩ := exists_rat_btwn hl,
⟨p, hap, hpu⟩ := exists_rat_btwn hu in
⟨Ioo q p,
by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩,
⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩)
instance : second_countable_topology ℝ :=
⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}),
by simp [countable_Union, countable_Union_Prop],
real.is_topological_basis_Ioo_rat.2.2⟩⟩
/- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings
lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) :=
_
lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) :=
_ -/
lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) :
uniform_continuous (λp:s, p.1⁻¹) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in
⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩
lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩
lemma real.continuous_abs : continuous (abs : ℝ → ℝ) :=
real.uniform_continuous_abs.continuous
lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
⟨ε, ε0, λ a b h, lt_of_le_of_lt
(by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩
lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) :=
rat.uniform_continuous_abs.continuous
lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (nhds r) (nhds r⁻¹) :=
by rw ← abs_pos_iff at r0; exact
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h))
(mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0))
lemma real.continuous_inv' : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) :=
continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩,
tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _)
lemma real.continuous_inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) :
continuous (λa, (f a)⁻¹) :=
show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩),
from real.continuous_inv'.comp (continuous_subtype_mk _ hf)
lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) :=
metric.uniform_continuous_iff.2 $ λ ε ε0, begin
cases no_top (abs x) with y xy,
have y0 := lt_of_le_of_lt (abs_nonneg _) xy,
refine ⟨_, div_pos ε0 y0, λ a b h, _⟩,
rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)],
exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0
end
lemma real.uniform_continuous_mul (s : set (ℝ × ℝ))
{r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) :
uniform_continuous (λp:s, p.1.1 * p.1.2) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in
⟨δ, δ0, λ a b h,
let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩
protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) :=
continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩,
tendsto_of_uniform_continuous_subtype
(real.uniform_continuous_mul
({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1})
(λ x, id))
(mem_nhds_sets
(is_open_prod
(real.continuous_abs _ $ is_open_gt' (abs a₁ + 1))
(real.continuous_abs _ $ is_open_gt' (abs a₂ + 1)))
⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩)
instance : topological_ring ℝ :=
{ continuous_mul := real.continuous_mul, ..real.topological_add_group }
instance : topological_semiring ℝ := by apply_instance
lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) :=
embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact
real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk
(continuous_of_rat.comp continuous_snd))
instance : topological_ring ℚ :=
{ continuous_mul := rat.continuous_mul, ..rat.topological_add_group }
theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) :=
set.ext $ λ y, by rw [mem_ball, real.dist_eq,
abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl
theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) :=
metric.totally_bounded_iff.2 $ λ ε ε0, begin
rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩,
rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba,
let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n},
refine ⟨s, finite_image _ ⟨set.fintype_lt_nat _⟩, λ x h, _⟩,
rcases h with ⟨ax, xb⟩,
let i : ℕ := ⌊(x - a) / ε⌋.to_nat,
have : (i : ℤ) = ⌊(x - a) / ε⌋ :=
int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)),
simp, refine ⟨_, ⟨i, _, rfl⟩, _⟩,
{ rw [← int.coe_nat_lt, this],
refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _),
rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'],
exact lt_trans xb ba },
{ rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg,
← sub_sub, sub_lt_iff_lt_add'],
{ have := lt_floor_add_one ((x - a) / ε),
rwa [div_lt_iff' ε0, mul_add, mul_one] at this },
{ have := floor_le ((x - a) / ε),
rwa [ge, sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } }
end
lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) :=
by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo
lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) :=
let ⟨c, ac⟩ := no_bot a in totally_bounded_subset
(by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩)
(real.totally_bounded_Ioo c b)
lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) :=
let ⟨c, bc⟩ := no_top b in totally_bounded_subset
(by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩)
(real.totally_bounded_Ico a c)
lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) :=
begin
have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b),
rwa (set.ext (λ q, _) : Icc _ _ = _), simp
end
-- TODO(Mario): Generalize to first-countable uniform spaces?
instance : complete_space ℝ :=
⟨λ f cf, begin
let g : ℕ → {ε:ℝ//ε>0} := λ n, ⟨n.to_pnat'⁻¹, inv_pos (nat.cast_pos.2 n.to_pnat'.pos)⟩,
choose S hS hS_dist using show ∀n:ℕ, ∃t ∈ f.sets, ∀ x y ∈ t, dist x y < g n, from
assume n, let ⟨t, tf, h⟩ := (metric.cauchy_iff.1 cf).2 (g n).1 (g n).2 in ⟨t, tf, h⟩,
let F : ℕ → set ℝ := λn, ⋂i≤n, S i,
have hF : ∀n, F n ∈ f.sets := assume n, Inter_mem_sets (finite_le_nat n) (λ i _, hS i),
have hF_dist : ∀n, ∀ x y ∈ F n, dist x y < g n :=
assume n x y hx hy,
have F n ⊆ S n := bInter_subset_of_mem (le_refl n),
(hS_dist n) _ _ (this hx) (this hy),
choose G hG using assume n:ℕ, inhabited_of_mem_sets cf.1 (hF n),
have hg : ∀ ε > 0, ∃ n, ∀ j ≥ n, (g j : ℝ) < ε,
{ intros ε ε0,
cases exists_nat_gt ε⁻¹ with n hn,
refine ⟨n, λ j nj, _⟩,
have hj := lt_of_lt_of_le hn (nat.cast_le.2 nj),
have j0 := lt_trans (inv_pos ε0) hj,
have jε := (inv_lt j0 ε0).2 hj,
rwa ← pnat.to_pnat'_coe (nat.cast_pos.1 j0) at jε },
let c : cau_seq ℝ abs,
{ refine ⟨λ n, G n, λ ε ε0, _⟩,
cases hg _ ε0 with n hn,
refine ⟨n, λ j jn, _⟩,
have : F j ⊆ F n :=
bInter_subset_bInter_left (λ i h, @le_trans _ _ i n j h jn),
exact lt_trans (hF_dist n _ _ (this (hG j)) (hG n)) (hn _ $ le_refl _) },
refine ⟨cau_seq.lim c, λ s h, _⟩,
rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩,
cases exists_forall_ge_and (hg _ $ half_pos ε0)
(cau_seq.equiv_lim c _ $ half_pos ε0) with n hn,
cases hn _ (le_refl _) with h₁ h₂,
refine sets_of_superset _ (hF n) (subset.trans _ $
subset.trans (ball_half_subset (G n) h₂) hε),
exact λ x h, lt_trans ((hF_dist n) x (G n) h (hG n)) h₁
end⟩
lemma tendsto_coe_nat_real_at_top_iff {f : α → ℕ} {l : filter α} :
tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top :=
tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) $
assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨n, le_of_lt hn⟩
lemma tendsto_coe_nat_real_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top :=
tendsto_coe_nat_real_at_top_iff.2 tendsto_id
lemma tendsto_coe_int_real_at_top_iff {f : α → ℤ} {l : filter α} :
tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top :=
tendsto_at_top_embedding (assume a₁ a₂, int.cast_le) $
assume r, let ⟨n, hn⟩ := exists_nat_gt r in
⟨(n:ℤ), le_of_lt $ by rwa [int.cast_coe_nat]⟩
lemma tendsto_coe_int_real_at_top_at_top : tendsto (coe : ℤ → ℝ) at_top at_top :=
tendsto_coe_int_real_at_top_iff.2 tendsto_id
section
lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} :=
subset.antisymm
((closure_subset_iff_subset_of_is_closed (is_closed_ge' _)).2
(image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $
λ x hx, mem_closure_iff_nhds.2 $ λ t ht,
let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in
let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in
ne_empty_iff_exists_mem.2 ⟨_, hε (show abs _ < _,
by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']),
p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩
/- TODO(Mario): Put these back only if needed later
lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} :=
_
lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) :
closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} :=
_-/
lemma compact_Icc {a b : ℝ} : compact (Icc a b) :=
compact_of_totally_bounded_is_closed
(real.totally_bounded_Icc a b)
(is_closed_inter (is_closed_ge' a) (is_closed_le' b))
instance : proper_space ℝ :=
{ compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc }
open real
lemma real.intermediate_value {f : ℝ → ℝ} {a b t : ℝ}
(hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x)))
(ha : f a ≤ t) (hb : t ≤ f b) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t :=
let x := real.Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} in
have hx₁ : ∃ y, ∀ g ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b}, g ≤ y := ⟨b, λ _ h, h.2.2⟩,
have hx₂ : ∃ y, y ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} := ⟨a, ha, le_refl _, hab⟩,
have hax : a ≤ x, from le_Sup _ hx₁ ⟨ha, le_refl _, hab⟩,
have hxb : x ≤ b, from (Sup_le _ hx₂ hx₁).2 (λ _ h, h.2.2),
⟨x, hax, hxb,
eq_of_forall_dist_le $ λ ε ε0,
let ⟨δ, hδ0, hδ⟩ := metric.tendsto_nhds_nhds.1 (hf _ hax hxb) ε ε0 in
(le_total t (f x)).elim
(λ h, le_of_not_gt $ λ hfε, begin
rw [dist_eq, abs_of_nonneg (sub_nonneg.2 h)] at hfε,
refine mt (Sup_le {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} hx₂ hx₁).2
(not_le_of_gt (sub_lt_self x (half_pos hδ0)))
(λ g hg, le_of_not_gt
(λ hgδ, not_lt_of_ge hg.1
(lt_trans (lt_sub.1 hfε) (sub_lt_of_sub_lt
(lt_of_le_of_lt (le_abs_self _) _))))),
rw abs_sub,
exact hδ (abs_sub_lt_iff.2 ⟨lt_of_le_of_lt (sub_nonpos.2 (le_Sup _ hx₁ hg)) hδ0,
by simp only [x] at *; linarith⟩)
end)
(λ h, le_of_not_gt $ λ hfε, begin
rw [dist_eq, abs_of_nonpos (sub_nonpos.2 h)] at hfε,
exact mt (le_Sup {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b})
(λ h : ∀ k, k ∈ {x | f x ≤ t ∧ a ≤ x ∧ x ≤ b} → k ≤ x,
not_le_of_gt ((lt_add_iff_pos_left x).2 (half_pos hδ0))
(h _ ⟨le_trans (le_sub_iff_add_le.2 (le_trans (le_abs_self _)
(le_of_lt (hδ $ by rw [dist_eq, add_sub_cancel, abs_of_nonneg (le_of_lt (half_pos hδ0))];
exact half_lt_self hδ0))))
(by linarith),
le_trans hax (le_of_lt ((lt_add_iff_pos_left _).2 (half_pos hδ0))),
le_of_not_gt (λ hδy, not_lt_of_ge hb (lt_of_le_of_lt
(show f b ≤ f b - f x - ε + t, by linarith)
(add_lt_of_neg_of_le
(sub_neg_of_lt (lt_of_le_of_lt (le_abs_self _)
(@hδ b (abs_sub_lt_iff.2 ⟨by simp only [x] at *; linarith,
by linarith⟩))))
(le_refl _))))⟩))
hx₁
end)⟩
lemma real.intermediate_value' {f : ℝ → ℝ} {a b t : ℝ}
(hf : ∀ x, a ≤ x → x ≤ b → tendsto f (nhds x) (nhds (f x)))
(ha : t ≤ f a) (hb : f b ≤ t) (hab : a ≤ b) : ∃ x : ℝ, a ≤ x ∧ x ≤ b ∧ f x = t :=
let ⟨x, hx₁, hx₂, hx₃⟩ := @real.intermediate_value
(λ x, - f x) a b (-t) (λ x hax hxb, tendsto_neg (hf x hax hxb))
(neg_le_neg ha) (neg_le_neg hb) hab in
⟨x, hx₁, hx₂, neg_inj hx₃⟩
lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s :=
⟨begin
assume bdd,
rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r
rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r)
exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩
end,
begin
rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩,
have I : s ⊆ Icc m M := λx hx, ⟨hm x hx, hM x hx⟩,
have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) :=
by rw closed_ball_Icc; congr; ring,
rw this at I,
exact bounded.subset I bounded_closed_ball
end⟩
end
|
30723b8e541af13aa6ba202abaa9718ad2f801a8 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/simplifier5.lean | ff8ebc31fcf056573096189aa6e9d8931bfb9fe5 | [
"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 | 749 | lean | /- Basic rewriting with iff with congr_iff -/
import logic.connectives
open nat
attribute not_true [simp]
#simplify iff env 2 (@le nat nat_has_le 0 0) -- true
#simplify iff env 2 (@le nat nat_has_le 0 1) -- true
#simplify iff env 2 (@le nat nat_has_le 0 2) -- true
#simplify iff env 2 (@lt nat nat_has_lt 0 0) -- false
#simplify iff env 2 (@lt nat nat_has_lt 0 (succ 0)) -- true
#simplify iff env 2 (@lt nat nat_has_lt 1 (succ 1)) -- true
#simplify iff env 2 (@lt nat nat_has_lt 0 (succ (succ 0))) -- true
#simplify iff env 2 (@le nat nat_has_le 0 0 ↔ @le nat nat_has_le 0 0) -- true
#simplify iff env 2 (@le nat nat_has_le 0 0 ↔ @le nat nat_has_le 0 1) -- true
#simplify iff env 2 (@le nat nat_has_le 0 0 ↔ @lt nat nat_has_lt 0 0) -- false
|
c956c3508f262f75b1a515b77a7dd42bce7e262c | 42610cc2e5db9c90269470365e6056df0122eaa0 | /hott/homotopy/EM.hlean | 3b3c8f4720f9917f2836753a8c7d086cd0f77723 | [
"Apache-2.0"
] | permissive | tomsib2001/lean | 2ab59bfaebd24a62109f800dcf4a7139ebd73858 | eb639a7d53fb40175bea5c8da86b51d14bb91f76 | refs/heads/master | 1,586,128,387,740 | 1,468,968,950,000 | 1,468,968,950,000 | 61,027,234 | 0 | 0 | null | 1,465,813,585,000 | 1,465,813,585,000 | null | UTF-8 | Lean | false | false | 8,934 | hlean | /-
Copyright (c) 2016 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Eilenberg MacLane spaces
-/
import hit.groupoid_quotient .hopf .freudenthal .homotopy_group
open algebra pointed nat eq category group algebra is_trunc iso pointed unit trunc equiv is_conn
namespace EM
open groupoid_quotient
variable {G : Group}
definition EM1 (G : Group) : Type :=
groupoid_quotient (Groupoid_of_Group G)
definition pEM1 [constructor] (G : Group) : Type* :=
pointed.MK (EM1 G) (elt star)
definition base : EM1 G := elt star
definition pth : G → base = base := pth
definition resp_mul (g h : G) : pth (g * h) = pth g ⬝ pth h := resp_comp h g
definition resp_one : pth (1 : G) = idp :=
resp_id star
definition resp_inv (g : G) : pth (g⁻¹) = (pth g)⁻¹ :=
resp_inv g
local attribute pointed.MK pointed.carrier pEM1 EM1 [reducible]
protected definition rec {P : EM1 G → Type} [H : Π(x : EM1 G), is_trunc 1 (P x)]
(Pb : P base) (Pp : Π(g : G), Pb =[pth g] Pb)
(Pmul : Π(g h : G), change_path (resp_mul g h) (Pp (g * h)) = Pp g ⬝o Pp h) (x : EM1 G) : P x :=
begin
induction x,
{ induction g, exact Pb},
{ induction a, induction b, exact Pp f},
{ induction a, induction b, induction c, exact Pmul f g}
end
protected definition rec_on {P : EM1 G → Type} [H : Π(x : EM1 G), is_trunc 1 (P x)]
(x : EM1 G) (Pb : P base) (Pp : Π(g : G), Pb =[pth g] Pb)
(Pmul : Π(g h : G), change_path (resp_mul g h) (Pp (g * h)) = Pp g ⬝o Pp h) : P x :=
EM.rec Pb Pp Pmul x
protected definition set_rec {P : EM1 G → Type} [H : Π(x : EM1 G), is_set (P x)]
(Pb : P base) (Pp : Π(g : G), Pb =[pth g] Pb) (x : EM1 G) : P x :=
EM.rec Pb Pp !center x
protected definition prop_rec {P : EM1 G → Type} [H : Π(x : EM1 G), is_prop (P x)]
(Pb : P base) (x : EM1 G) : P x :=
EM.rec Pb !center !center x
definition rec_pth {P : EM1 G → Type} [H : Π(x : EM1 G), is_trunc 1 (P x)]
{Pb : P base} {Pp : Π(g : G), Pb =[pth g] Pb}
(Pmul : Π(g h : G), change_path (resp_mul g h) (Pp (g * h)) = Pp g ⬝o Pp h)
(g : G) : apd (EM.rec Pb Pp Pmul) (pth g) = Pp g :=
proof !rec_pth qed
protected definition elim {P : Type} [is_trunc 1 P] (Pb : P) (Pp : Π(g : G), Pb = Pb)
(Pmul : Π(g h : G), Pp (g * h) = Pp g ⬝ Pp h) (x : EM1 G) : P :=
begin
induction x,
{ exact Pb},
{ exact Pp f},
{ exact Pmul f g}
end
protected definition elim_on [reducible] {P : Type} [is_trunc 1 P] (x : EM1 G)
(Pb : P) (Pp : G → Pb = Pb) (Pmul : Π(g h : G), Pp (g * h) = Pp g ⬝ Pp h) : P :=
EM.elim Pb Pp Pmul x
protected definition set_elim [reducible] {P : Type} [is_set P] (Pb : P) (Pp : G → Pb = Pb)
(x : EM1 G) : P :=
EM.elim Pb Pp !center x
protected definition prop_elim [reducible] {P : Type} [is_prop P] (Pb : P) (x : EM1 G) : P :=
EM.elim Pb !center !center x
definition elim_pth {P : Type} [is_trunc 1 P] {Pb : P} {Pp : G → Pb = Pb}
(Pmul : Π(g h : G), Pp (g * h) = Pp g ⬝ Pp h) (g : G) : ap (EM.elim Pb Pp Pmul) (pth g) = Pp g :=
proof !elim_pth qed
protected definition elim_set.{u} (Pb : Set.{u}) (Pp : Π(g : G), Pb ≃ Pb)
(Pmul : Π(g h : G) (x : Pb), Pp (g * h) x = Pp h (Pp g x)) (x : EM1 G) : Set.{u} :=
groupoid_quotient.elim_set (λu, Pb) (λu v, Pp) (λu v w g h, proof Pmul h g qed) x
theorem elim_set_pth {Pb : Set} {Pp : Π(g : G), Pb ≃ Pb}
(Pmul : Π(g h : G) (x : Pb), Pp (g * h) x = Pp h (Pp g x)) (g : G) :
transport (EM.elim_set Pb Pp Pmul) (pth g) = Pp g :=
!elim_set_pth
end EM
-- attribute EM.rec EM.elim [recursor 7]
attribute EM.base [constructor]
attribute EM.rec EM.elim [unfold 7] [recursor 7]
attribute EM.rec_on EM.elim_on [unfold 4]
attribute EM.set_rec EM.set_elim [unfold 6]
attribute EM.prop_rec EM.prop_elim EM.elim_set [unfold 5]
namespace EM
open groupoid_quotient
definition base_eq_base_equiv [constructor] (G : Group) : (base = base :> pEM1 G) ≃ G :=
!elt_eq_elt_equiv
definition fundamental_group_pEM1 (G : Group) : π₁ (pEM1 G) ≃g G :=
begin
fapply isomorphism_of_equiv,
{ exact trunc_equiv_trunc 0 !base_eq_base_equiv ⬝e trunc_equiv 0 G},
{ intros g h, induction g with p, induction h with q,
exact encode_con p q}
end
proposition is_trunc_pEM1 [instance] (G : Group) : is_trunc 1 (pEM1 G) :=
!is_trunc_groupoid_quotient
proposition is_trunc_EM1 [instance] (G : Group) : is_trunc 1 (EM1 G) :=
!is_trunc_groupoid_quotient
proposition is_conn_EM1 [instance] (G : Group) : is_conn 0 (EM1 G) :=
by apply @is_conn_groupoid_quotient; esimp; exact _
proposition is_conn_pEM1 [instance] (G : Group) : is_conn 0 (pEM1 G) :=
is_conn_EM1 G
-- TODO: prove this using truncated Whitehead.
definition EM1_map [unfold 7] {G : Group} {X : Type*} (e : Ω X ≃ G)
(r : Πp q, e (p ⬝ q) = e p * e q) [is_conn 0 X] [is_trunc 1 X] : EM1 G → X :=
begin
intro x, induction x using EM.elim,
{ exact Point X},
{ note p := e⁻¹ᵉ g, exact p},
{ exact inv_preserve_binary e concat mul r g h}
end
-- TODO
-- definition EM1_equiv {G : Group} {X : Type*} (e : Ω X ≃ G)
-- (r : Πp q, e (p ⬝ q) = e p * e q) [is_conn 0 X] [is_trunc 1 X] : EM1 G ≃ X :=
-- begin
-- apply equiv.mk (EM1_map e r),
-- apply whiteheads_principle 1,
-- { apply is_equiv_of_is_contr},
-- { intro x n, cases n with n,
-- { exact sorry},
-- { apply @is_equiv_of_is_contr, do 2 exact sorry}}
-- end
-- definition pequiv_pEM1 {G : Group} {X : Type*} (e : π₁ X ≃g G) [is_conn 0 X] [is_trunc 1 X]
-- : X ≃* pEM1 G :=
-- sorry
end EM
open hopf susp
namespace EM
-- The K(G,n+1):
variables (G : CommGroup) (n : ℕ)
definition EM1_mul [unfold 2 3] {G : CommGroup} (x x' : EM1 G) : EM1 G :=
begin
induction x,
{ exact x'},
{ induction x' using EM.set_rec,
{ exact pth g},
{ exact abstract begin apply loop_pathover, apply square_of_eq,
refine !resp_mul⁻¹ ⬝ _ ⬝ !resp_mul,
exact ap pth !mul.comm end end}},
{ refine EM.prop_rec _ x', esimp, apply resp_mul},
end
definition EM1_mul_one (G : CommGroup) (x : EM1 G) : EM1_mul x base = x :=
begin
induction x using EM.set_rec,
{ reflexivity},
{ apply eq_pathover_id_right, apply hdeg_square, refine EM.elim_pth _ g}
end
definition h_space_EM1 [constructor] [instance] (G : CommGroup) : h_space (pEM1 G) :=
begin
fapply h_space.mk,
{ exact EM1_mul},
{ exact base},
{ intro x', reflexivity},
{ apply EM1_mul_one}
end
/- K(G, n+1) -/
definition EMadd1 (G : CommGroup) (n : ℕ) : Type* :=
ptrunc (n+1) (iterate_psusp n (pEM1 G))
definition loop_EM2 (G : CommGroup) : Ω[1] (EMadd1 G 1) ≃* pEM1 G :=
begin
apply hopf.delooping, reflexivity
end
definition homotopy_group_EM2 (G : CommGroup) : πg[1+1] (EMadd1 G 1) ≃g G :=
begin
refine ghomotopy_group_succ_in _ 0 ⬝g _,
refine homotopy_group_isomorphism_of_pequiv 0 (loop_EM2 G) ⬝g _,
apply fundamental_group_pEM1
end
definition homotopy_group_EMadd1 (G : CommGroup) (n : ℕ) : πg[n+1] (EMadd1 G n) ≃g G :=
begin
cases n with n,
{ refine homotopy_group_isomorphism_of_pequiv 0 _ ⬝g fundamental_group_pEM1 G,
apply ptrunc_pequiv, apply is_trunc_pEM1},
induction n with n IH,
{ apply homotopy_group_EM2 G},
refine _ ⬝g IH,
refine !ghomotopy_group_ptrunc ⬝g _ ⬝g !ghomotopy_group_ptrunc⁻¹ᵍ,
apply iterate_psusp_stability_isomorphism,
rexact add_mul_le_mul_add n 1 1
end
local attribute EMadd1 [reducible]
definition is_conn_EMadd1 (G : CommGroup) (n : ℕ) : is_conn n (EMadd1 G n) := _
definition is_trunc_EMadd1 (G : CommGroup) (n : ℕ) : is_trunc (n+1) (EMadd1 G n) := _
/- K(G, n+1) -/
definition EM (G : CommGroup) : ℕ → Type*
| 0 := pType_of_Group G
| (k+1) := EMadd1 G k
definition phomotopy_group_EM (G : CommGroup) (n : ℕ) : π*[n] (EM G n) ≃* pType_of_Group G :=
begin
cases n with n,
{ rexact ptrunc_pequiv 0 (pType_of_Group G) _},
{ apply pequiv_of_isomorphism (homotopy_group_EMadd1 G n)}
end
definition ghomotopy_group_EM (G : CommGroup) (n : ℕ) : πg[n+1] (EM G (n+1)) ≃g G :=
homotopy_group_EMadd1 G n
definition is_conn_EM [instance] (G : CommGroup) (n : ℕ) : is_conn (n.-1) (EM G n) :=
begin
cases n with n,
{ apply is_conn_minus_one, apply tr, unfold [EM], exact 1},
{ apply is_conn_EMadd1}
end
definition is_conn_EM_succ [instance] (G : CommGroup) (n : ℕ) : is_conn n (EM G (succ n)) :=
is_conn_EM G (succ n)
definition is_trunc_EM [instance] (G : CommGroup) (n : ℕ) : is_trunc n (EM G n) :=
begin
cases n with n,
{ unfold [EM], apply semigroup.is_set_carrier},
{ apply is_trunc_EMadd1}
end
end EM
|
f8a53e5a189525695383de3716606984cd078382 | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/myset/basic.lean | 267568c32640b37e77019319ed788290df2c8cfa | [] | 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 | 16,810 | lean | -- vim: ts=2 sw=0 sts=-1 et ai tw=70
import ..logic
namespace hidden
universes u v w
-- A set of elements of type α is a function from elements of type α
-- to propositions
def myset (α : Type u) := α → Prop
-- Not sure if we want this, but I don't think it hurts
namespace myset
-- Need u and v to be most general
variables {α : Type u} {β : Type v}
def mem (a : α) (s : myset α) : Prop := s a
instance: has_mem α (myset α) := ⟨myset.mem⟩
theorem mem_def {a : α} {s : myset α} : a ∈ s = s a := rfl
theorem setext (A B : myset α) : (∀ x : α, x ∈ A ↔ x ∈ B) → A = B :=
begin
assume h,
apply funext,
intro x,
apply propext,
from h x,
end
def subset (s : myset α) (t : myset α) : Prop :=
∀ a : α, s a → t a
-- Use \subseteq
instance: has_subset (myset α) := ⟨myset.subset⟩
theorem setext_subs (A B: myset α): A ⊆ B → B ⊆ A → A = B :=
begin
assume hAB hBA,
apply setext,
intro x,
split; assume hx, {
apply hAB,
assumption,
}, {
apply hBA,
assumption,
},
end
@[refl]
theorem subset_refl (s: myset α):
s ⊆ s :=
λ x hxs, hxs
@[trans]
theorem subset_trans (A B C: myset α):
A ⊆ B → B ⊆ C → A ⊆ C :=
λ hAB hBC x hx, hBC x (hAB x hx)
def power_set (s : myset α) : myset (myset α) :=
λ t, t ⊆ s
def intersection (s : myset α) (t : myset α) : myset α :=
λ a, s a ∧ t a
instance: has_inter (myset α) := ⟨intersection⟩
def union (s : myset α) (t : myset α) : myset α :=
λ a, s a ∨ t a
instance: has_union (myset α) := ⟨union⟩
-- Construct an empty set with type α
def empty_of (α : Type u) : myset α := λ a, false
def empty {α : Type u} (s : myset α) : Prop := ∀ a : α, ¬(a ∈ s)
def all_of (α : Type u) : myset α := λ a, true
theorem exists_iff_nempty {s : myset α} :
(∃ x, x ∈ s) ↔ ¬empty s :=
begin
split; assume h, {
assume hemp,
cases h with x hx,
have := hemp x,
contradiction,
}, {
unfold myset.empty at h,
rw not_forall at h,
cases h with k hk,
existsi k,
rw not_not at hk,
assumption,
},
end
-- Set product, gives myset (α × β)
def set_prod (U : myset α) (V : myset β) : myset (α × β) :=
{t | t.1 ∈ U ∧ t.2 ∈ V}
notation U × V := set_prod U V
instance : has_emptyc (myset α) :=
⟨λ a, false⟩
theorem in_empty_false (x : α) : x ∈ (∅ : myset α) → false :=
begin
assume hx,
assumption,
end
theorem empty_iff_eq_empty {s: myset α}: empty s ↔ s = ∅ :=
begin
split; assume h, {
apply setext,
intro a,
have := h a,
split, {
assume hs, contradiction,
}, {
assume he,
exfalso,
from he,
},
}, {
intro a,
assume hs,
rw h at hs,
from hs,
},
end
theorem exists_iff_neq_empty {S: myset α}:
(∃ x, x ∈ S) ↔ S ≠ ∅ :=
begin
have: S ≠ ∅ ↔ ¬S = ∅ := iff.rfl,
rw this,
rw ←empty_iff_eq_empty,
rw ←exists_iff_nempty,
end
@[reducible]
def sUnion (s : myset (myset α)) : myset α := {t | ∃ a ∈ s, t ∈ a}
prefix `⋃₀`:120 := sUnion
@[reducible]
def sIntersection (s : myset (myset α)) : myset α :=
{t | ∀ a ∈ s, t ∈ a}
prefix `⋂₀`:120 := sIntersection
theorem union_two_sUnion
{α: Type u} (U V: myset α):
(U ∪ V) = ⋃₀ {S | S = U ∨ S = V} :=
begin
apply setext,
intro x,
split, {
assume hUVx,
cases hUVx with hUx hVx, {
existsi U,
existsi (or.inl rfl),
assumption,
}, {
existsi V,
existsi (or.inr rfl),
assumption,
},
}, {
assume hUVx,
cases hUVx with S hS,
cases hS with hS hx,
cases hS with hU hV, {
left,
rw ←hU,
assumption,
}, {
right,
rw ←hV,
assumption,
},
},
end
theorem intersect_two_sIntersection
{α: Type u} (U V: myset α):
(U ∩ V) = ⋂₀ {S | S = U ∨ S = V} :=
begin
apply setext,
intro x,
split, {
assume hUVx,
cases hUVx with hUx hVx,
intro S,
assume hS,
cases hS; {rw hS; assumption},
}, {
assume hUVx,
split, {
from hUVx U (or.inl rfl),
}, {
from hUVx V (or.inr rfl),
},
},
end
def univ : myset α :=
λ a, true
def singleton (x: α): myset α :=
{y | y = x}
theorem singleton_eq (x y: α): y ∈ singleton x → y = x :=
begin
assume hyx,
from hyx,
end
def image {α β : Type u} (f : α → β) (U : myset α) := {b | ∃ a, a ∈ U ∧ f a = b}
-- comes up often in algebra & topology etc
def imageu {α β: Type u} (f: α → β) := {b: β | ∃ a: α, f a = b}
def inverse_image {α β : Type u} (f : α → β) (V : myset β) := {a | f a ∈ V}
def cartprod {α: Type u} (I: Type u) (sets: I → myset α): Type u :=
{f: I → α // ∀ i: I, f i ∈ sets i}
theorem inverse_image_of_image
{α β : Type} (f: α → β) (U : myset α):
U ⊆ inverse_image f (image f U) :=
begin
intro x,
assume hx,
existsi x,
split, assumption, trivial,
end
theorem image_of_inverse_image
{α β : Type} (f: α → β) (U : myset β):
image f (inverse_image f U) ⊆ U :=
begin
intro x,
assume hx,
cases hx with y hy,
rw ←hy.right,
from hy.left,
end
theorem subset_empty_impl_empty
{α: Type} (U: myset α):
U ⊆ ∅ → U = ∅ :=
begin
assume hUe,
apply setext,
intro x,
split; assume h, {
from hUe _ h,
}, {
exfalso, from h,
},
end
theorem univ_subset_impl_univ
{α: Type} (U: myset α):
myset.univ ⊆ U → U = myset.univ :=
begin
assume h,
apply setext,
intro x,
split; assume hux, {
trivial,
}, {
from h x trivial,
},
end
theorem image_nonempty
{α β : Type} (f: α → β) (U: myset α):
U ≠ ∅ → image f U ≠ ∅ :=
begin
assume hUne,
assume hpreUe,
rw ←empty_iff_eq_empty at hpreUe,
change ¬(U = ∅) at hUne,
rw ←empty_iff_eq_empty at hUne,
rw ←exists_iff_nempty at hUne,
cases hUne with x hx,
apply hpreUe (f x),
existsi x,
split, assumption, refl,
end
theorem image_empty
{α β : Type} (f: α → β) (U: myset α):
U = ∅ → image f U = ∅ :=
begin
assume hUe,
apply setext,
intro x,
split; assume h, {
cases h with y hy,
rw hUe at hy,
from hy.left,
}, {
exfalso, from h,
},
end
theorem inverse_image_empty
{α β : Type} (f: α → β) (U: myset β):
U = ∅ → inverse_image f U = ∅ :=
begin
assume hUe,
apply setext,
intro x,
split; assume h, {
rw hUe at h,
from h,
}, {
exfalso, from h,
},
end
theorem inverse_image_intersection
{α β : Type} (f: α → β) (U V: myset β):
inverse_image f (U ∩ V) = inverse_image f U ∩ inverse_image f V :=
begin
refl,
end
theorem inverse_image_union
{α β : Type} (f: α → β) (U V: myset β):
inverse_image f (U ∪ V) = inverse_image f U ∪ inverse_image f V :=
begin
refl,
end
theorem inverse_image_sUnion
{α β : Type} (f: α → β) (S: myset (myset β)):
inverse_image f ⋃₀ S = ⋃₀ image (inverse_image f) S :=
begin
apply setext,
intro x,
split; assume hx, {
cases hx with U hU,
cases hU with hU hxU,
existsi (inverse_image f U),
split, {
existsi U,
split, {
assumption,
}, {
refl,
},
}, {
assumption,
},
}, {
cases hx with U hU,
cases hU with hU hxU,
cases hU with V hV,
existsi V,
split, {
from hV.left,
}, {
rw ←hV.right at hxU,
from hxU,
},
},
end
theorem inverse_image_sIntersection
{α β : Type} (f: α → β) (S: myset (myset β)):
inverse_image f ⋂₀ S = ⋂₀ image (inverse_image f) S :=
begin
apply setext,
intro x,
split; assume hx, {
intro U,
assume hUS,
cases hUS with V hV,
rw ←hV.right,
from hx V hV.left,
}, {
intro U,
assume hUs,
apply hx,
existsi U,
split, {
assumption,
}, {
refl,
},
},
end
theorem image_intersection
{α β : Type} (f: α → β) (U V: myset α):
image f (U ∩ V) ⊆ image f U ∩ image f V :=
begin
intro x,
assume hx,
cases hx with y hy,
split, {
existsi y,
split, {
from hy.left.left,
}, {
from hy.right,
},
}, {
existsi y,
split, {
from hy.left.right,
}, {
from hy.right,
},
},
end
theorem image_union
{α β : Type} (f: α → β) (U V: myset α):
image f (U ∪ V) = image f U ∪ image f V :=
begin
apply setext,
intro x,
split; assume hx, {
cases hx with y hy,
cases hy with hyUV hfyx,
rw ←hfyx,
cases hyUV with hyU hyV, {
left,
existsi y,
split, {
assumption,
}, {
refl,
},
}, {
right,
existsi y,
split, {
assumption,
}, {
refl,
},
},
}, {
cases hx with hxfU hxfV, {
cases hxfU with y hy,
existsi y,
split, {
left,
from hy.left,
}, {
from hy.right,
},
}, {
cases hxfV with y hy,
existsi y,
split, {
right,
from hy.left,
}, {
from hy.right,
},
},
},
end
theorem image_sUnion
{α β : Type} (f: α → β) (S: myset (myset α)):
image f ⋃₀ S = ⋃₀ image (image f) S :=
begin
apply setext,
intro x,
split; assume hx, {
cases hx with y hy,
cases hy with hy hfyx,
cases hy with U hU,
cases hU with hU hyU,
existsi image f U,
split, {
existsi U,
split, {
assumption,
}, {
refl,
},
}, {
existsi y,
split; assumption,
},
}, {
cases hx with U hU,
cases hU with hU hxU,
cases hU with V hV,
rw ←hV.right at hxU,
cases hxU with y hy,
existsi y,
split, {
existsi V,
split, {
from hV.left,
}, {
from hy.left,
},
}, {
from hy.right,
},
},
end
theorem image_sIntersection
{α β : Type} (f: α → β) (S: myset (myset α)):
image f ⋂₀ S ⊆ ⋂₀ image (image f) S :=
begin
intro x,
assume hx,
intro U,
assume hU,
cases hU with V hV,
cases hx with y hy,
rw ←hy.right,
rw ←hV.right,
existsi y,
split, {
apply hy.left,
from hV.left,
}, {
refl,
},
end
theorem inverse_image_composition
{α β γ: Type} (f: α → β) (g: β → γ) (U: myset γ):
inverse_image (g ∘ f) U =
inverse_image f (inverse_image g U) :=
begin
apply setext,
intro x,
refl,
end
theorem image_composition
{α β γ: Type} (f: α → β) (g: β → γ) (U: myset α):
image (g ∘ f) U =
image g (image f U) :=
begin
apply setext,
intro x,
split; assume h, {
cases h with y hy,
existsi f y,
split, {
existsi y, {
split, {
from hy.left,
}, {
refl,
},
},
}, {
from hy.right,
},
}, {
cases h with y hy,
cases hy with hy hgyx,
cases hy with z hz,
existsi z,
split, {
from hz.left,
}, {
change g (f z) = x,
rw hz.right,
assumption,
},
},
end
theorem image_subset
{α β: Type} (f: α → β) (U V: myset α):
U ⊆ V → image f U ⊆ image f V :=
begin
assume hUV,
intro x,
assume hximf,
cases hximf with y hy,
existsi y,
split, {
apply hUV,
from hy.left,
}, {
from hy.right,
},
end
theorem inverse_image_subset
{α β: Type} (f: α → β) (U V: myset β):
U ⊆ V → inverse_image f U ⊆ inverse_image f V :=
begin
assume hUV,
intro x,
assume hximf,
apply hUV,
from hximf,
end
theorem inverse_image_of_image_of_univ
{α β : Type} (f: α → β):
myset.univ = inverse_image f (image f myset.univ) :=
begin
symmetry,
apply univ_subset_impl_univ,
apply inverse_image_of_image,
end
def compl (s : myset α) : myset α :=
{a | a ∉ s}
theorem inverse_image_compl
{α β: Type} (S: myset β) (f: α → β):
inverse_image f S.compl = (inverse_image f S).compl :=
begin
refl,
end
theorem compl_compl
{α: Type} (S: myset α) [∀ x: α, decidable (x ∈ S)]:
S.compl.compl = S :=
begin
apply setext,
intro x,
from decidable.not_not_iff _,
end
theorem compl_cancel {α: Type} (S: myset α) (T: myset α) [∀ x: α, decidable (x ∈ S)]
[∀ x: α, decidable (x ∈ T)]:
S.compl = T.compl → S = T :=
begin
assume h,
rw [←compl_compl S, ←compl_compl T, h],
end
theorem compl_intersection {α : Type} (S T : myset α) :
(S ∩ T).compl = S.compl ∪ T.compl :=
begin
apply setext,
intro x,
from not_and_distrib,
end
-- Stronk decidability
theorem compl_sIntersection {α : Type} (σ : myset (myset α)) [∀ (x : α) (S: myset α), decidable (x ∈ S)] :
(⋂₀ σ).compl = ⋃₀ (image compl σ) :=
begin
apply setext,
intro x,
split; assume h, {
change ¬(∀ S ∈ σ, x ∈ S) at h,
rw not_forall at h,
cases h with S hS,
rw not_imp at hS,
existsi S.compl,
suffices : S.compl ∈ image compl σ,
existsi this,
from hS.right,
existsi S,
split,
from hS.left,
refl,
}, {
change ¬(∀ S ∈ σ, x ∈ S),
rw not_forall,
change ∃ S ∈ (image compl σ), x ∈ S at h,
cases h with S hS,
cases hS with hS hxS,
existsi S.compl,
assume h,
apply h,
cases hS with T hT,
rw [hT.right.symm, compl_compl],
from hT.left,
from hxS,
},
end
section
open classical
local attribute [instance] classical.prop_decidable
theorem compl_sUnion {α : Type} (σ : myset (myset α)) :
(⋃₀ σ).compl = ⋂₀ (image compl σ) :=
begin
apply compl_cancel,
rw [compl_compl, compl_sIntersection],
congr,
apply setext,
intro S,
split; assume hS,
existsi S.compl,
split,
existsi S,
split,
assumption,
refl,
rw compl_compl,
cases hS with T hT,
rw hT.right.symm,
cases hT.left with U hU,
rw [hU.right.symm, compl_compl],
from hU.left,
end
theorem compl_subset_compl {α : Type} (S T : myset α) :
S.compl ⊆ T.compl ↔ T ⊆ S :=
begin
split; assume h,
intros x hx,
by_contradiction,
from h _ a hx,
intros x hx,
assume hxT,
from hx (h _ hxT),
end
end
theorem disjoint_iff_subset_compl {α : Type} (S T : myset α) :
S ∩ T = ∅ ↔ S ⊆ T.compl :=
begin
split; assume h,
intros x hxS,
assume hx,
apply in_empty_false x, --??
rw ←h,
change x ∈ S ∧ x ∈ T,
split,
from hxS,
from hx,
apply setext,
intro x,
split; assume hx,
exfalso,
apply h _ hx.left,
from hx.right,
exfalso,
assumption,
end
theorem intersection_comm {α : Type} (S T : myset α) :
S ∩ T = T ∩ S :=
begin
apply setext,
intro x,
split; from λ h, ⟨h.right, h.left⟩,
end
theorem subset_compl_symm {α : Type} (S T : myset α) :
S ⊆ T.compl → T ⊆ S.compl :=
begin
assume h,
rwa [←disjoint_iff_subset_compl, intersection_comm, disjoint_iff_subset_compl],
end
-- Used to restrict some set to a subtype ("intersect" a set with a subtype)
def subtype_restriction (Y : myset α) (U : myset α) : myset (subtype Y) :=
{ w | ↑w ∈ U }
-- pffffff
def subtype_unrestriction (Y: myset α) (U: myset (subtype Y)): myset α :=
{x | ∃ hxS: x ∈ Y, (⟨x, hxS⟩: subtype Y) ∈ U}
def function_restrict_to_image
{α β: Type} (f: α → β): α → subtype (myset.imageu f)
:= λ x, ⟨f x, ⟨x, rfl⟩⟩
def function_restrict_to_set_image
{α β: Type} (f: α → β) (U: myset α): (subtype U) → subtype (myset.image f U)
:= λ x, ⟨f x, ⟨x.val, ⟨x.property, rfl⟩⟩⟩
theorem restrict_to_set_image_composition
{α β: Type} (f: α → β) (U: myset α):
function_restrict_to_set_image f U =
(λ y: subtype (imageu (λ x: subtype U, f x.val)), ⟨y.val,
begin
cases y.property with u hu,
rw ←hu,
existsi u.val,
split, {
from u.property,
}, {
refl,
},
end⟩) ∘
function_restrict_to_image (λ x: subtype U, f x.val) :=
rfl
theorem to_image_surjective
{α β: Type} (f: α → β):
(image (function_restrict_to_image f) univ) = univ :=
begin
apply setext,
intro x,
split; assume h, {
trivial,
}, {
cases x.property with y hy,
unfold image,
existsi y,
split, {
trivial,
}, {
apply subtype.eq,
rw ←hy,
refl,
},
},
end
theorem nonempty_inverse_image_surjective
{α β: Type} (f: α → β) (U: myset (subtype (imageu f))):
U ≠ ∅ →
inverse_image (function_restrict_to_image f) U ≠ ∅ :=
begin
assume hUne,
assume hpreUe,
rw ←empty_iff_eq_empty at hpreUe,
change ¬(U = ∅) at hUne,
rw ←empty_iff_eq_empty at hUne,
rw ←exists_iff_nempty at hUne,
cases hUne with x hx,
cases x.property with y hy,
apply hpreUe y,
unfold inverse_image,
have: x = ⟨f y, begin rw hy, from x.property end⟩, {
apply subtype.eq,
from hy.symm,
},
rw this at hx, clear this,
from hx,
end
end myset
end hidden
|
6b09f1ca6f3d730225c7082be941fa0a7b56d100 | 5412d79aa1dc0b521605c38bef9f0d4557b5a29d | /src/Lean/Meta/Basic.lean | 34a4ae7ee03422d4ceba630c3e64f9120f779065 | [
"Apache-2.0"
] | permissive | smunix/lean4 | a450ec0927dc1c74816a1bf2818bf8600c9fc9bf | 3407202436c141e3243eafbecb4b8720599b970a | refs/heads/master | 1,676,334,875,188 | 1,610,128,510,000 | 1,610,128,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 43,581 | 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.Data.LOption
import Lean.Environment
import Lean.Class
import Lean.ReducibilityAttrs
import Lean.Util.Trace
import Lean.Util.RecDepth
import Lean.Util.PPExt
import Lean.Compiler.InlineAttrs
import Lean.Meta.TransparencyMode
import Lean.Meta.DiscrTreeTypes
import Lean.Eval
import Lean.CoreM
/-
This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks.
1- Weak head normal form computation with support for metavariables and transparency modes.
2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality).
3- Type inference.
4- Type class resolution.
They are packed into the MetaM monad.
-/
namespace Lean.Meta
builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck
structure Config where
foApprox : Bool := false
ctxApprox : Bool := false
quasiPatternApprox : Bool := false
/- When `constApprox` is set to true,
we solve `?m t =?= c` using
`?m := fun _ => c`
when `?m t` is not a higher-order pattern and `c` is not an application as -/
constApprox : Bool := false
/-
When the following flag is set,
`isDefEq` throws the exeption `Exeption.isDefEqStuck`
whenever it encounters a constraint `?m ... =?= t` where
`?m` is read only.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`. -/
isDefEqStuckEx : Bool := false
transparency : TransparencyMode := TransparencyMode.default
/- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/
zetaNonDep : Bool := true
/- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/
trackZeta : Bool := false
unificationHints : Bool := true
structure ParamInfo where
implicit : Bool := false
instImplicit : Bool := false
hasFwdDeps : Bool := false
backDeps : Array Nat := #[]
deriving Inhabited
def ParamInfo.isExplicit (p : ParamInfo) : Bool :=
!p.implicit && p.instImplicit
structure FunInfo where
paramInfo : Array ParamInfo := #[]
resultDeps : Array Nat := #[]
structure InfoCacheKey where
transparency : TransparencyMode
expr : Expr
nargs? : Option Nat
deriving Inhabited, BEq
namespace InfoCacheKey
instance : Hashable InfoCacheKey :=
⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) $ mixHash (hash expr) (hash nargs)⟩
end InfoCacheKey
open Std (PersistentArray PersistentHashMap)
abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr)
structure Cache where
inferType : PersistentExprStructMap Expr := {}
funInfo : PersistentHashMap InfoCacheKey FunInfo := {}
synthInstance : SynthInstanceCache := {}
whnfDefault : PersistentExprStructMap Expr := {} -- cache for closed terms and `TransparencyMode.default`
whnfAll : PersistentExprStructMap Expr := {} -- cache for closed terms and `TransparencyMode.all`
deriving Inhabited
structure PostponedEntry where
lhs : Level
rhs : Level
structure State where
mctx : MetavarContext := {}
cache : Cache := {}
/- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/
zetaFVarIds : NameSet := {}
postponed : PersistentArray PostponedEntry := {}
deriving Inhabited
structure Context where
config : Config := {}
lctx : LocalContext := {}
localInstances : LocalInstances := #[]
abbrev MetaM := ReaderT Context $ StateRefT State CoreM
instance : Inhabited (MetaM α) where
default := fun _ _ => arbitrary
instance : MonadLCtx MetaM where
getLCtx := return (← read).lctx
instance : MonadMCtx MetaM where
getMCtx := return (← get).mctx
modifyMCtx f := modify fun s => { s with mctx := f s.mctx }
instance : AddMessageContext MetaM where
addMessageContext := addMessageContextFull
@[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) :=
x ctx |>.run s
@[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α :=
Prod.fst <$> x.run ctx s
@[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do
let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore
pure (a, sCore, s)
instance [MetaEval α] : MetaEval (MetaM α) :=
⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩
protected def throwIsDefEqStuck {α} : MetaM α :=
throw $ Exception.internal isDefEqStuckExceptionId
builtin_initialize
registerTraceClass `Meta
registerTraceClass `Meta.debug
@[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α :=
liftM x
@[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α :=
controlAt MetaM fun runInBase => f $ runInBase x
@[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α :=
controlAt MetaM fun runInBase => f fun b => runInBase $ k b
@[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α :=
controlAt MetaM fun runInBase => f fun b c => runInBase $ k b c
section Methods
variables {n : Type → Type} [MonadControlT MetaM n] [Monad n]
def getLocalInstances : MetaM LocalInstances :=
return (← read).localInstances
def getConfig : MetaM Config :=
return (← read).config
def setMCtx (mctx : MetavarContext) : MetaM Unit :=
modify fun s => { s with mctx := mctx }
def resetZetaFVarIds : MetaM Unit :=
modify fun s => { s with zetaFVarIds := {} }
def getZetaFVarIds : MetaM NameSet :=
return (← get).zetaFVarIds
def getPostponed : MetaM (PersistentArray PostponedEntry) :=
return (← get).postponed
def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := postponed }
@[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit :=
modify fun s => { s with postponed := f s.postponed }
builtin_initialize whnfRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "whnf implementation was not set"
builtin_initialize inferTypeRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "inferType implementation was not set"
builtin_initialize isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) ← IO.mkRef fun _ _ => throwError "isDefEq implementation was not set"
builtin_initialize synthPendingRef : IO.Ref (MVarId → MetaM Bool) ← IO.mkRef fun _ => pure false
def whnf (e : Expr) : MetaM Expr :=
withIncRecDepth do (← whnfRef.get) e
def whnfForall (e : Expr) : MetaM Expr := do
let e' ← whnf e
if e'.isForall then pure e' else pure e
def inferType (e : Expr) : MetaM Expr :=
withIncRecDepth do (← inferTypeRef.get) e
protected def isExprDefEqAux (t s : Expr) : MetaM Bool :=
withIncRecDepth do (← isExprDefEqAuxRef.get) t s
protected def synthPending (mvarId : MVarId) : MetaM Bool :=
withIncRecDepth do (← synthPendingRef.get) mvarId
-- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]`
protected def withIncRecDepth {α} (x : n α) : n α :=
mapMetaM (withIncRecDepth (m := MetaM)) x
private def mkFreshExprMVarAtCore
(mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do
modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs;
pure $ mkMVar mvarId
def mkFreshExprMVarAt
(lctx : LocalContext) (localInsts : LocalInstances) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
let mvarId ← mkFreshId
mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs
def mkFreshLevelMVar : MetaM Level := do
let mvarId ← mkFreshId
modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId;
return mkLevelMVar mvarId
private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do
let lctx ← getLCtx
let localInsts ← getLocalInstances
mkFreshExprMVarAt lctx localInsts type kind userName
private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarCore type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous
mkFreshExprMVarCore type kind userName
def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
mkFreshExprMVarImpl type? kind userName
def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do
let u ← mkFreshLevelMVar
mkFreshExprMVar (mkSort u) kind userName
/- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create
the metavar using this method. -/
private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr)
(kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0)
: MetaM Expr := do
let lctx ← getLCtx
let localInsts ← getLocalInstances
mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs
def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr :=
match type? with
| some type => mkFreshExprMVarWithIdCore mvarId type kind userName
| none => do
let u ← mkFreshLevelMVar
let type ← mkFreshExprMVar (mkSort u)
mkFreshExprMVarWithIdCore mvarId type kind userName
def shouldReduceAll : MetaM Bool :=
return (← read).config.transparency == TransparencyMode.all
def shouldReduceReducibleOnly : MetaM Bool :=
return (← read).config.transparency == TransparencyMode.reducible
def getTransparency : MetaM TransparencyMode :=
return (← read).config.transparency
def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do
let mctx ← getMCtx
match mctx.findDecl? mvarId with
| some d => pure d
| none => throwError! "unknown metavariable '{mkMVar mvarId}'"
def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit :=
modifyMCtx fun mctx => mctx.setMVarKind mvarId kind
/- Update the type of the given metavariable. This function assumes the new type is
definitionally equal to the current one -/
def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do
modifyMCtx fun mctx => mctx.setMVarType mvarId type
def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvarId
let mctx ← getMCtx
return mvarDecl.depth != mctx.depth
def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do
let mvarDecl ← getMVarDecl mvarId
match mvarDecl.kind with
| MetavarKind.syntheticOpaque => pure true
| _ =>
let mctx ← getMCtx
return mvarDecl.depth != mctx.depth
def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do
let mctx ← getMCtx
match mctx.findLevelDepth? mvarId with
| some depth => return depth != mctx.depth
| _ => throwError! "unknown universe metavariable '{mkLevelMVar mvarId}'"
def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit :=
modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName
def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isExprAssigned mvarId
def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) :=
return (← getMCtx).getExprAssignment? mvarId
def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit :=
modifyMCtx fun mctx => mctx.assignExpr mvarId val
def isDelayedAssigned (mvarId : MVarId) : MetaM Bool :=
return (← getMCtx).isDelayedAssigned mvarId
def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) :=
return (← getMCtx).getDelayedAssignment? mvarId
def hasAssignableMVar (e : Expr) : MetaM Bool :=
return (← getMCtx).hasAssignableMVar e
def throwUnknownFVar {α} (fvarId : FVarId) : MetaM α :=
throwError! "unknown free variable '{mkFVar fvarId}'"
def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) :=
return (← getLCtx).find? fvarId
def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do
match (← getLCtx).find? fvarId with
| some d => pure d
| none => throwUnknownFVar fvarId
def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl :=
getLocalDecl fvar.fvarId!
def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do
match (← getLCtx).findFromUserName? userName with
| some d => pure d
| none => throwError! "unknown local declaration '{userName}'"
def instantiateLevelMVars (u : Level) : MetaM Level :=
MetavarContext.instantiateLevelMVars u
def instantiateMVars (e : Expr) : MetaM Expr :=
(MetavarContext.instantiateExprMVars e).run
def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl := do
match localDecl with
| LocalDecl.cdecl idx id n type bi =>
let type ← instantiateMVars type
return LocalDecl.cdecl idx id n type bi
| LocalDecl.ldecl idx id n type val nonDep =>
let type ← instantiateMVars type
let val ← instantiateMVars val
return LocalDecl.ldecl idx id n type val nonDep
@[inline] def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α := do
match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with
| EStateM.Result.ok e newS => do
setNGen newS.ngen;
setMCtx newS.mctx;
pure e
| EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do
setMCtx newS.mctx;
setNGen newS.ngen;
throwError "failed to create binder due to failure when reverting variable dependencies"
def mkForallFVars (xs : Array Expr) (e : Expr) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e
def mkLambdaFVars (xs : Array Expr) (e : Expr) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e
def mkLetFVars (xs : Array Expr) (e : Expr) : MetaM Expr :=
mkLambdaFVars xs e
def mkArrow (d b : Expr) : MetaM Expr := do
let n ← mkFreshUserName `x
return Lean.mkForall n BinderInfo.default d b
def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MetaM (Expr × Nat) := do
if xs.isEmpty then pure (e, 0) else liftMkBindingM <| MetavarContext.mkForallUsedOnly xs e
def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr :=
if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder
@[inline] def withConfig {α} (f : Config → Config) : n α → n α :=
mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config })
@[inline] def withTrackingZeta {α} (x : n α) : n α :=
withConfig (fun cfg => { cfg with trackZeta := true }) x
@[inline] def withTransparency {α} (mode : TransparencyMode) : n α → n α :=
mapMetaM <| withConfig (fun config => { config with transparency := mode })
@[inline] def withDefault {α} (x : n α) : n α :=
withTransparency TransparencyMode.default x
@[inline] def withReducible {α} (x : n α) : n α :=
withTransparency TransparencyMode.reducible x
@[inline] def withReducibleAndInstances {α} (x : n α) : n α :=
withTransparency TransparencyMode.instances x
@[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : n α) : n α :=
withConfig
(fun config =>
let oldMode := config.transparency
let mode := if oldMode.lt mode then mode else oldMode
{ config with transparency := mode })
x
/-- Save cache, execute `x`, restore cache -/
@[inline] private def savingCacheImpl {α} (x : MetaM α) : MetaM α := do
let s ← get
let savedCache := s.cache
try x finally modify fun s => { s with cache := savedCache }
@[inline] def savingCache {α} : n α → n α :=
mapMetaM savingCacheImpl
def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
if (← shouldReduceAll) then
return some info
else
return none
private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do
match (← read).config.transparency with
| TransparencyMode.all => return some info
| TransparencyMode.default => return some info
| _ =>
if (← isReducible info.name) then
return some info
else
return none
/- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`.
This method is only used to implement `isClassQuickConst?`.
It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and
`constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/
private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do
let env ← getEnv
match env.find? constName with
| some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info
| some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info
| some info => pure (some info)
| none => throwUnknownConstant constName
private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do
let env ← getEnv
if isClass env constName then
pure (LOption.some constName)
else
match (← getConstTemp? constName) with
| some _ => pure LOption.undef
| none => pure LOption.none
private partial def isClassQuick? : Expr → MetaM (LOption Name)
| Expr.bvar .. => pure LOption.none
| Expr.lit .. => pure LOption.none
| Expr.fvar .. => pure LOption.none
| Expr.sort .. => pure LOption.none
| Expr.lam .. => pure LOption.none
| Expr.letE .. => pure LOption.undef
| Expr.proj .. => pure LOption.undef
| Expr.forallE _ _ b _ => isClassQuick? b
| Expr.mdata _ e _ => isClassQuick? e
| Expr.const n _ _ => isClassQuickConst? n
| Expr.mvar mvarId _ => do
match (← getExprMVarAssignment? mvarId) with
| some val => isClassQuick? val
| none => pure LOption.none
| Expr.app f _ _ =>
match f.getAppFn with
| Expr.const n .. => isClassQuickConst? n
| Expr.lam .. => pure LOption.undef
| _ => pure LOption.none
def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do
let s ← get
let savedSythInstance := s.cache.synthInstance
modify fun s => { s with cache := { s.cache with synthInstance := {} } }
pure savedSythInstance
def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit :=
modify fun s => { s with cache := { s.cache with synthInstance := cache } }
@[inline] private def resettingSynthInstanceCacheImpl {α} (x : MetaM α) : MetaM α := do
let savedSythInstance ← saveAndResetSynthInstanceCache
try x finally restoreSynthInstanceCache savedSythInstance
/-- Reset `synthInstance` cache, execute `x`, and restore cache -/
@[inline] def resettingSynthInstanceCache {α} : n α → n α :=
mapMetaM resettingSynthInstanceCacheImpl
@[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : n α) : n α :=
if b then resettingSynthInstanceCache x else x
private def withNewLocalInstanceImp {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do
let localDecl ← getFVarLocalDecl fvar
/- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/
match localDecl.binderInfo with
| BinderInfo.auxDecl => k
| _ =>
resettingSynthInstanceCache $
withReader
(fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } })
k
/-- Add entry `{ className := className, fvar := fvar }` to localInstances,
and then execute continuation `k`.
It resets the type class cache using `resettingSynthInstanceCache`. -/
def withNewLocalInstance {α} (className : Name) (fvar : Expr) : n α → n α :=
mapMetaM $ withNewLocalInstanceImp className fvar
private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool :=
match maxFVars? with
| some maxFVars => fvars.size < maxFVars
| none => true
mutual
/--
`withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances
using free variables `fvars[j] ... fvars.back`, and execute `k`.
- `isClassExpensive` is defined later.
- The type class chache is reset whenever a new local instance is found.
- `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances.
Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/
private partial def withNewLocalInstancesImp {α}
(fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do
if h : i < fvars.size then
let fvar := fvars.get ⟨i, h⟩
let decl ← getFVarLocalDecl fvar
match (← isClassQuick? decl.type) with
| LOption.none => withNewLocalInstancesImp fvars (i+1) k
| LOption.undef =>
match (← isClassExpensive? decl.type) with
| none => withNewLocalInstancesImp fvars (i+1) k
| some c => withNewLocalInstance c fvar $ withNewLocalInstancesImp fvars (i+1) k
| LOption.some c => withNewLocalInstance c fvar $ withNewLocalInstancesImp fvars (i+1) k
else
k
/--
`forallTelescopeAuxAux lctx fvars j type`
Remarks:
- `lctx` is the `MetaM` local context extended with declarations for `fvars`.
- `type` is the type we are computing the telescope for. It contains only
dangling bound variables in the range `[j, fvars.size)`
- if `reducing? == true` and `type` is not `forallE`, we use `whnf`.
- when `type` is not a `forallE` nor it can't be reduced to one, we
excute the continuation `k`.
Here is an example that demonstrates the `reducing?`.
Suppose we have
```
abbrev StateM s a := s -> Prod a s
```
Now, assume we are trying to build the telescope for
```
forall (x : Nat), StateM Int Bool
```
if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`.
if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)`
if `maxFVars?` is `some max`, then we interrupt the telescope construction
when `fvars.size == max`
-/
private partial def forallTelescopeReducingAuxAux {α}
(reducing : Bool) (maxFVars? : Option Nat)
(type : Expr)
(k : Array Expr → Expr → MetaM α) : MetaM α := do
let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do
match type with
| Expr.forallE n d b c =>
if fvarsSizeLtMaxFVars fvars maxFVars? then
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
let fvars := fvars.push fvar
process lctx fvars j b
else
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars type
| _ =>
let type := type.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then
let newType ← whnf type
if newType.isForall then
process lctx fvars fvars.size newType
else
k fvars type
else
k fvars type
process (← getLCtx) #[] 0 type
private partial def forallTelescopeReducingAux {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do
match maxFVars? with
| some 0 => k #[] type
| _ => do
let newType ← whnf type
if newType.isForall then
forallTelescopeReducingAuxAux true maxFVars? newType k
else
k #[] type
private partial def isClassExpensive? : Expr → MetaM (Option Name)
| type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants.
forallTelescopeReducingAux type none fun xs type => do
match type.getAppFn with
| Expr.const c _ _ => do
let env ← getEnv
return if isClass env c then some c else none
| _ => pure none
private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do
match (← isClassQuick? type) with
| LOption.none => pure none
| LOption.some c => pure (some c)
| LOption.undef => isClassExpensive? type
end
def isClass? (type : Expr) : MetaM (Option Name) :=
try isClassImp? type catch _ => pure none
private def withNewLocalInstancesImpAux {α} (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM $ withNewLocalInstancesImp fvars j
partial def withNewLocalInstances {α} (fvars : Array Expr) (j : Nat) : n α → n α :=
mapMetaM $ withNewLocalInstancesImpAux fvars j
@[inline] private def forallTelescopeImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do
forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k
/--
Given `type` of the form `forall xs, A`, execute `k xs A`.
This combinator will declare local declarations, create free variables for them,
execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/
def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeImp type k) k
private def forallTelescopeReducingImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type (maxFVars? := none) k
/--
Similar to `forallTelescope`, but given `type` of the form `forall xs, A`,
it reduces `A` and continues bulding the telescope if it is a `forall`. -/
def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallTelescopeReducingImp type k) k
private def forallBoundedTelescopeImp {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α :=
forallTelescopeReducingAux type maxFVars? k
/--
Similar to `forallTelescopeReducing`, stops constructing the telescope when
it reaches size `maxFVars`. -/
def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k
/-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/
private partial def lambdaTelescopeAux {α}
(k : Array Expr → Expr → MetaM α)
: Bool → LocalContext → Array Expr → Nat → Expr → MetaM α
| consumeLet, lctx, fvars, j, Expr.lam n d b c => do
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
lambdaTelescopeAux k consumeLet lctx (fvars.push fvar) j b
| true, lctx, fvars, j, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars
let v := v.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLetDecl fvarId n t v
let fvar := mkFVar fvarId
lambdaTelescopeAux k true lctx (fvars.push fvar) j b
| _, lctx, fvars, j, e =>
let e := e.instantiateRevRange j fvars.size fvars;
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars e
private partial def lambdaTelescopeImp {α} (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do
let rec process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do
match consumeLet, e with
| _, Expr.lam n d b c =>
let d := d.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo
let fvar := mkFVar fvarId
process consumeLet lctx (fvars.push fvar) j b
| true, Expr.letE n t v b _ => do
let t := t.instantiateRevRange j fvars.size fvars
let v := v.instantiateRevRange j fvars.size fvars
let fvarId ← mkFreshId
let lctx := lctx.mkLetDecl fvarId n t v
let fvar := mkFVar fvarId
process true lctx (fvars.push fvar) j b
| _, e =>
let e := e.instantiateRevRange j fvars.size fvars
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewLocalInstancesImp fvars j do
k fvars e
process consumeLet (← getLCtx) #[] 0 e
/-- Similar to `forallTelescope` but for lambda and let expressions. -/
def lambdaLetTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type true k) k
/-- Similar to `forallTelescope` but for lambda expressions. -/
def lambdaTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α :=
map2MetaM (fun k => lambdaTelescopeImp type false k) k
/-- Return the parameter names for the givel global declaration. -/
def getParamNames (declName : Name) : MetaM (Array Name) := do
let cinfo ← getConstInfo declName
forallTelescopeReducing cinfo.type fun xs _ => do
xs.mapM fun x => do
let localDecl ← getLocalDecl x.fvarId!
pure localDecl.userName
-- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments.
private partial def forallMetaTelescopeReducingAux
(e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) :=
let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
match type with
| Expr.forallE n d b c =>
let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
let d := d.instantiateRevRange j mvars.size mvars
let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind
let mvar ← mkFreshExprMVar d k n
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
match maxMVars? with
| none => cont ()
| some maxMVars =>
if mvars.size < maxMVars then
cont ()
else
let type := type.instantiateRevRange j mvars.size mvars;
pure (mvars, bis, type)
| _ =>
let type := type.instantiateRevRange j mvars.size mvars;
if reducing then do
let newType ← whnf type;
if newType.isForall then
process mvars bis mvars.size newType
else
pure (mvars, bis, type)
else
pure (mvars, bis, type)
process #[] #[] 0 e
/-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/
def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind
/-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/
def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) :=
forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind
/-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/
partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) :=
let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do
let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
let type := type.instantiateRevRange j mvars.size mvars
pure (mvars, bis, type)
let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do
match type with
| Expr.lam n d b c =>
let d := d.instantiateRevRange j mvars.size mvars
let mvar ← mkFreshExprMVar d
let mvars := mvars.push mvar
let bis := bis.push c.binderInfo
process mvars bis j b
| _ => finalize ()
match maxMVars? with
| none => cont ()
| some maxMVars =>
if mvars.size < maxMVars then
cont ()
else
finalize ()
process #[] #[] 0 e
private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do
match (← isClass? fvarType) with
| none => k fvar
| some c => withNewLocalInstance c fvar $ k fvar
private def withLocalDeclImp {α} (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshId
let ctx ← read
let lctx := ctx.lctx.mkLocalDecl fvarId n type bi
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLocalDecl {α} (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLocalDeclImp name bi type k) k
def withLocalDeclD {α} (name : Name) (type : Expr) (k : Expr → n α) : n α :=
withLocalDecl name BinderInfo.default type k
private def withLetDeclImp {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do
let fvarId ← mkFreshId
let ctx ← read
let lctx := ctx.lctx.mkLetDecl fvarId n type val
let fvar := mkFVar fvarId
withReader (fun ctx => { ctx with lctx := lctx }) do
withNewFVar fvar type k
def withLetDecl {α} (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α :=
map1MetaM (fun k => withLetDeclImp name type val k) k
private def withExistingLocalDeclsImp {α} (decls : List LocalDecl) (k : MetaM α) : MetaM α := do
let ctx ← read
let numLocalInstances := ctx.localInstances.size
let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx
withReader (fun ctx => { ctx with lctx := lctx }) do
let newLocalInsts ← decls.foldlM
(fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do {
match (← isClass? decl.type) with
| none => pure newlocalInsts
| some c => pure $ newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _))
ctx.localInstances;
if newLocalInsts.size == numLocalInstances then
k
else
resettingSynthInstanceCache $ withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k
def withExistingLocalDecls {α} (decls : List LocalDecl) : n α → n α :=
mapMetaM $ withExistingLocalDeclsImp decls
private def withNewMCtxDepthImp {α} (x : MetaM α) : MetaM α := do
let s ← get
let savedMCtx := s.mctx
modifyMCtx fun mctx => mctx.incDepth
try x finally setMCtx savedMCtx
/--
Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`,
and restore saved data. -/
def withNewMCtxDepth {α} : n α → n α :=
mapMetaM withNewMCtxDepthImp
private def withLocalContextImp {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do
let localInstsCurr ← getLocalInstances
withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do
if localInsts == localInstsCurr then
x
else
resettingSynthInstanceCache x
def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α :=
mapMetaM $ withLocalContextImp lctx localInsts
private def withMVarContextImp {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do
let mvarDecl ← getMVarDecl mvarId
withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x
/--
Execute `x` using the given metavariable `LocalContext` and `LocalInstances`.
The type class resolution cache is flushed when executing `x` if its `LocalInstances` are
different from the current ones. -/
def withMVarContext {α} (mvarId : MVarId) : n α → n α :=
mapMetaM $ withMVarContextImp mvarId
private def withMCtxImp {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do
let mctx' ← getMCtx
setMCtx mctx
try x finally setMCtx mctx'
def withMCtx {α} (mctx : MetavarContext) : n α → n α :=
mapMetaM $ withMCtxImp mctx
@[inline] private def approxDefEqImp {α} (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x
/-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/
@[inline] def approxDefEq {α} : n α → n α :=
mapMetaM approxDefEqImp
@[inline] private def fullApproxDefEqImp {α} (x : MetaM α) : MetaM α :=
withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x
/--
Similar to `approxDefEq`, but uses all available approximations.
We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code.
For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`.
Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved
as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to
solve `[Pure (fun _ => IO Bool)]` -/
@[inline] def fullApproxDefEq {α} : n α → n α :=
mapMetaM fullApproxDefEqImp
def normalizeLevel (u : Level) : MetaM Level := do
let u ← instantiateLevelMVars u
pure u.normalize
def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do
modifyMCtx fun mctx => mctx.assignLevel mvarId u
def whnfD [MonadLiftT MetaM n] (e : Expr) : n Expr :=
withTransparency TransparencyMode.default <| whnf e
def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do
let env ← getEnv
match Compiler.setInlineAttribute env declName kind with
| Except.ok env => setEnv env
| Except.error msg => throwError msg
private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
let e ← whnf e
match e with
| Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateForall, too many parameters"
else
pure e
/- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/
def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateForallAux ps 0 e
private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
let e ← whnf e
match e with
| Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p)
| _ => throwError "invalid instantiateLambda, too many parameters"
else
pure e
/- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`.
It uses `whnf` to reduce `e` if it is not a lambda -/
def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr :=
instantiateLambdaAux ps 0 e
/-- Return true iff `e` depends on the free variable `fvarId` -/
def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool :=
return (← getMCtx).exprDependsOn e fvarId
def ppExpr (e : Expr) : MetaM Format := do
let env ← getEnv
let mctx ← getMCtx
let lctx ← getLCtx
let opts ← getOptions
let ctxCore ← readThe Core.Context
Lean.ppExpr { env := env, mctx := mctx, lctx := lctx, opts := opts, currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e
@[inline] protected def orelse {α} (x y : MetaM α) : MetaM α := do
let env ← getEnv
let mctx ← getMCtx
try x catch _ => setEnv env; setMCtx mctx; y
instance {α} : OrElse (MetaM α) := ⟨Meta.orelse⟩
@[inline] private def orelseMergeErrorsImp {α} (x y : MetaM α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do
let env ← getEnv
let mctx ← getMCtx
try
x
catch ex =>
setEnv env
setMCtx mctx
match ex with
| Exception.error ref₁ m₁ =>
try
y
catch
| Exception.error ref₂ m₂ => throw $ Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂)
| ex => throw ex
| ex => throw ex
/--
Similar to `orelse`, but merge errors. Note that internal errors are not caught.
The default `mergeRef` uses the `ref` (position information) for the first message.
The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/
@[inline] def orelseMergeErrors {α m} [MonadControlT MetaM m] [Monad m] (x y : m α)
(mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁)
(mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do
controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg
/-- Execute `x`, and apply `f` to the produced error message -/
def mapErrorImp {α} (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do
try
x
catch
| Exception.error ref msg => throw $ Exception.error ref $ f msg
| ex => throw ex
@[inline] def mapError {α m} [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α :=
controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f
/-- `commitWhenSome? x` executes `x` and keep modifications when it returns `some a`. -/
@[specialize] def commitWhenSome? {α} (x? : MetaM (Option α)) : MetaM (Option α) := do
let env ← getEnv
let mctx ← getMCtx
try
match (← x?) with
| some a => pure (some a)
| none =>
setEnv env
setMCtx mctx
pure none
catch ex =>
setEnv env
setMCtx mctx
throw ex
end Methods
end Meta
export Meta (MetaM)
end Lean
|
50e4cfaf45b3a45deb883ccd059cd231d0e9c7d4 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /hott/algebra/homotopy_group.hlean | 9c0a38d33d7b5237b5861d2cc67bc4f9311fe894 | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,236 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
homotopy groups of a pointed space
-/
import types.pointed .trunc_group .hott types.trunc
open nat eq pointed trunc is_trunc algebra
namespace eq
definition homotopy_group [reducible] (n : ℕ) (A : Type*) : Type :=
trunc 0 (Ω[n] A)
notation `π[`:95 n:0 `] `:0 A:95 := homotopy_group n A
definition pointed_homotopy_group [instance] [constructor] (n : ℕ) (A : Type*)
: pointed (π[n] A) :=
pointed.mk (tr rfln)
definition group_homotopy_group [instance] [constructor] (n : ℕ) (A : Type*)
: group (π[succ n] A) :=
trunc_group concat inverse idp con.assoc idp_con con_idp con.left_inv
definition comm_group_homotopy_group [constructor] (n : ℕ) (A : Type*)
: comm_group (π[succ (succ n)] A) :=
trunc_comm_group concat inverse idp con.assoc idp_con con_idp con.left_inv eckmann_hilton
local attribute comm_group_homotopy_group [instance]
definition Pointed_homotopy_group [constructor] (n : ℕ) (A : Type*) : Type* :=
Pointed.mk (π[n] A)
definition Group_homotopy_group [constructor] (n : ℕ) (A : Type*) : Group :=
Group.mk (π[succ n] A) _
definition CommGroup_homotopy_group [constructor] (n : ℕ) (A : Type*) : CommGroup :=
CommGroup.mk (π[succ (succ n)] A) _
definition fundamental_group [constructor] (A : Type*) : Group :=
Group_homotopy_group zero A
notation `πP[`:95 n:0 `] `:0 A:95 := Pointed_homotopy_group n A
notation `πG[`:95 n:0 ` +1] `:0 A:95 := Group_homotopy_group n A
notation `πaG[`:95 n:0 ` +2] `:0 A:95 := CommGroup_homotopy_group n A
prefix `π₁`:95 := fundamental_group
open equiv unit
theorem trivial_homotopy_of_is_hset (A : Type*) [H : is_hset A] (n : ℕ) : πG[n+1] A = G0 :=
begin
apply trivial_group_of_is_contr,
apply is_trunc_trunc_of_is_trunc,
apply is_contr_loop_of_is_trunc,
apply is_trunc_succ_succ_of_is_hset
end
definition homotopy_group_succ_out (A : Type*) (n : ℕ) : πG[ n +1] A = π₁ Ω[n] A := idp
definition homotopy_group_succ_in (A : Type*) (n : ℕ) : πG[succ n +1] A = πG[n +1] Ω A :=
begin
fapply Group_eq,
{ apply equiv_of_eq, exact ap (λ(X : Type*), trunc 0 X) (loop_space_succ_eq_in A (succ n))},
{ exact abstract [irreducible] begin refine trunc.rec _, intro p, refine trunc.rec _, intro q,
rewrite [▸*,-+tr_eq_cast_ap, +trunc_transport, ↑[group_homotopy_group, group.to_monoid,
monoid.to_semigroup, semigroup.to_has_mul, trunc_mul], trunc_transport], apply ap tr,
apply loop_space_succ_eq_in_concat end end},
end
definition homotopy_group_add (A : Type*) (n m : ℕ) : πG[n+m +1] A = πG[n +1] Ω[m] A :=
begin
revert A, induction m with m IH: intro A,
{ reflexivity},
{ esimp [Iterated_loop_space, nat.add], refine !homotopy_group_succ_in ⬝ _, refine !IH ⬝ _,
exact ap (Group_homotopy_group n) !loop_space_succ_eq_in⁻¹}
end
theorem trivial_homotopy_of_is_hset_loop_space {A : Type*} {n : ℕ} (m : ℕ) (H : is_hset (Ω[n] A))
: πG[m+n+1] A = G0 :=
!homotopy_group_add ⬝ !trivial_homotopy_of_is_hset
end eq
|
90e83fe6b5b034050b5335aa320be09cef2d6f2a | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /library/init/core.lean | ea3f39539222e3715d8d0594a81eb8767ea293a9 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 15,650 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
notation `Prop` := Sort 0
notation f ` $ `:1 a:0 := f a
/- Logical operations and relations -/
reserve prefix `¬`:40
reserve prefix `~`:40
reserve infixr ` ∧ `:35
reserve infixr ` /\ `:35
reserve infixr ` \/ `:30
reserve infixr ` ∨ `:30
reserve infix ` <-> `:20
reserve infix ` ↔ `:20
reserve infix ` = `:50
reserve infix ` == `:50
reserve infix ` ≠ `:50
reserve infix ` ≈ `:50
reserve infix ` ~ `:50
reserve infix ` ≡ `:50
reserve infixl ` ⬝ `:75
reserve infixr ` ▸ `:75
reserve infixr ` ▹ `:75
/- types and type constructors -/
reserve infixr ` ⊕ `:30
reserve infixr ` × `:35
/- arithmetic operations -/
reserve infixl ` + `:65
reserve infixl ` - `:65
reserve infixl ` * `:70
reserve infixl ` / `:70
reserve infixl ` % `:70
reserve prefix `-`:100
reserve infix ` ^ `:80
reserve infixr ` ∘ `:90 -- input with \comp
reserve infix ` <= `:50
reserve infix ` ≤ `:50
reserve infix ` < `:50
reserve infix ` >= `:50
reserve infix ` ≥ `:50
reserve infix ` > `:50
/- boolean operations -/
reserve infixl ` && `:70
reserve infixl ` || `:65
/- set operations -/
reserve infix ` ∈ `:50
reserve infix ` ∉ `:50
reserve infixl ` ∩ `:70
reserve infixl ` ∪ `:65
reserve infix ` ⊆ `:50
reserve infix ` ⊇ `:50
reserve infix ` ⊂ `:50
reserve infix ` ⊃ `:50
reserve infix ` \ `:70
/- other symbols -/
reserve infix ` ∣ `:50
reserve infixl ` ++ `:65
reserve infixr ` :: `:67
reserve infixl `; `:1
universes u v w
/-- Gadget for optional parameter support. -/
@[reducible] def opt_param (α : Sort u) (default : α) : Sort u :=
α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def inout_param (α : Sort u) : Sort u := α
notation `inout`:1024 a:0 := inout_param a
inductive punit : Sort u
| star : punit
inductive unit : Type
| star : unit
/--
Gadget for defining thunks, thunk parameters have special treatment.
Example: given
def f (s : string) (t : thunk nat) : nat
an application
f "hello" 10
is converted into
f "hello" (λ _, 10)
-/
@[reducible] def thunk (α : Type u) : Type u :=
unit → α
inductive true : Prop
| intro : true
inductive false : Prop
inductive empty : Type
def not (a : Prop) := a → false
prefix `¬` := not
inductive eq {α : Sort u} (a : α) : α → Prop
| refl : eq a
init_quotient
inductive heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop
| refl : heq a
structure prod (α : Type u) (β : Type v) :=
(fst : α) (snd : β)
/- Similar to prod, but α and β can be propositions.
We use this type internally to automatically generate the brec_on recursor. -/
structure pprod (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
inductive and (a b : Prop) : Prop
| intro : a → b → and
def and.elim_left {a b : Prop} (h : and a b) : a :=
and.rec (λ ha hb, ha) h
def and.left := @and.elim_left
def and.elim_right {a b : Prop} (h : and a b) : b :=
and.rec (λ ha hb, hb) h
def and.right := @and.elim_right
/- eq basic support -/
infix = := eq
attribute [refl] eq.refl
@[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a
@[elab_as_eliminator, subst]
lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b :=
eq.rec h₂ h₁
notation h1 ▸ h2 := eq.subst h1 h2
@[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
@[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a :=
h ▸ rfl
infix == := heq
@[pattern] def heq.rfl {α : Sort u} {a : α} : a == a := heq.refl a
lemma eq_of_heq {α : Sort u} {a a' : α} (h : a == a') : a = a' :=
have ∀ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from
λ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl),
show (eq.rec_on (eq.refl α) a : α) = a', from
this α a' h (eq.refl α)
/- The following four lemmas could not be automatically generated when the
structures were declared, so we prove them manually here. -/
lemma prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → and (x₁ = x₂) (y₁ = y₂) :=
λ h, prod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
lemma pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: pprod.mk x₁ y₁ = pprod.mk x₂ y₂ → and (x₁ = x₂) (y₁ = y₂) :=
λ h, pprod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
inductive sum (α : Type u) (β : Type v)
| inl {} : α → sum
| inr {} : β → sum
inductive psum (α : Sort u) (β : Sort v)
| inl {} : α → psum
| inr {} : β → psum
inductive or (a b : Prop) : Prop
| inl {} : a → or
| inr {} : b → or
def or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b :=
or.inl ha
def or.intro_right (a : Prop) {b : Prop} (hb : b) : or a b :=
or.inr hb
structure sigma {α : Type u} (β : α → Type v) :=
mk :: (fst : α) (snd : β fst)
structure psigma {α : Sort u} (β : α → Sort v) :=
mk :: (fst : α) (snd : β fst)
inductive bool : Type
| ff : bool
| tt : bool
/- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/
structure subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
attribute [pp_using_anonymous_constructor] sigma psigma subtype pprod
class inductive decidable (p : Prop)
| is_false : ¬p → decidable
| is_true : p → decidable
@[reducible]
def decidable_pred {α : Sort u} (r : α → Prop) :=
Π (a : α), decidable (r a)
@[reducible]
def decidable_rel {α : Sort u} (r : α → α → Prop) :=
Π (a b : α), decidable (r a b)
@[reducible]
def decidable_eq (α : Sort u) :=
decidable_rel (@eq α)
inductive option (α : Type u)
| none {} : option
| some : α → option
export option (none some)
export bool (ff tt)
inductive list (T : Type u)
| nil {} : list
| cons : T → list → list
notation h :: t := list.cons h t
notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l
inductive nat
| zero : nat
| succ : nat → nat
structure unification_constraint :=
{α : Type u} (lhs : α) (rhs : α)
infix ` ≟ `:50 := unification_constraint.mk
infix ` =?= `:50 := unification_constraint.mk
structure unification_hint :=
(pattern : unification_constraint)
(constraints : list unification_constraint)
/- Declare builtin and reserved notation -/
class has_zero (α : Type u) := (zero : α)
class has_one (α : Type u) := (one : α)
class has_add (α : Type u) := (add : α → α → α)
class has_mul (α : Type u) := (mul : α → α → α)
class has_inv (α : Type u) := (inv : α → α)
class has_neg (α : Type u) := (neg : α → α)
class has_sub (α : Type u) := (sub : α → α → α)
class has_div (α : Type u) := (div : α → α → α)
class has_dvd (α : Type u) := (dvd : α → α → Prop)
class has_mod (α : Type u) := (mod : α → α → α)
class has_le (α : Type u) := (le : α → α → Prop)
class has_lt (α : Type u) := (lt : α → α → Prop)
class has_append (α : Type u) := (append : α → α → α)
class has_andthen (α : Type u) (β : Type v) (σ : inout Type w) := (andthen : α → β → σ)
class has_union (α : Type u) := (union : α → α → α)
class has_inter (α : Type u) := (inter : α → α → α)
class has_sdiff (α : Type u) := (sdiff : α → α → α)
class has_subset (α : Type u) := (subset : α → α → Prop)
class has_ssubset (α : Type u) := (ssubset : α → α → Prop)
/- Type classes has_emptyc and has_insert are
used to implement polymorphic notation for collections.
Example: {a, b, c}. -/
class has_emptyc (α : Type u) := (emptyc : α)
class has_insert (α : inout Type u) (γ : Type v) := (insert : α → γ → γ)
/- Type class used to implement the notation { a ∈ c | p a } -/
class has_sep (α : inout Type u) (γ : Type v) :=
(sep : (α → Prop) → γ → γ)
/- Type class for set-like membership -/
class has_mem (α : inout Type u) (γ : Type v) := (mem : α → γ → Prop)
def andthen {α : Type u} {β : Type v} {σ : Type w} [has_andthen α β σ] : α → β → σ :=
has_andthen.andthen σ
infix ∈ := has_mem.mem
notation a ∉ s := ¬ has_mem.mem a s
infix + := has_add.add
infix * := has_mul.mul
infix - := has_sub.sub
infix / := has_div.div
infix ∣ := has_dvd.dvd
infix % := has_mod.mod
prefix - := has_neg.neg
infix <= := has_le.le
infix ≤ := has_le.le
infix < := has_lt.lt
infix ++ := has_append.append
infix ; := andthen
notation `∅` := has_emptyc.emptyc _
infix ∪ := has_union.union
infix ∩ := has_inter.inter
infix ⊆ := has_subset.subset
infix ⊂ := has_ssubset.ssubset
infix \ := has_sdiff.sdiff
export has_append (append)
@[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := has_le.le b a
@[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := has_lt.lt b a
infix >= := ge
infix ≥ := ge
infix > := gt
@[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := has_subset.subset b a
@[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := has_ssubset.ssubset b a
infix ⊇ := superset
infix ⊃ := ssuperset
def bit0 {α : Type u} [s : has_add α] (a : α) : α := a + a
def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := (bit0 a) + 1
attribute [pattern] has_zero.zero has_one.one bit0 bit1 has_add.add has_neg.neg
def insert {α : Type u} {γ : Type v} [has_insert α γ] : α → γ → γ :=
has_insert.insert
/- The empty collection -/
def singleton {α : Type u} {γ : Type v} [has_emptyc γ] [has_insert α γ] (a : α) : γ :=
has_insert.insert a ∅
/- nat basic instances -/
namespace nat
protected def add : nat → nat → nat
| a zero := a
| a (succ b) := succ (add a b)
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation compiler. -/
attribute [pattern] nat.add nat.add._main
end nat
instance : has_zero nat := ⟨nat.zero⟩
instance : has_one nat := ⟨nat.succ (nat.zero)⟩
instance : has_add nat := ⟨nat.add⟩
def std.priority.default : nat := 1000
def std.priority.max : nat := 0xFFFFFFFF
namespace nat
protected def prio := std.priority.default + 100
end nat
/-
Global declarations of right binding strength
If a module reassigns these, it will be incompatible with other modules that adhere to these
conventions.
When hovering over a symbol, use "C-c C-k" to see how to input it.
-/
def std.prec.max : nat := 1024 -- the strength of application, identifiers, (, [, etc.
def std.prec.arrow : nat := 25
/-
The next def is "max + 10". It can be used e.g. for postfix operations that should
be stronger than application.
-/
def std.prec.max_plus : nat := std.prec.max + 10
reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv
postfix ⁻¹ := has_inv.inv
notation α × β := prod α β
-- notation for n-ary tuples
/- sizeof -/
class has_sizeof (α : Sort u) :=
(sizeof : α → nat)
def sizeof {α : Sort u} [s : has_sizeof α] : α → nat :=
has_sizeof.sizeof
/-
Declare sizeof instances and lemmas for types declared before has_sizeof.
From now on, the inductive compiler will automatically generate sizeof instances and lemmas.
-/
/- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → nat
| a := 0
instance default_has_sizeof (α : Sort u) : has_sizeof α :=
⟨default.sizeof α⟩
protected def nat.sizeof : nat → nat
| n := n
instance : has_sizeof nat :=
⟨nat.sizeof⟩
protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) :=
⟨prod.sizeof⟩
protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat
| (sum.inl a) := 1 + sizeof a
| (sum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) :=
⟨sum.sizeof⟩
protected def psum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (psum α β) → nat
| (psum.inl a) := 1 + sizeof a
| (psum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) :=
⟨psum.sizeof⟩
protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) :=
⟨sigma.sizeof⟩
protected def psigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : psigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (psigma β) :=
⟨psigma.sizeof⟩
protected def unit.sizeof : unit → nat
| u := 1
instance : has_sizeof unit := ⟨unit.sizeof⟩
protected def punit.sizeof : punit → nat
| u := 1
instance : has_sizeof punit := ⟨punit.sizeof⟩
protected def bool.sizeof : bool → nat
| b := 1
instance : has_sizeof bool := ⟨bool.sizeof⟩
protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat
| none := 1
| (some a) := 1 + sizeof a
instance (α : Type u) [has_sizeof α] : has_sizeof (option α) :=
⟨option.sizeof⟩
protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat
| list.nil := 1
| (list.cons a l) := 1 + sizeof a + list.sizeof l
instance (α : Type u) [has_sizeof α] : has_sizeof (list α) :=
⟨list.sizeof⟩
protected def subtype.sizeof {α : Type u} [has_sizeof α] {p : α → Prop} : subtype p → nat
| ⟨a, _⟩ := sizeof a
instance {α : Type u} [has_sizeof α] (p : α → Prop) : has_sizeof (subtype p) :=
⟨subtype.sizeof⟩
lemma nat_add_zero (n : nat) : n + 0 = n := rfl
/- Combinator calculus -/
namespace combinator
universes u₁ u₂ u₃
def I {α : Type u₁} (a : α) := a
def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a
def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z)
end combinator
/- Basic unification hints -/
@[unify] def add_succ_defeq_succ_add_hint (x y z : nat) : unification_hint :=
{ pattern := x + nat.succ y ≟ nat.succ z,
constraints := [z ≟ x + y] }
|
22239cf945dc1ce3f170c62c5aee715b39a9e1d2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Meta/Transform.lean | bcba08287a7f9feb9af5d6c9e87b7f2150272065 | [
"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 | 7,937 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Basic
namespace Lean
inductive TransformStep where
/-- Return expression without visiting any subexpressions. -/
| done (e : Expr)
/--
Visit expression (which should be different from current expression) instead.
The new expression `e` is passed to `pre` again.
-/
| visit (e : Expr)
/--
Continue transformation with the given expression (defaults to current expression).
For `pre`, this means visiting the children of the expression.
For `post`, this is equivalent to returning `done`. -/
| continue (e? : Option Expr := none)
namespace Core
/--
Transform the expression `input` using `pre` and `post`.
- First `pre` is invoked with the current expression and recursion is continued according to the `TransformStep` result.
In all cases, the expression contained in the result, if any, must be definitionally equal to the current expression.
- After recursion, if any, `post` is invoked on the resulting expression.
The term `s` in both `pre s` and `post s` may contain loose bound variables. So, this method is not appropriate for
if one needs to apply operations (e.g., `whnf`, `inferType`) that do not handle loose bound variables.
Consider using `Meta.transform` to avoid loose bound variables.
This method is useful for applying transformations such as beta-reduction and delta-reduction.
-/
partial def transform {m} [Monad m] [MonadLiftT CoreM m] [MonadControlT CoreM m]
(input : Expr)
(pre : Expr → m TransformStep := fun _ => return .continue)
(post : Expr → m TransformStep := fun e => return .done e)
: m Expr :=
let _ : STWorld IO.RealWorld m := ⟨⟩
let _ : MonadLiftT (ST IO.RealWorld) m := { monadLift := fun x => liftM (m := CoreM) (liftM (m := ST IO.RealWorld) x) }
let rec visit (e : Expr) : MonadCacheT ExprStructEq Expr m Expr :=
checkCache { val := e : ExprStructEq } fun _ => Core.withIncRecDepth do
let rec visitPost (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do
match (← post e) with
| .done e => pure e
| .visit e => visit e
| .continue e? => pure (e?.getD e)
match (← pre e) with
| .done e => pure e
| .visit e => visitPost (← visit e)
| .continue e? =>
let e := e?.getD e
match e with
| Expr.forallE _ d b _ => visitPost (e.updateForallE! (← visit d) (← visit b))
| Expr.lam _ d b _ => visitPost (e.updateLambdaE! (← visit d) (← visit b))
| Expr.letE _ t v b _ => visitPost (e.updateLet! (← visit t) (← visit v) (← visit b))
| Expr.app .. => e.withApp fun f args => do visitPost (mkAppN (← visit f) (← args.mapM visit))
| Expr.mdata _ b => visitPost (e.updateMData! (← visit b))
| Expr.proj _ _ b => visitPost (e.updateProj! (← visit b))
| _ => visitPost e
visit input |>.run
def betaReduce (e : Expr) : CoreM Expr :=
transform e (pre := fun e => return if e.isHeadBetaTarget then .visit e.headBeta else .continue)
end Core
namespace Meta
/--
Similar to `Core.transform`, but terms provided to `pre` and `post` do not contain loose bound variables.
So, it is safe to use any `MetaM` method at `pre` and `post`. -/
partial def transform {m} [Monad m] [MonadLiftT MetaM m] [MonadControlT MetaM m] [MonadTrace m] [MonadRef m] [MonadOptions m] [AddMessageContext m]
(input : Expr)
(pre : Expr → m TransformStep := fun _ => return .continue)
(post : Expr → m TransformStep := fun e => return .done e)
(usedLetOnly := false)
: m Expr := do
let _ : STWorld IO.RealWorld m := ⟨⟩
let _ : MonadLiftT (ST IO.RealWorld) m := { monadLift := fun x => liftM (m := MetaM) (liftM (m := ST IO.RealWorld) x) }
let rec visit (e : Expr) : MonadCacheT ExprStructEq Expr m Expr :=
checkCache { val := e : ExprStructEq } fun _ => Meta.withIncRecDepth do
let rec visitPost (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do
match (← post e) with
| .done e => pure e
| .visit e => visit e
| .continue e? => pure (e?.getD e)
let rec visitLambda (fvars : Array Expr) (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do
match e with
| Expr.lam n d b c =>
withLocalDecl n c (← visit (d.instantiateRev fvars)) fun x =>
visitLambda (fvars.push x) b
| e => visitPost (← mkLambdaFVars (usedLetOnly := usedLetOnly) fvars (← visit (e.instantiateRev fvars)))
let rec visitForall (fvars : Array Expr) (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do
match e with
| Expr.forallE n d b c =>
withLocalDecl n c (← visit (d.instantiateRev fvars)) fun x =>
visitForall (fvars.push x) b
| e => visitPost (← mkForallFVars (usedLetOnly := usedLetOnly) fvars (← visit (e.instantiateRev fvars)))
let rec visitLet (fvars : Array Expr) (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := do
match e with
| Expr.letE n t v b _ =>
withLetDecl n (← visit (t.instantiateRev fvars)) (← visit (v.instantiateRev fvars)) fun x =>
visitLet (fvars.push x) b
| e => visitPost (← mkLetFVars (usedLetOnly := usedLetOnly) fvars (← visit (e.instantiateRev fvars)))
let visitApp (e : Expr) : MonadCacheT ExprStructEq Expr m Expr :=
e.withApp fun f args => do
visitPost (mkAppN (← visit f) (← args.mapM visit))
match (← pre e) with
| .done e => pure e
| .visit e => visit e
| .continue e? =>
let e := e?.getD e
match e with
| Expr.forallE .. => visitForall #[] e
| Expr.lam .. => visitLambda #[] e
| Expr.letE .. => visitLet #[] e
| Expr.app .. => visitApp e
| Expr.mdata _ b => visitPost (e.updateMData! (← visit b))
| Expr.proj _ _ b => visitPost (e.updateProj! (← visit b))
| _ => visitPost e
visit input |>.run
def zetaReduce (e : Expr) : MetaM Expr := do
let pre (e : Expr) : MetaM TransformStep := do
match e with
| Expr.fvar fvarId =>
match (← getLCtx).find? fvarId with
| none => return TransformStep.done e
| some localDecl =>
if let some value := localDecl.value? then
return TransformStep.visit value
else
return TransformStep.done e
| _ => return .continue
transform e (pre := pre) (usedLetOnly := true)
/-- Unfold definitions and theorems in `e` that are not in the current environment, but are in `biggerEnv`. -/
def unfoldDeclsFrom (biggerEnv : Environment) (e : Expr) : CoreM Expr := do
withoutModifyingEnv do
let env ← getEnv
setEnv biggerEnv -- `e` has declarations from `biggerEnv` that are not in `env`
let pre (e : Expr) : CoreM TransformStep := do
match e with
| Expr.const declName us .. =>
if env.contains declName then
return TransformStep.done e
else if let some info := biggerEnv.find? declName then
if info.hasValue then
return TransformStep.visit (← instantiateValueLevelParams info us)
else
return TransformStep.done e
else
return TransformStep.done e
| _ => return .continue
Core.transform e (pre := pre)
def eraseInaccessibleAnnotations (e : Expr) : CoreM Expr :=
Core.transform e (post := fun e => return TransformStep.done <| if let some e := inaccessible? e then e else e)
def erasePatternRefAnnotations (e : Expr) : CoreM Expr :=
Core.transform e (post := fun e => return TransformStep.done <| if let some (_, e) := patternWithRef? e then e else e)
end Meta
end Lean
|
4dfb05951c48cd4883da074a0406a8fd18f27371 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/tactic/squeeze.lean | cbbd0771c73ee08ee1878815afb0cc17cf883f29 | [
"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 | 14,615 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.traversable.basic
import tactic.simpa
open interactive interactive.types lean.parser
private meta def loc.to_string_aux : option name → string
| none := "⊢"
| (some x) := to_string x
/-- pretty print a `loc` -/
meta def loc.to_string : loc → string
| (loc.ns []) := ""
| (loc.ns [none]) := ""
| (loc.ns ls) := string.join $ list.intersperse " " (" at" :: ls.map loc.to_string_aux)
| loc.wildcard := " at *"
/-- shift `pos` `n` columns to the left -/
meta def pos.move_left (p : pos) (n : ℕ) : pos :=
{ line := p.line, column := p.column - n }
namespace tactic
open list
/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/
meta def struct_inst : lean.parser pexpr :=
do tk "{",
ls ← sep_by (skip_info (tk ","))
( sum.inl <$> (tk ".." *> texpr) <|>
sum.inr <$> (prod.mk <$> ident <* tk ":=" <*> texpr)),
tk "}",
let (srcs,fields) := partition_map id ls,
let (names,values) := unzip fields,
pure $ pexpr.mk_structure_instance
{ field_names := names,
field_values := values,
sources := srcs }
/-- pretty print structure instance -/
meta def struct.to_tactic_format (e : pexpr) : tactic format :=
do r ← e.get_structure_instance_info,
fs ← mzip_with (λ n v,
do v ← to_expr v >>= pp,
pure $ format!"{n} := {v}" )
r.field_names r.field_values,
let ss := r.sources.map (λ s, format!" .. {s}"),
let x : format := format.join $ list.intersperse ", " (fs ++ ss),
pure format!" {{{x}}"
/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/
@[user_attribute]
private meta def squeeze_loc_attr :
user_attribute unit (option (list (pos × string × list simp_arg_type × string))) :=
{ name := `_squeeze_loc,
parser := fail "this attribute should not be used",
descr := "table to accumulate multiple `squeeze_simp` suggestions" }
/-- dummy declaration used as target of `squeeze_loc` attribute -/
def squeeze_loc_attr_carrier := ()
run_cmd squeeze_loc_attr.set ``squeeze_loc_attr_carrier none tt
/-- Format a list of arguments for use with `simp` and friends. This omits the
list entirely if it is empty. -/
meta def render_simp_arg_list : list simp_arg_type → tactic format
| [] := pure ""
| args := (++) " " <$> to_line_wrap_format <$> args.mmap pp
/-- Emit a suggestion to the user. If inside a `squeeze_scope` block,
the suggestions emitted through `mk_suggestion` will be aggregated so that
every tactic that makes a suggestion can consider multiple execution of the
same invocation.
If `at_pos` is true, make the suggestion at `p` instead of the current position. -/
meta def mk_suggestion (p : pos) (pre post : string) (args : list simp_arg_type)
(at_pos := ff) : tactic unit :=
do xs ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier,
match xs with
| none := do
args ← render_simp_arg_list args,
if at_pos then
@scope_trace _ p.line p.column $
λ _, _root_.trace sformat!"{pre}{args}{post}" (pure () : tactic unit)
else
trace sformat!"{pre}{args}{post}"
| some xs := do
squeeze_loc_attr.set ``squeeze_loc_attr_carrier ((p,pre,args,post) :: xs) ff
end
local postfix `?`:9001 := optional
/-- translate a `pexpr` into a `simp` configuration -/
meta def parse_config : option pexpr → tactic (simp_config_ext × format)
| none := pure ({}, "")
| (some cfg) :=
do e ← to_expr ``(%%cfg : simp_config_ext),
fmt ← has_to_tactic_format.to_tactic_format cfg,
prod.mk <$> eval_expr simp_config_ext e
<*> struct.to_tactic_format cfg
/-- translate a `pexpr` into a `dsimp` configuration -/
meta def parse_dsimp_config : option pexpr → tactic (dsimp_config × format)
| none := pure ({}, "")
| (some cfg) :=
do e ← to_expr ``(%%cfg : simp_config_ext),
fmt ← has_to_tactic_format.to_tactic_format cfg,
prod.mk <$> eval_expr dsimp_config e
<*> struct.to_tactic_format cfg
/-- `same_result proof tac` runs tactic `tac` and checks if the proof
produced by `tac` is equivalent to `proof`. -/
meta def same_result (pr : proof_state) (tac : tactic unit) : tactic bool :=
do s ← get_proof_state_after tac,
pure $ some pr = s
private meta def filter_simp_set_aux
(tac : bool → list simp_arg_type → tactic unit)
(args : list simp_arg_type) (pr : proof_state) :
list simp_arg_type → list simp_arg_type →
list simp_arg_type → tactic (list simp_arg_type × list simp_arg_type)
| [] ys ds := pure (ys.reverse, ds.reverse)
| (x :: xs) ys ds :=
do b ← same_result pr (tac tt (args ++ xs ++ ys)),
if b
then filter_simp_set_aux xs ys (x:: ds)
else filter_simp_set_aux xs (x :: ys) ds
declare_trace squeeze.deleted
/--
`filter_simp_set g call_simp user_args simp_args` returns `args'` such that, when calling
`call_simp tt /- only -/ args'` on the goal `g` (`g` is a meta var) we end up in the same
state as if we had called `call_simp ff (user_args ++ simp_args)` and removing any one
element of `args'` changes the resulting proof.
-/
meta def filter_simp_set
(tac : bool → list simp_arg_type → tactic unit)
(user_args simp_args : list simp_arg_type) : tactic (list simp_arg_type) :=
do some s ← get_proof_state_after (tac ff (user_args ++ simp_args)),
(simp_args', _) ← filter_simp_set_aux tac user_args s simp_args [] [],
(user_args', ds) ← filter_simp_set_aux tac simp_args' s user_args [] [],
when (is_trace_enabled_for `squeeze.deleted = tt ∧ ¬ ds.empty)
trace!"deleting provided arguments {ds}",
pure (user_args' ++ simp_args')
/-- make a `simp_arg_type` that references the name given as an argument -/
meta def name.to_simp_args (n : name) : tactic simp_arg_type :=
do e ← resolve_name' n, pure $ simp_arg_type.expr e
/-- tactic combinator to create a `simp`-like tactic that minimizes its
argument list.
* `slow`: adds all rfl-lemmas from the environment to the initial list (this is a slower but more
accurate strategy)
* `no_dflt`: did the user use the `only` keyword?
* `args`: list of `simp` arguments
* `tac`: how to invoke the underlying `simp` tactic
-/
meta def squeeze_simp_core
(slow no_dflt : bool) (args : list simp_arg_type)
(tac : Π (no_dflt : bool) (args : list simp_arg_type), tactic unit)
(mk_suggestion : list simp_arg_type → tactic unit) : tactic unit :=
do v ← target >>= mk_meta_var,
args ← if slow then do
simp_set ← attribute.get_instances `simp,
simp_set ← simp_set.mfilter $ has_attribute' `_refl_lemma,
simp_set ← simp_set.mmap $ resolve_name' >=> pure ∘ simp_arg_type.expr,
pure $ args ++ simp_set
else pure args,
g ← retrieve $ do
{ g ← main_goal,
tac no_dflt args,
instantiate_mvars g },
let vs := g.list_constant,
vs ← vs.mfilter is_simp_lemma,
vs ← vs.mmap strip_prefix,
vs ← vs.to_list.mmap name.to_simp_args,
with_local_goals' [v] (filter_simp_set tac args vs)
>>= mk_suggestion,
tac no_dflt args
namespace interactive
attribute [derive decidable_eq] simp_arg_type
/-- Turn a `simp_arg_type` into a string. -/
meta instance simp_arg_type.has_to_string : has_to_string simp_arg_type :=
⟨λ a, match a with
| simp_arg_type.all_hyps := "*"
| (simp_arg_type.except n) := "-" ++ to_string n
| (simp_arg_type.expr e) := to_string e
| (simp_arg_type.symm_expr e) := "←" ++ to_string e
end⟩
/-- combinator meant to aggregate the suggestions issued by multiple calls
of `squeeze_simp` (due, for instance, to `;`).
Can be used as:
```lean
example {α β} (xs ys : list α) (f : α → β) :
(xs ++ ys.tail).map f = xs.map f ∧ (xs.tail.map f).length = xs.length :=
begin
have : xs = ys, admit,
squeeze_scope
{ split; squeeze_simp,
-- `squeeze_simp` is run twice, the first one requires
-- `list.map_append` and the second one
-- `[list.length_map, list.length_tail]`
-- prints only one message and combine the suggestions:
-- > Try this: simp only [list.length_map, list.length_tail, list.map_append]
squeeze_simp [this]
-- `squeeze_simp` is run only once
-- prints:
-- > Try this: simp only [this]
},
end
```
-/
meta def squeeze_scope (tac : itactic) : tactic unit :=
do none ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | pure (),
squeeze_loc_attr.set ``squeeze_loc_attr_carrier (some []) ff,
finally tac $ do
some xs ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | fail "invalid state",
let m := native.rb_lmap.of_list xs,
squeeze_loc_attr.set ``squeeze_loc_attr_carrier none ff,
m.to_list.reverse.mmap' $ λ ⟨p,suggs⟩, do
{ let ⟨pre,_,post⟩ := suggs.head,
let suggs : list (list simp_arg_type) := suggs.map $ prod.fst ∘ prod.snd,
mk_suggestion p pre post (suggs.foldl list.union []) tt, pure () }
/--
`squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp` perform the same
task with the difference that `squeeze_simp` relates to `simp` while
`squeeze_simpa` relates to `simpa` and `squeeze_dsimp` relates to
`dsimp`. The following applies to `squeeze_simp`, `squeeze_simpa` and
`squeeze_dsimp`.
`squeeze_simp` behaves like `simp` (including all its arguments)
and prints a `simp only` invocation to skip the search through the
`simp` lemma list.
For instance, the following is easily solved with `simp`:
```lean
example : 0 + 1 = 1 + 0 := by simp
```
To guide the proof search and speed it up, we may replace `simp`
with `squeeze_simp`:
```lean
example : 0 + 1 = 1 + 0 := by squeeze_simp
-- prints:
-- Try this: simp only [add_zero, eq_self_iff_true, zero_add]
```
`squeeze_simp` suggests a replacement which we can use instead of
`squeeze_simp`.
```lean
example : 0 + 1 = 1 + 0 := by simp only [add_zero, eq_self_iff_true, zero_add]
```
`squeeze_simp only` prints nothing as it already skips the `simp` list.
This tactic is useful for speeding up the compilation of a complete file.
Steps:
1. search and replace ` simp` with ` squeeze_simp` (the space helps avoid the
replacement of `simp` in `@[simp]`) throughout the file.
2. Starting at the beginning of the file, go to each printout in turn, copy
the suggestion in place of `squeeze_simp`.
3. after all the suggestions were applied, search and replace `squeeze_simp` with
`simp` to remove the occurrences of `squeeze_simp` that did not produce a suggestion.
Known limitation(s):
* in cases where `squeeze_simp` is used after a `;` (e.g. `cases x; squeeze_simp`),
`squeeze_simp` will produce as many suggestions as the number of goals it is applied to.
It is likely that none of the suggestion is a good replacement but they can all be
combined by concatenating their list of lemmas. `squeeze_scope` can be used to
combine the suggestions: `by squeeze_scope { cases x; squeeze_simp }`
* sometimes, `simp` lemmas are also `_refl_lemma` and they can be used without appearing in the
resulting proof. `squeeze_simp` won't know to try that lemma unless it is called as
`squeeze_simp?`
-/
meta def squeeze_simp
(key : parse cur_pos)
(slow_and_accurate : parse (tk "?")?)
(use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list) (locat : parse location)
(cfg : parse struct_inst?) : tactic unit :=
do (cfg',c) ← parse_config cfg,
squeeze_simp_core slow_and_accurate.is_some no_dflt hs
(λ l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg')
(λ args,
let use_iota_eqn := if use_iota_eqn.is_some then "!" else "",
attrs := if attr_names.empty then ""
else string.join (list.intersperse " " (" with" :: attr_names.map to_string)),
loc := loc.to_string locat in
mk_suggestion (key.move_left 1)
sformat!"Try this: simp{use_iota_eqn} only"
sformat!"{attrs}{loc}{c}" args)
/-- see `squeeze_simp` -/
meta def squeeze_simpa
(key : parse cur_pos)
(slow_and_accurate : parse (tk "?")?)
(use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?)
(cfg : parse struct_inst?) : tactic unit :=
do (cfg',c) ← parse_config cfg,
tgt' ← traverse (λ t, do t ← to_expr t >>= pp,
pure format!" using {t}") tgt,
squeeze_simp_core slow_and_accurate.is_some no_dflt hs
(λ l_no_dft l_args, simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg')
(λ args,
let use_iota_eqn := if use_iota_eqn.is_some then "!" else "",
attrs := if attr_names.empty then ""
else string.join (list.intersperse " " (" with" :: attr_names.map to_string)),
tgt' := tgt'.get_or_else "" in
mk_suggestion (key.move_left 1)
sformat!"Try this: simpa{use_iota_eqn} only"
sformat!"{attrs}{tgt'}{c}" args)
/-- `squeeze_dsimp` behaves like `dsimp` (including all its arguments)
and prints a `dsimp only` invocation to skip the search through the
`simp` lemma list. See the doc string of `squeeze_simp` for examples.
-/
meta def squeeze_dsimp
(key : parse cur_pos)
(slow_and_accurate : parse (tk "?")?)
(use_iota_eqn : parse (tk "!")?)
(no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list) (locat : parse location)
(cfg : parse struct_inst?) : tactic unit :=
do (cfg',c) ← parse_dsimp_config cfg,
squeeze_simp_core slow_and_accurate.is_some no_dflt hs
(λ l_no_dft l_args, dsimp l_no_dft l_args attr_names locat cfg')
(λ args,
let use_iota_eqn := if use_iota_eqn.is_some then "!" else "",
attrs := if attr_names.empty then ""
else string.join (list.intersperse " " (" with" :: attr_names.map to_string)),
loc := loc.to_string locat in
mk_suggestion (key.move_left 1)
sformat!"Try this: dsimp{use_iota_eqn} only"
sformat!"{attrs}{loc}{c}" args)
end interactive
end tactic
open tactic.interactive
add_tactic_doc
{ name := "squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope",
category := doc_category.tactic,
decl_names :=
[``squeeze_simp,
``squeeze_dsimp,
``squeeze_simpa,
``squeeze_scope],
tags := ["simplification", "Try this"],
inherit_description_from := ``squeeze_simp }
|
bbead8a565eb4dba0ad22e531dfbac36e03712e1 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/beginend3.lean | e25e4422a4c7ba95e7b16c0ef795cb15a40e2b87 | [
"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 | 272 | lean | import logic
open tactic
theorem foo (A : Type) (a b c : A) : a = b → b = c → a = c ∧ c = a :=
begin
intros [Hab, Hbc],
apply and.intro,
apply eq.trans,
rotate 2,
apply eq.trans,
apply (eq.symm Hbc),
apply (eq.symm Hab),
apply Hab,
apply Hbc,
end
|
02aaee3ca5187d64b2e5b3aa1d480d7311052df7 | 07c6143268cfb72beccd1cc35735d424ebcb187b | /src/data/real/ereal.lean | 6571518a61ab8bc9981160301fdba20eb93c2e0d | [
"Apache-2.0"
] | permissive | khoek/mathlib | bc49a842910af13a3c372748310e86467d1dc766 | aa55f8b50354b3e11ba64792dcb06cccb2d8ee28 | refs/heads/master | 1,588,232,063,837 | 1,587,304,803,000 | 1,587,304,803,000 | 176,688,517 | 0 | 0 | Apache-2.0 | 1,553,070,585,000 | 1,553,070,585,000 | null | UTF-8 | Lean | false | false | 3,264 | lean | /-
Copyright (c) 2019 Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard
-/
import data.real.basic
/-!
# The extended reals [-∞, ∞].
This file defines `ereal`, the real numbers together with a top and bottom element,
referred to as ⊤ and ⊥. It is implemented as `with_top (with_bot ℝ)`
Addition and multiplication are problematic in the presence of ±∞, but
negation has a natural definition and satisfies the usual properties.
An addition is derived, but `ereal` is not even a monoid (there is no identity).
`ereal` is a `complete_lattice`; this is now deduced by type class inference from
the fact that `with_top (with_bot L)` is a complete lattice if `L` is
a conditionally complete lattice.
## Tags
real, ereal, complete lattice
## TODO
abs : ereal → ennreal
In Isabelle they define + - * and / (making junk choices for things like -∞ + ∞)
and then prove whatever bits of the ordered ring/field axioms still hold. They
also do some limits stuff (liminf/limsup etc).
See https://isabelle.in.tum.de/dist/library/HOL/HOL-Library/Extended_Real.html
-/
/-- ereal : The type `[-∞, ∞]` -/
@[derive [linear_order, order_bot, order_top,
has_Sup, has_Inf, complete_lattice, has_add]]
def ereal := with_top (with_bot ℝ)
namespace ereal
instance : has_coe ℝ ereal := ⟨some ∘ some⟩
@[simp, norm_cast] protected lemma coe_real_le {x y : ℝ} : (x : ereal) ≤ (y : ereal) ↔ x ≤ y :=
by { unfold_coes, norm_num }
@[simp, norm_cast] protected lemma coe_real_lt {x y : ℝ} : (x : ereal) < (y : ereal) ↔ x < y :=
by { unfold_coes, norm_num }
@[simp, norm_cast] protected lemma coe_real_inj' {x y : ℝ} : (x : ereal) = (y : ereal) ↔ x = y :=
by { unfold_coes, simp [option.some_inj] }
/- neg -/
/-- negation on ereal -/
protected def neg : ereal → ereal
| ⊥ := ⊤
| ⊤ := ⊥
| (x : ℝ) := (-x : ℝ)
instance : has_neg ereal := ⟨ereal.neg⟩
@[norm_cast] protected lemma neg_def (x : ℝ) : ((-x : ℝ) : ereal) = -x := rfl
/-- - -a = a on ereal -/
protected theorem neg_neg : ∀ (a : ereal), - (- a) = a
| ⊥ := rfl
| ⊤ := rfl
| (a : ℝ) := by { norm_cast, simp [neg_neg a] }
theorem neg_inj (a b : ereal) (h : -a = -b) : a = b := by rw [←ereal.neg_neg a, h, ereal.neg_neg b]
/-- Even though ereal is not an additive group, -a = b ↔ -b = a still holds -/
theorem neg_eq_iff_neg_eq {a b : ereal} : -a = b ↔ -b = a :=
⟨by {intro h, rw ←h, exact ereal.neg_neg a},
by {intro h, rw ←h, exact ereal.neg_neg b}⟩
/-- if -a ≤ b then -b ≤ a on ereal -/
protected theorem neg_le_of_neg_le : ∀ {a b : ereal} (h : -a ≤ b), -b ≤ a
| ⊥ ⊥ h := h
| ⊥ (some b) h := by cases (top_le_iff.1 h)
| ⊤ l h := le_top
| (a : ℝ) ⊥ h := by cases (le_bot_iff.1 h)
| l ⊤ h := bot_le
| (a : ℝ) (b : ℝ) h := by { norm_cast at h ⊢, exact _root_.neg_le_of_neg_le h }
/-- -a ≤ b ↔ -b ≤ a on ereal-/
protected theorem neg_le {a b : ereal} : -a ≤ b ↔ -b ≤ a :=
⟨ereal.neg_le_of_neg_le, ereal.neg_le_of_neg_le⟩
/-- a ≤ -b → b ≤ -a on ereal -/
theorem le_neg_of_le_neg {a b : ereal} (h : a ≤ -b) : b ≤ -a :=
by rwa [←ereal.neg_neg b, ereal.neg_le, ereal.neg_neg]
end ereal
|
52e04a0c88b42e31993de6ecc39d0922f5f1de22 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Lean/Compiler/ImplementedByAttr.lean | 5be302e786519d49c9048f46c6a781cbb8b6b26a | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 1,386 | 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.Attributes
import Lean.MonadEnv
namespace Lean.Compiler
builtin_initialize implementedByAttr : ParametricAttribute Name ← registerParametricAttribute {
name := `implementedBy,
descr := "name of the Lean (probably unsafe) function that implements opaque constant",
getParam := fun declName stx => do
let decl ← getConstInfo declName
let fnName ← Attribute.Builtin.getId stx
let fnName ← resolveGlobalConstNoOverload fnName
let fnDecl ← getConstInfo fnName
unless decl.type == fnDecl.type do
throwError "invalid function '{fnName}' type mismatch"
return fnName
}
@[export lean_get_implemented_by]
def getImplementedBy (env : Environment) (declName : Name) : Option Name :=
implementedByAttr.getParam env declName
def setImplementedBy (env : Environment) (declName : Name) (impName : Name) : Except String Environment :=
implementedByAttr.setParam env declName impName
end Compiler
def setImplementedBy {m} [Monad m] [MonadEnv m] [MonadError m] (declName : Name) (impName : Name) : m Unit := do
let env ← getEnv
match Compiler.setImplementedBy env declName impName with
| Except.ok env => setEnv env
| Except.error ex => throwError ex
end Lean
|
bb956073a1b4a3800f99016dd541339d1b031703 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/set_theory/pgame_auto.lean | 5bc7259b7a60e325175a417d6ee096898cb17c2d | [] | 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 | 34,359 | lean | /-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.logic.embedding
import Mathlib.data.nat.cast
import Mathlib.data.fin
import Mathlib.PostPort
universes u l u_1 u_2
namespace Mathlib
/-!
# Combinatorial (pre-)games.
The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We
construct "pregames", define an ordering and arithmetic operations on them, then show that the
operations descend to "games", defined via the equivalence relation `p ≈ q ↔ p ≤ q ∧ q ≤ p`.
The surreal numbers will be built as a quotient of a subtype of pregames.
A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two
types (thought of as indexing the the possible moves for the players Left and Right), and a pair of
functions out of these types to `pgame` (thought of as describing the resulting game after making a
move).
Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`.
## Conway induction
By construction, the induction principle for pregames is exactly "Conway induction". That is, to
prove some predicate `pgame → Prop` holds for all pregames, it suffices to prove that for every
pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds
for `g`.
While it is often convenient to work "by induction" on pregames, in some situations this becomes
awkward, so we also define accessor functions `left_moves`, `right_moves`, `move_left` and
`move_right`. There is a relation `subsequent p q`, saying that `p` can be reached by playing some
non-empty sequence of moves starting from `q`, an instance `well_founded subsequent`, and a local
tactic `pgame_wf_tac` which is helpful for discharging proof obligations in inductive proofs relying
on this relation.
## Order properties
Pregames have both a `≤` and a `<` relation, which are related in quite a subtle way. In particular,
it is worth noting that in Lean's (perhaps unfortunate?) definition of a `preorder`, we have
`lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)`, but this is _not_ satisfied by the usual
`≤` and `<` relations on pregames. (It is satisfied once we restrict to the surreal numbers.) In
particular, `<` is not transitive; there is an example below showing `0 < star ∧ star < 0`.
We do have
```
theorem not_le {x y : pgame} : ¬ x ≤ y ↔ y < x := ...
theorem not_lt {x y : pgame} : ¬ x < y ↔ y ≤ x := ...
```
The statement `0 ≤ x` means that Left has a good response to any move by Right; in particular, the
theorem `zero_le` below states
```
0 ≤ x ↔ ∀ j : x.right_moves, ∃ i : (x.move_right j).left_moves, 0 ≤ (x.move_right j).move_left i
```
On the other hand the statement `0 < x` means that Left has a good move right now; in particular the
theorem `zero_lt` below states
```
0 < x ↔ ∃ i : left_moves x, ∀ j : right_moves (x.move_left i), 0 < (x.move_left i).move_right j
```
The theorems `le_def`, `lt_def`, give a recursive characterisation of each relation, in terms of
themselves two moves later. The theorems `le_def_lt` and `lt_def_lt` give recursive
characterisations of each relation in terms of the other relation one move later.
We define an equivalence relation `equiv p q ↔ p ≤ q ∧ q ≤ p`. Later, games will be defined as the
quotient by this relation.
## Algebraic structures
We next turn to defining the operations necessary to make games into a commutative additive group.
Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR +
y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$.
The order structures interact in the expected way with addition, so we have
```
theorem le_iff_sub_nonneg {x y : pgame} : x ≤ y ↔ 0 ≤ y - x := sorry
theorem lt_iff_sub_pos {x y : pgame} : x < y ↔ 0 < y - x := sorry
```
We show that these operations respect the equivalence relation, and hence descend to games. At the
level of games, these operations satisfy all the laws of a commutative group. To prove the necessary
equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a
game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`.
## Future work
* The theory of dominated and reversible positions, and unique normal form for short games.
* Analysis of basic domineering positions.
* Hex.
* Temperature.
* The development of surreal numbers, based on this development of combinatorial games, is still
quite incomplete.
## References
The material here is all drawn from
* [Conway, *On numbers and games*][conway2001]
An interested reader may like to formalise some of the material from
* [Andreas Blass, *A game semantics for linear logic*][MR1167694]
* [André Joyal, *Remarques sur la théorie des jeux à deux personnes*][joyal1997]
-/
/-- The type of pre-games, before we have quotiented
by extensionality. In ZFC, a combinatorial game is constructed from
two sets of combinatorial games that have been constructed at an earlier
stage. To do this in type theory, we say that a pre-game is built
inductively from two families of pre-games indexed over any type
in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`,
reflecting that it is a proper class in ZFC. -/
inductive pgame where
| mk : (α β : Type u) → (α → pgame) → (β → pgame) → pgame
namespace pgame
/--
Construct a pre-game from list of pre-games describing the available moves for Left and Right.
-/
-- TODO provide some API describing the interaction with
-- `left_moves`, `right_moves`, `move_left` and `move_right` below.
-- TODO define this at the level of games, as well, and perhaps also for finsets of games.
def of_lists (L : List pgame) (R : List pgame) : pgame :=
mk (fin (list.length L)) (fin (list.length R))
(fun (i : fin (list.length L)) => list.nth_le L ↑i sorry)
fun (j : fin (list.length R)) => list.nth_le R (subtype.val j) sorry
/-- The indexing type for allowable moves by Left. -/
def left_moves : pgame → Type u := sorry
/-- The indexing type for allowable moves by Right. -/
def right_moves : pgame → Type u := sorry
/-- The new game after Left makes an allowed move. -/
def move_left (g : pgame) : left_moves g → pgame := sorry
/-- The new game after Right makes an allowed move. -/
def move_right (g : pgame) : right_moves g → pgame := sorry
@[simp] theorem left_moves_mk {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame} :
left_moves (mk xl xr xL xR) = xl :=
rfl
@[simp] theorem move_left_mk {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame}
{i : left_moves (mk xl xr xL xR)} : move_left (mk xl xr xL xR) i = xL i :=
rfl
@[simp] theorem right_moves_mk {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame} :
right_moves (mk xl xr xL xR) = xr :=
rfl
@[simp] theorem move_right_mk {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame}
{j : right_moves (mk xl xr xL xR)} : move_right (mk xl xr xL xR) j = xR j :=
rfl
/-- `subsequent p q` says that `p` can be obtained by playing
some nonempty sequence of moves from `q`. -/
inductive subsequent : pgame → pgame → Prop where
| left : ∀ (x : pgame) (i : left_moves x), subsequent (move_left x i) x
| right : ∀ (x : pgame) (j : right_moves x), subsequent (move_right x j) x
| trans : ∀ (x y z : pgame), subsequent x y → subsequent y z → subsequent x z
theorem wf_subsequent : well_founded subsequent := sorry
protected instance has_well_founded : has_well_founded pgame :=
has_well_founded.mk subsequent wf_subsequent
/-- A move by Left produces a subsequent game. (For use in pgame_wf_tac.) -/
theorem subsequent.left_move {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame}
{i : xl} : subsequent (xL i) (mk xl xr xL xR) :=
subsequent.left (mk xl xr xL xR) i
/-- A move by Right produces a subsequent game. (For use in pgame_wf_tac.) -/
theorem subsequent.right_move {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame}
{j : xr} : subsequent (xR j) (mk xl xr xL xR) :=
subsequent.right (mk xl xr xL xR) j
/-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/
/-- The pre-game `zero` is defined by `0 = { | }`. -/
protected instance has_zero : HasZero pgame := { zero := mk pempty pempty pempty.elim pempty.elim }
@[simp] theorem zero_left_moves : left_moves 0 = pempty := rfl
@[simp] theorem zero_right_moves : right_moves 0 = pempty := rfl
protected instance inhabited : Inhabited pgame := { default := 0 }
/-- The pre-game `one` is defined by `1 = { 0 | }`. -/
protected instance has_one : HasOne pgame :=
{ one := mk PUnit pempty (fun (_x : PUnit) => 0) pempty.elim }
@[simp] theorem one_left_moves : left_moves 1 = PUnit := rfl
@[simp] theorem one_move_left : move_left 1 PUnit.unit = 0 := rfl
@[simp] theorem one_right_moves : right_moves 1 = pempty := rfl
/-- Define simultaneously by mutual induction the `<=` and `<`
relation on pre-games. The ZFC definition says that `x = {xL | xR}`
is less or equal to `y = {yL | yR}` if `∀ x₁ ∈ xL, x₁ < y`
and `∀ y₂ ∈ yR, x < y₂`, where `x < y` is the same as `¬ y <= x`.
This is a tricky induction because it only decreases one side at
a time, and it also swaps the arguments in the definition of `<`.
The solution is to define `x < y` and `x <= y` simultaneously. -/
def le_lt (x : pgame) (y : pgame) : Prop × Prop := sorry
protected instance has_le : HasLessEq pgame :=
{ LessEq := fun (x y : pgame) => prod.fst (le_lt x y) }
protected instance has_lt : HasLess pgame := { Less := fun (x y : pgame) => prod.snd (le_lt x y) }
/-- Definition of `x ≤ y` on pre-games built using the constructor. -/
@[simp] theorem mk_le_mk {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame}
{yl : Type u_1} {yr : Type u_1} {yL : yl → pgame} {yR : yr → pgame} :
mk xl xr xL xR ≤ mk yl yr yL yR ↔
(∀ (i : xl), xL i < mk yl yr yL yR) ∧ ∀ (j : yr), mk xl xr xL xR < yR j :=
iff.rfl
/-- Definition of `x ≤ y` on pre-games, in terms of `<` -/
theorem le_def_lt {x : pgame} {y : pgame} :
x ≤ y ↔ (∀ (i : left_moves x), move_left x i < y) ∧ ∀ (j : right_moves y), x < move_right y j :=
sorry
/-- Definition of `x < y` on pre-games built using the constructor. -/
@[simp] theorem mk_lt_mk {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame}
{yl : Type u_1} {yr : Type u_1} {yL : yl → pgame} {yR : yr → pgame} :
mk xl xr xL xR < mk yl yr yL yR ↔
(∃ (i : yl), mk xl xr xL xR ≤ yL i) ∨ ∃ (j : xr), xR j ≤ mk yl yr yL yR :=
iff.rfl
/-- Definition of `x < y` on pre-games, in terms of `≤` -/
theorem lt_def_le {x : pgame} {y : pgame} :
x < y ↔ (∃ (i : left_moves y), x ≤ move_left y i) ∨ ∃ (j : right_moves x), move_right x j ≤ y :=
sorry
/-- The definition of `x ≤ y` on pre-games, in terms of `≤` two moves later. -/
theorem le_def {x : pgame} {y : pgame} :
x ≤ y ↔
(∀ (i : left_moves x),
(∃ (i' : left_moves y), move_left x i ≤ move_left y i') ∨
∃ (j : right_moves (move_left x i)), move_right (move_left x i) j ≤ y) ∧
∀ (j : right_moves y),
(∃ (i : left_moves (move_right y j)), x ≤ move_left (move_right y j) i) ∨
∃ (j' : right_moves x), move_right x j' ≤ move_right y j :=
sorry
/-- The definition of `x < y` on pre-games, in terms of `<` two moves later. -/
theorem lt_def {x : pgame} {y : pgame} :
x < y ↔
(∃ (i : left_moves y),
(∀ (i' : left_moves x), move_left x i' < move_left y i) ∧
∀ (j : right_moves (move_left y i)), x < move_right (move_left y i) j) ∨
∃ (j : right_moves x),
(∀ (i : left_moves (move_right x j)), move_left (move_right x j) i < y) ∧
∀ (j' : right_moves y), move_right x j < move_right y j' :=
sorry
/-- The definition of `x ≤ 0` on pre-games, in terms of `≤ 0` two moves later. -/
theorem le_zero {x : pgame} :
x ≤ 0 ↔
∀ (i : left_moves x),
∃ (j : right_moves (move_left x i)), move_right (move_left x i) j ≤ 0 :=
sorry
/-- The definition of `0 ≤ x` on pre-games, in terms of `0 ≤` two moves later. -/
theorem zero_le {x : pgame} :
0 ≤ x ↔
∀ (j : right_moves x),
∃ (i : left_moves (move_right x j)), 0 ≤ move_left (move_right x j) i :=
sorry
/-- The definition of `x < 0` on pre-games, in terms of `< 0` two moves later. -/
theorem lt_zero {x : pgame} :
x < 0 ↔
∃ (j : right_moves x),
∀ (i : left_moves (move_right x j)), move_left (move_right x j) i < 0 :=
sorry
/-- The definition of `0 < x` on pre-games, in terms of `< x` two moves later. -/
theorem zero_lt {x : pgame} :
0 < x ↔
∃ (i : left_moves x),
∀ (j : right_moves (move_left x i)), 0 < move_right (move_left x i) j :=
sorry
/-- Given a right-player-wins game, provide a response to any move by left. -/
def right_response {x : pgame} (h : x ≤ 0) (i : left_moves x) : right_moves (move_left x i) :=
classical.some sorry
/-- Show that the response for right provided by `right_response`
preserves the right-player-wins condition. -/
theorem right_response_spec {x : pgame} (h : x ≤ 0) (i : left_moves x) :
move_right (move_left x i) (right_response h i) ≤ 0 :=
classical.some_spec (iff.mp le_zero h i)
/-- Given a left-player-wins game, provide a response to any move by right. -/
def left_response {x : pgame} (h : 0 ≤ x) (j : right_moves x) : left_moves (move_right x j) :=
classical.some sorry
/-- Show that the response for left provided by `left_response`
preserves the left-player-wins condition. -/
theorem left_response_spec {x : pgame} (h : 0 ≤ x) (j : right_moves x) :
0 ≤ move_left (move_right x j) (left_response h j) :=
classical.some_spec (iff.mp zero_le h j)
theorem lt_of_le_mk {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame} {y : pgame}
{i : xl} : mk xl xr xL xR ≤ y → xL i < y :=
pgame.cases_on y
fun (y_α y_β : Type u_1) (y_ᾰ : y_α → pgame) (y_ᾰ_1 : y_β → pgame)
(h : mk xl xr xL xR ≤ mk y_α y_β y_ᾰ y_ᾰ_1) => and.left h i
theorem lt_of_mk_le {x : pgame} {yl : Type u_1} {yr : Type u_1} {yL : yl → pgame} {yR : yr → pgame}
{i : yr} : x ≤ mk yl yr yL yR → x < yR i :=
pgame.cases_on x
fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame)
(h : mk x_α x_β x_ᾰ x_ᾰ_1 ≤ mk yl yr yL yR) => and.right h i
theorem mk_lt_of_le {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame} {y : pgame}
{i : xr} : xR i ≤ y → mk xl xr xL xR < y :=
pgame.cases_on y
fun (y_α y_β : Type u_1) (y_ᾰ : y_α → pgame) (y_ᾰ_1 : y_β → pgame)
(h : xR i ≤ mk y_α y_β y_ᾰ y_ᾰ_1) => Or.inr (Exists.intro i h)
theorem lt_mk_of_le {x : pgame} {yl : Type u_1} {yr : Type u_1} {yL : yl → pgame} {yR : yr → pgame}
{i : yl} : x ≤ yL i → x < mk yl yr yL yR :=
pgame.cases_on x
fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame)
(h : mk x_α x_β x_ᾰ x_ᾰ_1 ≤ yL i) => Or.inl (Exists.intro i h)
theorem not_le_lt {x : pgame} {y : pgame} : (¬x ≤ y ↔ y < x) ∧ (¬x < y ↔ y ≤ x) := sorry
theorem not_le {x : pgame} {y : pgame} : ¬x ≤ y ↔ y < x := and.left not_le_lt
theorem not_lt {x : pgame} {y : pgame} : ¬x < y ↔ y ≤ x := and.right not_le_lt
theorem le_refl (x : pgame) : x ≤ x := sorry
theorem lt_irrefl (x : pgame) : ¬x < x := iff.mpr not_lt (le_refl x)
theorem ne_of_lt {x : pgame} {y : pgame} : x < y → x ≠ y := sorry
theorem le_trans_aux {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame}
{yl : Type u_1} {yr : Type u_1} {yL : yl → pgame} {yR : yr → pgame} {zl : Type u_1}
{zr : Type u_1} {zL : zl → pgame} {zR : zr → pgame}
(h₁ :
∀ (i : xl), mk yl yr yL yR ≤ mk zl zr zL zR → mk zl zr zL zR ≤ xL i → mk yl yr yL yR ≤ xL i)
(h₂ :
∀ (i : zr), zR i ≤ mk xl xr xL xR → mk xl xr xL xR ≤ mk yl yr yL yR → zR i ≤ mk yl yr yL yR) :
mk xl xr xL xR ≤ mk yl yr yL yR →
mk yl yr yL yR ≤ mk zl zr zL zR → mk xl xr xL xR ≤ mk zl zr zL zR :=
sorry
theorem le_trans {x : pgame} {y : pgame} {z : pgame} : x ≤ y → y ≤ z → x ≤ z := sorry
theorem lt_of_le_of_lt {x : pgame} {y : pgame} {z : pgame} (hxy : x ≤ y) (hyz : y < z) : x < z :=
eq.mpr (id (Eq._oldrec (Eq.refl (x < z)) (Eq.symm (propext not_le))))
(mt (fun (H : z ≤ x) => le_trans H hxy)
(eq.mp (Eq._oldrec (Eq.refl (y < z)) (Eq.symm (propext not_le))) hyz))
theorem lt_of_lt_of_le {x : pgame} {y : pgame} {z : pgame} (hxy : x < y) (hyz : y ≤ z) : x < z :=
eq.mpr (id (Eq._oldrec (Eq.refl (x < z)) (Eq.symm (propext not_le))))
(mt (fun (H : z ≤ x) => le_trans hyz H)
(eq.mp (Eq._oldrec (Eq.refl (x < y)) (Eq.symm (propext not_le))) hxy))
/-- Define the equivalence relation on pre-games. Two pre-games
`x`, `y` are equivalent if `x ≤ y` and `y ≤ x`. -/
def equiv (x : pgame) (y : pgame) := x ≤ y ∧ y ≤ x
theorem equiv_refl (x : pgame) : equiv x x := { left := le_refl x, right := le_refl x }
theorem equiv_symm {x : pgame} {y : pgame} : equiv x y → equiv y x :=
fun (ᾰ : equiv x y) =>
and.dcases_on ᾰ
fun (ᾰ_left : x ≤ y) (ᾰ_right : y ≤ x) =>
idRhs (y ≤ x ∧ x ≤ y) { left := ᾰ_right, right := ᾰ_left }
theorem equiv_trans {x : pgame} {y : pgame} {z : pgame} : equiv x y → equiv y z → equiv x z := sorry
theorem lt_of_lt_of_equiv {x : pgame} {y : pgame} {z : pgame} (h₁ : x < y) (h₂ : equiv y z) :
x < z :=
lt_of_lt_of_le h₁ (and.left h₂)
theorem le_of_le_of_equiv {x : pgame} {y : pgame} {z : pgame} (h₁ : x ≤ y) (h₂ : equiv y z) :
x ≤ z :=
le_trans h₁ (and.left h₂)
theorem lt_of_equiv_of_lt {x : pgame} {y : pgame} {z : pgame} (h₁ : equiv x y) (h₂ : y < z) :
x < z :=
lt_of_le_of_lt (and.left h₁) h₂
theorem le_of_equiv_of_le {x : pgame} {y : pgame} {z : pgame} (h₁ : equiv x y) (h₂ : y ≤ z) :
x ≤ z :=
le_trans (and.left h₁) h₂
theorem le_congr {x₁ : pgame} {y₁ : pgame} {x₂ : pgame} {y₂ : pgame} :
equiv x₁ x₂ → equiv y₁ y₂ → (x₁ ≤ y₁ ↔ x₂ ≤ y₂) :=
sorry
theorem lt_congr {x₁ : pgame} {y₁ : pgame} {x₂ : pgame} {y₂ : pgame} (hx : equiv x₁ x₂)
(hy : equiv y₁ y₂) : x₁ < y₁ ↔ x₂ < y₂ :=
iff.trans (iff.symm not_le) (iff.trans (not_congr (le_congr hy hx)) not_le)
theorem equiv_congr_left {y₁ : pgame} {y₂ : pgame} :
equiv y₁ y₂ ↔ ∀ (x₁ : pgame), equiv x₁ y₁ ↔ equiv x₁ y₂ :=
sorry
theorem equiv_congr_right {x₁ : pgame} {x₂ : pgame} :
equiv x₁ x₂ ↔ ∀ (y₁ : pgame), equiv x₁ y₁ ↔ equiv x₂ y₁ :=
sorry
/-- `restricted x y` says that Left always has no more moves in `x` than in `y`,
and Right always has no more moves in `y` than in `x` -/
inductive restricted : pgame → pgame → Type (u + 1) where
| mk :
{x y : pgame} →
(L : left_moves x → left_moves y) →
(R : right_moves y → right_moves x) →
((i : left_moves x) → restricted (move_left x i) (move_left y (L i))) →
((j : right_moves y) → restricted (move_right x (R j)) (move_right y j)) →
restricted x y
/-- The identity restriction. -/
def restricted.refl (x : pgame) : restricted x x := sorry
-- TODO trans for restricted
theorem le_of_restricted {x : pgame} {y : pgame} (r : restricted x y) : x ≤ y := sorry
/--
`relabelling x y` says that `x` and `y` are really the same game, just dressed up differently.
Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly
for Right, and under these bijections we inductively have `relabelling`s for the consequent games.
-/
inductive relabelling : pgame → pgame → Type (u + 1) where
| mk :
{x y : pgame} →
(L : left_moves x ≃ left_moves y) →
(R : right_moves x ≃ right_moves y) →
((i : left_moves x) → relabelling (move_left x i) (move_left y (coe_fn L i))) →
((j : right_moves y) →
relabelling (move_right x (coe_fn (equiv.symm R) j)) (move_right y j)) →
relabelling x y
/-- If `x` is a relabelling of `y`, then Left and Right have the same moves in either game,
so `x` is a restriction of `y`. -/
def restricted_of_relabelling {x : pgame} {y : pgame} (r : relabelling x y) : restricted x y :=
sorry
-- It's not the case that `restricted x y → restricted y x → relabelling x y`,
-- but if we insisted that the maps in a restriction were injective, then one
-- could use Schröder-Bernstein for do this.
/-- The identity relabelling. -/
def relabelling.refl (x : pgame) : relabelling x x := sorry
/-- Reverse a relabelling. -/
def relabelling.symm {x : pgame} {y : pgame} : relabelling x y → relabelling y x := sorry
/-- Transitivity of relabelling -/
def relabelling.trans {x : pgame} {y : pgame} {z : pgame} :
relabelling x y → relabelling y z → relabelling x z :=
sorry
theorem le_of_relabelling {x : pgame} {y : pgame} (r : relabelling x y) : x ≤ y :=
le_of_restricted (restricted_of_relabelling r)
/-- A relabelling lets us prove equivalence of games. -/
theorem equiv_of_relabelling {x : pgame} {y : pgame} (r : relabelling x y) : equiv x y :=
{ left := le_of_relabelling r, right := le_of_relabelling (relabelling.symm r) }
protected instance equiv.has_coe {x : pgame} {y : pgame} : has_coe (relabelling x y) (equiv x y) :=
has_coe.mk equiv_of_relabelling
/-- Replace the types indexing the next moves for Left and Right by equivalent types. -/
def relabel {x : pgame} {xl' : Type u_1} {xr' : Type u_1} (el : left_moves x ≃ xl')
(er : right_moves x ≃ xr') : pgame :=
mk xl' xr' (fun (i : xl') => move_left x (coe_fn (equiv.symm el) i))
fun (j : xr') => move_right x (coe_fn (equiv.symm er) j)
@[simp] theorem relabel_move_left' {x : pgame} {xl' : Type u_1} {xr' : Type u_1}
(el : left_moves x ≃ xl') (er : right_moves x ≃ xr') (i : xl') :
move_left (relabel el er) i = move_left x (coe_fn (equiv.symm el) i) :=
rfl
@[simp] theorem relabel_move_left {x : pgame} {xl' : Type u_1} {xr' : Type u_1}
(el : left_moves x ≃ xl') (er : right_moves x ≃ xr') (i : left_moves x) :
move_left (relabel el er) (coe_fn el i) = move_left x i :=
sorry
@[simp] theorem relabel_move_right' {x : pgame} {xl' : Type u_1} {xr' : Type u_1}
(el : left_moves x ≃ xl') (er : right_moves x ≃ xr') (j : xr') :
move_right (relabel el er) j = move_right x (coe_fn (equiv.symm er) j) :=
rfl
@[simp] theorem relabel_move_right {x : pgame} {xl' : Type u_1} {xr' : Type u_1}
(el : left_moves x ≃ xl') (er : right_moves x ≃ xr') (j : right_moves x) :
move_right (relabel el er) (coe_fn er j) = move_right x j :=
sorry
/-- The game obtained by relabelling the next moves is a relabelling of the original game. -/
def relabel_relabelling {x : pgame} {xl' : Type u_1} {xr' : Type u_1} (el : left_moves x ≃ xl')
(er : right_moves x ≃ xr') : relabelling x (relabel el er) :=
relabelling.mk el er (fun (i : left_moves x) => eq.mpr sorry (relabelling.refl (move_left x i)))
fun (j : right_moves (relabel el er)) =>
eq.mpr sorry (relabelling.refl (move_right x (coe_fn (equiv.symm er) j)))
/-- The negation of `{L | R}` is `{-R | -L}`. -/
def neg : pgame → pgame := sorry
protected instance has_neg : Neg pgame := { neg := neg }
@[simp] theorem neg_def {xl : Type u_1} {xr : Type u_1} {xL : xl → pgame} {xR : xr → pgame} :
-mk xl xr xL xR = mk xr xl (fun (j : xr) => -xR j) fun (i : xl) => -xL i :=
rfl
@[simp] theorem neg_neg {x : pgame} : --x = x := sorry
@[simp] theorem neg_zero : -0 = 0 := sorry
/-- An explicit equivalence between the moves for Left in `-x` and the moves for Right in `x`. -/
-- This equivalence is useful to avoid having to use `cases` unnecessarily.
def left_moves_neg (x : pgame) : left_moves (-x) ≃ right_moves x :=
pgame.cases_on x
fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame) =>
equiv.refl (left_moves (-mk x_α x_β x_ᾰ x_ᾰ_1))
/-- An explicit equivalence between the moves for Right in `-x` and the moves for Left in `x`. -/
def right_moves_neg (x : pgame) : right_moves (-x) ≃ left_moves x :=
pgame.cases_on x
fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame) =>
equiv.refl (right_moves (-mk x_α x_β x_ᾰ x_ᾰ_1))
@[simp] theorem move_right_left_moves_neg {x : pgame} (i : left_moves (-x)) :
move_right x (coe_fn (left_moves_neg x) i) = -move_left (-x) i :=
sorry
@[simp] theorem move_left_left_moves_neg_symm {x : pgame} (i : right_moves x) :
move_left (-x) (coe_fn (equiv.symm (left_moves_neg x)) i) = -move_right x i :=
sorry
@[simp] theorem move_left_right_moves_neg {x : pgame} (i : right_moves (-x)) :
move_left x (coe_fn (right_moves_neg x) i) = -move_right (-x) i :=
sorry
@[simp] theorem move_right_right_moves_neg_symm {x : pgame} (i : left_moves x) :
move_right (-x) (coe_fn (equiv.symm (right_moves_neg x)) i) = -move_left x i :=
sorry
theorem le_iff_neg_ge {x : pgame} {y : pgame} : x ≤ y ↔ -y ≤ -x := sorry
theorem neg_congr {x : pgame} {y : pgame} (h : equiv x y) : equiv (-x) (-y) :=
{ left := iff.mp le_iff_neg_ge (and.right h), right := iff.mp le_iff_neg_ge (and.left h) }
theorem lt_iff_neg_gt {x : pgame} {y : pgame} : x < y ↔ -y < -x :=
eq.mpr (id (Eq._oldrec (Eq.refl (x < y ↔ -y < -x)) (Eq.symm (propext not_le))))
(eq.mpr (id (Eq._oldrec (Eq.refl (¬y ≤ x ↔ -y < -x)) (Eq.symm (propext not_le))))
(eq.mpr (id (Eq._oldrec (Eq.refl (¬y ≤ x ↔ ¬-x ≤ -y)) (propext not_iff_not))) le_iff_neg_ge))
theorem zero_le_iff_neg_le_zero {x : pgame} : 0 ≤ x ↔ -x ≤ 0 := sorry
theorem le_zero_iff_zero_le_neg {x : pgame} : x ≤ 0 ↔ 0 ≤ -x := sorry
/-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
def add (x : pgame) (y : pgame) : pgame :=
pgame.rec
(fun (xl xr : Type u_1) (xL : xl → pgame) (xR : xr → pgame)
(IHxl : (ᾰ : xl) → (fun (x : pgame) => pgame → pgame) (xL ᾰ))
(IHxr : (ᾰ : xr) → (fun (x : pgame) => pgame → pgame) (xR ᾰ)) (y : pgame) =>
pgame.rec
(fun (yl yr : Type u_2) (yL : yl → pgame) (yR : yr → pgame)
(IHyl : (ᾰ : yl) → (fun (y : pgame) => pgame) (yL ᾰ))
(IHyr : (ᾰ : yr) → (fun (y : pgame) => pgame) (yR ᾰ)) =>
mk (xl ⊕ yl) (xr ⊕ yr)
(sum.rec (fun (i : xl) => IHxl i (mk yl yr yL yR)) fun (i : yl) => IHyl i)
(sum.rec (fun (i : xr) => IHxr i (mk yl yr yL yR)) fun (i : yr) => IHyr i))
y)
x y
protected instance has_add : Add pgame := { add := add }
/-- `x + 0` has exactly the same moves as `x`. -/
def add_zero_relabelling (x : pgame) : relabelling (x + 0) x := sorry
/-- `x + 0` is equivalent to `x`. -/
theorem add_zero_equiv (x : pgame) : equiv (x + 0) x :=
equiv_of_relabelling (add_zero_relabelling x)
/-- `0 + x` has exactly the same moves as `x`. -/
def zero_add_relabelling (x : pgame) : relabelling (0 + x) x := sorry
/-- `0 + x` is equivalent to `x`. -/
theorem zero_add_equiv (x : pgame) : equiv (0 + x) x :=
equiv_of_relabelling (zero_add_relabelling x)
/-- An explicit equivalence between the moves for Left in `x + y` and the type-theory sum
of the moves for Left in `x` and in `y`. -/
def left_moves_add (x : pgame) (y : pgame) : left_moves (x + y) ≃ left_moves x ⊕ left_moves y :=
pgame.cases_on x
fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame) =>
pgame.cases_on y
fun (y_α y_β : Type u_1) (y_ᾰ : y_α → pgame) (y_ᾰ_1 : y_β → pgame) =>
equiv.refl (left_moves (mk x_α x_β x_ᾰ x_ᾰ_1 + mk y_α y_β y_ᾰ y_ᾰ_1))
/-- An explicit equivalence between the moves for Right in `x + y` and the type-theory sum
of the moves for Right in `x` and in `y`. -/
def right_moves_add (x : pgame) (y : pgame) : right_moves (x + y) ≃ right_moves x ⊕ right_moves y :=
pgame.cases_on x
fun (x_α x_β : Type u_1) (x_ᾰ : x_α → pgame) (x_ᾰ_1 : x_β → pgame) =>
pgame.cases_on y
fun (y_α y_β : Type u_1) (y_ᾰ : y_α → pgame) (y_ᾰ_1 : y_β → pgame) =>
equiv.refl (right_moves (mk x_α x_β x_ᾰ x_ᾰ_1 + mk y_α y_β y_ᾰ y_ᾰ_1))
@[simp] theorem mk_add_move_left_inl {xl : Type u_1} {xr : Type u_1} {yl : Type u_1} {yr : Type u_1}
{xL : xl → pgame} {xR : xr → pgame} {yL : yl → pgame} {yR : yr → pgame} {i : xl} :
move_left (mk xl xr xL xR + mk yl yr yL yR) (sum.inl i) =
move_left (mk xl xr xL xR) i + mk yl yr yL yR :=
rfl
@[simp] theorem add_move_left_inl {x : pgame} {y : pgame} {i : left_moves x} :
move_left (x + y) (coe_fn (equiv.symm (left_moves_add x y)) (sum.inl i)) = move_left x i + y :=
sorry
@[simp] theorem mk_add_move_right_inl {xl : Type u_1} {xr : Type u_1} {yl : Type u_1}
{yr : Type u_1} {xL : xl → pgame} {xR : xr → pgame} {yL : yl → pgame} {yR : yr → pgame}
{i : xr} :
move_right (mk xl xr xL xR + mk yl yr yL yR) (sum.inl i) =
move_right (mk xl xr xL xR) i + mk yl yr yL yR :=
rfl
@[simp] theorem add_move_right_inl {x : pgame} {y : pgame} {i : right_moves x} :
move_right (x + y) (coe_fn (equiv.symm (right_moves_add x y)) (sum.inl i)) =
move_right x i + y :=
sorry
@[simp] theorem mk_add_move_left_inr {xl : Type u_1} {xr : Type u_1} {yl : Type u_1} {yr : Type u_1}
{xL : xl → pgame} {xR : xr → pgame} {yL : yl → pgame} {yR : yr → pgame} {i : yl} :
move_left (mk xl xr xL xR + mk yl yr yL yR) (sum.inr i) =
mk xl xr xL xR + move_left (mk yl yr yL yR) i :=
rfl
@[simp] theorem add_move_left_inr {x : pgame} {y : pgame} {i : left_moves y} :
move_left (x + y) (coe_fn (equiv.symm (left_moves_add x y)) (sum.inr i)) = x + move_left y i :=
sorry
@[simp] theorem mk_add_move_right_inr {xl : Type u_1} {xr : Type u_1} {yl : Type u_1}
{yr : Type u_1} {xL : xl → pgame} {xR : xr → pgame} {yL : yl → pgame} {yR : yr → pgame}
{i : yr} :
move_right (mk xl xr xL xR + mk yl yr yL yR) (sum.inr i) =
mk xl xr xL xR + move_right (mk yl yr yL yR) i :=
rfl
@[simp] theorem add_move_right_inr {x : pgame} {y : pgame} {i : right_moves y} :
move_right (x + y) (coe_fn (equiv.symm (right_moves_add x y)) (sum.inr i)) =
x + move_right y i :=
sorry
protected instance has_sub : Sub pgame := { sub := fun (x y : pgame) => x + -y }
/-- `-(x+y)` has exactly the same moves as `-x + -y`. -/
def neg_add_relabelling (x : pgame) (y : pgame) : relabelling (-(x + y)) (-x + -y) := sorry
theorem neg_add_le {x : pgame} {y : pgame} : -(x + y) ≤ -x + -y :=
le_of_relabelling (neg_add_relabelling x y)
/-- `x+y` has exactly the same moves as `y+x`. -/
def add_comm_relabelling (x : pgame) (y : pgame) : relabelling (x + y) (y + x) := sorry
theorem add_comm_le {x : pgame} {y : pgame} : x + y ≤ y + x :=
le_of_relabelling (add_comm_relabelling x y)
theorem add_comm_equiv {x : pgame} {y : pgame} : equiv (x + y) (y + x) :=
equiv_of_relabelling (add_comm_relabelling x y)
/-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/
def add_assoc_relabelling (x : pgame) (y : pgame) (z : pgame) :
relabelling (x + y + z) (x + (y + z)) :=
sorry
theorem add_assoc_equiv {x : pgame} {y : pgame} {z : pgame} : equiv (x + y + z) (x + (y + z)) :=
equiv_of_relabelling (add_assoc_relabelling x y z)
theorem add_le_add_right {x : pgame} {y : pgame} {z : pgame} (h : x ≤ y) : x + z ≤ y + z := sorry
theorem add_le_add_left {x : pgame} {y : pgame} {z : pgame} (h : y ≤ z) : x + y ≤ x + z :=
le_trans (le_trans add_comm_le (add_le_add_right h)) add_comm_le
theorem add_congr {w : pgame} {x : pgame} {y : pgame} {z : pgame} (h₁ : equiv w x)
(h₂ : equiv y z) : equiv (w + y) (x + z) :=
{ left := le_trans (add_le_add_left (and.left h₂)) (add_le_add_right (and.left h₁)),
right := le_trans (add_le_add_left (and.right h₂)) (add_le_add_right (and.right h₁)) }
theorem add_left_neg_le_zero {x : pgame} : -x + x ≤ 0 := sorry
theorem zero_le_add_left_neg {x : pgame} : 0 ≤ -x + x :=
eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ -x + x)) (propext le_iff_neg_ge)))
(eq.mpr (id (Eq._oldrec (Eq.refl (-(-x + x) ≤ -0)) neg_zero))
(le_trans neg_add_le add_left_neg_le_zero))
theorem add_left_neg_equiv {x : pgame} : equiv (-x + x) 0 :=
{ left := add_left_neg_le_zero, right := zero_le_add_left_neg }
theorem add_right_neg_le_zero {x : pgame} : x + -x ≤ 0 := le_trans add_comm_le add_left_neg_le_zero
theorem zero_le_add_right_neg {x : pgame} : 0 ≤ x + -x := le_trans zero_le_add_left_neg add_comm_le
theorem add_lt_add_right {x : pgame} {y : pgame} {z : pgame} (h : x < y) : x + z < y + z := sorry
theorem add_lt_add_left {x : pgame} {y : pgame} {z : pgame} (h : y < z) : x + y < x + z :=
lt_of_lt_of_le (lt_of_le_of_lt add_comm_le (add_lt_add_right h)) add_comm_le
theorem le_iff_sub_nonneg {x : pgame} {y : pgame} : x ≤ y ↔ 0 ≤ y - x := sorry
theorem lt_iff_sub_pos {x : pgame} {y : pgame} : x < y ↔ 0 < y - x := sorry
/-- The pre-game `star`, which is fuzzy/confused with zero. -/
def star : pgame := of_lists [0] [0]
theorem star_lt_zero : star < 0 := sorry
theorem zero_lt_star : 0 < star := sorry
/-- The pre-game `ω`. (In fact all ordinals have game and surreal representatives.) -/
def omega : pgame := mk (ulift ℕ) pempty (fun (n : ulift ℕ) => ↑(ulift.down n)) pempty.elim
end Mathlib |
a73feb03ddc4e728147abcc5624efee4163aa5bd | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/universal/products.lean | 7cde5986007b3a5483ed6c6dff054efcc6ba8a36 | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 1,286 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison, Reid Barton, Mario Carneiro
import category_theory.limits.binary_products
open category_theory
universes u v
namespace category_theory.limits
variables {C : Type u} [𝒞 : category.{u v} C] [has_binary_products.{u v} C]
include 𝒞
def binary_product.braiding (P Q : C) : prod P Q ≅ prod Q P :=
{ hom := prod.lift (prod.π₂ _ _) (prod.π₁ _ _),
inv := prod.lift (prod.π₂ _ _) (prod.π₁ _ _) }
def binary_product.symmetry (P Q : C) : (binary_product.braiding P Q).hom ≫ (binary_product.braiding Q P).hom = 𝟙 _ :=
begin
dunfold binary_product.braiding,
obviously,
end
def binary_product.associativity (P Q R : C) : (prod (prod P Q) R) ≅ (prod P (prod Q R)) :=
{ hom := prod.lift (prod.π₁ _ _ ≫ prod.π₁ _ _) (prod.lift (prod.π₁ _ _ ≫ prod.π₂ _ _) (prod.π₂ _ _)),
inv := prod.lift (prod.lift (prod.π₁ _ _) (prod.π₂ _ _ ≫ prod.π₁ _ _)) (prod.π₂ _ _ ≫ prod.π₂ _ _),
hom_inv_id' := begin ext; simp; rw ← category.assoc; simp, end,
inv_hom_id' := begin ext; simp; rw ← category.assoc; simp, end }
-- TODO verify the pentagon?
end category_theory.limits |
58cb4408c114683ecd047d4b32e1907a8dddc886 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/471.lean | 4d6091215b6988aea89a0a3c865219a21e25c9a8 | [
"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 | 733 | lean | inductive vec : Nat → Type where
| nil : vec 0
| cons : Int → vec n → vec n.succ
def vec_len : vec n → Nat
| vec.nil => 0
| x@(vec.cons h t) => vec_len t + 1
def vec_len' : {n : Nat} → vec n → Nat
| _, vec.nil => 0
| _, x@(vec.cons h t) => vec_len' t + 1
def tst1 : vec (n+1) → Int × vec (n+1) × vec n
| x@(vec.cons h t) => (h, x, t)
def tst2 : vec n → Option (Int × vec n)
| x@(vec.cons h t) => some (h, x)
| _ => none
example (a : Int) (x : vec n) : tst2 (vec.cons a x) = some (a, vec.cons a x) :=
rfl
def vec_len_non_as : vec n → Nat
| vec.nil => 0
| vec.cons h t => vec_len_non_as t + 1
def list_len : List Int → Nat
| List.nil => 0
| x@(List.cons h t) => list_len t + 1
|
a2792691b34da4e168e35efa1139165b98b9af54 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/category_theory/limits/shapes/finite_products.lean | 21583289c46008618857c0228c6183333cbe85fd | [
"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 | 2,543 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.shapes.finite_limits
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.terminal
universes v u
open category_theory
namespace category_theory.limits
variables (C : Type u) [category.{v} C]
/--
A category has finite products if there is a chosen limit for every diagram
with shape `discrete J`, where we have `[decidable_eq J]` and `[fintype J]`.
-/
-- We can't simply make this an abbreviation, as we do with other `has_Xs` limits typeclasses,
-- because of https://github.com/leanprover-community/lean/issues/429
class has_finite_products : Prop :=
(out (J : Type v) [decidable_eq J] [fintype J] : has_limits_of_shape (discrete J) C)
instance has_limits_of_shape_discrete
(J : Type v) [fintype J] [has_finite_products C] :
has_limits_of_shape (discrete J) C :=
by { haveI := @has_finite_products.out C _ _ J (classical.dec_eq _), apply_instance }
/-- If `C` has finite limits then it has finite products. -/
@[priority 10]
instance has_finite_products_of_has_finite_limits [has_finite_limits C] : has_finite_products C :=
⟨λ J 𝒥₁ 𝒥₂, by { resetI, apply_instance }⟩
/--
If a category has all products then in particular it has finite products.
-/
lemma has_finite_products_of_has_products [has_products C] : has_finite_products C :=
⟨by apply_instance⟩
/--
A category has finite coproducts if there is a chosen colimit for every diagram
with shape `discrete J`, where we have `[decidable_eq J]` and `[fintype J]`.
-/
class has_finite_coproducts : Prop :=
(out (J : Type v) [decidable_eq J] [fintype J] : has_colimits_of_shape (discrete J) C)
attribute [class] has_finite_coproducts
instance has_colimits_of_shape_discrete
(J : Type v) [fintype J] [has_finite_coproducts C] :
has_colimits_of_shape (discrete J) C :=
by { haveI := @has_finite_coproducts.out C _ _ J (classical.dec_eq _), apply_instance }
/-- If `C` has finite colimits then it has finite coproducts. -/
@[priority 10]
instance has_finite_coproducts_of_has_finite_colimits [has_finite_colimits C] :
has_finite_coproducts C :=
⟨λ J 𝒥₁ 𝒥₂, by { resetI, apply_instance }⟩
/--
If a category has all coproducts then in particular it has finite coproducts.
-/
lemma has_finite_coproducts_of_has_coproducts [has_coproducts C] : has_finite_coproducts C :=
⟨by apply_instance⟩
end category_theory.limits
|
072b7bd6059c967c641b234d7e2295151f4d4f7a | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/probability_theory/notation.lean | 1eff42950a88c0c2245ec977b791cf55f6770071 | [
"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 | 1,806 | lean | /-
Copyright (c) 2021 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne
-/
import measure_theory.function.conditional_expectation
import measure_theory.decomposition.radon_nikodym
/-! # Notations for probability theory
This file defines the following notations, for functions `X,Y`, measures `P, Q` defined on a
measurable space `m0`, and another measurable space structure `m` with `hm : m ≤ m0`,
- `P[X] = ∫ a, X a ∂P`
- `𝔼[X] = ∫ a, X a`
- `𝔼[X|hm]`: conditional expectation of `X` with respect to the measure `volume` and the
measurable space `m`. The similar `P[X|hm]` for a measure `P` is defined in
measure_theory.function.conditional_expectation.
- `X =ₐₛ Y`: `X =ᵐ[volume] Y`
- `X ≤ₐₛ Y`: `X ≤ᵐ[volume] Y`
- `∂P/∂Q = P.rn_deriv Q`
We note that the notation `∂P/∂Q` applies to three different cases, namely,
`measure_theory.measure.rn_deriv`, `measure_theory.signed_measure.rn_deriv` and
`measure_theory.complex_measure.rn_deriv`.
TODO: define the notation `ℙ s` for the probability of a set `s`, and decide whether it should be a
value in `ℝ`, `ℝ≥0` or `ℝ≥0∞`.
-/
open measure_theory
localized "notation `𝔼[` X `|` hm `]` := measure_theory.condexp hm measure_theory.measure.volume X"
in probability_theory
localized "notation P `[` X `]` := ∫ x, X x ∂P" in probability_theory
localized "notation `𝔼[` X `]` := ∫ a, X a" in probability_theory
localized "notation X `=ₐₛ`:50 Y:50 := X =ᵐ[measure_theory.measure.volume] Y" in probability_theory
localized "notation X `≤ₐₛ`:50 Y:50 := X ≤ᵐ[measure_theory.measure.volume] Y" in probability_theory
localized "notation `∂` P `/∂`:50 Q:50 := P.rn_deriv Q" in probability_theory
|
ba00c7a053694813b2ba4c5b80e488062dc7e1b6 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/direct_sum/module.lean | 6275b203e2853fbeff9ab7fbe317bd1d913596a0 | [
"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 | 15,842 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.direct_sum.basic
import linear_algebra.dfinsupp
/-!
# Direct sum of modules
The first part of the file provides constructors for direct sums of modules. It provides a
construction of the direct sum using the universal property and proves its uniqueness
(`direct_sum.to_module.unique`).
The second part of the file covers the special case of direct sums of submodules of a fixed module
`M`. There is a canonical linear map from this direct sum to `M`, and the construction is
of particular importance when this linear map is an equivalence; that is, when the submodules
provide an internal decomposition of `M`. The property is defined as
`direct_sum.submodule_is_internal`, and its basic consequences are established.
-/
universes u v w u₁
namespace direct_sum
open_locale direct_sum
section general
variables {R : Type u} [semiring R]
variables {ι : Type v} [dec_ι : decidable_eq ι]
include R
variables {M : ι → Type w} [Π i, add_comm_monoid (M i)] [Π i, module R (M i)]
instance : module R (⨁ i, M i) := dfinsupp.module
instance {S : Type*} [semiring S] [Π i, module S (M i)] [Π i, smul_comm_class R S (M i)] :
smul_comm_class R S (⨁ i, M i) := dfinsupp.smul_comm_class
instance {S : Type*} [semiring S] [has_scalar R S] [Π i, module S (M i)]
[Π i, is_scalar_tower R S (M i)] :
is_scalar_tower R S (⨁ i, M i) := dfinsupp.is_scalar_tower
instance [Π i, module Rᵐᵒᵖ (M i)] [Π i, is_central_scalar R (M i)] :
is_central_scalar R (⨁ i, M i) := dfinsupp.is_central_scalar
lemma smul_apply (b : R) (v : ⨁ i, M i) (i : ι) :
(b • v) i = b • (v i) := dfinsupp.smul_apply _ _ _
include dec_ι
variables R ι M
/-- Create the direct sum given a family `M` of `R` modules indexed over `ι`. -/
def lmk : Π s : finset ι, (Π i : (↑s : set ι), M i.val) →ₗ[R] (⨁ i, M i) :=
dfinsupp.lmk
/-- Inclusion of each component into the direct sum. -/
def lof : Π i : ι, M i →ₗ[R] (⨁ i, M i) :=
dfinsupp.lsingle
lemma lof_eq_of (i : ι) (b : M i) : lof R ι M i b = of M i b := rfl
variables {ι M}
lemma single_eq_lof (i : ι) (b : M i) :
dfinsupp.single i b = lof R ι M i b := rfl
/-- Scalar multiplication commutes with direct sums. -/
theorem mk_smul (s : finset ι) (c : R) (x) : mk M s (c • x) = c • mk M s x :=
(lmk R ι M s).map_smul c x
/-- Scalar multiplication commutes with the inclusion of each component into the direct sum. -/
theorem of_smul (i : ι) (c : R) (x) : of M i (c • x) = c • of M i x :=
(lof R ι M i).map_smul c x
variables {R}
lemma support_smul [Π (i : ι) (x : M i), decidable (x ≠ 0)]
(c : R) (v : ⨁ i, M i) : (c • v).support ⊆ v.support := dfinsupp.support_smul _ _
variables {N : Type u₁} [add_comm_monoid N] [module R N]
variables (φ : Π i, M i →ₗ[R] N)
variables (R ι N φ)
/-- The linear map constructed using the universal property of the coproduct. -/
def to_module : (⨁ i, M i) →ₗ[R] N :=
dfinsupp.lsum ℕ φ
/-- Coproducts in the categories of modules and additive monoids commute with the forgetful functor
from modules to additive monoids. -/
lemma coe_to_module_eq_coe_to_add_monoid :
(to_module R ι N φ : (⨁ i, M i) → N) = to_add_monoid (λ i, (φ i).to_add_monoid_hom) :=
rfl
variables {ι N φ}
/-- The map constructed using the universal property gives back the original maps when
restricted to each component. -/
@[simp] lemma to_module_lof (i) (x : M i) : to_module R ι N φ (lof R ι M i x) = φ i x :=
to_add_monoid_of (λ i, (φ i).to_add_monoid_hom) i x
variables (ψ : (⨁ i, M i) →ₗ[R] N)
/-- Every linear map from a direct sum agrees with the one obtained by applying
the universal property to each of its components. -/
theorem to_module.unique (f : ⨁ i, M i) : ψ f = to_module R ι N (λ i, ψ.comp $ lof R ι M i) f :=
to_add_monoid.unique ψ.to_add_monoid_hom f
variables {ψ} {ψ' : (⨁ i, M i) →ₗ[R] N}
/-- Two `linear_map`s out of a direct sum are equal if they agree on the generators.
See note [partially-applied ext lemmas]. -/
@[ext]
theorem linear_map_ext ⦃ψ ψ' : (⨁ i, M i) →ₗ[R] N⦄
(H : ∀ i, ψ.comp (lof R ι M i) = ψ'.comp (lof R ι M i)) : ψ = ψ' :=
dfinsupp.lhom_ext' H
/--
The inclusion of a subset of the direct summands
into a larger subset of the direct summands, as a linear map.
-/
def lset_to_set (S T : set ι) (H : S ⊆ T) :
(⨁ (i : S), M i) →ₗ[R] (⨁ (i : T), M i) :=
to_module R _ _ $ λ i, lof R T (λ (i : subtype T), M i) ⟨i, H i.prop⟩
omit dec_ι
variables (ι M)
/-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence
between `⨁ i, M i` and `Π i, M i`. -/
@[simps apply] def linear_equiv_fun_on_fintype [fintype ι] :
(⨁ i, M i) ≃ₗ[R] (Π i, M i) :=
{ to_fun := coe_fn,
map_add' := λ f g, by { ext, simp only [add_apply, pi.add_apply] },
map_smul' := λ c f, by { ext, simp only [dfinsupp.coe_smul, ring_hom.id_apply] },
.. dfinsupp.equiv_fun_on_fintype }
variables {ι M}
@[simp] lemma linear_equiv_fun_on_fintype_lof [fintype ι] [decidable_eq ι] (i : ι) (m : M i) :
(linear_equiv_fun_on_fintype R ι M) (lof R ι M i m) = pi.single i m :=
begin
ext a,
change (dfinsupp.equiv_fun_on_fintype (lof R ι M i m)) a = _,
convert _root_.congr_fun (dfinsupp.equiv_fun_on_fintype_single i m) a,
end
@[simp] lemma linear_equiv_fun_on_fintype_symm_single [fintype ι] [decidable_eq ι]
(i : ι) (m : M i) :
(linear_equiv_fun_on_fintype R ι M).symm (pi.single i m) = lof R ι M i m :=
begin
ext a,
change (dfinsupp.equiv_fun_on_fintype.symm (pi.single i m)) a = _,
rw (dfinsupp.equiv_fun_on_fintype_symm_single i m),
refl
end
@[simp] lemma linear_equiv_fun_on_fintype_symm_coe [fintype ι] (f : ⨁ i, M i) :
(linear_equiv_fun_on_fintype R ι M).symm f = f :=
by { ext, simp [linear_equiv_fun_on_fintype], }
/-- The natural linear equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/
protected def lid (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [module R M]
[unique ι] :
(⨁ (_ : ι), M) ≃ₗ[R] M :=
{ .. direct_sum.id M ι,
.. to_module R ι M (λ i, linear_map.id) }
variables (ι M)
/-- The projection map onto one component, as a linear map. -/
def component (i : ι) : (⨁ i, M i) →ₗ[R] M i :=
dfinsupp.lapply i
variables {ι M}
lemma apply_eq_component (f : ⨁ i, M i) (i : ι) :
f i = component R ι M i f := rfl
@[ext] lemma ext {f g : ⨁ i, M i}
(h : ∀ i, component R ι M i f = component R ι M i g) : f = g :=
dfinsupp.ext h
lemma ext_iff {f g : ⨁ i, M i} : f = g ↔
∀ i, component R ι M i f = component R ι M i g :=
⟨λ h _, by rw h, ext R⟩
include dec_ι
@[simp] lemma lof_apply (i : ι) (b : M i) : ((lof R ι M i) b) i = b :=
dfinsupp.single_eq_same
@[simp] lemma component.lof_self (i : ι) (b : M i) :
component R ι M i ((lof R ι M i) b) = b :=
lof_apply R i b
lemma component.of (i j : ι) (b : M j) :
component R ι M i ((lof R ι M j) b) =
if h : j = i then eq.rec_on h b else 0 :=
dfinsupp.single_apply
omit dec_ι
section congr_left
variables {κ : Type*}
/--Reindexing terms of a direct sum is linear.-/
def lequiv_congr_left (h : ι ≃ κ) : (⨁ i, M i) ≃ₗ[R] ⨁ k, M (h.symm k) :=
{ map_smul' := dfinsupp.comap_domain'_smul _ _,
..equiv_congr_left h }
@[simp] lemma lequiv_congr_left_apply (h : ι ≃ κ) (f : ⨁ i, M i) (k : κ) :
lequiv_congr_left R h f k = f (h.symm k) := equiv_congr_left_apply _ _ _
end congr_left
section sigma
variables {α : ι → Type u} {δ : Π i, α i → Type w}
variables [Π i j, add_comm_monoid (δ i j)] [Π i j, module R (δ i j)]
/--`curry` as a linear map.-/
noncomputable def sigma_lcurry : (⨁ (i : Σ i, _), δ i.1 i.2) →ₗ[R] ⨁ i j, δ i j :=
{ map_smul' := λ r, by convert (@dfinsupp.sigma_curry_smul _ _ _ δ _ _ _ r),
..sigma_curry }
@[simp] lemma sigma_lcurry_apply (f : ⨁ (i : Σ i, _), δ i.1 i.2) (i : ι) (j : α i) :
sigma_lcurry R f i j = f ⟨i, j⟩ := sigma_curry_apply f i j
/--`uncurry` as a linear map.-/
noncomputable def sigma_luncurry : (⨁ i j, δ i j) →ₗ[R] ⨁ (i : Σ i, _), δ i.1 i.2 :=
{ map_smul' := dfinsupp.sigma_uncurry_smul,
..sigma_uncurry }
@[simp] lemma sigma_luncurry_apply (f : ⨁ i j, δ i j) (i : ι) (j : α i) :
sigma_luncurry R f ⟨i, j⟩ = f i j := sigma_uncurry_apply f i j
/--`curry_equiv` as a linear equiv.-/
noncomputable def sigma_lcurry_equiv : (⨁ (i : Σ i, _), δ i.1 i.2) ≃ₗ[R] ⨁ i j, δ i j :=
{ ..sigma_curry_equiv, ..sigma_lcurry R }
end sigma
section option
variables {α : option ι → Type w} [Π i, add_comm_monoid (α i)] [Π i, module R (α i)]
include dec_ι
/--Linear isomorphism obtained by separating the term of index `none` of a direct sum over
`option ι`.-/
@[simps] noncomputable def lequiv_prod_direct_sum : (⨁ i, α i) ≃ₗ[R] α none × ⨁ i, α (some i) :=
{ map_smul' := dfinsupp.equiv_prod_dfinsupp_smul,
..add_equiv_prod_direct_sum }
end option
end general
section submodule
section semiring
variables {R : Type u} [semiring R]
variables {ι : Type v} [dec_ι : decidable_eq ι]
include dec_ι
variables {M : Type*} [add_comm_monoid M] [module R M]
variables (A : ι → submodule R M)
/-- The canonical embedding from `⨁ i, A i` to `M` where `A` is a collection of `submodule R M`
indexed by `ι`-/
def submodule_coe : (⨁ i, A i) →ₗ[R] M := to_module R ι M (λ i, (A i).subtype)
@[simp] lemma submodule_coe_of (i : ι) (x : A i) : submodule_coe A (of (λ i, A i) i x) = x :=
to_add_monoid_of _ _ _
lemma coe_of_submodule_apply (i j : ι) (x : A i) :
(direct_sum.of _ i x j : M) = if i = j then x else 0 :=
begin
obtain rfl | h := decidable.eq_or_ne i j,
{ rw [direct_sum.of_eq_same, if_pos rfl], },
{ rw [direct_sum.of_eq_of_ne _ _ _ _ h, if_neg h, submodule.coe_zero], },
end
/-- The `direct_sum` formed by a collection of `submodule`s of `M` is said to be internal if the
canonical map `(⨁ i, A i) →ₗ[R] M` is bijective.
For the alternate statement in terms of independence and spanning, see
`direct_sum.submodule_is_internal_iff_independent_and_supr_eq_top`. -/
def submodule_is_internal : Prop := function.bijective (submodule_coe A)
lemma submodule_is_internal.to_add_submonoid :
submodule_is_internal A ↔ add_submonoid_is_internal (λ i, (A i).to_add_submonoid) :=
iff.rfl
variables {A}
/-- If a direct sum of submodules is internal then the submodules span the module. -/
lemma submodule_is_internal.supr_eq_top (h : submodule_is_internal A) : supr A = ⊤ :=
begin
rw [submodule.supr_eq_range_dfinsupp_lsum, linear_map.range_eq_top],
exact function.bijective.surjective h,
end
/-- If a direct sum of submodules is internal then the submodules are independent. -/
lemma submodule_is_internal.independent (h : submodule_is_internal A) :
complete_lattice.independent A :=
complete_lattice.independent_of_dfinsupp_lsum_injective _ h.injective
/-- Given an internal direct sum decomposition of a module `M`, and a basis for each of the
components of the direct sum, the disjoint union of these bases is a basis for `M`. -/
noncomputable def submodule_is_internal.collected_basis
(h : submodule_is_internal A) {α : ι → Type*} (v : Π i, basis (α i) R (A i)) :
basis (Σ i, α i) R M :=
{ repr := (linear_equiv.of_bijective _ h.injective h.surjective).symm ≪≫ₗ
(dfinsupp.map_range.linear_equiv (λ i, (v i).repr)) ≪≫ₗ
(sigma_finsupp_lequiv_dfinsupp R).symm }
@[simp] lemma submodule_is_internal.collected_basis_coe
(h : submodule_is_internal A) {α : ι → Type*} (v : Π i, basis (α i) R (A i)) :
⇑(h.collected_basis v) = λ a : Σ i, (α i), ↑(v a.1 a.2) :=
begin
funext a,
simp only [submodule_is_internal.collected_basis, to_module, submodule_coe,
add_equiv.to_fun_eq_coe, basis.coe_of_repr, basis.repr_symm_apply, dfinsupp.lsum_apply_apply,
dfinsupp.map_range.linear_equiv_apply, dfinsupp.map_range.linear_equiv_symm,
dfinsupp.map_range_single, finsupp.total_single, linear_equiv.of_bijective_apply,
linear_equiv.symm_symm, linear_equiv.symm_trans_apply, one_smul,
sigma_finsupp_add_equiv_dfinsupp_apply, sigma_finsupp_equiv_dfinsupp_single,
sigma_finsupp_lequiv_dfinsupp_apply],
convert dfinsupp.sum_add_hom_single (λ i, (A i).subtype.to_add_monoid_hom) a.1 (v a.1 a.2),
end
lemma submodule_is_internal.collected_basis_mem
(h : submodule_is_internal A) {α : ι → Type*} (v : Π i, basis (α i) R (A i)) (a : Σ i, α i) :
h.collected_basis v a ∈ A a.1 :=
by simp
/-- When indexed by only two distinct elements, `direct_sum.submodule_is_internal` implies
the two submodules are complementary. Over a `ring R`, this is true as an iff, as
`direct_sum.submodule_is_internal_iff_is_compl`. --/
lemma submodule_is_internal.is_compl {A : ι → submodule R M} {i j : ι} (hij : i ≠ j)
(h : (set.univ : set ι) = {i, j}) (hi : submodule_is_internal A) : is_compl (A i) (A j) :=
⟨hi.independent.pairwise_disjoint _ _ hij, eq.le $ hi.supr_eq_top.symm.trans $
by rw [←Sup_pair, supr, ←set.image_univ, h, set.image_insert_eq, set.image_singleton]⟩
end semiring
section ring
variables {R : Type u} [ring R]
variables {ι : Type v} [dec_ι : decidable_eq ι]
include dec_ι
variables {M : Type*} [add_comm_group M] [module R M]
lemma submodule_is_internal.to_add_subgroup (A : ι → submodule R M) :
submodule_is_internal A ↔ add_subgroup_is_internal (λ i, (A i).to_add_subgroup) :=
iff.rfl
/-- Note that this is not generally true for `[semiring R]`; see
`complete_lattice.independent.dfinsupp_lsum_injective` for details. -/
lemma submodule_is_internal_of_independent_of_supr_eq_top {A : ι → submodule R M}
(hi : complete_lattice.independent A) (hs : supr A = ⊤) : submodule_is_internal A :=
⟨hi.dfinsupp_lsum_injective, linear_map.range_eq_top.1 $
(submodule.supr_eq_range_dfinsupp_lsum _).symm.trans hs⟩
/-- `iff` version of `direct_sum.submodule_is_internal_of_independent_of_supr_eq_top`,
`direct_sum.submodule_is_internal.independent`, and `direct_sum.submodule_is_internal.supr_eq_top`.
-/
lemma submodule_is_internal_iff_independent_and_supr_eq_top (A : ι → submodule R M) :
submodule_is_internal A ↔ complete_lattice.independent A ∧ supr A = ⊤ :=
⟨λ i, ⟨i.independent, i.supr_eq_top⟩,
and.rec submodule_is_internal_of_independent_of_supr_eq_top⟩
/-- If a collection of submodules has just two indices, `i` and `j`, then
`direct_sum.submodule_is_internal` is equivalent to `is_compl`. -/
lemma submodule_is_internal_iff_is_compl (A : ι → submodule R M) {i j : ι} (hij : i ≠ j)
(h : (set.univ : set ι) = {i, j}) :
submodule_is_internal A ↔ is_compl (A i) (A j) :=
begin
have : ∀ k, k = i ∨ k = j := λ k, by simpa using set.ext_iff.mp h k,
rw [submodule_is_internal_iff_independent_and_supr_eq_top,
supr, ←set.image_univ, h, set.image_insert_eq, set.image_singleton, Sup_pair,
complete_lattice.independent_pair hij this],
exact ⟨λ ⟨hd, ht⟩, ⟨hd, ht.ge⟩, λ ⟨hd, ht⟩, ⟨hd, eq_top_iff.mpr ht⟩⟩,
end
/-! Now copy the lemmas for subgroup and submonoids. -/
lemma add_submonoid_is_internal.independent {M : Type*} [add_comm_monoid M]
{A : ι → add_submonoid M} (h : add_submonoid_is_internal A) :
complete_lattice.independent A :=
complete_lattice.independent_of_dfinsupp_sum_add_hom_injective _ h.injective
lemma add_subgroup_is_internal.independent {M : Type*} [add_comm_group M]
{A : ι → add_subgroup M} (h : add_subgroup_is_internal A) :
complete_lattice.independent A :=
complete_lattice.independent_of_dfinsupp_sum_add_hom_injective' _ h.injective
end ring
end submodule
end direct_sum
|
9af16685e1b238ea1df002b496407ac216a4b1b3 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/linear_recurrence.lean | be9b92321b59b4880d911297fdf8e0947c02f439 | [
"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 | 8,195 | lean | /-
Copyright (c) 2020 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import data.polynomial.eval
import linear_algebra.dimension
/-!
# Linear recurrence
Informally, a "linear recurrence" is an assertion of the form
`∀ n : ℕ, u (n + d) = a 0 * u n + a 1 * u (n+1) + ... + a (d-1) * u (n+d-1)`,
where `u` is a sequence, `d` is the *order* of the recurrence and the `a i`
are its *coefficients*.
In this file, we define the structure `linear_recurrence` so that
`linear_recurrence.mk d a` represents the above relation, and we call
a sequence `u` which verifies it a *solution* of the linear recurrence.
We prove a few basic lemmas about this concept, such as :
* the space of solutions is a submodule of `(ℕ → α)` (i.e a vector space if `α`
is a field)
* the function that maps a solution `u` to its first `d` terms builds a `linear_equiv`
between the solution space and `fin d → α`, aka `α ^ d`. As a consequence, two
solutions are equal if and only if their first `d` terms are equals.
* a geometric sequence `q ^ n` is solution iff `q` is a root of a particular polynomial,
which we call the *characteristic polynomial* of the recurrence
Of course, although we can inductively generate solutions (cf `mk_sol`), the
interesting part would be to determinate closed-forms for the solutions.
This is currently *not implemented*, as we are waiting for definition and
properties of eigenvalues and eigenvectors.
-/
noncomputable theory
open finset
open_locale big_operators polynomial
/-- A "linear recurrence relation" over a commutative semiring is given by its
order `n` and `n` coefficients. -/
structure linear_recurrence (α : Type*) [comm_semiring α] := (order : ℕ) (coeffs : fin order → α)
instance (α : Type*) [comm_semiring α] : inhabited (linear_recurrence α) :=
⟨⟨0, default⟩⟩
namespace linear_recurrence
section comm_semiring
variables {α : Type*} [comm_semiring α] (E : linear_recurrence α)
/-- We say that a sequence `u` is solution of `linear_recurrence order coeffs` when we have
`u (n + order) = ∑ i : fin order, coeffs i * u (n + i)` for any `n`. -/
def is_solution (u : ℕ → α) :=
∀ n, u (n + E.order) = ∑ i, E.coeffs i * u (n + i)
/-- A solution of a `linear_recurrence` which satisfies certain initial conditions.
We will prove this is the only such solution. -/
def mk_sol (init : fin E.order → α) : ℕ → α
| n := if h : n < E.order then init ⟨n, h⟩ else
∑ k : fin E.order,
have n - E.order + k < n :=
begin
rw [add_comm, ← add_tsub_assoc_of_le (not_lt.mp h), tsub_lt_iff_left],
{ exact add_lt_add_right k.is_lt n },
{ convert add_le_add (zero_le (k : ℕ)) (not_lt.mp h),
simp only [zero_add] }
end,
E.coeffs k * mk_sol (n - E.order + k)
/-- `E.mk_sol` indeed gives solutions to `E`. -/
lemma is_sol_mk_sol (init : fin E.order → α) : E.is_solution (E.mk_sol init) :=
λ n, by rw mk_sol; simp
/-- `E.mk_sol init`'s first `E.order` terms are `init`. -/
lemma mk_sol_eq_init (init : fin E.order → α) : ∀ n : fin E.order, E.mk_sol init n = init n :=
λ n, by { rw mk_sol, simp only [n.is_lt, dif_pos, fin.mk_coe, fin.eta] }
/-- If `u` is a solution to `E` and `init` designates its first `E.order` values,
then `∀ n, u n = E.mk_sol init n`. -/
lemma eq_mk_of_is_sol_of_eq_init {u : ℕ → α} {init : fin E.order → α}
(h : E.is_solution u) (heq : ∀ n : fin E.order, u n = init n) :
∀ n, u n = E.mk_sol init n
| n := if h' : n < E.order
then by rw mk_sol; simp only [h', dif_pos]; exact_mod_cast heq ⟨n, h'⟩
else begin
rw [mk_sol, ← tsub_add_cancel_of_le (le_of_not_lt h'), h (n-E.order)],
simp [h'],
congr' with k,
exact have wf : n - E.order + k < n :=
begin
rw [add_comm, ← add_tsub_assoc_of_le (not_lt.mp h'), tsub_lt_iff_left],
{ exact add_lt_add_right k.is_lt n },
{ convert add_le_add (zero_le (k : ℕ)) (not_lt.mp h'),
simp only [zero_add] }
end,
by rw eq_mk_of_is_sol_of_eq_init
end
/-- If `u` is a solution to `E` and `init` designates its first `E.order` values,
then `u = E.mk_sol init`. This proves that `E.mk_sol init` is the only solution
of `E` whose first `E.order` values are given by `init`. -/
lemma eq_mk_of_is_sol_of_eq_init' {u : ℕ → α} {init : fin E.order → α}
(h : E.is_solution u) (heq : ∀ n : fin E.order, u n = init n) : u = E.mk_sol init :=
funext (E.eq_mk_of_is_sol_of_eq_init h heq)
/-- The space of solutions of `E`, as a `submodule` over `α` of the module `ℕ → α`. -/
def sol_space : submodule α (ℕ → α) :=
{ carrier := {u | E.is_solution u},
zero_mem' := λ n, by simp,
add_mem' := λ u v hu hv n, by simp [mul_add, sum_add_distrib, hu n, hv n],
smul_mem' := λ a u hu n, by simp [hu n, mul_sum]; congr'; ext; ac_refl }
/-- Defining property of the solution space : `u` is a solution
iff it belongs to the solution space. -/
lemma is_sol_iff_mem_sol_space (u : ℕ → α) : E.is_solution u ↔ u ∈ E.sol_space :=
iff.rfl
/-- The function that maps a solution `u` of `E` to its first
`E.order` terms as a `linear_equiv`. -/
def to_init :
E.sol_space ≃ₗ[α] (fin E.order → α) :=
{ to_fun := λ u x, (u : ℕ → α) x,
map_add' := λ u v, by { ext, simp },
map_smul' := λ a u, by { ext, simp },
inv_fun := λ u, ⟨E.mk_sol u, E.is_sol_mk_sol u⟩,
left_inv := λ u, by ext n; symmetry; apply E.eq_mk_of_is_sol_of_eq_init u.2; intros k; refl,
right_inv := λ u, function.funext_iff.mpr (λ n, E.mk_sol_eq_init u n) }
/-- Two solutions are equal iff they are equal on `range E.order`. -/
lemma sol_eq_of_eq_init (u v : ℕ → α) (hu : E.is_solution u) (hv : E.is_solution v) :
u = v ↔ set.eq_on u v ↑(range E.order) :=
begin
refine iff.intro (λ h x hx, h ▸ rfl) _,
intro h,
set u' : ↥(E.sol_space) := ⟨u, hu⟩,
set v' : ↥(E.sol_space) := ⟨v, hv⟩,
change u'.val = v'.val,
suffices h' : u' = v', from h' ▸ rfl,
rw [← E.to_init.to_equiv.apply_eq_iff_eq, linear_equiv.coe_to_equiv],
ext x,
exact_mod_cast h (mem_range.mpr x.2)
end
/-! `E.tuple_succ` maps `![s₀, s₁, ..., sₙ]` to `![s₁, ..., sₙ, ∑ (E.coeffs i) * sᵢ]`,
where `n := E.order`. This operation is quite useful for determining closed-form
solutions of `E`. -/
/-- `E.tuple_succ` maps `![s₀, s₁, ..., sₙ]` to `![s₁, ..., sₙ, ∑ (E.coeffs i) * sᵢ]`,
where `n := E.order`. -/
def tuple_succ : (fin E.order → α) →ₗ[α] (fin E.order → α) :=
{ to_fun := λ X i, if h : (i : ℕ) + 1 < E.order then X ⟨i+1, h⟩ else (∑ i, E.coeffs i * X i),
map_add' := λ x y,
begin
ext i,
split_ifs ; simp [h, mul_add, sum_add_distrib],
end,
map_smul' := λ x y,
begin
ext i,
split_ifs ; simp [h, mul_sum],
exact sum_congr rfl (λ x _, by ac_refl),
end }
end comm_semiring
section field
variables {α : Type*} [field α] (E : linear_recurrence α)
/-- The dimension of `E.sol_space` is `E.order`. -/
lemma sol_space_dim : module.rank α E.sol_space = E.order :=
@dim_fin_fun α _ E.order ▸ E.to_init.dim_eq
end field
section comm_ring
variables {α : Type*} [comm_ring α] (E : linear_recurrence α)
/-- The characteristic polynomial of `E` is
`X ^ E.order - ∑ i : fin E.order, (E.coeffs i) * X ^ i`. -/
def char_poly : α[X] :=
polynomial.monomial E.order 1 - (∑ i : fin E.order, polynomial.monomial i (E.coeffs i))
/-- The geometric sequence `q^n` is a solution of `E` iff
`q` is a root of `E`'s characteristic polynomial. -/
lemma geom_sol_iff_root_char_poly (q : α) : E.is_solution (λ n, q^n) ↔ E.char_poly.is_root q :=
begin
rw [char_poly, polynomial.is_root.def, polynomial.eval],
simp only [polynomial.eval₂_finset_sum, one_mul,
ring_hom.id_apply, polynomial.eval₂_monomial, polynomial.eval₂_sub],
split,
{ intro h,
simpa [sub_eq_zero] using h 0 },
{ intros h n,
simp only [pow_add, sub_eq_zero.mp h, mul_sum],
exact sum_congr rfl (λ _ _, by ring) }
end
end comm_ring
end linear_recurrence
|
cb715e6a071e2519a470a1dd8b0e1d4a7dc09251 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /stage0/src/Lean/Meta/DiscrTree.lean | e969c711fb86a0071a54072108603b03143ee31a | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,752 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Basic
import Lean.Meta.FunInfo
import Lean.Meta.InferType
namespace Lean.Meta.DiscrTree
/-
(Imperfect) discrimination trees.
We use a hybrid representation.
- A `PersistentHashMap` for the root node which usually contains many children.
- A sorted array of key/node pairs for inner nodes.
The edges are labeled by keys:
- Constant names (and arity). Universe levels are ignored.
- Free variables (and arity). Thus, an entry in the discrimination tree
may reference hypotheses from the local context.
- Literals
- Star/Wildcard. We use them to represent metavariables and terms
we want to ignore. We ignore implicit arguments and proofs.
- Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc).
We reduce terms using `TransparencyMode.reducible`. Thus, all reducible
definitions in an expression `e` are unfolded before we insert it into the
discrimination tree.
Recall that projections from classes are **NOT** reducible.
For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x`
and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys
respctively
```
⟨Add.add, 4⟩, *, *, *, *
⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩
```
That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`.
We say the `Add.add` applications are the de-facto canonical forms in
the metaprogramming framework.
Moreover, it is the metaprogrammer's responsibility to re-pack applications such as
`Nat.add a b` into `Add.add Nat inst a b`.
Remark: we store the arity in the keys
1- To be able to implement the "skip" operation when retrieving "candidate"
unifiers.
2- Distinguish partial applications `f a`, `f a b`, and `f a b c`.
-/
def Key.ctorIdx : Key → Nat
| Key.star => 0
| Key.other => 1
| Key.lit _ => 2
| Key.fvar _ _ => 3
| Key.const _ _ => 4
def Key.lt : Key → Key → Bool
| Key.lit v₁, Key.lit v₂ => v₁ < v₂
| Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)
| Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂)
| k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx
instance : HasLess Key := ⟨fun a b => Key.lt a b⟩
instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b))
def Key.format : Key → Format
| Key.star => "*"
| Key.other => "◾"
| Key.lit (Literal.natVal v) => fmt v
| Key.lit (Literal.strVal v) => repr v
| Key.const k _ => fmt k
| Key.fvar k _ => fmt k
instance : ToFormat Key := ⟨Key.format⟩
def Key.arity : Key → Nat
| Key.const _ a => a
| Key.fvar _ a => a
| _ => 0
instance {α} : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩
def empty {α} : DiscrTree α := { root := {} }
/- The discrimination tree ignores implicit arguments and proofs.
We use the following auxiliary id as a "mark". -/
private def tmpMVarId : MVarId := `_discr_tree_tmp
private def tmpStar := mkMVar tmpMVarId
instance {α} : Inhabited (DiscrTree α) := ⟨{}⟩
/--
Return true iff the argument should be treated as a "wildcard" by the discrimination tree.
- We ignore proofs because of proof irrelevance. It doesn't make sense to try to
index their structure.
- We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical.
Moreover, we may have many definitionally equal terms floating around.
Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`.
- We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them,
and may not even understand why some simplification rule is not firing.
However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`,
where `Nat` is an implicit argument. Thus, we would add the path
```
Decidable -> Eq -> * -> * -> * -> [Nat.decEq]
```
to the discrimination tree IF we ignored the implict `Nat` argument.
This would be BAD since **ALL** decidable equality instances would be in the same path.
So, we index implicit arguments if they are types.
This setting seems sensible for simplification lemmas such as:
```
forall (x y : Unit), (@Eq Unit x y) = true
```
If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate
simplification lemma for any equality in our goal.
Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation,
and `ignoreArg` would return true for any term of the form `noIndexing t`.
-/
private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool :=
if h : i < infos.size then
let info := infos.get ⟨i, h⟩
if info.instImplicit then
pure true
else if info.implicit then
not <$> isType a
else
isProof a
else
isProof a
private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr)
| i, Expr.app f a _, todo => do
if (← ignoreArg a i infos) then
pushArgsAux infos (i-1) f (todo.push tmpStar)
else
pushArgsAux infos (i-1) f (todo.push a)
| _, _, todo => pure todo
private partial def whnfEta (e : Expr) : MetaM Expr := do
let e ← whnf e
match e.etaExpandedStrict? with
| some e => whnfEta e
| none => pure e
/-
TODO: add a parameter (wildcardConsts : NameSet) to `DiscrTree.insert`.
Then, `DiscrTree` users may control which symbols should be treated as wildcards.
Different `DiscrTree` users may populate this set using, for example, attributes. -/
private def shouldAddAsStar (constName : Name) : Bool :=
constName == `Nat.zero || constName == `Nat.succ || constName == `Nat.add || constName == `Add.add
private def pushArgs (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do
let e ← whnfEta e
let fn := e.getAppFn
let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do
let info ← getFunInfoNArgs fn nargs
let todo ← pushArgsAux info.paramInfo (nargs-1) e todo
pure (k, todo)
match fn with
| Expr.lit v _ => pure (Key.lit v, todo)
| Expr.const c _ _ =>
if shouldAddAsStar c then
pure (Key.star, todo)
else
let nargs := e.getAppNumArgs
push (Key.const c nargs) nargs
| Expr.fvar fvarId _ =>
let nargs := e.getAppNumArgs
push (Key.fvar fvarId nargs) nargs
| Expr.mvar mvarId _ =>
if mvarId == tmpMVarId then
-- We use `tmp to mark implicit arguments and proofs
pure (Key.star, todo)
else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
pure (Key.other, todo)
else
pure (Key.star, todo)
| _ => pure (Key.other, todo)
partial def mkPathAux (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do
if todo.isEmpty then
pure keys
else
let e := todo.back
let todo := todo.pop
let (k, todo) ← pushArgs todo e
mkPathAux todo (keys.push k)
private def initCapacity := 8
def mkPath (e : Expr) : MetaM (Array Key) :=
withReducible do
let todo : Array Expr := Array.mkEmpty initCapacity
let keys : Array Key := Array.mkEmpty initCapacity
mkPathAux (todo.push e) keys
private partial def createNodes {α} (keys : Array Key) (v : α) (i : Nat) : Trie α :=
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let c := createNodes keys v (i+1)
Trie.node #[] #[(k, c)]
else
Trie.node #[v] #[]
private def insertVal {α} [BEq α] (vs : Array α) (v : α) : Array α :=
if vs.contains v then vs else vs.push v
private partial def insertAux {α} [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α
| i, Trie.node vs cs =>
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let c := Id.run $ cs.binInsertM
(fun a b => a.1 < b.1)
(fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing
(fun _ => let c := createNodes keys v (i+1); (k, c))
(k, arbitrary _)
Trie.node vs c
else
Trie.node (insertVal vs v) cs
def insertCore {α} [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α :=
if keys.isEmpty then panic! "invalid key sequence"
else
let k := keys[0]
match d.root.find? k with
| none =>
let c := createNodes keys v 1
{ root := d.root.insert k c }
| some c =>
let c := insertAux keys v 1 c
{ root := d.root.insert k c }
def insert {α} [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do
let keys ← mkPath e
pure $ d.insertCore keys v
partial def Trie.format {α} [ToFormat α] : Trie α → Format
| Trie.node vs cs => Format.group $ Format.paren $
"node" ++ (if vs.isEmpty then Format.nil else " " ++ fmt vs)
++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (fmt k ++ " => " ++ format c))
instance {α} [ToFormat α] : ToFormat (Trie α) := ⟨Trie.format⟩
partial def format {α} [ToFormat α] (d : DiscrTree α) : Format :=
let (_, r) := d.root.foldl
(fun (p : Bool × Format) k c =>
(false, p.2 ++ (if p.1 == true then Format.nil else Format.line) ++ Format.paren (fmt k ++ " => " ++ fmt c))) -- TODO: fix p.1 == true
(true, Format.nil)
Format.group r
instance {α} [ToFormat α] : ToFormat (DiscrTree α) := ⟨format⟩
private def getKeyArgs (e : Expr) (isMatch? : Bool) : MetaM (Key × Array Expr) := do
let e ← whnfEta e
match e.getAppFn with
| Expr.lit v _ => pure (Key.lit v, #[])
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
pure (Key.const c nargs, e.getAppRevArgs)
| Expr.fvar fvarId _ =>
let nargs := e.getAppNumArgs
pure (Key.fvar fvarId nargs, e.getAppRevArgs)
| Expr.mvar mvarId _ =>
if isMatch? then
pure (Key.other, #[])
else do
let ctx ← read
if ctx.config.isDefEqStuckEx then
/-
When the configuration flag `isDefEqStuckEx` is set to true,
we want `isDefEq` to throw an exception whenever it tries to assign
a read-only metavariable.
This feature is useful for type class resolution where
we may want to notify the caller that the TC problem may be solveable
later after it assigns `?m`.
The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`.
That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)`
where `?m` is a read-only metavariable, and the discrimination tree contains the keys
`HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as
a regular metavariable here, otherwise we return the empty set of candidates.
This is incorrect because it is equivalent to saying that there is no solution even if
the caller assigns `?m` and try again. -/
pure (Key.star, #[])
else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then
pure (Key.other, #[])
else
pure (Key.star, #[])
| _ => pure (Key.other, #[])
private abbrev getMatchKeyArgs (e : Expr) : MetaM (Key × Array Expr) :=
getKeyArgs e true
private abbrev getUnifyKeyArgs (e : Expr) : MetaM (Key × Array Expr) :=
getKeyArgs e false
private partial def getMatchAux {α} : Array Expr → Trie α → Array α → MetaM (Array α)
| todo, Trie.node vs cs, result =>
if todo.isEmpty then pure $ result ++ vs
else if cs.isEmpty then pure result
else do
let e := todo.back
let todo := todo.pop
let first := cs[0] /- Recall that `Key.star` is the minimal key -/
let (k, args) ← getMatchKeyArgs e
/- We must always visit `Key.star` edges since they are wildcards.
Thus, `todo` is not used linearly when there is `Key.star` edge
and there is an edge for `k` and `k != Key.star`. -/
let visitStarChild (result : Array α) : MetaM (Array α) :=
if first.1 == Key.star then getMatchAux todo first.2 result else pure result
match k with
| Key.star => visitStarChild result
| _ =>
match cs.binSearch (k, arbitrary _) (fun a b => a.1 < b.1) with
| none => visitStarChild result
| some c =>
let result ← visitStarChild result
getMatchAux (todo ++ args) c.2 result
private def getStarResult {α} (d : DiscrTree α) : Array α :=
let result : Array α := Array.mkEmpty initCapacity
match d.root.find? Key.star with
| none => result
| some (Trie.node vs _) => result ++ vs
def getMatch {α} (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withReducible do
let result := getStarResult d
let (k, args) ← getMatchKeyArgs e
match k with
| Key.star => pure result
| _ =>
match d.root.find? k with
| none => pure result
| some c => getMatchAux args c result
private partial def getUnifyAux {α} : Nat → Array Expr → Trie α → (Array α) → MetaM (Array α)
| skip+1, todo, Trie.node vs cs, result =>
if cs.isEmpty then pure result
else cs.foldlM (fun result ⟨k, c⟩ => getUnifyAux (skip + k.arity) todo c result) result
| 0, todo, Trie.node vs cs, result => do
if todo.isEmpty then pure (result ++ vs)
else if cs.isEmpty then pure result
else
let e := todo.back
let todo := todo.pop
let (k, args) ← getUnifyKeyArgs e
match k with
| Key.star => cs.foldlM (fun result ⟨k, c⟩ => getUnifyAux k.arity todo c result) result
| _ =>
let first := cs[0]
let visitStarChild (result : Array α) : MetaM (Array α) :=
if first.1 == Key.star then getUnifyAux 0 todo first.2 result else pure result
match cs.binSearch (k, arbitrary _) (fun a b => a.1 < b.1) with
| none => visitStarChild result
| some c =>
let result ← visitStarChild result
getUnifyAux 0 (todo ++ args) c.2 result
def getUnify {α} (d : DiscrTree α) (e : Expr) : MetaM (Array α) :=
withReducible do
let (k, args) ← getUnifyKeyArgs e
match k with
| Key.star => d.root.foldlM (fun result k c => getUnifyAux k.arity #[] c result) #[]
| _ =>
let result := getStarResult d
match d.root.find? k with
| none => pure result
| some c => getUnifyAux 0 args c result
end Lean.Meta.DiscrTree
|
051e3563aee2202ef6f19e402059b20928bd36af | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/valid/mathd-algebra-77.lean | a8f115cc3b837de9cf8da27101a9027f230d8dc8 | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 347 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.real.basic
example (a b : ℝ) (f : ℝ → ℝ) (h₀ : a ≠ 0 ∧ b ≠ 0) (h₁ : ∀ x, f x = x^2 + a * x + b) (h₂ : f a = 0) (h₃ : f b = 0) : a = 1 ∧ b = -2 :=
begin
sorry
end
|
37de08b622060645d73a02f0976f17166e23fdd4 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/normed_space/ball_action.lean | 99295ec561d813f61bebf8bd0bb84fd1c088b026 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 8,003 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Heather Macbeth
-/
import analysis.normed.field.unit_ball
import analysis.normed_space.basic
/-!
# Multiplicative actions of/on balls and spheres
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Let `E` be a normed vector space over a normed field `𝕜`. In this file we define the following
multiplicative actions.
- The closed unit ball in `𝕜` acts on open balls and closed balls centered at `0` in `E`.
- The unit sphere in `𝕜` acts on open balls, closed balls, and spheres centered at `0` in `E`.
-/
open metric set
variables {𝕜 𝕜' E : Type*} [normed_field 𝕜] [normed_field 𝕜']
[seminormed_add_comm_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] {r : ℝ}
section closed_ball
instance mul_action_closed_ball_ball : mul_action (closed_ball (0 : 𝕜) 1) (ball (0 : E) r) :=
{ smul := λ c x, ⟨(c : 𝕜) • x, mem_ball_zero_iff.2 $
by simpa only [norm_smul, one_mul]
using mul_lt_mul' (mem_closed_ball_zero_iff.1 c.2) (mem_ball_zero_iff.1 x.2)
(norm_nonneg _) one_pos⟩,
one_smul := λ x, subtype.ext $ one_smul 𝕜 _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_closed_ball_ball :
has_continuous_smul (closed_ball (0 : 𝕜) 1) (ball (0 : E) r) :=
⟨(continuous_subtype_val.fst'.smul continuous_subtype_val.snd').subtype_mk _⟩
instance mul_action_closed_ball_closed_ball :
mul_action (closed_ball (0 : 𝕜) 1) (closed_ball (0 : E) r) :=
{ smul := λ c x, ⟨(c : 𝕜) • x, mem_closed_ball_zero_iff.2 $
by simpa only [norm_smul, one_mul]
using mul_le_mul (mem_closed_ball_zero_iff.1 c.2) (mem_closed_ball_zero_iff.1 x.2)
(norm_nonneg _) zero_le_one⟩,
one_smul := λ x, subtype.ext $ one_smul 𝕜 _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_closed_ball_closed_ball :
has_continuous_smul (closed_ball (0 : 𝕜) 1) (closed_ball (0 : E) r) :=
⟨(continuous_subtype_val.fst'.smul continuous_subtype_val.snd').subtype_mk _⟩
end closed_ball
section sphere
instance mul_action_sphere_ball : mul_action (sphere (0 : 𝕜) 1) (ball (0 : E) r) :=
{ smul := λ c x, inclusion sphere_subset_closed_ball c • x,
one_smul := λ x, subtype.ext $ one_smul _ _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_sphere_ball :
has_continuous_smul (sphere (0 : 𝕜) 1) (ball (0 : E) r) :=
⟨(continuous_subtype_val.fst'.smul continuous_subtype_val.snd').subtype_mk _⟩
instance mul_action_sphere_closed_ball : mul_action (sphere (0 : 𝕜) 1) (closed_ball (0 : E) r) :=
{ smul := λ c x, inclusion sphere_subset_closed_ball c • x,
one_smul := λ x, subtype.ext $ one_smul _ _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_sphere_closed_ball :
has_continuous_smul (sphere (0 : 𝕜) 1) (closed_ball (0 : E) r) :=
⟨(continuous_subtype_val.fst'.smul continuous_subtype_val.snd').subtype_mk _⟩
instance mul_action_sphere_sphere : mul_action (sphere (0 : 𝕜) 1) (sphere (0 : E) r) :=
{ smul := λ c x, ⟨(c : 𝕜) • x, mem_sphere_zero_iff_norm.2 $
by rw [norm_smul, mem_sphere_zero_iff_norm.1 c.coe_prop, mem_sphere_zero_iff_norm.1 x.coe_prop,
one_mul]⟩,
one_smul := λ x, subtype.ext $ one_smul _ _,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul _ _ _ }
instance has_continuous_smul_sphere_sphere :
has_continuous_smul (sphere (0 : 𝕜) 1) (sphere (0 : E) r) :=
⟨(continuous_subtype_val.fst'.smul continuous_subtype_val.snd').subtype_mk _⟩
end sphere
section is_scalar_tower
variables [normed_algebra 𝕜 𝕜'] [is_scalar_tower 𝕜 𝕜' E]
instance is_scalar_tower_closed_ball_closed_ball_closed_ball :
is_scalar_tower (closed_ball (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_closed_ball_closed_ball_ball :
is_scalar_tower (closed_ball (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_closed_ball_closed_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_closed_ball_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_sphere_closed_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_sphere_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_sphere_sphere :
is_scalar_tower (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (sphere (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : E)⟩
instance is_scalar_tower_sphere_ball_ball :
is_scalar_tower (sphere (0 : 𝕜) 1) (ball (0 : 𝕜') 1) (ball (0 : 𝕜') 1) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : 𝕜')⟩
instance is_scalar_tower_closed_ball_ball_ball :
is_scalar_tower (closed_ball (0 : 𝕜) 1) (ball (0 : 𝕜') 1) (ball (0 : 𝕜') 1) :=
⟨λ a b c, subtype.ext $ smul_assoc (a : 𝕜) (b : 𝕜') (c : 𝕜')⟩
end is_scalar_tower
section smul_comm_class
variables [smul_comm_class 𝕜 𝕜' E]
instance smul_comm_class_closed_ball_closed_ball_closed_ball :
smul_comm_class (closed_ball (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_closed_ball_closed_ball_ball :
smul_comm_class (closed_ball (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_closed_ball_closed_ball :
smul_comm_class (sphere (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_closed_ball_ball :
smul_comm_class (sphere (0 : 𝕜) 1) (closed_ball (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_ball_ball [normed_algebra 𝕜 𝕜'] :
smul_comm_class (sphere (0 : 𝕜) 1) (ball (0 : 𝕜') 1) (ball (0 : 𝕜') 1) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : 𝕜')⟩
instance smul_comm_class_sphere_sphere_closed_ball :
smul_comm_class (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (closed_ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_sphere_ball :
smul_comm_class (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (ball (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
instance smul_comm_class_sphere_sphere_sphere :
smul_comm_class (sphere (0 : 𝕜) 1) (sphere (0 : 𝕜') 1) (sphere (0 : E) r) :=
⟨λ a b c, subtype.ext $ smul_comm (a : 𝕜) (b : 𝕜') (c : E)⟩
end smul_comm_class
variables (𝕜) [char_zero 𝕜]
lemma ne_neg_of_mem_sphere {r : ℝ} (hr : r ≠ 0) (x : sphere (0:E) r) : x ≠ - x :=
λ h, ne_zero_of_mem_sphere hr x ((self_eq_neg 𝕜 _).mp (by { conv_lhs {rw h}, simp }))
lemma ne_neg_of_mem_unit_sphere (x : sphere (0:E) 1) : x ≠ - x :=
ne_neg_of_mem_sphere 𝕜 one_ne_zero x
|
98fb2393f2680672cab69e128220a554872b6db7 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/geometry/manifold/partition_of_unity.lean | f24d750963758810ae06a817ccced66d55756374 | [
"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 | 9,060 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import topology.paracompact
import topology.shrinking_lemma
import geometry.manifold.bump_function
/-!
# Smooth partition of unity
In this file we define `smooth_bump_covering`, a structure that will be used to construct a smooth
partition of unity. Namely, a `smooth_bump_covering` of a set `s : set M` is a collection of
`smooth_bump_function`s such that their supports is a locally finite family of sets, and for each
point `x ∈ s` there exists a bump function `f i` in the collection such that `f i =ᶠ[𝓝 x] 1`. This
structure is the main building block in the construction of a smooth partition of unity (see TODO),
and can be used instead of a partition of unity in some proofs.
We say that `f : smooth_bump_covering I s` is *subordinate* to a map `U : M → set M` if for each
index `i`, we have `closure (support (f i)) ⊆ U (f i).c`. This notion is a bit more general than
being subordinate to an open covering of `M`, because we make no assumption about the way `U x`
depends on `x`.
We prove that on a smooth finitely dimensional real manifold with `σ`-compact Hausdorff topology,
for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering I s`
subordinate to `U`.
## TODO
* Construct a smooth partition of unity.
* Deduce some corollaries from existence of a smooth partition of unity.
- Prove that for any disjoint closed sets `s`, `t` there exists a smooth function `f` suth that
`f` equals zero on `s` and `f` equals one on `t`.
- Build a framework for to transfer local definitions to global using partition of unity and use
it to define, e.g., the integral of a differential form over a manifold.
## Tags
manifold, smooth bump function, partition of unity
-/
universes uE uF uH uM
variables
{E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E]
{H : Type uH} [topological_space H] (I : model_with_corners ℝ E H)
{M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
open function filter finite_dimensional set
open_locale topological_space manifold classical filter big_operators
noncomputable theory
/-!
### Covering by supports of smooth bump functions
In this section we define `smooth_bump_covering I s` to be a collection of `smooth_bump_function`s
such that their supports is a locally finite family of sets and for each `x ∈ s` some function `f i`
from the collection is equal to `1` in a neighborhood of `x`. A covering of this type is useful to
construct a smooth partition of unity and can be used instead of a partition of unity in some
proofs.
We prove that on a smooth finite dimensional real manifold with `σ`-compact Hausdorff topology,
for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering I s`
subordinate to `U`. Then we use this fact to prove a version of the Whitney embedding theorem: any
compact real manifold can be embedded into `ℝ^n` for large enough `n`.
-/
/-- We say that a collection of `smooth_bump_function`s is a `smooth_bump_covering` of a set `s` if
* `(f i).c ∈ s` for all `i`;
* the family `λ i, support (f i)` is locally finite;
* for each point `x ∈ s` there exists `i` such that `f i =ᶠ[𝓝 x] 1`;
in other words, `x` belongs to the interior of `{y | f i y = 1}`;
If `M` is a finite dimensional real manifold which is a sigma-compact Hausdorff topological space,
then a choice of `smooth_bump_covering` is available as `smooth_bump_covering.choice_set`, see also
`smooth_bump_covering.choice` for the case `s = univ` and
`smooth_bump_covering.exists_is_subordinate` for a lemma providing a covering subordinate to a given
`U : M → set M`.
This covering can be used, e.g., to construct a partition of unity and to prove the weak
Whitney embedding theorem. -/
structure smooth_bump_covering (s : set M) :=
(ι : Type uM)
(c : ι → M)
(to_fun : Π i, smooth_bump_function I (c i))
(c_mem' : ∀ i, c i ∈ s)
(locally_finite' : locally_finite (λ i, support (to_fun i)))
(eventually_eq_one' : ∀ x ∈ s, ∃ i, to_fun i =ᶠ[𝓝 x] 1)
namespace smooth_bump_covering
variables {s : set M} {U : M → set M} (fs : smooth_bump_covering I s) {I}
instance : has_coe_to_fun (smooth_bump_covering I s) := ⟨_, to_fun⟩
@[simp] lemma coe_mk (ι : Type uM) (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i))
(h₁ h₂ h₃) : ⇑(mk ι c to_fun h₁ h₂ h₃ : smooth_bump_covering I s) = to_fun :=
rfl
/--
We say that `f : smooth_bump_covering I s` is *subordinate* to a map `U : M → set M` if for each
index `i`, we have `closure (support (f i)) ⊆ U (f i).c`. This notion is a bit more general than
being subordinate to an open covering of `M`, because we make no assumption about the way `U x`
depends on `x`.
-/
def is_subordinate {s : set M} (f : smooth_bump_covering I s) (U : M → set M) :=
∀ i, closure (support $ f i) ⊆ U (f.c i)
variable (I)
/-- Let `M` be a smooth manifold with corners modelled on a finite dimensional real vector space.
Suppose also that `M` is a Hausdorff `σ`-compact topological space. Let `s` be a closed set
in `M` and `U : M → set M` be a collection of sets such that `U x ∈ 𝓝 x` for every `x ∈ s`.
Then there exists a smooth bump covering of `s` that is subordinate to `U`. -/
lemma exists_is_subordinate [t2_space M] [sigma_compact_space M] (hs : is_closed s)
(hU : ∀ x ∈ s, U x ∈ 𝓝 x) :
∃ f : smooth_bump_covering I s, f.is_subordinate U :=
begin
-- First we deduce some missing instances
haveI : locally_compact_space H := I.locally_compact,
haveI : locally_compact_space M := charted_space.locally_compact H,
haveI : normal_space M := normal_of_paracompact_t2,
-- Next we choose a covering by supports of smooth bump functions
have hB := λ x hx, smooth_bump_function.nhds_basis_support I (hU x hx),
rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis_set hs hB
with ⟨ι, c, f, hf, hsub', hfin⟩, choose hcs hfU using hf,
/- Then we use the shrinking lemma to get a covering by smaller open -/
rcases exists_subset_Union_closed_subset hs (λ i, (f i).open_support)
(λ x hx, hfin.point_finite x) hsub' with ⟨V, hsV, hVc, hVf⟩,
choose r hrR hr using λ i, (f i).exists_r_pos_lt_subset_ball (hVc i) (hVf i),
refine ⟨⟨ι, c, λ i, (f i).update_r (r i) (hrR i), hcs, _, λ x hx, _⟩, λ i, _⟩,
{ simpa only [smooth_bump_function.support_update_r] },
{ refine (mem_Union.1 $ hsV hx).imp (λ i hi, _),
exact ((f i).update_r _ _).eventually_eq_one_of_dist_lt
((f i).support_subset_source $ hVf _ hi) (hr i hi).2 },
{ simpa only [coe_mk, smooth_bump_function.support_update_r] using hfU i }
end
/-- Choice of a covering of a closed set `s` by supports of smooth bump functions. -/
def choice_set [t2_space M] [sigma_compact_space M] (s : set M) (hs : is_closed s) :
smooth_bump_covering I s :=
(exists_is_subordinate I hs (λ x hx, univ_mem_sets)).some
instance [t2_space M] [sigma_compact_space M] {s : set M} [is_closed s] :
inhabited (smooth_bump_covering I s) :=
⟨choice_set I s ‹_›⟩
variable (M)
/-- Choice of a covering of a manifold by supports of smooth bump functions. -/
def choice [t2_space M] [sigma_compact_space M] :
smooth_bump_covering I (univ : set M) :=
choice_set I univ is_closed_univ
variables {I M}
protected lemma locally_finite : locally_finite (λ i, support (fs i)) := fs.locally_finite'
protected lemma point_finite (x : M) : {i | fs i x ≠ 0}.finite :=
fs.locally_finite.point_finite x
lemma mem_chart_at_source_of_eq_one {i : fs.ι} {x : M} (h : fs i x = 1) :
x ∈ (chart_at H (fs.c i)).source :=
(fs i).support_subset_source $ by simp [h]
lemma mem_ext_chart_at_source_of_eq_one {i : fs.ι} {x : M} (h : fs i x = 1) :
x ∈ (ext_chart_at I (fs.c i)).source :=
by { rw ext_chart_at_source, exact fs.mem_chart_at_source_of_eq_one h }
/-- Index of a bump function such that `fs i =ᶠ[𝓝 x] 1`. -/
def ind (x : M) (hx : x ∈ s) : fs.ι := (fs.eventually_eq_one' x hx).some
lemma eventually_eq_one (x : M) (hx : x ∈ s) : fs (fs.ind x hx) =ᶠ[𝓝 x] 1 :=
(fs.eventually_eq_one' x hx).some_spec
lemma apply_ind (x : M) (hx : x ∈ s) : fs (fs.ind x hx) x = 1 :=
(fs.eventually_eq_one x hx).eq_of_nhds
lemma mem_support_ind (x : M) (hx : x ∈ s) : x ∈ support (fs $ fs.ind x hx) :=
by simp [fs.apply_ind x hx]
lemma mem_chart_at_ind_source (x : M) (hx : x ∈ s) :
x ∈ (chart_at H (fs.c (fs.ind x hx))).source :=
fs.mem_chart_at_source_of_eq_one (fs.apply_ind x hx)
lemma mem_ext_chart_at_ind_source (x : M) (hx : x ∈ s) :
x ∈ (ext_chart_at I (fs.c (fs.ind x hx))).source :=
fs.mem_ext_chart_at_source_of_eq_one (fs.apply_ind x hx)
instance fintype_ι_of_compact [compact_space M] : fintype fs.ι :=
fs.locally_finite.fintype_of_compact $ λ i, (fs i).nonempty_support
end smooth_bump_covering
|
74cb7cff4e17ef52dfa04c80b1e38aca4ff92b6a | 99b5e6372af1f404777312358869f95be7de84a3 | /src/hott/types/arrow.lean | 740446cbf69739814b27985b52b3b6f74ddaba01 | [
"Apache-2.0"
] | permissive | forked-from-1kasper/hott3 | 8fa064ab5e8c9d6752a783d74ab226ddc5b5232a | 2db24de7a361a7793b0eae4ca5c3fd4d4a0fc691 | refs/heads/master | 1,584,867,131,028 | 1,530,766,841,000 | 1,530,766,841,000 | 139,797,034 | 0 | 0 | Apache-2.0 | 1,530,766,961,000 | 1,530,766,961,000 | null | UTF-8 | Lean | false | false | 5,888 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Ported from Coq HoTT
Theorems about arrow types (function spaces)
-/
import hott.types.pi
universe u
hott_theory
namespace hott
open eq equiv is_equiv funext pi is_trunc unit
namespace pi
variables {A : Type _} {A' : Type _} {B : Type _} {B' : Type _} {C : A → B → Type _} {D : A → Type _}
{a a' a'' : A} {b b' b'' : B} {f g : A → B} {d : D a} {d' : D a'}
-- all lemmas here are special cases of the ones for pi-types
/- Functorial action -/
variables (f0 : A' → A) (f1 : B → B')
@[hott] def arrow_functor : (A → B) → (A' → B') := pi_functor f0 (λa, f1)
/- Equivalences -/
@[hott] def is_equiv_arrow_functor
[H0 : is_equiv f0] [H1 : is_equiv f1] : is_equiv (arrow_functor f0 f1) :=
is_equiv_pi_functor f0 (λa, f1)
@[hott] def arrow_equiv_arrow_rev (f0 : A' ≃ A) (f1 : B ≃ B')
: (A → B) ≃ (A' → B') :=
equiv.mk _ (is_equiv_arrow_functor f0 f1)
@[hott] def arrow_equiv_arrow (f0 : A ≃ A') (f1 : B ≃ B') : (A → B) ≃ (A' → B') :=
arrow_equiv_arrow_rev (equiv.symm f0) f1
variable (A)
@[hott] def arrow_equiv_arrow_right (f1 : B ≃ B') : (A → B) ≃ (A → B') :=
arrow_equiv_arrow_rev equiv.rfl f1
variables {A} (B)
@[hott] def arrow_equiv_arrow_left_rev (f0 : A' ≃ A) : (A → B) ≃ (A' → B) :=
arrow_equiv_arrow_rev f0 equiv.rfl
@[hott] def arrow_equiv_arrow_left (f0 : A ≃ A') : (A → B) ≃ (A' → B) :=
arrow_equiv_arrow f0 equiv.rfl
variables {B}
@[hott] def arrow_equiv_arrow_right' (f1 : A → (B ≃ B')) : (A → B) ≃ (A → B') :=
pi_equiv_pi_right f1
/- Equivalence if one of the types is contractible -/
variables (A B)
-- we prove this separately from pi_equiv_of_is_contr_left,
-- because the underlying inverse function is simpler here (no transport needed)
@[hott] def arrow_equiv_of_is_contr_left [H : is_contr A] : (A → B) ≃ B :=
begin
fapply equiv.MK,
{ intro f, exact f (center A)},
{ intros b a, exact b},
{ intro b, reflexivity},
{ intro f, apply eq_of_homotopy, intro a, exact ap f (is_prop.elim _ _)}
end
@[hott] def arrow_equiv_of_is_contr_right [H : is_contr B] : (A → B) ≃ unit :=
pi_equiv_of_is_contr_right _
/- Interaction with other type constructors -/
-- most of these are in the file of the other type constructor
@[hott] def arrow_empty_left : (empty → B) ≃ unit :=
pi_empty_left _
@[hott] def arrow_unit_left : (unit → B) ≃ B :=
arrow_equiv_of_is_contr_left _ _
@[hott] def arrow_unit_right : (A → unit) ≃ unit :=
arrow_equiv_of_is_contr_right _ _
variables {A B}
/- Transport -/
@[hott] def arrow_transport {B C : A → Type _} (p : a = a') (f : B a → C a)
: (transport (λa, B a → C a) p f) ~ (λb, p ▸ f (p⁻¹ ▸ b)) :=
eq.rec_on p (λx, idp)
/- Pathovers -/
@[hott] def arrow_pathover {B C : A → Type _} {f : B a → C a} {g : B a' → C a'} {p : a = a'}
(r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p; λa, B a → C a] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
exact eq_of_pathover_idp (r b b idpo),
end
@[hott] def arrow_pathover_left {B C : A → Type _} {f : B a → C a} {g : B a' → C a'} {p : a = a'}
(r : Π(b : B a), f b =[p] g (p ▸ b)) : f =[p; λa, B a → C a] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
exact eq_of_pathover_idp (r b),
end
@[hott] def arrow_pathover_right {B C : A → Type _} {f : B a → C a} {g : B a' → C a'} {p : a = a'}
(r : Π(b' : B a'), f (p⁻¹ ▸ b') =[p] g b') : f =[p; λa, B a → C a] g :=
begin
induction p, apply pathover_idp_of_eq,
apply eq_of_homotopy, hintro b,
exact eq_of_pathover_idp (r b),
end
@[hott] def arrow_pathover_constant_left {B : Type _} {C : A → Type _} {f : B → C a} {g : B → C a'}
{p : a = a'} (r : Π(b : B), f b =[p] g b) : f =[p; λa, B → C a] g :=
pi_pathover_constant r
@[hott] def arrow_pathover_constant_right' {B : A → Type _} {C : Type _}
{f : B a → C} {g : B a' → C} {p : a = a'}
(r : Π⦃b : B a⦄ ⦃b' : B a'⦄ (q : b =[p] b'), f b = g b') : f =[p; λa, B a → C] g :=
arrow_pathover (λb b' q, pathover_of_eq p (r q))
@[hott] def arrow_pathover_constant_right {B : A → Type _} {C : Type _} {f : B a → C}
{g : B a' → C} {p : a = a'} (r : Π(b : B a), f b = g (p ▸ b)) : f =[p; λa, B a → C] g :=
arrow_pathover_left (λb, pathover_of_eq p (r b))
@[hott] def arrow_pathover_constant_right_rev {A : Type _} {B : A → Type _} {C : Type _} {a a' : A}
{f : B a → C} {g : B a' → C} {p : a = a'} (r : Π(b : B a'), f (p⁻¹ ▸ b) = g b) : f =[p; λa, B a → C] g :=
arrow_pathover_right (λb, pathover_of_eq p (r b))
/- a @[hott] lemma used for the flattening lemma, and is also used in the colimits file -/
@[hott] def apo11_arrow_pathover_constant_right {f : D a → A'} {g : D a' → A'} {p : a = a'}
{q : d =[p] d'} (r : Π(d : D a), f d = g (p ▸ d))
: apo11_constant_right (arrow_pathover_constant_right r) q = r d ⬝ ap g (tr_eq_of_pathover q)
:=
begin
induction q,
eapply homotopy.rec_on r, clear r, intro r, dsimp at r, induction r,
dsimp [apd10, arrow_pathover_constant_right, arrow_pathover_left, pathover_of_eq, eq_of_pathover_idp, tr_eq_of_pathover],
rwr [eq_of_homotopy_idp]
end
/-
The fact that the arrow type preserves truncation level is a direct consequence
of the fact that pi's preserve truncation level
-/
@[hott] def is_trunc_arrow (B : Type _) (n : ℕ₋₂) [H : is_trunc n B] : is_trunc n (A → B) :=
by apply_instance
end pi
end hott |
389f529b67b4730d16194865c4bc5417b941b23f | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/linear_algebra/eigenspace.lean | daa17c7a583f30aa04bb399a4b1a46289019daeb | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 29,088 | lean | /-
Copyright (c) 2020 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp
-/
import linear_algebra.charpoly.basic
import linear_algebra.finsupp
import linear_algebra.matrix.to_lin
import algebra.algebra.spectrum
import order.hom.basic
/-!
# Eigenvectors and eigenvalues
This file defines eigenspaces, eigenvalues, and eigenvalues, as well as their generalized
counterparts. We follow Axler's approach [axler2015] because it allows us to derive many properties
without choosing a basis and without using matrices.
An eigenspace of a linear map `f` for a scalar `μ` is the kernel of the map `(f - μ • id)`. The
nonzero elements of an eigenspace are eigenvectors `x`. They have the property `f x = μ • x`. If
there are eigenvectors for a scalar `μ`, the scalar `μ` is called an eigenvalue.
There is no consensus in the literature whether `0` is an eigenvector. Our definition of
`has_eigenvector` permits only nonzero vectors. For an eigenvector `x` that may also be `0`, we
write `x ∈ f.eigenspace μ`.
A generalized eigenspace of a linear map `f` for a natural number `k` and a scalar `μ` is the kernel
of the map `(f - μ • id) ^ k`. The nonzero elements of a generalized eigenspace are generalized
eigenvectors `x`. If there are generalized eigenvectors for a natural number `k` and a scalar `μ`,
the scalar `μ` is called a generalized eigenvalue.
## References
* [Sheldon Axler, *Linear Algebra Done Right*][axler2015]
* https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors
## Tags
eigenspace, eigenvector, eigenvalue, eigen
-/
universes u v w
namespace module
namespace End
open module principal_ideal_ring polynomial finite_dimensional
variables {K R : Type v} {V M : Type w}
[comm_ring R] [add_comm_group M] [module R M] [field K] [add_comm_group V] [module K V]
/-- The submodule `eigenspace f μ` for a linear map `f` and a scalar `μ` consists of all vectors `x`
such that `f x = μ • x`. (Def 5.36 of [axler2015])-/
def eigenspace (f : End R M) (μ : R) : submodule R M :=
(f - algebra_map R (End R M) μ).ker
/-- A nonzero element of an eigenspace is an eigenvector. (Def 5.7 of [axler2015]) -/
def has_eigenvector (f : End R M) (μ : R) (x : M) : Prop :=
x ∈ eigenspace f μ ∧ x ≠ 0
/-- A scalar `μ` is an eigenvalue for a linear map `f` if there are nonzero vectors `x`
such that `f x = μ • x`. (Def 5.5 of [axler2015]) -/
def has_eigenvalue (f : End R M) (a : R) : Prop :=
eigenspace f a ≠ ⊥
/-- The eigenvalues of the endomorphism `f`, as a subtype of `R`. -/
def eigenvalues (f : End R M) : Type* := {μ : R // f.has_eigenvalue μ}
instance (f : End R M) : has_coe f.eigenvalues R := coe_subtype
lemma has_eigenvalue_of_has_eigenvector {f : End R M} {μ : R} {x : M} (h : has_eigenvector f μ x) :
has_eigenvalue f μ :=
begin
rw [has_eigenvalue, submodule.ne_bot_iff],
use x, exact h,
end
lemma mem_eigenspace_iff {f : End R M} {μ : R} {x : M} : x ∈ eigenspace f μ ↔ f x = μ • x :=
by rw [eigenspace, linear_map.mem_ker, linear_map.sub_apply, algebra_map_End_apply,
sub_eq_zero]
lemma has_eigenvector.apply_eq_smul {f : End R M} {μ : R} {x : M} (hx : f.has_eigenvector μ x) :
f x = μ • x :=
mem_eigenspace_iff.mp hx.1
lemma has_eigenvalue.exists_has_eigenvector {f : End R M} {μ : R} (hμ : f.has_eigenvalue μ) :
∃ v, f.has_eigenvector μ v :=
submodule.exists_mem_ne_zero_of_ne_bot hμ
lemma mem_spectrum_of_has_eigenvalue {f : End R M} {μ : R} (hμ : has_eigenvalue f μ) :
μ ∈ spectrum R f :=
begin
refine spectrum.mem_iff.mpr (λ h_unit, _),
set f' := linear_map.general_linear_group.to_linear_equiv h_unit.unit,
rcases hμ.exists_has_eigenvector with ⟨v, hv⟩,
refine hv.2 ((linear_map.ker_eq_bot'.mp f'.ker) v (_ : μ • v - f v = 0)),
rw [hv.apply_eq_smul, sub_self]
end
lemma has_eigenvalue_iff_mem_spectrum [finite_dimensional K V] {f : End K V} {μ : K} :
f.has_eigenvalue μ ↔ μ ∈ spectrum K f :=
iff.intro mem_spectrum_of_has_eigenvalue
(λ h, by rwa [spectrum.mem_iff, is_unit.sub_iff, linear_map.is_unit_iff_ker_eq_bot] at h)
lemma eigenspace_div (f : End K V) (a b : K) (hb : b ≠ 0) :
eigenspace f (a / b) = (b • f - algebra_map K (End K V) a).ker :=
calc
eigenspace f (a / b) = eigenspace f (b⁻¹ * a) : by { rw [div_eq_mul_inv, mul_comm] }
... = (f - (b⁻¹ * a) • linear_map.id).ker : rfl
... = (f - b⁻¹ • a • linear_map.id).ker : by rw smul_smul
... = (f - b⁻¹ • algebra_map K (End K V) a).ker : rfl
... = (b • (f - b⁻¹ • algebra_map K (End K V) a)).ker : by rw linear_map.ker_smul _ b hb
... = (b • f - algebra_map K (End K V) a).ker : by rw [smul_sub, smul_inv_smul₀ hb]
lemma eigenspace_aeval_polynomial_degree_1
(f : End K V) (q : polynomial K) (hq : degree q = 1) :
eigenspace f (- q.coeff 0 / q.leading_coeff) = (aeval f q).ker :=
calc
eigenspace f (- q.coeff 0 / q.leading_coeff)
= (q.leading_coeff • f - algebra_map K (End K V) (- q.coeff 0)).ker
: by { rw eigenspace_div, intro h, rw leading_coeff_eq_zero_iff_deg_eq_bot.1 h at hq, cases hq }
... = (aeval f (C q.leading_coeff * X + C (q.coeff 0))).ker
: by { rw [C_mul', aeval_def], simp [algebra_map, algebra.to_ring_hom], }
... = (aeval f q).ker
: by { congr, apply (eq_X_add_C_of_degree_eq_one hq).symm }
lemma ker_aeval_ring_hom'_unit_polynomial
(f : End K V) (c : (polynomial K)ˣ) :
(aeval f (c : polynomial K)).ker = ⊥ :=
begin
rw polynomial.eq_C_of_degree_eq_zero (degree_coe_units c),
simp only [aeval_def, eval₂_C],
apply ker_algebra_map_End,
apply coeff_coe_units_zero_ne_zero c
end
theorem aeval_apply_of_has_eigenvector {f : End K V}
{p : polynomial K} {μ : K} {x : V} (h : f.has_eigenvector μ x) :
aeval f p x = (p.eval μ) • x :=
begin
apply p.induction_on,
{ intro a, simp [module.algebra_map_End_apply] },
{ intros p q hp hq, simp [hp, hq, add_smul] },
{ intros n a hna,
rw [mul_comm, pow_succ, mul_assoc, alg_hom.map_mul, linear_map.mul_apply, mul_comm, hna],
simp [algebra_map_End_apply, mem_eigenspace_iff.1 h.1, smul_smul, mul_comm] }
end
section minpoly
theorem is_root_of_has_eigenvalue {f : End K V} {μ : K} (h : f.has_eigenvalue μ) :
(minpoly K f).is_root μ :=
begin
rcases (submodule.ne_bot_iff _).1 h with ⟨w, ⟨H, ne0⟩⟩,
refine or.resolve_right (smul_eq_zero.1 _) ne0,
simp [← aeval_apply_of_has_eigenvector ⟨H, ne0⟩, minpoly.aeval K f],
end
variables [finite_dimensional K V] (f : End K V)
variables {f} {μ : K}
theorem has_eigenvalue_of_is_root (h : (minpoly K f).is_root μ) :
f.has_eigenvalue μ :=
begin
cases dvd_iff_is_root.2 h with p hp,
rw [has_eigenvalue, eigenspace],
intro con,
cases (linear_map.is_unit_iff_ker_eq_bot _).2 con with u hu,
have p_ne_0 : p ≠ 0,
{ intro con,
apply minpoly.ne_zero f.is_integral,
rw [hp, con, mul_zero] },
have h_deg := minpoly.degree_le_of_ne_zero K f p_ne_0 _,
{ rw [hp, degree_mul, degree_X_sub_C, polynomial.degree_eq_nat_degree p_ne_0] at h_deg,
norm_cast at h_deg,
linarith, },
{ have h_aeval := minpoly.aeval K f,
revert h_aeval,
simp [hp, ← hu] },
end
theorem has_eigenvalue_iff_is_root :
f.has_eigenvalue μ ↔ (minpoly K f).is_root μ :=
⟨is_root_of_has_eigenvalue, has_eigenvalue_of_is_root⟩
/-- An endomorphism of a finite-dimensional vector space has finitely many eigenvalues. -/
noncomputable instance (f : End K V) : fintype f.eigenvalues :=
set.finite.fintype
begin
have h : minpoly K f ≠ 0 := minpoly.ne_zero f.is_integral,
convert (minpoly K f).root_set_finite K,
ext μ,
have : (μ ∈ {μ : K | f.eigenspace μ = ⊥ → false}) ↔ ¬f.eigenspace μ = ⊥ := by tauto,
convert rfl.mpr this,
simp [polynomial.root_set_def, polynomial.mem_roots h, ← has_eigenvalue_iff_is_root,
has_eigenvalue]
end
end minpoly
/-- Every linear operator on a vector space over an algebraically closed field has
an eigenvalue. -/
-- This is Lemma 5.21 of [axler2015], although we are no longer following that proof.
lemma exists_eigenvalue [is_alg_closed K] [finite_dimensional K V] [nontrivial V] (f : End K V) :
∃ (c : K), f.has_eigenvalue c :=
by { simp_rw has_eigenvalue_iff_mem_spectrum,
exact spectrum.nonempty_of_is_alg_closed_of_finite_dimensional K f }
noncomputable instance [is_alg_closed K] [finite_dimensional K V] [nontrivial V] (f : End K V) :
inhabited f.eigenvalues :=
⟨⟨f.exists_eigenvalue.some, f.exists_eigenvalue.some_spec⟩⟩
/-- The eigenspaces of a linear operator form an independent family of subspaces of `V`. That is,
any eigenspace has trivial intersection with the span of all the other eigenspaces. -/
lemma eigenspaces_independent (f : End K V) : complete_lattice.independent f.eigenspace :=
begin
classical,
-- Define an operation from `Π₀ μ : K, f.eigenspace μ`, the vector space of of finitely-supported
-- choices of an eigenvector from each eigenspace, to `V`, by sending a collection to its sum.
let S : @linear_map K K _ _ (ring_hom.id K) (Π₀ μ : K, f.eigenspace μ) V
(@dfinsupp.add_comm_monoid K (λ μ, f.eigenspace μ) _) _
(@dfinsupp.module K _ (λ μ, f.eigenspace μ) _ _ _) _ :=
@dfinsupp.lsum K K ℕ _ V _ _ _ _ _ _ _ _ _
(λ μ, (f.eigenspace μ).subtype),
-- We need to show that if a finitely-supported collection `l` of representatives of the
-- eigenspaces has sum `0`, then it itself is zero.
suffices : ∀ l : Π₀ μ, f.eigenspace μ, S l = 0 → l = 0,
{ rw complete_lattice.independent_iff_dfinsupp_lsum_injective,
change function.injective S,
rw ← @linear_map.ker_eq_bot K K (Π₀ μ, (f.eigenspace μ)) V _ _
(@dfinsupp.add_comm_group K (λ μ, f.eigenspace μ) _),
rw eq_bot_iff,
exact this },
intros l hl,
-- We apply induction on the finite set of eigenvalues from which `l` selects a nonzero
-- eigenvector, i.e. on the support of `l`.
induction h_l_support : l.support using finset.induction with μ₀ l_support' hμ₀ ih generalizing l,
-- If the support is empty, all coefficients are zero and we are done.
{ exact dfinsupp.support_eq_empty.1 h_l_support },
-- Now assume that the support of `l` contains at least one eigenvalue `μ₀`. We define a new
-- collection of representatives `l'` to apply the induction hypothesis on later. The collection
-- of representatives `l'` is derived from `l` by multiplying the coefficient of the eigenvector
-- with eigenvalue `μ` by `μ - μ₀`.
{ let l' := dfinsupp.map_range.linear_map
(λ μ, (μ - μ₀) • @linear_map.id K (f.eigenspace μ) _ _ _) l,
-- The support of `l'` is the support of `l` without `μ₀`.
have h_l_support' : l'.support = l_support',
{ have : l_support' = finset.erase l.support μ₀,
{ rw [h_l_support, finset.erase_insert hμ₀] },
rw this,
ext a,
have : ¬(a = μ₀ ∨ l a = 0) ↔ ¬a = μ₀ ∧ ¬l a = 0 := by tauto,
simp only [l', dfinsupp.map_range.linear_map_apply, dfinsupp.map_range_apply,
dfinsupp.mem_support_iff, finset.mem_erase, id.def, linear_map.id_coe,
linear_map.smul_apply, ne.def, smul_eq_zero, sub_eq_zero, this] },
-- The entries of `l'` add up to `0`.
have total_l' : S l' = 0,
{ let g := f - algebra_map K (End K V) μ₀,
let a : Π₀ μ : K, V := dfinsupp.map_range.linear_map (λ μ, (f.eigenspace μ).subtype) l,
calc S l'
= dfinsupp.lsum ℕ (λ μ, (f.eigenspace μ).subtype.comp ((μ - μ₀) • linear_map.id)) l : _
... = dfinsupp.lsum ℕ (λ μ, g.comp (f.eigenspace μ).subtype) l : _
... = dfinsupp.lsum ℕ (λ μ, g) a : _
... = g (dfinsupp.lsum ℕ (λ μ, (linear_map.id : V →ₗ[K] V)) a) : _
... = g (S l) : _
... = 0 : by rw [hl, g.map_zero],
{ rw dfinsupp.sum_map_range_index.linear_map },
{ congr,
ext μ v,
simp only [g, eq_self_iff_true, function.comp_app, id.def, linear_map.coe_comp,
linear_map.id_coe, linear_map.smul_apply, linear_map.sub_apply,
module.algebra_map_End_apply, sub_left_inj, sub_smul, submodule.coe_smul_of_tower,
submodule.coe_sub, submodule.subtype_apply, mem_eigenspace_iff.1 v.prop], },
{ rw dfinsupp.sum_map_range_index.linear_map },
{ simp only [dfinsupp.sum_add_hom_apply, linear_map.id_coe, linear_map.map_dfinsupp_sum,
id.def, linear_map.to_add_monoid_hom_coe, dfinsupp.lsum_apply_apply], },
{ congr,
simp only [S, a, dfinsupp.sum_map_range_index.linear_map, linear_map.id_comp] } },
-- Therefore, by the induction hypothesis, all entries of `l'` are zero.
have l'_eq_0 := ih l' total_l' h_l_support',
-- By the definition of `l'`, this means that `(μ - μ₀) • l μ = 0` for all `μ`.
have h_smul_eq_0 : ∀ μ, (μ - μ₀) • l μ = 0,
{ intro μ,
calc (μ - μ₀) • l μ = l' μ : by simp only [l', linear_map.id_coe, id.def,
linear_map.smul_apply, dfinsupp.map_range_apply, dfinsupp.map_range.linear_map_apply]
... = 0 : by { rw [l'_eq_0], refl } },
-- Thus, the eigenspace-representatives in `l` for all `μ ≠ μ₀` are `0`.
have h_lμ_eq_0 : ∀ μ : K, μ ≠ μ₀ → l μ = 0,
{ intros μ hμ,
apply or_iff_not_imp_left.1 (smul_eq_zero.1 (h_smul_eq_0 μ)),
rwa [sub_eq_zero] },
-- So if we sum over all these representatives, we obtain `0`.
have h_sum_l_support'_eq_0 : finset.sum l_support' (λ μ, (l μ : V)) = 0,
{ rw ←finset.sum_const_zero,
apply finset.sum_congr rfl,
intros μ hμ,
norm_cast,
rw h_lμ_eq_0,
intro h,
rw h at hμ,
contradiction },
-- The only potentially nonzero eigenspace-representative in `l` is the one corresponding to
-- `μ₀`. But since the overall sum is `0` by assumption, this representative must also be `0`.
have : l μ₀ = 0,
{ simp only [S, dfinsupp.lsum_apply_apply, dfinsupp.sum_add_hom_apply,
linear_map.to_add_monoid_hom_coe, dfinsupp.sum, h_l_support, submodule.subtype_apply,
submodule.coe_eq_zero, finset.sum_insert hμ₀, h_sum_l_support'_eq_0, add_zero] at hl,
exact_mod_cast hl },
-- Thus, all coefficients in `l` are `0`.
show l = 0,
{ ext μ,
by_cases h_cases : μ = μ₀,
{ rw h_cases,
exact_mod_cast this },
exact congr_arg (coe : _ → V) (h_lμ_eq_0 μ h_cases) }}
end
/-- Eigenvectors corresponding to distinct eigenvalues of a linear operator are linearly
independent. (Lemma 5.10 of [axler2015])
We use the eigenvalues as indexing set to ensure that there is only one eigenvector for each
eigenvalue in the image of `xs`. -/
lemma eigenvectors_linear_independent (f : End K V) (μs : set K) (xs : μs → V)
(h_eigenvec : ∀ μ : μs, f.has_eigenvector μ (xs μ)) :
linear_independent K xs :=
complete_lattice.independent.linear_independent _
(f.eigenspaces_independent.comp (coe : μs → K) subtype.coe_injective)
(λ μ, (h_eigenvec μ).1) (λ μ, (h_eigenvec μ).2)
/-- The generalized eigenspace for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the
kernel of `(f - μ • id) ^ k`. (Def 8.10 of [axler2015]). Furthermore, a generalized eigenspace for
some exponent `k` is contained in the generalized eigenspace for exponents larger than `k`. -/
def generalized_eigenspace (f : End R M) (μ : R) : ℕ →o submodule R M :=
{ to_fun := λ k, ((f - algebra_map R (End R M) μ) ^ k).ker,
monotone' := λ k m hm,
begin
simp only [← pow_sub_mul_pow _ hm],
exact linear_map.ker_le_ker_comp
((f - algebra_map R (End R M) μ) ^ k) ((f - algebra_map R (End R M) μ) ^ (m - k)),
end }
@[simp] lemma mem_generalized_eigenspace (f : End R M) (μ : R) (k : ℕ) (m : M) :
m ∈ f.generalized_eigenspace μ k ↔ ((f - μ • 1)^k) m = 0 :=
iff.rfl
/-- A nonzero element of a generalized eigenspace is a generalized eigenvector.
(Def 8.9 of [axler2015])-/
def has_generalized_eigenvector (f : End R M) (μ : R) (k : ℕ) (x : M) : Prop :=
x ≠ 0 ∧ x ∈ generalized_eigenspace f μ k
/-- A scalar `μ` is a generalized eigenvalue for a linear map `f` and an exponent `k ∈ ℕ` if there
are generalized eigenvectors for `f`, `k`, and `μ`. -/
def has_generalized_eigenvalue (f : End R M) (μ : R) (k : ℕ) : Prop :=
generalized_eigenspace f μ k ≠ ⊥
/-- The generalized eigenrange for a linear map `f`, a scalar `μ`, and an exponent `k ∈ ℕ` is the
range of `(f - μ • id) ^ k`. -/
def generalized_eigenrange (f : End R M) (μ : R) (k : ℕ) : submodule R M :=
((f - algebra_map R (End R M) μ) ^ k).range
/-- The exponent of a generalized eigenvalue is never 0. -/
lemma exp_ne_zero_of_has_generalized_eigenvalue {f : End R M} {μ : R} {k : ℕ}
(h : f.has_generalized_eigenvalue μ k) : k ≠ 0 :=
begin
rintro rfl,
exact h linear_map.ker_id
end
/-- The union of the kernels of `(f - μ • id) ^ k` over all `k`. -/
def maximal_generalized_eigenspace (f : End R M) (μ : R) : submodule R M :=
⨆ k, f.generalized_eigenspace μ k
lemma generalized_eigenspace_le_maximal (f : End R M) (μ : R) (k : ℕ) :
f.generalized_eigenspace μ k ≤ f.maximal_generalized_eigenspace μ :=
le_supr _ _
@[simp] lemma mem_maximal_generalized_eigenspace (f : End R M) (μ : R) (m : M) :
m ∈ f.maximal_generalized_eigenspace μ ↔ ∃ (k : ℕ), ((f - μ • 1)^k) m = 0 :=
by simp only [maximal_generalized_eigenspace, ← mem_generalized_eigenspace,
submodule.mem_supr_of_chain]
/-- If there exists a natural number `k` such that the kernel of `(f - μ • id) ^ k` is the
maximal generalized eigenspace, then this value is the least such `k`. If not, this value is not
meaningful. -/
noncomputable def maximal_generalized_eigenspace_index (f : End R M) (μ : R) :=
monotonic_sequence_limit_index (f.generalized_eigenspace μ)
/-- For an endomorphism of a Noetherian module, the maximal eigenspace is always of the form kernel
`(f - μ • id) ^ k` for some `k`. -/
lemma maximal_generalized_eigenspace_eq [h : is_noetherian R M] (f : End R M) (μ : R) :
maximal_generalized_eigenspace f μ =
f.generalized_eigenspace μ (maximal_generalized_eigenspace_index f μ) :=
begin
rw is_noetherian_iff_well_founded at h,
exact (well_founded.supr_eq_monotonic_sequence_limit h (f.generalized_eigenspace μ) : _),
end
/-- A generalized eigenvalue for some exponent `k` is also
a generalized eigenvalue for exponents larger than `k`. -/
lemma has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le
{f : End R M} {μ : R} {k : ℕ} {m : ℕ} (hm : k ≤ m) (hk : f.has_generalized_eigenvalue μ k) :
f.has_generalized_eigenvalue μ m :=
begin
unfold has_generalized_eigenvalue at *,
contrapose! hk,
rw [←le_bot_iff, ←hk],
exact (f.generalized_eigenspace μ).monotone hm,
end
/-- The eigenspace is a subspace of the generalized eigenspace. -/
lemma eigenspace_le_generalized_eigenspace {f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) :
f.eigenspace μ ≤ f.generalized_eigenspace μ k :=
(f.generalized_eigenspace μ).monotone (nat.succ_le_of_lt hk)
/-- All eigenvalues are generalized eigenvalues. -/
lemma has_generalized_eigenvalue_of_has_eigenvalue
{f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) (hμ : f.has_eigenvalue μ) :
f.has_generalized_eigenvalue μ k :=
begin
apply has_generalized_eigenvalue_of_has_generalized_eigenvalue_of_le hk,
rw [has_generalized_eigenvalue, generalized_eigenspace, order_hom.coe_fun_mk, pow_one],
exact hμ,
end
/-- All generalized eigenvalues are eigenvalues. -/
lemma has_eigenvalue_of_has_generalized_eigenvalue
{f : End R M} {μ : R} {k : ℕ} (hμ : f.has_generalized_eigenvalue μ k) :
f.has_eigenvalue μ :=
begin
intros contra, apply hμ,
erw linear_map.ker_eq_bot at ⊢ contra, rw linear_map.coe_pow,
exact function.injective.iterate contra k,
end
/-- Generalized eigenvalues are actually just eigenvalues. -/
@[simp] lemma has_generalized_eigenvalue_iff_has_eigenvalue
{f : End R M} {μ : R} {k : ℕ} (hk : 0 < k) :
f.has_generalized_eigenvalue μ k ↔ f.has_eigenvalue μ :=
⟨has_eigenvalue_of_has_generalized_eigenvalue, has_generalized_eigenvalue_of_has_eigenvalue hk⟩
/-- Every generalized eigenvector is a generalized eigenvector for exponent `finrank K V`.
(Lemma 8.11 of [axler2015]) -/
lemma generalized_eigenspace_le_generalized_eigenspace_finrank
[finite_dimensional K V] (f : End K V) (μ : K) (k : ℕ) :
f.generalized_eigenspace μ k ≤ f.generalized_eigenspace μ (finrank K V) :=
ker_pow_le_ker_pow_finrank _ _
/-- Generalized eigenspaces for exponents at least `finrank K V` are equal to each other. -/
lemma generalized_eigenspace_eq_generalized_eigenspace_finrank_of_le [finite_dimensional K V]
(f : End K V) (μ : K) {k : ℕ} (hk : finrank K V ≤ k) :
f.generalized_eigenspace μ k = f.generalized_eigenspace μ (finrank K V) :=
ker_pow_eq_ker_pow_finrank_of_le hk
/-- If `f` maps a subspace `p` into itself, then the generalized eigenspace of the restriction
of `f` to `p` is the part of the generalized eigenspace of `f` that lies in `p`. -/
lemma generalized_eigenspace_restrict
(f : End R M) (p : submodule R M) (k : ℕ) (μ : R) (hfp : ∀ (x : M), x ∈ p → f x ∈ p) :
generalized_eigenspace (linear_map.restrict f hfp) μ k =
submodule.comap p.subtype (f.generalized_eigenspace μ k) :=
begin
simp only [generalized_eigenspace, order_hom.coe_fun_mk, ← linear_map.ker_comp],
induction k with k ih,
{ rw [pow_zero, pow_zero, linear_map.one_eq_id],
apply (submodule.ker_subtype _).symm },
{ erw [pow_succ', pow_succ', linear_map.ker_comp, linear_map.ker_comp, ih,
← linear_map.ker_comp, linear_map.comp_assoc] },
end
/-- If `p` is an invariant submodule of an endomorphism `f`, then the `μ`-eigenspace of the
restriction of `f` to `p` is a submodule of the `μ`-eigenspace of `f`. -/
lemma eigenspace_restrict_le_eigenspace (f : End R M) {p : submodule R M}
(hfp : ∀ x ∈ p, f x ∈ p) (μ : R) :
(eigenspace (f.restrict hfp) μ).map p.subtype ≤ f.eigenspace μ :=
begin
rintros a ⟨x, hx, rfl⟩,
simp only [set_like.mem_coe, mem_eigenspace_iff, linear_map.restrict_apply] at hx ⊢,
exact congr_arg coe hx
end
/-- Generalized eigenrange and generalized eigenspace for exponent `finrank K V` are disjoint. -/
lemma generalized_eigenvec_disjoint_range_ker [finite_dimensional K V] (f : End K V) (μ : K) :
disjoint (f.generalized_eigenrange μ (finrank K V)) (f.generalized_eigenspace μ (finrank K V)) :=
begin
have h := calc
submodule.comap ((f - algebra_map _ _ μ) ^ finrank K V)
(f.generalized_eigenspace μ (finrank K V))
= ((f - algebra_map _ _ μ) ^ finrank K V *
(f - algebra_map K (End K V) μ) ^ finrank K V).ker :
by { simpa only [generalized_eigenspace, order_hom.coe_fun_mk, ← linear_map.ker_comp] }
... = f.generalized_eigenspace μ (finrank K V + finrank K V) :
by { rw ←pow_add, refl }
... = f.generalized_eigenspace μ (finrank K V) :
by { rw generalized_eigenspace_eq_generalized_eigenspace_finrank_of_le, linarith },
rw [disjoint, generalized_eigenrange, linear_map.range_eq_map, submodule.map_inf_eq_map_inf_comap,
top_inf_eq, h],
apply submodule.map_comap_le
end
/-- If an invariant subspace `p` of an endomorphism `f` is disjoint from the `μ`-eigenspace of `f`,
then the restriction of `f` to `p` has trivial `μ`-eigenspace. -/
lemma eigenspace_restrict_eq_bot {f : End R M} {p : submodule R M}
(hfp : ∀ x ∈ p, f x ∈ p) {μ : R} (hμp : disjoint (f.eigenspace μ) p) :
eigenspace (f.restrict hfp) μ = ⊥ :=
begin
rw eq_bot_iff,
intros x hx,
simpa using hμp ⟨eigenspace_restrict_le_eigenspace f hfp μ ⟨x, hx, rfl⟩, x.prop⟩,
end
/-- The generalized eigenspace of an eigenvalue has positive dimension for positive exponents. -/
lemma pos_finrank_generalized_eigenspace_of_has_eigenvalue [finite_dimensional K V]
{f : End K V} {k : ℕ} {μ : K} (hx : f.has_eigenvalue μ) (hk : 0 < k):
0 < finrank K (f.generalized_eigenspace μ k) :=
calc
0 = finrank K (⊥ : submodule K V) : by rw finrank_bot
... < finrank K (f.eigenspace μ) : submodule.finrank_lt_finrank_of_lt (bot_lt_iff_ne_bot.2 hx)
... ≤ finrank K (f.generalized_eigenspace μ k) :
submodule.finrank_mono ((f.generalized_eigenspace μ).monotone (nat.succ_le_of_lt hk))
/-- A linear map maps a generalized eigenrange into itself. -/
lemma map_generalized_eigenrange_le {f : End K V} {μ : K} {n : ℕ} :
submodule.map f (f.generalized_eigenrange μ n) ≤ f.generalized_eigenrange μ n :=
calc submodule.map f (f.generalized_eigenrange μ n)
= (f * ((f - algebra_map _ _ μ) ^ n)).range : (linear_map.range_comp _ _).symm
... = (((f - algebra_map _ _ μ) ^ n) * f).range : by rw algebra.mul_sub_algebra_map_pow_commutes
... = submodule.map ((f - algebra_map _ _ μ) ^ n) f.range : linear_map.range_comp _ _
... ≤ f.generalized_eigenrange μ n : linear_map.map_le_range
/-- The generalized eigenvectors span the entire vector space (Lemma 8.21 of [axler2015]). -/
lemma supr_generalized_eigenspace_eq_top [is_alg_closed K] [finite_dimensional K V] (f : End K V) :
(⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤ :=
begin
-- We prove the claim by strong induction on the dimension of the vector space.
unfreezingI { induction h_dim : finrank K V using nat.strong_induction_on
with n ih generalizing V },
cases n,
-- If the vector space is 0-dimensional, the result is trivial.
{ rw ←top_le_iff,
simp only [finrank_eq_zero.1 (eq.trans finrank_top h_dim), bot_le] },
-- Otherwise the vector space is nontrivial.
{ haveI : nontrivial V := finrank_pos_iff.1 (by { rw h_dim, apply nat.zero_lt_succ }),
-- Hence, `f` has an eigenvalue `μ₀`.
obtain ⟨μ₀, hμ₀⟩ : ∃ μ₀, f.has_eigenvalue μ₀ := exists_eigenvalue f,
-- We define `ES` to be the generalized eigenspace
let ES := f.generalized_eigenspace μ₀ (finrank K V),
-- and `ER` to be the generalized eigenrange.
let ER := f.generalized_eigenrange μ₀ (finrank K V),
-- `f` maps `ER` into itself.
have h_f_ER : ∀ (x : V), x ∈ ER → f x ∈ ER,
from λ x hx, map_generalized_eigenrange_le (submodule.mem_map_of_mem hx),
-- Therefore, we can define the restriction `f'` of `f` to `ER`.
let f' : End K ER := f.restrict h_f_ER,
-- The dimension of `ES` is positive
have h_dim_ES_pos : 0 < finrank K ES,
{ dsimp only [ES],
rw h_dim,
apply pos_finrank_generalized_eigenspace_of_has_eigenvalue hμ₀ (nat.zero_lt_succ n) },
-- and the dimensions of `ES` and `ER` add up to `finrank K V`.
have h_dim_add : finrank K ER + finrank K ES = finrank K V,
{ apply linear_map.finrank_range_add_finrank_ker },
-- Therefore the dimension `ER` mus be smaller than `finrank K V`.
have h_dim_ER : finrank K ER < n.succ, by linarith,
-- This allows us to apply the induction hypothesis on `ER`:
have ih_ER : (⨆ (μ : K) (k : ℕ), f'.generalized_eigenspace μ k) = ⊤,
from ih (finrank K ER) h_dim_ER f' rfl,
-- The induction hypothesis gives us a statement about subspaces of `ER`. We can transfer this
-- to a statement about subspaces of `V` via `submodule.subtype`:
have ih_ER' : (⨆ (μ : K) (k : ℕ), (f'.generalized_eigenspace μ k).map ER.subtype) = ER,
by simp only [(submodule.map_supr _ _).symm, ih_ER, submodule.map_subtype_top ER],
-- Moreover, every generalized eigenspace of `f'` is contained in the corresponding generalized
-- eigenspace of `f`.
have hff' : ∀ μ k,
(f'.generalized_eigenspace μ k).map ER.subtype ≤ f.generalized_eigenspace μ k,
{ intros,
rw generalized_eigenspace_restrict,
apply submodule.map_comap_le },
-- It follows that `ER` is contained in the span of all generalized eigenvectors.
have hER : ER ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k,
{ rw ← ih_ER',
apply supr_le_supr _,
exact λ μ, supr_le_supr (λ k, hff' μ k), },
-- `ES` is contained in this span by definition.
have hES : ES ≤ ⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k,
from le_trans
(le_supr (λ k, f.generalized_eigenspace μ₀ k) (finrank K V))
(le_supr (λ (μ : K), ⨆ (k : ℕ), f.generalized_eigenspace μ k) μ₀),
-- Moreover, we know that `ER` and `ES` are disjoint.
have h_disjoint : disjoint ER ES,
from generalized_eigenvec_disjoint_range_ker f μ₀,
-- Since the dimensions of `ER` and `ES` add up to the dimension of `V`, it follows that the
-- span of all generalized eigenvectors is all of `V`.
show (⨆ (μ : K) (k : ℕ), f.generalized_eigenspace μ k) = ⊤,
{ rw [←top_le_iff, ←submodule.eq_top_of_disjoint ER ES h_dim_add h_disjoint],
apply sup_le hER hES } }
end
end End
end module
|
2308ba0dca914faff13dc1781fc10a62d1a268c3 | 56af0912bd25910f5caae91d6dd0603b0c032989 | /src/complex/your_solutions/Level_01_of_real.lean | 40aaea49dd5a2cde8b783222c5d7797f8acfd11e | [
"Apache-2.0"
] | permissive | isabella232/complex-number-game | ae36e0b1df9761d9df07049ca29c91ae44dbdc2d | 3d767f14041f9002e435bed3a3527fdd297c166d | refs/heads/master | 1,679,305,953,116 | 1,606,397,567,000 | 1,606,397,567,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,549 | lean | /-
Copyright (c) 2020 The Xena project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard.
Thanks: Imperial College London, leanprover-community
-/
-- import the definition and basic properties of ℂ
import complex.Level_00_basic
/-! # Level 1 : the map from ℝ to ℂ
This file sets up the coercion from the reals to the complexes,
sending `r` to `⟨r, 0⟩`. Mathematically it is straightforward.
All the proofs below are sorried. You can try them in tactic mode
by replacing `sorry` with `begin sorry end` and then starting to write
tactics in the `begin end` block.
-/
namespace complex
-- fill in the definition of the map below,
-- sending the real number r to the complex number ⟨r, 0⟩
/-- The canonical map from ℝ to ℂ. -/
def of_real (r : ℝ) : ℂ := sorry
/-
We make this map into a *coercion*, which means that if `(r : ℝ)` is a real
number, then `(r : ℂ)` or `(↑r : ℂ)` will indicate the corresponding
complex number with no imaginary part. This is the notation we shall
use in our `simp` lemmas.
-/
/-- The coercion from ℝ to ℂ sending `r` to the complex number `⟨r, 0⟩` -/
instance : has_coe ℝ ℂ := ⟨of_real⟩
/-
As usual, we need to train the `simp` tactic. But we also need to train
the `norm_cast` tactic. The `norm_cast` tactic enables Lean to prove
results like r^2=2*s for reals `r` and `s`, if it knows that
`(r : ℂ)^2 = 2*(s : ℂ)`. Such results are intuitive for matheamticians
but involve "invisible maps" in Lean
-/
@[simp, norm_cast] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := sorry
@[simp, norm_cast] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := sorry
-- The map from the reals to the complexes is injective, something we
-- write in iff form so `simp` can use it; `simp` also works on `iff` goals.
@[simp, norm_cast] theorem of_real_inj {r s : ℝ} : (r : ℂ) = s ↔ r = s := sorry
-- what does norm_cast do?? Here are two examples of usage:
/-
example (r s : ℝ) (h : (r : ℂ) = s) : r = s :=
begin
norm_cast at h,
exact h,
end
example (r s : ℝ) (h : r = s) : (r : ℂ) = (s : ℂ) :=
begin
norm_cast,
exact h,
end
-/
/-
We now go through all the basic constants and constructions we've defined so
far, namely 0, 1, +, -, *, and tell the simplifier how they behave with respect
to this new function.
-/
/-! ## zero -/
@[simp, norm_cast] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := sorry
@[simp] theorem of_real_eq_zero {r : ℝ} : (r : ℂ) = 0 ↔ r = 0 := sorry
theorem of_real_ne_zero {r : ℝ} : (r : ℂ) ≠ 0 ↔ r ≠ 0 := sorry
/-! ## one -/
@[simp, norm_cast] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := sorry
/-! ## add -/
@[simp, norm_cast] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s :=
begin
sorry
end
/-! ## neg -/
@[simp, norm_cast] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r :=
begin
sorry
end
/-! ## mul -/
@[simp, norm_cast] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s :=
begin
sorry
end
/-- The canonical ring homomorphism from ℝ to ℂ -/
def Of_real : ℝ →+* ℂ :=
{ to_fun := coe, -- use the coercion from ℝ to ℂ
map_zero' := of_real_zero,
map_one' := of_real_one,
map_add' := of_real_add,
map_mul' := of_real_mul,
}
/-! ## numerals.
This is quite a computer-sciency bit.
These last two lemmas are to do with the canonical map from numerals
into the complexes, e.g. `(23 : ℂ)`. Lean stores the numeral in binary.
See for example
set_option pp.numerals false
#check (37 : ℂ)-- bit1 (bit0 (bit1 (bit0 (bit0 has_one.one)))) : ℂ
`bit0 x` is defined to be `x + x`, and `bit1 x` is defined to be `bit0 x + 1`.
We need these results so that `norm_cast` can prove results such
as (↑(37 : ℝ) : ℂ) = 37 : ℂ (i.e. coercion commutes with numerals)
-/
@[simp, norm_cast] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r :=
sorry
@[simp, norm_cast] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r :=
sorry
end complex
/-! ## norm_cast examples
The idea is that the "invisible map" from the reals to the complexes should not
create any trouble to mathematicians who just want things to work as normal
https://xenaproject.wordpress.com/2020/04/30/the-invisible-map/
example (a b c : ℝ) : ((a * b : ℝ) : ℂ) * c = (a : ℂ) * b * c :=
begin
norm_cast,
end
example (a b c : ℝ) : ((a : ℂ) + b) * c = ((a + b) * c : ℝ) :=
begin
norm_cast,
end
example : (37 : ℂ) = (37 : ℝ) :=
begin
norm_cast,
end
-/
|
5838ff02348cb287e99b8ca257230235c5e9e866 | 968e2f50b755d3048175f176376eff7139e9df70 | /welcome.lean | d0fc472a6ef14c4c4a7ae44d1b469569defbac11 | [] | no_license | gihanmarasingha/mth1001_sphinx | 190a003269ba5e54717b448302a27ca26e31d491 | 05126586cbf5786e521be1ea2ef5b4ba3c44e74a | refs/heads/master | 1,672,913,933,677 | 1,604,516,583,000 | 1,604,516,583,000 | 309,245,750 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32 | lean | --> check the documentation tab
|
3a9c2dd914eec20fb245b9af86ba45b8463c2b9c | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Compiler/IR/CompilerM.lean | a9437865b0b70a356d1157b218c299f9575f0e47 | [
"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 | 4,880 | 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
-/
prelude
import Init.Control.Reader
import Init.Lean.Environment
import Init.Lean.Compiler.IR.Basic
import Init.Lean.Compiler.IR.Format
namespace Lean
namespace IR
inductive LogEntry
| step (cls : Name) (decls : Array Decl)
| message (msg : Format)
namespace LogEntry
protected def fmt : LogEntry → Format
| step cls decls => Format.bracket "[" (format cls) "]" ++ decls.foldl (fun fmt decl => fmt ++ Format.line ++ format decl) Format.nil
| message msg => msg
instance : HasFormat LogEntry := ⟨LogEntry.fmt⟩
end LogEntry
abbrev Log := Array LogEntry
def Log.format (log : Log) : Format :=
log.foldl (fun fmt entry => fmt ++ Format.line ++ format entry) Format.nil
@[export lean_ir_log_to_string]
def Log.toString (log : Log) : String :=
log.format.pretty
structure CompilerState :=
(env : Environment) (log : Log := #[])
abbrev CompilerM := ReaderT Options (EStateM String CompilerState)
def log (entry : LogEntry) : CompilerM Unit :=
modify $ fun s => { log := s.log.push entry, .. s }
def tracePrefixOptionName := `trace.compiler.ir
private def isLogEnabledFor (opts : Options) (optName : Name) : Bool :=
match opts.find optName with
| some (DataValue.ofBool v) => v
| other => opts.getBool tracePrefixOptionName
private def logDeclsAux (optName : Name) (cls : Name) (decls : Array Decl) : CompilerM Unit := do
opts ← read;
when (isLogEnabledFor opts optName) $ log (LogEntry.step cls decls)
@[inline] def logDecls (cls : Name) (decl : Array Decl) : CompilerM Unit :=
logDeclsAux (tracePrefixOptionName ++ cls) cls decl
private def logMessageIfAux {α : Type} [HasFormat α] (optName : Name) (a : α) : CompilerM Unit := do
opts ← read;
when (isLogEnabledFor opts optName) $ log (LogEntry.message (format a))
@[inline] def logMessageIf {α : Type} [HasFormat α] (cls : Name) (a : α) : CompilerM Unit :=
logMessageIfAux (tracePrefixOptionName ++ cls) a
@[inline] def logMessage {α : Type} [HasFormat α] (cls : Name) (a : α) : CompilerM Unit :=
logMessageIfAux tracePrefixOptionName a
@[inline] def modifyEnv (f : Environment → Environment) : CompilerM Unit :=
modify $ fun s => { env := f s.env, .. s }
abbrev DeclMap := SMap Name Decl
/- Create an array of decls to be saved on .olean file.
`decls` may contain duplicate entries, but we assume the one that occurs last is the most recent one. -/
private def mkEntryArray (decls : List Decl) : Array Decl :=
/- Remove duplicates by adding decls into a map -/
let map : HashMap Name Decl := {};
let map := decls.foldl (fun (map : HashMap Name Decl) decl => map.insert decl.name decl) map;
map.fold (fun a k v => a.push v) #[]
def mkDeclMapExtension : IO (SimplePersistentEnvExtension Decl DeclMap) :=
registerSimplePersistentEnvExtension {
name := `IRDecls,
addImportedFn := fun as =>
let m : DeclMap := mkStateFromImportedEntries (fun s (d : Decl) => s.insert d.name d) {} as;
m.switch,
addEntryFn := fun s d => s.insert d.name d,
toArrayFn := mkEntryArray
}
@[init mkDeclMapExtension]
constant declMapExt : SimplePersistentEnvExtension Decl DeclMap := arbitrary _
@[export lean_ir_find_env_decl]
def findEnvDecl (env : Environment) (n : Name) : Option Decl :=
(declMapExt.getState env).find? n
def findDecl (n : Name) : CompilerM (Option Decl) := do
s ← get;
pure $ findEnvDecl s.env n
def containsDecl (n : Name) : CompilerM Bool := do
s ← get;
pure $ (declMapExt.getState s.env).contains n
def getDecl (n : Name) : CompilerM Decl := do
(some decl) ← findDecl n | throw ("unknown declaration '" ++ toString n ++ "'");
pure decl
@[export lean_ir_add_decl]
def addDeclAux (env : Environment) (decl : Decl) : Environment :=
declMapExt.addEntry env decl
def getDecls (env : Environment) : List Decl :=
declMapExt.getEntries env
def getEnv : CompilerM Environment := do
s ← get; pure s.env
def addDecl (decl : Decl) : CompilerM Unit :=
modifyEnv (fun env => declMapExt.addEntry env decl)
def addDecls (decls : Array Decl) : CompilerM Unit :=
decls.forM addDecl
def findEnvDecl' (env : Environment) (n : Name) (decls : Array Decl) : Option Decl :=
match decls.find? (fun decl => decl.name == n) with
| some decl => some decl
| none => (declMapExt.getState env).find? n
def findDecl' (n : Name) (decls : Array Decl) : CompilerM (Option Decl) := do
s ← get; pure $ findEnvDecl' s.env n decls
def containsDecl' (n : Name) (decls : Array Decl) : CompilerM Bool :=
if decls.any (fun decl => decl.name == n) then pure true
else do
s ← get;
pure $ (declMapExt.getState s.env).contains n
def getDecl' (n : Name) (decls : Array Decl) : CompilerM Decl := do
(some decl) ← findDecl' n decls | throw ("unknown declaration '" ++ toString n ++ "'");
pure decl
end IR
end Lean
|
fb01236da29b49e654348d5fd246be7ed0cb00c3 | abd85493667895c57a7507870867b28124b3998f | /src/analysis/mean_inequalities.lean | 1e308ec203d122b902bc752f685e36ca2f685f83 | [
"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 | 6,827 | 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 analysis.convex.specific_functions
import analysis.special_functions.pow
/-!
# Mean value inequalities
In this file we prove various inequalities between mean values:
arithmetic mean, geometric mean, generalized mean (natural and integer
cases).
For generalized means we only prove
$\left( ∑_j w_j z_j \right)^n ≤ ∑_j w_j z_j^n$ because standard versions would
require $\sqrt[n]{x}$ which is not implemented in `mathlib` yet.
Probably a better approach to the generalized means inequality is to
prove `convex_on_rpow` in `analysis/convex/specific_functions` first,
then apply it.
It is not yet clear which versions will be useful in the future, so we
provide two different forms of most inequalities : for `ℝ` and for
`ℝ≥0`. For the AM-GM inequality we also prove special cases for `n=2`
and `n=3`.
-/
universes u v
open real finset
open_locale classical nnreal big_operators
variables {ι : Type u} (s : finset ι)
/-- Geometric mean is less than or equal to the arithmetic mean, weighted version
for functions on `finset`s. -/
theorem real.am_gm_weighted (w z : ι → ℝ)
(hw : ∀ i ∈ s, 0 ≤ w i) (hw' : s.sum w = 1) (hz : ∀ i ∈ s, 0 ≤ z i) :
(∏ i in s, (z i) ^ (w i)) ≤ s.sum (λ i, w i * z i) :=
begin
let s' := s.filter (λ i, w i ≠ 0),
rw [← sum_filter_ne_zero] at hw',
suffices : (∏ i in s', (z i) ^ (w i)) ≤ s'.sum (λ i, w i * z i),
{ have A : ∀ i ∈ s, i ∉ s' → w i = 0,
{ intros i hi hi',
simpa only [hi, mem_filter, ne.def, true_and, not_not] using hi' },
have B : ∀ i ∈ s, i ∉ s' → (z i) ^ (w i) = 1,
from λ i hi hi', by rw [A i hi hi', rpow_zero],
have C : ∀ i ∈ s, i ∉ s' → w i * z i = 0,
from λ i hi hi', by rw [A i hi hi', zero_mul],
rwa [← prod_subset s.filter_subset B, ← sum_subset s.filter_subset C] },
have A : ∀ i ∈ s', i ∈ s ∧ w i ≠ 0, from λ i hi, mem_filter.1 hi,
replace hz : ∀ i ∈ s', 0 ≤ z i := λ i hi, hz i (A i hi).1,
replace hw : ∀ i ∈ s', 0 ≤ w i := λ i hi, hw i (A i hi).1,
by_cases B : ∃ i ∈ s', z i = 0,
{ rcases B with ⟨i, imem, hzi⟩,
rw [prod_eq_zero imem],
{ exact sum_nonneg (λ j hj, mul_nonneg (hw j hj) (hz j hj)) },
{ rw hzi, exact zero_rpow (A i imem).2 } },
{ replace hz : ∀ i ∈ s', 0 < z i,
from λ i hi, lt_of_le_of_ne (hz _ hi) (λ h, B ⟨i, hi, h.symm⟩),
have := convex_on_exp.map_sum_le hw hw' (λ i _, set.mem_univ $ log (z i)),
simp only [exp_sum, (∘), smul_eq_mul, mul_comm (w _) (log _)] at this,
convert this using 1,
{ exact prod_congr rfl (λ i hi, rpow_def_of_pos (hz i hi) _) },
{ exact sum_congr rfl (λ i hi, congr_arg _ (exp_log $ hz i hi).symm) } }
end
theorem nnreal.am_gm_weighted (w z : ι → ℝ≥0) (hw' : s.sum w = 1) :
(∏ i in s, (z i) ^ (w i:ℝ)) ≤ s.sum (λ i, w i * z i) :=
begin
rw [← nnreal.coe_le_coe, nnreal.coe_prod, nnreal.coe_sum],
refine real.am_gm_weighted _ _ _ (λ i _, (w i).coe_nonneg) _ (λ i _, (z i).coe_nonneg),
assumption_mod_cast
end
theorem nnreal.am_gm2_weighted (w₁ w₂ p₁ p₂ : ℝ≥0) (hw : w₁ + w₂ = 1) :
p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) ≤ w₁ * p₁ + w₂ * p₂ :=
begin
have := nnreal.am_gm_weighted (univ : finset (fin 2)) (fin.cons w₁ $ fin.cons w₂ fin_zero_elim)
(fin.cons p₁ $ fin.cons p₂ $ fin_zero_elim),
simp only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero,
fin.cons_succ, fin.cons_zero, add_zero, mul_one] at this,
exact this hw
end
theorem real.am_gm2_weighted {w₁ w₂ p₁ p₂ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂)
(hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hw : w₁ + w₂ = 1) :
p₁ ^ w₁ * p₂ ^ w₂ ≤ w₁ * p₁ + w₂ * p₂ :=
nnreal.am_gm2_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ $ nnreal.coe_eq.1 $ by assumption
theorem nnreal.am_gm3_weighted (w₁ w₂ w₃ p₁ p₂ p₃ : ℝ≥0) (hw : w₁ + w₂ + w₃ = 1) :
p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) * p₃ ^ (w₃:ℝ) ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃:=
begin
have := nnreal.am_gm_weighted (univ : finset (fin 3))
(fin.cons w₁ $ fin.cons w₂ $ fin.cons w₃ fin_zero_elim)
(fin.cons p₁ $ fin.cons p₂ $ fin.cons p₃ fin_zero_elim),
simp only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero,
fin.cons_succ, fin.cons_zero, add_zero, mul_one, (add_assoc _ _ _).symm,
(mul_assoc _ _ _).symm] at this,
exact this hw
end
/-- Young's inequality, `ℝ≥0` version -/
theorem nnreal.young_inequality (a b : ℝ≥0) {p q : ℝ≥0} (hp : 1 < p) (hq : 1 < q)
(hpq : 1/p + 1/q = 1) : a * b ≤ a^(p:ℝ) / p + b^(q:ℝ) / q :=
begin
have := nnreal.am_gm2_weighted (1/p) (1/q) (a^(p:ℝ)) (b^(q:ℝ)) hpq,
simp only [← nnreal.rpow_mul, one_div_eq_inv, nnreal.coe_div, nnreal.coe_one] at this,
rw [mul_inv_cancel, mul_inv_cancel, nnreal.rpow_one, nnreal.rpow_one] at this,
{ ring at ⊢ this,
convert this;
{ rw [nnreal.div_def, nnreal.div_def], ring } },
{ exact ne_of_gt (lt_trans zero_lt_one hq) },
{ exact ne_of_gt (lt_trans zero_lt_one hp) }
end
/-- Young's inequality, `ℝ` version -/
theorem real.young_inequality {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b)
{p q : ℝ} (hp : 1 < p) (hq : 1 < q) (hpq : 1/p + 1/q = 1) :
a * b ≤ a^p / p + b^q / q :=
@nnreal.young_inequality ⟨a, ha⟩ ⟨b, hb⟩ ⟨p, le_trans zero_le_one (le_of_lt hp)⟩
⟨q, le_trans zero_le_one (le_of_lt hq)⟩ hp hq (nnreal.coe_eq.1 hpq)
theorem real.pow_am_le_am_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : s.sum w = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) :
(s.sum (λ i, w i * z i)) ^ n ≤ s.sum (λ i, w i * z i ^ n) :=
(convex_on_pow n).map_sum_le hw hw' hz
theorem nnreal.pow_am_le_am_pow (w z : ι → ℝ≥0) (hw' : s.sum w = 1) (n : ℕ) :
(s.sum (λ i, w i * z i)) ^ n ≤ s.sum (λ i, w i * z i ^ n) :=
begin
rw [← nnreal.coe_le_coe],
push_cast,
refine (convex_on_pow n).map_sum_le (λ i _, (w i).coe_nonneg) _ (λ i _, (z i).coe_nonneg),
assumption_mod_cast
end
theorem real.pow_am_le_am_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : s.sum w = 1) {n : ℕ} (hn : n.even) :
(s.sum (λ i, w i * z i)) ^ n ≤ s.sum (λ i, w i * z i ^ n) :=
(convex_on_pow_of_even hn).map_sum_le hw hw' (λ _ _, trivial)
theorem real.fpow_am_le_am_fpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i)
(hw' : s.sum w = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) :
(s.sum (λ i, w i * z i)) ^ m ≤ s.sum (λ i, w i * z i ^ m) :=
(convex_on_fpow m).map_sum_le hw hw' hz
|
005abe0d1a24340a2292a13f56095d236c95d404 | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/RightCancellativeMagma.lean | ea15f3ee1a86fbd52ffdfa87e251cfd4907e1075 | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,576 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section RightCancellativeMagma
structure RightCancellativeMagma (A : Type) : Type :=
(op : (A → (A → A)))
(rightCancellative : (∀ {x y z : A} , ((op x z) = (op y z) → x = y)))
open RightCancellativeMagma
structure Sig (AS : Type) : Type :=
(opS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(opP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(rightCancellativeP : (∀ {xP yP zP : (Prod A A)} , ((opP xP zP) = (opP yP zP) → xP = yP)))
structure Hom {A1 : Type} {A2 : Type} (Ri1 : (RightCancellativeMagma A1)) (Ri2 : (RightCancellativeMagma A2)) : Type :=
(hom : (A1 → A2))
(pres_op : (∀ {x1 x2 : A1} , (hom ((op Ri1) x1 x2)) = ((op Ri2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (RightCancellativeMagma A1)) (Ri2 : (RightCancellativeMagma A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Ri1) x1 x2) ((op Ri2) y1 y2))))))
inductive RightCancellativeMagmaTerm : Type
| opL : (RightCancellativeMagmaTerm → (RightCancellativeMagmaTerm → RightCancellativeMagmaTerm))
open RightCancellativeMagmaTerm
inductive ClRightCancellativeMagmaTerm (A : Type) : Type
| sing : (A → ClRightCancellativeMagmaTerm)
| opCl : (ClRightCancellativeMagmaTerm → (ClRightCancellativeMagmaTerm → ClRightCancellativeMagmaTerm))
open ClRightCancellativeMagmaTerm
inductive OpRightCancellativeMagmaTerm (n : ℕ) : Type
| v : ((fin n) → OpRightCancellativeMagmaTerm)
| opOL : (OpRightCancellativeMagmaTerm → (OpRightCancellativeMagmaTerm → OpRightCancellativeMagmaTerm))
open OpRightCancellativeMagmaTerm
inductive OpRightCancellativeMagmaTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpRightCancellativeMagmaTerm2)
| sing2 : (A → OpRightCancellativeMagmaTerm2)
| opOL2 : (OpRightCancellativeMagmaTerm2 → (OpRightCancellativeMagmaTerm2 → OpRightCancellativeMagmaTerm2))
open OpRightCancellativeMagmaTerm2
def simplifyCl {A : Type} : ((ClRightCancellativeMagmaTerm A) → (ClRightCancellativeMagmaTerm A))
| (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpRightCancellativeMagmaTerm n) → (OpRightCancellativeMagmaTerm n))
| (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpRightCancellativeMagmaTerm2 n A) → (OpRightCancellativeMagmaTerm2 n A))
| (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((RightCancellativeMagma A) → (RightCancellativeMagmaTerm → A))
| Ri (opL x1 x2) := ((op Ri) (evalB Ri x1) (evalB Ri x2))
def evalCl {A : Type} : ((RightCancellativeMagma A) → ((ClRightCancellativeMagmaTerm A) → A))
| Ri (sing x1) := x1
| Ri (opCl x1 x2) := ((op Ri) (evalCl Ri x1) (evalCl Ri x2))
def evalOpB {A : Type} {n : ℕ} : ((RightCancellativeMagma A) → ((vector A n) → ((OpRightCancellativeMagmaTerm n) → A)))
| Ri vars (v x1) := (nth vars x1)
| Ri vars (opOL x1 x2) := ((op Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2))
def evalOp {A : Type} {n : ℕ} : ((RightCancellativeMagma A) → ((vector A n) → ((OpRightCancellativeMagmaTerm2 n A) → A)))
| Ri vars (v2 x1) := (nth vars x1)
| Ri vars (sing2 x1) := x1
| Ri vars (opOL2 x1 x2) := ((op Ri) (evalOp Ri vars x1) (evalOp Ri vars x2))
def inductionB {P : (RightCancellativeMagmaTerm → Type)} : ((∀ (x1 x2 : RightCancellativeMagmaTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → (∀ (x : RightCancellativeMagmaTerm) , (P x)))
| popl (opL x1 x2) := (popl _ _ (inductionB popl x1) (inductionB popl x2))
def inductionCl {A : Type} {P : ((ClRightCancellativeMagmaTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRightCancellativeMagmaTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → (∀ (x : (ClRightCancellativeMagmaTerm A)) , (P x))))
| psing popcl (sing x1) := (psing x1)
| psing popcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl x1) (inductionCl psing popcl x2))
def inductionOpB {n : ℕ} {P : ((OpRightCancellativeMagmaTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRightCancellativeMagmaTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → (∀ (x : (OpRightCancellativeMagmaTerm n)) , (P x))))
| pv popol (v x1) := (pv x1)
| pv popol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol x1) (inductionOpB pv popol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpRightCancellativeMagmaTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRightCancellativeMagmaTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → (∀ (x : (OpRightCancellativeMagmaTerm2 n A)) , (P x)))))
| pv2 psing2 popol2 (v2 x1) := (pv2 x1)
| pv2 psing2 popol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 popol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 x1) (inductionOp pv2 psing2 popol2 x2))
def stageB : (RightCancellativeMagmaTerm → (Staged RightCancellativeMagmaTerm))
| (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClRightCancellativeMagmaTerm A) → (Staged (ClRightCancellativeMagmaTerm A)))
| (sing x1) := (Now (sing x1))
| (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpRightCancellativeMagmaTerm n) → (Staged (OpRightCancellativeMagmaTerm n)))
| (v x1) := (const (code (v x1)))
| (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpRightCancellativeMagmaTerm2 n A) → (Staged (OpRightCancellativeMagmaTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(opT : ((Repr A) → ((Repr A) → (Repr A))))
end RightCancellativeMagma |
712b14050af887ddb31657069c263066524cd157 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/category_theory/graded_object.lean | c711bd8535c8e9998eaf50723668383b08d99bf5 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 6,871 | 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 category_theory.shift
import category_theory.limits.shapes.zero
/-!
# The category of graded objects
For any type `β`, a `β`-graded object over some category `C` is just
a function `β → C` into the objects of `C`.
We define the category structure on these.
We describe the `comap` functors obtained by precomposing with functions `β → γ`.
As a consequence a fixed element (e.g. `1`) in an additive group `β` provides a shift
functor on `β`-graded objects
When `C` has coproducts we construct the `total` functor `graded_object β C ⥤ C`,
show that it is faithful, and deduce that when `C` is concrete so is `graded_object β C`.
-/
open category_theory.limits
namespace category_theory
universes w v u
/-- A type synonym for `β → C`, used for `β`-graded objects in a category `C`. -/
def graded_object (β : Type w) (C : Type u) : Type (max w u) := β → C
-- Satisfying the inhabited linter...
instance inhabited_graded_object (β : Type w) (C : Type u) [inhabited C] :
inhabited (graded_object β C) :=
⟨λ b, inhabited.default C⟩
/--
A type synonym for `β → C`, used for `β`-graded objects in a category `C`
with a shift functor given by translation by `s`.
-/
@[nolint unused_arguments] -- `s` is here to distinguish type synonyms asking for different shifts
abbreviation graded_object_with_shift {β : Type w} [add_comm_group β] (s : β) (C : Type u) : Type (max w u) := graded_object β C
namespace graded_object
variables {C : Type u} [𝒞 : category.{v} C]
include 𝒞
instance category_of_graded_objects (β : Type w) : category.{(max w v)} (graded_object β C) :=
{ hom := λ X Y, Π b : β, X b ⟶ Y b,
id := λ X b, 𝟙 (X b),
comp := λ X Y Z f g b, f b ≫ g b, }
@[simp]
lemma id_apply {β : Type w} (X : graded_object β C) (b : β) :
((𝟙 X) : Π b, X b ⟶ X b) b = 𝟙 (X b) := rfl
@[simp]
lemma comp_apply {β : Type w} {X Y Z : graded_object β C} (f : X ⟶ Y) (g : Y ⟶ Z) (b : β) :
((f ≫ g) : Π b, X b ⟶ Z b) b = f b ≫ g b := rfl
section
variable (C)
/-- Pull back a graded object along a change-of-grading function. -/
@[simps]
def comap {β γ : Type w} (f : β → γ) :
(graded_object γ C) ⥤ (graded_object β C) :=
{ obj := λ X, X ∘ f,
map := λ X Y g b, g (f b) }
/--
The natural isomorphism between
pulling back a grading along the identity function,
and the identity functor. -/
@[simps]
def comap_id (β : Type w) : comap C (id : β → β) ≅ 𝟭 (graded_object β C) :=
{ hom := { app := λ X, 𝟙 X },
inv := { app := λ X, 𝟙 X } }.
/--
The natural isomorphism comparing between
pulling back along two successive functions, and
pulling back along their composition
-/
@[simps]
def comap_comp {β γ δ : Type w} (f : β → γ) (g : γ → δ) : comap C g ⋙ comap C f ≅ comap C (g ∘ f) :=
{ hom := { app := λ X b, 𝟙 (X (g (f b))) },
inv := { app := λ X b, 𝟙 (X (g (f b))) } }
/--
The natural isomorphism comparing between
pulling back along two propositionally equal functions.
-/
@[simps]
def comap_eq {β γ : Type w} {f g : β → γ} (h : f = g) : comap C f ≅ comap C g :=
{ hom := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end },
inv := { app := λ X b, eq_to_hom begin dsimp [comap], subst h, end }, }
@[simp]
lemma comap_eq_symm {β γ : Type w} {f g : β → γ} (h : f = g) : comap_eq C h.symm = (comap_eq C h).symm :=
by tidy
@[simp]
lemma comap_eq_trans {β γ : Type w} {f g h : β → γ} (k : f = g) (l : g = h) :
comap_eq C (k.trans l) = comap_eq C k ≪≫ comap_eq C l :=
begin
ext X b,
simp,
end
/--
The equivalence between β-graded objects and γ-graded objects,
given an equivalence between β and γ.
-/
@[simps]
def comap_equiv {β γ : Type w} (e : β ≃ γ) :
(graded_object β C) ≌ (graded_object γ C) :=
{ functor := comap C (e.symm : γ → β),
inverse := comap C (e : β → γ),
counit_iso := (comap_comp C _ _).trans (comap_eq C (by { ext, simp } )),
unit_iso := (comap_eq C (by { ext, simp} )).trans (comap_comp _ _ _).symm,
functor_unit_iso_comp' := λ X, begin ext b, dsimp, simp, end, }
end
instance has_shift {β : Type} [add_comm_group β] (s : β) : has_shift.{v} (graded_object_with_shift s C) :=
{ shift := comap_equiv C
{ to_fun := λ b, b-s,
inv_fun := λ b, b+s,
left_inv := λ x, (by simp),
right_inv := λ x, (by simp), } }
instance has_zero_morphisms [has_zero_morphisms.{v} C] (β : Type w) :
has_zero_morphisms.{(max w v)} (graded_object β C) :=
{ has_zero := λ X Y,
{ zero := λ b, 0 } }
@[simp]
lemma zero_apply [has_zero_morphisms.{v} C] (β : Type w) (X Y : graded_object β C) (b : β) :
(0 : X ⟶ Y) b = 0 := rfl
section
local attribute [instance] has_zero_object.has_zero
instance has_zero_object [has_zero_object.{v} C] [has_zero_morphisms.{v} C] (β : Type w) :
has_zero_object.{(max w v)} (graded_object β C) :=
{ zero := λ b, (0 : C),
unique_to := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩,
unique_from := λ X, ⟨⟨λ b, 0⟩, λ f, (by ext)⟩, }
end
end graded_object
namespace graded_object
-- The universes get a little hairy here, so we restrict the universe level for the grading to 0.
-- Since we're typically interested in grading by ℤ or a finite group, this should be okay.
-- If you're grading by things in higher universes, have fun!
variables (β : Type)
variables (C : Type u) [𝒞 : category.{v} C]
include 𝒞
variables [has_coproducts.{v} C]
/--
The total object of a graded object is the coproduct of the graded components.
-/
def total : graded_object β C ⥤ C :=
{ obj := λ X, ∐ (λ i : ulift.{v} β, X i.down),
map := λ X Y f, limits.sigma.map (λ i, f i.down) }.
variables [has_zero_morphisms.{v} C]
/--
The `total` functor taking a graded object to the coproduct of its graded components is faithful.
To prove this, we need to know that the coprojections into the coproduct are monomorphisms,
which follows from the fact we have zero morphisms and decidable equality for the grading.
-/
instance : faithful.{v} (total.{v u} β C) :=
{ injectivity' := λ X Y f g w,
begin
classical,
ext i,
replace w := sigma.ι (λ i : ulift β, X i.down) ⟨i⟩ ≫= w,
erw [colimit.ι_map, colimit.ι_map] at w,
exact mono.right_cancellation _ _ w,
end }
end graded_object
namespace graded_object
variables (β : Type)
variables (C : Type (u+1)) [large_category C] [𝒞 : concrete_category C]
[has_coproducts.{u} C] [has_zero_morphisms.{u} C]
include 𝒞
instance : concrete_category (graded_object β C) :=
{ forget := total β C ⋙ forget C }
instance : has_forget₂ (graded_object β C) C :=
{ forget₂ := total β C }
end graded_object
end category_theory
|
61a5aaab125f23383dd6724e460dd042e299b96d | d9ed0fce1c218297bcba93e046cb4e79c83c3af8 | /library/init/meta/default.lean | 7800f80f63b31e75602c93092d829a057d74f3c4 | [
"Apache-2.0"
] | permissive | leodemoura/lean_clone | 005c63aa892a6492f2d4741ee3c2cb07a6be9d7f | cc077554b584d39bab55c360bc12a6fe7957afe6 | refs/heads/master | 1,610,506,475,484 | 1,482,348,354,000 | 1,482,348,543,000 | 77,091,586 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 842 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.name init.meta.options init.meta.format init.meta.rb_map
import init.meta.level init.meta.expr init.meta.environment init.meta.attribute
import init.meta.tactic init.meta.contradiction_tactic init.meta.constructor_tactic
import init.meta.injection_tactic init.meta.relation_tactics init.meta.fun_info
import init.meta.congr_lemma init.meta.match_tactic init.meta.ac_tactics
import init.meta.backward init.meta.rewrite_tactic
import init.meta.mk_dec_eq_instance init.meta.mk_inhabited_instance
import init.meta.simp_tactic init.meta.set_get_option_tactics
import init.meta.interactive init.meta.converter init.meta.vm
import init.meta.comp_value_tactics
|
3479b1391e78a54c19a8902a3775199d35e2bc54 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/function/special_functions/basic.lean | 17665d0e7e0cc7b89a395352ed36db14ab6c7748 | [
"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 | 6,316 | 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.special_functions.pow.nnreal
import measure_theory.constructions.borel_space.complex
/-!
# Measurability of real and complex functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We show that most standard real and complex functions are measurable, notably `exp`, `cos`, `sin`,
`cosh`, `sinh`, `log`, `pow`, `arcsin`, `arccos`.
See also `measure_theory.function.special_functions.arctan` and
`measure_theory.function.special_functions.inner`, which have been split off to minimize imports.
-/
noncomputable theory
open_locale nnreal ennreal
namespace real
@[measurability] lemma measurable_exp : measurable exp := continuous_exp.measurable
@[measurability] lemma measurable_log : measurable log :=
measurable_of_measurable_on_compl_singleton 0 $ continuous.measurable $
continuous_on_iff_continuous_restrict.1 continuous_on_log
@[measurability] lemma measurable_sin : measurable sin := continuous_sin.measurable
@[measurability] lemma measurable_cos : measurable cos := continuous_cos.measurable
@[measurability] lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
@[measurability] lemma measurable_cosh : measurable cosh := continuous_cosh.measurable
@[measurability] lemma measurable_arcsin : measurable arcsin := continuous_arcsin.measurable
@[measurability] lemma measurable_arccos : measurable arccos := continuous_arccos.measurable
end real
namespace complex
@[measurability] lemma measurable_re : measurable re := continuous_re.measurable
@[measurability] lemma measurable_im : measurable im := continuous_im.measurable
@[measurability] lemma measurable_of_real : measurable (coe : ℝ → ℂ) :=
continuous_of_real.measurable
@[measurability] lemma measurable_exp : measurable exp := continuous_exp.measurable
@[measurability] lemma measurable_sin : measurable sin := continuous_sin.measurable
@[measurability] lemma measurable_cos : measurable cos := continuous_cos.measurable
@[measurability] lemma measurable_sinh : measurable sinh := continuous_sinh.measurable
@[measurability] lemma measurable_cosh : measurable cosh := continuous_cosh.measurable
@[measurability] lemma measurable_arg : measurable arg :=
have A : measurable (λ x : ℂ, real.arcsin (x.im / x.abs)),
from real.measurable_arcsin.comp (measurable_im.div measurable_norm),
have B : measurable (λ x : ℂ, real.arcsin ((-x).im / x.abs)),
from real.measurable_arcsin.comp ((measurable_im.comp measurable_neg).div measurable_norm),
measurable.ite (is_closed_le continuous_const continuous_re).measurable_set A $
measurable.ite (is_closed_le continuous_const continuous_im).measurable_set
(B.add_const _) (B.sub_const _)
@[measurability] lemma measurable_log : measurable log :=
(measurable_of_real.comp $ real.measurable_log.comp measurable_norm).add $
(measurable_of_real.comp measurable_arg).mul_const I
end complex
section real_composition
open real
variables {α : Type*} {m : measurable_space α} {f : α → ℝ} (hf : measurable f)
@[measurability] lemma measurable.exp : measurable (λ x, real.exp (f x)) :=
real.measurable_exp.comp hf
@[measurability] lemma measurable.log : measurable (λ x, log (f x)) :=
measurable_log.comp hf
@[measurability] lemma measurable.cos : measurable (λ x, real.cos (f x)) :=
real.measurable_cos.comp hf
@[measurability] lemma measurable.sin : measurable (λ x, real.sin (f x)) :=
real.measurable_sin.comp hf
@[measurability] lemma measurable.cosh : measurable (λ x, real.cosh (f x)) :=
real.measurable_cosh.comp hf
@[measurability] lemma measurable.sinh : measurable (λ x, real.sinh (f x)) :=
real.measurable_sinh.comp hf
@[measurability] lemma measurable.sqrt : measurable (λ x, sqrt (f x)) :=
continuous_sqrt.measurable.comp hf
end real_composition
section complex_composition
open complex
variables {α : Type*} {m : measurable_space α} {f : α → ℂ} (hf : measurable f)
@[measurability] lemma measurable.cexp : measurable (λ x, complex.exp (f x)) :=
complex.measurable_exp.comp hf
@[measurability] lemma measurable.ccos : measurable (λ x, complex.cos (f x)) :=
complex.measurable_cos.comp hf
@[measurability] lemma measurable.csin : measurable (λ x, complex.sin (f x)) :=
complex.measurable_sin.comp hf
@[measurability] lemma measurable.ccosh : measurable (λ x, complex.cosh (f x)) :=
complex.measurable_cosh.comp hf
@[measurability] lemma measurable.csinh : measurable (λ x, complex.sinh (f x)) :=
complex.measurable_sinh.comp hf
@[measurability] lemma measurable.carg : measurable (λ x, arg (f x)) :=
measurable_arg.comp hf
@[measurability] lemma measurable.clog : measurable (λ x, log (f x)) :=
measurable_log.comp hf
end complex_composition
section pow_instances
instance complex.has_measurable_pow : has_measurable_pow ℂ ℂ :=
⟨measurable.ite (measurable_fst (measurable_set_singleton 0))
(measurable.ite (measurable_snd (measurable_set_singleton 0)) measurable_one measurable_zero)
(measurable_fst.clog.mul measurable_snd).cexp⟩
instance real.has_measurable_pow : has_measurable_pow ℝ ℝ :=
⟨complex.measurable_re.comp $ ((complex.measurable_of_real.comp measurable_fst).pow
(complex.measurable_of_real.comp measurable_snd))⟩
instance nnreal.has_measurable_pow : has_measurable_pow ℝ≥0 ℝ :=
⟨(measurable_fst.coe_nnreal_real.pow measurable_snd).subtype_mk⟩
instance ennreal.has_measurable_pow : has_measurable_pow ℝ≥0∞ ℝ :=
begin
refine ⟨ennreal.measurable_of_measurable_nnreal_prod _ _⟩,
{ simp_rw ennreal.coe_rpow_def,
refine measurable.ite _ measurable_const
(measurable_fst.pow measurable_snd).coe_nnreal_ennreal,
exact measurable_set.inter (measurable_fst (measurable_set_singleton 0))
(measurable_snd measurable_set_Iio), },
{ simp_rw ennreal.top_rpow_def,
refine measurable.ite measurable_set_Ioi measurable_const _,
exact measurable.ite (measurable_set_singleton 0) measurable_const measurable_const, },
end
end pow_instances
-- Guard against import creep:
assert_not_exists inner_product_space
assert_not_exists real.arctan
assert_not_exists finite_dimensional.proper
|
f574422dd0f1338024b5193dda0a5c265763fa4e | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/geometry/manifold/mfderiv.lean | c621b85eee4fc9a20f8c1f11d98fed37557f1261 | [
"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 | 93,958 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Floris van Doorn
-/
import geometry.manifold.vector_bundle.tangent
/-!
# The derivative of functions between smooth manifolds
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Let `M` and `M'` be two smooth manifolds with corners over a field `𝕜` (with respective models with
corners `I` on `(E, H)` and `I'` on `(E', H')`), and let `f : M → M'`. We define the
derivative of the function at a point, within a set or along the whole space, mimicking the API
for (Fréchet) derivatives. It is denoted by `mfderiv I I' f x`, where "m" stands for "manifold" and
"f" for "Fréchet" (as in the usual derivative `fderiv 𝕜 f x`).
## Main definitions
* `unique_mdiff_on I s` : predicate saying that, at each point of the set `s`, a function can have
at most one derivative. This technical condition is important when we define
`mfderiv_within` below, as otherwise there is an arbitrary choice in the derivative,
and many properties will fail (for instance the chain rule). This is analogous to
`unique_diff_on 𝕜 s` in a vector space.
Let `f` be a map between smooth manifolds. The following definitions follow the `fderiv` API.
* `mfderiv I I' f x` : the derivative of `f` at `x`, as a continuous linear map from the tangent
space at `x` to the tangent space at `f x`. If the map is not differentiable, this is `0`.
* `mfderiv_within I I' f s x` : the derivative of `f` at `x` within `s`, as a continuous linear map
from the tangent space at `x` to the tangent space at `f x`. If the map is not differentiable
within `s`, this is `0`.
* `mdifferentiable_at I I' f x` : Prop expressing whether `f` is differentiable at `x`.
* `mdifferentiable_within_at 𝕜 f s x` : Prop expressing whether `f` is differentiable within `s`
at `x`.
* `has_mfderiv_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative at `x`.
* `has_mfderiv_within_at I I' f s x f'` : Prop expressing whether `f` has `f'` as a derivative
within `s` at `x`.
* `mdifferentiable_on I I' f s` : Prop expressing that `f` is differentiable on the set `s`.
* `mdifferentiable I I' f` : Prop expressing that `f` is differentiable everywhere.
* `tangent_map I I' f` : the derivative of `f`, as a map from the tangent bundle of `M` to the
tangent bundle of `M'`.
We also establish results on the differential of the identity, constant functions, charts, extended
charts. For functions between vector spaces, we show that the usual notions and the manifold notions
coincide.
## Implementation notes
The tangent bundle is constructed using the machinery of topological fiber bundles, for which one
can define bundled morphisms and construct canonically maps from the total space of one bundle to
the total space of another one. One could use this mechanism to construct directly the derivative
of a smooth map. However, we want to define the derivative of any map (and let it be zero if the map
is not differentiable) to avoid proof arguments everywhere. This means we have to go back to the
details of the definition of the total space of a fiber bundle constructed from core, to cook up a
suitable definition of the derivative. It is the following: at each point, we have a preferred chart
(used to identify the fiber above the point with the model vector space in fiber bundles). Then one
should read the function using these preferred charts at `x` and `f x`, and take the derivative
of `f` in these charts.
Due to the fact that we are working in a model with corners, with an additional embedding `I` of the
model space `H` in the model vector space `E`, the charts taking values in `E` are not the original
charts of the manifold, but those ones composed with `I`, called extended charts. We define
`written_in_ext_chart I I' x f` for the function `f` written in the preferred extended charts. Then
the manifold derivative of `f`, at `x`, is just the usual derivative of
`written_in_ext_chart I I' x f`, at the point `(ext_chart_at I x) x`.
There is a subtelty with respect to continuity: if the function is not continuous, then the image
of a small open set around `x` will not be contained in the source of the preferred chart around
`f x`, which means that when reading `f` in the chart one is losing some information. To avoid this,
we include continuity in the definition of differentiablity (which is reasonable since with any
definition, differentiability implies continuity).
*Warning*: the derivative (even within a subset) is a linear map on the whole tangent space. Suppose
that one is given a smooth submanifold `N`, and a function which is smooth on `N` (i.e., its
restriction to the subtype `N` is smooth). Then, in the whole manifold `M`, the property
`mdifferentiable_on I I' f N` holds. However, `mfderiv_within I I' f N` is not uniquely defined
(what values would one choose for vectors that are transverse to `N`?), which can create issues down
the road. The problem here is that knowing the value of `f` along `N` does not determine the
differential of `f` in all directions. This is in contrast to the case where `N` would be an open
subset, or a submanifold with boundary of maximal dimension, where this issue does not appear.
The predicate `unique_mdiff_on I N` indicates that the derivative along `N` is unique if it exists,
and is an assumption in most statements requiring a form of uniqueness.
On a vector space, the manifold derivative and the usual derivative are equal. This means in
particular that they live on the same space, i.e., the tangent space is defeq to the original vector
space. To get this property is a motivation for our definition of the tangent space as a single
copy of the vector space, instead of more usual definitions such as the space of derivations, or
the space of equivalence classes of smooth curves in the manifold.
## Tags
Derivative, manifold
-/
noncomputable theory
open_locale classical topology manifold bundle
open set bundle
universe u
section derivatives_definitions
/-!
### Derivative of maps between manifolds
The derivative of a smooth map `f` between smooth manifold `M` and `M'` at `x` is a bounded linear
map from the tangent space to `M` at `x`, to the tangent space to `M'` at `f x`. Since we defined
the tangent space using one specific chart, the formula for the derivative is written in terms of
this specific chart.
We use the names `mdifferentiable` and `mfderiv`, where the prefix letter `m` means "manifold".
-/
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M] [charted_space H M]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H')
{M' : Type*} [topological_space M'] [charted_space H' M']
/-- Property in the model space of a model with corners of being differentiable within at set at a
point, when read in the model vector space. This property will be lifted to manifolds to define
differentiable functions between manifolds. -/
def differentiable_within_at_prop (f : H → H') (s : set H) (x : H) : Prop :=
differentiable_within_at 𝕜 (I' ∘ f ∘ (I.symm)) (⇑(I.symm) ⁻¹' s ∩ set.range I) (I x)
/-- Being differentiable in the model space is a local property, invariant under smooth maps.
Therefore, it will lift nicely to manifolds. -/
lemma differentiable_within_at_local_invariant_prop :
(cont_diff_groupoid ⊤ I).local_invariant_prop (cont_diff_groupoid ⊤ I')
(differentiable_within_at_prop I I') :=
{ is_local :=
begin
assume s x u f u_open xu,
have : I.symm ⁻¹' (s ∩ u) ∩ set.range I = (I.symm ⁻¹' s ∩ set.range I) ∩ I.symm ⁻¹' u,
by simp only [set.inter_right_comm, set.preimage_inter],
rw [differentiable_within_at_prop, differentiable_within_at_prop, this],
symmetry,
apply differentiable_within_at_inter,
have : u ∈ 𝓝 (I.symm (I x)),
by { rw [model_with_corners.left_inv], exact is_open.mem_nhds u_open xu },
apply continuous_at.preimage_mem_nhds I.continuous_symm.continuous_at this,
end,
right_invariance' :=
begin
assume s x f e he hx h,
rw differentiable_within_at_prop at h ⊢,
have : I x = (I ∘ e.symm ∘ I.symm) (I (e x)), by simp only [hx] with mfld_simps,
rw this at h,
have : I (e x) ∈ (I.symm) ⁻¹' e.target ∩ set.range I, by simp only [hx] with mfld_simps,
have := ((mem_groupoid_of_pregroupoid.2 he).2.cont_diff_within_at this),
convert (h.comp' _ (this.differentiable_within_at le_top)).mono_of_mem _ using 1,
{ ext y, simp only with mfld_simps },
refine mem_nhds_within.mpr ⟨I.symm ⁻¹' e.target, e.open_target.preimage I.continuous_symm,
by simp_rw [set.mem_preimage, I.left_inv, e.maps_to hx], _⟩,
mfld_set_tac
end,
congr_of_forall :=
begin
assume s x f g h hx hf,
apply hf.congr,
{ assume y hy,
simp only with mfld_simps at hy,
simp only [h, hy] with mfld_simps },
{ simp only [hx] with mfld_simps }
end,
left_invariance' :=
begin
assume s x f e' he' hs hx h,
rw differentiable_within_at_prop at h ⊢,
have A : (I' ∘ f ∘ I.symm) (I x) ∈ (I'.symm ⁻¹' e'.source ∩ set.range I'),
by simp only [hx] with mfld_simps,
have := ((mem_groupoid_of_pregroupoid.2 he').1.cont_diff_within_at A),
convert (this.differentiable_within_at le_top).comp _ h _,
{ ext y, simp only with mfld_simps },
{ assume y hy, simp only with mfld_simps at hy, simpa only [hy] with mfld_simps using hs hy.1 }
end }
/-- Predicate ensuring that, at a point and within a set, a function can have at most one
derivative. This is expressed using the preferred chart at the considered point. -/
def unique_mdiff_within_at (s : set M) (x : M) :=
unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x)
/-- Predicate ensuring that, at all points of a set, a function can have at most one derivative. -/
def unique_mdiff_on (s : set M) :=
∀x∈s, unique_mdiff_within_at I s x
/-- `mdifferentiable_within_at I I' f s x` indicates that the function `f` between manifolds
has a derivative at the point `x` within the set `s`.
This is a generalization of `differentiable_within_at` to manifolds.
We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by
`f` outside of the chart domain around `f x`. Then the chart could do anything to the image points,
and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while
this would not mean anything relevant. -/
def mdifferentiable_within_at (f : M → M') (s : set M) (x : M) :=
continuous_within_at f s x ∧
differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f)
((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x)
lemma mdifferentiable_within_at_iff_lift_prop_within_at (f : M → M') (s : set M) (x : M) :
mdifferentiable_within_at I I' f s x
↔ lift_prop_within_at (differentiable_within_at_prop I I') f s x :=
by refl
/-- `mdifferentiable_at I I' f x` indicates that the function `f` between manifolds
has a derivative at the point `x`.
This is a generalization of `differentiable_at` to manifolds.
We require continuity in the definition, as otherwise points close to `x` could be sent by
`f` outside of the chart domain around `f x`. Then the chart could do anything to the image points,
and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while
this would not mean anything relevant. -/
def mdifferentiable_at (f : M → M') (x : M) :=
continuous_at f x ∧
differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f) (range I)
((ext_chart_at I x) x)
lemma mdifferentiable_at_iff_lift_prop_at (f : M → M') (x : M) :
mdifferentiable_at I I' f x
↔ lift_prop_at (differentiable_within_at_prop I I') f x :=
begin
congrm _ ∧ _,
{ rw continuous_within_at_univ },
{ simp [differentiable_within_at_prop, set.univ_inter] }
end
/-- `mdifferentiable_on I I' f s` indicates that the function `f` between manifolds
has a derivative within `s` at all points of `s`.
This is a generalization of `differentiable_on` to manifolds. -/
def mdifferentiable_on (f : M → M') (s : set M) :=
∀x ∈ s, mdifferentiable_within_at I I' f s x
/-- `mdifferentiable I I' f` indicates that the function `f` between manifolds
has a derivative everywhere.
This is a generalization of `differentiable` to manifolds. -/
def mdifferentiable (f : M → M') :=
∀x, mdifferentiable_at I I' f x
/-- Prop registering if a local homeomorphism is a local diffeomorphism on its source -/
def local_homeomorph.mdifferentiable (f : local_homeomorph M M') :=
(mdifferentiable_on I I' f f.source) ∧ (mdifferentiable_on I' I f.symm f.target)
variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M']
/-- `has_mfderiv_within_at I I' f s x f'` indicates that the function `f` between manifolds
has, at the point `x` and within the set `s`, the derivative `f'`. Here, `f'` is a continuous linear
map from the tangent space at `x` to the tangent space at `f x`.
This is a generalization of `has_fderiv_within_at` to manifolds (as indicated by the prefix `m`).
The order of arguments is changed as the type of the derivative `f'` depends on the choice of `x`.
We require continuity in the definition, as otherwise points close to `x` in `s` could be sent by
`f` outside of the chart domain around `f x`. Then the chart could do anything to the image points,
and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while
this would not mean anything relevant. -/
def has_mfderiv_within_at (f : M → M') (s : set M) (x : M)
(f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) :=
continuous_within_at f s x ∧
has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f'
((ext_chart_at I x).symm ⁻¹' s ∩ range I) ((ext_chart_at I x) x)
/-- `has_mfderiv_at I I' f x f'` indicates that the function `f` between manifolds
has, at the point `x`, the derivative `f'`. Here, `f'` is a continuous linear
map from the tangent space at `x` to the tangent space at `f x`.
We require continuity in the definition, as otherwise points close to `x` `s` could be sent by
`f` outside of the chart domain around `f x`. Then the chart could do anything to the image points,
and in particular by coincidence `written_in_ext_chart_at I I' x f` could be differentiable, while
this would not mean anything relevant. -/
def has_mfderiv_at (f : M → M') (x : M)
(f' : tangent_space I x →L[𝕜] tangent_space I' (f x)) :=
continuous_at f x ∧
has_fderiv_within_at (written_in_ext_chart_at I I' x f : E → E') f' (range I)
((ext_chart_at I x) x)
/-- Let `f` be a function between two smooth manifolds. Then `mfderiv_within I I' f s x` is the
derivative of `f` at `x` within `s`, as a continuous linear map from the tangent space at `x` to the
tangent space at `f x`. -/
def mfderiv_within (f : M → M') (s : set M) (x : M) :
tangent_space I x →L[𝕜] tangent_space I' (f x) :=
if mdifferentiable_within_at I I' f s x then
(fderiv_within 𝕜 (written_in_ext_chart_at I I' x f) ((ext_chart_at I x).symm ⁻¹' s ∩ range I)
((ext_chart_at I x) x) : _)
else 0
/-- Let `f` be a function between two smooth manifolds. Then `mfderiv I I' f x` is the derivative of
`f` at `x`, as a continuous linear map from the tangent space at `x` to the tangent space at
`f x`. -/
def mfderiv (f : M → M') (x : M) : tangent_space I x →L[𝕜] tangent_space I' (f x) :=
if mdifferentiable_at I I' f x then
(fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : E → E') (range I)
((ext_chart_at I x) x) : _)
else 0
/-- The derivative within a set, as a map between the tangent bundles -/
def tangent_map_within (f : M → M') (s : set M) : tangent_bundle I M → tangent_bundle I' M' :=
λp, ⟨f p.1, (mfderiv_within I I' f s p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩
/-- The derivative, as a map between the tangent bundles -/
def tangent_map (f : M → M') : tangent_bundle I M → tangent_bundle I' M' :=
λp, ⟨f p.1, (mfderiv I I' f p.1 : tangent_space I p.1 → tangent_space I' (f p.1)) p.2⟩
end derivatives_definitions
section derivatives_properties
/-! ### Unique differentiability sets in manifolds -/
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M] [charted_space H M] --
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{M' : Type*} [topological_space M'] [charted_space H' M']
{E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E'']
{H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''}
{M'' : Type*} [topological_space M''] [charted_space H'' M'']
{f f₀ f₁ : M → M'}
{x : M}
{s t : set M}
{g : M' → M''}
{u : set M'}
lemma unique_mdiff_within_at_univ : unique_mdiff_within_at I univ x :=
begin
unfold unique_mdiff_within_at,
simp only [preimage_univ, univ_inter],
exact I.unique_diff _ (mem_range_self _)
end
variable {I}
lemma unique_mdiff_within_at_iff {s : set M} {x : M} :
unique_mdiff_within_at I s x ↔
unique_diff_within_at 𝕜 ((ext_chart_at I x).symm ⁻¹' s ∩ (ext_chart_at I x).target)
((ext_chart_at I x) x) :=
begin
apply unique_diff_within_at_congr,
rw [nhds_within_inter, nhds_within_inter, nhds_within_ext_chart_at_target_eq]
end
lemma unique_mdiff_within_at.mono (h : unique_mdiff_within_at I s x) (st : s ⊆ t) :
unique_mdiff_within_at I t x :=
unique_diff_within_at.mono h $ inter_subset_inter (preimage_mono st) (subset.refl _)
lemma unique_mdiff_within_at.inter' (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝[s] x) :
unique_mdiff_within_at I (s ∩ t) x :=
begin
rw [unique_mdiff_within_at, ext_chart_at_preimage_inter_eq],
exact unique_diff_within_at.inter' hs (ext_chart_at_preimage_mem_nhds_within I x ht)
end
lemma unique_mdiff_within_at.inter (hs : unique_mdiff_within_at I s x) (ht : t ∈ 𝓝 x) :
unique_mdiff_within_at I (s ∩ t) x :=
begin
rw [unique_mdiff_within_at, ext_chart_at_preimage_inter_eq],
exact unique_diff_within_at.inter hs (ext_chart_at_preimage_mem_nhds I x ht)
end
lemma is_open.unique_mdiff_within_at (xs : x ∈ s) (hs : is_open s) : unique_mdiff_within_at I s x :=
begin
have := unique_mdiff_within_at.inter (unique_mdiff_within_at_univ I) (is_open.mem_nhds hs xs),
rwa univ_inter at this
end
lemma unique_mdiff_on.inter (hs : unique_mdiff_on I s) (ht : is_open t) :
unique_mdiff_on I (s ∩ t) :=
λx hx, unique_mdiff_within_at.inter (hs _ hx.1) (is_open.mem_nhds ht hx.2)
lemma is_open.unique_mdiff_on (hs : is_open s) : unique_mdiff_on I s :=
λx hx, is_open.unique_mdiff_within_at hx hs
lemma unique_mdiff_on_univ : unique_mdiff_on I (univ : set M) :=
is_open_univ.unique_mdiff_on
/- We name the typeclass variables related to `smooth_manifold_with_corners` structure as they are
necessary in lemmas mentioning the derivative, but not in lemmas about differentiability, so we
want to include them or omit them when necessary. -/
variables [Is : smooth_manifold_with_corners I M] [I's : smooth_manifold_with_corners I' M']
[I''s : smooth_manifold_with_corners I'' M'']
{f' f₀' f₁' : tangent_space I x →L[𝕜] tangent_space I' (f x)}
{g' : tangent_space I' (f x) →L[𝕜] tangent_space I'' (g (f x))}
/-- `unique_mdiff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/
theorem unique_mdiff_within_at.eq (U : unique_mdiff_within_at I s x)
(h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') :
f' = f₁' :=
U.eq h.2 h₁.2
theorem unique_mdiff_on.eq (U : unique_mdiff_on I s) (hx : x ∈ s)
(h : has_mfderiv_within_at I I' f s x f') (h₁ : has_mfderiv_within_at I I' f s x f₁') :
f' = f₁' :=
unique_mdiff_within_at.eq (U _ hx) h h₁
/-!
### General lemmas on derivatives of functions between manifolds
We mimick the API for functions between vector spaces
-/
lemma mdifferentiable_within_at_iff {f : M → M'} {s : set M} {x : M} :
mdifferentiable_within_at I I' f s x ↔
continuous_within_at f s x ∧
differentiable_within_at 𝕜 (written_in_ext_chart_at I I' x f)
((ext_chart_at I x).target ∩ (ext_chart_at I x).symm ⁻¹' s) ((ext_chart_at I x) x) :=
begin
refine and_congr iff.rfl (exists_congr $ λ f', _),
rw [inter_comm],
simp only [has_fderiv_within_at, nhds_within_inter, nhds_within_ext_chart_at_target_eq]
end
include Is I's
/-- One can reformulate differentiability within a set at a point as continuity within this set at
this point, and differentiability in any chart containing that point. -/
lemma mdifferentiable_within_at_iff_of_mem_source
{x' : M} {y : M'}
(hx : x' ∈ (charted_space.chart_at H x).source)
(hy : f x' ∈ (charted_space.chart_at H' y).source) :
mdifferentiable_within_at I I' f s x'
↔ continuous_within_at f s x'
∧ differentiable_within_at 𝕜
((ext_chart_at I' y) ∘ f ∘ ((ext_chart_at I x).symm))
(((ext_chart_at I x).symm) ⁻¹' s ∩ set.range I)
((ext_chart_at I x) x') :=
(differentiable_within_at_local_invariant_prop I I').lift_prop_within_at_indep_chart
(structure_groupoid.chart_mem_maximal_atlas _ x) hx
(structure_groupoid.chart_mem_maximal_atlas _ y) hy
lemma mfderiv_within_zero_of_not_mdifferentiable_within_at
(h : ¬ mdifferentiable_within_at I I' f s x) : mfderiv_within I I' f s x = 0 :=
by simp only [mfderiv_within, h, if_neg, not_false_iff]
lemma mfderiv_zero_of_not_mdifferentiable_at
(h : ¬ mdifferentiable_at I I' f x) : mfderiv I I' f x = 0 :=
by simp only [mfderiv, h, if_neg, not_false_iff]
theorem has_mfderiv_within_at.mono (h : has_mfderiv_within_at I I' f t x f') (hst : s ⊆ t) :
has_mfderiv_within_at I I' f s x f' :=
⟨ continuous_within_at.mono h.1 hst,
has_fderiv_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩
theorem has_mfderiv_at.has_mfderiv_within_at
(h : has_mfderiv_at I I' f x f') : has_mfderiv_within_at I I' f s x f' :=
⟨ continuous_at.continuous_within_at h.1, has_fderiv_within_at.mono h.2 (inter_subset_right _ _) ⟩
lemma has_mfderiv_within_at.mdifferentiable_within_at (h : has_mfderiv_within_at I I' f s x f') :
mdifferentiable_within_at I I' f s x :=
⟨h.1, ⟨f', h.2⟩⟩
lemma has_mfderiv_at.mdifferentiable_at (h : has_mfderiv_at I I' f x f') :
mdifferentiable_at I I' f x :=
⟨h.1, ⟨f', h.2⟩⟩
@[simp, mfld_simps] lemma has_mfderiv_within_at_univ :
has_mfderiv_within_at I I' f univ x f' ↔ has_mfderiv_at I I' f x f' :=
by simp only [has_mfderiv_within_at, has_mfderiv_at, continuous_within_at_univ] with mfld_simps
theorem has_mfderiv_at_unique
(h₀ : has_mfderiv_at I I' f x f₀') (h₁ : has_mfderiv_at I I' f x f₁') : f₀' = f₁' :=
begin
rw ← has_mfderiv_within_at_univ at h₀ h₁,
exact (unique_mdiff_within_at_univ I).eq h₀ h₁
end
lemma has_mfderiv_within_at_inter' (h : t ∈ 𝓝[s] x) :
has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' :=
begin
rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_at_preimage_inter_eq,
has_fderiv_within_at_inter', continuous_within_at_inter' h],
exact ext_chart_at_preimage_mem_nhds_within I x h,
end
lemma has_mfderiv_within_at_inter (h : t ∈ 𝓝 x) :
has_mfderiv_within_at I I' f (s ∩ t) x f' ↔ has_mfderiv_within_at I I' f s x f' :=
begin
rw [has_mfderiv_within_at, has_mfderiv_within_at, ext_chart_at_preimage_inter_eq,
has_fderiv_within_at_inter, continuous_within_at_inter h],
exact ext_chart_at_preimage_mem_nhds I x h,
end
lemma has_mfderiv_within_at.union
(hs : has_mfderiv_within_at I I' f s x f') (ht : has_mfderiv_within_at I I' f t x f') :
has_mfderiv_within_at I I' f (s ∪ t) x f' :=
begin
split,
{ exact continuous_within_at.union hs.1 ht.1 },
{ convert has_fderiv_within_at.union hs.2 ht.2,
simp only [union_inter_distrib_right, preimage_union] }
end
lemma has_mfderiv_within_at.nhds_within (h : has_mfderiv_within_at I I' f s x f')
(ht : s ∈ 𝓝[t] x) : has_mfderiv_within_at I I' f t x f' :=
(has_mfderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
lemma has_mfderiv_within_at.has_mfderiv_at (h : has_mfderiv_within_at I I' f s x f')
(hs : s ∈ 𝓝 x) :
has_mfderiv_at I I' f x f' :=
by rwa [← univ_inter s, has_mfderiv_within_at_inter hs, has_mfderiv_within_at_univ] at h
lemma mdifferentiable_within_at.has_mfderiv_within_at (h : mdifferentiable_within_at I I' f s x) :
has_mfderiv_within_at I I' f s x (mfderiv_within I I' f s x) :=
begin
refine ⟨h.1, _⟩,
simp only [mfderiv_within, h, if_pos] with mfld_simps,
exact differentiable_within_at.has_fderiv_within_at h.2
end
lemma mdifferentiable_within_at.mfderiv_within (h : mdifferentiable_within_at I I' f s x) :
(mfderiv_within I I' f s x) =
fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) ((ext_chart_at I x).symm ⁻¹' s ∩ range I)
((ext_chart_at I x) x) :=
by simp only [mfderiv_within, h, if_pos]
lemma mdifferentiable_at.has_mfderiv_at (h : mdifferentiable_at I I' f x) :
has_mfderiv_at I I' f x (mfderiv I I' f x) :=
begin
refine ⟨h.1, _⟩,
simp only [mfderiv, h, if_pos] with mfld_simps,
exact differentiable_within_at.has_fderiv_within_at h.2
end
lemma mdifferentiable_at.mfderiv (h : mdifferentiable_at I I' f x) :
(mfderiv I I' f x) =
fderiv_within 𝕜 (written_in_ext_chart_at I I' x f : _) (range I) ((ext_chart_at I x) x) :=
by simp only [mfderiv, h, if_pos]
lemma has_mfderiv_at.mfderiv (h : has_mfderiv_at I I' f x f') :
mfderiv I I' f x = f' :=
(has_mfderiv_at_unique h h.mdifferentiable_at.has_mfderiv_at).symm
lemma has_mfderiv_within_at.mfderiv_within
(h : has_mfderiv_within_at I I' f s x f') (hxs : unique_mdiff_within_at I s x) :
mfderiv_within I I' f s x = f' :=
by { ext, rw hxs.eq h h.mdifferentiable_within_at.has_mfderiv_within_at }
lemma mdifferentiable.mfderiv_within
(h : mdifferentiable_at I I' f x) (hxs : unique_mdiff_within_at I s x) :
mfderiv_within I I' f s x = mfderiv I I' f x :=
begin
apply has_mfderiv_within_at.mfderiv_within _ hxs,
exact h.has_mfderiv_at.has_mfderiv_within_at
end
lemma mfderiv_within_subset (st : s ⊆ t) (hs : unique_mdiff_within_at I s x)
(h : mdifferentiable_within_at I I' f t x) :
mfderiv_within I I' f s x = mfderiv_within I I' f t x :=
((mdifferentiable_within_at.has_mfderiv_within_at h).mono st).mfderiv_within hs
omit Is I's
lemma mdifferentiable_within_at.mono (hst : s ⊆ t)
(h : mdifferentiable_within_at I I' f t x) : mdifferentiable_within_at I I' f s x :=
⟨ continuous_within_at.mono h.1 hst,
differentiable_within_at.mono h.2 (inter_subset_inter (preimage_mono hst) (subset.refl _)) ⟩
lemma mdifferentiable_within_at_univ :
mdifferentiable_within_at I I' f univ x ↔ mdifferentiable_at I I' f x :=
by simp only [mdifferentiable_within_at, mdifferentiable_at, continuous_within_at_univ]
with mfld_simps
lemma mdifferentiable_within_at_inter (ht : t ∈ 𝓝 x) :
mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x :=
begin
rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_at_preimage_inter_eq,
differentiable_within_at_inter, continuous_within_at_inter ht],
exact ext_chart_at_preimage_mem_nhds I x ht
end
lemma mdifferentiable_within_at_inter' (ht : t ∈ 𝓝[s] x) :
mdifferentiable_within_at I I' f (s ∩ t) x ↔ mdifferentiable_within_at I I' f s x :=
begin
rw [mdifferentiable_within_at, mdifferentiable_within_at, ext_chart_at_preimage_inter_eq,
differentiable_within_at_inter', continuous_within_at_inter' ht],
exact ext_chart_at_preimage_mem_nhds_within I x ht
end
lemma mdifferentiable_at.mdifferentiable_within_at
(h : mdifferentiable_at I I' f x) : mdifferentiable_within_at I I' f s x :=
mdifferentiable_within_at.mono (subset_univ _) (mdifferentiable_within_at_univ.2 h)
lemma mdifferentiable_within_at.mdifferentiable_at
(h : mdifferentiable_within_at I I' f s x) (hs : s ∈ 𝓝 x) : mdifferentiable_at I I' f x :=
begin
have : s = univ ∩ s, by rw univ_inter,
rwa [this, mdifferentiable_within_at_inter hs, mdifferentiable_within_at_univ] at h,
end
lemma mdifferentiable_on.mono
(h : mdifferentiable_on I I' f t) (st : s ⊆ t) : mdifferentiable_on I I' f s :=
λx hx, (h x (st hx)).mono st
lemma mdifferentiable_on_univ :
mdifferentiable_on I I' f univ ↔ mdifferentiable I I' f :=
by { simp only [mdifferentiable_on, mdifferentiable_within_at_univ] with mfld_simps, refl }
lemma mdifferentiable.mdifferentiable_on
(h : mdifferentiable I I' f) : mdifferentiable_on I I' f s :=
(mdifferentiable_on_univ.2 h).mono (subset_univ _)
lemma mdifferentiable_on_of_locally_mdifferentiable_on
(h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ mdifferentiable_on I I' f (s ∩ u)) :
mdifferentiable_on I I' f s :=
begin
assume x xs,
rcases h x xs with ⟨t, t_open, xt, ht⟩,
exact (mdifferentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 (ht x ⟨xs, xt⟩)
end
include Is I's
@[simp, mfld_simps] lemma mfderiv_within_univ : mfderiv_within I I' f univ = mfderiv I I' f :=
begin
ext x : 1,
simp only [mfderiv_within, mfderiv] with mfld_simps,
rw mdifferentiable_within_at_univ
end
lemma mfderiv_within_inter (ht : t ∈ 𝓝 x) :
mfderiv_within I I' f (s ∩ t) x = mfderiv_within I I' f s x :=
by rw [mfderiv_within, mfderiv_within, ext_chart_at_preimage_inter_eq,
mdifferentiable_within_at_inter ht,
fderiv_within_inter (ext_chart_at_preimage_mem_nhds I x ht)]
lemma mdifferentiable_at_iff_of_mem_source {x' : M} {y : M'}
(hx : x' ∈ (charted_space.chart_at H x).source)
(hy : f x' ∈ (charted_space.chart_at H' y).source) :
mdifferentiable_at I I' f x'
↔ continuous_at f x'
∧ differentiable_within_at 𝕜
((ext_chart_at I' y) ∘ f ∘ ((ext_chart_at I x).symm))
(set.range I)
((ext_chart_at I x) x') :=
mdifferentiable_within_at_univ.symm.trans $
(mdifferentiable_within_at_iff_of_mem_source hx hy).trans $
by rw [continuous_within_at_univ, set.preimage_univ, set.univ_inter]
omit Is I's
/-! ### Deriving continuity from differentiability on manifolds -/
theorem has_mfderiv_within_at.continuous_within_at
(h : has_mfderiv_within_at I I' f s x f') : continuous_within_at f s x :=
h.1
theorem has_mfderiv_at.continuous_at (h : has_mfderiv_at I I' f x f') :
continuous_at f x :=
h.1
lemma mdifferentiable_within_at.continuous_within_at (h : mdifferentiable_within_at I I' f s x) :
continuous_within_at f s x :=
h.1
lemma mdifferentiable_at.continuous_at (h : mdifferentiable_at I I' f x) : continuous_at f x :=
h.1
lemma mdifferentiable_on.continuous_on (h : mdifferentiable_on I I' f s) : continuous_on f s :=
λx hx, (h x hx).continuous_within_at
lemma mdifferentiable.continuous (h : mdifferentiable I I' f) : continuous f :=
continuous_iff_continuous_at.2 $ λx, (h x).continuous_at
include Is I's
lemma tangent_map_within_subset {p : tangent_bundle I M}
(st : s ⊆ t) (hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_within_at I I' f t p.1) :
tangent_map_within I I' f s p = tangent_map_within I I' f t p :=
begin
simp only [tangent_map_within] with mfld_simps,
rw mfderiv_within_subset st hs h,
end
lemma tangent_map_within_univ :
tangent_map_within I I' f univ = tangent_map I I' f :=
by { ext p : 1, simp only [tangent_map_within, tangent_map] with mfld_simps }
lemma tangent_map_within_eq_tangent_map {p : tangent_bundle I M}
(hs : unique_mdiff_within_at I s p.1) (h : mdifferentiable_at I I' f p.1) :
tangent_map_within I I' f s p = tangent_map I I' f p :=
begin
rw ← mdifferentiable_within_at_univ at h,
rw ← tangent_map_within_univ,
exact tangent_map_within_subset (subset_univ _) hs h,
end
@[simp, mfld_simps] lemma tangent_map_within_proj {p : tangent_bundle I M} :
(tangent_map_within I I' f s p).proj = f p.proj := rfl
@[simp, mfld_simps] lemma tangent_map_proj {p : tangent_bundle I M} :
(tangent_map I I' f p).proj = f p.proj := rfl
omit Is I's
lemma mdifferentiable_within_at.prod_mk {f : M → M'} {g : M → M''}
(hf : mdifferentiable_within_at I I' f s x)
(hg : mdifferentiable_within_at I I'' g s x) :
mdifferentiable_within_at I (I'.prod I'') (λ x, (f x, g x)) s x :=
⟨hf.1.prod hg.1, hf.2.prod hg.2⟩
lemma mdifferentiable_at.prod_mk {f : M → M'} {g : M → M''}
(hf : mdifferentiable_at I I' f x)
(hg : mdifferentiable_at I I'' g x) :
mdifferentiable_at I (I'.prod I'') (λ x, (f x, g x)) x :=
⟨hf.1.prod hg.1, hf.2.prod hg.2⟩
lemma mdifferentiable_on.prod_mk {f : M → M'} {g : M → M''}
(hf : mdifferentiable_on I I' f s)
(hg : mdifferentiable_on I I'' g s) :
mdifferentiable_on I (I'.prod I'') (λ x, (f x, g x)) s :=
λ x hx, (hf x hx).prod_mk (hg x hx)
lemma mdifferentiable.prod_mk {f : M → M'} {g : M → M''}
(hf : mdifferentiable I I' f)
(hg : mdifferentiable I I'' g) :
mdifferentiable I (I'.prod I'') (λ x, (f x, g x)) :=
λ x, (hf x).prod_mk (hg x)
lemma mdifferentiable_within_at.prod_mk_space {f : M → E'} {g : M → E''}
(hf : mdifferentiable_within_at I 𝓘(𝕜, E') f s x)
(hg : mdifferentiable_within_at I 𝓘(𝕜, E'') g s x) :
mdifferentiable_within_at I 𝓘(𝕜, E' × E'') (λ x, (f x, g x)) s x :=
⟨hf.1.prod hg.1, hf.2.prod hg.2⟩
lemma mdifferentiable_at.prod_mk_space {f : M → E'} {g : M → E''}
(hf : mdifferentiable_at I 𝓘(𝕜, E') f x)
(hg : mdifferentiable_at I 𝓘(𝕜, E'') g x) :
mdifferentiable_at I 𝓘(𝕜, E' × E'') (λ x, (f x, g x)) x :=
⟨hf.1.prod hg.1, hf.2.prod hg.2⟩
lemma mdifferentiable_on.prod_mk_space {f : M → E'} {g : M → E''}
(hf : mdifferentiable_on I 𝓘(𝕜, E') f s)
(hg : mdifferentiable_on I 𝓘(𝕜, E'') g s) :
mdifferentiable_on I 𝓘(𝕜, E' × E'') (λ x, (f x, g x)) s :=
λ x hx, (hf x hx).prod_mk_space (hg x hx)
lemma mdifferentiable.prod_mk_space {f : M → E'} {g : M → E''}
(hf : mdifferentiable I 𝓘(𝕜, E') f)
(hg : mdifferentiable I 𝓘(𝕜, E'') g) :
mdifferentiable I 𝓘(𝕜, E' × E'') (λ x, (f x, g x)) :=
λ x, (hf x).prod_mk_space (hg x)
/-! ### Congruence lemmas for derivatives on manifolds -/
lemma has_mfderiv_within_at.congr_of_eventually_eq (h : has_mfderiv_within_at I I' f s x f')
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_mfderiv_within_at I I' f₁ s x f' :=
begin
refine ⟨continuous_within_at.congr_of_eventually_eq h.1 h₁ hx, _⟩,
apply has_fderiv_within_at.congr_of_eventually_eq h.2,
{ have : (ext_chart_at I x).symm ⁻¹' {y | f₁ y = f y} ∈
𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) :=
ext_chart_at_preimage_mem_nhds_within I x h₁,
apply filter.mem_of_superset this (λy, _),
simp only [hx] with mfld_simps {contextual := tt} },
{ simp only [hx] with mfld_simps },
end
lemma has_mfderiv_within_at.congr_mono (h : has_mfderiv_within_at I I' f s x f')
(ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) :
has_mfderiv_within_at I I' f₁ t x f' :=
(h.mono h₁).congr_of_eventually_eq (filter.mem_inf_of_right ht) hx
lemma has_mfderiv_at.congr_of_eventually_eq (h : has_mfderiv_at I I' f x f')
(h₁ : f₁ =ᶠ[𝓝 x] f) : has_mfderiv_at I I' f₁ x f' :=
begin
rw ← has_mfderiv_within_at_univ at ⊢ h,
apply h.congr_of_eventually_eq _ (mem_of_mem_nhds h₁ : _),
rwa nhds_within_univ
end
include Is I's
lemma mdifferentiable_within_at.congr_of_eventually_eq
(h : mdifferentiable_within_at I I' f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f)
(hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x :=
(h.has_mfderiv_within_at.congr_of_eventually_eq h₁ hx).mdifferentiable_within_at
variables (I I')
lemma filter.eventually_eq.mdifferentiable_within_at_iff
(h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
mdifferentiable_within_at I I' f s x ↔ mdifferentiable_within_at I I' f₁ s x :=
begin
split,
{ assume h,
apply h.congr_of_eventually_eq h₁ hx },
{ assume h,
apply h.congr_of_eventually_eq _ hx.symm,
apply h₁.mono,
intro y,
apply eq.symm }
end
variables {I I'}
lemma mdifferentiable_within_at.congr_mono (h : mdifferentiable_within_at I I' f s x)
(ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) :
mdifferentiable_within_at I I' f₁ t x :=
(has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx h₁).mdifferentiable_within_at
lemma mdifferentiable_within_at.congr (h : mdifferentiable_within_at I I' f s x)
(ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : mdifferentiable_within_at I I' f₁ s x :=
(has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at ht hx
(subset.refl _)).mdifferentiable_within_at
lemma mdifferentiable_on.congr_mono (h : mdifferentiable_on I I' f s) (h' : ∀x ∈ t, f₁ x = f x)
(h₁ : t ⊆ s) : mdifferentiable_on I I' f₁ t :=
λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁
lemma mdifferentiable_at.congr_of_eventually_eq (h : mdifferentiable_at I I' f x)
(hL : f₁ =ᶠ[𝓝 x] f) : mdifferentiable_at I I' f₁ x :=
((h.has_mfderiv_at).congr_of_eventually_eq hL).mdifferentiable_at
lemma mdifferentiable_within_at.mfderiv_within_congr_mono (h : mdifferentiable_within_at I I' f s x)
(hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_mdiff_within_at I t x) (h₁ : t ⊆ s) :
mfderiv_within I I' f₁ t x = (mfderiv_within I I' f s x : _) :=
(has_mfderiv_within_at.congr_mono h.has_mfderiv_within_at hs hx h₁).mfderiv_within hxt
lemma filter.eventually_eq.mfderiv_within_eq (hs : unique_mdiff_within_at I s x)
(hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) :
mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) :=
begin
by_cases h : mdifferentiable_within_at I I' f s x,
{ exact ((h.has_mfderiv_within_at).congr_of_eventually_eq hL hx).mfderiv_within hs },
{ unfold mfderiv_within,
rw [if_neg h, if_neg],
rwa ← hL.mdifferentiable_within_at_iff I I' hx }
end
lemma mfderiv_within_congr (hs : unique_mdiff_within_at I s x)
(hL : ∀ x ∈ s, f₁ x = f x) (hx : f₁ x = f x) :
mfderiv_within I I' f₁ s x = (mfderiv_within I I' f s x : _) :=
filter.eventually_eq.mfderiv_within_eq hs (filter.eventually_eq_of_mem (self_mem_nhds_within) hL) hx
lemma tangent_map_within_congr (h : ∀ x ∈ s, f x = f₁ x)
(p : tangent_bundle I M) (hp : p.1 ∈ s) (hs : unique_mdiff_within_at I s p.1) :
tangent_map_within I I' f s p = tangent_map_within I I' f₁ s p :=
begin
simp only [tangent_map_within, h p.1 hp, true_and, eq_self_iff_true, heq_iff_eq],
congr' 1,
exact mfderiv_within_congr hs h (h _ hp)
end
lemma filter.eventually_eq.mfderiv_eq (hL : f₁ =ᶠ[𝓝 x] f) :
mfderiv I I' f₁ x = (mfderiv I I' f x : _) :=
begin
have A : f₁ x = f x := (mem_of_mem_nhds hL : _),
rw [← mfderiv_within_univ, ← mfderiv_within_univ],
rw ← nhds_within_univ at hL,
exact hL.mfderiv_within_eq (unique_mdiff_within_at_univ I) A
end
/-- A congruence lemma for `mfderiv`, (ab)using the fact that `tangent_space I' (f x)` is
definitionally equal to `E'`. -/
lemma mfderiv_congr_point {x' : M} (h : x = x') :
@eq (E →L[𝕜] E') (mfderiv I I' f x) (mfderiv I I' f x') :=
by subst h
/-- A congruence lemma for `mfderiv`, (ab)using the fact that `tangent_space I' (f x)` is
definitionally equal to `E'`. -/
lemma mfderiv_congr {f' : M → M'} (h : f = f') :
@eq (E →L[𝕜] E') (mfderiv I I' f x) (mfderiv I I' f' x) :=
by subst h
/-! ### Composition lemmas -/
omit Is I's
lemma written_in_ext_chart_comp (h : continuous_within_at f s x) :
{y | written_in_ext_chart_at I I'' x (g ∘ f) y
= ((written_in_ext_chart_at I' I'' (f x) g) ∘ (written_in_ext_chart_at I I' x f)) y}
∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) :=
begin
apply @filter.mem_of_superset _ _
((f ∘ (ext_chart_at I x).symm)⁻¹' (ext_chart_at I' (f x)).source) _
(ext_chart_at_preimage_mem_nhds_within I x
(h.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))),
mfld_set_tac,
end
variable (x)
include Is I's I''s
theorem has_mfderiv_within_at.comp
(hg : has_mfderiv_within_at I' I'' g u (f x) g') (hf : has_mfderiv_within_at I I' f s x f')
(hst : s ⊆ f ⁻¹' u) :
has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') :=
begin
refine ⟨continuous_within_at.comp hg.1 hf.1 hst, _⟩,
have A : has_fderiv_within_at ((written_in_ext_chart_at I' I'' (f x) g) ∘
(written_in_ext_chart_at I I' x f))
(continuous_linear_map.comp g' f' : E →L[𝕜] E'')
((ext_chart_at I x).symm ⁻¹' s ∩ range (I))
((ext_chart_at I x) x),
{ have : (ext_chart_at I x).symm ⁻¹' (f ⁻¹' (ext_chart_at I' (f x)).source)
∈ 𝓝[(ext_chart_at I x).symm ⁻¹' s ∩ range I] ((ext_chart_at I x) x) :=
(ext_chart_at_preimage_mem_nhds_within I x
(hf.1.preimage_mem_nhds_within (ext_chart_at_source_mem_nhds _ _))),
unfold has_mfderiv_within_at at *,
rw [← has_fderiv_within_at_inter' this, ← ext_chart_at_preimage_inter_eq] at hf ⊢,
have : written_in_ext_chart_at I I' x f ((ext_chart_at I x) x)
= (ext_chart_at I' (f x)) (f x),
by simp only with mfld_simps,
rw ← this at hg,
apply has_fderiv_within_at.comp ((ext_chart_at I x) x) hg.2 hf.2 _,
assume y hy,
simp only with mfld_simps at hy,
have : f (((chart_at H x).symm : H → M) (I.symm y)) ∈ u := hst hy.1.1,
simp only [hy, this] with mfld_simps },
apply A.congr_of_eventually_eq (written_in_ext_chart_comp hf.1),
simp only with mfld_simps
end
/-- The chain rule. -/
theorem has_mfderiv_at.comp
(hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_at I I' f x f') :
has_mfderiv_at I I'' (g ∘ f) x (g'.comp f') :=
begin
rw ← has_mfderiv_within_at_univ at *,
exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ
end
theorem has_mfderiv_at.comp_has_mfderiv_within_at
(hg : has_mfderiv_at I' I'' g (f x) g') (hf : has_mfderiv_within_at I I' f s x f') :
has_mfderiv_within_at I I'' (g ∘ f) s x (g'.comp f') :=
begin
rw ← has_mfderiv_within_at_univ at *,
exact has_mfderiv_within_at.comp x (hg.mono (subset_univ _)) hf subset_preimage_univ
end
lemma mdifferentiable_within_at.comp
(hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x)
(h : s ⊆ f ⁻¹' u) : mdifferentiable_within_at I I'' (g ∘ f) s x :=
begin
rcases hf.2 with ⟨f', hf'⟩,
have F : has_mfderiv_within_at I I' f s x f' := ⟨hf.1, hf'⟩,
rcases hg.2 with ⟨g', hg'⟩,
have G : has_mfderiv_within_at I' I'' g u (f x) g' := ⟨hg.1, hg'⟩,
exact (has_mfderiv_within_at.comp x G F h).mdifferentiable_within_at
end
lemma mdifferentiable_at.comp
(hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) :
mdifferentiable_at I I'' (g ∘ f) x :=
(hg.has_mfderiv_at.comp x hf.has_mfderiv_at).mdifferentiable_at
lemma mfderiv_within_comp
(hg : mdifferentiable_within_at I' I'' g u (f x)) (hf : mdifferentiable_within_at I I' f s x)
(h : s ⊆ f ⁻¹' u) (hxs : unique_mdiff_within_at I s x) :
mfderiv_within I I'' (g ∘ f) s x =
(mfderiv_within I' I'' g u (f x)).comp (mfderiv_within I I' f s x) :=
begin
apply has_mfderiv_within_at.mfderiv_within _ hxs,
exact has_mfderiv_within_at.comp x hg.has_mfderiv_within_at hf.has_mfderiv_within_at h
end
lemma mfderiv_comp
(hg : mdifferentiable_at I' I'' g (f x)) (hf : mdifferentiable_at I I' f x) :
mfderiv I I'' (g ∘ f) x = (mfderiv I' I'' g (f x)).comp (mfderiv I I' f x) :=
begin
apply has_mfderiv_at.mfderiv,
exact has_mfderiv_at.comp x hg.has_mfderiv_at hf.has_mfderiv_at
end
lemma mfderiv_comp_of_eq {x : M} {y : M'}
(hg : mdifferentiable_at I' I'' g y) (hf : mdifferentiable_at I I' f x) (hy : f x = y) :
mfderiv I I'' (g ∘ f) x = (mfderiv I' I'' g (f x)).comp (mfderiv I I' f x) :=
by { subst hy, exact mfderiv_comp x hg hf }
lemma mdifferentiable_on.comp
(hg : mdifferentiable_on I' I'' g u) (hf : mdifferentiable_on I I' f s) (st : s ⊆ f ⁻¹' u) :
mdifferentiable_on I I'' (g ∘ f) s :=
λx hx, mdifferentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st
lemma mdifferentiable.comp
(hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) : mdifferentiable I I'' (g ∘ f) :=
λx, mdifferentiable_at.comp x (hg (f x)) (hf x)
lemma tangent_map_within_comp_at (p : tangent_bundle I M)
(hg : mdifferentiable_within_at I' I'' g u (f p.1)) (hf : mdifferentiable_within_at I I' f s p.1)
(h : s ⊆ f ⁻¹' u) (hps : unique_mdiff_within_at I s p.1) :
tangent_map_within I I'' (g ∘ f) s p =
tangent_map_within I' I'' g u (tangent_map_within I I' f s p) :=
begin
simp only [tangent_map_within] with mfld_simps,
rw mfderiv_within_comp p.1 hg hf h hps,
refl
end
lemma tangent_map_comp_at (p : tangent_bundle I M)
(hg : mdifferentiable_at I' I'' g (f p.1)) (hf : mdifferentiable_at I I' f p.1) :
tangent_map I I'' (g ∘ f) p = tangent_map I' I'' g (tangent_map I I' f p) :=
begin
simp only [tangent_map] with mfld_simps,
rw mfderiv_comp p.1 hg hf,
refl
end
lemma tangent_map_comp (hg : mdifferentiable I' I'' g) (hf : mdifferentiable I I' f) :
tangent_map I I'' (g ∘ f) = (tangent_map I' I'' g) ∘ (tangent_map I I' f) :=
by { ext p : 1, exact tangent_map_comp_at _ (hg _) (hf _) }
end derivatives_properties
section mfderiv_fderiv
/-!
### Relations between vector space derivative and manifold derivative
The manifold derivative `mfderiv`, when considered on the model vector space with its trivial
manifold structure, coincides with the usual Frechet derivative `fderiv`. In this section, we prove
this and related statements.
-/
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{f : E → E'} {s : set E} {x : E}
lemma unique_mdiff_within_at_iff_unique_diff_within_at :
unique_mdiff_within_at (𝓘(𝕜, E)) s x ↔ unique_diff_within_at 𝕜 s x :=
by simp only [unique_mdiff_within_at] with mfld_simps
alias unique_mdiff_within_at_iff_unique_diff_within_at ↔
unique_mdiff_within_at.unique_diff_within_at unique_diff_within_at.unique_mdiff_within_at
lemma unique_mdiff_on_iff_unique_diff_on :
unique_mdiff_on (𝓘(𝕜, E)) s ↔ unique_diff_on 𝕜 s :=
by simp [unique_mdiff_on, unique_diff_on, unique_mdiff_within_at_iff_unique_diff_within_at]
alias unique_mdiff_on_iff_unique_diff_on ↔
unique_mdiff_on.unique_diff_on unique_diff_on.unique_mdiff_on
@[simp, mfld_simps] lemma written_in_ext_chart_model_space :
written_in_ext_chart_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) x f = f :=
rfl
lemma has_mfderiv_within_at_iff_has_fderiv_within_at {f'} :
has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x f' ↔
has_fderiv_within_at f f' s x :=
by simpa only [has_mfderiv_within_at, and_iff_right_iff_imp] with mfld_simps
using has_fderiv_within_at.continuous_within_at
alias has_mfderiv_within_at_iff_has_fderiv_within_at ↔
has_mfderiv_within_at.has_fderiv_within_at has_fderiv_within_at.has_mfderiv_within_at
lemma has_mfderiv_at_iff_has_fderiv_at {f'} :
has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x f' ↔ has_fderiv_at f f' x :=
by rw [← has_mfderiv_within_at_univ, has_mfderiv_within_at_iff_has_fderiv_within_at,
has_fderiv_within_at_univ]
alias has_mfderiv_at_iff_has_fderiv_at ↔ has_mfderiv_at.has_fderiv_at has_fderiv_at.has_mfderiv_at
/-- For maps between vector spaces, `mdifferentiable_within_at` and `fdifferentiable_within_at`
coincide -/
theorem mdifferentiable_within_at_iff_differentiable_within_at :
mdifferentiable_within_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x
↔ differentiable_within_at 𝕜 f s x :=
begin
simp only [mdifferentiable_within_at] with mfld_simps,
exact ⟨λH, H.2, λH, ⟨H.continuous_within_at, H⟩⟩
end
alias mdifferentiable_within_at_iff_differentiable_within_at ↔
mdifferentiable_within_at.differentiable_within_at
differentiable_within_at.mdifferentiable_within_at
/-- For maps between vector spaces, `mdifferentiable_at` and `differentiable_at` coincide -/
theorem mdifferentiable_at_iff_differentiable_at :
mdifferentiable_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f x ↔ differentiable_at 𝕜 f x :=
begin
simp only [mdifferentiable_at, differentiable_within_at_univ] with mfld_simps,
exact ⟨λH, H.2, λH, ⟨H.continuous_at, H⟩⟩
end
alias mdifferentiable_at_iff_differentiable_at ↔
mdifferentiable_at.differentiable_at differentiable_at.mdifferentiable_at
/-- For maps between vector spaces, `mdifferentiable_on` and `differentiable_on` coincide -/
theorem mdifferentiable_on_iff_differentiable_on :
mdifferentiable_on (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s ↔ differentiable_on 𝕜 f s :=
by simp only [mdifferentiable_on, differentiable_on,
mdifferentiable_within_at_iff_differentiable_within_at]
alias mdifferentiable_on_iff_differentiable_on ↔
mdifferentiable_on.differentiable_on differentiable_on.mdifferentiable_on
/-- For maps between vector spaces, `mdifferentiable` and `differentiable` coincide -/
theorem mdifferentiable_iff_differentiable :
mdifferentiable (𝓘(𝕜, E)) (𝓘(𝕜, E')) f ↔ differentiable 𝕜 f :=
by simp only [mdifferentiable, differentiable, mdifferentiable_at_iff_differentiable_at]
alias mdifferentiable_iff_differentiable ↔
mdifferentiable.differentiable differentiable.mdifferentiable
/-- For maps between vector spaces, `mfderiv_within` and `fderiv_within` coincide -/
@[simp] theorem mfderiv_within_eq_fderiv_within :
mfderiv_within (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x = fderiv_within 𝕜 f s x :=
begin
by_cases h : mdifferentiable_within_at (𝓘(𝕜, E)) (𝓘(𝕜, E')) f s x,
{ simp only [mfderiv_within, h, if_pos] with mfld_simps },
{ simp only [mfderiv_within, h, if_neg, not_false_iff],
rw [mdifferentiable_within_at_iff_differentiable_within_at] at h,
exact (fderiv_within_zero_of_not_differentiable_within_at h).symm }
end
/-- For maps between vector spaces, `mfderiv` and `fderiv` coincide -/
@[simp] theorem mfderiv_eq_fderiv :
mfderiv (𝓘(𝕜, E)) (𝓘(𝕜, E')) f x = fderiv 𝕜 f x :=
begin
rw [← mfderiv_within_univ, ← fderiv_within_univ],
exact mfderiv_within_eq_fderiv_within
end
end mfderiv_fderiv
section specific_functions
/-! ### Differentiability of specific functions -/
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H')
{M' : Type*} [topological_space M'] [charted_space H' M'] [smooth_manifold_with_corners I' M']
{E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E'']
{H'' : Type*} [topological_space H''] (I'' : model_with_corners 𝕜 E'' H'')
{M'' : Type*} [topological_space M''] [charted_space H'' M''] [smooth_manifold_with_corners I'' M'']
namespace continuous_linear_map
variables (f : E →L[𝕜] E') {s : set E} {x : E}
protected lemma has_mfderiv_within_at : has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x f :=
f.has_fderiv_within_at.has_mfderiv_within_at
protected lemma has_mfderiv_at : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x f :=
f.has_fderiv_at.has_mfderiv_at
protected lemma mdifferentiable_within_at : mdifferentiable_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x :=
f.differentiable_within_at.mdifferentiable_within_at
protected lemma mdifferentiable_on : mdifferentiable_on 𝓘(𝕜, E) 𝓘(𝕜, E') f s :=
f.differentiable_on.mdifferentiable_on
protected lemma mdifferentiable_at : mdifferentiable_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x :=
f.differentiable_at.mdifferentiable_at
protected lemma mdifferentiable : mdifferentiable 𝓘(𝕜, E) 𝓘(𝕜, E') f :=
f.differentiable.mdifferentiable
lemma mfderiv_eq : mfderiv 𝓘(𝕜, E) 𝓘(𝕜, E') f x = f :=
f.has_mfderiv_at.mfderiv
lemma mfderiv_within_eq (hs : unique_mdiff_within_at 𝓘(𝕜, E) s x) :
mfderiv_within 𝓘(𝕜, E) 𝓘(𝕜, E') f s x = f :=
f.has_mfderiv_within_at.mfderiv_within hs
end continuous_linear_map
namespace continuous_linear_equiv
variables (f : E ≃L[𝕜] E') {s : set E} {x : E}
protected lemma has_mfderiv_within_at :
has_mfderiv_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x (f : E →L[𝕜] E') :=
f.has_fderiv_within_at.has_mfderiv_within_at
protected lemma has_mfderiv_at : has_mfderiv_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x (f : E →L[𝕜] E') :=
f.has_fderiv_at.has_mfderiv_at
protected lemma mdifferentiable_within_at : mdifferentiable_within_at 𝓘(𝕜, E) 𝓘(𝕜, E') f s x :=
f.differentiable_within_at.mdifferentiable_within_at
protected lemma mdifferentiable_on : mdifferentiable_on 𝓘(𝕜, E) 𝓘(𝕜, E') f s :=
f.differentiable_on.mdifferentiable_on
protected lemma mdifferentiable_at : mdifferentiable_at 𝓘(𝕜, E) 𝓘(𝕜, E') f x :=
f.differentiable_at.mdifferentiable_at
protected lemma mdifferentiable : mdifferentiable 𝓘(𝕜, E) 𝓘(𝕜, E') f :=
f.differentiable.mdifferentiable
lemma mfderiv_eq : mfderiv 𝓘(𝕜, E) 𝓘(𝕜, E') f x = (f : E →L[𝕜] E') :=
f.has_mfderiv_at.mfderiv
lemma mfderiv_within_eq (hs : unique_mdiff_within_at 𝓘(𝕜, E) s x) :
mfderiv_within 𝓘(𝕜, E) 𝓘(𝕜, E') f s x = (f : E →L[𝕜] E') :=
f.has_mfderiv_within_at.mfderiv_within hs
end continuous_linear_equiv
variables {s : set M} {x : M}
section id
/-! #### Identity -/
lemma has_mfderiv_at_id (x : M) :
has_mfderiv_at I I (@_root_.id M) x (continuous_linear_map.id 𝕜 (tangent_space I x)) :=
begin
refine ⟨continuous_at_id, _⟩,
have : ∀ᶠ y in 𝓝[range I] ((ext_chart_at I x) x),
((ext_chart_at I x) ∘ (ext_chart_at I x).symm) y = id y,
{ apply filter.mem_of_superset (ext_chart_at_target_mem_nhds_within I x),
mfld_set_tac },
apply has_fderiv_within_at.congr_of_eventually_eq (has_fderiv_within_at_id _ _) this,
simp only with mfld_simps
end
theorem has_mfderiv_within_at_id (s : set M) (x : M) :
has_mfderiv_within_at I I (@_root_.id M) s x (continuous_linear_map.id 𝕜 (tangent_space I x)) :=
(has_mfderiv_at_id I x).has_mfderiv_within_at
lemma mdifferentiable_at_id : mdifferentiable_at I I (@_root_.id M) x :=
(has_mfderiv_at_id I x).mdifferentiable_at
lemma mdifferentiable_within_at_id : mdifferentiable_within_at I I (@_root_.id M) s x :=
(mdifferentiable_at_id I).mdifferentiable_within_at
lemma mdifferentiable_id : mdifferentiable I I (@_root_.id M) :=
λx, mdifferentiable_at_id I
lemma mdifferentiable_on_id : mdifferentiable_on I I (@_root_.id M) s :=
(mdifferentiable_id I).mdifferentiable_on
@[simp, mfld_simps] lemma mfderiv_id :
mfderiv I I (@_root_.id M) x = (continuous_linear_map.id 𝕜 (tangent_space I x)) :=
has_mfderiv_at.mfderiv (has_mfderiv_at_id I x)
lemma mfderiv_within_id (hxs : unique_mdiff_within_at I s x) :
mfderiv_within I I (@_root_.id M) s x = (continuous_linear_map.id 𝕜 (tangent_space I x)) :=
begin
rw mdifferentiable.mfderiv_within (mdifferentiable_at_id I) hxs,
exact mfderiv_id I
end
@[simp, mfld_simps] lemma tangent_map_id : tangent_map I I (id : M → M) = id :=
by { ext1 ⟨x, v⟩, simp [tangent_map] }
lemma tangent_map_within_id {p : tangent_bundle I M}
(hs : unique_mdiff_within_at I s p.proj) :
tangent_map_within I I (id : M → M) s p = p :=
begin
simp only [tangent_map_within, id.def],
rw mfderiv_within_id,
{ rcases p, refl },
{ exact hs }
end
end id
section const
/-! #### Constants -/
variables {c : M'}
lemma has_mfderiv_at_const (c : M') (x : M) :
has_mfderiv_at I I' (λy : M, c) x
(0 : tangent_space I x →L[𝕜] tangent_space I' c) :=
begin
refine ⟨continuous_const.continuous_at, _⟩,
simp only [written_in_ext_chart_at, (∘), has_fderiv_within_at_const]
end
theorem has_mfderiv_within_at_const (c : M') (s : set M) (x : M) :
has_mfderiv_within_at I I' (λy : M, c) s x
(0 : tangent_space I x →L[𝕜] tangent_space I' c) :=
(has_mfderiv_at_const I I' c x).has_mfderiv_within_at
lemma mdifferentiable_at_const : mdifferentiable_at I I' (λy : M, c) x :=
(has_mfderiv_at_const I I' c x).mdifferentiable_at
lemma mdifferentiable_within_at_const : mdifferentiable_within_at I I' (λy : M, c) s x :=
(mdifferentiable_at_const I I').mdifferentiable_within_at
lemma mdifferentiable_const : mdifferentiable I I' (λy : M, c) :=
λx, mdifferentiable_at_const I I'
lemma mdifferentiable_on_const : mdifferentiable_on I I' (λy : M, c) s :=
(mdifferentiable_const I I').mdifferentiable_on
@[simp, mfld_simps] lemma mfderiv_const : mfderiv I I' (λy : M, c) x =
(0 : tangent_space I x →L[𝕜] tangent_space I' c) :=
has_mfderiv_at.mfderiv (has_mfderiv_at_const I I' c x)
lemma mfderiv_within_const (hxs : unique_mdiff_within_at I s x) :
mfderiv_within I I' (λy : M, c) s x =
(0 : tangent_space I x →L[𝕜] tangent_space I' c) :=
(has_mfderiv_within_at_const _ _ _ _ _).mfderiv_within hxs
end const
section prod
/-! Operations on the product of two manifolds-/
lemma has_mfderiv_at_fst (x : M × M') :
has_mfderiv_at (I.prod I') I prod.fst x
(continuous_linear_map.fst 𝕜 (tangent_space I x.1) (tangent_space I' x.2)) :=
begin
refine ⟨continuous_fst.continuous_at, _⟩,
have : ∀ᶠ y in 𝓝[range (I.prod I')] (ext_chart_at (I.prod I') x x),
((ext_chart_at I x.1) ∘ prod.fst ∘ (ext_chart_at (I.prod I') x).symm) y = y.1,
{ apply filter.mem_of_superset (ext_chart_at_target_mem_nhds_within (I.prod I') x),
mfld_set_tac },
apply has_fderiv_within_at.congr_of_eventually_eq has_fderiv_within_at_fst this,
simp only with mfld_simps
end
theorem has_mfderiv_within_at_fst (s : set (M × M')) (x : M × M') :
has_mfderiv_within_at (I.prod I') I prod.fst s x
(continuous_linear_map.fst 𝕜 (tangent_space I x.1) (tangent_space I' x.2)) :=
(has_mfderiv_at_fst I I' x).has_mfderiv_within_at
lemma mdifferentiable_at_fst {x : M × M'} : mdifferentiable_at (I.prod I') I prod.fst x :=
(has_mfderiv_at_fst I I' x).mdifferentiable_at
lemma mdifferentiable_within_at_fst {s : set (M × M')} {x : M × M'} :
mdifferentiable_within_at (I.prod I') I prod.fst s x :=
(mdifferentiable_at_fst I I').mdifferentiable_within_at
lemma mdifferentiable_fst : mdifferentiable (I.prod I') I (prod.fst : M × M' → M) :=
λx, mdifferentiable_at_fst I I'
lemma mdifferentiable_on_fst {s : set (M × M')} : mdifferentiable_on (I.prod I') I prod.fst s :=
(mdifferentiable_fst I I').mdifferentiable_on
@[simp, mfld_simps] lemma mfderiv_fst {x : M × M'} :
mfderiv (I.prod I') I prod.fst x =
continuous_linear_map.fst 𝕜 (tangent_space I x.1) (tangent_space I' x.2) :=
(has_mfderiv_at_fst I I' x).mfderiv
lemma mfderiv_within_fst {s : set (M × M')} {x : M × M'}
(hxs : unique_mdiff_within_at (I.prod I') s x) :
mfderiv_within (I.prod I') I prod.fst s x =
continuous_linear_map.fst 𝕜 (tangent_space I x.1) (tangent_space I' x.2) :=
by { rw mdifferentiable.mfderiv_within (mdifferentiable_at_fst I I') hxs, exact mfderiv_fst I I' }
@[simp, mfld_simps] lemma tangent_map_prod_fst {p : tangent_bundle (I.prod I') (M × M')} :
tangent_map (I.prod I') I prod.fst p = ⟨p.proj.1, p.2.1⟩ :=
by simp [tangent_map]
lemma tangent_map_within_prod_fst {s : set (M × M')} {p : tangent_bundle (I.prod I') (M × M')}
(hs : unique_mdiff_within_at (I.prod I') s p.proj) :
tangent_map_within (I.prod I') I prod.fst s p = ⟨p.proj.1, p.2.1⟩ :=
begin
simp only [tangent_map_within],
rw mfderiv_within_fst _ _ hs,
rcases p,
exact ⟨rfl, heq.rfl⟩
end
lemma has_mfderiv_at_snd (x : M × M') :
has_mfderiv_at (I.prod I') I' prod.snd x
(continuous_linear_map.snd 𝕜 (tangent_space I x.1) (tangent_space I' x.2)) :=
begin
refine ⟨continuous_snd.continuous_at, _⟩,
have : ∀ᶠ y in 𝓝[range (I.prod I')] (ext_chart_at (I.prod I') x x),
((ext_chart_at I' x.2) ∘ prod.snd ∘ (ext_chart_at (I.prod I') x).symm) y = y.2,
{ apply filter.mem_of_superset (ext_chart_at_target_mem_nhds_within (I.prod I') x),
mfld_set_tac },
apply has_fderiv_within_at.congr_of_eventually_eq has_fderiv_within_at_snd this,
simp only with mfld_simps
end
theorem has_mfderiv_within_at_snd (s : set (M × M')) (x : M × M') :
has_mfderiv_within_at (I.prod I') I' prod.snd s x
(continuous_linear_map.snd 𝕜 (tangent_space I x.1) (tangent_space I' x.2)) :=
(has_mfderiv_at_snd I I' x).has_mfderiv_within_at
lemma mdifferentiable_at_snd {x : M × M'} : mdifferentiable_at (I.prod I') I' prod.snd x :=
(has_mfderiv_at_snd I I' x).mdifferentiable_at
lemma mdifferentiable_within_at_snd {s : set (M × M')} {x : M × M'} :
mdifferentiable_within_at (I.prod I') I' prod.snd s x :=
(mdifferentiable_at_snd I I').mdifferentiable_within_at
lemma mdifferentiable_snd : mdifferentiable (I.prod I') I' (prod.snd : M × M' → M') :=
λx, mdifferentiable_at_snd I I'
lemma mdifferentiable_on_snd {s : set (M × M')} : mdifferentiable_on (I.prod I') I' prod.snd s :=
(mdifferentiable_snd I I').mdifferentiable_on
@[simp, mfld_simps] lemma mfderiv_snd {x : M × M'} :
mfderiv (I.prod I') I' prod.snd x =
continuous_linear_map.snd 𝕜 (tangent_space I x.1) (tangent_space I' x.2) :=
(has_mfderiv_at_snd I I' x).mfderiv
lemma mfderiv_within_snd {s : set (M × M')} {x : M × M'}
(hxs : unique_mdiff_within_at (I.prod I') s x) :
mfderiv_within (I.prod I') I' prod.snd s x =
continuous_linear_map.snd 𝕜 (tangent_space I x.1) (tangent_space I' x.2) :=
by { rw mdifferentiable.mfderiv_within (mdifferentiable_at_snd I I') hxs, exact mfderiv_snd I I' }
@[simp, mfld_simps] lemma tangent_map_prod_snd {p : tangent_bundle (I.prod I') (M × M')} :
tangent_map (I.prod I') I' prod.snd p = ⟨p.proj.2, p.2.2⟩ :=
by simp [tangent_map]
lemma tangent_map_within_prod_snd {s : set (M × M')} {p : tangent_bundle (I.prod I') (M × M')}
(hs : unique_mdiff_within_at (I.prod I') s p.proj) :
tangent_map_within (I.prod I') I' prod.snd s p = ⟨p.proj.2, p.2.2⟩ :=
begin
simp only [tangent_map_within],
rw mfderiv_within_snd,
{ rcases p, split; refl },
{ exact hs }
end
variables {I I' I''}
lemma mdifferentiable_at.mfderiv_prod {f : M → M'} {g : M → M''} {x : M}
(hf : mdifferentiable_at I I' f x)
(hg : mdifferentiable_at I I'' g x) :
mfderiv I (I'.prod I'') (λ x, (f x, g x)) x = (mfderiv I I' f x).prod (mfderiv I I'' g x) :=
begin
classical,
simp_rw [mfderiv, if_pos (hf.prod_mk hg), if_pos hf, if_pos hg],
exact hf.2.fderiv_within_prod hg.2 (I.unique_diff _ (mem_range_self _))
end
variables (I I' I'')
lemma mfderiv_prod_left {x₀ : M} {y₀ : M'} :
mfderiv I (I.prod I') (λ x, (x, y₀)) x₀ =
continuous_linear_map.inl 𝕜 (tangent_space I x₀) (tangent_space I' y₀) :=
begin
refine ((mdifferentiable_at_id I).mfderiv_prod (mdifferentiable_at_const I I')).trans _,
rw [mfderiv_id, mfderiv_const, continuous_linear_map.inl]
end
lemma mfderiv_prod_right {x₀ : M} {y₀ : M'} :
mfderiv I' (I.prod I') (λ y, (x₀, y)) y₀ =
continuous_linear_map.inr 𝕜 (tangent_space I x₀) (tangent_space I' y₀) :=
begin
refine ((mdifferentiable_at_const I' I).mfderiv_prod (mdifferentiable_at_id I')).trans _,
rw [mfderiv_id, mfderiv_const, continuous_linear_map.inr]
end
/-- The total derivative of a function in two variables is the sum of the partial derivatives.
Note that to state this (without casts) we need to be able to see through the definition of
`tangent_space`. -/
lemma mfderiv_prod_eq_add {f : M × M' → M''} {p : M × M'}
(hf : mdifferentiable_at (I.prod I') I'' f p) :
mfderiv (I.prod I') I'' f p =
(show E × E' →L[𝕜] E'', from mfderiv (I.prod I') I'' (λ (z : M × M'), f (z.1, p.2)) p +
mfderiv (I.prod I') I'' (λ (z : M × M'), f (p.1, z.2)) p) :=
begin
dsimp only,
rw [← @prod.mk.eta _ _ p] at hf,
rw [mfderiv_comp_of_eq hf ((mdifferentiable_at_fst I I').prod_mk (mdifferentiable_at_const _ _))
rfl,
mfderiv_comp_of_eq hf ((mdifferentiable_at_const _ _).prod_mk (mdifferentiable_at_snd I I'))
rfl,
← continuous_linear_map.comp_add,
(mdifferentiable_at_fst I I').mfderiv_prod (mdifferentiable_at_const (I.prod I') I'),
(mdifferentiable_at_const (I.prod I') I).mfderiv_prod (mdifferentiable_at_snd I I'),
mfderiv_fst, mfderiv_snd, mfderiv_const, mfderiv_const],
symmetry,
convert continuous_linear_map.comp_id _,
{ exact continuous_linear_map.coprod_inl_inr },
simp_rw [prod.mk.eta],
all_goals { apply_instance }
end
end prod
section arithmetic
/-! #### Arithmetic
Note that in the in `has_mfderiv_at` lemmas there is an abuse of the defeq between `E'` and
`tangent_space 𝓘(𝕜, E') (f z)` (similarly for `g',F',p',q'`). In general this defeq is not
canonical, but in this case (the tangent space of a vector space) it is canonical.
-/
section group
variables {I} {z : M} {f g : M → E'} {f' g' : tangent_space I z →L[𝕜] E'}
lemma has_mfderiv_at.add (hf : has_mfderiv_at I 𝓘(𝕜, E') f z f')
(hg : has_mfderiv_at I 𝓘(𝕜, E') g z g') : has_mfderiv_at I 𝓘(𝕜, E') (f + g) z (f' + g') :=
⟨hf.1.add hg.1, hf.2.add hg.2⟩
lemma mdifferentiable_at.add (hf : mdifferentiable_at I 𝓘(𝕜, E') f z)
(hg : mdifferentiable_at I 𝓘(𝕜, E') g z) : mdifferentiable_at I 𝓘(𝕜, E') (f + g) z :=
(hf.has_mfderiv_at.add hg.has_mfderiv_at).mdifferentiable_at
lemma mdifferentiable.add (hf : mdifferentiable I 𝓘(𝕜, E') f) (hg : mdifferentiable I 𝓘(𝕜, E') g) :
mdifferentiable I 𝓘(𝕜, E') (f + g) :=
λ x, (hf x).add (hg x)
lemma mfderiv_add (hf : mdifferentiable_at I 𝓘(𝕜, E') f z)
(hg : mdifferentiable_at I 𝓘(𝕜, E') g z) :
(mfderiv I 𝓘(𝕜, E') (f + g) z : tangent_space I z →L[𝕜] E') =
(mfderiv I 𝓘(𝕜, E') f z + mfderiv I 𝓘(𝕜, E') g z : tangent_space I z →L[𝕜] E') :=
(hf.has_mfderiv_at.add hg.has_mfderiv_at).mfderiv
lemma has_mfderiv_at.const_smul (hf : has_mfderiv_at I 𝓘(𝕜, E') f z f') (s : 𝕜) :
has_mfderiv_at I 𝓘(𝕜, E') (s • f) z (s • f') :=
⟨hf.1.const_smul s, hf.2.const_smul s⟩
lemma mdifferentiable_at.const_smul (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) (s : 𝕜) :
mdifferentiable_at I 𝓘(𝕜, E') (s • f) z :=
(hf.has_mfderiv_at.const_smul s).mdifferentiable_at
lemma mdifferentiable.const_smul (s : 𝕜) (hf : mdifferentiable I 𝓘(𝕜, E') f) :
mdifferentiable I 𝓘(𝕜, E') (s • f) :=
λ x, (hf x).const_smul s
lemma const_smul_mfderiv (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) (s : 𝕜) :
(mfderiv I 𝓘(𝕜, E') (s • f) z : tangent_space I z →L[𝕜] E') =
(s • mfderiv I 𝓘(𝕜, E') f z : tangent_space I z →L[𝕜] E') :=
(hf.has_mfderiv_at.const_smul s).mfderiv
lemma has_mfderiv_at.neg (hf : has_mfderiv_at I 𝓘(𝕜, E') f z f') :
has_mfderiv_at I 𝓘(𝕜, E') (-f) z (-f') :=
⟨hf.1.neg, hf.2.neg⟩
lemma has_mfderiv_at_neg :
has_mfderiv_at I 𝓘(𝕜, E') (-f) z (-f') ↔ has_mfderiv_at I 𝓘(𝕜, E') f z f' :=
⟨λ hf, by { convert hf.neg; rw [neg_neg] }, λ hf, hf.neg⟩
lemma mdifferentiable_at.neg (hf : mdifferentiable_at I 𝓘(𝕜, E') f z) :
mdifferentiable_at I 𝓘(𝕜, E') (-f) z :=
hf.has_mfderiv_at.neg.mdifferentiable_at
lemma mdifferentiable_at_neg :
mdifferentiable_at I 𝓘(𝕜, E') (-f) z ↔ mdifferentiable_at I 𝓘(𝕜, E') f z :=
⟨λ hf, by { convert hf.neg; rw [neg_neg] }, λ hf, hf.neg⟩
lemma mdifferentiable.neg (hf : mdifferentiable I 𝓘(𝕜, E') f) :
mdifferentiable I 𝓘(𝕜, E') (-f) :=
λ x, (hf x).neg
lemma mfderiv_neg (f : M → E') (x : M) :
(mfderiv I 𝓘(𝕜, E') (-f) x : tangent_space I x →L[𝕜] E') =
(- mfderiv I 𝓘(𝕜, E') f x : tangent_space I x →L[𝕜] E') :=
begin
simp_rw [mfderiv],
by_cases hf : mdifferentiable_at I 𝓘(𝕜, E') f x,
{ exact hf.has_mfderiv_at.neg.mfderiv },
{ rw [if_neg hf], rw [← mdifferentiable_at_neg] at hf, rw [if_neg hf, neg_zero] },
end
lemma has_mfderiv_at.sub (hf : has_mfderiv_at I 𝓘(𝕜, E') f z f')
(hg : has_mfderiv_at I 𝓘(𝕜, E') g z g') : has_mfderiv_at I 𝓘(𝕜, E') (f - g) z (f'- g') :=
⟨hf.1.sub hg.1, hf.2.sub hg.2⟩
lemma mdifferentiable_at.sub (hf : mdifferentiable_at I 𝓘(𝕜, E') f z)
(hg : mdifferentiable_at I 𝓘(𝕜, E') g z) : mdifferentiable_at I 𝓘(𝕜, E') (f - g) z :=
(hf.has_mfderiv_at.sub hg.has_mfderiv_at).mdifferentiable_at
lemma mdifferentiable.sub (hf : mdifferentiable I 𝓘(𝕜, E') f)
(hg : mdifferentiable I 𝓘(𝕜, E') g) : mdifferentiable I 𝓘(𝕜, E') (f - g) :=
λ x, (hf x).sub (hg x)
lemma mfderiv_sub (hf : mdifferentiable_at I 𝓘(𝕜, E') f z)
(hg : mdifferentiable_at I 𝓘(𝕜, E') g z) :
(mfderiv I 𝓘(𝕜, E') (f - g) z : tangent_space I z →L[𝕜] E') =
(mfderiv I 𝓘(𝕜, E') f z - mfderiv I 𝓘(𝕜, E') g z : tangent_space I z →L[𝕜] E') :=
(hf.has_mfderiv_at.sub hg.has_mfderiv_at).mfderiv
end group
section algebra_over_ring
variables {I} {z : M} {F' : Type*} [normed_ring F'] [normed_algebra 𝕜 F']
{p q : M → F'} {p' q' : tangent_space I z →L[𝕜] F'}
lemma has_mfderiv_within_at.mul' (hp : has_mfderiv_within_at I 𝓘(𝕜, F') p s z p')
(hq : has_mfderiv_within_at I 𝓘(𝕜, F') q s z q') :
has_mfderiv_within_at I 𝓘(𝕜, F') (p * q) s z (p z • q' + p'.smul_right (q z) : E →L[𝕜] F') :=
⟨hp.1.mul hq.1, by simpa only with mfld_simps using hp.2.mul' hq.2⟩
lemma has_mfderiv_at.mul' (hp : has_mfderiv_at I 𝓘(𝕜, F') p z p')
(hq : has_mfderiv_at I 𝓘(𝕜, F') q z q') :
has_mfderiv_at I 𝓘(𝕜, F') (p * q) z (p z • q' + p'.smul_right (q z) : E →L[𝕜] F') :=
has_mfderiv_within_at_univ.mp $ hp.has_mfderiv_within_at.mul' hq.has_mfderiv_within_at
lemma mdifferentiable_within_at.mul (hp : mdifferentiable_within_at I 𝓘(𝕜, F') p s z)
(hq : mdifferentiable_within_at I 𝓘(𝕜, F') q s z) :
mdifferentiable_within_at I 𝓘(𝕜, F') (p * q) s z :=
(hp.has_mfderiv_within_at.mul' hq.has_mfderiv_within_at).mdifferentiable_within_at
lemma mdifferentiable_at.mul (hp : mdifferentiable_at I 𝓘(𝕜, F') p z)
(hq : mdifferentiable_at I 𝓘(𝕜, F') q z) : mdifferentiable_at I 𝓘(𝕜, F') (p * q) z :=
(hp.has_mfderiv_at.mul' hq.has_mfderiv_at).mdifferentiable_at
lemma mdifferentiable_on.mul (hp : mdifferentiable_on I 𝓘(𝕜, F') p s)
(hq : mdifferentiable_on I 𝓘(𝕜, F') q s) : mdifferentiable_on I 𝓘(𝕜, F') (p * q) s :=
λ x hx, (hp x hx).mul $ hq x hx
lemma mdifferentiable.mul (hp : mdifferentiable I 𝓘(𝕜, F') p)
(hq : mdifferentiable I 𝓘(𝕜, F') q) : mdifferentiable I 𝓘(𝕜, F') (p * q) :=
λ x, (hp x).mul (hq x)
end algebra_over_ring
section algebra_over_comm_ring
variables {I} {z : M} {F' : Type*} [normed_comm_ring F'] [normed_algebra 𝕜 F']
{p q : M → F'} {p' q' : tangent_space I z →L[𝕜] F'}
lemma has_mfderiv_within_at.mul (hp : has_mfderiv_within_at I 𝓘(𝕜, F') p s z p')
(hq : has_mfderiv_within_at I 𝓘(𝕜, F') q s z q') :
has_mfderiv_within_at I 𝓘(𝕜, F') (p * q) s z (p z • q' + q z • p' : E →L[𝕜] F') :=
by { convert hp.mul' hq, ext z, apply mul_comm }
lemma has_mfderiv_at.mul (hp : has_mfderiv_at I 𝓘(𝕜, F') p z p')
(hq : has_mfderiv_at I 𝓘(𝕜, F') q z q') :
has_mfderiv_at I 𝓘(𝕜, F') (p * q) z (p z • q' + q z • p' : E →L[𝕜] F') :=
has_mfderiv_within_at_univ.mp $ hp.has_mfderiv_within_at.mul hq.has_mfderiv_within_at
end algebra_over_comm_ring
end arithmetic
namespace model_with_corners
/-! #### Model with corners -/
protected lemma has_mfderiv_at {x} :
has_mfderiv_at I 𝓘(𝕜, E) I x (continuous_linear_map.id _ _) :=
⟨I.continuous_at, (has_fderiv_within_at_id _ _).congr' I.right_inv_on (mem_range_self _)⟩
protected lemma has_mfderiv_within_at {s x} :
has_mfderiv_within_at I 𝓘(𝕜, E) I s x (continuous_linear_map.id _ _) :=
I.has_mfderiv_at.has_mfderiv_within_at
protected lemma mdifferentiable_within_at {s x} :
mdifferentiable_within_at I 𝓘(𝕜, E) I s x :=
I.has_mfderiv_within_at.mdifferentiable_within_at
protected lemma mdifferentiable_at {x} :
mdifferentiable_at I 𝓘(𝕜, E) I x :=
I.has_mfderiv_at.mdifferentiable_at
protected lemma mdifferentiable_on {s} :
mdifferentiable_on I 𝓘(𝕜, E) I s :=
λ x hx, I.mdifferentiable_within_at
protected lemma mdifferentiable :
mdifferentiable I (𝓘(𝕜, E)) I :=
λ x, I.mdifferentiable_at
lemma has_mfderiv_within_at_symm {x} (hx : x ∈ range I) :
has_mfderiv_within_at 𝓘(𝕜, E) I I.symm (range I) x (continuous_linear_map.id _ _) :=
⟨I.continuous_within_at_symm, (has_fderiv_within_at_id _ _).congr'
(λ y hy, I.right_inv_on hy.1) ⟨hx, mem_range_self _⟩⟩
lemma mdifferentiable_on_symm :
mdifferentiable_on (𝓘(𝕜, E)) I I.symm (range I) :=
λ x hx, (I.has_mfderiv_within_at_symm hx).mdifferentiable_within_at
end model_with_corners
section charts
variable {e : local_homeomorph M H}
lemma mdifferentiable_at_atlas (h : e ∈ atlas H M) {x : M} (hx : x ∈ e.source) :
mdifferentiable_at I I e x :=
begin
refine ⟨(e.continuous_on x hx).continuous_at (is_open.mem_nhds e.open_source hx), _⟩,
have mem : I ((chart_at H x : M → H) x) ∈
I.symm ⁻¹' ((chart_at H x).symm ≫ₕ e).source ∩ range I,
by simp only [hx] with mfld_simps,
have : (chart_at H x).symm.trans e ∈ cont_diff_groupoid ∞ I :=
has_groupoid.compatible _ (chart_mem_atlas H x) h,
have A : cont_diff_on 𝕜 ∞
(I ∘ ((chart_at H x).symm.trans e) ∘ I.symm)
(I.symm ⁻¹' ((chart_at H x).symm.trans e).source ∩ range I) :=
this.1,
have B := A.differentiable_on le_top (I ((chart_at H x : M → H) x)) mem,
simp only with mfld_simps at B,
rw [inter_comm, differentiable_within_at_inter] at B,
{ simpa only with mfld_simps },
{ apply is_open.mem_nhds ((local_homeomorph.open_source _).preimage I.continuous_symm) mem.1 }
end
lemma mdifferentiable_on_atlas (h : e ∈ atlas H M) :
mdifferentiable_on I I e e.source :=
λx hx, (mdifferentiable_at_atlas I h hx).mdifferentiable_within_at
lemma mdifferentiable_at_atlas_symm (h : e ∈ atlas H M) {x : H} (hx : x ∈ e.target) :
mdifferentiable_at I I e.symm x :=
begin
refine ⟨(e.continuous_on_symm x hx).continuous_at (is_open.mem_nhds e.open_target hx), _⟩,
have mem : I x ∈ I.symm ⁻¹' (e.symm ≫ₕ chart_at H (e.symm x)).source ∩ range (I),
by simp only [hx] with mfld_simps,
have : e.symm.trans (chart_at H (e.symm x)) ∈ cont_diff_groupoid ∞ I :=
has_groupoid.compatible _ h (chart_mem_atlas H _),
have A : cont_diff_on 𝕜 ∞
(I ∘ (e.symm.trans (chart_at H (e.symm x))) ∘ I.symm)
(I.symm ⁻¹' (e.symm.trans (chart_at H (e.symm x))).source ∩ range I) :=
this.1,
have B := A.differentiable_on le_top (I x) mem,
simp only with mfld_simps at B,
rw [inter_comm, differentiable_within_at_inter] at B,
{ simpa only with mfld_simps },
{ apply (is_open.mem_nhds ((local_homeomorph.open_source _).preimage I.continuous_symm) mem.1) }
end
lemma mdifferentiable_on_atlas_symm (h : e ∈ atlas H M) :
mdifferentiable_on I I e.symm e.target :=
λx hx, (mdifferentiable_at_atlas_symm I h hx).mdifferentiable_within_at
lemma mdifferentiable_of_mem_atlas (h : e ∈ atlas H M) : e.mdifferentiable I I :=
⟨mdifferentiable_on_atlas I h, mdifferentiable_on_atlas_symm I h⟩
lemma mdifferentiable_chart (x : M) : (chart_at H x).mdifferentiable I I :=
mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)
/-- The derivative of the chart at a base point is the chart of the tangent bundle, composed with
the identification between the tangent bundle of the model space and the product space. -/
lemma tangent_map_chart {p q : tangent_bundle I M} (h : q.1 ∈ (chart_at H p.1).source) :
tangent_map I I (chart_at H p.1) q =
(total_space.to_prod _ _).symm
((chart_at (model_prod H E) p : tangent_bundle I M → model_prod H E) q) :=
begin
dsimp [tangent_map],
rw mdifferentiable_at.mfderiv,
{ refl },
{ exact mdifferentiable_at_atlas _ (chart_mem_atlas _ _) h }
end
/-- The derivative of the inverse of the chart at a base point is the inverse of the chart of the
tangent bundle, composed with the identification between the tangent bundle of the model space and
the product space. -/
lemma tangent_map_chart_symm {p : tangent_bundle I M} {q : tangent_bundle I H}
(h : q.1 ∈ (chart_at H p.1).target) :
tangent_map I I (chart_at H p.1).symm q =
((chart_at (model_prod H E) p).symm : model_prod H E → tangent_bundle I M)
((total_space.to_prod H E) q) :=
begin
dsimp only [tangent_map],
rw mdifferentiable_at.mfderiv (mdifferentiable_at_atlas_symm _ (chart_mem_atlas _ _) h),
-- a trivial instance is needed after the rewrite, handle it right now.
rotate, { apply_instance },
simp only [continuous_linear_map.coe_coe, tangent_bundle.chart_at, h,
tangent_bundle_core, chart_at, total_space.to_prod_apply] with mfld_simps,
end
end charts
end specific_functions
/-! ### Differentiable local homeomorphisms -/
namespace local_homeomorph.mdifferentiable
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
{M : Type*} [topological_space M] [charted_space H M]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{M' : Type*} [topological_space M'] [charted_space H' M']
{E'' : Type*} [normed_add_comm_group E''] [normed_space 𝕜 E'']
{H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''}
{M'' : Type*} [topological_space M''] [charted_space H'' M'']
{e : local_homeomorph M M'} (he : e.mdifferentiable I I')
{e' : local_homeomorph M' M''}
include he
lemma symm : e.symm.mdifferentiable I' I :=
⟨he.2, he.1⟩
protected lemma mdifferentiable_at {x : M} (hx : x ∈ e.source) :
mdifferentiable_at I I' e x :=
(he.1 x hx).mdifferentiable_at (is_open.mem_nhds e.open_source hx)
lemma mdifferentiable_at_symm {x : M'} (hx : x ∈ e.target) :
mdifferentiable_at I' I e.symm x :=
(he.2 x hx).mdifferentiable_at (is_open.mem_nhds e.open_target hx)
variables [smooth_manifold_with_corners I M] [smooth_manifold_with_corners I' M']
[smooth_manifold_with_corners I'' M'']
lemma symm_comp_deriv {x : M} (hx : x ∈ e.source) :
(mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) =
continuous_linear_map.id 𝕜 (tangent_space I x) :=
begin
have : (mfderiv I I (e.symm ∘ e) x) =
(mfderiv I' I e.symm (e x)).comp (mfderiv I I' e x) :=
mfderiv_comp x (he.mdifferentiable_at_symm (e.map_source hx)) (he.mdifferentiable_at hx),
rw ← this,
have : mfderiv I I (_root_.id : M → M) x = continuous_linear_map.id _ _ := mfderiv_id I,
rw ← this,
apply filter.eventually_eq.mfderiv_eq,
have : e.source ∈ 𝓝 x := is_open.mem_nhds e.open_source hx,
exact filter.mem_of_superset this (by mfld_set_tac)
end
lemma comp_symm_deriv {x : M'} (hx : x ∈ e.target) :
(mfderiv I I' e (e.symm x)).comp (mfderiv I' I e.symm x) =
continuous_linear_map.id 𝕜 (tangent_space I' x) :=
he.symm.symm_comp_deriv hx
/-- The derivative of a differentiable local homeomorphism, as a continuous linear equivalence
between the tangent spaces at `x` and `e x`. -/
protected def mfderiv {x : M} (hx : x ∈ e.source) :
tangent_space I x ≃L[𝕜] tangent_space I' (e x) :=
{ inv_fun := (mfderiv I' I e.symm (e x)),
continuous_to_fun := (mfderiv I I' e x).cont,
continuous_inv_fun := (mfderiv I' I e.symm (e x)).cont,
left_inv := λy, begin
have : (continuous_linear_map.id _ _ : tangent_space I x →L[𝕜] tangent_space I x) y = y := rfl,
conv_rhs { rw [← this, ← he.symm_comp_deriv hx] },
refl
end,
right_inv := λy, begin
have : (continuous_linear_map.id 𝕜 _ :
tangent_space I' (e x) →L[𝕜] tangent_space I' (e x)) y = y := rfl,
conv_rhs { rw [← this, ← he.comp_symm_deriv (e.map_source hx)] },
rw e.left_inv hx,
refl
end,
.. mfderiv I I' e x }
lemma mfderiv_bijective {x : M} (hx : x ∈ e.source) :
function.bijective (mfderiv I I' e x) :=
(he.mfderiv hx).bijective
lemma mfderiv_injective {x : M} (hx : x ∈ e.source) :
function.injective (mfderiv I I' e x) :=
(he.mfderiv hx).injective
lemma mfderiv_surjective {x : M} (hx : x ∈ e.source) :
function.surjective (mfderiv I I' e x) :=
(he.mfderiv hx).surjective
lemma ker_mfderiv_eq_bot {x : M} (hx : x ∈ e.source) :
linear_map.ker (mfderiv I I' e x) = ⊥ :=
(he.mfderiv hx).to_linear_equiv.ker
lemma range_mfderiv_eq_top {x : M} (hx : x ∈ e.source) :
linear_map.range (mfderiv I I' e x) = ⊤ :=
(he.mfderiv hx).to_linear_equiv.range
lemma range_mfderiv_eq_univ {x : M} (hx : x ∈ e.source) :
range (mfderiv I I' e x) = univ :=
(he.mfderiv_surjective hx).range_eq
lemma trans (he': e'.mdifferentiable I' I'') : (e.trans e').mdifferentiable I I'' :=
begin
split,
{ assume x hx,
simp only with mfld_simps at hx,
exact ((he'.mdifferentiable_at hx.2).comp _
(he.mdifferentiable_at hx.1)).mdifferentiable_within_at },
{ assume x hx,
simp only with mfld_simps at hx,
exact ((he.symm.mdifferentiable_at hx.2).comp _
(he'.symm.mdifferentiable_at hx.1)).mdifferentiable_within_at }
end
end local_homeomorph.mdifferentiable
/-! ### Differentiability of `ext_chart_at` -/
section ext_chart_at
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
{M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
{s : set M} {x y : M}
lemma has_mfderiv_at_ext_chart_at (h : y ∈ (chart_at H x).source) :
has_mfderiv_at I 𝓘(𝕜, E) (ext_chart_at I x) y (mfderiv I I (chart_at H x) y : _) :=
I.has_mfderiv_at.comp y ((mdifferentiable_chart I x).mdifferentiable_at h).has_mfderiv_at
lemma has_mfderiv_within_at_ext_chart_at (h : y ∈ (chart_at H x).source) :
has_mfderiv_within_at I 𝓘(𝕜, E) (ext_chart_at I x) s y (mfderiv I I (chart_at H x) y : _) :=
(has_mfderiv_at_ext_chart_at I h).has_mfderiv_within_at
lemma mdifferentiable_at_ext_chart_at (h : y ∈ (chart_at H x).source) :
mdifferentiable_at I 𝓘(𝕜, E) (ext_chart_at I x) y :=
(has_mfderiv_at_ext_chart_at I h).mdifferentiable_at
lemma mdifferentiable_on_ext_chart_at :
mdifferentiable_on I 𝓘(𝕜, E) (ext_chart_at I x) (chart_at H x).source :=
λ y hy, (has_mfderiv_within_at_ext_chart_at I hy).mdifferentiable_within_at
end ext_chart_at
/-! ### Unique derivative sets in manifolds -/
section unique_mdiff
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H}
{M : Type*} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{M' : Type*} [topological_space M'] [charted_space H' M']
{s : set M}
/-- If a set has the unique differential property, then its image under a local
diffeomorphism also has the unique differential property. -/
lemma unique_mdiff_on.unique_mdiff_on_preimage [smooth_manifold_with_corners I' M']
(hs : unique_mdiff_on I s) {e : local_homeomorph M M'} (he : e.mdifferentiable I I') :
unique_mdiff_on I' (e.target ∩ e.symm ⁻¹' s) :=
begin
/- Start from a point `x` in the image, and let `z` be its preimage. Then the unique
derivative property at `x` is expressed through `ext_chart_at I' x`, and the unique
derivative property at `z` is expressed through `ext_chart_at I z`. We will argue that
the composition of these two charts with `e` is a local diffeomorphism in vector spaces,
and therefore preserves the unique differential property thanks to lemma
`has_fderiv_within_at.unique_diff_within_at`, saying that a differentiable function with onto
derivative preserves the unique derivative property.-/
assume x hx,
let z := e.symm x,
have z_source : z ∈ e.source, by simp only [hx.1] with mfld_simps,
have zx : e z = x, by simp only [z, hx.1] with mfld_simps,
let F := ext_chart_at I z,
-- the unique derivative property at `z` is expressed through its preferred chart,
-- that we call `F`.
have B : unique_diff_within_at 𝕜
(F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z),
{ have : unique_mdiff_within_at I s z := hs _ hx.2,
have S : e.source ∩ e ⁻¹' ((ext_chart_at I' x).source) ∈ 𝓝 z,
{ apply is_open.mem_nhds,
apply e.continuous_on.preimage_open_of_open e.open_source (is_open_ext_chart_at_source I' x),
simp only [z_source, zx] with mfld_simps },
have := this.inter S,
rw [unique_mdiff_within_at_iff] at this,
exact this },
-- denote by `G` the change of coordinate, i.e., the composition of the two extended charts and
-- of `e`
let G := F.symm ≫ e.to_local_equiv ≫ (ext_chart_at I' x),
-- `G` is differentiable
have Diff : ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).mdifferentiable I I',
{ have A := mdifferentiable_of_mem_atlas I (chart_mem_atlas H z),
have B := mdifferentiable_of_mem_atlas I' (chart_mem_atlas H' x),
exact A.symm.trans (he.trans B) },
have Mmem : (chart_at H z : M → H) z ∈ ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x)).source,
by simp only [z_source, zx] with mfld_simps,
have A : differentiable_within_at 𝕜 G (range I) (F z),
{ refine (Diff.mdifferentiable_at Mmem).2.congr (λp hp, _) _;
simp only [G, F] with mfld_simps },
-- let `G'` be its derivative
let G' := fderiv_within 𝕜 G (range I) (F z),
have D₁ : has_fderiv_within_at G G' (range I) (F z) :=
A.has_fderiv_within_at,
have D₂ : has_fderiv_within_at G G'
(F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) (F z) :=
D₁.mono (by mfld_set_tac),
-- The derivative `G'` is onto, as it is the derivative of a local diffeomorphism, the composition
-- of the two charts and of `e`.
have C : dense_range (G' : E → E'),
{ have : G' = mfderiv I I' ((chart_at H z).symm ≫ₕ e ≫ₕ (chart_at H' x))
((chart_at H z : M → H) z),
by { rw (Diff.mdifferentiable_at Mmem).mfderiv, refl },
rw this,
exact (Diff.mfderiv_surjective Mmem).dense_range },
-- key step: thanks to what we have proved about it, `G` preserves the unique derivative property
have key : unique_diff_within_at 𝕜
(G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target))
(G (F z)) := D₂.unique_diff_within_at B C,
have : G (F z) = (ext_chart_at I' x) x, by { dsimp [G, F], simp only [hx.1] with mfld_simps },
rw this at key,
apply key.mono,
show G '' (F.symm ⁻¹' (s ∩ (e.source ∩ e ⁻¹' ((ext_chart_at I' x).source))) ∩ F.target) ⊆
(ext_chart_at I' x).symm ⁻¹' e.target ∩ (ext_chart_at I' x).symm ⁻¹' (e.symm ⁻¹' s) ∩
range (I'),
rw image_subset_iff,
mfld_set_tac
end
/-- If a set in a manifold has the unique derivative property, then its pullback by any extended
chart, in the vector space, also has the unique derivative property. -/
lemma unique_mdiff_on.unique_diff_on_target_inter (hs : unique_mdiff_on I s) (x : M) :
unique_diff_on 𝕜 ((ext_chart_at I x).target ∩ ((ext_chart_at I x).symm ⁻¹' s)) :=
begin
-- this is just a reformulation of `unique_mdiff_on.unique_mdiff_on_preimage`, using as `e`
-- the local chart at `x`.
assume z hz,
simp only with mfld_simps at hz,
have : (chart_at H x).mdifferentiable I I := mdifferentiable_chart _ _,
have T := (hs.unique_mdiff_on_preimage this) (I.symm z),
simp only [hz.left.left, hz.left.right, hz.right, unique_mdiff_within_at] with mfld_simps at ⊢ T,
convert T using 1,
rw @preimage_comp _ _ _ _ (chart_at H x).symm,
mfld_set_tac
end
/-- When considering functions between manifolds, this statement shows up often. It entails
the unique differential of the pullback in extended charts of the set where the function can
be read in the charts. -/
lemma unique_mdiff_on.unique_diff_on_inter_preimage (hs : unique_mdiff_on I s) (x : M) (y : M')
{f : M → M'} (hf : continuous_on f s) :
unique_diff_on 𝕜 ((ext_chart_at I x).target
∩ ((ext_chart_at I x).symm ⁻¹' (s ∩ f⁻¹' (ext_chart_at I' y).source))) :=
begin
have : unique_mdiff_on I (s ∩ f ⁻¹' (ext_chart_at I' y).source),
{ assume z hz,
apply (hs z hz.1).inter',
apply (hf z hz.1).preimage_mem_nhds_within,
exact (is_open_ext_chart_at_source I' y).mem_nhds hz.2 },
exact this.unique_diff_on_target_inter _
end
open bundle
variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F]
(Z : M → Type*) [topological_space (total_space F Z)] [∀ b, topological_space (Z b)]
[∀ b, add_comm_monoid (Z b)] [∀ b, module 𝕜 (Z b)]
[fiber_bundle F Z] [vector_bundle 𝕜 F Z] [smooth_vector_bundle F Z I]
/-- In a smooth fiber bundle, the preimage under the projection of a set with
unique differential in the basis also has unique differential. -/
lemma unique_mdiff_on.smooth_bundle_preimage (hs : unique_mdiff_on I s) :
unique_mdiff_on (I.prod (𝓘(𝕜, F))) (π F Z ⁻¹' s) :=
begin
/- Using a chart (and the fact that unique differentiability is invariant under charts), we
reduce the situation to the model space, where we can use the fact that products respect
unique differentiability. -/
assume p hp,
replace hp : p.1 ∈ s, by simpa only with mfld_simps using hp,
let e₀ := chart_at H p.1,
let e := chart_at (model_prod H F) p,
have h2s : ∀ x, x ∈ e.target ∩ e.symm ⁻¹' (π F Z ⁻¹' s) ↔
(x.1 ∈ e₀.target ∧ (e₀.symm) x.1 ∈ (trivialization_at F Z p.1).base_set) ∧ (e₀.symm) x.1 ∈ s,
{ intro x,
have A : x ∈ e.target ↔ x.1 ∈ e₀.target ∧
(e₀.symm) x.1 ∈ (trivialization_at F Z p.1).base_set,
{ simp only [e, fiber_bundle.charted_space_chart_at, trivialization.mem_target,
bundle.total_space.proj] with mfld_simps },
rw [← A, mem_inter_iff, and.congr_right_iff],
intro hx,
simp only [fiber_bundle.charted_space_chart_at_symm_fst p x hx] with mfld_simps },
-- It suffices to prove unique differentiability in a chart
suffices h : unique_mdiff_on (I.prod (𝓘(𝕜, F)))
(e.target ∩ e.symm ⁻¹' (π F Z ⁻¹' s)),
{ have A : unique_mdiff_on (I.prod (𝓘(𝕜, F))) (e.symm.target ∩
e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (π F Z ⁻¹' s))),
{ apply h.unique_mdiff_on_preimage,
exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)).symm,
apply_instance },
have : p ∈ e.symm.target ∩ e.symm.symm ⁻¹' (e.target ∩ e.symm⁻¹' (π F Z ⁻¹' s)),
{ simp only [e, hp] with mfld_simps },
apply (A _ this).mono,
assume q hq,
simp only [e, local_homeomorph.left_inv _ hq.1] with mfld_simps at hq,
simp only [hq] with mfld_simps },
assume q hq,
simp only [unique_mdiff_within_at, model_with_corners.prod, -preimage_inter] with mfld_simps,
have : 𝓝[(I.symm ⁻¹' (e₀.target ∩ e₀.symm⁻¹' s) ∩ range I) ×ˢ univ] (I q.1, q.2) ≤
𝓝[(λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' (e.target ∩ e.symm ⁻¹' (π F Z ⁻¹' s)) ∩
(range I ×ˢ univ)] (I q.1, q.2),
{ rw [nhds_within_le_iff, mem_nhds_within],
refine ⟨(λ (p : E × F), (I.symm p.1, p.snd)) ⁻¹' e.target, _, _, _⟩,
{ exact e.open_target.preimage (I.continuous_symm.prod_map continuous_id) },
{ simp only [prod.mk.eta] with mfld_simps at hq,
simp only [prod.mk.eta, hq] with mfld_simps },
rintro x hx,
simp only with mfld_simps at hx,
have h2x := hx,
simp only [e, fiber_bundle.charted_space_chart_at, trivialization.mem_target]
with mfld_simps at h2x,
simp only [h2s, hx, h2x, -preimage_inter] with mfld_simps },
refine unique_diff_within_at.mono_nhds _ this,
rw [h2s] at hq,
-- apply unique differentiability of products to conclude
apply unique_diff_on.prod _ unique_diff_on_univ,
{ simp only [hq] with mfld_simps },
{ assume x hx,
have A : unique_mdiff_on I (e₀.target ∩ e₀.symm⁻¹' s),
{ apply hs.unique_mdiff_on_preimage,
exact (mdifferentiable_of_mem_atlas _ (chart_mem_atlas _ _)),
apply_instance },
simp only [unique_mdiff_on, unique_mdiff_within_at, preimage_inter] with mfld_simps at A,
have B := A (I.symm x) hx.1.1 hx.1.2,
rwa [← preimage_inter, model_with_corners.right_inv _ hx.2] at B }
end
lemma unique_mdiff_on.tangent_bundle_proj_preimage (hs : unique_mdiff_on I s):
unique_mdiff_on I.tangent (π E (tangent_space I) ⁻¹' s) :=
hs.smooth_bundle_preimage _
end unique_mdiff
|
81b5c5f143fe5d39f4e227e6cabd57dc853cbccb | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/1433.lean | 3dec7cc651cb07a47b844ee6f99653306b45356f | [
"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 | 510 | lean | def dividend := 2^65
def divisor := 2^33+1
def correctQuot := 2^32-1
def correctRem := 2^32+1
def wrongRem := 1
theorem correct₁ : dividend / divisor = correctQuot := rfl
theorem correct₂ : dividend = divisor * correctQuot + correctRem := rfl
theorem wrong : dividend % divisor = wrongRem := rfl
theorem unsound : False := by
have : wrongRem = correctRem := by
have h := Nat.div_add_mod dividend divisor
rw [wrong, correct₁, correct₂] at h
apply Nat.add_left_cancel h
contradiction
|
bdd8dadcc4e8896a5df6a3300ffd5247558e90e7 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/pnat/xgcd.lean | 18129c7850407d58e82dc7bd6b1a4b5f0750fbc7 | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 13,645 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
-/
import tactic.ring
import data.pnat.prime
/-!
# Euclidean algorithm for ℕ
This file sets up a version of the Euclidean algorithm that only works with natural numbers.
Given `0 < a, b`, it computes the unique `(w, x, y, z, d)` such that the following identities hold:
* `a = (w + x) d`
* `b = (y + z) d`
* `w * z = x * y + 1`
`d` is then the gcd of `a` and `b`, and `a' := a / d = w + x` and `b' := b / d = y + z` are coprime.
This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and
the theory of continued fractions.
## Main declarations
* `xgcd_type`: Helper type in defining the gcd. Encapsulates `(wp, x, y, zp, ap, bp)`. where `wp`
`zp`, `ap`, `bp` are the variables getting changed through the algorithm.
* `is_special`: States `wp * zp = x * y + 1`
* `is_reduced`: States `ap = a ∧ bp = b`
## Notes
See `nat.xgcd` for a very similar algorithm allowing values in `ℤ`.
-/
open nat
namespace pnat
/-- A term of xgcd_type is a system of six naturals. They should
be thought of as representing the matrix
[[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]]
together with the vector [a, b] = [ap + 1, bp + 1].
-/
@[derive inhabited]
structure xgcd_type :=
(wp x y zp ap bp : ℕ)
namespace xgcd_type
variable (u : xgcd_type)
instance : has_sizeof xgcd_type := ⟨λ u, u.bp⟩
/-- The has_repr instance converts terms to strings in a way that
reflects the matrix/vector interpretation as above. -/
instance : has_repr xgcd_type :=
⟨λ u, "[[[" ++ (repr (u.wp + 1)) ++ ", " ++ (repr u.x) ++
"], [" ++ (repr u.y) ++ ", " ++ (repr (u.zp + 1)) ++ "]], [" ++
(repr (u.ap + 1)) ++ ", " ++ (repr (u.bp + 1)) ++ "]]"⟩
def mk' (w : ℕ+) (x : ℕ) (y : ℕ) (z : ℕ+) (a : ℕ+) (b : ℕ+) : xgcd_type :=
mk w.val.pred x y z.val.pred a.val.pred b.val.pred
def w : ℕ+ := succ_pnat u.wp
def z : ℕ+ := succ_pnat u.zp
def a : ℕ+ := succ_pnat u.ap
def b : ℕ+ := succ_pnat u.bp
def r : ℕ := (u.ap + 1) % (u.bp + 1)
def q : ℕ := (u.ap + 1) / (u.bp + 1)
def qp : ℕ := u.q - 1
/-- The map v gives the product of the matrix
[[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]]
and the vector [a, b] = [ap + 1, bp + 1]. The map
vp gives [sp, tp] such that v = [sp + 1, tp + 1].
-/
def vp : ℕ × ℕ :=
⟨ u.wp + u.x + u.ap + u.wp * u.ap + u.x * u.bp,
u.y + u.zp + u.bp + u.y * u.ap + u.zp * u.bp ⟩
def v : ℕ × ℕ := ⟨u.w * u.a + u.x * u.b, u.y * u.a + u.z * u.b⟩
def succ₂ (t : ℕ × ℕ) : ℕ × ℕ := ⟨t.1.succ, t.2.succ⟩
theorem v_eq_succ_vp : u.v = succ₂ u.vp :=
by { ext; dsimp [v, vp, w, z, a, b, succ₂];
repeat { rw [nat.succ_eq_add_one] }; ring }
/-- is_special holds if the matrix has determinant one. -/
def is_special : Prop := u.wp + u.zp + u.wp * u.zp = u.x * u.y
def is_special' : Prop := u.w * u.z = succ_pnat (u.x * u.y)
theorem is_special_iff : u.is_special ↔ u.is_special' :=
begin
dsimp [is_special, is_special'],
split; intro h,
{ apply eq, dsimp [w, z, succ_pnat], rw [← h],
repeat { rw [nat.succ_eq_add_one] }, ring },
{ apply nat.succ.inj,
replace h := congr_arg (coe : ℕ+ → ℕ) h,
rw [mul_coe, w, z] at h,
repeat { rw [succ_pnat_coe, nat.succ_eq_add_one] at h },
repeat { rw [nat.succ_eq_add_one] }, rw [← h], ring }
end
/-- is_reduced holds if the two entries in the vector are the
same. The reduction algorithm will produce a system with this
property, whose product vector is the same as for the original
system. -/
def is_reduced : Prop := u.ap = u.bp
def is_reduced' : Prop := u.a = u.b
theorem is_reduced_iff : u.is_reduced ↔ u.is_reduced' :=
⟨ congr_arg succ_pnat, succ_pnat_inj ⟩
def flip : xgcd_type :=
{ wp := u.zp, x := u.y, y := u.x, zp := u.wp, ap := u.bp, bp := u.ap }
@[simp] theorem flip_w : (flip u).w = u.z := rfl
@[simp] theorem flip_x : (flip u).x = u.y := rfl
@[simp] theorem flip_y : (flip u).y = u.x := rfl
@[simp] theorem flip_z : (flip u).z = u.w := rfl
@[simp] theorem flip_a : (flip u).a = u.b := rfl
@[simp] theorem flip_b : (flip u).b = u.a := rfl
theorem flip_is_reduced : (flip u).is_reduced ↔ u.is_reduced :=
by { dsimp [is_reduced, flip], split; intro h; exact h.symm }
theorem flip_is_special : (flip u).is_special ↔ u.is_special :=
by { dsimp [is_special, flip], rw[mul_comm u.x, mul_comm u.zp, add_comm u.zp] }
theorem flip_v : (flip u).v = (u.v).swap :=
by { dsimp [v], ext, { simp only, ring }, { simp only, ring } }
/-- Properties of division with remainder for a / b. -/
theorem rq_eq : u.r + (u.bp + 1) * u.q = u.ap + 1 :=
nat.mod_add_div (u.ap + 1) (u.bp + 1)
theorem qp_eq (hr : u.r = 0) : u.q = u.qp + 1 :=
begin
by_cases hq : u.q = 0,
{ let h := u.rq_eq, rw [hr, hq, mul_zero, add_zero] at h, cases h },
{ exact (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hq)).symm }
end
/-- The following function provides the starting point for
our algorithm. We will apply an iterative reduction process
to it, which will produce a system satisfying is_reduced.
The gcd can be read off from this final system.
-/
def start (a b : ℕ+) : xgcd_type := ⟨0, 0, 0, 0, a - 1, b - 1⟩
theorem start_is_special (a b : ℕ+) : (start a b).is_special :=
by { dsimp [start, is_special], refl }
theorem start_v (a b : ℕ+) : (start a b).v = ⟨a, b⟩ :=
begin
dsimp [start, v, xgcd_type.a, xgcd_type.b, w, z],
rw [one_mul, one_mul, zero_mul, zero_mul, zero_add, add_zero],
rw [← nat.pred_eq_sub_one, ← nat.pred_eq_sub_one],
rw [nat.succ_pred_eq_of_pos a.pos, nat.succ_pred_eq_of_pos b.pos]
end
def finish : xgcd_type :=
xgcd_type.mk u.wp ((u.wp + 1) * u.qp + u.x) u.y (u.y * u.qp + u.zp) u.bp u.bp
theorem finish_is_reduced : u.finish.is_reduced :=
by { dsimp [is_reduced], refl }
theorem finish_is_special (hs : u.is_special) : u.finish.is_special :=
begin
dsimp [is_special, finish] at hs ⊢,
rw [add_mul _ _ u.y, add_comm _ (u.x * u.y), ← hs],
ring
end
theorem finish_v (hr : u.r = 0) : u.finish.v = u.v :=
begin
let ha : u.r + u.b * u.q = u.a := u.rq_eq,
rw [hr, zero_add] at ha,
ext,
{ change (u.wp + 1) * u.b + ((u.wp + 1) * u.qp + u.x) * u.b = u.w * u.a + u.x * u.b,
have : u.wp + 1 = u.w := rfl, rw [this, ← ha, u.qp_eq hr], ring },
{ change u.y * u.b + (u.y * u.qp + u.z) * u.b = u.y * u.a + u.z * u.b,
rw [← ha, u.qp_eq hr], ring }
end
/-- This is the main reduction step, which is used when u.r ≠ 0, or
equivalently b does not divide a. -/
def step : xgcd_type :=
xgcd_type.mk (u.y * u.q + u.zp) u.y ((u.wp + 1) * u.q + u.x) u.wp u.bp (u.r - 1)
/-- We will apply the above step recursively. The following result
is used to ensure that the process terminates. -/
theorem step_wf (hr : u.r ≠ 0) : sizeof u.step < sizeof u :=
begin
change u.r - 1 < u.bp,
have h₀ : (u.r - 1) + 1 = u.r := nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hr),
have h₁ : u.r < u.bp + 1 := nat.mod_lt (u.ap + 1) u.bp.succ_pos,
rw[← h₀] at h₁,
exact lt_of_succ_lt_succ h₁,
end
theorem step_is_special (hs : u.is_special) : u.step.is_special :=
begin
dsimp [is_special, step] at hs ⊢,
rw [mul_add, mul_comm u.y u.x, ← hs],
ring
end
/-- The reduction step does not change the product vector. -/
theorem step_v (hr : u.r ≠ 0) : u.step.v = (u.v).swap :=
begin
let ha : u.r + u.b * u.q = u.a := u.rq_eq,
let hr : (u.r - 1) + 1 = u.r :=
(add_comm _ 1).trans (nat.add_sub_of_le (nat.pos_of_ne_zero hr)),
ext,
{ change ((u.y * u.q + u.z) * u.b + u.y * (u.r - 1 + 1) : ℕ) = u.y * u.a + u.z * u.b,
rw [← ha, hr], ring },
{ change ((u.w * u.q + u.x) * u.b + u.w * (u.r - 1 + 1) : ℕ) = u.w * u.a + u.x * u.b,
rw [← ha, hr], ring }
end
/-- We can now define the full reduction function, which applies
step as long as possible, and then applies finish. Note that the
"have" statement puts a fact in the local context, and the
equation compiler uses this fact to help construct the full
definition in terms of well-founded recursion. The same fact
needs to be introduced in all the inductive proofs of properties
given below. -/
def reduce : xgcd_type → xgcd_type
| u := dite (u.r = 0)
(λ h, u.finish)
(λ h, have sizeof u.step < sizeof u, from u.step_wf h,
flip (reduce u.step))
theorem reduce_a {u : xgcd_type} (h : u.r = 0) :
u.reduce = u.finish := by { rw [reduce], simp only, rw [if_pos h] }
theorem reduce_b {u : xgcd_type} (h : u.r ≠ 0) :
u.reduce = u.step.reduce.flip := by { rw [reduce], simp only, rw [if_neg h, step] }
theorem reduce_reduced : ∀ (u : xgcd_type), u.reduce.is_reduced
| u := dite (u.r = 0) (λ h, by { rw [reduce_a h], exact u.finish_is_reduced })
(λ h, have sizeof u.step < sizeof u, from u.step_wf h,
by { rw [reduce_b h, flip_is_reduced], apply reduce_reduced })
theorem reduce_reduced' (u : xgcd_type) : u.reduce.is_reduced' :=
(is_reduced_iff _).mp u.reduce_reduced
theorem reduce_special : ∀ (u : xgcd_type), u.is_special → u.reduce.is_special
| u := dite (u.r = 0)
(λ h hs, by { rw [reduce_a h], exact u.finish_is_special hs })
(λ h hs, have sizeof u.step < sizeof u, from u.step_wf h,
by { rw [reduce_b h],
exact (flip_is_special _).mpr (reduce_special _ (u.step_is_special hs)) })
theorem reduce_special' (u : xgcd_type) (hs : u.is_special) : u.reduce.is_special' :=
(is_special_iff _).mp (u.reduce_special hs)
theorem reduce_v : ∀ (u : xgcd_type), u.reduce.v = u.v
| u := dite (u.r = 0)
(λ h, by {rw[reduce_a h, finish_v u h]})
(λ h, have sizeof u.step < sizeof u, from u.step_wf h,
by { rw[reduce_b h, flip_v, reduce_v (step u), step_v u h, prod.swap_swap] })
end xgcd_type
section gcd
variables (a b : ℕ+)
def xgcd : xgcd_type := (xgcd_type.start a b).reduce
def gcd_d : ℕ+ := (xgcd a b).a
def gcd_w : ℕ+ := (xgcd a b).w
def gcd_x : ℕ := (xgcd a b).x
def gcd_y : ℕ := (xgcd a b).y
def gcd_z : ℕ+ := (xgcd a b).z
def gcd_a' : ℕ+ := succ_pnat ((xgcd a b).wp + (xgcd a b).x)
def gcd_b' : ℕ+ := succ_pnat ((xgcd a b).y + (xgcd a b).zp)
theorem gcd_a'_coe : ((gcd_a' a b) : ℕ) = (gcd_w a b) + (gcd_x a b) :=
by { dsimp [gcd_a', gcd_x, gcd_w, xgcd_type.w],
rw [nat.succ_eq_add_one, nat.succ_eq_add_one, add_right_comm] }
theorem gcd_b'_coe : ((gcd_b' a b) : ℕ) = (gcd_y a b) + (gcd_z a b) :=
by { dsimp [gcd_b', gcd_y, gcd_z, xgcd_type.z],
rw [nat.succ_eq_add_one, nat.succ_eq_add_one, add_assoc] }
theorem gcd_props :
let d := gcd_d a b,
w := gcd_w a b, x := gcd_x a b, y := gcd_y a b, z := gcd_z a b,
a' := gcd_a' a b, b' := gcd_b' a b in
(w * z = succ_pnat (x * y) ∧
(a = a' * d) ∧ (b = b' * d) ∧
z * a' = succ_pnat (x * b') ∧ w * b' = succ_pnat (y * a') ∧
(z * a : ℕ) = x * b + d ∧ (w * b : ℕ) = y * a + d
) :=
begin
intros,
let u := (xgcd_type.start a b),
let ur := u.reduce,
have ha : d = ur.a := rfl,
have hb : d = ur.b := u.reduce_reduced',
have ha' : (a' : ℕ) = w + x := gcd_a'_coe a b,
have hb' : (b' : ℕ) = y + z := gcd_b'_coe a b,
have hdet : w * z = succ_pnat (x * y) := u.reduce_special' rfl,
split, exact hdet,
have hdet' : ((w * z) : ℕ) = x * y + 1 :=
by { rw [← mul_coe, hdet, succ_pnat_coe] },
have huv : u.v = ⟨a, b⟩ := (xgcd_type.start_v a b),
let hv : prod.mk (w * d + x * ur.b : ℕ) (y * d + z * ur.b : ℕ) = ⟨a, b⟩ :=
u.reduce_v.trans (xgcd_type.start_v a b),
rw [← hb, ← add_mul, ← add_mul, ← ha', ← hb'] at hv,
have ha'' : (a : ℕ) = a' * d := (congr_arg prod.fst hv).symm,
have hb'' : (b : ℕ) = b' * d := (congr_arg prod.snd hv).symm,
split, exact eq ha'', split, exact eq hb'',
have hza' : (z * a' : ℕ) = x * b' + 1,
by { rw [ha', hb', mul_add, mul_add, mul_comm (z : ℕ), hdet'], ring },
have hwb' : (w * b' : ℕ) = y * a' + 1,
by { rw [ha', hb', mul_add, mul_add, hdet'], ring },
split,
{ apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hza'] },
split,
{ apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hwb'] },
rw [ha'', hb''], repeat { rw [← mul_assoc] }, rw [hza', hwb'],
split; ring,
end
theorem gcd_eq : gcd_d a b = gcd a b :=
begin
rcases gcd_props a b with ⟨h₀, h₁, h₂, h₃, h₄, h₅, h₆⟩,
apply dvd_antisymm,
{ apply dvd_gcd,
exact dvd.intro (gcd_a' a b) (h₁.trans (mul_comm _ _)).symm,
exact dvd.intro (gcd_b' a b) (h₂.trans (mul_comm _ _)).symm},
{ have h₇ : (gcd a b : ℕ) ∣ (gcd_z a b) * a :=
dvd_trans (nat.gcd_dvd_left a b) (dvd_mul_left _ _),
have h₈ : (gcd a b : ℕ) ∣ (gcd_x a b) * b :=
dvd_trans (nat.gcd_dvd_right a b) (dvd_mul_left _ _),
rw[h₅] at h₇, rw dvd_iff,
exact (nat.dvd_add_iff_right h₈).mpr h₇,}
end
theorem gcd_det_eq :
(gcd_w a b) * (gcd_z a b) = succ_pnat ((gcd_x a b) * (gcd_y a b)) :=
(gcd_props a b).1
theorem gcd_a_eq : a = (gcd_a' a b) * (gcd a b) :=
(gcd_eq a b) ▸ (gcd_props a b).2.1
theorem gcd_b_eq : b = (gcd_b' a b) * (gcd a b) :=
(gcd_eq a b) ▸ (gcd_props a b).2.2.1
theorem gcd_rel_left' :
(gcd_z a b) * (gcd_a' a b) = succ_pnat ((gcd_x a b) * (gcd_b' a b)) :=
(gcd_props a b).2.2.2.1
theorem gcd_rel_right' :
(gcd_w a b) * (gcd_b' a b) = succ_pnat ((gcd_y a b) * (gcd_a' a b)) :=
(gcd_props a b).2.2.2.2.1
theorem gcd_rel_left :
((gcd_z a b) * a : ℕ) = (gcd_x a b) * b + (gcd a b) :=
(gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.1
theorem gcd_rel_right :
((gcd_w a b) * b : ℕ) = (gcd_y a b) * a + (gcd a b) :=
(gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.2
end gcd
end pnat
|
0287fe3f4a2f495d9ccf5f0ef6fd1ff648d16df6 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/tactic/alias.lean | a4fe87f82de478bebf46285e4a774b2cc9fb8ba0 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 6,036 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.core
/-!
# The `alias` command
This file defines an `alias` command, which can be used to create copies
of a theorem or definition with different names.
Syntax:
```lean
/-- doc string -/
alias my_theorem ← alias1 alias2 ...
```
This produces defs or theorems of the form:
```lean
/-- doc string -/
@[alias] theorem alias1 : <type of my_theorem> := my_theorem
/-- doc string -/
@[alias] theorem alias2 : <type of my_theorem> := my_theorem
```
Iff alias syntax:
```lean
alias A_iff_B ↔ B_of_A A_of_B
alias A_iff_B ↔ ..
```
This gets an existing biconditional theorem `A_iff_B` and produces
the one-way implications `B_of_A` and `A_of_B` (with no change in
implicit arguments). A blank `_` can be used to avoid generating one direction.
The `..` notation attempts to generate the 'of'-names automatically when the
input theorem has the form `A_iff_B` or `A_iff_B_left` etc.
-/
open lean.parser tactic interactive
namespace tactic.alias
/-- An alias can be in one of three forms -/
@[derive has_reflect]
meta inductive target
| plain : name -> target
| forward : name -> target
| backwards : name -> target
/-- The name underlying an alias target -/
meta def target.to_name : target → name
| (target.plain n) := n
| (target.forward n) := n
| (target.backwards n) := n
/-- The docstring for an alias. Used by `alias` _and_ by `to_additive` -/
meta def target.to_string : target → string
| (target.plain n) := sformat!"**Alias** of {n}`."
| (target.forward n) := sformat!"**Alias** of the forward direction of {n}`."
| (target.backwards n) := sformat!"**Alias** of the reverse direction of {n}`."
@[user_attribute] meta def alias_attr : user_attribute unit target :=
{ name := `alias, descr := "This definition is an alias of another.", parser := failed }
meta def alias_direct (d : declaration) (al : name) : tactic unit :=
do updateex_env $ λ env,
env.add (match d.to_definition with
| declaration.defn n ls t _ _ _ :=
declaration.defn al ls t (expr.const n (level.param <$> ls))
reducibility_hints.abbrev tt
| declaration.thm n ls t _ :=
declaration.thm al ls t $ task.pure $ expr.const n (level.param <$> ls)
| _ := undefined
end),
let target := target.plain d.to_name,
alias_attr.set al target tt,
add_doc_string al target.to_string
meta def mk_iff_mp_app (iffmp : name) : expr → (ℕ → expr) → tactic expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := pure $ @expr.const tt iffmp [] a b (f 0)
| _ f := fail "Target theorem must have the form `Π x y z, a ↔ b`"
meta def alias_iff (d : declaration) (al : name) (is_forward : bool) : tactic unit :=
(if al = `_ then skip else get_decl al >> skip) <|> do
let ls := d.univ_params,
let t := d.type,
let target := if is_forward then target.forward d.to_name else target.backwards d.to_name,
let iffmp := if is_forward then `iff.mp else `iff.mpr,
v ← mk_iff_mp_app iffmp t (λ_, expr.const d.to_name (level.param <$> ls)),
t' ← infer_type v,
updateex_env $ λ env, env.add (declaration.thm al ls t' $ task.pure v),
alias_attr.set al target tt,
add_doc_string al target.to_string
meta def make_left_right : name → tactic (name × name)
| (name.mk_string s p) := do
let buf : char_buffer := s.to_char_buffer,
let parts := s.split_on '_',
(left, _::right) ← pure $ parts.span (≠ "iff"),
let pfx (a b : string) := a.to_list.is_prefix_of b.to_list,
(suffix', right') ← pure $ right.reverse.span (λ s, pfx "left" s ∨ pfx "right" s),
let right := right'.reverse,
let suffix := suffix'.reverse,
pure (p <.> "_".intercalate (right ++ "of" :: left ++ suffix),
p <.> "_".intercalate (left ++ "of" :: right ++ suffix))
| _ := failed
/--
The `alias` command can be used to create copies
of a theorem or definition with different names.
Syntax:
```lean
/-- doc string -/
alias my_theorem ← alias1 alias2 ...
```
This produces defs or theorems of the form:
```lean
/-- doc string -/
@[alias] theorem alias1 : <type of my_theorem> := my_theorem
/-- doc string -/
@[alias] theorem alias2 : <type of my_theorem> := my_theorem
```
Iff alias syntax:
```lean
alias A_iff_B ↔ B_of_A A_of_B
alias A_iff_B ↔ ..
```
This gets an existing biconditional theorem `A_iff_B` and produces
the one-way implications `B_of_A` and `A_of_B` (with no change in
implicit arguments). A blank `_` can be used to avoid generating one direction.
The `..` notation attempts to generate the 'of'-names automatically when the
input theorem has the form `A_iff_B` or `A_iff_B_left` etc.
-/
@[user_command] meta def alias_cmd (meta_info : decl_meta_info)
(_ : parse $ tk "alias") : lean.parser unit :=
do old ← ident,
d ← (do old ← resolve_constant old, get_decl old) <|>
fail ("declaration " ++ to_string old ++ " not found"),
let doc := λ (al : name) (inf : string), meta_info.doc_string.get_or_else $
sformat!"**Alias** of {inf}`{old}`.",
do
{ tk "←" <|> tk "<-",
aliases ← many ident,
↑(aliases.mmap' $ λ al, alias_direct d al) } <|>
do
{ tk "↔" <|> tk "<->",
(left, right) ←
mcond ((tk ".." >> pure tt) <|> pure ff)
(make_left_right old <|> fail "invalid name for automatic name generation")
(prod.mk <$> types.ident_ <*> types.ident_),
alias_iff d left tt,
alias_iff d right ff }
add_tactic_doc
{ name := "alias",
category := doc_category.cmd,
decl_names := [`tactic.alias.alias_cmd],
tags := ["renaming"] }
meta def get_lambda_body : expr → expr
| (expr.lam _ _ _ b) := get_lambda_body b
| a := a
meta def get_alias_target (n : name) : tactic (option target) :=
do tt ← has_attribute' `alias n | pure none,
v ← alias_attr.get_param n,
pure $ some v
end tactic.alias
|
9eb66dc5aa626ffca32fe0edf284eedc947807aa | c777c32c8e484e195053731103c5e52af26a25d1 | /src/topology/continuous_function/zero_at_infty.lean | 2eca0c8ff9a9281ad3d894a5ce496287c8e781e5 | [
"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 | 22,927 | lean | /-
Copyright (c) 2022 Jireh Loreaux. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jireh Loreaux
-/
import topology.continuous_function.bounded
import topology.continuous_function.cocompact_map
/-!
# Continuous functions vanishing at infinity
The type of continuous functions vanishing at infinity. When the domain is compact
`C(α, β) ≃ C₀(α, β)` via the identity map. When the codomain is a metric space, every continuous
map which vanishes at infinity is a bounded continuous function. When the domain is a locally
compact space, this type has nice properties.
## TODO
* Create more intances of algebraic structures (e.g., `non_unital_semiring`) once the necessary
type classes (e.g., `topological_ring`) are sufficiently generalized.
* Relate the unitization of `C₀(α, β)` to the Alexandroff compactification.
-/
universes u v w
variables {F : Type*} {α : Type u} {β : Type v} {γ : Type w} [topological_space α]
open_locale bounded_continuous_function topology
open filter metric
/-- `C₀(α, β)` is the type of continuous functions `α → β` which vanish at infinity from a
topological space to a metric space with a zero element.
When possible, instead of parametrizing results over `(f : C₀(α, β))`,
you should parametrize over `(F : Type*) [zero_at_infty_continuous_map_class F α β] (f : F)`.
When you extend this structure, make sure to extend `zero_at_infty_continuous_map_class`. -/
structure zero_at_infty_continuous_map (α : Type u) (β : Type v)
[topological_space α] [has_zero β] [topological_space β] extends continuous_map α β :
Type (max u v) :=
(zero_at_infty' : tendsto to_fun (cocompact α) (𝓝 0))
localized "notation [priority 2000] (name := zero_at_infty_continuous_map)
`C₀(` α `, ` β `)` := zero_at_infty_continuous_map α β" in zero_at_infty
localized "notation (name := zero_at_infty_continuous_map.arrow)
α ` →C₀ ` β := zero_at_infty_continuous_map α β" in zero_at_infty
section
set_option old_structure_cmd true
/-- `zero_at_infty_continuous_map_class F α β` states that `F` is a type of continuous maps which
vanish at infinity.
You should also extend this typeclass when you extend `zero_at_infty_continuous_map`. -/
class zero_at_infty_continuous_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α]
[has_zero β] [topological_space β] extends continuous_map_class F α β :=
(zero_at_infty (f : F) : tendsto f (cocompact α) (𝓝 0))
end
export zero_at_infty_continuous_map_class (zero_at_infty)
namespace zero_at_infty_continuous_map
section basics
variables [topological_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β]
instance : zero_at_infty_continuous_map_class C₀(α, β) α β :=
{ coe := λ f, f.to_fun,
coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' },
map_continuous := λ f, f.continuous_to_fun,
zero_at_infty := λ f, f.zero_at_infty' }
/-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`
directly. -/
instance : has_coe_to_fun C₀(α, β) (λ _, α → β) := fun_like.has_coe_to_fun
instance : has_coe_t F C₀(α, β) :=
⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f, zero_at_infty' := zero_at_infty f }⟩
@[simp] lemma coe_to_continuous_fun (f : C₀(α, β)) : (f.to_continuous_map : α → β) = f := rfl
@[ext] lemma ext {f g : C₀(α, β)} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h
/-- Copy of a `zero_at_infinity_continuous_map` with a new `to_fun` equal to the old one. Useful
to fix definitional equalities. -/
protected def copy (f : C₀(α, β)) (f' : α → β) (h : f' = f) : C₀(α, β) :=
{ to_fun := f',
continuous_to_fun := by { rw h, exact f.continuous_to_fun },
zero_at_infty' := by { simp_rw h, exact f.zero_at_infty' } }
@[simp] lemma coe_copy (f : C₀(α, β)) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl
lemma copy_eq (f : C₀(α, β)) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h
lemma eq_of_empty [is_empty α] (f g : C₀(α, β)) : f = g :=
ext $ is_empty.elim ‹_›
/-- A continuous function on a compact space is automatically a continuous function vanishing at
infinity. -/
@[simps]
def continuous_map.lift_zero_at_infty [compact_space α] : C(α, β) ≃ C₀(α, β) :=
{ to_fun := λ f, { to_fun := f, continuous_to_fun := f.continuous, zero_at_infty' := by simp },
inv_fun := λ f, f,
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- A continuous function on a compact space is automatically a continuous function vanishing at
infinity. This is not an instance to avoid type class loops. -/
@[simps]
def zero_at_infty_continuous_map_class.of_compact {G : Type*} [continuous_map_class G α β]
[compact_space α] : zero_at_infty_continuous_map_class G α β :=
{ coe := λ g, g,
coe_injective' := λ f g h, fun_like.coe_fn_eq.mp h,
map_continuous := map_continuous,
zero_at_infty := by simp }
end basics
/-! ### Algebraic structure
Whenever `β` has suitable algebraic structure and a compatible topological structure, then
`C₀(α, β)` inherits a corresponding algebraic structure. The primary exception to this is that
`C₀(α, β)` will not have a multiplicative identity.
-/
section algebraic_structure
variables [topological_space β] (x : α)
instance [has_zero β] : has_zero C₀(α, β) := ⟨⟨0, tendsto_const_nhds⟩⟩
instance [has_zero β] : inhabited C₀(α, β) := ⟨0⟩
@[simp] lemma coe_zero [has_zero β] : ⇑(0 : C₀(α, β)) = 0 := rfl
lemma zero_apply [has_zero β] : (0 : C₀(α, β)) x = 0 := rfl
instance [mul_zero_class β] [has_continuous_mul β] : has_mul C₀(α, β) :=
⟨λ f g, ⟨f * g, by simpa only [mul_zero] using (zero_at_infty f).mul (zero_at_infty g)⟩⟩
@[simp] lemma coe_mul [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) :
⇑(f * g) = f * g := rfl
lemma mul_apply [mul_zero_class β] [has_continuous_mul β] (f g : C₀(α, β)) :
(f * g) x = f x * g x := rfl
instance [mul_zero_class β] [has_continuous_mul β] : mul_zero_class C₀(α, β) :=
fun_like.coe_injective.mul_zero_class _ coe_zero coe_mul
instance [semigroup_with_zero β] [has_continuous_mul β] : semigroup_with_zero C₀(α, β) :=
fun_like.coe_injective.semigroup_with_zero _ coe_zero coe_mul
instance [add_zero_class β] [has_continuous_add β] : has_add C₀(α, β) :=
⟨λ f g, ⟨f + g, by simpa only [add_zero] using (zero_at_infty f).add (zero_at_infty g)⟩⟩
@[simp] lemma coe_add [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) :
⇑(f + g) = f + g := rfl
lemma add_apply [add_zero_class β] [has_continuous_add β] (f g : C₀(α, β)) :
(f + g) x = f x + g x := rfl
instance [add_zero_class β] [has_continuous_add β] : add_zero_class C₀(α, β) :=
fun_like.coe_injective.add_zero_class _ coe_zero coe_add
section add_monoid
variables [add_monoid β] [has_continuous_add β] (f g : C₀(α, β))
@[simp] lemma coe_nsmul_rec : ∀ n, ⇑(nsmul_rec n f) = n • f
| 0 := by rw [nsmul_rec, zero_smul, coe_zero]
| (n + 1) := by rw [nsmul_rec, succ_nsmul, coe_add, coe_nsmul_rec]
instance has_nat_scalar : has_smul ℕ C₀(α, β) :=
⟨λ n f, ⟨n • f, by simpa [coe_nsmul_rec] using zero_at_infty (nsmul_rec n f)⟩⟩
instance : add_monoid C₀(α, β) :=
fun_like.coe_injective.add_monoid _ coe_zero coe_add (λ _ _, rfl)
end add_monoid
instance [add_comm_monoid β] [has_continuous_add β] : add_comm_monoid C₀(α, β) :=
fun_like.coe_injective.add_comm_monoid _ coe_zero coe_add (λ _ _, rfl)
section add_group
variables [add_group β] [topological_add_group β] (f g : C₀(α, β))
instance : has_neg C₀(α, β) :=
⟨λ f, ⟨-f, by simpa only [neg_zero] using (zero_at_infty f).neg⟩⟩
@[simp] lemma coe_neg : ⇑(-f) = -f := rfl
lemma neg_apply : (-f) x = -f x := rfl
instance : has_sub C₀(α, β) :=
⟨λ f g, ⟨f - g, by simpa only [sub_zero] using (zero_at_infty f).sub (zero_at_infty g)⟩⟩
@[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl
lemma sub_apply : (f - g) x = f x - g x := rfl
@[simp] lemma coe_zsmul_rec : ∀ z, ⇑(zsmul_rec z f) = z • f
| (int.of_nat n) := by rw [zsmul_rec, int.of_nat_eq_coe, coe_nsmul_rec, coe_nat_zsmul]
| -[1+ n] := by rw [zsmul_rec, zsmul_neg_succ_of_nat, coe_neg, coe_nsmul_rec]
instance has_int_scalar : has_smul ℤ C₀(α, β) :=
⟨λ n f, ⟨n • f, by simpa using zero_at_infty (zsmul_rec n f)⟩⟩
instance : add_group C₀(α, β) :=
fun_like.coe_injective.add_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl)
end add_group
instance [add_comm_group β] [topological_add_group β] : add_comm_group C₀(α, β) :=
fun_like.coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, rfl) (λ _ _, rfl)
instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β]
[has_continuous_const_smul R β] : has_smul R C₀(α, β) :=
⟨λ r f, ⟨r • f, by simpa [smul_zero] using (zero_at_infty f).const_smul r⟩⟩
@[simp] lemma coe_smul [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β]
[has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) : ⇑(r • f) = r • f := rfl
lemma smul_apply [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β]
[has_continuous_const_smul R β] (r : R) (f : C₀(α, β)) (x : α) : (r • f) x = r • f x := rfl
instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β] [smul_with_zero Rᵐᵒᵖ β]
[has_continuous_const_smul R β] [is_central_scalar R β] : is_central_scalar R C₀(α, β) :=
⟨λ r f, ext $ λ x, op_smul_eq_smul _ _⟩
instance [has_zero β] {R : Type*} [has_zero R] [smul_with_zero R β]
[has_continuous_const_smul R β] : smul_with_zero R C₀(α, β) :=
function.injective.smul_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul
instance [has_zero β] {R : Type*} [monoid_with_zero R] [mul_action_with_zero R β]
[has_continuous_const_smul R β] : mul_action_with_zero R C₀(α, β) :=
function.injective.mul_action_with_zero ⟨_, coe_zero⟩ fun_like.coe_injective coe_smul
instance [add_comm_monoid β] [has_continuous_add β] {R : Type*} [semiring R] [module R β]
[has_continuous_const_smul R β] : module R C₀(α, β) :=
function.injective.module R ⟨_, coe_zero, coe_add⟩ fun_like.coe_injective coe_smul
instance [non_unital_non_assoc_semiring β] [topological_semiring β] :
non_unital_non_assoc_semiring C₀(α, β) :=
fun_like.coe_injective.non_unital_non_assoc_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl)
instance [non_unital_semiring β] [topological_semiring β] :
non_unital_semiring C₀(α, β) :=
fun_like.coe_injective.non_unital_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl)
instance [non_unital_comm_semiring β] [topological_semiring β] :
non_unital_comm_semiring C₀(α, β) :=
fun_like.coe_injective.non_unital_comm_semiring _ coe_zero coe_add coe_mul (λ _ _, rfl)
instance [non_unital_non_assoc_ring β] [topological_ring β] :
non_unital_non_assoc_ring C₀(α, β) :=
fun_like.coe_injective.non_unital_non_assoc_ring _ coe_zero coe_add coe_mul coe_neg coe_sub
(λ _ _, rfl) (λ _ _, rfl)
instance [non_unital_ring β] [topological_ring β] :
non_unital_ring C₀(α, β) :=
fun_like.coe_injective.non_unital_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl)
(λ _ _, rfl)
instance [non_unital_comm_ring β] [topological_ring β] :
non_unital_comm_ring C₀(α, β) :=
fun_like.coe_injective.non_unital_comm_ring _ coe_zero coe_add coe_mul coe_neg coe_sub (λ _ _, rfl)
(λ _ _, rfl)
instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β]
[module R β] [has_continuous_const_smul R β] [is_scalar_tower R β β] :
is_scalar_tower R C₀(α, β) C₀(α, β) :=
{ smul_assoc := λ r f g,
begin
ext,
simp only [smul_eq_mul, coe_mul, coe_smul, pi.mul_apply, pi.smul_apply],
rw [←smul_eq_mul, ←smul_eq_mul, smul_assoc],
end }
instance {R : Type*} [semiring R] [non_unital_non_assoc_semiring β] [topological_semiring β]
[module R β] [has_continuous_const_smul R β] [smul_comm_class R β β] :
smul_comm_class R C₀(α, β) C₀(α, β) :=
{ smul_comm := λ r f g,
begin
ext,
simp only [smul_eq_mul, coe_smul, coe_mul, pi.smul_apply, pi.mul_apply],
rw [←smul_eq_mul, ←smul_eq_mul, smul_comm],
end }
end algebraic_structure
section uniform
variables [uniform_space β] [uniform_space γ] [has_zero γ]
[zero_at_infty_continuous_map_class F β γ]
lemma uniform_continuous (f : F) : uniform_continuous (f : β → γ) :=
(map_continuous f).uniform_continuous_of_tendsto_cocompact (zero_at_infty f)
end uniform
/-! ### Metric structure
When `β` is a metric space, then every element of `C₀(α, β)` is bounded, and so there is a natural
inclusion map `zero_at_infty_continuous_map.to_bcf : C₀(α, β) → (α →ᵇ β)`. Via this map `C₀(α, β)`
inherits a metric as the pullback of the metric on `α →ᵇ β`. Moreover, this map has closed range
in `α →ᵇ β` and consequently `C₀(α, β)` is a complete space whenever `β` is complete.
-/
section metric
open metric set
variables [metric_space β] [has_zero β] [zero_at_infty_continuous_map_class F α β]
protected lemma bounded (f : F) : ∃ C, ∀ x y : α, dist ((f : α → β) x) (f y) ≤ C :=
begin
obtain ⟨K : set α, hK₁, hK₂⟩ := mem_cocompact.mp (tendsto_def.mp (zero_at_infty (f : F)) _
(closed_ball_mem_nhds (0 : β) zero_lt_one)),
obtain ⟨C, hC⟩ := (hK₁.image (map_continuous f)).bounded.subset_ball (0 : β),
refine ⟨max C 1 + max C 1, (λ x y, _)⟩,
have : ∀ x, f x ∈ closed_ball (0 : β) (max C 1),
{ intro x,
by_cases hx : x ∈ K,
{ exact (mem_closed_ball.mp $ hC ⟨x, hx, rfl⟩).trans (le_max_left _ _) },
{ exact (mem_closed_ball.mp $ mem_preimage.mp (hK₂ hx)).trans (le_max_right _ _) } },
exact (dist_triangle (f x) 0 (f y)).trans
(add_le_add (mem_closed_ball.mp $ this x) (mem_closed_ball'.mp $ this y)),
end
lemma bounded_range (f : C₀(α, β)) : bounded (range f) :=
bounded_range_iff.2 f.bounded
lemma bounded_image (f : C₀(α, β)) (s : set α) : bounded (f '' s) :=
f.bounded_range.mono $ image_subset_range _ _
@[priority 100]
instance : bounded_continuous_map_class F α β :=
{ map_bounded := λ f, zero_at_infty_continuous_map.bounded f,
..‹zero_at_infty_continuous_map_class F α β› }
/-- Construct a bounded continuous function from a continuous function vanishing at infinity. -/
@[simps]
def to_bcf (f : C₀(α, β)) : α →ᵇ β :=
⟨f, map_bounded f⟩
section
variables (α) (β)
lemma to_bcf_injective :
function.injective (to_bcf : C₀(α, β) → α →ᵇ β) :=
λ f g h, by { ext, simpa only using fun_like.congr_fun h x, }
end
variables {C : ℝ} {f g : C₀(α, β)}
/-- The type of continuous functions vanishing at infinity, with the uniform distance induced by the
inclusion `zero_at_infinity_continuous_map.to_bcf`, is a metric space. -/
noncomputable instance : metric_space C₀(α, β) :=
metric_space.induced _ (to_bcf_injective α β) (by apply_instance)
@[simp]
lemma dist_to_bcf_eq_dist {f g : C₀(α, β)} : dist f.to_bcf g.to_bcf = dist f g := rfl
open bounded_continuous_function
/-- Convergence in the metric on `C₀(α, β)` is uniform convergence. -/
lemma tendsto_iff_tendsto_uniformly {ι : Type*} {F : ι → C₀(α, β)} {f : C₀(α, β)} {l : filter ι} :
tendsto F l (𝓝 f) ↔ tendsto_uniformly (λ i, F i) f l :=
by simpa only [metric.tendsto_nhds] using @bounded_continuous_function.tendsto_iff_tendsto_uniformly
_ _ _ _ _ (λ i, (F i).to_bcf) f.to_bcf l
lemma isometry_to_bcf : isometry (to_bcf : C₀(α, β) → α →ᵇ β) := by tauto
lemma closed_range_to_bcf : is_closed (range (to_bcf : C₀(α, β) → α →ᵇ β)) :=
begin
refine is_closed_iff_cluster_pt.mpr (λ f hf, _),
rw cluster_pt_principal_iff at hf,
have : tendsto f (cocompact α) (𝓝 0),
{ refine metric.tendsto_nhds.mpr (λ ε hε, _),
obtain ⟨_, hg, g, rfl⟩ := hf (ball f (ε / 2)) (ball_mem_nhds f $ half_pos hε),
refine (metric.tendsto_nhds.mp (zero_at_infty g) (ε / 2)
(half_pos hε)).mp (eventually_of_forall $ λ x hx, _),
calc dist (f x) 0 ≤ dist (g.to_bcf x) (f x) + dist (g x) 0 : dist_triangle_left _ _ _
... < dist g.to_bcf f + ε / 2 : add_lt_add_of_le_of_lt (dist_coe_le_dist x) hx
... < ε : by simpa [add_halves ε] using add_lt_add_right hg (ε / 2) },
exact ⟨⟨f.to_continuous_map, this⟩, by {ext, refl}⟩,
end
/-- Continuous functions vanishing at infinity taking values in a complete space form a
complete space. -/
instance [complete_space β] : complete_space C₀(α, β) :=
(complete_space_iff_is_complete_range isometry_to_bcf.uniform_inducing).mpr
closed_range_to_bcf.is_complete
end metric
section norm
/-! ### Normed space
The norm structure on `C₀(α, β)` is the one induced by the inclusion `to_bcf : C₀(α, β) → (α →ᵇ b)`,
viewed as an additive monoid homomorphism. Then `C₀(α, β)` is naturally a normed space over a normed
field `𝕜` whenever `β` is as well.
-/
section normed_space
variables [normed_add_comm_group β] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β]
noncomputable instance : normed_add_comm_group C₀(α, β) :=
normed_add_comm_group.induced C₀(α, β) (α →ᵇ β) (⟨to_bcf, rfl, λ x y, rfl⟩ : C₀(α, β) →+ (α →ᵇ β))
(to_bcf_injective α β)
@[simp]
lemma norm_to_bcf_eq_norm {f : C₀(α, β)} : ‖f.to_bcf‖ = ‖f‖ := rfl
instance : normed_space 𝕜 C₀(α, β) :=
{ norm_smul_le := λ k f, norm_smul_le k f.to_bcf }
end normed_space
section normed_ring
variables [non_unital_normed_ring β]
noncomputable instance : non_unital_normed_ring C₀(α, β) :=
{ norm_mul := λ f g, norm_mul_le f.to_bcf g.to_bcf,
..zero_at_infty_continuous_map.non_unital_ring,
..zero_at_infty_continuous_map.normed_add_comm_group }
end normed_ring
end norm
section star
/-! ### Star structure
It is possible to equip `C₀(α, β)` with a pointwise `star` operation whenever there is a continuous
`star : β → β` for which `star (0 : β) = 0`. We don't have quite this weak a typeclass, but
`star_add_monoid` is close enough.
The `star_add_monoid` and `normed_star_group` classes on `C₀(α, β)` are inherited from their
counterparts on `α →ᵇ β`. Ultimately, when `β` is a C⋆-ring, then so is `C₀(α, β)`.
-/
variables [topological_space β] [add_monoid β] [star_add_monoid β] [has_continuous_star β]
instance : has_star C₀(α, β) :=
{ star := λ f,
{ to_fun := λ x, star (f x),
continuous_to_fun := (map_continuous f).star,
zero_at_infty' := by simpa only [star_zero]
using (continuous_star.tendsto (0 : β)).comp (zero_at_infty f) } }
@[simp]
lemma coe_star (f : C₀(α, β)) : ⇑(star f) = star f := rfl
lemma star_apply (f : C₀(α, β)) (x : α) :
(star f) x = star (f x) := rfl
instance [has_continuous_add β] : star_add_monoid C₀(α, β) :=
{ star_involutive := λ f, ext $ λ x, star_star (f x),
star_add := λ f g, ext $ λ x, star_add (f x) (g x) }
end star
section normed_star
variables [normed_add_comm_group β] [star_add_monoid β] [normed_star_group β]
instance : normed_star_group C₀(α, β) :=
{ norm_star := λ f, (norm_star f.to_bcf : _) }
end normed_star
section star_module
variables {𝕜 : Type*} [has_zero 𝕜] [has_star 𝕜]
[add_monoid β] [star_add_monoid β] [topological_space β] [has_continuous_star β]
[smul_with_zero 𝕜 β] [has_continuous_const_smul 𝕜 β] [star_module 𝕜 β]
instance : star_module 𝕜 C₀(α, β) :=
{ star_smul := λ k f, ext $ λ x, star_smul k (f x) }
end star_module
section star_ring
variables [non_unital_semiring β] [star_ring β] [topological_space β] [has_continuous_star β]
[topological_semiring β]
instance : star_ring C₀(α, β) :=
{ star_mul := λ f g, ext $ λ x, star_mul (f x) (g x),
..zero_at_infty_continuous_map.star_add_monoid }
end star_ring
section cstar_ring
instance [non_unital_normed_ring β] [star_ring β] [cstar_ring β] : cstar_ring C₀(α, β) :=
{ norm_star_mul_self := λ f, @cstar_ring.norm_star_mul_self _ _ _ _ f.to_bcf }
end cstar_ring
/-! ### C₀ as a functor
For each `β` with sufficient structure, there is a contravariant functor `C₀(-, β)` from the
category of topological spaces with morphisms given by `cocompact_map`s.
-/
variables {δ : Type*} [topological_space β] [topological_space γ] [topological_space δ]
local notation α ` →co ` β := cocompact_map α β
section
variables [has_zero δ]
/-- Composition of a continuous function vanishing at infinity with a cocompact map yields another
continuous function vanishing at infinity. -/
def comp (f : C₀(γ, δ)) (g : β →co γ) : C₀(β, δ) :=
{ to_continuous_map := (f : C(γ, δ)).comp g,
zero_at_infty' := (zero_at_infty f).comp (cocompact_tendsto g) }
@[simp] lemma coe_comp_to_continuous_fun (f : C₀(γ, δ)) (g : β →co γ) :
((f.comp g).to_continuous_map : β → δ) = f ∘ g := rfl
@[simp] lemma comp_id (f : C₀(γ, δ)) : f.comp (cocompact_map.id γ) = f := ext (λ x, rfl)
@[simp] lemma comp_assoc (f : C₀(γ, δ)) (g : β →co γ) (h : α →co β) :
(f.comp g).comp h = f.comp (g.comp h) := rfl
@[simp] lemma zero_comp (g : β →co γ) : (0 : C₀(γ, δ)).comp g = 0 := rfl
end
/-- Composition as an additive monoid homomorphism. -/
def comp_add_monoid_hom [add_monoid δ] [has_continuous_add δ] (g : β →co γ) :
C₀(γ, δ) →+ C₀(β, δ) :=
{ to_fun := λ f, f.comp g,
map_zero' := zero_comp g,
map_add' := λ f₁ f₂, rfl }
/-- Composition as a semigroup homomorphism. -/
def comp_mul_hom [mul_zero_class δ] [has_continuous_mul δ]
(g : β →co γ) : C₀(γ, δ) →ₙ* C₀(β, δ) :=
{ to_fun := λ f, f.comp g,
map_mul' := λ f₁ f₂, rfl }
/-- Composition as a linear map. -/
def comp_linear_map [add_comm_monoid δ] [has_continuous_add δ] {R : Type*}
[semiring R] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) :
C₀(γ, δ) →ₗ[R] C₀(β, δ) :=
{ to_fun := λ f, f.comp g,
map_add' := λ f₁ f₂, rfl,
map_smul' := λ r f, rfl }
/-- Composition as a non-unital algebra homomorphism. -/
def comp_non_unital_alg_hom {R : Type*} [semiring R] [non_unital_non_assoc_semiring δ]
[topological_semiring δ] [module R δ] [has_continuous_const_smul R δ] (g : β →co γ) :
C₀(γ, δ) →ₙₐ[R] C₀(β, δ) :=
{ to_fun := λ f, f.comp g,
map_smul' := λ r f, rfl,
map_zero' := rfl,
map_add' := λ f₁ f₂, rfl,
map_mul' := λ f₁ f₂, rfl }
end zero_at_infty_continuous_map
|
01adb78f8867f746b3f6b220e5ebc55d7442eedf | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/run/assert_tac1.lean | 991d4499b5cc03cefc912a07222a535b0335f673 | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 610 | lean | open tactic
definition tst1 (a : nat) : a = a :=
by do
define `x (expr.const `nat []),
trace_state,
a ← get_local `a,
exact a,
x ← get_local `x,
mk_app `eq.refl [x] >>= exact
#print tst1
definition tst2 (a : nat) : a = a :=
by do
define `x (expr.const `nat []),
a ← get_local `a,
exact a,
trace "------------",
trace_state,
get_local `x >>= revert,
intro `y,
trace_state,
y ← get_local `y,
mk_app `eq.refl [y] >>= exact
#print tst2
definition tst3 (a : nat) : a = a :=
begin
define x : nat,
exact a,
revert x,
intro y,
apply eq.refl y
end
|
5ddd2c981b1ffec03dc38b78a629a9b5f431ca11 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/nat/choose/sum.lean | 2304080d66257c42004ac05dc83ae27463d174d0 | [
"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 | 6,993 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Patrick Stevens
-/
import data.nat.choose.basic
import tactic.linarith
import algebra.big_operators.ring
import algebra.big_operators.intervals
import algebra.big_operators.order
import algebra.big_operators.nat_antidiagonal
/-!
# Sums of binomial coefficients
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file includes variants of the binomial theorem and other results on sums of binomial
coefficients. Theorems whose proofs depend on such sums may also go in this file for import
reasons.
-/
open nat
open finset
open_locale big_operators
variables {R : Type*}
namespace commute
variables [semiring R] {x y : R} (h : commute x y) (n : ℕ)
include h
/-- A version of the **binomial theorem** for commuting elements in noncommutative semirings. -/
theorem add_pow :
(x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m :=
begin
let t : ℕ → ℕ → R := λ n m, x ^ m * (y ^ (n - m)) * (choose n m),
change (x + y) ^ n = ∑ m in range (n + 1), t n m,
have h_first : ∀ n, t n 0 = y ^ n :=
λ n, by { dsimp [t], rw [choose_zero_right, pow_zero, nat.cast_one, mul_one, one_mul] },
have h_last : ∀ n, t n n.succ = 0 :=
λ n, by { dsimp [t], rw [choose_succ_self, nat.cast_zero, mul_zero] },
have h_middle : ∀ (n i : ℕ), (i ∈ range n.succ) →
((t n.succ) ∘ nat.succ) i = x * (t n i) + y * (t n i.succ) :=
begin
intros n i h_mem,
have h_le : i ≤ n := nat.le_of_lt_succ (mem_range.mp h_mem),
dsimp [t],
rw [choose_succ_succ, nat.cast_add, mul_add],
congr' 1,
{ rw [pow_succ x, succ_sub_succ, mul_assoc, mul_assoc, mul_assoc] },
{ rw [← mul_assoc y, ← mul_assoc y, (h.symm.pow_right i.succ).eq],
by_cases h_eq : i = n,
{ rw [h_eq, choose_succ_self, nat.cast_zero, mul_zero, mul_zero] },
{ rw [succ_sub (lt_of_le_of_ne h_le h_eq)],
rw [pow_succ y, mul_assoc, mul_assoc, mul_assoc, mul_assoc] } }
end,
induction n with n ih,
{ rw [pow_zero, sum_range_succ, range_zero, sum_empty, zero_add],
dsimp [t], rw [pow_zero, pow_zero, choose_self, nat.cast_one, mul_one, mul_one] },
{ rw [sum_range_succ', h_first],
rw [sum_congr rfl (h_middle n), sum_add_distrib, add_assoc],
rw [pow_succ (x + y), ih, add_mul, mul_sum, mul_sum],
congr' 1,
rw [sum_range_succ', sum_range_succ, h_first, h_last,
mul_zero, add_zero, pow_succ] }
end
/-- A version of `commute.add_pow` that avoids ℕ-subtraction by summing over the antidiagonal and
also with the binomial coefficient applied via scalar action of ℕ. -/
lemma add_pow' :
(x + y) ^ n = ∑ m in nat.antidiagonal n, choose n m.fst • (x ^ m.fst * y ^ m.snd) :=
by simp_rw [finset.nat.sum_antidiagonal_eq_sum_range_succ (λ m p, choose n m • (x^m * y^p)),
_root_.nsmul_eq_mul, cast_comm, h.add_pow]
end commute
/-- The **binomial theorem** -/
theorem add_pow [comm_semiring R] (x y : R) (n : ℕ) :
(x + y) ^ n = ∑ m in range (n + 1), x ^ m * y ^ (n - m) * choose n m :=
(commute.all x y).add_pow n
namespace nat
/-- The sum of entries in a row of Pascal's triangle -/
theorem sum_range_choose (n : ℕ) :
∑ m in range (n + 1), choose n m = 2 ^ n :=
by simpa using (add_pow 1 1 n).symm
lemma sum_range_choose_halfway (m : nat) :
∑ i in range (m + 1), choose (2 * m + 1) i = 4 ^ m :=
have ∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) =
∑ i in range (m + 1), choose (2 * m + 1) i,
from sum_congr rfl $ λ i hi, choose_symm $ by linarith [mem_range.1 hi],
mul_right_injective₀ two_ne_zero $
calc 2 * (∑ i in range (m + 1), choose (2 * m + 1) i) =
(∑ i in range (m + 1), choose (2 * m + 1) i) +
∑ i in range (m + 1), choose (2 * m + 1) (2 * m + 1 - i) :
by rw [two_mul, this]
... = (∑ i in range (m + 1), choose (2 * m + 1) i) +
∑ i in Ico (m + 1) (2 * m + 2), choose (2 * m + 1) i : begin
rw [range_eq_Ico, sum_Ico_reflect],
{ congr,
have A : m + 1 ≤ 2 * m + 1, by linarith,
rw [add_comm, add_tsub_assoc_of_le A, ← add_comm],
congr,
rw tsub_eq_iff_eq_add_of_le A,
ring, },
{ linarith }
end
... = ∑ i in range (2 * m + 2), choose (2 * m + 1) i : sum_range_add_sum_Ico _ (by linarith)
... = 2^(2 * m + 1) : sum_range_choose (2 * m + 1)
... = 2 * 4^m : by { rw [pow_succ, pow_mul], refl }
lemma choose_middle_le_pow (n : ℕ) : choose (2 * n + 1) n ≤ 4 ^ n :=
begin
have t : choose (2 * n + 1) n ≤ ∑ i in range (n + 1), choose (2 * n + 1) i :=
single_le_sum (λ x _, by linarith) (self_mem_range_succ n),
simpa [sum_range_choose_halfway n] using t
end
lemma four_pow_le_two_mul_add_one_mul_central_binom (n : ℕ) :
4 ^ n ≤ (2 * n + 1) * choose (2 * n) n :=
calc 4 ^ n = (1 + 1) ^ (2 * n) : by norm_num [pow_mul]
... = ∑ m in range (2 * n + 1), choose (2 * n) m : by simp [add_pow]
... ≤ ∑ m in range (2 * n + 1), choose (2 * n) (2 * n / 2) :
sum_le_sum (λ i hi, choose_le_middle i (2 * n))
... = (2 * n + 1) * choose (2 * n) n : by simp
end nat
theorem int.alternating_sum_range_choose {n : ℕ} :
∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = if n = 0 then 1 else 0 :=
begin
cases n, { simp },
have h := add_pow (-1 : ℤ) 1 n.succ,
simp only [one_pow, mul_one, add_left_neg] at h,
rw [← h, zero_pow (nat.succ_pos n), if_neg (nat.succ_ne_zero n)],
end
theorem int.alternating_sum_range_choose_of_ne {n : ℕ} (h0 : n ≠ 0) :
∑ m in range (n + 1), ((-1) ^ m * ↑(choose n m) : ℤ) = 0 :=
by rw [int.alternating_sum_range_choose, if_neg h0]
namespace finset
theorem sum_powerset_apply_card {α β : Type*} [add_comm_monoid α] (f : ℕ → α) {x : finset β} :
∑ m in x.powerset, f m.card = ∑ m in range (x.card + 1), (x.card.choose m) • f m :=
begin
transitivity ∑ m in range (x.card + 1), ∑ j in x.powerset.filter (λ z, z.card = m), f j.card,
{ refine (sum_fiberwise_of_maps_to _ _).symm,
intros y hy,
rw [mem_range, nat.lt_succ_iff],
rw mem_powerset at hy,
exact card_le_of_subset hy },
{ refine sum_congr rfl (λ y hy, _),
rw [← card_powerset_len, ← sum_const],
refine sum_congr powerset_len_eq_filter.symm (λ z hz, _),
rw (mem_powerset_len.1 hz).2 }
end
theorem sum_powerset_neg_one_pow_card {α : Type*} [decidable_eq α] {x : finset α} :
∑ m in x.powerset, (-1 : ℤ) ^ m.card = if x = ∅ then 1 else 0 :=
begin
rw sum_powerset_apply_card,
simp only [nsmul_eq_mul', ← card_eq_zero, int.alternating_sum_range_choose]
end
theorem sum_powerset_neg_one_pow_card_of_nonempty {α : Type*} {x : finset α}
(h0 : x.nonempty) :
∑ m in x.powerset, (-1 : ℤ) ^ m.card = 0 :=
begin
classical,
rw [sum_powerset_neg_one_pow_card, if_neg],
rw [← ne.def, ← nonempty_iff_ne_empty],
apply h0,
end
end finset
|
e206f60070508055234fd6691683650ba26c6171 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/standard/data/nat/sub.lean | c77e9b524a4ca5caa381393c0d64be1462f9c855 | [
"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 | 17,840 | lean | ----------------------------------------------------------------------------------------------------
--- Copyright (c) 2014 Floris van Doorn. All rights reserved.
--- Released under Apache 2.0 license as described in the file LICENSE.
--- Author: Floris van Doorn
----------------------------------------------------------------------------------------------------
import data.nat.order
using nat eq_proofs tactic
using helper_tactics
namespace nat
-- data.nat.basic2
-- ===============
--
-- More basic operations on the natural numbers.
-- subtraction
-- -----------
definition sub (n m : ℕ) : nat := nat_rec n (fun m x, pred x) m
infixl `-` : 65 := sub
theorem sub_zero_right (n : ℕ) : n - 0 = n
theorem sub_succ_right (n m : ℕ) : n - succ m = pred (n - m)
opaque_hint (hiding sub)
theorem sub_zero_left (n : ℕ) : 0 - n = 0 :=
induction_on n (sub_zero_right 0)
(take k : nat,
assume IH : 0 - k = 0,
calc
0 - succ k = pred (0 - k) : sub_succ_right 0 k
... = pred 0 : {IH}
... = 0 : pred_zero)
--(
--theorem sub_succ_left (n m : ℕ) : pred (succ n - m) = n - m
-- :=
-- induction_on m
-- (calc
-- pred (succ n - 0) = pred (succ n) : {sub_zero_right (succ n)}
-- ... = n : pred_succ n
-- ... = n - 0 : symm (sub_zero_right n))
-- (take k : nat,
-- assume IH : pred (succ n - k) = n - k,
-- _)
--)
--succ_sub_succ
theorem sub_succ_succ (n m : ℕ) : succ n - succ m = n - m :=
induction_on m
(calc
succ n - 1 = pred (succ n - 0) : sub_succ_right (succ n) 0
... = pred (succ n) : {sub_zero_right (succ n)}
... = n : pred_succ n
... = n - 0 : symm (sub_zero_right n))
(take k : nat,
assume IH : succ n - succ k = n - k,
calc
succ n - succ (succ k) = pred (succ n - succ k) : sub_succ_right (succ n) (succ k)
... = pred (n - k) : {IH}
... = n - succ k : symm (sub_succ_right n k))
theorem sub_self (n : ℕ) : n - n = 0 :=
induction_on n (sub_zero_right 0) (take k IH, trans (sub_succ_succ k k) IH)
-- TODO: add_sub_add_right
theorem sub_add_add_right (n k m : ℕ) : (n + k) - (m + k) = n - m :=
induction_on k
(calc
(n + 0) - (m + 0) = n - (m + 0) : {add_zero_right _}
... = n - m : {add_zero_right _})
(take l : nat,
assume IH : (n + l) - (m + l) = n - m,
calc
(n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {add_succ_right _ _}
... = succ (n + l) - succ (m + l) : {add_succ_right _ _}
... = (n + l) - (m + l) : sub_succ_succ _ _
... = n - m : IH)
theorem sub_add_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m :=
add_comm m k ▸ add_comm n k ▸ sub_add_add_right n k m
-- TODO: add_sub_inv
theorem sub_add_left (n m : ℕ) : n + m - m = n :=
induction_on m
((add_zero_right n)⁻¹ ▸ sub_zero_right n)
(take k : ℕ,
assume IH : n + k - k = n,
calc
n + succ k - succ k = succ (n + k) - succ k : {add_succ_right n k}
... = n + k - k : sub_succ_succ _ _
... = n : IH)
-- TODO: add_sub_inv'
theorem sub_add_left2 (n m : ℕ) : n + m - n = m :=
add_comm m n ▸ sub_add_left m n
theorem sub_sub (n m k : ℕ) : n - m - k = n - (m + k) :=
induction_on k
(calc
n - m - 0 = n - m : sub_zero_right _
... = n - (m + 0) : {symm (add_zero_right m)})
(take l : nat,
assume IH : n - m - l = n - (m + l),
calc
n - m - succ l = pred (n - m - l) : sub_succ_right (n - m) l
... = pred (n - (m + l)) : {IH}
... = n - succ (m + l) : symm (sub_succ_right n (m + l))
... = n - (m + succ l) : {symm (add_succ_right m l)})
theorem succ_sub_sub (n m k : ℕ) : succ n - m - succ k = n - m - k :=
calc
succ n - m - succ k = succ n - (m + succ k) : sub_sub _ _ _
... = succ n - succ (m + k) : {add_succ_right m k}
... = n - (m + k) : sub_succ_succ _ _
... = n - m - k : symm (sub_sub n m k)
theorem sub_add_right_eq_zero (n m : ℕ) : n - (n + m) = 0 :=
calc
n - (n + m) = n - n - m : symm (sub_sub n n m)
... = 0 - m : {sub_self n}
... = 0 : sub_zero_left m
theorem sub_comm (m n k : ℕ) : m - n - k = m - k - n :=
calc
m - n - k = m - (n + k) : sub_sub m n k
... = m - (k + n) : {add_comm n k}
... = m - k - n : symm (sub_sub m k n)
theorem sub_one (n : ℕ) : n - 1 = pred n :=
calc
n - 1 = pred (n - 0) : sub_succ_right n 0
... = pred n : {sub_zero_right n}
theorem succ_sub_one (n : ℕ) : succ n - 1 = n :=
trans (sub_succ_succ n 0) (sub_zero_right n)
-- add_rewrite sub_add_left
-- ### interaction with multiplication
theorem mul_pred_left (n m : ℕ) : pred n * m = n * m - m :=
induction_on n
(calc
pred 0 * m = 0 * m : {pred_zero}
... = 0 : mul_zero_left _
... = 0 - m : symm (sub_zero_left m)
... = 0 * m - m : {symm (mul_zero_left m)})
(take k : nat,
assume IH : pred k * m = k * m - m,
calc
pred (succ k) * m = k * m : {pred_succ k}
... = k * m + m - m : symm (sub_add_left _ _)
... = succ k * m - m : {symm (mul_succ_left k m)})
theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n :=
calc n * pred m = pred m * n : mul_comm _ _
... = m * n - n : mul_pred_left m n
... = n * m - n : {mul_comm m n}
theorem mul_sub_distr_right (n m k : ℕ) : (n - m) * k = n * k - m * k :=
induction_on m
(calc
(n - 0) * k = n * k : {sub_zero_right n}
... = n * k - 0 : symm (sub_zero_right _)
... = n * k - 0 * k : {symm (mul_zero_left _)})
(take l : nat,
assume IH : (n - l) * k = n * k - l * k,
calc
(n - succ l) * k = pred (n - l) * k : {sub_succ_right n l}
... = (n - l) * k - k : mul_pred_left _ _
... = n * k - l * k - k : {IH}
... = n * k - (l * k + k) : sub_sub _ _ _
... = n * k - (succ l * k) : {symm (mul_succ_left l k)})
theorem mul_sub_distr_left (n m k : ℕ) : n * (m - k) = n * m - n * k :=
calc
n * (m - k) = (m - k) * n : mul_comm _ _
... = m * n - k * n : mul_sub_distr_right _ _ _
... = n * m - k * n : {mul_comm _ _}
... = n * m - n * k : {mul_comm _ _}
-- ### interaction with inequalities
theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n) :=
sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
succ k - 0 = succ k : sub_zero_right (succ k)
... = succ (k - 0) : {symm (sub_zero_right k)})
(take k,
assume H : succ k ≤ 0,
absurd_elim _ H (not_succ_zero_le k))
(take k l,
assume IH : k ≤ l → succ l - k = succ (l - k),
take H : succ k ≤ succ l,
calc
succ (succ l) - succ k = succ l - k : sub_succ_succ (succ l) k
... = succ (l - k) : IH (succ_le_cancel H)
... = succ (succ l - succ k) : {symm (sub_succ_succ l k)})
theorem le_imp_sub_eq_zero {n m : ℕ} (H : n ≤ m) : n - m = 0 :=
obtain (k : ℕ) (Hk : n + k = m), from le_elim H, Hk ▸ sub_add_right_eq_zero n k
theorem add_sub_le {n m : ℕ} : n ≤ m → n + (m - n) = m :=
sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
0 + (k - 0) = k - 0 : add_zero_left (k - 0)
... = k : sub_zero_right k)
(take k, assume H : succ k ≤ 0, absurd_elim _ H (not_succ_zero_le k))
(take k l,
assume IH : k ≤ l → k + (l - k) = l,
take H : succ k ≤ succ l,
calc
succ k + (succ l - succ k) = succ k + (l - k) : {sub_succ_succ l k}
... = succ (k + (l - k)) : add_succ_left k (l - k)
... = succ l : {IH (succ_le_cancel H)})
theorem add_sub_ge_left {n m : ℕ} : n ≥ m → n - m + m = n :=
add_comm m (n - m) ▸ add_sub_le
theorem add_sub_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n :=
calc
n + (m - n) = n + 0 : {le_imp_sub_eq_zero H}
... = n : add_zero_right n
theorem add_sub_le_left {n m : ℕ} : n ≤ m → n - m + m = m :=
add_comm m (n - m) ▸ add_sub_ge
theorem le_add_sub_left (n m : ℕ) : n ≤ n + (m - n) :=
or_elim (le_total n m)
(assume H : n ≤ m, (add_sub_le H)⁻¹ ▸ H)
(assume H : m ≤ n, (add_sub_ge H)⁻¹ ▸ le_refl n)
theorem le_add_sub_right (n m : ℕ) : m ≤ n + (m - n) :=
or_elim (le_total n m)
(assume H : n ≤ m, subst (symm (add_sub_le H)) (le_refl m))
(assume H : m ≤ n, subst (symm (add_sub_ge H)) H)
theorem sub_split {P : ℕ → Prop} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : ∀k, m + k = n -> P k)
: P (n - m) :=
or_elim (le_total n m)
(assume H3 : n ≤ m, subst (symm (le_imp_sub_eq_zero H3)) (H1 H3))
(assume H3 : m ≤ n, H2 (n - m) (add_sub_le H3))
theorem sub_le_self (n m : ℕ) : n - m ≤ n :=
sub_split
(assume H : n ≤ m, zero_le n)
(take k : ℕ, assume H : m + k = n, le_intro (subst (add_comm m k) H))
theorem le_elim_sub (n m : ℕ) (H : n ≤ m) : ∃k, m - k = n :=
obtain (k : ℕ) (Hk : n + k = m), from le_elim H,
exists_intro k
(calc
m - k = n + k - k : {symm Hk}
... = n : sub_add_left n k)
theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) :=
have l1 : k ≤ m → n + m - k = n + (m - k), from
sub_induction k m
(take m : ℕ,
assume H : 0 ≤ m,
calc
n + m - 0 = n + m : sub_zero_right (n + m)
... = n + (m - 0) : {symm (sub_zero_right m)})
(take k : ℕ, assume H : succ k ≤ 0, absurd_elim _ H (not_succ_zero_le k))
(take k m,
assume IH : k ≤ m → n + m - k = n + (m - k),
take H : succ k ≤ succ m,
calc
n + succ m - succ k = succ (n + m) - succ k : {add_succ_right n m}
... = n + m - k : sub_succ_succ (n + m) k
... = n + (m - k) : IH (succ_le_cancel H)
... = n + (succ m - succ k) : {symm (sub_succ_succ m k)}),
l1 H
theorem sub_eq_zero_imp_le {n m : ℕ} : n - m = 0 → n ≤ m :=
sub_split
(assume H1 : n ≤ m, assume H2 : 0 = 0, H1)
(take k : ℕ,
assume H1 : m + k = n,
assume H2 : k = 0,
have H3 : n = m, from subst (add_zero_right m) (subst H2 (symm H1)),
subst H3 (le_refl n))
theorem sub_sub_split {P : ℕ → ℕ → Prop} {n m : ℕ} (H1 : ∀k, n = m + k -> P k 0)
(H2 : ∀k, m = n + k → P 0 k) : P (n - m) (m - n) :=
or_elim (le_total n m)
(assume H3 : n ≤ m,
le_imp_sub_eq_zero H3⁻¹ ▸ (H2 (m - n) (add_sub_le H3⁻¹)))
(assume H3 : m ≤ n,
le_imp_sub_eq_zero H3⁻¹ ▸ (H1 (n - m) (add_sub_le H3⁻¹)))
theorem sub_intro {n m k : ℕ} (H : n + m = k) : k - n = m :=
have H2 : k - n + n = m + n, from
calc
k - n + n = k : add_sub_ge_left (le_intro H)
... = n + m : symm H
... = m + n : add_comm n m,
add_cancel_right H2
theorem sub_lt {x y : ℕ} (xpos : x > 0) (ypos : y > 0) : x - y < x :=
obtain (x' : ℕ) (xeq : x = succ x'), from pos_imp_eq_succ xpos,
obtain (y' : ℕ) (yeq : y = succ y'), from pos_imp_eq_succ ypos,
have xsuby_eq : x - y = x' - y', from
calc
x - y = succ x' - y : {xeq}
... = succ x' - succ y' : {yeq}
... = x' - y' : sub_succ_succ _ _,
have H1 : x' - y' ≤ x', from sub_le_self _ _,
have H2 : x' < succ x', from self_lt_succ _,
show x - y < x, from xeq⁻¹ ▸ xsuby_eq⁻¹ ▸ le_lt_trans H1 H2
theorem sub_le_right {n m : ℕ} (H : n ≤ m) (k : nat) : n - k ≤ m - k :=
obtain (l : ℕ) (Hl : n + l = m), from le_elim H,
or_elim (le_total n k)
(assume H2 : n ≤ k, (le_imp_sub_eq_zero H2)⁻¹ ▸ zero_le (m - k))
(assume H2 : k ≤ n,
have H3 : n - k + l = m - k, from
calc
n - k + l = l + (n - k) : by simp
... = l + n - k : symm (add_sub_assoc H2 l)
... = n + l - k : {add_comm l n}
... = m - k : {Hl},
le_intro H3)
theorem sub_le_left {n m : ℕ} (H : n ≤ m) (k : nat) : k - m ≤ k - n :=
obtain (l : ℕ) (Hl : n + l = m), from le_elim H,
sub_split
(assume H2 : k ≤ m, zero_le (k - n))
(take m' : ℕ,
assume Hm : m + m' = k,
have H3 : n ≤ k, from le_trans H (le_intro Hm),
have H4 : m' + l + n = k - n + n, from
calc
m' + l + n = n + l + m' : by simp
... = m + m' : {Hl}
... = k : Hm
... = k - n + n : symm (add_sub_ge_left H3),
le_intro (add_cancel_right H4))
-- theorem sub_lt_cancel_right {n m k : ℕ) (H : n - k < m - k) : n < m
-- :=
-- _
-- theorem sub_lt_cancel_left {n m k : ℕ) (H : n - m < n - k) : k < m
-- :=
-- _
theorem sub_triangle_inequality (n m k : ℕ) : n - k ≤ (n - m) + (m - k) :=
sub_split
(assume H : n ≤ m, (add_zero_left (m - k))⁻¹ ▸ sub_le_right H k)
(take mn : ℕ,
assume Hmn : m + mn = n,
sub_split
(assume H : m ≤ k,
have H2 : n - k ≤ n - m, from sub_le_left H n,
have H3 : n - k ≤ mn, from sub_intro Hmn ▸ H2,
show n - k ≤ mn + 0, from (add_zero_right mn)⁻¹ ▸ H3)
(take km : ℕ,
assume Hkm : k + km = m,
have H : k + (mn + km) = n, from
calc
k + (mn + km) = k + km + mn : by simp
... = m + mn : {Hkm}
... = n : Hmn,
have H2 : n - k = mn + km, from sub_intro H,
H2 ▸ (le_refl (n - k))))
-- add_rewrite sub_self mul_sub_distr_left mul_sub_distr_right
-- Max, min, iteration, and absolute difference
-- --------------------------------------------
definition max (n m : ℕ) : ℕ := n + (m - n)
definition min (n m : ℕ) : ℕ := m - (m - n)
theorem max_le {n m : ℕ} (H : n ≤ m) : n + (m - n) = m := add_sub_le H
theorem max_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := add_sub_ge H
theorem left_le_max (n m : ℕ) : n ≤ n + (m - n) := le_add_sub_left n m
theorem right_le_max (n m : ℕ) : m ≤ max n m := le_add_sub_right n m
-- ### absolute difference
-- This section is still incomplete
definition dist (n m : ℕ) := (n - m) + (m - n)
theorem dist_comm (n m : ℕ) : dist n m = dist m n :=
add_comm (n - m) (m - n)
theorem dist_self (n : ℕ) : dist n n = 0 :=
calc
(n - n) + (n - n) = 0 + 0 : by simp
... = 0 : by simp
theorem dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m :=
have H2 : n - m = 0, from add_eq_zero_left H,
have H3 : n ≤ m, from sub_eq_zero_imp_le H2,
have H4 : m - n = 0, from add_eq_zero_right H,
have H5 : m ≤ n, from sub_eq_zero_imp_le H4,
le_antisym H3 H5
theorem dist_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n :=
calc
dist n m = 0 + (m - n) : {le_imp_sub_eq_zero H}
... = m - n : add_zero_left (m - n)
theorem dist_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m :=
dist_comm m n ▸ dist_le H
theorem dist_zero_right (n : ℕ) : dist n 0 = n :=
trans (dist_ge (zero_le n)) (sub_zero_right n)
theorem dist_zero_left (n : ℕ) : dist 0 n = n :=
trans (dist_le (zero_le n)) (sub_zero_right n)
theorem dist_intro {n m k : ℕ} (H : n + m = k) : dist k n = m :=
calc
dist k n = k - n : dist_ge (le_intro H)
... = m : sub_intro H
theorem dist_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m :=
calc
dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : refl _
... = (n - m) + ((m + k) - (n + k)) : {sub_add_add_right _ _ _}
... = (n - m) + (m - n) : {sub_add_add_right _ _ _}
theorem dist_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m :=
add_comm m k ▸ add_comm n k ▸ dist_add_right n k m
-- add_rewrite dist_self dist_add_right dist_add_left dist_zero_left dist_zero_right
theorem dist_ge_add_right {n m : ℕ} (H : n ≥ m) : dist n m + m = n :=
calc
dist n m + m = n - m + m : {dist_ge H}
... = n : add_sub_ge_left H
theorem dist_eq_intro {n m k l : ℕ} (H : n + m = k + l) : dist n k = dist l m :=
calc
dist n k = dist (n + m) (k + m) : symm (dist_add_right n m k)
... = dist (k + l) (k + m) : {H}
... = dist l m : dist_add_left k l m
theorem dist_sub_move_add {n m : ℕ} (H : n ≥ m) (k : ℕ) : dist (n - m) k = dist n (k + m) :=
have H2 : n - m + (k + m) = k + n, from
calc
n - m + (k + m) = n - m + m + k : by simp
... = n + k : {add_sub_ge_left H}
... = k + n : by simp,
dist_eq_intro H2
theorem dist_sub_move_add' {k m : ℕ} (H : k ≥ m) (n : ℕ) : dist n (k - m) = dist (n + m) k :=
subst (subst (dist_sub_move_add H n) (dist_comm (k - m) n)) (dist_comm k (n + m))
--triangle inequality formulated with dist
theorem triangle_inequality (n m k : ℕ) : dist n k ≤ dist n m + dist m k :=
have H : (n - m) + (m - k) + ((k - m) + (m - n)) = (n - m) + (m - n) + ((m - k) + (k - m)),
by simp,
H ▸ add_le (sub_triangle_inequality n m k) (sub_triangle_inequality k m n)
theorem dist_add_le_add_dist (n m k l : ℕ) : dist (n + m) (k + l) ≤ dist n k + dist m l :=
have H : dist (n + m) (k + m) + dist (k + m) (k + l) = dist n k + dist m l, from
calc
_ = dist n k + dist (k + m) (k + l) : {dist_add_right n m k}
... = _ : {dist_add_left k m l},
H ▸ (triangle_inequality (n + m) (k + m) (k + l))
--interaction with multiplication
theorem dist_mul_left (k n m : ℕ) : dist (k * n) (k * m) = k * dist n m :=
have H : ∀n m, dist n m = n - m + (m - n), from take n m, refl _,
by simp
theorem dist_mul_right (n k m : ℕ) : dist (n * k) (m * k) = dist n m * k :=
have H : ∀n m, dist n m = n - m + (m - n), from take n m, refl _,
by simp
-- add_rewrite dist_mul_right dist_mul_left dist_comm
--needed to prove |a| * |b| = |a * b| in int
theorem dist_mul_dist (n m k l : ℕ) : dist n m * dist k l = dist (n * k + m * l) (n * l + m * k) :=
have aux : ∀k l, k ≥ l → dist n m * dist k l = dist (n * k + m * l) (n * l + m * k), from
take k l : ℕ,
assume H : k ≥ l,
have H2 : m * k ≥ m * l, from mul_le_left H m,
have H3 : n * l + m * k ≥ m * l, from le_trans H2 (le_add_left _ _),
calc
dist n m * dist k l = dist n m * (k - l) : {dist_ge H}
... = dist (n * (k - l)) (m * (k - l)) : symm (dist_mul_right n (k - l) m)
... = dist (n * k - n * l) (m * k - m * l) : by simp
... = dist (n * k) (m * k - m * l + n * l) : dist_sub_move_add (mul_le_left H n) _
... = dist (n * k) (n * l + (m * k - m * l)) : {add_comm _ _}
... = dist (n * k) (n * l + m * k - m * l) : {symm (add_sub_assoc H2 (n * l))}
... = dist (n * k + m * l) (n * l + m * k) : dist_sub_move_add' H3 _,
or_elim (le_total k l)
(assume H : k ≤ l, dist_comm l k ▸ dist_comm _ _ ▸ aux l k H)
(assume H : l ≤ k, aux k l H)
opaque_hint (hiding dist)
end -- namespace nat |
faa58ea0ab5c88470b6643928c02450c039e9f97 | 9631e35ca5dd719ccc7d3a57ec322fd93d6a0776 | /src/example_maze/definition.lean | db86d2c4ba6c60136a59caa852b2880dc5cc4441 | [] | no_license | kbuzzard/maze-game | 123fa47e0262edb6d147178d239a345d847ff147 | 362ab394ae5218c43b24232aaeef08efc0067eab | refs/heads/master | 1,670,131,466,823 | 1,598,546,702,000 | 1,598,546,702,000 | 290,744,081 | 5 | 1 | null | 1,598,546,703,000 | 1,598,523,538,000 | Lean | UTF-8 | Lean | false | false | 2,337 | lean | /-
Ideas about a maze game, from the Xena Discord.
-/
import tactic -- I don't even know if I need this
/-
This is an example level of a puzzle game.
AB
CD
E
01
23
4
Can people write computer programs in Lean which solve
levels like this?
Can people write computer programs in Python which design
levels like this?
The below is Lean 3 code.
Can stuff like this be made to work in Lean 4? I have
Lean 4 working on my laptop, it's usable, but you have
to learn the emacs interface. Is there any way to make
this easier for people wanting to transition from VS Code?
-/
/-- Solver docs : Terms of type `maze` are rooms in the game. -/
def maze := ℕ
-- Lean remarks:
-- this definition is an implementation detail.
-- This type will be made irreducible at the end.
-- Let's now make the interface for `maze`.
namespace maze
def mk (n : ℕ) : maze := n
/-- The map. Interface will be unknown to player -/
inductive can_escape : maze → Prop
| have_escaped : can_escape $ mk 4
| N1 : can_escape (mk 0) → can_escape (mk 2)
| N2 : can_escape (mk 1) → can_escape (mk 3)
| N3 : can_escape (mk 3) → can_escape (mk 4)
| S1 : can_escape (mk 2) → can_escape (mk 0)
| S2 : can_escape (mk 3) → can_escape (mk 1)
| S3 : can_escape (mk 4) → can_escape (mk 3)
| E1 : can_escape (mk 1) → can_escape (mk 0)
| E2 : can_escape (mk 3) → can_escape (mk 2)
| W1 : can_escape (mk 0) → can_escape (mk 1)
| W2 : can_escape (mk 2) → can_escape (mk 3)
@[reducible] def goal : Prop := can_escape (mk 0)
def hint : can_escape (mk 4) := can_escape.have_escaped
end maze
namespace tactic.interactive
--open maze.can_escape
open tactic
meta def n :=
`[apply maze.can_escape.N1 <|> apply maze.can_escape.N2 <|> apply maze.can_escape.N3 <|> fail "you cannot go north"]
meta def s :=
`[apply maze.can_escape.S1 <|> apply maze.can_escape.S2 <|> apply maze.can_escape.S3 <|> fail "you cannot go south"]
meta def e :=
`[apply maze.can_escape.E1 <|> apply maze.can_escape.E2 <|> fail "you cannot go east"]
meta def w :=
`[apply maze.can_escape.W1 <|> apply maze.can_escape.W2 <|> fail "you cannot go west"]
meta def out := `[apply maze.can_escape.have_escaped <|> fail "you are not at the exit"]
-- hand-generated solver
meta def xyzzy :=
`[ {s,e,s, out} <|> {s,s,out} <|> {e,s,out} <|> {s,out} <|> {out} ]
end tactic.interactive
|
91231d89584b1e6bcc6baae842046eea1a01dd24 | 5e3548e65f2c037cb94cd5524c90c623fbd6d46a | /src_icannos_totilas/aops/2011-IMO-Problem_3.lean | 2d8ce28806754cde3eba65d726eb327e21439fcb | [] | 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 | 143 | lean |
import data.real.basic
theorem exo (f: real -> real) :
(forall x y, f(x + y) <= y* f(x) + f(f x))
-> (forall x > 0, f(x) = 0)
:= sorry
|
710aa5373aebaa2cbde369b76f85d2ceb31b349e | e151e9053bfd6d71740066474fc500a087837323 | /src/hott/types/sigma.lean | 83d00aecfeb420504844835dd51373efdde23d96 | [
"Apache-2.0"
] | permissive | daniel-carranza/hott3 | 15bac2d90589dbb952ef15e74b2837722491963d | 913811e8a1371d3a5751d7d32ff9dec8aa6815d9 | refs/heads/master | 1,610,091,349,670 | 1,596,222,336,000 | 1,596,222,336,000 | 241,957,822 | 0 | 0 | Apache-2.0 | 1,582,222,839,000 | 1,582,222,838,000 | null | UTF-8 | Lean | false | false | 24,152 | lean | /-
Copyright (c) 2014-15 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about sigma-types (dependent sums)
-/
import .prod
universes u v w
hott_theory
namespace hott
open hott.eq sigma hott.equiv hott.is_equiv function hott.is_trunc sum unit
@[reducible, hott]
def dpair {α β} := @sigma.mk α β
namespace sigma
variables {A : Type _} {A' : Type _} {B : A → Type _} {B' : A' → Type _} {C : Πa, B a → Type _}
{D : Πa b, C a b → Type _}
{a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {u v w : Σa, B a}
@[hott] def destruct := @sigma.cases_on
/- Paths in a sigma-type -/
@[hott] protected def eta : Π (u : Σa, B a), (⟨u.1 , u.2⟩: sigma _) = u
| ⟨u₁, u₂⟩ := idp
@[hott] def eta2 : Π (u : Σa b, C a b), (⟨u.1, u.2.1, u.2.2⟩: Σ _ _, _) = u
| ⟨u₁, u₂, u₃⟩ := idp
@[hott] def eta3 : Π (u : Σa b c, D a b c), (⟨u.1, u.2.1, u.2.2.1, u.2.2.2⟩: Σ _ _ _, _) = u
| ⟨u₁, u₂, u₃, u₄⟩ := idp
@[hott] def dpair_eq_dpair (p : a = a') (q : b =[p] b') : (⟨a, b⟩: Σ _, _) = ⟨a', b'⟩ :=
apd011 sigma.mk p q
@[hott] def sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2) : u = v :=
by induction u; induction v; exact (dpair_eq_dpair p q)
@[hott] def sigma_eq_right (q : b₁ = b₂) : (⟨a, b₁⟩: Σ _, _) = ⟨a, b₂⟩ :=
ap (dpair a) q
@[hott] def eq_fst (p : u = v) : u.1 = v.1 :=
ap fst p
postfix `..1`:(max+1) := eq_fst
@[hott] def eq_snd (p : u = v) : u.2 =[p..1] v.2 :=
by induction p; exact idpo
postfix `..2`:(max+1) := eq_snd
@[hott] def dpair_sigma_eq (p : u.1 = v.1) (q : u.2 =[p] v.2)
: (⟨(sigma_eq p q)..1, (sigma_eq p q)..2⟩: Σ p, u.2 =[p] v.2) = ⟨p, q⟩ :=
by induction u; induction v;dsimp at *;induction q;refl
@[hott] def sigma_eq_fst (p : u.1 = v.1) (q : u.2 =[p] v.2) : (sigma_eq p q)..1 = p :=
(dpair_sigma_eq p q)..1
@[hott] def sigma_eq_snd (p : u.1 = v.1) (q : u.2 =[p] v.2)
: (sigma_eq p q)..2 =[sigma_eq_fst p q; λ p, u.2 =[p] v.2] q :=
(dpair_sigma_eq p q)..2
@[hott] def sigma_eq_eta (p : u = v) : sigma_eq (p..1) (p..2) = p :=
by induction p; induction u; reflexivity
@[hott] def eq2_fst {p q : u = v} (r : p = q) : p..1 = q..1 :=
ap eq_fst r
@[hott] def eq2_snd {p q : u = v} (r : p = q) : p..2 =[eq2_fst r; λ x, u.2 =[x] v.2] q..2 :=
by apply pathover_ap; apply (apd eq_snd r)
@[hott] def tr_fst_sigma_eq {B' : A → Type _} (p : u.1 = v.1) (q : u.2 =[p] v.2)
: transport (λx : sigma _, B' x.1) (sigma_eq p q) = transport B' p :=
by induction u; induction v; dsimp at *;induction q; reflexivity
@[hott] protected def ap_fst (p : u = v) : ap (λx : sigma B, x.1) p = p..1 := idp
/- the uncurried version of sigma_eq. We will prove that this is an equivalence -/
@[hott] def sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2), u = v
| ⟨pq₁, pq₂⟩ := sigma_eq pq₁ pq₂
@[hott] def dpair_sigma_eq_unc : Π (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2),
(⟨(sigma_eq_unc pq)..1, (sigma_eq_unc pq)..2⟩: Σ p, u.2 =[p] v.2) = pq
| ⟨pq₁, pq₂⟩ := dpair_sigma_eq pq₁ pq₂
@[hott] def sigma_eq_fst_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2)
: (sigma_eq_unc pq)..1 = pq.1 :=
(dpair_sigma_eq_unc pq)..1
@[hott] def sigma_eq_snd_unc (pq : Σ(p : u.1 = v.1), u.2 =[p] v.2) :
(sigma_eq_unc pq)..2 =[sigma_eq_fst_unc pq; λ p, u.2 =[p] v.2] pq.2 :=
(dpair_sigma_eq_unc pq)..2
@[hott] def sigma_eq_eta_unc (p : u = v) : sigma_eq_unc ⟨p..1, p..2⟩ = p :=
sigma_eq_eta p
@[hott] def tr_sigma_eq_fst_unc {B' : A → Type _}
(pq : Σ(p : u.1 = v.1), u.2 =[p] v.2)
: transport (λx:sigma _, B' x.1) (@sigma_eq_unc A B u v pq) = transport B' pq.1 :=
by apply destruct pq; apply tr_fst_sigma_eq
@[hott, instance] def is_equiv_sigma_eq (u v : Σa, B a)
: is_equiv (@sigma_eq_unc A B u v) :=
adjointify sigma_eq_unc
(λp, ⟨p..1, p..2⟩)
sigma_eq_eta_unc
dpair_sigma_eq_unc
@[hott] def sigma_eq_equiv (u v : Σa, B a)
: (u = v) ≃ (Σ(p : u.1 = v.1), u.2 =[p] v.2) :=
(equiv.mk sigma_eq_unc (by apply_instance))⁻¹ᵉ
@[hott] def dpair_eq_dpair_con (p1 : a = a' ) (q1 : b =[p1] b' )
(p2 : a' = a'') (q2 : b' =[p2] b'') :
dpair_eq_dpair (p1 ⬝ p2) (q1 ⬝o q2) = dpair_eq_dpair p1 q1 ⬝ dpair_eq_dpair p2 q2 :=
by induction q1; induction q2; reflexivity
@[hott] def sigma_eq_con (p1 : u.1 = v.1) (q1 : u.2 =[p1] v.2)
(p2 : v.1 = w.1) (q2 : v.2 =[p2] w.2) :
sigma_eq (p1 ⬝ p2) (q1 ⬝o q2) = sigma_eq p1 q1 ⬝ sigma_eq p2 q2 :=
by induction u; induction v; induction w; apply dpair_eq_dpair_con
@[hott] def dpair_eq_dpair_con_idp (p : a = a') (q : b =[p] b') :
dpair_eq_dpair p q = dpair_eq_dpair p (pathover_tr _ _) ⬝
dpair_eq_dpair idp (pathover_idp_of_eq _ (tr_eq_of_pathover q)) :=
by induction q; reflexivity
/- eq_fst commutes with the groupoid structure. -/
@[hott] def eq_fst_idp (u : Σa, B a) : (idpath u) ..1 = refl (u.1) := idp
@[hott] def eq_fst_con (p : u = v) (q : v = w) : (p ⬝ q) ..1 = (p..1) ⬝ (q..1) := ap_con _ _ _
@[hott] def eq_fst_inv (p : u = v) : p⁻¹ ..1 = (p..1)⁻¹ := ap_inv _ _
/- Applying dpair to one argument is the same as dpair_eq_dpair with reflexivity in the first place. -/
@[hott] def ap_dpair (q : b₁ = b₂) :
ap (sigma.mk a) q = dpair_eq_dpair idp (pathover_idp_of_eq _ q) :=
by induction q; reflexivity
/- Dependent transport is the same as transport along a sigma_eq. -/
@[hott] def transportD_eq_transport (p : a = a') (c : C a b) :
p ▸D c = transport (λu : sigma _, C (u.1) (u.2)) (dpair_eq_dpair p (pathover_tr _ _)) c :=
by induction p; reflexivity
@[hott] def sigma_eq_eq_sigma_eq {p1 q1 : a = a'} {p2 : b =[p1] b'} {q2 : b =[q1] b'}
(r : p1 = q1) (s : p2 =[r; λ p, b =[p] b'] q2) : @sigma_eq _ _ ⟨a,b⟩ ⟨a',b'⟩ p1 p2 = sigma_eq q1 q2 :=
by induction s; reflexivity
/- A path between paths in a total space is commonly shown component wise. -/
@[hott] def sigma_eq2 {p q : u = v} (r : p..1 = q..1) (s : p..2 =[r; λ p, u.2 =[p] v.2] q..2)
: p = q :=
begin
induction p, induction u with u1 u2,
transitivity sigma_eq q..1 q..2,
apply sigma_eq_eq_sigma_eq r s,
apply sigma_eq_eta,
end
@[hott] def sigma_eq2_unc {p q : u = v} (rs : Σ(r : p..1 = q..1), p..2 =[r; λ p, u.2 =[p] v.2] q..2) : p = q :=
by apply destruct rs; apply sigma_eq2
@[hott] def ap_dpair_eq_dpair (f : Πa, B a → A') (p : a = a') (q : b =[p] b')
: @ap _ A' (@sigma.rec _ _ (λ _, A') f) _ _ (dpair_eq_dpair p q) = apd011 f p q :=
by induction q; reflexivity
/- Transport -/
/- The concrete description of transport in sigmas (and also pis) is rather trickier than in the other types. In particular, these cannot be described just in terms of transport in simpler types; they require also the dependent transport [transportD].
In particular, this indicates why `transport` alone cannot be fully defined by induction on the structure of types, although Id-elim/transportD can be (cf. Observational Type _ Theory). A more thorough set of lemmas, along the lines of the present ones but dealing with Id-elim rather than just transport, might be nice to have eventually? -/
@[hott] def sigma_transport (p : a = a') (bc : Σ(b : B a), C a b)
: p ▸ bc = ⟨p ▸ bc.1, p ▸D bc.2⟩ :=
by induction p; induction bc; reflexivity
/- The special case when the second variable doesn't depend on the first is simpler. -/
@[hott] def sigma_transport_nondep {B : Type _} {C : A → B → Type _} (p : a = a')
(bc : Σ(b : B), C a b) : p ▸ bc = ⟨bc.1, transport (λ a, C a bc.1) p bc.2⟩ :=
by induction p; induction bc; reflexivity
/- Or if the second variable contains a first component that doesn't depend on the first. -/
@[hott] def sigma_transport2_nondep {C : A → Type _} {D : Π a:A, B a → C a → Type _} (p : a = a')
(bcd : Σ(b : B a) (c : C a), D a b c) : p ▸ bcd = ⟨p ▸ bcd.1, p ▸ bcd.2.1, p ▸D2 bcd.2.2⟩ :=
begin
induction p, induction bcd with b cd, induction cd, reflexivity
end
/- Pathovers -/
@[hott] def etao (p : a = a') (bc : Σ(b : B a), C a b)
: bc =[p; λ a, Σ b, C a b] ⟨p ▸ bc.1, p ▸D bc.2⟩ :=
by induction p; induction bc; apply idpo
-- TODO: interchange sigma_pathover and sigma_pathover'
@[hott] def sigma_pathover (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b)
(r : u.1 =[p] v.1) (s : u.2 =[apd011 C p r; id] v.2) : u =[p; λ a, Σ b, C a b] v :=
begin
induction u, induction v, dsimp at *, induction r,
dsimp [apd011] at s, apply idp_rec_on s, apply idpo
end
@[hott] def sigma_pathover' (p : a = a') (u : Σ(b : B a), C a b) (v : Σ(b : B a'), C a' b)
(r : u.1 =[p] v.1) (s : @pathover (sigma _) ⟨a,u.1⟩ (λ x, C x.1 x.2) u.2 ⟨a',v.1⟩ (sigma_eq p r) v.2) :
u =[p; λ a, Σ b, C a b] v :=
begin
induction u, induction v, dsimp at *, induction r,
apply idp_rec_on s, apply idpo
end
@[hott] def sigma_pathover_nondep {B : Type _} {C : A → B → Type _} (p : a = a')
(u : Σ(b : B), C a b) (v : Σ(b : B), C a' b)
(r : u.1 = v.1) (s : @pathover (prod _ _) (a,u.1) (λx, C x.1 x.2) u.2 (a',v.1) (prod.prod_eq p r) v.2) :
u =[p; λ a, Σ b, C a b] v :=
begin
induction p, induction u, induction v, dsimp at *, induction r,
apply idp_rec_on s, apply idpo
end
@[hott] def pathover_fst {A : Type _} {B : A → Type _} {C : Πa, B a → Type _}
{a a' : A} {p : a = a'} {x : Σb, C a b} {x' : Σb', C a' b'}
(q : x =[p; λ a, Σb, C a b] x') : x.1 =[p] x'.1 :=
begin induction q, constructor end
@[hott] def sigma_pathover_equiv_of_is_prop {A : Type _} {B : A → Type _} (C : Πa, B a → Type _)
{a a' : A} (p : a = a') (x : Σb, C a b) (x' : Σb', C a' b')
[Πa b, is_prop (C a b)] : x =[p; λa, Σb, C a b] x' ≃ x.1 =[p] x'.1 :=
begin
fapply equiv.MK,
{ exact pathover_fst },
{ intro q, induction x with b c, induction x' with b' c', dsimp at q, induction q,
apply pathover_idp_of_eq, exact sigma_eq idp (is_prop.elimo _ _ _) },
{ intro q, induction x with b c, induction x' with b' c', dsimp at q, induction q,
have: c = c', by apply is_prop.elim, induction this,
dsimp, rwr is_prop_elimo_self, },
{ intro q, induction q, induction x with b c,
dsimp [pathover_fst], rwr is_prop_elimo_self }
end
/-
TODO:
* define the projections from the type u =[p] v
* show that the uncurried version of sigma_pathover is an equivalence
-/
/- Squares in a sigma type are characterized in cubical.squareover (to avoid circular imports) -/
/- Functorial action -/
variables (f : A → A') (g : Πa, B a → B' (f a))
@[hott] def sigma_functor (u : Σa, B a) : Σa', B' a' :=
⟨f u.1, g u.1 u.2⟩
@[hott] def total {B' : A → Type _} (g : Πa, B a → B' a) : (Σa, B a) → (Σa, B' a) :=
sigma_functor id g
/- Equivalences -/
@[hott] def is_equiv_sigma_functor [H1 : is_equiv f] [H2 : Π a, is_equiv (g a)]
: is_equiv (sigma_functor f g) :=
adjointify (sigma_functor f g)
(sigma_functor f⁻¹ᶠ (λ(a' : A') (b' : B' a'),
((g (f⁻¹ᶠ a'))⁻¹ᶠ (transport B' (right_inv f a')⁻¹ b'))))
begin abstract {
intro u', induction u' with a' b', fapply sigma_eq,
{apply right_inv f},
{dsimp [sigma_functor], rwr right_inv (g (f⁻¹ᶠ a')), apply tr_pathover}
} end
begin abstract {
intro u, induction u with a b, fapply sigma_eq,
{apply left_inv f},
{apply pathover_of_tr_eq, dsimp only [sigma_functor],
rwr [adj f, ← fn_tr_eq_tr_fn (left_inv f a) (λ a, (g a)⁻¹ᶠ),
tr_compose B', tr_inv_tr], dsimp, rwr left_inv }
} end
@[hott] def sigma_equiv_sigma_of_is_equiv
[H1 : is_equiv f] [H2 : Π a, is_equiv (g a)] : (Σa, B a) ≃ (Σa', B' a') :=
equiv.mk (sigma_functor f g) (is_equiv_sigma_functor _ _)
@[hott] def sigma_equiv_sigma (Hf : A ≃ A') (Hg : Π a, B a ≃ B' (Hf a)) :
(Σa, B a) ≃ (Σa', B' a') :=
sigma_equiv_sigma_of_is_equiv Hf (λ a, Hg a)
@[hott] def sigma_equiv_sigma_right {B' : A → Type _} (Hg : Π a, B a ≃ B' a)
: (Σa, B a) ≃ Σa, B' a :=
sigma_equiv_sigma equiv.rfl Hg
variable (B)
@[hott] def sigma_equiv_sigma_left (Hf : A ≃ A') :
(Σa, B a) ≃ (Σa', B (Hf⁻¹ᶠ a')) :=
sigma_equiv_sigma Hf (λ a, equiv_ap B (right_inv Hf⁻¹ᶠ a)⁻¹ᵖ)
@[hott] def sigma_equiv_sigma_left' (Hf : A' ≃ A) : (Σa, B (Hf a)) ≃ (Σa', B a') :=
sigma_equiv_sigma Hf (λa, erfl)
variable {B}
@[hott] def ap_sigma_functor_eq_dpair (p : a = a') (q : b =[p] b') :
ap (sigma_functor f g) (@sigma_eq _ _ ⟨a,b⟩ ⟨a',b'⟩ p q) =
sigma_eq (ap f p) (by exact pathover.rec_on q idpo) :=
by induction q; reflexivity
@[hott] def sigma_ua {A B : Type _} (C : A ≃ B → Type _) :
(Σ(p : A = B), C (equiv_of_eq p)) ≃ Σ(e : A ≃ B), C e :=
sigma_equiv_sigma_left' C (eq_equiv_equiv _ _)
-- @[hott] def ap_sigma_functor_eq (p : u.1 = v.1) (q : u.2 =[p] v.2)
-- : ap (sigma_functor f g) (sigma_eq p q) =
-- sigma_eq (ap f p)
-- ((tr_compose B' f p (g u.1 u.2))⁻¹ ⬝ (fn_tr_eq_tr_fn p g u.2)⁻¹ ⬝ ap (g v.1) q) :=
-- by induction u; induction v; apply ap_sigma_functor_eq_dpair
/- definition 3.11.9(i): Summing up a contractible family of types does nothing. -/
@[hott, instance] def is_equiv_fst (B : A → Type _) [H : Π a, is_contr (B a)]
: is_equiv (@fst A B) :=
adjointify fst
(λa, ⟨a, center _⟩)
(λa, idp)
(λu, sigma_eq idp (pathover_idp_of_eq _ (center_eq _)))
@[hott] def sigma_equiv_of_is_contr_right (B : A → Type _) [H : Π a, is_contr (B a)]
: (Σa, B a) ≃ A :=
equiv.mk fst (by apply_instance)
/- definition 3.11.9(ii): Dually, summing up over a contractible type does nothing. -/
@[hott] def sigma_equiv_of_is_contr_left (B : A → Type _) [H : is_contr A]
: (Σa, B a) ≃ B (center A) :=
equiv.MK
(λu, (center_eq u.1)⁻¹ ▸ u.2)
(λb, ⟨center _, b⟩)
begin abstract { intro b, change _ = idpath (center A) ▸ b,
apply ap (λx, x ▸ b), apply prop_eq_of_is_contr, } end
begin abstract { exact λu, sigma_eq (center_eq _) (tr_pathover _ _) } end
/- Associativity -/
--this proof is harder than in Coq because we don't have eta definitionally for sigma
@[hott] def sigma_assoc_equiv (C : (Σa, B a) → Type _)
: (Σa b, C ⟨a, b⟩) ≃ (Σu, C u) :=
equiv.mk _ (adjointify
(λav, ⟨⟨av.1, av.2.1⟩, av.2.2⟩)
(λuc, ⟨uc.1.1, uc.1.2, by rwr sigma.eta; exact uc.2⟩)
begin abstract { intro uc, induction uc with u c, induction u, reflexivity } end
begin abstract { intro av, induction av with a v, induction v, reflexivity } end)
open prod
@[hott] def assoc_equiv_prod (C : (A × A') → Type _) : (Σa a', C (a,a')) ≃ (Σu, C u) :=
equiv.mk _ (adjointify
(λav, ⟨(av.1, av.2.1), av.2.2⟩)
(λuc, ⟨(uc.1).1, (uc.1).2, by rwr prod.eta; exact uc.2⟩)
(λ ⟨⟨a,b⟩,c⟩, idp) (λ ⟨a,⟨b,c⟩⟩, idp))
/- Symmetry -/
@[hott] def comm_equiv_unc (C : A × A' → Type _) : (Σa a', C (a, a')) ≃ (Σa' a, C (a, a')) :=
calc
(Σa a', C (a, a')) ≃ Σu, C u : assoc_equiv_prod _
... ≃ Σv, C (flip v) : sigma_equiv_sigma (prod.prod_comm_equiv _ _)
(λ ⟨a,a'⟩, equiv.rfl)
... ≃ Σa' a, C (a, a') : by symmetry; exact assoc_equiv_prod (C ∘ prod.flip)
@[hott] def sigma_comm_equiv (C : A → A' → Type _)
: (Σa a', C a a') ≃ (Σa' a, C a a') :=
comm_equiv_unc (λu, C (fst u) (snd u))
@[hott] def equiv_prod (A B : Type _) : (Σ(a : A), B) ≃ A × B :=
equiv.mk _ (adjointify
(λs, (s.1, s.2))
(λp, ⟨fst p, snd p⟩)
(λ⟨a,b⟩, idp) (λ⟨a,b⟩, idp))
@[hott] def comm_equiv_nondep (A B : Type _) : (Σ(a : A), B) ≃ Σ(b : B), A :=
calc
(Σ(a : A), B) ≃ A × B : by apply equiv_prod
... ≃ B × A : by apply prod.prod_comm_equiv
... ≃ Σ(b : B), A : by symmetry; apply equiv_prod
@[hott] def sigma_assoc_comm_equiv {A : Type _} (B C : A → Type _)
: (Σ(v : Σa, B a), C v.1) ≃ (Σ(u : Σa, C a), B u.1) :=
calc (Σ(v : Σa, B a), C v.1)
≃ (Σa (b : B a), C a) : by symmetry; apply sigma_assoc_equiv (C ∘ fst)
... ≃ (Σa (c : C a), B a) : by apply sigma_equiv_sigma_right; intro a; apply comm_equiv_nondep
... ≃ (Σ(u : Σa, C a), B u.1) : by apply sigma_assoc_equiv (B ∘ fst)
/- Interaction with other type constructors -/
@[hott] def sigma_empty_left (B : empty → Type _) : (Σx, B x) ≃ empty :=
begin
fapply equiv.MK,
{ intro v, induction v, cases v_fst},
{ intro x, cases x},
{ intro x, cases x},
{ intro v, induction v, cases v_fst},
end
@[hott] def sigma_empty_right (A : Type _) : (Σ(a : A), empty) ≃ empty :=
begin
fapply equiv.MK,
{ intro v, induction v, cases v_snd},
{ intro x, cases x},
{ intro x, cases x},
{ intro v, induction v, cases v_snd},
end
@[hott] def sigma_unit_left (B : unit → Type _) : (Σx, B x) ≃ B star :=
sigma_equiv_of_is_contr_left _
@[hott] def sigma_unit_right (A : Type _) : (Σ(a : A), unit) ≃ A :=
sigma_equiv_of_is_contr_right _
@[hott] def sigma_sum_left (B : A ⊎ A' → Type _)
: (Σp, B p) ≃ (Σa, B (inl a)) ⊎ (Σa, B (inr a)) :=
begin
fapply equiv.MK,
{ intro v,
induction v with p b,
induction p,
{ apply inl, constructor, assumption },
{ apply inr, constructor, assumption }},
{ intro p, induction p with v v; induction v; constructor; assumption},
{ intro p, induction p with v v; induction v; reflexivity},
{ intro v, induction v with p b, induction p; reflexivity},
end
@[hott] def sigma_sum_right (B C : A → Type _)
: (Σa, B a ⊎ C a) ≃ (Σa, B a) ⊎ (Σa, C a) :=
begin
fapply equiv.MK,
{ intro v,
induction v with a p,
induction p,
{ apply inl, constructor, assumption},
{ apply inr, constructor, assumption}},
{ intro p,
induction p with v v,
{ induction v, constructor, apply inl, assumption },
{ induction v, constructor, apply inr, assumption }},
{ intro p, induction p with v v; induction v; reflexivity},
{ intro v, induction v with a p, induction p; reflexivity},
end
@[hott] def sigma_sigma_eq_right {A : Type _} (a : A) (P : Π(b : A), a = b → Type _)
: (Σ(b : A) (p : a = b), P b p) ≃ P a idp :=
calc
(Σ(b : A) (p : a = b), P b p) ≃ (Σ(v : Σ(b : A), a = b), P v.1 v.2) : by apply sigma_assoc_equiv (λ u, P u.fst u.snd)
... ≃ P a idp : by apply sigma_equiv_of_is_contr_left (λ v : Σ b, a=b, P v.fst v.snd)
@[hott] def sigma_sigma_eq_left {A : Type _} (a : A) (P : Π(b : A), b = a → Type _)
: (Σ(b : A) (p : b = a), P b p) ≃ P a idp :=
calc
(Σ(b : A) (p : b = a), P b p) ≃ (Σ(v : Σ(b : A), b = a), P v.1 v.2) : by apply sigma_assoc_equiv (λ u : Σ b, b=a, P u.fst u.snd)
... ≃ P a idp : by apply sigma_equiv_of_is_contr_left (λ v : Σ b, b=a, P v.fst v.snd)
/- ** Universal mapping properties -/
/- *** The positive universal property. -/
section
@[hott, instance] def is_equiv_sigma_rec (C : (Σa, B a) → Type _)
: is_equiv (sigma.rec : (Πa b, C ⟨a, b⟩) → Πab, C ab) :=
adjointify _ (λ g a b, g ⟨a, b⟩)
(λ g, eq_of_homotopy (λ⟨a,b⟩, idp))
(λ f, refl f)
@[hott] def equiv_sigma_rec (C : (Σa, B a) → Type _)
: (Π(a : A) (b: B a), C ⟨a, b⟩) ≃ (Πxy, C xy) :=
equiv.mk sigma.rec (by apply_instance)
/- *** The negative universal property. -/
@[hott] protected def coind_unc (fg : Σ(f : Πa, B a), Πa, C a (f a)) (a : A)
: Σ(b : B a), C a b :=
⟨fg.1 a, fg.2 a⟩
@[hott] protected def coind (f : Π a, B a) (g : Π a, C a (f a)) (a : A) : Σ(b : B a), C a b :=
sigma.coind_unc ⟨f, g⟩ a
--is the instance below dangerous?
--in Coq this can be done without function extensionality
@[hott, instance] def is_equiv_coind (C : Πa, B a → Type _)
: is_equiv (@sigma.coind_unc _ _ C) :=
adjointify _ (λ h, ⟨λa, (h a).1, λa, (h a).2⟩)
(λ h, eq_of_homotopy (λu, sigma.eta _))
(λ⟨f,g⟩, idp)
variable (C)
@[hott] def sigma_pi_equiv_pi_sigma : (Σ(f : Πa, B a), Πa, C a (f a)) ≃ (Πa, Σb, C a b) :=
equiv.mk sigma.coind_unc (by apply_instance)
variable {C}
end
/- Subtypes (sigma types whose second components are props) -/
@[hott] def subtype {A : Type _} (P : A → Type _) [H : Πa, is_prop (P a)] :=
Σ(a : A), P a
notation [parsing_only] `{` binder `|` r:(scoped:1 P, subtype P) `}` := r
/- To prove equality in a subtype, we only need equality of the first component. -/
@[hott] def subtype_eq [H : Πa, is_prop (B a)] {u v : {a | B a}} :
u.1 = v.1 → u = v :=
sigma_eq_unc ∘ inv fst
@[hott] def is_equiv_subtype_eq [H : Πa, is_prop (B a)] (u v : {a | B a})
: is_equiv (subtype_eq : u.1 = v.1 → u = v) :=
is_equiv_compose _ _
local attribute [instance] is_equiv_subtype_eq
@[hott] def equiv_subtype [H : Πa, is_prop (B a)] (u v : {a | B a}) :
(u.1 = v.1) ≃ (u = v) :=
equiv.mk subtype_eq (by apply_instance)
@[hott] def subtype_eq_equiv [H : Πa, is_prop (B a)] (u v : {a | B a}) :
(u = v) ≃ (u.1 = v.1) :=
(equiv_subtype u v)⁻¹ᵉ
@[hott] def subtype_eq_inv {A : Type _} {B : A → Type _} [H : Πa, is_prop (B a)] (u v : Σa, B a)
: u = v → u.1 = v.1 :=
subtype_eq⁻¹ᶠ
@[hott] def is_equiv_subtype_eq_inv {A : Type _} {B : A → Type _} [H : Πa, is_prop (B a)]
(u v : Σa, B a) : is_equiv (subtype_eq_inv u v) :=
by delta subtype_eq_inv; apply_instance
/- truncatedness -/
@[hott] def is_trunc_sigma (B : A → Type _) (n : trunc_index)
[HA : is_trunc n A] [HB : Πa, is_trunc n (B a)] : is_trunc n (Σa, B a) :=
begin
unfreezeI, revert A B HA HB,
induction n with n IH; resetI,
{ intros A B HA HB, apply is_trunc_equiv_closed_rev -2 (sigma_equiv_of_is_contr_left B) (HB _) },
{ intros A B HA HB, apply is_trunc_succ_intro, intros u v,
apply is_trunc_equiv_closed_rev _ (sigma_eq_equiv _ _) (IH _);
apply_instance }
end
@[hott] theorem is_trunc_subtype (B : A → Prop) (n : trunc_index)
[HA : is_trunc (n.+1) A] : is_trunc (n.+1) (Σa, B a) :=
@is_trunc_sigma _ (λ a, B a) (n.+1) _ (λa, is_trunc_succ_of_is_prop _ _)
/- if the total space is a mere proposition, you can equate two points in the base type by
finding points in their fibers -/
@[hott] def eq_base_of_is_prop_sigma {A : Type _} (B : A → Type _) (H : is_prop (Σa, B a)) {a a' : A}
(b : B a) (b' : B a') : a = a' :=
(@is_prop.elim (Σa, B a) _ ⟨a, b⟩ ⟨a', b'⟩)..1
end sigma
attribute [instance] sigma.is_trunc_sigma
attribute [instance] sigma.is_trunc_subtype
namespace sigma
/- pointed sigma type -/
open pointed
@[hott, instance] def pointed_sigma {A : Type _} (P : A → Type _) [G : pointed A]
[H : pointed (P pt)] : pointed (Σx, P x) :=
pointed.mk ⟨pt,pt⟩
@[hott] def psigma {A : Type*} (P : A → Type*) : Type* :=
pointed.mk' (Σa, P a)
notation `Σ*` binders `, ` r:(scoped P, psigma P) := r
@[hott] def pfst {A : Type*} {B : A → Type*} : (Σ*(x : A), B x) →* A :=
pmap.mk fst idp
@[hott] def psnd {A : Type*} {B : A → Type*} (v : (Σ*(x : A), B x)) : B (pfst.to_fun v) :=
snd v
@[hott] def ptsigma {n : ℕ₋₂} {A : n-Type*} (P : A → (n-Type*)) : n-Type* :=
ptrunctype.mk' n (Σa, P a)
end sigma
end hott |
96aa67528985b93075b4d542c2836ebfcecad594 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /tests/lean/run/check_constants.lean | 62f9d1ecb7231a1a7b47f824a3905ae19ee263f5 | [
"Apache-2.0"
] | permissive | pacchiano/lean | 9324b33f3ac3b5c5647285160f9f6ea8d0d767dc | fdadada3a970377a6df8afcd629a6f2eab6e84e8 | refs/heads/master | 1,611,357,380,399 | 1,489,870,101,000 | 1,489,870,101,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,872 | lean | -- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py
import smt system.io
open tactic
meta def script_check_id (n : name) : tactic unit :=
do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute")
run_cmd script_check_id `abs
run_cmd script_check_id `absurd
run_cmd script_check_id `acc.cases_on
run_cmd script_check_id `add
run_cmd script_check_id `add_comm_group
run_cmd script_check_id `add_comm_semigroup
run_cmd script_check_id `add_group
run_cmd script_check_id `add_monoid
run_cmd script_check_id `and
run_cmd script_check_id `and.elim_left
run_cmd script_check_id `and.elim_right
run_cmd script_check_id `and.intro
run_cmd script_check_id `andthen
run_cmd script_check_id `applicative.pure
run_cmd script_check_id `auto_param
run_cmd script_check_id `bit0
run_cmd script_check_id `bit1
run_cmd script_check_id `bool
run_cmd script_check_id `bool.ff
run_cmd script_check_id `bool.tt
run_cmd script_check_id `bind
run_cmd script_check_id `combinator.K
run_cmd script_check_id `caching_user_attribute
run_cmd script_check_id `cast
run_cmd script_check_id `cast_heq
run_cmd script_check_id `char
run_cmd script_check_id `char.of_nat
run_cmd script_check_id `char.of_nat_ne_of_ne
run_cmd script_check_id `classical.prop_decidable
run_cmd script_check_id `classical.type_decidable_eq
run_cmd script_check_id `coe
run_cmd script_check_id `coe_fn
run_cmd script_check_id `coe_sort
run_cmd script_check_id `coe_to_lift
run_cmd script_check_id `congr
run_cmd script_check_id `congr_arg
run_cmd script_check_id `congr_fun
run_cmd script_check_id `decidable
run_cmd script_check_id `decidable.to_bool
run_cmd script_check_id `distrib
run_cmd script_check_id `dite
run_cmd script_check_id `div
run_cmd script_check_id `id
run_cmd script_check_id `empty
run_cmd script_check_id `emptyc
run_cmd script_check_id `Exists
run_cmd script_check_id `eq
run_cmd script_check_id `eq.cases_on
run_cmd script_check_id `eq.drec
run_cmd script_check_id `eq.mp
run_cmd script_check_id `eq.mpr
run_cmd script_check_id `eq.rec
run_cmd script_check_id `eq.refl
run_cmd script_check_id `eq.subst
run_cmd script_check_id `eq.symm
run_cmd script_check_id `eq.trans
run_cmd script_check_id `eq_of_heq
run_cmd script_check_id `eq_rec_heq
run_cmd script_check_id `eq_true_intro
run_cmd script_check_id `eq_false_intro
run_cmd script_check_id `eq_self_iff_true
run_cmd script_check_id `expr
run_cmd script_check_id `expr.subst
run_cmd script_check_id `format
run_cmd script_check_id `false
run_cmd script_check_id `false_of_true_iff_false
run_cmd script_check_id `false_of_true_eq_false
run_cmd script_check_id `true_eq_false_of_false
run_cmd script_check_id `false.rec
run_cmd script_check_id `field
run_cmd script_check_id `fin.mk
run_cmd script_check_id `fin.ne_of_vne
run_cmd script_check_id `forall_congr
run_cmd script_check_id `forall_congr_eq
run_cmd script_check_id `forall_not_of_not_exists
run_cmd script_check_id `funext
run_cmd script_check_id `ge
run_cmd script_check_id `gt
run_cmd script_check_id `has_add
run_cmd script_check_id `has_bind.bind
run_cmd script_check_id `has_bind.and_then
run_cmd script_check_id `has_bind.seq
run_cmd script_check_id `has_div
run_cmd script_check_id `has_mul
run_cmd script_check_id `has_inv
run_cmd script_check_id `has_le
run_cmd script_check_id `has_lt
run_cmd script_check_id `has_neg
run_cmd script_check_id `has_one
run_cmd script_check_id `has_one.one
run_cmd script_check_id `has_sizeof
run_cmd script_check_id `has_sizeof.mk
run_cmd script_check_id `has_sub
run_cmd script_check_id `has_to_format
run_cmd script_check_id `has_to_string
run_cmd script_check_id `has_zero
run_cmd script_check_id `has_zero.zero
run_cmd script_check_id `has_coe_t
run_cmd script_check_id `heq
run_cmd script_check_id `heq.refl
run_cmd script_check_id `heq.symm
run_cmd script_check_id `heq.trans
run_cmd script_check_id `heq_of_eq
run_cmd script_check_id `id_locked
run_cmd script_check_id `if_neg
run_cmd script_check_id `if_pos
run_cmd script_check_id `iff
run_cmd script_check_id `iff_false_intro
run_cmd script_check_id `iff.intro
run_cmd script_check_id `iff.mp
run_cmd script_check_id `iff.mpr
run_cmd script_check_id `iff.refl
run_cmd script_check_id `iff.symm
run_cmd script_check_id `iff.trans
run_cmd script_check_id `iff_true_intro
run_cmd script_check_id `imp_congr
run_cmd script_check_id `imp_congr_eq
run_cmd script_check_id `imp_congr_ctx
run_cmd script_check_id `imp_congr_ctx_eq
run_cmd script_check_id `implies
run_cmd script_check_id `implies_of_if_neg
run_cmd script_check_id `implies_of_if_pos
run_cmd script_check_id `inductive_compiler.tactic.prove_nested_inj
run_cmd script_check_id `inductive_compiler.tactic.prove_pack_inj
run_cmd script_check_id `insert
run_cmd script_check_id `int
run_cmd script_check_id `int.has_add
run_cmd script_check_id `int.has_mul
run_cmd script_check_id `int.has_sub
run_cmd script_check_id `int.has_div
run_cmd script_check_id `int.has_le
run_cmd script_check_id `int.has_lt
run_cmd script_check_id `int.has_neg
run_cmd script_check_id `int.has_mod
run_cmd script_check_id `int.bit0_nonneg
run_cmd script_check_id `int.bit1_nonneg
run_cmd script_check_id `int.one_nonneg
run_cmd script_check_id `int.zero_nonneg
run_cmd script_check_id `int.bit0_pos
run_cmd script_check_id `int.bit1_pos
run_cmd script_check_id `int.one_pos
run_cmd script_check_id `int.nat_abs_zero
run_cmd script_check_id `int.nat_abs_one
run_cmd script_check_id `int.nat_abs_bit0_step
run_cmd script_check_id `int.nat_abs_bit1_nonneg_step
run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case
run_cmd script_check_id `int.ne_neg_of_ne
run_cmd script_check_id `int.neg_ne_of_pos
run_cmd script_check_id `int.ne_neg_of_pos
run_cmd script_check_id `int.neg_ne_zero_of_ne
run_cmd script_check_id `int.zero_ne_neg_of_ne
run_cmd script_check_id `int.decidable_linear_ordered_comm_group
run_cmd script_check_id `interactive.param_desc
run_cmd script_check_id `interactive.parse
run_cmd script_check_id `inv
run_cmd script_check_id `io
run_cmd script_check_id `io.map
run_cmd script_check_id `io.bind
run_cmd script_check_id `io.monad
run_cmd script_check_id `io.return
run_cmd script_check_id `io.put_str
run_cmd script_check_id `io.get_line
run_cmd script_check_id `is_associative
run_cmd script_check_id `is_associative.assoc
run_cmd script_check_id `is_commutative
run_cmd script_check_id `is_commutative.comm
run_cmd script_check_id `ite
run_cmd script_check_id `left_distrib
run_cmd script_check_id `left_comm
run_cmd script_check_id `le
run_cmd script_check_id `le_refl
run_cmd script_check_id `linear_ordered_ring
run_cmd script_check_id `linear_ordered_semiring
run_cmd script_check_id `list
run_cmd script_check_id `list.nil
run_cmd script_check_id `list.cons
run_cmd script_check_id `lt
run_cmd script_check_id `match_failed
run_cmd script_check_id `mod
run_cmd script_check_id `monad
run_cmd script_check_id `monad.bind
run_cmd script_check_id `monad_fail
run_cmd script_check_id `monoid
run_cmd script_check_id `mul
run_cmd script_check_id `mul_one
run_cmd script_check_id `mul_zero
run_cmd script_check_id `mul_zero_class
run_cmd script_check_id `name.anonymous
run_cmd script_check_id `name.mk_numeral
run_cmd script_check_id `name.mk_string
run_cmd script_check_id `nat
run_cmd script_check_id `nat.of_num
run_cmd script_check_id `nat.succ
run_cmd script_check_id `nat.zero
run_cmd script_check_id `nat.has_zero
run_cmd script_check_id `nat.has_one
run_cmd script_check_id `nat.has_add
run_cmd script_check_id `nat.add
run_cmd script_check_id `nat.cases_on
run_cmd script_check_id `nat.bit0_ne
run_cmd script_check_id `nat.bit0_ne_bit1
run_cmd script_check_id `nat.bit0_ne_zero
run_cmd script_check_id `nat.bit0_ne_one
run_cmd script_check_id `nat.bit1_ne
run_cmd script_check_id `nat.bit1_ne_bit0
run_cmd script_check_id `nat.bit1_ne_zero
run_cmd script_check_id `nat.bit1_ne_one
run_cmd script_check_id `nat.zero_ne_one
run_cmd script_check_id `nat.zero_ne_bit0
run_cmd script_check_id `nat.zero_ne_bit1
run_cmd script_check_id `nat.one_ne_zero
run_cmd script_check_id `nat.one_ne_bit0
run_cmd script_check_id `nat.one_ne_bit1
run_cmd script_check_id `nat.bit0_lt
run_cmd script_check_id `nat.bit1_lt
run_cmd script_check_id `nat.bit0_lt_bit1
run_cmd script_check_id `nat.bit1_lt_bit0
run_cmd script_check_id `nat.zero_lt_one
run_cmd script_check_id `nat.zero_lt_bit1
run_cmd script_check_id `nat.zero_lt_bit0
run_cmd script_check_id `nat.one_lt_bit0
run_cmd script_check_id `nat.one_lt_bit1
run_cmd script_check_id `nat.le_of_lt
run_cmd script_check_id `nat.le_refl
run_cmd script_check_id `ne
run_cmd script_check_id `neg
run_cmd script_check_id `neq_of_not_iff
run_cmd script_check_id `norm_num.add1
run_cmd script_check_id `norm_num.add1_bit0
run_cmd script_check_id `norm_num.add1_bit1_helper
run_cmd script_check_id `norm_num.add1_one
run_cmd script_check_id `norm_num.add1_zero
run_cmd script_check_id `norm_num.add_div_helper
run_cmd script_check_id `norm_num.bin_add_zero
run_cmd script_check_id `norm_num.bin_zero_add
run_cmd script_check_id `norm_num.bit0_add_bit0_helper
run_cmd script_check_id `norm_num.bit0_add_bit1_helper
run_cmd script_check_id `norm_num.bit0_add_one
run_cmd script_check_id `norm_num.bit1_add_bit0_helper
run_cmd script_check_id `norm_num.bit1_add_bit1_helper
run_cmd script_check_id `norm_num.bit1_add_one_helper
run_cmd script_check_id `norm_num.div_add_helper
run_cmd script_check_id `norm_num.div_eq_div_helper
run_cmd script_check_id `norm_num.div_helper
run_cmd script_check_id `norm_num.div_mul_helper
run_cmd script_check_id `norm_num.mk_cong
run_cmd script_check_id `norm_num.mul_bit0_helper
run_cmd script_check_id `norm_num.mul_bit1_helper
run_cmd script_check_id `norm_num.mul_div_helper
run_cmd script_check_id `norm_num.neg_add_neg_helper
run_cmd script_check_id `norm_num.neg_add_pos_helper1
run_cmd script_check_id `norm_num.neg_add_pos_helper2
run_cmd script_check_id `norm_num.neg_mul_neg_helper
run_cmd script_check_id `norm_num.neg_mul_pos_helper
run_cmd script_check_id `norm_num.neg_neg_helper
run_cmd script_check_id `norm_num.neg_zero_helper
run_cmd script_check_id `norm_num.nonneg_bit0_helper
run_cmd script_check_id `norm_num.nonneg_bit1_helper
run_cmd script_check_id `norm_num.nonzero_of_div_helper
run_cmd script_check_id `norm_num.nonzero_of_neg_helper
run_cmd script_check_id `norm_num.nonzero_of_pos_helper
run_cmd script_check_id `norm_num.one_add_bit0
run_cmd script_check_id `norm_num.one_add_bit1_helper
run_cmd script_check_id `norm_num.one_add_one
run_cmd script_check_id `norm_num.pos_add_neg_helper
run_cmd script_check_id `norm_num.pos_bit0_helper
run_cmd script_check_id `norm_num.pos_bit1_helper
run_cmd script_check_id `norm_num.pos_mul_neg_helper
run_cmd script_check_id `norm_num.sub_nat_zero_helper
run_cmd script_check_id `norm_num.sub_nat_pos_helper
run_cmd script_check_id `norm_num.subst_into_div
run_cmd script_check_id `norm_num.subst_into_prod
run_cmd script_check_id `norm_num.subst_into_subtr
run_cmd script_check_id `norm_num.subst_into_sum
run_cmd script_check_id `not
run_cmd script_check_id `not_of_iff_false
run_cmd script_check_id `not_of_eq_false
run_cmd script_check_id `num
run_cmd script_check_id `num.pos
run_cmd script_check_id `num.zero
run_cmd script_check_id `of_eq_true
run_cmd script_check_id `of_iff_true
run_cmd script_check_id `one
run_cmd script_check_id `opt_param
run_cmd script_check_id `or
run_cmd script_check_id `orelse
run_cmd script_check_id `out_param
run_cmd script_check_id `punit
run_cmd script_check_id `punit.star
run_cmd script_check_id `pos_num.bit0
run_cmd script_check_id `pos_num.bit1
run_cmd script_check_id `pos_num.one
run_cmd script_check_id `prod.mk
run_cmd script_check_id `pprod
run_cmd script_check_id `pprod.mk
run_cmd script_check_id `pprod.fst
run_cmd script_check_id `pprod.snd
run_cmd script_check_id `propext
run_cmd script_check_id `pexpr
run_cmd script_check_id `pexpr.subst
run_cmd script_check_id `to_pexpr
run_cmd script_check_id `quot.mk
run_cmd script_check_id `quot.lift
run_cmd script_check_id `real
run_cmd script_check_id `real.of_int
run_cmd script_check_id `real.to_int
run_cmd script_check_id `real.is_int
run_cmd script_check_id `real.has_neg
run_cmd script_check_id `real.has_div
run_cmd script_check_id `real.has_add
run_cmd script_check_id `real.has_mul
run_cmd script_check_id `real.has_sub
run_cmd script_check_id `real.has_lt
run_cmd script_check_id `real.has_le
run_cmd script_check_id `rfl
run_cmd script_check_id `right_distrib
run_cmd script_check_id `ring
run_cmd script_check_id `scope_trace
run_cmd script_check_id `set_of
run_cmd script_check_id `sep
run_cmd script_check_id `semiring
run_cmd script_check_id `sigma
run_cmd script_check_id `sigma.mk
run_cmd script_check_id `sigma.fst
run_cmd script_check_id `sigma.snd
run_cmd script_check_id `psigma
run_cmd script_check_id `psigma.cases_on
run_cmd script_check_id `psigma.mk
run_cmd script_check_id `singleton
run_cmd script_check_id `sizeof
run_cmd script_check_id `smt.array
run_cmd script_check_id `smt.select
run_cmd script_check_id `smt.store
run_cmd script_check_id `smt.prove
run_cmd script_check_id `string
run_cmd script_check_id `string.empty
run_cmd script_check_id `string.str
run_cmd script_check_id `string.empty_ne_str
run_cmd script_check_id `string.str_ne_empty
run_cmd script_check_id `string.str_ne_str_left
run_cmd script_check_id `string.str_ne_str_right
run_cmd script_check_id `sub
run_cmd script_check_id `subsingleton
run_cmd script_check_id `subsingleton.elim
run_cmd script_check_id `subsingleton.helim
run_cmd script_check_id `subtype
run_cmd script_check_id `subtype.mk
run_cmd script_check_id `subtype.val
run_cmd script_check_id `subtype.rec
run_cmd script_check_id `psum
run_cmd script_check_id `psum.cases_on
run_cmd script_check_id `psum.inl
run_cmd script_check_id `psum.inr
run_cmd script_check_id `tactic
run_cmd script_check_id `tactic.eval_expr
run_cmd script_check_id `tactic.try
run_cmd script_check_id `tactic.triv
run_cmd script_check_id `thunk
run_cmd script_check_id `to_fmt
run_cmd script_check_id `to_string
run_cmd script_check_id `trans_rel_left
run_cmd script_check_id `trans_rel_right
run_cmd script_check_id `true
run_cmd script_check_id `true.intro
run_cmd script_check_id `unification_hint
run_cmd script_check_id `unification_hint.mk
run_cmd script_check_id `unit
run_cmd script_check_id `unit.cases_on
run_cmd script_check_id `unit.star
run_cmd script_check_id `user_attribute
run_cmd script_check_id `vm_monitor
run_cmd script_check_id `weak_order
run_cmd script_check_id `well_founded
run_cmd script_check_id `xor
run_cmd script_check_id `zero
run_cmd script_check_id `zero_le_one
run_cmd script_check_id `zero_lt_one
run_cmd script_check_id `zero_mul
|
96c40e8fa60a36801b1e4d0652d68e4dd566112c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/field_theory/laurent.lean | f9717fa802e17197197b9b70602cb563769a7da1 | [
"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,770 | lean | /-
Copyright (c) 2022 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import data.polynomial.taylor
import field_theory.ratfunc
import ring_theory.laurent_series
/-!
# Laurent expansions of rational functions
## Main declarations
* `ratfunc.laurent`: the Laurent expansion of the rational function `f` at `r`, as an `alg_hom`.
* `ratfunc.laurent_injective`: the Laurent expansion at `r` is unique
## Implementation details
Implemented as the quotient of two Taylor expansions, over domains.
An auxiliary definition is provided first to make the construction of the `alg_hom` easier,
which works on `comm_ring` which are not necessarily domains.
-/
universe u
namespace ratfunc
noncomputable theory
open polynomial
open_locale classical non_zero_divisors
variables {R : Type u} [comm_ring R] [hdomain : is_domain R]
(r s : R) (p q : polynomial R) (f : ratfunc R)
lemma taylor_mem_non_zero_divisors (hp : p ∈ (polynomial R)⁰) : taylor r p ∈ (polynomial R)⁰ :=
begin
rw mem_non_zero_divisors_iff,
intros x hx,
have : x = taylor (r - r) x,
{ simp },
have ht := polynomial.taylor_injective r,
rwa [this, sub_eq_add_neg, ←taylor_taylor, ←taylor_mul,
linear_map.map_eq_zero_iff _ (taylor_injective _),
mul_right_mem_non_zero_divisors_eq_zero_iff hp,
linear_map.map_eq_zero_iff _ (taylor_injective _)] at hx,
end
/-- The Laurent expansion of rational functions about a value.
Auxiliary definition, usage when over integral domains should prefer `ratfunc.laurent`. -/
def laurent_aux : ratfunc R →+* ratfunc R :=
ratfunc.map_ring_hom (ring_hom.mk (taylor r) (taylor_one _) (taylor_mul _)
(linear_map.map_zero _) (linear_map.map_add _)) (taylor_mem_non_zero_divisors _)
lemma laurent_aux_of_fraction_ring_mk (q : (polynomial R)⁰) :
laurent_aux r (of_fraction_ring (localization.mk p q)) =
of_fraction_ring (localization.mk (taylor r p)
⟨taylor r q, taylor_mem_non_zero_divisors r q q.prop⟩) :=
map_apply_of_fraction_ring_mk _ _ _ _
include hdomain
lemma laurent_aux_div :
laurent_aux r (algebra_map _ _ p / (algebra_map _ _ q)) =
algebra_map _ _ (taylor r p) / (algebra_map _ _ (taylor r q)) :=
map_apply_div _ _ _ _
@[simp] lemma laurent_aux_algebra_map :
laurent_aux r (algebra_map _ _ p) = algebra_map _ _ (taylor r p) :=
by rw [←mk_one, ←mk_one, mk_eq_div, laurent_aux_div, mk_eq_div, taylor_one, _root_.map_one]
/-- The Laurent expansion of rational functions about a value. -/
def laurent : ratfunc R →ₐ[R] ratfunc R :=
ratfunc.map_alg_hom (alg_hom.mk (taylor r) (taylor_one _) (taylor_mul _)
(linear_map.map_zero _) (linear_map.map_add _) (by simp [polynomial.algebra_map_apply]))
(taylor_mem_non_zero_divisors _)
lemma laurent_div :
laurent r (algebra_map _ _ p / (algebra_map _ _ q)) =
algebra_map _ _ (taylor r p) / (algebra_map _ _ (taylor r q)) :=
laurent_aux_div r p q
@[simp] lemma laurent_algebra_map :
laurent r (algebra_map _ _ p) = algebra_map _ _ (taylor r p) :=
laurent_aux_algebra_map _ _
@[simp] lemma laurent_X : laurent r X = X + C r :=
by rw [←algebra_map_X, laurent_algebra_map, taylor_X, _root_.map_add, algebra_map_C]
@[simp] lemma laurent_C (x : R) : laurent r (C x) = C x :=
by rw [←algebra_map_C, laurent_algebra_map, taylor_C]
@[simp] lemma laurent_at_zero : laurent 0 f = f :=
by { induction f using ratfunc.induction_on, simp }
lemma laurent_laurent :
laurent r (laurent s f) = laurent (r + s) f :=
begin
induction f using ratfunc.induction_on,
simp_rw [laurent_div, taylor_taylor]
end
lemma laurent_injective : function.injective (laurent r) :=
λ _ _ h, by simpa [laurent_laurent] using congr_arg (laurent (-r)) h
end ratfunc
|
e2150256487978a882fd6336dcd104692cacf36b | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/char_p/default.lean | f0898fa6bdf4116f2caf8c9a785c549cb9a4ba41 | [
"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 | 144 | lean | import algebra.char_p.algebra
import algebra.char_p.basic
import algebra.char_p.pi
import algebra.char_p.quotient
import algebra.char_p.subring
|
139e11e06da457fa119c81841d0122a08b954c57 | f3a5af2927397cf346ec0e24312bfff077f00425 | /src/game/world8/level9.lean | 70e3556de9d6d82d177c15e14557af5b036fa233 | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/natural_number_game | 05c39e1586408cfb563d1a12e1085a90726ab655 | f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd | refs/heads/master | 1,688,570,964,990 | 1,636,908,242,000 | 1,636,908,242,000 | 195,403,790 | 277 | 84 | Apache-2.0 | 1,694,547,955,000 | 1,562,328,792,000 | Lean | UTF-8 | Lean | false | false | 1,643 | lean | import mynat.definition -- hide
import mynat.add -- hide
import game.world8.level8 -- hide
namespace mynat -- hide
/- Axiom : zero_ne_succ (a : mynat) :
0 ≠ succ(a)
-/
/- Tactic : symmetry
## Summary
`symmetry` turns goals of the form `⊢ A = B` to `⊢ B = A`.
Also works with `≠`. Also works on hypotheses: if `h : a ≠ b`
then `symmetry at h` gives `h : b ≠ a`.
## Details
`symmetry` works on both goals and hypotheses. By default it
works on the goal. It will turn a goal of the form `⊢ A = B`
to `⊢ B = A`. More generally it will work with any symmetric
binary relation (for example `≠`, or more generally any
binary relation whose proof of symmetry has been tagged
with the `symm` attribute).
To get `symmetry` working on a hypothesis, use `symmetry at h`.
## Examples
If the tactic state is
```
h : a = b
⊢ c ≠ d
```
then `symmetry` changes the goal to `⊢ d ≠ c` and
`symmetry at h` changes `h` to `h : b = a`.
-/
/-
# Advanced Addition World
## Level 9: `succ_ne_zero`
Levels 9 to 13 introduce the last axiom of Peano, namely
that $0\not=\operatorname{succ}(a)$. The proof of this is called `zero_ne_succ a`.
`zero_ne_succ (a : mynat) : 0 ≠ succ(a)`
The `symmetry` tactic will turn any goal of the form `R x y` into `R y x`,
if `R` is a symmetric binary relation (for example `=` or `≠`).
In particular, you can prove `succ_ne_zero` below by first using
`symmetry` and then `exact zero_ne_succ a`.
-/
/- Theorem
Zero is not the successor of any natural number.
-/
theorem succ_ne_zero (a : mynat) : succ a ≠ 0 :=
begin [nat_num_game]
symmetry,
exact zero_ne_succ a,
end
end mynat
|
57f32c01eeebbc86f8e02003c2c58a42840039ce | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/dunfold3.lean | 413858040b8d9143d19d4ef759e589b18661f349 | [
"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 | 552 | lean | open tactic
def g : nat → nat := λ x, x + 5
set_option pp.all true
example (a b : nat) (p : nat → Prop) (h : p (g (nat.succ (nat.succ a)))) : p (g (a + 2)) :=
begin
unfold g at h,
do { h ← get_local `h >>= infer_type, t ← to_expr ```(p (nat.succ (nat.succ a) + 5)), guard (h = t) },
unfold has_add.add bit0 has_one.one nat.add,
unfold g,
do { t ← target, h ← get_local `h >>= infer_type, guard (t = h) },
assumption
end
meta def check_expected (p : pexpr) : tactic unit :=
do t ← target, ex ← to_expr p, guard (t = ex)
|
b8cae3a70438c4dc57c7b7ff58a88d3c34bbcc49 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/order/filter/ultrafilter.lean | 13963d6a379abf854cca83385afd7f91f0508bd1 | [
"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 | 14,858 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov
-/
import order.filter.cofinite
import order.zorn
/-!
# Ultrafilters
An ultrafilter is a minimal (maximal in the set order) proper filter.
In this file we define
* `ultrafilter.of`: an ultrafilter that is less than or equal to a given filter;
* `ultrafilter`: subtype of ultrafilters;
* `ultrafilter.pure`: `pure x` as an `ultrafiler`;
* `ultrafilter.map`, `ultrafilter.bind`, `ultrafilter.comap` : operations on ultrafilters;
* `hyperfilter`: the ultrafilter extending the cofinite filter.
-/
universes u v
variables {α : Type u} {β : Type v}
open set zorn filter function
open_locale classical filter
/-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/
@[protect_proj]
structure ultrafilter (α : Type*) extends filter α :=
(ne_bot' : ne_bot to_filter)
(le_of_le : ∀ g, filter.ne_bot g → g ≤ to_filter → to_filter ≤ g)
namespace ultrafilter
variables {f g : ultrafilter α} {s t : set α} {p q : α → Prop}
instance : has_coe_t (ultrafilter α) (filter α) := ⟨ultrafilter.to_filter⟩
instance : has_mem (set α) (ultrafilter α) := ⟨λ s f, s ∈ (f : filter α)⟩
lemma unique (f : ultrafilter α) {g : filter α} (h : g ≤ f)
(hne : ne_bot g . tactic.apply_instance) : g = f :=
le_antisymm h $ f.le_of_le g hne h
instance ne_bot (f : ultrafilter α) : ne_bot (f : filter α) := f.ne_bot'
@[simp, norm_cast] lemma mem_coe : s ∈ (f : filter α) ↔ s ∈ f := iff.rfl
lemma coe_injective : injective (coe : ultrafilter α → filter α)
| ⟨f, h₁, h₂⟩ ⟨g, h₃, h₄⟩ rfl := by congr
lemma eq_of_le {f g : ultrafilter α} (h : (f : filter α) ≤ g) : f = g :=
coe_injective (g.unique h)
@[simp, norm_cast] lemma coe_le_coe {f g : ultrafilter α} : (f : filter α) ≤ g ↔ f = g :=
⟨λ h, eq_of_le h, λ h, h ▸ le_rfl⟩
@[simp, norm_cast] lemma coe_inj : (f : filter α) = g ↔ f = g := coe_injective.eq_iff
@[ext] lemma ext ⦃f g : ultrafilter α⦄ (h : ∀ s, s ∈ f ↔ s ∈ g) : f = g :=
coe_injective $ filter.ext h
lemma le_of_inf_ne_bot (f : ultrafilter α) {g : filter α} (hg : ne_bot (↑f ⊓ g)) : ↑f ≤ g :=
le_of_inf_eq (f.unique inf_le_left hg)
lemma le_of_inf_ne_bot' (f : ultrafilter α) {g : filter α} (hg : ne_bot (g ⊓ f)) : ↑f ≤ g :=
f.le_of_inf_ne_bot $ by rwa inf_comm
@[simp] lemma compl_not_mem_iff : sᶜ ∉ f ↔ s ∈ f :=
⟨λ hsc, le_principal_iff.1 $ f.le_of_inf_ne_bot
⟨λ h, hsc $ mem_of_eq_bot$ by rwa compl_compl⟩, compl_not_mem⟩
@[simp] lemma frequently_iff_eventually : (∃ᶠ x in f, p x) ↔ ∀ᶠ x in f, p x :=
compl_not_mem_iff
alias frequently_iff_eventually ↔ filter.frequently.eventually _
lemma compl_mem_iff_not_mem : sᶜ ∈ f ↔ s ∉ f := by rw [← compl_not_mem_iff, compl_compl]
lemma diff_mem_iff (f : ultrafilter α) : s \ t ∈ f ↔ s ∈ f ∧ t ∉ f :=
inter_mem_iff.trans $ and_congr iff.rfl compl_mem_iff_not_mem
/-- If `sᶜ ∉ f ↔ s ∈ f`, then `f` is an ultrafilter. The other implication is given by
`ultrafilter.compl_not_mem_iff`. -/
def of_compl_not_mem_iff (f : filter α) (h : ∀ s, sᶜ ∉ f ↔ s ∈ f) : ultrafilter α :=
{ to_filter := f,
ne_bot' := ⟨λ hf, by simpa [hf] using h⟩,
le_of_le := λ g hg hgf s hs, (h s).1 $ λ hsc, by exactI compl_not_mem hs (hgf hsc) }
lemma nonempty_of_mem (hs : s ∈ f) : s.nonempty := nonempty_of_mem hs
lemma ne_empty_of_mem (hs : s ∈ f) : s ≠ ∅ := (nonempty_of_mem hs).ne_empty
@[simp] lemma empty_not_mem : ∅ ∉ f := empty_not_mem f
lemma mem_or_compl_mem (f : ultrafilter α) (s : set α) : s ∈ f ∨ sᶜ ∈ f :=
or_iff_not_imp_left.2 compl_mem_iff_not_mem.2
protected lemma em (f : ultrafilter α) (p : α → Prop) :
(∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x :=
f.mem_or_compl_mem {x | p x}
lemma eventually_or : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x :=
⟨λ H, (f.em p).imp_right $ λ hp, (H.and hp).mono $ λ x ⟨hx, hnx⟩, hx.resolve_left hnx,
λ H, H.elim (λ hp, hp.mono $ λ x, or.inl) (λ hp, hp.mono $ λ x, or.inr)⟩
lemma union_mem_iff : s ∪ t ∈ f ↔ s ∈ f ∨ t ∈ f := eventually_or
lemma eventually_not : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := compl_mem_iff_not_mem
lemma eventually_imp : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x :=
by simp only [imp_iff_not_or, eventually_or, eventually_not]
lemma finite_sUnion_mem_iff {s : set (set α)} (hs : finite s) : ⋃₀ s ∈ f ↔ ∃t∈s, t ∈ f :=
finite.induction_on hs (by simp) $ λ a s ha hs his,
by simp [union_mem_iff, his, or_and_distrib_right, exists_or_distrib]
lemma finite_bUnion_mem_iff {is : set β} {s : β → set α} (his : finite is) :
(⋃i∈is, s i) ∈ f ↔ ∃i∈is, s i ∈ f :=
by simp only [← sUnion_image, finite_sUnion_mem_iff (his.image s), bex_image_iff]
/-- Pushforward for ultrafilters. -/
def map (m : α → β) (f : ultrafilter α) : ultrafilter β :=
of_compl_not_mem_iff (map m f) $ λ s, @compl_not_mem_iff _ f (m ⁻¹' s)
@[simp, norm_cast] lemma coe_map (m : α → β) (f : ultrafilter α) :
(map m f : filter β) = filter.map m ↑f := rfl
@[simp] lemma mem_map {m : α → β} {f : ultrafilter α} {s : set β} :
s ∈ map m f ↔ m ⁻¹' s ∈ f := iff.rfl
/-- The pullback of an ultrafilter along an injection whose range is large with respect to the given
ultrafilter. -/
def comap {m : α → β} (u : ultrafilter β) (inj : injective m)
(large : set.range m ∈ u) : ultrafilter α :=
{ to_filter := comap m u,
ne_bot' := u.ne_bot'.comap_of_range_mem large,
le_of_le := λ g hg hgu, by { resetI,
simp only [← u.unique (map_le_iff_le_comap.2 hgu), comap_map inj, le_rfl] } }
@[simp] lemma mem_comap {m : α → β} (u : ultrafilter β) (inj : injective m)
(large : set.range m ∈ u) {s : set α} :
s ∈ u.comap inj large ↔ m '' s ∈ u :=
mem_comap_iff inj large
@[simp] lemma coe_comap {m : α → β} (u : ultrafilter β) (inj : injective m)
(large : set.range m ∈ u) : (u.comap inj large : filter α) = filter.comap m u := rfl
/-- The principal ultrafilter associated to a point `x`. -/
instance : has_pure ultrafilter :=
⟨λ α a, of_compl_not_mem_iff (pure a) $ λ s, by simp⟩
@[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : ultrafilter α) ↔ a ∈ s := iff.rfl
instance [inhabited α] : inhabited (ultrafilter α) := ⟨pure default⟩
instance [nonempty α] : nonempty (ultrafilter α) := nonempty.map pure infer_instance
lemma eq_principal_of_finite_mem {f : ultrafilter α} {s : set α} (h : s.finite) (h' : s ∈ f) :
∃ x ∈ s, (f : filter α) = pure x :=
begin
rw ← bUnion_of_singleton s at h',
rcases (ultrafilter.finite_bUnion_mem_iff h).mp h' with ⟨a, has, haf⟩,
use [a, has],
change (f : filter α) = (pure a : ultrafilter α),
rw [ultrafilter.coe_inj, ← ultrafilter.coe_le_coe],
change (f : filter α) ≤ pure a,
rwa [← principal_singleton, le_principal_iff]
end
/-- Monadic bind for ultrafilters, coming from the one on filters
defined in terms of map and join.-/
def bind (f : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β :=
of_compl_not_mem_iff (bind ↑f (λ x, ↑(m x))) $ λ s,
by simp only [mem_bind', mem_coe, ← compl_mem_iff_not_mem, compl_set_of, compl_compl]
instance has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩
instance functor : functor ultrafilter := { map := @ultrafilter.map }
instance monad : monad ultrafilter := { map := @ultrafilter.map }
section
local attribute [instance] filter.monad filter.is_lawful_monad
instance is_lawful_monad : is_lawful_monad ultrafilter :=
{ id_map := assume α f, coe_injective (id_map f.1),
pure_bind := assume α β a f, coe_injective (pure_bind a (coe ∘ f)),
bind_assoc := assume α β γ f m₁ m₂, coe_injective (filter_eq rfl),
bind_pure_comp_eq_map := assume α β f x, coe_injective (bind_pure_comp_eq_map f x.1) }
end
/-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/
lemma exists_le (f : filter α) [h : ne_bot f] : ∃u : ultrafilter α, ↑u ≤ f :=
begin
let τ := {f' // ne_bot f' ∧ f' ≤ f},
let r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val,
haveI := nonempty_of_ne_bot f,
let top : τ := ⟨f, h, le_refl f⟩,
let sup : Π(c:set τ), chain r c → τ :=
λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.1,
infi_ne_bot_of_directed
(directed_of_chain $ chain_insert hc $ λ ⟨b, _, hb⟩ _ _, or.inl hb)
(assume ⟨⟨a, ha, _⟩, _⟩, ha),
infi_le_of_le ⟨top, mem_insert _ _⟩ le_rfl⟩,
have : ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc),
from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ le_rfl,
have : (∃ (u : τ), ∀ (a : τ), r u a → r a u),
from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩)
(assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁),
cases this with uτ hmin,
exact ⟨⟨uτ.val, uτ.property.left, assume g hg₁ hg₂,
hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩, uτ.property.right⟩
end
alias exists_le ← filter.exists_ultrafilter_le
/-- Construct an ultrafilter extending a given filter.
The ultrafilter lemma is the assertion that such a filter exists;
we use the axiom of choice to pick one. -/
noncomputable def of (f : filter α) [ne_bot f] : ultrafilter α :=
classical.some (exists_le f)
lemma of_le (f : filter α) [ne_bot f] : ↑(of f) ≤ f := classical.some_spec (exists_le f)
lemma of_coe (f : ultrafilter α) : of ↑f = f :=
coe_inj.1 $ f.unique (of_le f)
lemma exists_ultrafilter_of_finite_inter_nonempty (S : set (set α))
(cond : ∀ T : finset (set α), (↑T : set (set α)) ⊆ S → (⋂₀ (↑T : set (set α))).nonempty) :
∃ F : ultrafilter α, S ⊆ F.sets :=
begin
suffices : ∃ F : filter α, ne_bot F ∧ S ⊆ F.sets,
{ rcases this with ⟨F, cond, hF⟩,
resetI,
obtain ⟨G : ultrafilter α, h1 : ↑G ≤ F⟩ := exists_le F,
exact ⟨G, λ T hT, h1 (hF hT)⟩ },
use filter.generate S,
refine ⟨_, λ T hT, filter.generate_sets.basic hT⟩,
rw ← forall_mem_nonempty_iff_ne_bot,
intros T hT,
rcases mem_generate_iff.mp hT with ⟨A, h1, h2, h3⟩,
let B := set.finite.to_finset h2,
rw (show A = ↑B, by simp) at *,
rcases cond B h1 with ⟨x, hx⟩,
exact ⟨x, h3 hx⟩,
end
end ultrafilter
namespace filter
open ultrafilter
lemma mem_iff_ultrafilter {s : set α} {f : filter α} :
s ∈ f ↔ ∀ g : ultrafilter α, ↑g ≤ f → s ∈ g :=
begin
refine ⟨λ hf g hg, hg hf, λ H, by_contra $ λ hf, _⟩,
set g : filter ↥sᶜ := comap coe f,
haveI : ne_bot g := comap_ne_bot_iff_compl_range.2 (by simpa [compl_set_of]),
simpa using H ((of g).map coe) (map_le_iff_le_comap.mpr (of_le g))
end
lemma le_iff_ultrafilter {f₁ f₂ : filter α} : f₁ ≤ f₂ ↔ ∀ g : ultrafilter α, ↑g ≤ f₁ → ↑g ≤ f₂ :=
⟨λ h g h₁, h₁.trans h, λ h s hs, mem_iff_ultrafilter.2 $ λ g hg, h g hg hs⟩
/-- A filter equals the intersection of all the ultrafilters which contain it. -/
lemma supr_ultrafilter_le_eq (f : filter α) :
(⨆ (g : ultrafilter α) (hg : ↑g ≤ f), (g : filter α)) = f :=
eq_of_forall_ge_iff $ λ f', by simp only [supr_le_iff, ← le_iff_ultrafilter]
/-- The `tendsto` relation can be checked on ultrafilters. -/
lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) :
tendsto f l₁ l₂ ↔ ∀ g : ultrafilter α, ↑g ≤ l₁ → tendsto f g l₂ :=
by simpa only [tendsto_iff_comap] using le_iff_ultrafilter
lemma exists_ultrafilter_iff {f : filter α} : (∃ (u : ultrafilter α), ↑u ≤ f) ↔ ne_bot f :=
⟨λ ⟨u, uf⟩, ne_bot_of_le uf, λ h, @exists_ultrafilter_le _ _ h⟩
lemma forall_ne_bot_le_iff {g : filter α} {p : filter α → Prop} (hp : monotone p) :
(∀ f : filter α, ne_bot f → f ≤ g → p f) ↔ ∀ f : ultrafilter α, ↑f ≤ g → p f :=
begin
refine ⟨λ H f hf, H f f.ne_bot hf, _⟩,
introsI H f hf hfg,
exact hp (of_le f) (H _ ((of_le f).trans hfg))
end
section hyperfilter
variables (α) [infinite α]
/-- The ultrafilter extending the cofinite filter. -/
noncomputable def hyperfilter : ultrafilter α := ultrafilter.of cofinite
variable {α}
lemma hyperfilter_le_cofinite : ↑(hyperfilter α) ≤ @cofinite α :=
ultrafilter.of_le cofinite
@[simp] lemma bot_ne_hyperfilter : (⊥ : filter α) ≠ hyperfilter α :=
(by apply_instance : ne_bot ↑(hyperfilter α)).1.symm
theorem nmem_hyperfilter_of_finite {s : set α} (hf : s.finite) : s ∉ hyperfilter α :=
λ hy, compl_not_mem hy $ hyperfilter_le_cofinite hf.compl_mem_cofinite
alias nmem_hyperfilter_of_finite ← set.finite.nmem_hyperfilter
theorem compl_mem_hyperfilter_of_finite {s : set α} (hf : set.finite s) :
sᶜ ∈ hyperfilter α :=
compl_mem_iff_not_mem.2 hf.nmem_hyperfilter
alias compl_mem_hyperfilter_of_finite ← set.finite.compl_mem_hyperfilter
theorem mem_hyperfilter_of_finite_compl {s : set α} (hf : set.finite sᶜ) :
s ∈ hyperfilter α :=
compl_compl s ▸ hf.compl_mem_hyperfilter
end hyperfilter
end filter
namespace ultrafilter
open filter
variables {m : α → β} {s : set α} {g : ultrafilter β}
lemma comap_inf_principal_ne_bot_of_image_mem (h : m '' s ∈ g) :
(filter.comap m g ⊓ 𝓟 s).ne_bot :=
filter.comap_inf_principal_ne_bot_of_image_mem g.ne_bot h
/-- Ultrafilter extending the inf of a comapped ultrafilter and a principal ultrafilter. -/
noncomputable def of_comap_inf_principal (h : m '' s ∈ g) : ultrafilter α :=
@of _ (filter.comap m g ⊓ 𝓟 s) (comap_inf_principal_ne_bot_of_image_mem h)
lemma of_comap_inf_principal_mem (h : m '' s ∈ g) : s ∈ of_comap_inf_principal h :=
begin
let f := filter.comap m g ⊓ 𝓟 s,
haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h,
have : s ∈ f := mem_inf_of_right (mem_principal_self s),
exact le_def.mp (of_le _) s this
end
lemma of_comap_inf_principal_eq_of_map (h : m '' s ∈ g) :
(of_comap_inf_principal h).map m = g :=
begin
let f := filter.comap m g ⊓ 𝓟 s,
haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h,
apply eq_of_le,
calc filter.map m (of f) ≤ filter.map m f : map_mono (of_le _)
... ≤ (filter.map m $ filter.comap m g) ⊓ filter.map m (𝓟 s) : map_inf_le
... = (filter.map m $ filter.comap m g) ⊓ (𝓟 $ m '' s) : by rw map_principal
... ≤ g ⊓ (𝓟 $ m '' s) : inf_le_inf_right _ map_comap_le
... = g : inf_of_le_left (le_principal_iff.mpr h)
end
end ultrafilter
|
dba23245fb3c6cca4253ccf992db131cb804b952 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/group_power/identities.lean | 82982c73a74eb08b42b306071219d174281ce804 | [
"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 | 3,307 | lean | /-
Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bryan Gin-ge Chen, Kevin Lacker
-/
import tactic.ring
/-!
# Identities
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains some "named" commutative ring identities.
-/
variables {R : Type*} [comm_ring R]
{a b x₁ x₂ x₃ x₄ x₅ x₆ x₇ x₈ y₁ y₂ y₃ y₄ y₅ y₆ y₇ y₈ n : R}
/--
Brahmagupta-Fibonacci identity or Diophantus identity, see
<https://en.wikipedia.org/wiki/Brahmagupta%E2%80%93Fibonacci_identity>.
This sign choice here corresponds to the signs obtained by multiplying two complex numbers.
-/
theorem sq_add_sq_mul_sq_add_sq :
(x₁^2 + x₂^2) * (y₁^2 + y₂^2) = (x₁*y₁ - x₂*y₂)^2 + (x₁*y₂ + x₂*y₁)^2 :=
by ring
/--
Brahmagupta's identity, see <https://en.wikipedia.org/wiki/Brahmagupta%27s_identity>
-/
theorem sq_add_mul_sq_mul_sq_add_mul_sq :
(x₁^2 + n*x₂^2) * (y₁^2 + n*y₂^2) = (x₁*y₁ - n*x₂*y₂)^2 + n*(x₁*y₂ + x₂*y₁)^2 :=
by ring
/--
Sophie Germain's identity, see <https://www.cut-the-knot.org/blue/SophieGermainIdentity.shtml>.
-/
theorem pow_four_add_four_mul_pow_four : a^4 + 4*b^4 = ((a - b)^2 + b^2) * ((a + b)^2 + b^2) :=
by ring
/--
Sophie Germain's identity, see <https://www.cut-the-knot.org/blue/SophieGermainIdentity.shtml>.
-/
theorem pow_four_add_four_mul_pow_four' :
a^4 + 4*b^4 = (a^2 - 2*a*b + 2*b^2) * (a^2 + 2*a*b + 2*b^2) :=
by ring
/--
Euler's four-square identity, see <https://en.wikipedia.org/wiki/Euler%27s_four-square_identity>.
This sign choice here corresponds to the signs obtained by multiplying two quaternions.
-/
theorem sum_four_sq_mul_sum_four_sq : (x₁^2 + x₂^2 + x₃^2 + x₄^2) * (y₁^2 + y₂^2 + y₃^2 + y₄^2) =
(x₁*y₁ - x₂*y₂ - x₃*y₃ - x₄*y₄)^2 + (x₁*y₂ + x₂*y₁ + x₃*y₄ - x₄*y₃)^2 +
(x₁*y₃ - x₂*y₄ + x₃*y₁ + x₄*y₂)^2 + (x₁*y₄ + x₂*y₃ - x₃*y₂ + x₄*y₁)^2 :=
by ring
/--
Degen's eight squares identity, see <https://en.wikipedia.org/wiki/Degen%27s_eight-square_identity>.
This sign choice here corresponds to the signs obtained by multiplying two octonions.
-/
theorem sum_eight_sq_mul_sum_eight_sq : (x₁^2 + x₂^2 + x₃^2 + x₄^2 + x₅^2 + x₆^2 + x₇^2 + x₈^2) *
(y₁^2 + y₂^2 + y₃^2 + y₄^2 + y₅^2 + y₆^2 + y₇^2 + y₈^2) =
(x₁*y₁ - x₂*y₂ - x₃*y₃ - x₄*y₄ - x₅*y₅ - x₆*y₆ - x₇*y₇ - x₈*y₈)^2 +
(x₁*y₂ + x₂*y₁ + x₃*y₄ - x₄*y₃ + x₅*y₆ - x₆*y₅ - x₇*y₈ + x₈*y₇)^2 +
(x₁*y₃ - x₂*y₄ + x₃*y₁ + x₄*y₂ + x₅*y₇ + x₆*y₈ - x₇*y₅ - x₈*y₆)^2 +
(x₁*y₄ + x₂*y₃ - x₃*y₂ + x₄*y₁ + x₅*y₈ - x₆*y₇ + x₇*y₆ - x₈*y₅)^2 +
(x₁*y₅ - x₂*y₆ - x₃*y₇ - x₄*y₈ + x₅*y₁ + x₆*y₂ + x₇*y₃ + x₈*y₄)^2 +
(x₁*y₆ + x₂*y₅ - x₃*y₈ + x₄*y₇ - x₅*y₂ + x₆*y₁ - x₇*y₄ + x₈*y₃)^2 +
(x₁*y₇ + x₂*y₈ + x₃*y₅ - x₄*y₆ - x₅*y₃ + x₆*y₄ + x₇*y₁ - x₈*y₂)^2 +
(x₁*y₈ - x₂*y₇ + x₃*y₆ + x₄*y₅ - x₅*y₄ - x₆*y₃ + x₇*y₂ + x₈*y₁)^2 :=
by ring
|
9caf2db81427649f703c248e8d4f9252834ff0b6 | 618003631150032a5676f229d13a079ac875ff77 | /src/topology/metric_space/completion.lean | 5e0de9a0096edad3011e539f60b92f356c708f52 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 8,580 | 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
-/
import topology.uniform_space.completion
import topology.metric_space.isometry
/-!
# The completion of a metric space
Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show
here that the uniform space completion of a metric space inherits a metric space structure,
by extending the distance to the completion and checking that it is indeed a distance, and that
it defines the same uniformity as the already defined uniform structure on the completion
-/
open set filter uniform_space uniform_space.completion
noncomputable theory
universes u
variables {α : Type u} [metric_space α]
namespace metric
/-- The distance on the completion is obtained by extending the distance on the original space,
by uniform continuity. -/
instance : has_dist (completion α) :=
⟨completion.extension₂ dist⟩
/-- The new distance is uniformly continuous. -/
protected lemma completion.uniform_continuous_dist :
uniform_continuous (λp:completion α × completion α, dist p.1 p.2) :=
uniform_continuous_extension₂ dist
/-- The new distance is an extension of the original distance. -/
protected lemma completion.dist_eq (x y : α) : dist (x : completion α) y = dist x y :=
completion.extension₂_coe_coe uniform_continuous_dist' _ _
/- Let us check that the new distance satisfies the axioms of a distance, by starting from the
properties on α and extending them to `completion α` by continuity. -/
protected lemma completion.dist_self (x : completion α) : dist x x = 0 :=
begin
apply induction_on x,
{ refine is_closed_eq _ continuous_const,
exact (completion.uniform_continuous_dist.continuous.comp
(continuous.prod_mk continuous_id continuous_id) : _) },
{ assume a,
rw [completion.dist_eq, dist_self] }
end
protected lemma completion.dist_comm (x y : completion α) : dist x y = dist y x :=
begin
apply induction_on₂ x y,
{ refine is_closed_eq completion.uniform_continuous_dist.continuous _,
exact (completion.uniform_continuous_dist.continuous.comp continuous_swap : _) },
{ assume a b,
rw [completion.dist_eq, completion.dist_eq, dist_comm] }
end
protected lemma completion.dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z :=
begin
apply induction_on₃ x y z,
{ refine is_closed_le _ (continuous.add _ _),
{ have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.2)) :=
continuous.prod_mk continuous_fst (continuous.comp continuous_snd continuous_snd),
exact (completion.uniform_continuous_dist.continuous.comp this : _) },
{ have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.1)) :=
continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd),
exact (completion.uniform_continuous_dist.continuous.comp this : _) },
{ have : continuous (λp : completion α × completion α × completion α, (p.2.1, p.2.2)) :=
continuous.prod_mk (continuous_fst.comp continuous_snd)
(continuous.comp continuous_snd continuous_snd),
exact (continuous.comp completion.uniform_continuous_dist.continuous this : _) } },
{ assume a b c,
rw [completion.dist_eq, completion.dist_eq, completion.dist_eq],
exact dist_triangle a b c }
end
/-- Elements of the uniformity (defined generally for completions) can be characterized in terms
of the distance. -/
protected lemma completion.mem_uniformity_dist (s : set (completion α × completion α)) :
s ∈ uniformity (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) :=
begin
split,
{ /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in α is an
entourage, so it contains an ε-neighborhood of the diagonal by definition of the entourages
in metric spaces. Then `t` contains an ε-neighborhood of the diagonal in `completion α`, as
closed properties pass to the completion. -/
assume hs,
rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩,
have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α :=
uniform_continuous_def.1 (uniform_continuous_coe α) t ht,
rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩,
refine ⟨ε, εpos, λx y hxy, _⟩,
have : ε ≤ dist x y ∨ (x, y) ∈ t,
{ apply induction_on₂ x y,
{ have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t}
= {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp,
rw this,
apply is_closed_union _ tclosed,
exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous },
{ assume x y,
rw completion.dist_eq,
by_cases h : ε ≤ dist x y,
{ exact or.inl h },
{ have Z := hε (not_le.1 h),
simp only [set.mem_set_of_eq] at Z,
exact or.inr Z }}},
simp only [not_le.mpr hxy, false_or, not_le] at this,
exact ts this },
{ /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show
that it is an entourage, we use the fact that `dist` is uniformly continuous on
`completion α × completion α` (this is a general property of the extension of uniformly
continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ
is an entourage in `completion α × completion α`. Massaging this property, it follows that
the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is
also the case of `s`. -/
rintros ⟨ε, εpos, hε⟩,
let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε},
have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos,
have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this,
simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop,
filter.mem_map, set.mem_set_of_eq] at T,
rcases T with ⟨t1, ht1, t2, ht2, ht⟩,
refine mem_sets_of_superset ht1 _,
have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε,
{ assume a b hab,
have : ((a, b), (a, a)) ∈ set.prod t1 t2 := ⟨hab, refl_mem_uniformity ht2⟩,
have I := ht this,
simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I,
exact lt_of_le_of_lt (le_abs_self _) I },
show t1 ⊆ s,
{ rintros ⟨a, b⟩ hp,
have : dist a b < ε := A a b hp,
exact hε this }}
end
/-- If two points are at distance 0, then they coincide. -/
protected lemma completion.eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y :=
begin
/- This follows from the separation of `completion α` and from the description of
entourages in terms of the distance. -/
have : separated (completion α) := by apply_instance,
refine separated_def.1 this x y (λs hs, _),
rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩,
rw ← h at εpos,
exact hε εpos
end
/- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition
of the metric space structure. -/
protected lemma completion.uniformity_dist' :
uniformity (completion α) = (⨅ε:{ε:ℝ // ε>0}, principal {p | dist p.1 p.2 < ε.val}) :=
begin
ext s, rw mem_infi,
{ simp [completion.mem_uniformity_dist, subset_def] },
{ rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩,
simp [lt_min_iff, (≥)] {contextual := tt} },
{ exact ⟨⟨1, zero_lt_one⟩⟩ }
end
protected lemma completion.uniformity_dist :
uniformity (completion α) = (⨅ ε>0, principal {p | dist p.1 p.2 < ε}) :=
by simpa [infi_subtype] using @completion.uniformity_dist' α _
/-- Metric space structure on the completion of a metric space. -/
instance completion.metric_space : metric_space (completion α) :=
{ dist_self := completion.dist_self,
eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero,
dist_comm := completion.dist_comm,
dist_triangle := completion.dist_triangle,
to_uniform_space := by apply_instance,
uniformity_dist := completion.uniformity_dist }
/-- The embedding of a metric space in its completion is an isometry. -/
lemma completion.coe_isometry : isometry (coe : α → completion α) :=
isometry_emetric_iff_metric.2 completion.dist_eq
end metric
|
31252f7a17c3fd6dba151b6dff196638a85545d7 | ac2987d8c7832fb4a87edb6bee26141facbb6fa0 | /Mathlib.lean | a20ccfe0e7d1b9153e5a09664c59d544e172b616 | [
"Apache-2.0"
] | permissive | AurelienSaue/mathlib4 | 52204b9bd9d207c922fe0cf3397166728bb6c2e2 | 84271fe0875bafdaa88ac41f1b5a7c18151bd0d5 | refs/heads/master | 1,689,156,096,545 | 1,629,378,840,000 | 1,629,378,840,000 | 389,648,603 | 0 | 0 | Apache-2.0 | 1,627,307,284,000 | 1,627,307,284,000 | null | UTF-8 | Lean | false | false | 1,175 | lean | import Mathlib.Algebra.Group.Basic
import Mathlib.Algebra.Group.Defs
import Mathlib.Algebra.GroupWithZero.Defs
import Mathlib.Algebra.Ring.Basic
import Mathlib.Data.Array.Basic
import Mathlib.Data.ByteArray
import Mathlib.Data.Char
import Mathlib.Data.Equiv.Basic
import Mathlib.Data.Equiv.Functor
import Mathlib.Data.Int.Basic
import Mathlib.Data.List.Basic
import Mathlib.Data.List.Card
import Mathlib.Data.Nat.Basic
import Mathlib.Data.Nat.Gcd
import Mathlib.Data.Prod
import Mathlib.Data.Subtype
import Mathlib.Data.UInt
import Mathlib.Dvd
import Mathlib.Function
import Mathlib.Init.Algebra.Order
import Mathlib.Init.Logic
import Mathlib.Logic.Basic
import Mathlib.Logic.Function.Basic
import Mathlib.Set
import Mathlib.SetNotation
import Mathlib.Tactic.Basic
import Mathlib.Tactic.Block
import Mathlib.Tactic.Coe
import Mathlib.Tactic.Core
import Mathlib.Tactic.NoMatch
import Mathlib.Tactic.NormNum
import Mathlib.Tactic.OpenPrivate
import Mathlib.Tactic.PrintPrefix
import Mathlib.Tactic.Ring
import Mathlib.Tactic.RunTac
import Mathlib.Tactic.Split
import Mathlib.Tactic.Spread
import Mathlib.Tactic.SudoSetOption
import Mathlib.Util.Export
import Mathlib.Util.Time
|
17797810468ac82f7e0e9cfa031255d2492e76bd | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/ring_theory/integral_closure.lean | 8aba99fae32f52d340e03b50626acba97e7f0be7 | [
"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 | 25,835 | lean | /-
Copyright (c) 2019 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.adjoin.basic
import ring_theory.polynomial.scale_roots
import ring_theory.polynomial.tower
/-!
# Integral closure of a subring.
If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial
with coefficients in R. Enough theory is developed to prove that integral elements
form a sub-R-algebra of A.
## Main definitions
Let `R` be a `comm_ring` and let `A` be an R-algebra.
* `ring_hom.is_integral_elem (f : R →+* A) (x : A)` : `x` is integral with respect to the map `f`,
* `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with
coefficients in `R`.
* `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`.
-/
open_locale classical
open_locale big_operators
open polynomial submodule
section ring
variables {R S A : Type*}
variables [comm_ring R] [ring A] [ring S] (f : R →+* S)
/-- An element `x` of `A` is said to be integral over `R` with respect to `f`
if it is a root of a monic polynomial `p : polynomial R` evaluated under `f` -/
def ring_hom.is_integral_elem (f : R →+* A) (x : A) :=
∃ p : polynomial R, monic p ∧ eval₂ f x p = 0
/-- A ring homomorphism `f : R →+* A` is said to be integral
if every element `A` is integral with respect to the map `f` -/
def ring_hom.is_integral (f : R →+* A) :=
∀ x : A, f.is_integral_elem x
variables [algebra R A] (R)
/-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*,
if it is a root of some monic polynomial `p : polynomial R`.
Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/
def is_integral (x : A) : Prop :=
(algebra_map R A).is_integral_elem x
variable (A)
/-- An algebra is integral if every element of the extension is integral over the base ring -/
def algebra.is_integral : Prop :=
(algebra_map R A).is_integral
variables {R A}
lemma ring_hom.is_integral_map {x : R} : f.is_integral_elem (f x) :=
⟨X - C x, monic_X_sub_C _, by simp⟩
theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) :=
(algebra_map R A).is_integral_map
theorem is_integral_of_noetherian (H : is_noetherian R A) (x : A) :
is_integral R x :=
begin
let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval x).to_linear_map,
let D : ℕ → submodule R A := λ n, (degree_le R n).map leval,
let M := well_founded.min (is_noetherian_iff_well_founded.1 H)
(set.range D) ⟨_, ⟨0, rfl⟩⟩,
have HM : M ∈ set.range D := well_founded.min_mem _ _ _,
cases HM with N HN,
have HM : ¬M < D (N+1) := well_founded.not_lt_min
(is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩,
rw ← HN at HM,
have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM
(lt_of_le_not_le (map_mono (degree_le_mono
(with_bot.coe_le_coe.2 (nat.le_succ N)))) H)),
have HN3 : leval (X^(N+1)) ∈ D N,
{ exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) },
rcases HN3 with ⟨p, hdp, hpe⟩,
refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩,
show leval (X ^ (N + 1) - p) = 0,
rw [linear_map.map_sub, hpe, sub_self]
end
theorem is_integral_of_submodule_noetherian (S : subalgebra R A)
(H : is_noetherian R S.to_submodule) (x : A) (hx : x ∈ S) :
is_integral R x :=
begin
suffices : is_integral R (show S, from ⟨x, hx⟩),
{ rcases this with ⟨p, hpm, hpx⟩,
replace hpx := congr_arg S.val hpx,
refine ⟨p, hpm, eq.trans _ hpx⟩,
simp only [aeval_def, eval₂, sum_def],
rw S.val.map_sum,
refine finset.sum_congr rfl (λ n hn, _),
rw [S.val.map_mul, S.val.map_pow, S.val.commutes, S.val_apply, subtype.coe_mk], },
refine is_integral_of_noetherian H ⟨x, hx⟩
end
end ring
section
variables {R A B S : Type*}
variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S]
variables [algebra R A] [algebra R B] (f : R →+* S)
theorem is_integral_alg_hom (f : A →ₐ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) :=
let ⟨p, hp, hpx⟩ :=
hx in ⟨p, hp, by rw [← aeval_def, aeval_alg_hom_apply, aeval_def, hpx, f.map_zero]⟩
theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B]
(x : B) (hx : is_integral R x) : is_integral A x :=
let ⟨p, hp, hpx⟩ := hx in
⟨p.map $ algebra_map R A, monic_map _ hp,
by rw [← aeval_def, ← is_scalar_tower.aeval_apply, aeval_def, hpx]⟩
section
local attribute [instance] subset.comm_ring algebra.of_is_subring
theorem is_integral_of_subring {x : A} (T : set R) [is_subring T]
(hx : is_integral T x) : is_integral R x :=
is_integral_of_is_scalar_tower x hx
lemma is_integral_algebra_map_iff [algebra A B] [is_scalar_tower R A B]
{x : A} (hAB : function.injective (algebra_map A B)) :
is_integral R (algebra_map A B x) ↔ is_integral R x :=
begin
split; rintros ⟨f, hf, hx⟩; use [f, hf],
{ exact is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero R A B hAB hx },
{ rw [is_scalar_tower.algebra_map_eq R A B, ← hom_eval₂, hx, ring_hom.map_zero] }
end
theorem is_integral_iff_is_integral_closure_finite {r : A} :
is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (ring.closure s) r :=
begin
split; intro hr,
{ rcases hr with ⟨p, hmp, hpr⟩,
refine ⟨_, set.finite_mem_finset _, p.restriction, monic_restriction.2 hmp, _⟩,
erw [← aeval_def, is_scalar_tower.aeval_apply _ R, map_restriction, aeval_def, hpr] },
rcases hr with ⟨s, hs, hsr⟩,
exact is_integral_of_subring _ hsr
end
end
theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) :
(algebra.adjoin R ({x} : set A)).to_submodule.fg :=
begin
rcases hx with ⟨f, hfm, hfx⟩,
existsi finset.image ((^) x) (finset.range (nat_degree f + 1)),
apply le_antisymm,
{ rw span_le, intros s hs, rw finset.mem_coe at hs,
rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk,
exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) },
intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr,
rw algebra.adjoin_singleton_eq_range at hr,
rcases (aeval x).mem_range.mp hr with ⟨p, rfl⟩,
rw ← mod_by_monic_add_div p hfm,
rw ← aeval_def at hfx,
rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero],
have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm,
generalize_hyp : p %ₘ f = q at this ⊢,
rw [← sum_C_mul_X_eq q, aeval_def, eval₂_sum, sum_def],
refine sum_mem _ (λ k hkq, _),
rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def],
refine smul_mem _ _ (subset_span _),
rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩,
rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _),
rw [degree_le_iff_coeff_zero] at this,
rw [mem_support_iff] at hkq, apply hkq, apply this,
exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk)
end
theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite)
(his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s).to_submodule.fg :=
set.finite.induction_on hfs (λ _, ⟨{1}, submodule.ext $ λ x,
by { erw [algebra.adjoin_empty, finset.coe_singleton, ← one_eq_span, one_eq_map_top,
map_top, linear_map.mem_range, algebra.mem_bot], refl }⟩)
(λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact
fg_mul _ _ (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi)
(fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his
theorem is_integral_of_mem_of_fg (S : subalgebra R A)
(HS : S.to_submodule.fg) (x : A) (hx : x ∈ S) : is_integral R x :=
begin
cases HS with y hy,
obtain ⟨lx, hlx1, hlx2⟩ :
∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x,
{ rwa [←(@finsupp.mem_span_image_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] },
have hyS : ∀ {p}, p ∈ y → p ∈ S := λ p hp, show p ∈ S.to_submodule,
by { rw ← hy, exact subset_span hp },
have : ∀ (jk : (↑(y.product y) : set (A × A))), jk.1.1 * jk.1.2 ∈ S.to_submodule :=
λ jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2),
rw [← hy, ← set.image_id ↑y] at this, simp only [finsupp.mem_span_image_iff_total] at this,
choose ly hly1 hly2,
let S₀ : set R := ring.closure ↑(lx.frange ∪ finset.bUnion finset.univ (finsupp.frange ∘ ly)),
refine is_integral_of_subring S₀ _,
letI : comm_ring S₀ := @subtype.comm_ring _ _ _ ring.closure.is_subring,
letI : algebra S₀ A := algebra.of_is_subring _,
have :
span S₀ (insert 1 ↑y : set A) * span S₀ (insert 1 ↑y : set A) ≤ span S₀ (insert 1 ↑y : set A),
{ rw span_mul_span, refine span_le.2 (λ z hz, _),
rcases set.mem_mul.1 hz with ⟨p, q, rfl | hp, hq, rfl⟩,
{ rw one_mul, exact subset_span hq },
rcases hq with rfl | hq,
{ rw mul_one, exact subset_span (or.inr hp) },
erw ← hly2 ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩,
rw [finsupp.total_apply, finsupp.sum],
refine (span S₀ (insert 1 ↑y : set A)).sum_mem (λ t ht, _),
have : ly ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩ t ∈ S₀ :=
ring.subset_closure (finset.mem_union_right _ $ finset.mem_bUnion.2
⟨⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, finset.mem_univ _,
finsupp.mem_frange.2 ⟨finsupp.mem_support_iff.1 ht, _, rfl⟩⟩),
change (⟨_, this⟩ : S₀) • t ∈ _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) },
haveI : is_subring (span S₀ (insert 1 ↑y : set A) : set A) :=
{ one_mem := subset_span $ or.inl rfl,
mul_mem := λ p q hp hq, this $ mul_mem_mul hp hq,
zero_mem := (span S₀ (insert 1 ↑y : set A)).zero_mem,
add_mem := λ _ _, (span S₀ (insert 1 ↑y : set A)).add_mem,
neg_mem := λ _, (span S₀ (insert 1 ↑y : set A)).neg_mem },
have : span S₀ (insert 1 ↑y : set A) = (algebra.adjoin S₀ (↑y : set A)).to_submodule,
{ refine le_antisymm (span_le.2 $ set.insert_subset.2
⟨(algebra.adjoin S₀ ↑y).one_mem, algebra.subset_adjoin⟩) (λ z hz, _),
rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, rw ← set_like.mem_coe,
refine ring.closure_subset (set.union_subset (set.range_subset_iff.2 $ λ t, _)
(λ t ht, subset_span $ or.inr ht)) hz,
rw algebra.algebra_map_eq_smul_one,
exact smul_mem (span S₀ (insert 1 ↑y : set A)) _ (subset_span $ or.inl rfl) },
haveI : is_noetherian_ring ↥S₀ := is_noetherian_ring_closure _ (finset.finite_to_set _),
refine is_integral_of_submodule_noetherian (algebra.adjoin S₀ ↑y)
(is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by rw [finset.coe_insert, this]⟩) _ _,
rw [← hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (λ r hr, _),
have : lx r ∈ S₀ := ring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)),
change (⟨_, this⟩ : S₀) • r ∈ _,
rw finsupp.mem_supported at hlx1,
exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _
end
lemma ring_hom.is_integral_of_mem_closure {x y z : S}
(hx : f.is_integral_elem x) (hy : f.is_integral_elem y)
(hz : z ∈ ring.closure ({x, y} : set S)) :
f.is_integral_elem z :=
begin
letI : algebra R S := f.to_algebra,
have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy),
rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this,
exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z
(algebra.mem_adjoin_iff.2 $ ring.closure_mono (set.subset_union_right _ _) hz),
end
theorem is_integral_of_mem_closure {x y z : A}
(hx : is_integral R x) (hy : is_integral R y)
(hz : z ∈ ring.closure ({x, y} : set A)) :
is_integral R z :=
(algebra_map R A).is_integral_of_mem_closure hx hy hz
lemma ring_hom.is_integral_zero : f.is_integral_elem 0 :=
f.map_zero ▸ f.is_integral_map
theorem is_integral_zero : is_integral R (0:A) :=
(algebra_map R A).is_integral_zero
lemma ring_hom.is_integral_one : f.is_integral_elem 1 :=
f.map_one ▸ f.is_integral_map
theorem is_integral_one : is_integral R (1:A) :=
(algebra_map R A).is_integral_one
lemma ring_hom.is_integral_add {x y : S}
(hx : f.is_integral_elem x) (hy : f.is_integral_elem y) :
f.is_integral_elem (x + y) :=
f.is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem
(ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl)))
theorem is_integral_add {x y : A}
(hx : is_integral R x) (hy : is_integral R y) :
is_integral R (x + y) :=
(algebra_map R A).is_integral_add hx hy
lemma ring_hom.is_integral_neg {x : S}
(hx : f.is_integral_elem x) : f.is_integral_elem (-x) :=
f.is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem
(ring.subset_closure (or.inl rfl)))
theorem is_integral_neg {x : A}
(hx : is_integral R x) : is_integral R (-x) :=
(algebra_map R A).is_integral_neg hx
lemma ring_hom.is_integral_sub {x y : S}
(hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x - y) :=
by simpa only [sub_eq_add_neg] using f.is_integral_add hx (f.is_integral_neg hy)
theorem is_integral_sub {x y : A}
(hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) :=
(algebra_map R A).is_integral_sub hx hy
lemma ring_hom.is_integral_mul {x y : S}
(hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x * y) :=
f.is_integral_of_mem_closure hx hy (is_submonoid.mul_mem
(ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl)))
theorem is_integral_mul {x y : A}
(hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) :=
(algebra_map R A).is_integral_mul hx hy
variables (R A)
/-- The integral closure of R in an R-algebra A. -/
def integral_closure : subalgebra R A :=
{ carrier := { r | is_integral R r },
zero_mem' := is_integral_zero,
one_mem' := is_integral_one,
add_mem' := λ _ _, is_integral_add,
mul_mem' := λ _ _, is_integral_mul,
algebra_map_mem' := λ x, is_integral_algebra_map }
theorem mem_integral_closure_iff_mem_fg {r : A} :
r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, M.to_submodule.fg ∧ r ∈ M :=
⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩,
λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩
variables {R} {A}
/-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/
lemma integral_closure_map_alg_equiv (f : A ≃ₐ[R] B) :
(integral_closure R A).map (f : A →ₐ[R] B) = integral_closure R B :=
begin
ext y,
rw subalgebra.mem_map,
split,
{ rintros ⟨x, hx, rfl⟩,
exact is_integral_alg_hom f hx },
{ intro hy,
use [f.symm y, is_integral_alg_hom (f.symm : B →ₐ[R] A) hy],
simp }
end
lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x :=
let ⟨p, hpm, hpx⟩ := x.2 in ⟨p, hpm, subtype.eq $
by rwa [← aeval_def, subtype.val_eq_coe, ← subalgebra.val_apply, aeval_alg_hom_apply] at hpx⟩
lemma ring_hom.is_integral_of_is_integral_mul_unit (x y : S) (r : R) (hr : f r * y = 1)
(hx : f.is_integral_elem (x * y)) : f.is_integral_elem x :=
begin
obtain ⟨p, ⟨p_monic, hp⟩⟩ := hx,
refine ⟨scale_roots p r, ⟨(monic_scale_roots_iff r).2 p_monic, _⟩⟩,
convert scale_roots_eval₂_eq_zero f hp,
rw [mul_comm x y, ← mul_assoc, hr, one_mul],
end
theorem is_integral_of_is_integral_mul_unit {x y : A} {r : R} (hr : algebra_map R A r * y = 1)
(hx : is_integral R (x * y)) : is_integral R x :=
(algebra_map R A).is_integral_of_is_integral_mul_unit x y r hr hx
/-- Generalization of `is_integral_of_mem_closure` bootstrapped up from that lemma -/
lemma is_integral_of_mem_closure' (G : set A) (hG : ∀ x ∈ G, is_integral R x) :
∀ x ∈ (subring.closure G), is_integral R x :=
λ x hx, subring.closure_induction hx hG is_integral_zero is_integral_one
(λ _ _, is_integral_add) (λ _, is_integral_neg) (λ _ _, is_integral_mul)
lemma is_integral_of_mem_closure'' {S : Type*} [comm_ring S] {f : R →+* S} (G : set S)
(hG : ∀ x ∈ G, f.is_integral_elem x) : ∀ x ∈ (subring.closure G), f.is_integral_elem x :=
λ x hx, @is_integral_of_mem_closure' R S _ _ f.to_algebra G hG x hx
end
section algebra
open algebra
variables {R A B S T : Type*}
variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S] [comm_ring T]
variables [algebra A B] [algebra R B] (f : R →+* S) (g : S →+* T)
lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval x p = 0) :
is_integral (adjoin R (↑(p.map $ algebra_map A B).frange : set B)) x :=
begin
generalize hS : (↑(p.map $ algebra_map A B).frange : set B) = S,
have coeffs_mem : ∀ i, (p.map $ algebra_map A B).coeff i ∈ adjoin R S,
{ intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0,
{ rw hi, exact subalgebra.zero_mem _ },
rw ← hS,
exact subset_adjoin (coeff_mem_frange _ _ hi) },
obtain ⟨q, hq⟩ : ∃ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) B) =
(p.map $ algebra_map A B),
{ rw ← set.mem_range, exact (polynomial.mem_map_range _).2 (λ i, ⟨⟨_, coeffs_mem i⟩, rfl⟩) },
use q,
split,
{ suffices h : (q.map (algebra_map (adjoin R S) B)).monic,
{ refine monic_of_injective _ h,
exact subtype.val_injective },
{ rw hq, exact monic_map _ pmonic } },
{ convert hp using 1,
replace hq := congr_arg (eval x) hq,
convert hq using 1; symmetry; apply eval_map },
end
variables [algebra R A] [is_scalar_tower R A B]
/-- If A is an R-algebra all of whose elements are integral over R,
and x is an element of an A-algebra that is integral over A, then x is integral over R.-/
lemma is_integral_trans (A_int : is_integral R A) (x : B) (hx : is_integral A x) :
is_integral R x :=
begin
rcases hx with ⟨p, pmonic, hp⟩,
let S : set B := ↑(p.map $ algebra_map A B).frange,
refine is_integral_of_mem_of_fg (adjoin R (S ∪ {x})) _ _ (subset_adjoin $ or.inr rfl),
refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (λ x hx, _)) _,
{ rw [finset.mem_coe, frange, finset.mem_image] at hx,
rcases hx with ⟨i, _, rfl⟩,
rw coeff_map,
exact is_integral_alg_hom (is_scalar_tower.to_alg_hom R A B) (A_int _) },
{ apply fg_adjoin_singleton_of_integral,
exact is_integral_trans_aux _ pmonic hp }
end
/-- If A is an R-algebra all of whose elements are integral over R,
and B is an A-algebra all of whose elements are integral over A,
then all elements of B are integral over R.-/
lemma algebra.is_integral_trans (hA : is_integral R A) (hB : is_integral A B) : is_integral R B :=
λ x, is_integral_trans hA x (hB x)
lemma ring_hom.is_integral_trans (hf : f.is_integral) (hg : g.is_integral) :
(g.comp f).is_integral :=
@algebra.is_integral_trans R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra
(@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra
(ring_hom.comp_apply g f)) hf hg
lemma ring_hom.is_integral_of_surjective (hf : function.surjective f) : f.is_integral :=
λ x, (hf x).rec_on (λ y hy, (hy ▸ f.is_integral_map : f.is_integral_elem x))
lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : is_integral R A :=
(algebra_map R A).is_integral_of_surjective h
/-- If `R → A → B` is an algebra tower with `A → B` injective,
then if the entire tower is an integral extension so is `R → A` -/
lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B))
{x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x :=
begin
rcases h with ⟨p, ⟨hp, hp'⟩⟩,
refine ⟨p, ⟨hp, _⟩⟩,
rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map,
eval₂_hom, ← ring_hom.map_zero (algebra_map A B)] at hp',
rw [eval₂_eq_eval_map],
exact H hp',
end
lemma ring_hom.is_integral_tower_bot_of_is_integral (hg : function.injective g)
(hfg : (g.comp f).is_integral) : f.is_integral :=
λ x,
@is_integral_tower_bot_of_is_integral R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra
(@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra
(ring_hom.comp_apply g f)) hg x (hfg (g x))
lemma is_integral_tower_bot_of_is_integral_field {R A B : Type*} [comm_ring R] [field A]
[comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B]
{x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x :=
is_integral_tower_bot_of_is_integral (algebra_map A B).injective h
lemma ring_hom.is_integral_elem_of_is_integral_elem_comp {x : T}
(h : (g.comp f).is_integral_elem x) : g.is_integral_elem x :=
let ⟨p, ⟨hp, hp'⟩⟩ := h in ⟨p.map f, monic_map f hp, by rwa ← eval₂_map at hp'⟩
lemma ring_hom.is_integral_tower_top_of_is_integral (h : (g.comp f).is_integral) : g.is_integral :=
λ x, ring_hom.is_integral_elem_of_is_integral_elem_comp f g (h x)
/-- If `R → A → B` is an algebra tower,
then if the entire tower is an integral extension so is `A → B`. -/
lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x :=
begin
rcases h with ⟨p, ⟨hp, hp'⟩⟩,
refine ⟨p.map (algebra_map R A), ⟨monic_map (algebra_map R A) hp, _⟩⟩,
rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map] at hp',
exact hp',
end
lemma ring_hom.is_integral_quotient_of_is_integral {I : ideal S} (hf : f.is_integral) :
(ideal.quotient_map I f le_rfl).is_integral :=
begin
rintros ⟨x⟩,
obtain ⟨p, ⟨p_monic, hpx⟩⟩ := hf x,
refine ⟨p.map (ideal.quotient.mk _), ⟨monic_map _ p_monic, _⟩⟩,
simpa only [hom_eval₂, eval₂_map] using congr_arg (ideal.quotient.mk I) hpx
end
lemma is_integral_quotient_of_is_integral {I : ideal A} (hRA : is_integral R A) :
is_integral (I.comap (algebra_map R A)).quotient I.quotient :=
(algebra_map R A).is_integral_quotient_of_is_integral hRA
lemma is_integral_quotient_map_iff {I : ideal S} :
(ideal.quotient_map I f le_rfl).is_integral ↔
((ideal.quotient.mk I).comp f : R →+* I.quotient).is_integral :=
begin
let g := ideal.quotient.mk (I.comap f),
have := ideal.quotient_map_comp_mk le_rfl,
refine ⟨λ h, _, λ h, ring_hom.is_integral_tower_top_of_is_integral g _ (this ▸ h)⟩,
refine this ▸ ring_hom.is_integral_trans g (ideal.quotient_map I f le_rfl) _ h,
exact ring_hom.is_integral_of_surjective g ideal.quotient.mk_surjective,
end
/-- If the integral extension `R → S` is injective, and `S` is a field, then `R` is also a field. -/
lemma is_field_of_is_integral_of_is_field {R S : Type*} [integral_domain R] [integral_domain S]
[algebra R S] (H : is_integral R S) (hRS : function.injective (algebra_map R S))
(hS : is_field S) : is_field R :=
begin
refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, λ a ha, _⟩,
-- Let `a_inv` be the inverse of `algebra_map R S a`,
-- then we need to show that `a_inv` is of the form `algebra_map R S b`.
obtain ⟨a_inv, ha_inv⟩ := hS.mul_inv_cancel (λ h, ha (hRS (trans h (ring_hom.map_zero _).symm))),
-- Let `p : polynomial R` be monic with root `a_inv`,
-- and `q` be `p` with coefficients reversed (so `q(a) = q'(a) * a + 1`).
-- We claim that `q(a) = 0`, so `-q'(a)` is the inverse of `a`.
obtain ⟨p, p_monic, hp⟩ := H a_inv,
use -∑ (i : ℕ) in finset.range p.nat_degree, (p.coeff i) * a ^ (p.nat_degree - i - 1),
-- `q(a) = 0`, because multiplying everything with `a_inv^n` gives `p(a_inv) = 0`.
-- TODO: this could be a lemma for `polynomial.reverse`.
have hq : ∑ (i : ℕ) in finset.range (p.nat_degree + 1), (p.coeff i) * a ^ (p.nat_degree - i) = 0,
{ apply (algebra_map R S).injective_iff.mp hRS,
have a_inv_ne_zero : a_inv ≠ 0 := right_ne_zero_of_mul (mt ha_inv.symm.trans one_ne_zero),
refine (mul_eq_zero.mp _).resolve_right (pow_ne_zero p.nat_degree a_inv_ne_zero),
rw [eval₂_eq_sum_range] at hp,
rw [ring_hom.map_sum, finset.sum_mul],
refine (finset.sum_congr rfl (λ i hi, _)).trans hp,
rw [ring_hom.map_mul, mul_assoc],
congr,
have : a_inv ^ p.nat_degree = a_inv ^ (p.nat_degree - i) * a_inv ^ i,
{ rw [← pow_add a_inv, nat.sub_add_cancel (nat.le_of_lt_succ (finset.mem_range.mp hi))] },
rw [ring_hom.map_pow, this, ← mul_assoc, ← mul_pow, ha_inv, one_pow, one_mul] },
-- Since `q(a) = 0` and `q(a) = q'(a) * a + 1`, we have `a * -q'(a) = 1`.
-- TODO: we could use a lemma for `polynomial.div_X` here.
rw [finset.sum_range_succ_comm, p_monic.coeff_nat_degree, one_mul, nat.sub_self, pow_zero,
add_eq_zero_iff_eq_neg, eq_comm] at hq,
rw [mul_comm, ← neg_mul_eq_neg_mul, finset.sum_mul],
convert hq using 2,
refine finset.sum_congr rfl (λ i hi, _),
have : 1 ≤ p.nat_degree - i := nat.le_sub_left_of_add_le (finset.mem_range.mp hi),
rw [mul_assoc, ← pow_succ', nat.sub_add_cancel this]
end
end algebra
section
local attribute [instance] subset.comm_ring algebra.of_is_subring
theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] :
integral_closure (integral_closure R A : set A) A = ⊥ :=
eq_bot_iff.2 $ λ x hx, algebra.mem_bot.2
⟨⟨x, @is_integral_trans _ _ _ _ _ _ _ _ (integral_closure R A).algebra
_ integral_closure.is_integral x hx⟩, rfl⟩
end
section integral_domain
variables {R S : Type*} [comm_ring R] [integral_domain S] [algebra R S]
instance : integral_domain (integral_closure R S) :=
infer_instance
end integral_domain
|
990106c6aa62fa9bac4f77017831e0ed6214e243 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/function/special_functions/arctan.lean | 8817055039e83d3fa2789955bd8c34a6134d3248 | [
"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 | 664 | 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.special_functions.trigonometric.arctan
import measure_theory.constructions.borel_space
/-!
# Measurability of arctan
-/
namespace real
@[measurability] lemma measurable_arctan : measurable arctan := continuous_arctan.measurable
end real
section real_composition
open real
variables {α : Type*} {m : measurable_space α} {f : α → ℝ} (hf : measurable f)
@[measurability] lemma measurable.arctan : measurable (λ x, arctan (f x)) :=
measurable_arctan.comp hf
end real_composition
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.