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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
257bfc1ff7865c2d87fad1845ceb8032f2cf2b86 | 32da3d0f92cab08875472ef6cacc1931c2b3eafa | /src/linear_algebra/determinant.lean | 1689aa6bfc0ccdfa2be0f92109f4326bc213cfc3 | [
"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 | 12,676 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes, Tim Baanen
-/
import data.matrix.pequiv
import data.fintype.card
import group_theory.perm.sign
import algebra.algebra.basic
import tactic.ring
import linear_algebra.alternating
universes u v w z
open equiv equiv.perm finset function
namespace matrix
open_locale matrix big_operators
variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R]
local notation `ε` σ:max := ((sign σ : ℤ ) : R)
/-- The determinant of a matrix given by the Leibniz formula. -/
definition det (M : matrix n n R) : R :=
∑ σ : perm n, ε σ * ∏ i, M (σ i) i
@[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i :=
begin
refine (finset.sum_eq_single 1 _ _).trans _,
{ intros σ h1 h2,
cases not_forall.1 (mt equiv.ext h2) with x h3,
convert mul_zero _,
apply finset.prod_eq_zero,
{ change x ∈ _, simp },
exact if_neg h3 },
{ simp },
{ simp }
end
@[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 :=
by rw [← diagonal_zero, det_diagonal, finset.prod_const, ← fintype.card,
zero_pow (fintype.card_pos_iff.2 h)]
@[simp] lemma det_one : det (1 : matrix n n R) = 1 :=
by rw [← diagonal_one]; simp [-diagonal_one]
lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 :=
begin
have perm_eq : (univ : finset (perm n)) = {1} :=
univ_eq_singleton_of_card_one (1 : perm n) (by simp [card_univ, fintype.card_perm, h]),
simp [det, card_eq_zero.mp h, perm_eq],
end
lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) :
∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 :=
begin
obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j,
{ rw [← fintype.injective_iff_bijective, injective] at H,
push_neg at H,
exact H },
exact sum_involution
(λ σ _, σ * swap i j)
(λ σ _,
have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x),
from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _)
(by simp [apply_swap_eq_self hpij])
(λ _ _ _ _ h, (swap i j).injective h)
(λ b _, ⟨swap i j b, mem_univ _, by simp⟩),
by simp [sign_mul, this, sign_swap hij, prod_mul_distrib])
(λ σ _ _, (not_congr mul_swap_eq_iff).mpr hij)
(λ _ _, mem_univ _)
(λ σ _, mul_swap_involutive i j σ)
end
@[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N :=
calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
by simp only [det, mul_apply, prod_univ_sum, mul_sum,
fintype.pi_finset_univ]; rw [finset.sum_comm]
... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n,
ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
eq.symm $ sum_subset (filter_subset _ _)
(λ f _ hbij, det_mul_aux $ by simpa using hbij)
... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) :
sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _)
(λ _ _, rfl) (λ _ _ _ _ h, by injection h)
(λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, injective_coe_fn rfl⟩)
... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) :
by simp [mul_sum, det, mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc]
... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) :
sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _)
(λ τ _,
have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j,
by rw ← σ⁻¹.prod_comp; simp [mul_apply],
have h : ε σ * ε (τ * σ⁻¹) = ε τ :=
calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) :
by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp [sign_mul]
... = ε τ : by simp,
by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm])
(λ _ _ _ _, mul_right_cancel) (λ τ _, ⟨τ * σ, by simp⟩))
... = det M * det N : by simp [det, mul_assoc, mul_sum, mul_comm, mul_left_comm]
instance : is_monoid_hom (det : matrix n n R → R) :=
{ map_one := det_one,
map_mul := det_mul }
/-- Transposing a matrix preserves the determinant. -/
@[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det :=
begin
apply sum_bij (λ σ _, σ⁻¹),
{ intros σ _, apply mem_univ },
{ intros σ _,
rw [sign_inv],
congr' 1,
apply prod_bij (λ i _, σ i),
{ intros i _, apply mem_univ },
{ intros i _, simp },
{ intros i j _ _ h, simp at h, assumption },
{ intros i _, use σ⁻¹ i, finish } },
{ intros σ σ' _ _ h, simp at h, assumption },
{ intros σ _, use σ⁻¹, finish }
end
/-- The determinant of a permutation matrix equals its sign. -/
@[simp] lemma det_permutation (σ : perm n) :
matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign :=
begin
suffices : matrix.det (σ.to_pequiv.to_matrix) = ↑σ.sign * det (1 : matrix n n R), { simp [this] },
unfold det,
rw mul_sum,
apply sum_bij (λ τ _, σ * τ),
{ intros τ _, apply mem_univ },
{ intros τ _,
rw [←mul_assoc, sign_mul, coe_coe, ←int.cast_mul, ←units.coe_mul, ←mul_assoc,
int.units_mul_self, one_mul],
congr,
ext i,
apply pequiv.equiv_to_pequiv_to_matrix },
{ intros τ τ' _ _, exact (mul_right_inj σ).mp },
{ intros τ _, use σ⁻¹ * τ, use (mem_univ _), exact (mul_inv_cancel_left _ _).symm }
end
/-- Permuting the columns changes the sign of the determinant. -/
lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det :=
by rw [←det_permutation, ←det_mul, pequiv.to_pequiv_mul_matrix]
@[simp] lemma det_smul {A : matrix n n R} {c : R} : det (c • A) = c ^ fintype.card n * det A :=
calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul]
... = det (diagonal (λ _, c)) * det A : det_mul _ _
... = c ^ fintype.card n * det A : by simp [card_univ]
section hom_map
variables {S : Type w} [comm_ring S]
lemma ring_hom.map_det {M : matrix n n R} {f : R →+* S} :
f M.det = matrix.det (f.map_matrix M) :=
by simp [matrix.det, f.map_sum, f.map_prod]
lemma alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T]
{M : matrix n n S} {f : S →ₐ[R] T} :
f M.det = matrix.det ((f : S →+* T).map_matrix M) :=
by rw [← alg_hom.coe_to_ring_hom, ring_hom.map_det]
end hom_map
section det_zero
/-!
### `det_zero` section
Prove that a matrix with a repeated column has determinant equal to zero.
-/
lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 :=
begin
rw [←det_transpose, det],
convert @sum_const_zero _ _ (univ : finset (perm n)) _,
ext σ,
convert mul_zero ↑(sign σ),
apply prod_eq_zero (mem_univ i),
rw [transpose_apply],
apply h
end
lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : ∀ i, A i j = 0) : det A = 0 :=
by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, }
variables {M : matrix n n R} {i j : n}
/-- If a matrix has a repeated row, the determinant will be zero. -/
theorem det_zero_of_row_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 :=
begin
apply finset.sum_involution
(λ σ _, swap i j * σ)
(λ σ _, _)
(λ σ _ _, (not_congr swap_mul_eq_iff).mpr i_ne_j)
(λ σ _, finset.mem_univ _)
(λ σ _, swap_mul_involutive i j σ),
convert add_right_neg (↑↑(sign σ) * ∏ i, M (σ i) i),
rw neg_mul_eq_neg_mul,
congr,
{ rw [sign_mul, sign_swap i_ne_j], norm_num },
{ ext j, rw [perm.mul_apply, apply_swap_eq_self hij], }
end
end det_zero
lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) :=
begin
simp only [det],
have : ∀ σ : perm n, ∏ i, M.update_column j (u + v) (σ i) i =
∏ i, M.update_column j u (σ i) i + ∏ i, M.update_column j v (σ i) i,
{ intros σ,
simp only [update_column_apply, prod_ite, filter_eq',
finset.prod_singleton, finset.mem_univ, if_true, pi.add_apply, add_mul] },
rw [← sum_add_distrib],
apply sum_congr rfl,
intros x _,
rw [this, mul_add]
end
lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) :=
begin
rw [← det_transpose, ← update_column_transpose, det_update_column_add],
simp [update_column_transpose, det_transpose]
end
lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_column M j $ s • u) = s * det (update_column M j u) :=
begin
simp only [det],
have : ∀ σ : perm n, ∏ i, M.update_column j (s • u) (σ i) i = s * ∏ i, M.update_column j u (σ i) i,
{ intros σ,
simp only [update_column_apply, prod_ite, filter_eq', finset.prod_singleton, finset.mem_univ,
if_true, algebra.id.smul_eq_mul, pi.smul_apply],
ring },
rw mul_sum,
apply sum_congr rfl,
intros x _,
rw this,
ring
end
lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_row M j $ s • u) = s * det (update_row M j u) :=
begin
rw [← det_transpose, ← update_column_transpose, det_update_column_smul],
simp [update_column_transpose, det_transpose]
end
/-- `det` is an alternating multilinear map over the rows of the matrix.
See also `is_basis.det`. -/
@[simps apply]
def det_row_multilinear : alternating_map R (n → R) R n:=
{ to_fun := det,
map_add' := det_update_row_add,
map_smul' := det_update_row_smul,
map_eq_zero_of_eq' := λ M i j h hij, det_zero_of_row_eq hij h }
@[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) :
(block_diagonal M).det = ∏ k, (M k).det :=
begin
-- Rewrite the determinants as a sum over permutations.
unfold det,
-- The right hand side is a product of sums, rewrite it as a sum of products.
rw finset.prod_sum,
simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ],
-- We claim that the only permutations contributing to the sum are those that
-- preserve their second component.
let preserving_snd : finset (equiv.perm (n × o)) :=
finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd),
have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)},
σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd :=
λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩,
rw ← finset.sum_subset (finset.subset_univ preserving_snd) _,
-- And that these are in bijection with `o → equiv.perm m`.
rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _,
prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm,
{ intros σ _,
rw mem_preserving_snd,
rintros ⟨k, x⟩,
simp },
{ intros σ _,
rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product, finset.prod_comm],
simp [sign_prod_congr_left] },
{ intros σ σ' _ _ eq,
ext x hx k,
simp only at eq,
have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) =
prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) :=
λ k x, by rw eq,
simp only [prod_congr_left_apply, prod.mk.inj_iff] at this,
exact (this k x).1 },
{ intros σ hσ,
rw mem_preserving_snd at hσ,
have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd,
{ intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } },
have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k),
{ intros k x,
ext; simp [hσ] },
have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k),
{ intros k x,
conv_lhs { rw ← perm.apply_inv_self σ (x, k) },
ext; simp [hσ'] },
refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩,
{ intro x,
simp [mk_apply_eq, mk_inv_apply_eq] },
{ intro x,
simp [mk_apply_eq, mk_inv_apply_eq] },
{ apply finset.mem_univ },
{ ext ⟨k, x⟩; simp [hσ] } },
{ intros σ _ hσ,
rw mem_preserving_snd at hσ,
obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ,
rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero],
rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne],
exact hkx }
end
end matrix
|
816bba0eb2cfedb16a709314a816e4e1f1bba3f6 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/divisibility.lean | 7af98d63cbf3074307cf6ac83ef1619854526d4c | [] | 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 | 8,989 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov,
Neil Strickland, Aaron Anderson
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.group_with_zero.default
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Divisibility
This file defines the basics of the divisibility relation in the context of `(comm_)` `monoid`s
`(_with_zero)`.
## Main definitions
* `monoid.has_dvd`
## Implementation notes
The divisibility relation is defined for all monoids, and as such, depends on the order of
multiplication if the monoid is not commutative. There are two possible conventions for
divisibility in the noncommutative context, and this relation follows the convention for ordinals,
so `a | b` is defined as `∃ c, b = a * c`.
## Tags
divisibility, divides
-/
/-- There are two possible conventions for divisibility, which coincide in a `comm_monoid`.
This matches the convention for ordinals. -/
protected instance monoid_has_dvd {α : Type u_1} [monoid α] : has_dvd α :=
has_dvd.mk fun (a b : α) => ∃ (c : α), b = a * c
-- TODO: this used to not have c explicit, but that seems to be important
-- for use with tactics, similar to exist.intro
theorem dvd.intro {α : Type u_1} [monoid α] {a : α} {b : α} (c : α) (h : a * c = b) : a ∣ b :=
exists.intro c (Eq.symm h)
theorem dvd_of_mul_right_eq {α : Type u_1} [monoid α] {a : α} {b : α} (c : α) (h : a * c = b) : a ∣ b :=
dvd.intro
theorem exists_eq_mul_right_of_dvd {α : Type u_1} [monoid α] {a : α} {b : α} (h : a ∣ b) : ∃ (c : α), b = a * c :=
h
theorem dvd.elim {α : Type u_1} [monoid α] {P : Prop} {a : α} {b : α} (H₁ : a ∣ b) (H₂ : ∀ (c : α), b = a * c → P) : P :=
exists.elim H₁ H₂
@[simp] theorem dvd_refl {α : Type u_1} [monoid α] (a : α) : a ∣ a := sorry
theorem dvd_trans {α : Type u_1} [monoid α] {a : α} {b : α} {c : α} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := sorry
theorem dvd.trans {α : Type u_1} [monoid α] {a : α} {b : α} {c : α} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c :=
dvd_trans
theorem one_dvd {α : Type u_1} [monoid α] (a : α) : 1 ∣ a := sorry
@[simp] theorem dvd_mul_right {α : Type u_1} [monoid α] (a : α) (b : α) : a ∣ a * b :=
dvd.intro b rfl
theorem dvd_mul_of_dvd_left {α : Type u_1} [monoid α] {a : α} {b : α} (h : a ∣ b) (c : α) : a ∣ b * c := sorry
theorem dvd_of_mul_right_dvd {α : Type u_1} [monoid α] {a : α} {b : α} {c : α} (h : a * b ∣ c) : a ∣ c := sorry
theorem dvd.intro_left {α : Type u_1} [comm_monoid α] {a : α} {b : α} (c : α) (h : c * a = b) : a ∣ b :=
dvd.intro c (eq.mp (Eq._oldrec (Eq.refl (c * a = b)) (mul_comm c a)) h)
theorem dvd_of_mul_left_eq {α : Type u_1} [comm_monoid α] {a : α} {b : α} (c : α) (h : c * a = b) : a ∣ b :=
dvd.intro_left
theorem exists_eq_mul_left_of_dvd {α : Type u_1} [comm_monoid α] {a : α} {b : α} (h : a ∣ b) : ∃ (c : α), b = c * a :=
dvd.elim h fun (c : α) (H1 : b = a * c) => exists.intro c (Eq.trans H1 (mul_comm a c))
theorem dvd.elim_left {α : Type u_1} [comm_monoid α] {a : α} {b : α} {P : Prop} (h₁ : a ∣ b) (h₂ : ∀ (c : α), b = c * a → P) : P :=
exists.elim (exists_eq_mul_left_of_dvd h₁) fun (c : α) (h₃ : b = c * a) => h₂ c h₃
@[simp] theorem dvd_mul_left {α : Type u_1} [comm_monoid α] (a : α) (b : α) : a ∣ b * a :=
dvd.intro b (mul_comm a b)
theorem dvd_mul_of_dvd_right {α : Type u_1} [comm_monoid α] {a : α} {b : α} (h : a ∣ b) (c : α) : a ∣ c * b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ∣ c * b)) (mul_comm c b))) (dvd_mul_of_dvd_left h c)
theorem mul_dvd_mul {α : Type u_1} [comm_monoid α] {a : α} {b : α} {c : α} {d : α} : a ∣ b → c ∣ d → a * c ∣ b * d := sorry
theorem mul_dvd_mul_left {α : Type u_1} [comm_monoid α] (a : α) {b : α} {c : α} (h : b ∣ c) : a * b ∣ a * c :=
mul_dvd_mul (dvd_refl a) h
theorem mul_dvd_mul_right {α : Type u_1} [comm_monoid α] {a : α} {b : α} (h : a ∣ b) (c : α) : a * c ∣ b * c :=
mul_dvd_mul h (dvd_refl c)
theorem dvd_of_mul_left_dvd {α : Type u_1} [comm_monoid α] {a : α} {b : α} {c : α} (h : a * b ∣ c) : b ∣ c := sorry
theorem eq_zero_of_zero_dvd {α : Type u_1} [monoid_with_zero α] {a : α} (h : 0 ∣ a) : a = 0 :=
dvd.elim h fun (c : α) (H' : a = 0 * c) => Eq.trans H' (zero_mul c)
/-- Given an element `a` of a commutative monoid with zero, there exists another element whose
product with zero equals `a` iff `a` equals zero. -/
@[simp] theorem zero_dvd_iff {α : Type u_1} [monoid_with_zero α] {a : α} : 0 ∣ a ↔ a = 0 :=
{ mp := eq_zero_of_zero_dvd, mpr := fun (h : a = 0) => eq.mpr (id (Eq._oldrec (Eq.refl (0 ∣ a)) h)) (dvd_refl 0) }
@[simp] theorem dvd_zero {α : Type u_1} [monoid_with_zero α] (a : α) : a ∣ 0 := sorry
/-- Given two elements `b`, `c` of a `cancel_monoid_with_zero` and a nonzero element `a`,
`a*b` divides `a*c` iff `b` divides `c`. -/
theorem mul_dvd_mul_iff_left {α : Type u_1} [cancel_monoid_with_zero α] {a : α} {b : α} {c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := sorry
/-- Given two elements `a`, `b` of a commutative `cancel_monoid_with_zero` and a nonzero
element `c`, `a*c` divides `b*c` iff `a` divides `b`. -/
theorem mul_dvd_mul_iff_right {α : Type u_1} [comm_cancel_monoid_with_zero α] {a : α} {b : α} {c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := sorry
/-!
### Units in various monoids
-/
namespace units
/-- Elements of the unit group of a monoid represented as elements of the monoid
divide any element of the monoid. -/
theorem coe_dvd {α : Type u_1} [monoid α] {a : α} {u : units α} : ↑u ∣ a := sorry
/-- In a monoid, an element `a` divides an element `b` iff `a` divides all
associates of `b`. -/
theorem dvd_mul_right {α : Type u_1} [monoid α] {a : α} {b : α} {u : units α} : a ∣ b * ↑u ↔ a ∣ b := sorry
/-- In a monoid, an element a divides an element b iff all associates of `a` divide `b`.-/
theorem mul_right_dvd {α : Type u_1} [monoid α] {a : α} {b : α} {u : units α} : a * ↑u ∣ b ↔ a ∣ b := sorry
/-- In a commutative monoid, an element `a` divides an element `b` iff `a` divides all left
associates of `b`. -/
theorem dvd_mul_left {α : Type u_1} [comm_monoid α] {a : α} {b : α} {u : units α} : a ∣ ↑u * b ↔ a ∣ b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ∣ ↑u * b ↔ a ∣ b)) (mul_comm (↑u) b))) dvd_mul_right
/-- In a commutative monoid, an element `a` divides an element `b` iff all
left associates of `a` divide `b`.-/
theorem mul_left_dvd {α : Type u_1} [comm_monoid α] {a : α} {b : α} {u : units α} : ↑u * a ∣ b ↔ a ∣ b :=
eq.mpr (id (Eq._oldrec (Eq.refl (↑u * a ∣ b ↔ a ∣ b)) (mul_comm (↑u) a))) mul_right_dvd
end units
namespace is_unit
/-- Units of a monoid divide any element of the monoid. -/
@[simp] theorem dvd {α : Type u_1} [monoid α] {a : α} {u : α} (hu : is_unit u) : u ∣ a :=
Exists.dcases_on hu fun (u_1 : units α) (hu_h : ↑u_1 = u) => Eq._oldrec units.coe_dvd hu_h
@[simp] theorem dvd_mul_right {α : Type u_1} [monoid α] {a : α} {b : α} {u : α} (hu : is_unit u) : a ∣ b * u ↔ a ∣ b :=
Exists.dcases_on hu fun (u_1 : units α) (hu_h : ↑u_1 = u) => Eq._oldrec units.dvd_mul_right hu_h
/-- In a monoid, an element a divides an element b iff all associates of `a` divide `b`.-/
@[simp] theorem mul_right_dvd {α : Type u_1} [monoid α] {a : α} {b : α} {u : α} (hu : is_unit u) : a * u ∣ b ↔ a ∣ b :=
Exists.dcases_on hu fun (u_1 : units α) (hu_h : ↑u_1 = u) => Eq._oldrec units.mul_right_dvd hu_h
/-- In a commutative monoid, an element `a` divides an element `b` iff `a` divides all left
associates of `b`. -/
@[simp] theorem dvd_mul_left {α : Type u_1} [comm_monoid α] (a : α) (b : α) (u : α) (hu : is_unit u) : a ∣ u * b ↔ a ∣ b :=
Exists.dcases_on hu fun (u_1 : units α) (hu_h : ↑u_1 = u) => Eq._oldrec units.dvd_mul_left hu_h
/-- In a commutative monoid, an element `a` divides an element `b` iff all
left associates of `a` divide `b`.-/
@[simp] theorem mul_left_dvd {α : Type u_1} [comm_monoid α] (a : α) (b : α) (u : α) (hu : is_unit u) : u * a ∣ b ↔ a ∣ b :=
Exists.dcases_on hu fun (u_1 : units α) (hu_h : ↑u_1 = u) => Eq._oldrec units.mul_left_dvd hu_h
end is_unit
/-- `dvd_not_unit a b` expresses that `a` divides `b` "strictly", i.e. that `b` divided by `a` is not a unit. -/
def dvd_not_unit {α : Type u_1} [comm_monoid_with_zero α] (a : α) (b : α) :=
a ≠ 0 ∧ ∃ (x : α), ¬is_unit x ∧ b = a * x
theorem dvd_not_unit_of_dvd_of_not_dvd {α : Type u_1} [comm_monoid_with_zero α] {a : α} {b : α} (hd : a ∣ b) (hnd : ¬b ∣ a) : dvd_not_unit a b := sorry
|
33f6c2dc280e2722b913827b75acaed729a29141 | 5df84495ec6c281df6d26411cc20aac5c941e745 | /src/formal_ml/prod_measure.lean | a28edb8bcbbfbc199a18e305c8849f02bd1d8c12 | [
"Apache-2.0"
] | permissive | eric-wieser/formal-ml | e278df5a8df78aa3947bc8376650419e1b2b0a14 | 630011d19fdd9539c8d6493a69fe70af5d193590 | refs/heads/master | 1,681,491,589,256 | 1,612,642,743,000 | 1,612,642,743,000 | 360,114,136 | 0 | 0 | Apache-2.0 | 1,618,998,189,000 | 1,618,998,188,000 | null | UTF-8 | Lean | false | false | 12,479 | lean | /-
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-/
import measure_theory.measurable_space
import measure_theory.measure_space
import measure_theory.outer_measure
import measure_theory.lebesgue_measure
import measure_theory.integration
import measure_theory.borel_space
import data.set.countable
import formal_ml.nnreal
import formal_ml.ennreal
import formal_ml.sum
import formal_ml.lattice
import formal_ml.measurable_space
import formal_ml.classical
import formal_ml.core
import formal_ml.characteristic
import formal_ml.measure
import data.equiv.list
noncomputable def prod.outer_measure {α:Type*} {β:Type*} [Mα:measurable_space α] [Mβ:measurable_space β]
(μα:measure_theory.outer_measure α) (μβ:measure_theory.outer_measure β):measure_theory.outer_measure (α × β) :=
measure_theory.outer_measure.of_function
(λ P:set (α × β), μα (prod.fst '' P) * μβ (prod.snd '' P))
begin
simp,
end
noncomputable def prod.measure {α:Type*} {β:Type*} [Mα:measurable_space α] [Mβ:measurable_space β]
(μα:measure_theory.measure α) (μβ:measure_theory.measure β):measure_theory.measure (α × β) :=
(prod.outer_measure μα.to_outer_measure μβ.to_outer_measure).to_measure
begin
unfold prod.measurable_space,
simp,
split;
intros P A1;
unfold measurable_space.comap at A1;
cases A1 with s A1;
cases A1 with A1 A2;
subst P;
apply measure_theory.outer_measure.of_function_caratheodory;
simp,
{intros t,
have B1:μα (prod.fst '' t ∩ s) + μα (prod.fst '' t \ s) = μα (prod.fst '' t),
{rw ← measure_theory.measure_eq_inter_diff', apply A1},
rw ← B1,
clear B1,
rw right_distrib,
apply @add_le_add ennreal _;apply ennreal.mul_le_mul;try {apply measure_theory.measure_mono};simp;rw set.subset_def;
intros p B2;cases p;simp at B2;simp [B2];
try {apply exists.intro p_snd,simp [B2]};
{apply exists.intro p_fst,simp [B2]}},
{intros t,
have B1:μβ (prod.snd '' t ∩ s) + μβ (prod.snd '' t \ s) = μβ (prod.snd '' t),
{rw ← measure_theory.measure_eq_inter_diff', apply A1},
rw ← B1,
clear B1,
rw left_distrib,
apply @add_le_add ennreal _;apply ennreal.mul_le_mul;try {apply measure_theory.measure_mono};simp;rw set.subset_def;
intros p B2;cases p;simp at B2;simp [B2];
try {apply exists.intro p_snd,simp [B2]};
{apply exists.intro p_fst,simp [B2]}},
end
@[simp]
lemma set.prod_fst_image_of_prod {α:Type*} {β:Type*} (A:set α) (B:set β) (h:B.nonempty):(prod.fst '' (A.prod B)) = A :=
begin
ext p;split;intros A1,
simp at A1,simp [A1],
simp [A1],
apply h,
end
@[simp]
lemma set.prod_snd_image_of_prod {α:Type*} {β:Type*} (A:set α) (B:set β) (h:A.nonempty):(prod.snd '' (A.prod B)) = B :=
begin
ext p;split;intros A1,
simp at A1,simp [A1],
simp [A1],
apply h,
end
lemma prod.outer_measure.Inf_sum {α:Type*} {β:Type*} [Mα:measurable_space α] [Mβ:measurable_space β]
(μα:measure_theory.outer_measure α) (μβ:measure_theory.outer_measure β) {P:set (α × β)}:
prod.outer_measure μα μβ P =
⨅ (f:ℕ → set α) (g:ℕ → set β) (h₁: P ⊆ ⋃ n, (f n).prod (g n)), ∑' n, μα (f n) * μβ (g n) :=
begin
unfold prod.outer_measure measure_theory.outer_measure.of_function,
rw ← measure_theory.outer_measure.measure_of_eq_coe,
simp,
apply le_antisymm,
simp,
intros f g B1,
apply @infi_le_of_le ennreal _ _ _ _ (λ (n:ℕ), (f n).prod (g n)),
apply @infi_le_of_le ennreal _ _ _ _ _,
apply ennreal.tsum_le_tsum,
intros a,
cases (set.eq_empty_or_nonempty (f a)) with B2 B2,
{simp [B2]},
cases (set.eq_empty_or_nonempty (g a)) with B3 B3,
{simp [B3]},
{simp [B2,B3,le_refl]},
{simp [B1]},
simp,
intros h C1,
apply @infi_le_of_le ennreal _ _ _ _ (λ n, prod.fst '' (h n)),
apply @infi_le_of_le ennreal _ _ _ _ (λ n, prod.snd '' (h n)),
apply @infi_le_of_le ennreal _ _ _ _ _,
simp,
apply le_refl _,
simp,
apply @set.subset.trans (α × β) P (set.Union h) (⋃ (n : ℕ), (prod.fst '' h n).prod (prod.snd '' h n)) C1,
apply set.Union_subset_Union,
intro i,
rw set.subset_def,
intros a C2,cases a,simp,
apply and.intro (exists.intro a_snd C2) (exists.intro a_fst C2),
end
lemma set.prod_subset_prod {α:Type*} {β:Type*} {A A':set α} {B B':set β}:A ⊆ A' → B ⊆ B' →
A.prod B ⊆ A'.prod B' := begin
intros hA hB,
intros p hp,
split,
simp at hp,
apply hA,
apply hp.left,
apply hB,
apply hp.right,
end
lemma prod.outer_measure.Inf_sum2 {α:Type*} {β:Type*} [Mα:measurable_space α] [Mβ:measurable_space β]
(μα:measure_theory.measure α) (μβ:measure_theory.measure β) {P:set (α × β)}:
prod.outer_measure μα.to_outer_measure μβ.to_outer_measure P =
⨅ (f:ℕ → set α) (g:ℕ → set β)
(h₁ : ∀ n, measurable_set (f n))
(h₂ : ∀ n, measurable_set (g n))
(h₃: P ⊆ ⋃ n, (f n).prod (g n)), ∑' n, μα (f n) * μβ (g n) :=
begin
rw prod.outer_measure.Inf_sum,
apply le_antisymm,
{ simp,
intros f g h₁ h₂ h₃,
apply @infi_le_trans (ℕ→ set α) ennreal _ f,
apply @infi_le_trans (ℕ→ set β) ennreal _ g,
rw infi_prop_def,
apply le_refl _,
apply h₃ },
{ simp,
intros f g h₃,
have h4 := λ n, measure_theory.measurable_eq μα (f n),
rw classical.skolem at h4,
cases h4 with f' h4,
have h5 := λ n, measure_theory.measurable_eq μβ (g n),
rw classical.skolem at h5,
cases h5 with g' h5,
apply @infi_le_trans (ℕ→ set α) ennreal _ f',
apply @infi_le_trans (ℕ→ set β) ennreal _ g',
rw infi_prop_def,
rw infi_prop_def,
rw infi_prop_def,
apply ennreal.tsum_le_tsum,
intro n,
rw (h4 n).right.left,
rw (h5 n).right.left,
apply le_refl _,
apply @set.subset.trans _ P (⋃ (n : ℕ), (f n).prod (g n))
(⋃ (n : ℕ), (f' n).prod (g' n)) h₃,
apply set.Union_subset_Union,
intro n,
apply set.prod_subset_prod,
apply (h4 n).right.right,
apply (h5 n).right.right,
{ intro n, apply (h5 n).left },
{ intro n, apply (h4 n).left },
},
-- sorry
end
/-
If we can make this into an equality, we're home free.
See https://www.math.ucdavis.edu/~hunter/measure_theory/measure_notes_ch5.pdf
Those notes focus on measurable sets. We could theoretically do the same. However,
it would make the rest of the analysis much more complex.
I wonder if using an "outer measure lower integral" would make this useful.
-/
lemma prod.outer_measure.apply_prod_le {α:Type*} {β:Type*} [Mα:measurable_space α] [Mβ:measurable_space β]
(μα:measure_theory.outer_measure α) (μβ:measure_theory.outer_measure β) {A:set α} {B:set β}:
prod.outer_measure μα μβ (A.prod B) ≤ μα A * μβ B :=
begin
rw prod.outer_measure.Inf_sum,
{apply @infi_le_of_le ennreal _ _ _ _ (λ (n:ℕ), ite (n = 0) A ∅),
apply @infi_le_of_le ennreal _ _ _ _ (λ (n:ℕ), ite (n = 0) B ∅),
apply @infi_le_of_le ennreal _ _ _ _ _,
rw tsum_eq_single 0,
{simp [le_refl]},
intros b' B1,
simp [B1],
apply ennreal.t2_space,
rw set.subset_def,
intros p B2,
simp,
apply exists.intro 0,
{simp at B2,simp [B2]}},
end
--measure_theory.lintegral_characteristic
/- The primary focus is on measures, instead of outer measures. This establishes an
inequality when the sets are measurable and we are looking at a product of two
measures. -/
lemma prod.outer_measure.le_apply_prod {α:Type*} {β:Type*} [Mα:measurable_space α] [Mβ:measurable_space β]
(μα:measure_theory.measure α) (μβ:measure_theory.measure β) {A:set α} {B:set β}:
(measurable_set A) → (measurable_set B) →
μα A * μβ B ≤ prod.outer_measure μα.to_outer_measure μβ.to_outer_measure (A.prod B) :=
begin
intros A4 A5,
rw prod.outer_measure.Inf_sum2,
simp,
intros f g A2 A3 A1,
have h2:(A.prod B).characteristic ≤ ∑' (n : ℕ), ((f n).prod (g n)).characteristic,
{ apply function.le_trans (set.characteristic.subset A1),
apply set.characteristic.Union,
},
have h3:∀ (a:α) (b:β), (A.characteristic a) * (B.characteristic b) ≤
∑' (n : ℕ), ((f n).characteristic a * (g n).characteristic b),
{ intros a b,
rw ← set.characteristic.prod,
have h3a: (λ n, ((f n).characteristic a * (g n).characteristic b)) =
(λ n, ((f n).prod (g n)).characteristic (a, b)),
{ ext n, rw set.characteristic.prod },
rw h3a,
have h3b:((∑' (n : ℕ), ((f n).prod (g n)).characteristic) (a, b)) =
(∑' (n : ℕ), ((f n).prod (g n)).characteristic (a, b)) ,
{ apply ennreal.tsum_apply },
rw ← h3b,
apply h2 },
have h4:∀ (b:β), measure_theory.lintegral μα (λ a, A.characteristic a * (B.characteristic b)) ≤ measure_theory.lintegral μα (λ a,
∑' (n : ℕ), ((f n).characteristic a) * (g n).characteristic b),
{ intro b,
have h4a: ∀ (a:α), (A.characteristic a) * (B.characteristic b) ≤
∑' (n : ℕ), ((f n).characteristic a * (g n).characteristic b),
{ intro a, apply h3 },
apply measure_theory.lintegral_mono, apply h4a },
have h5:∀ (b:β), μα A * (B.characteristic b) ≤
∑' (n : ℕ), ((μα (f n)) * (g n).characteristic b),
{ intro b,
have h5a := h4 b,
rw measure_theory.lintegral_mul_const at h5a,
rw measure_theory.lintegral_characteristic at h5a,
rw measure_theory.lintegral_tsum at h5a,
have h5b : (λ i, (∫⁻ (a : α), (f i).characteristic a * (g i).characteristic b ∂μα)) =
(λ i, μα (f i) * (g i).characteristic b),
{ ext1 i,
rw measure_theory.lintegral_mul_const,
--rw set.characteristic_integral,
rw measure_theory.lintegral_characteristic,
apply A2,
apply measurable.characteristic,
apply A2 },
rw h5b at h5a,
apply h5a,
{ intro i, apply measurable.ennreal_mul,
apply measurable.characteristic,
apply A2,
apply measurable_const },
{ apply A4 },
{ apply measurable.characteristic, apply A4 } },
have h6:∫⁻ (b : β), (μα A) * B.characteristic b ∂μβ ≤
∫⁻ (b : β), ( ∑' (n : ℕ), (μα (f n)) * (g n).characteristic b) ∂μβ,
{ apply measure_theory.lintegral_mono,
apply h5, },
rw measure_theory.lintegral_const_mul at h6,
rw measure_theory.lintegral_characteristic at h6, -- set.characteristic_integral at h6,
rw measure_theory.lintegral_tsum at h6,
have h7: (λ i, ∫⁻ (b : β), μα (f i) * (g i).characteristic b ∂μβ) =
(λ i, μα (f i) * μβ (g i)),
{ ext1 i,
rw measure_theory.lintegral_const_mul,
rw measure_theory.lintegral_characteristic, -- set.characteristic_integral,
apply A3, apply measurable.characteristic,
apply A3 },
rw h7 at h6,
apply h6,
{ intro i, apply measurable.ennreal_mul,
apply measurable_const,
apply measurable.characteristic,
apply A3 },
{ apply A5 },
{ apply measurable.characteristic, apply A5 },
end
lemma prod.measure_apply {α:Type*} {β:Type*} [Mα:measurable_space α] [Mβ:measurable_space β]
(μα:measure_theory.measure α) (μβ:measure_theory.measure β) (S:set (α × β)):measurable_set S →
prod.measure μα μβ S =
prod.outer_measure μα.to_outer_measure μβ.to_outer_measure S :=
begin
intro h,
simp [prod.measure],
rw measure_theory.to_measure_apply,
apply h,
end
lemma prod.measure.apply_prod
{α:Type*} {β:Type*} [Mα:measurable_space α] [Mβ:measurable_space β]
(μα:measure_theory.measure α) (μβ:measure_theory.measure β) (A:set α) (B:set β):measurable_set A →
measurable_set B →
(prod.measure μα μβ) (A.prod B) = (μα A) * (μβ B) :=
begin
intros A1 A2,
rw prod.measure_apply,
apply le_antisymm,
{ apply prod.outer_measure.apply_prod_le,
},
apply prod.outer_measure.le_apply_prod,
apply A1,
apply A2,
apply measurable_set.prod A1 A2,
end
|
0905236aab78047529cf24c505544ec17c99c41b | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/Tactic/Generalize.lean | 9d8bb924a1628c8a2b7e9b6c7ee7ae08b1f930d8 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 819 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Meta.Tactic.Generalize
import Lean.Meta.Check
import Lean.Meta.Tactic.Intro
import Lean.Elab.Tactic.ElabTerm
namespace Lean.Elab.Tactic
open Meta
@[builtinTactic Lean.Parser.Tactic.generalize] def evalGeneralize : Tactic := fun stx =>
withMainContext do
let args ← stx[1].getSepArgs.mapM fun arg => do
let hName? := if arg[0].isNone then none else some arg[0][0].getId
let expr ← elabTerm arg[1] none
return { hName?, expr, xName? := arg[3].getId : GeneralizeArg }
liftMetaTactic fun mvarId => do
let (_, mvarId) ← generalize mvarId args
return [mvarId]
end Lean.Elab.Tactic
|
6075f578dab0d53fa3df2cf5b8f41639586244a1 | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/tactic/core.lean | 81aee8921a52046174a6dd3a2e4c91d0e72801bb | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 70,353 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic category.basic meta.expr meta.rb_map data.bool tactic.doc_commands
tactic.derive_inhabited
universe variable u
instance : has_lt pos :=
{ lt := λ x y, (x.line, x.column) < (y.line, y.column) }
namespace expr
open tactic
attribute [derive has_reflect] binder_info
attribute [derive decidable_eq] binder_info congr_arg_kind
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
end expr
namespace interaction_monad
open result
/-- `get_result tac` returns the result state of applying `tac` to the current state.
Note that it does not update the current state. -/
meta def get_result {σ α} (tac : interaction_monad σ α) :
interaction_monad σ (interaction_monad.result σ α) | s :=
match tac s with
| r@(success _ s') := success r s'
| r@(exception _ _ s') := success r s'
end
end interaction_monad
namespace lean.parser
open lean interaction_monad.result
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here : string → lean.parser unit
| str := do left ← emit_command_here str,
if left.length = 0 then return ()
else emit_code_here left
end lean.parser
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] : list α → format
| [] := to_fmt "[]"
| xs := to_fmt "[" ++ group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) ++ to_fmt "]"
end format
namespace tactic
open function
/-- `mk_local_pisn e n` instantiates the first `n` variables of a pi expression `e`,
and returns the new local constants along with the instantiated expression. Fails if `e` does
not begin with at least `n` pi binders. -/
meta def mk_local_pisn : expr → nat → tactic (list expr × expr)
| (expr.pi n bi d b) (c + 1) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pisn (b.instantiate_var p) c,
return ((p :: ps), r)
| e 0 := return ([], e)
| _ _ := failed
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks whether `decl_name` has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file' e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro1) <|> note n none e
/-! ### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`. -/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `revert_deps e` reverts all the hypotheses that depend on one of the local
constants `e`, including the local definitions that have `e` in their definition.
This fixes a bug in `revert_kdeps` that does not revert local definitions for which `e` only
appears in the definition. -/
/- We cannot implement it as `revert e >> intro1`, because that would change the local constant in
the context. -/
meta def revert_deps (e : expr) : tactic ℕ := do
n ← revert_kdeps e,
l ← local_context,
[pos] ← return $ l.indexes_of e,
let l := l.drop pos.succ, -- local hypotheses after `e`
ls ← l.mfilter $ λ e', try_core (local_def_value e') >>= λ o, return $ o.elim ff $ λ e'',
e''.has_local_constant e,
n' ← revert_lst ls,
return $ n + n'
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit :=
retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip
/-- `clear_value e` clears the body of the local definition `e`, changing it into a regular
hypothesis. A hypothesis `e : α := t` is changed to `e : α`.
This tactic is called `clearbody` in Coq. -/
meta def clear_value (e : expr) : tactic unit := do
n ← revert_after e,
is_local_def e <|>
pp e >>= λ s, fail format!"Cannot clear the body of {s}. It is not a local definition.",
let nm := e.local_pp_name,
(generalize' e nm >> clear e) <|>
fail format!"Cannot clear the body of {nm}. The resulting goal is not type correct.",
intron n
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
end instance_cache
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of the given (Pi-)type. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of the given function. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
/-- Auxilliary defintion for `get_pi_binders`. -/
meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr)
| es (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
let new_b := expr.instantiate_var b l,
get_pi_binders_aux (⟨n, bi, d⟩::es) new_b
| es e := return (es, e)
/-- Get the binders and target of a pi-type. Instantiates bound variables by
local constants. Cf. `pi_binders` in `meta.expr` (which produces open terms).
See also `mk_local_pis` in `init.core.tactic` which does almost the same. -/
meta def get_pi_binders : expr → tactic (list binder × expr) | e :=
do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e)
/-- Auxilliary definition for `get_pi_binders_dep`. -/
meta def get_pi_binders_dep_aux : ℕ → expr → tactic (list (ℕ × binder) × expr)
| n (expr.pi nm bi d b) :=
do l ← mk_local' nm bi d,
(ls, r) ← get_pi_binders_dep_aux (n+1) (expr.instantiate_var b l),
return (if b.has_var then ls else (n, ⟨nm, bi, d⟩)::ls, r)
| n e := return ([], e)
/-- A variant of `get_pi_binders` that only returns the binders that do not occur in later
arguments or in the target. Also returns the argument position of each returned binder. -/
meta def get_pi_binders_dep : expr → tactic (list (ℕ × binder) × expr) :=
get_pi_binders_dep_aux 0
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
[c] ← pure $ env.constructors_of struct_n | fail "too many constructors",
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= mk_local_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`. -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- `apply_list l`: try to apply the tactics in the list `l` on the first goal, and
fail if none succeeds -/
meta def apply_list_expr : list expr → tactic unit
| [] := fail "no matching rule"
| (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t
/-- constructs a list of expressions given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.-/
meta def build_list_expr_for_apply : list pexpr → tactic (list expr)
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← list.mmap mk_const l,
return (m.append tail))
<|> return (a::tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times -/
meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit :=
do l ← build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option 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 := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
`apply_any` tries to apply one of a list of lemmas to the current goal.
Optional arguments:
* `lemmas` controls which expressions are applied.
* `tac` is called after a successful application. Defaults to `skip`.
* `use_symmetry`: if no lemma applies, call `symmetry` and try again.
* `use_exfalso`: if no lemma applies, call `exfalso` and try again.
-/
meta def apply_any
(lemmas : list expr)
(tac : tactic unit := skip)
(use_symmetry : bool := tt)
(use_exfalso : bool := tt) : tactic unit :=
do
let modes := [skip]
++ (if use_symmetry then [symmetry] else [])
++ (if use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m, lemmas.any_of (λ H, apply H >> tac)) <|>
fail "apply_any tactic failed; no lemma could be applied"
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
private meta def iterate_aux (t : tactic α) : list α → tactic (list α)
| L := (do r ← t, iterate_aux (r :: L)) <|> return L
/-- Apply a tactic as many times as possible, collecting the results in a list. -/
meta def iterate' (t : tactic α) : tactic (list α) :=
list.reverse <$> iterate_aux t []
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (α × list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate' t,
return (r, L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1 >>= λ p, return (p.1 :: p.2)
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) :=
λ s, result.success
(tactics.map $
λ t : tactic α,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) :
tactic (list α) :=
λ s, result.success
(((tactics.map $
λ t : tactic α,
match (do a ← t, n ← sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (λ p q : α × ℕ, p.2 < q.2)).map (prod.fst)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/-- Given a proof `pr : t`, adds `h : t` to the current context, where the name `h` is fresh. -/
meta def note_anon (e : expr) : tactic expr :=
do n ← get_unused_name "lh",
note n none e
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
prod.snd <$> solve_aux t' assumption
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
t ← target,
new_goal ← mk_meta_var (t.pis lc),
old::other_goals ← get_goals,
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/-- Like `mk_local_pis` but translating into weak head normal form before checking if it is a `Π`.
-/
meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do
(expr.pi n bi d b) ← whnf e | return ([], e),
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
/-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g`. -/
meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do
t ← infer_type h,
(ctxt, t) ← mk_local_pis_whnf t,
`(@Exists %%α %%p) ← whnf t transparency.all |
fail "expected a term of the shape ∀xs, ∃a, p xs a",
α_t ← infer_type α,
expr.sort u ← whnf α_t transparency.all,
value ← mk_local_def data (α.pis ctxt),
t' ← head_beta (p.app (value.mk_app ctxt)),
spec ← mk_local_def spec (t'.pis ctxt),
dependent_pose_core [
(value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt),
(spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)],
try (tactic.clear h),
intro1,
intro1
/-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`,
and a final hypothesis on `p as`. -/
meta def choose : expr → list name → tactic unit
| h [] := fail "expect list of variables"
| h [n] := do
cnt ← revert h,
intro n,
intron (cnt - 1),
return ()
| h (n::ns) := do
v ← get_unused_name >>= choose1 h n,
choose v ns
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals $ instantiate_mvars_in_target
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/-- Similar to `mk_local_pis` but make meta variables instead of
local constants. -/
meta def mk_meta_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_meta_var d,
(ps, r) ← mk_meta_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : ℤ ⊕ ℕ :=
{! !}
```
produces:
```lean
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← mk_local_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail "symmetry tactic failed, target is not a relation application with the expected property."
end
precedence `setup_tactic_parser`:0
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open lean
open lean.parser
open interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α :=
λ s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit :=
do x ← retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) :=
do gs' ← get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
l₀ : T,
l₁ : T
⊢ ∀ v : T, foo
```
is represented as
```
(2, ∀ l₀ l₁ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`∀` are actually local constant. Comparing two such goals with `=`
rather than `=ₐ` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := ℕ × expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls ← local_context,
tgt ← target >>= instantiate_mvars,
tgt ← pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `ℕ × expr` where
the `expr` encodes the following proof state:
```lean
2 goals
l₁ : t₁,
l₂ : t₂,
l₃ : t₃
⊢ tgt₁
⊢ tgt₂
```
as
```lean
[ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁),
(0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs ← get_goals,
gs.mmap $ λ g, do
⟨n,g⟩ ← goal_of_mvar g,
g ← gs.mfoldl (λ g v, do
g ← kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] :
has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
reserve prefix `pformat! `:100
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```lean
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
reserve prefix `fail! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
reserve prefix `trace! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n))
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for apply_under_pis -/
private meta def apply_under_pis_aux (func arg : pexpr) : ℕ → expr → pexpr
| n (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_pis_aux (n+1) bd)
| n _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_pis_aux func arg 0 pi_expr
/--
Tries to derive instances by unfolding the newly introduced type and applying type class resolution.
For example,
```lean
@[derive ring] def new_int : Type := ℤ
```
adds an instance `ring new_int`, defined to be the instance of `ring ℤ` found by `apply_instance`.
Multiple instances can be added with `@[derive [ring, module ℝ]]`.
This derive handler applies only to declarations made using `def`, and will fail on such a
declaration if it is unable to derive an instance. It is run with higher priority than the built-in
handlers, which will fail on `def`s.
-/
@[derive_handler, priority 2000] meta def delta_instance : derive_handler :=
λ cls new_decl_name,
do env ← get_env,
if env.is_inductive new_decl_name then return ff else
do new_decl_type ← declaration.type <$> get_decl new_decl_name,
new_decl_pexpr ← resolve_name new_decl_name,
tgt ← to_expr $ apply_under_pis cls new_decl_pexpr new_decl_type,
(_, inst) ← solve_aux tgt
(intros >> reset_instance_cache >> delta_target [new_decl_name] >> apply_instance >> done),
inst ← instantiate_mvars inst,
tgt ← instantiate_mvars tgt,
nm ← get_unused_decl_name $ new_decl_name ++
match cls with
-- the postfix is needed because we can't protect this name. using nm.last directly can
-- conflict with open namespaces
| (expr.const nm _) := (nm.last ++ "_1" : string)
| _ := "inst"
end,
add_decl $ mk_definition nm inst.collect_univ_params tgt inst,
set_basic_attribute `instance nm tt,
return tt
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← types.with_ident_list <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
end tactic
|
f8a1ee2eb15a0719449595f3f305ffb8665f3a94 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/metric_space/metrizable_uniformity.lean | 599bd8385e65906c0f4d933936abc7c76ce5c541 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 14,398 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import topology.metric_space.metrizable
/-!
# Metrizable uniform spaces
In this file we prove that a uniform space with countably generated uniformity filter is
pseudometrizable: there exists a `pseudo_metric_space` structure that generates the same uniformity.
The proof follows [Sergey Melikhov, Metrizable uniform spaces][melikhov2011].
## Main definitions
* `pseudo_metric_space.of_prenndist`: given a function `d : X → X → ℝ≥0` such that `d x x = 0` and
`d x y = d y x` for all `x y : X`, constructs the maximal pseudo metric space structure such that
`nndist x y ≤ d x y` for all `x y : X`.
* `uniform_space.pseudo_metric_space`: given a uniform space `X` with countably generated `𝓤 X`,
constructs a `pseudo_metric_space X` instance that is compatible with the uniform space structure.
* `uniform_space.metric_space`: given a T₀ uniform space `X` with countably generated `𝓤 X`,
constructs a `metric_space X` instance that is compatible with the uniform space structure.
## Main statements
* `uniform_space.metrizable_uniformity`: if `X` is a uniform space with countably generated `𝓤 X`,
then there exists a `pseudo_metric_space` structure that is compatible with this `uniform_space`
structure. Use `uniform_space.pseudo_metric_space` or `uniform_space.metric_space` instead.
* `uniform_space.pseudo_metrizable_space`: a uniform space with countably generated `𝓤 X` is pseudo
metrizable.
* `uniform_space.metrizable_space`: a T₀ uniform space with countably generated `𝓤 X` is
metrizable. This is not an instance to avoid loops.
## Tags
metrizable space, uniform space
-/
open set function metric list filter
open_locale nnreal filter uniformity
variables {X : Type*}
namespace pseudo_metric_space
/-- The maximal pseudo metric space structure on `X` such that `dist x y ≤ d x y` for all `x y`,
where `d : X → X → ℝ≥0` is a function such that `d x x = 0` and `d x y = d y x` for all `x`, `y`. -/
noncomputable def of_prenndist (d : X → X → ℝ≥0) (dist_self : ∀ x, d x x = 0)
(dist_comm : ∀ x y, d x y = d y x) :
pseudo_metric_space X :=
{ dist := λ x y, ↑(⨅ l : list X, ((x :: l).zip_with d (l ++ [y])).sum : ℝ≥0),
dist_self := λ x, (nnreal.coe_eq_zero _).2 $ nonpos_iff_eq_zero.1 $
(cinfi_le (order_bot.bdd_below _) []).trans_eq $ by simp [dist_self],
dist_comm := λ x y, nnreal.coe_eq.2 $
begin
refine reverse_surjective.infi_congr _ (λ l, _),
rw [← sum_reverse, zip_with_distrib_reverse, reverse_append, reverse_reverse,
reverse_singleton, singleton_append, reverse_cons, reverse_reverse,
zip_with_comm_of_comm _ dist_comm],
simp only [length, length_append]
end,
dist_triangle := λ x y z,
begin
rw [← nnreal.coe_add, nnreal.coe_le_coe],
refine nnreal.le_infi_add_infi (λ lxy lyz, _),
calc (⨅ l, (zip_with d (x :: l) (l ++ [z])).sum) ≤
(zip_with d (x :: (lxy ++ y :: lyz)) ((lxy ++ y :: lyz) ++ [z])).sum :
cinfi_le (order_bot.bdd_below _) (lxy ++ y :: lyz)
... = (zip_with d (x :: lxy) (lxy ++ [y])).sum + (zip_with d (y :: lyz) (lyz ++ [z])).sum : _,
rw [← sum_append, ← zip_with_append, cons_append, ← @singleton_append _ y, append_assoc,
append_assoc, append_assoc],
rw [length_cons, length_append, length_singleton]
end }
lemma dist_of_prenndist (d : X → X → ℝ≥0) (dist_self : ∀ x, d x x = 0)
(dist_comm : ∀ x y, d x y = d y x) (x y : X) :
@dist X (@pseudo_metric_space.to_has_dist X
(pseudo_metric_space.of_prenndist d dist_self dist_comm)) x y =
↑(⨅ l : list X, ((x :: l).zip_with d (l ++ [y])).sum : ℝ≥0) := rfl
lemma dist_of_prenndist_le (d : X → X → ℝ≥0) (dist_self : ∀ x, d x x = 0)
(dist_comm : ∀ x y, d x y = d y x) (x y : X) :
@dist X (@pseudo_metric_space.to_has_dist X
(pseudo_metric_space.of_prenndist d dist_self dist_comm)) x y ≤ d x y :=
nnreal.coe_le_coe.2 $ (cinfi_le (order_bot.bdd_below _) []).trans_eq $ by simp
/-- Consider a function `d : X → X → ℝ≥0` such that `d x x = 0` and `d x y = d y x` for all `x`,
`y`. Let `dist` be the largest pseudometric distance such that `dist x y ≤ d x y`, see
`pseudo_metric_space.of_prenndist`. Suppose that `d` satisfies the following triangle-like
inequality: `d x₁ x₄ ≤ 2 * max (d x₁ x₂, d x₂ x₃, d x₃ x₄)`. Then `d x y ≤ 2 * dist x y` for all
`x`, `y`. -/
lemma le_two_mul_dist_of_prenndist (d : X → X → ℝ≥0) (dist_self : ∀ x, d x x = 0)
(dist_comm : ∀ x y, d x y = d y x)
(hd : ∀ x₁ x₂ x₃ x₄, d x₁ x₄ ≤ 2 * max (d x₁ x₂) (max (d x₂ x₃) (d x₃ x₄))) (x y : X) :
↑(d x y) ≤ 2 * @dist X (@pseudo_metric_space.to_has_dist X
(pseudo_metric_space.of_prenndist d dist_self dist_comm)) x y :=
begin
/- We need to show that `d x y` is at most twice the sum `L` of `d xᵢ xᵢ₊₁` over a path
`x₀=x, ..., xₙ=y`. We prove it by induction on the length `n` of the sequence. Find an edge that
splits the path into two parts of almost equal length: both `d x₀ x₁ + ... + d xₖ₋₁ xₖ` and
`d xₖ₊₁ xₖ₊₂ + ... + d xₙ₋₁ xₙ` are less than or equal to `L / 2`.
Then `d x₀ xₖ ≤ L`, `d xₖ xₖ₊₁ ≤ L`, and `d xₖ₊₁ xₙ ≤ L`, thus `d x₀ xₙ ≤ 2 * L`. -/
rw [dist_of_prenndist, ← nnreal.coe_two, ← nnreal.coe_mul, nnreal.mul_infi, nnreal.coe_le_coe],
refine le_cinfi (λ l, _),
have hd₀_trans : transitive (λ x y, d x y = 0),
{ intros a b c hab hbc,
rw ← nonpos_iff_eq_zero,
simpa only [*, max_eq_right, mul_zero] using hd a b c c },
haveI : is_trans X (λ x y, d x y = 0) := ⟨hd₀_trans⟩,
induction hn : length l using nat.strong_induction_on with n ihn generalizing x y l,
simp only at ihn, subst n,
set L := zip_with d (x :: l) (l ++ [y]),
have hL_len : length L = length l + 1, by simp,
cases eq_or_ne (d x y) 0 with hd₀ hd₀, { simp only [hd₀, zero_le] },
rsuffices ⟨z, z', hxz, hzz', hz'y⟩ : ∃ z z' : X, d x z ≤ L.sum ∧ d z z' ≤ L.sum ∧ d z' y ≤ L.sum,
{ exact (hd x z z' y).trans (mul_le_mul_left' (max_le hxz (max_le hzz' hz'y)) _) },
set s : set ℕ := {m : ℕ | 2 * (take m L).sum ≤ L.sum},
have hs₀ : 0 ∈ s, by simp [s],
have hsne : s.nonempty, from ⟨0, hs₀⟩,
obtain ⟨M, hMl, hMs⟩ : ∃ M ≤ length l, is_greatest s M,
{ have hs_ub : length l ∈ upper_bounds s,
{ intros m hm,
rw [← not_lt, nat.lt_iff_add_one_le, ← hL_len],
intro hLm,
rw [mem_set_of_eq, take_all_of_le hLm, two_mul, add_le_iff_nonpos_left, nonpos_iff_eq_zero,
sum_eq_zero_iff, ← all₂_iff_forall, all₂_zip_with, ← chain_append_singleton_iff_forall₂]
at hm; [skip, by simp],
exact hd₀ (hm.rel (mem_append.2 $ or.inr $ mem_singleton_self _)) },
have hs_bdd : bdd_above s, from ⟨length l, hs_ub⟩,
exact ⟨Sup s, cSup_le hsne hs_ub, ⟨nat.Sup_mem hsne hs_bdd, λ k, le_cSup hs_bdd⟩⟩ },
have hM_lt : M < length L, by rwa [hL_len, nat.lt_succ_iff],
have hM_ltx : M < length (x :: l), from lt_length_left_of_zip_with hM_lt,
have hM_lty : M < length (l ++ [y]), from lt_length_right_of_zip_with hM_lt,
refine ⟨(x :: l).nth_le M hM_ltx, (l ++ [y]).nth_le M hM_lty, _, _, _⟩,
{ cases M, { simp [dist_self] },
rw nat.succ_le_iff at hMl,
have hMl' : length (take M l) = M, from (length_take _ _).trans (min_eq_left hMl.le),
simp only [nth_le],
refine (ihn _ hMl _ _ _ hMl').trans _,
convert hMs.1.out,
rw [zip_with_distrib_take, take, take_succ, nth_append hMl, nth_le_nth hMl,
← option.coe_def, option.to_list_some, take_append_of_le_length hMl.le],
refl },
{ refine single_le_sum (λ x hx, zero_le x) _ (mem_iff_nth_le.2 ⟨M, hM_lt, _⟩),
apply nth_le_zip_with },
{ rcases hMl.eq_or_lt with rfl|hMl,
{ simp only [nth_le_append_right le_rfl, sub_self, nth_le_singleton, dist_self, zero_le] },
rw [nth_le_append _ hMl],
have hlen : length (drop (M + 1) l) = length l - (M + 1), from length_drop _ _,
have hlen_lt : length l - (M + 1) < length l, from nat.sub_lt_of_pos_le _ _ M.succ_pos hMl,
refine (ihn _ hlen_lt _ y _ hlen).trans _,
rw [cons_nth_le_drop_succ],
have hMs' : L.sum ≤ 2 * (L.take (M + 1)).sum,
from not_lt.1 (λ h, (hMs.2 h.le).not_lt M.lt_succ_self),
rw [← sum_take_add_sum_drop L (M + 1), two_mul, add_le_add_iff_left,
← add_le_add_iff_right, sum_take_add_sum_drop, ← two_mul] at hMs',
convert hMs',
rwa [zip_with_distrib_drop, drop, drop_append_of_le_length] }
end
end pseudo_metric_space
/-- If `X` is a uniform space with countably generated uniformity filter, there exists a
`pseudo_metric_space` structure compatible with the `uniform_space` structure. Use
`uniform_space.pseudo_metric_space` or `uniform_space.metric_space` instead. -/
protected lemma uniform_space.metrizable_uniformity (X : Type*) [uniform_space X]
[is_countably_generated (𝓤 X)] :
∃ I : pseudo_metric_space X, I.to_uniform_space = ‹_› :=
begin
/- Choose a fast decreasing antitone basis `U : ℕ → set (X × X)` of the uniformity filter `𝓤 X`.
Define `d x y : ℝ≥0` to be `(1 / 2) ^ n`, where `n` is the minimal index of `U n` that separates
`x` and `y`: `(x, y) ∉ U n`, or `0` if `x` is not separated from `y`. This function satisfies the
assumptions of `pseudo_metric_space.of_prenndist` and
`pseudo_metric_space.le_two_mul_dist_of_prenndist`, hence the distance given by the former pseudo
metric space structure is Lipschitz equivalent to the `d`. Thus the uniformities generated by
`d` and `dist` are equal. Since the former uniformity is equal to `𝓤 X`, the latter is equal to
`𝓤 X` as well. -/
classical,
obtain ⟨U, hU_symm, hU_comp, hB⟩ : ∃ U : ℕ → set (X × X), (∀ n, symmetric_rel (U n)) ∧
(∀ ⦃m n⦄, m < n → U n ○ (U n ○ U n) ⊆ U m) ∧ (𝓤 X).has_antitone_basis U,
{ rcases uniform_space.has_seq_basis X with ⟨V, hB, hV_symm⟩,
rcases hB.subbasis_with_rel (λ m, hB.tendsto_small_sets.eventually
(eventually_uniformity_iterate_comp_subset (hB.mem m) 2)) with ⟨φ, hφ_mono, hφ_comp, hφB⟩,
exact ⟨V ∘ φ, λ n, hV_symm _, hφ_comp, hφB⟩ },
letI := uniform_space.separation_setoid X,
set d : X → X → ℝ≥0 := λ x y, if h : ∃ n, (x, y) ∉ U n then (1 / 2) ^ nat.find h else 0,
have hd₀ : ∀ {x y}, d x y = 0 ↔ x ≈ y,
{ intros x y, dsimp only [d],
refine iff.trans _ hB.to_has_basis.mem_separation_rel.symm,
simp only [true_implies_iff],
split_ifs with h,
{ rw [← not_forall] at h, simp [h, pow_eq_zero_iff'] },
{ simpa only [not_exists, not_not, eq_self_iff_true, true_iff] using h } },
have hd_symm : ∀ x y, d x y = d y x,
{ intros x y, dsimp only [d],
simp only [@symmetric_rel.mk_mem_comm _ _ (hU_symm _) x y] },
have hr : (1 / 2 : ℝ≥0) ∈ Ioo (0 : ℝ≥0) 1,
from ⟨nnreal.half_pos one_pos, nnreal.half_lt_self one_ne_zero⟩,
letI I := pseudo_metric_space.of_prenndist d (λ x, hd₀.2 (setoid.refl _)) hd_symm,
have hdist_le : ∀ x y, dist x y ≤ d x y,
from pseudo_metric_space.dist_of_prenndist_le _ _ _,
have hle_d : ∀ {x y : X} {n : ℕ}, (1 / 2) ^ n ≤ d x y ↔ (x, y) ∉ U n,
{ intros x y n,
simp only [d], split_ifs with h,
{ rw [(strict_anti_pow hr.1 hr.2).le_iff_le, nat.find_le_iff],
exact ⟨λ ⟨m, hmn, hm⟩ hn, hm (hB.antitone hmn hn), λ h, ⟨n, le_rfl, h⟩⟩ },
{ push_neg at h,
simp only [h, not_true, (pow_pos hr.1 _).not_le] } },
have hd_le : ∀ x y, ↑(d x y) ≤ 2 * dist x y,
{ refine pseudo_metric_space.le_two_mul_dist_of_prenndist _ _ _ (λ x₁ x₂ x₃ x₄, _),
by_cases H : ∃ n, (x₁, x₄) ∉ U n,
{ refine (dif_pos H).trans_le _,
rw [← nnreal.div_le_iff' two_ne_zero, ← mul_one_div (_ ^ _), ← pow_succ'],
simp only [le_max_iff, hle_d, ← not_and_distrib],
rintro ⟨h₁₂, h₂₃, h₃₄⟩,
refine nat.find_spec H (hU_comp (lt_add_one $ nat.find H) _),
exact ⟨x₂, h₁₂, x₃, h₂₃, h₃₄⟩ },
{ exact (dif_neg H).trans_le (zero_le _) } },
refine ⟨I, uniform_space_eq $ (uniformity_basis_dist_pow hr.1 hr.2).ext hB.to_has_basis _ _⟩,
{ refine λ n hn, ⟨n, hn, λ x hx, (hdist_le _ _).trans_lt _⟩,
rwa [← nnreal.coe_pow, nnreal.coe_lt_coe, ← not_le, hle_d, not_not, prod.mk.eta] },
{ refine λ n hn, ⟨n + 1, trivial, λ x hx, _⟩,
rw [mem_set_of_eq] at hx,
contrapose! hx,
refine le_trans _ ((div_le_iff' (zero_lt_two' ℝ)).2 (hd_le x.1 x.2)),
rwa [← nnreal.coe_two, ← nnreal.coe_div, ← nnreal.coe_pow, nnreal.coe_le_coe, pow_succ',
mul_one_div, nnreal.div_le_iff two_ne_zero, div_mul_cancel _ (two_ne_zero' ℝ≥0),
hle_d, prod.mk.eta] }
end
/-- A `pseudo_metric_space` instance compatible with a given `uniform_space` structure. -/
protected noncomputable def uniform_space.pseudo_metric_space (X : Type*) [uniform_space X]
[is_countably_generated (𝓤 X)] : pseudo_metric_space X :=
(uniform_space.metrizable_uniformity X).some.replace_uniformity $
congr_arg _ (uniform_space.metrizable_uniformity X).some_spec.symm
/-- A `metric_space` instance compatible with a given `uniform_space` structure. -/
protected noncomputable def uniform_space.metric_space (X : Type*) [uniform_space X]
[is_countably_generated (𝓤 X)] [t0_space X] : metric_space X :=
@of_t0_pseudo_metric_space X (uniform_space.pseudo_metric_space X) _
/-- A uniform space with countably generated `𝓤 X` is pseudo metrizable. -/
@[priority 100]
instance uniform_space.pseudo_metrizable_space [uniform_space X] [is_countably_generated (𝓤 X)] :
topological_space.pseudo_metrizable_space X :=
by { letI := uniform_space.pseudo_metric_space X, apply_instance }
/-- A T₀ uniform space with countably generated `𝓤 X` is metrizable. This is not an instance to
avoid loops. -/
lemma uniform_space.metrizable_space [uniform_space X] [is_countably_generated (𝓤 X)] [t0_space X] :
topological_space.metrizable_space X :=
by { letI := uniform_space.metric_space X, apply_instance }
|
e8eaccce7a0703139eb4f448537901f14c6fdfc6 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/roots_of_unity.lean | 9288372fb3cc18810be0eab67e16488978337b35 | [
"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 | 44,516 | 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.polynomial.ring_division
import tactic.zify
import field_theory.separable
import data.zmod.basic
import ring_theory.integral_domain
import number_theory.divisors
import field_theory.finite.basic
import group_theory.specific_groups.cyclic
import algebra.char_p.two
/-!
# 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_zpowers`: `zmod k` is equivalent to
the subgroup generated by a primitive `k`-th root of unity.
* `is_primitive_root.zpowers_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 F : Type*}
variables [comm_monoid M] [comm_monoid N] [comm_group G] [comm_group_with_zero G₀]
section roots_of_unity
variables {k l : ℕ+}
/-- `roots_of_unity k M` is the subgroup of elements `m : Mˣ` that satisfy `m ^ k = 1` -/
def roots_of_unity (k : ℕ+) (M : Type*) [comm_monoid M] : subgroup 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 : ℕ+) (ζ : Mˣ) :
ζ ∈ roots_of_unity k M ↔ ζ ^ (k : ℕ) = 1 := iff.rfl
lemma roots_of_unity.coe_injective {n : ℕ+} : function.injective (coe : (roots_of_unity n M) → M) :=
units.ext.comp (λ x y, subtype.ext)
/-- Make an element of `roots_of_unity` from a member of the base ring, and a proof that it has
a positive power equal to one. -/
@[simps coe_coe] def roots_of_unity.mk_of_pow_eq (ζ : M) {n : ℕ+} (h : ζ ^ (n : ℕ) = 1) :
roots_of_unity n M :=
⟨units.mk_of_mul_eq_one ζ (ζ ^ n.nat_pred) $
by rwa [←pow_one ζ, ←pow_mul, ←pow_add, one_mul, pnat.one_add_nat_pred],
units.ext $ by simpa⟩
@[simp] lemma roots_of_unity.coe_mk_of_pow_eq {ζ : M} {n : ℕ+}
(h : ζ ^ (n : ℕ) = 1) : (roots_of_unity.mk_of_pow_eq _ h : M) = ζ := 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 : Mˣ →* Nˣ) (k : ℕ+) :
(roots_of_unity k M).map f ≤ roots_of_unity k N :=
begin
rintros _ ⟨ζ, h, rfl⟩,
simp only [←map_pow, *, mem_roots_of_unity, set_like.mem_coe, monoid_hom.map_one] at *
end
variables [comm_ring R]
@[norm_cast]
lemma roots_of_unity.coe_pow (ζ : roots_of_unity k R) (m : ℕ) : ↑(ζ ^ m) = (ζ ^ m : R) :=
begin
change ↑(↑(ζ ^ m) : Rˣ) = ↑(ζ : Rˣ) ^ m,
rw [subgroup.coe_pow, units.coe_pow],
end
variables [comm_ring S]
/-- Restrict a ring homomorphism between integral domains to the nth roots of unity -/
def restrict_roots_of_unity [ring_hom_class F R S] (σ : F) (n : ℕ+) :
roots_of_unity n R →* roots_of_unity n S :=
let h : ∀ ξ : roots_of_unity n R, (σ ξ) ^ (n : ℕ) = 1 := λ ξ, by
{ change (σ (ξ : Rˣ)) ^ (n : ℕ) = 1,
rw [←map_pow, ←units.coe_pow, show ((ξ : 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 restrict_roots_of_unity_coe_apply [ring_hom_class F R S] (σ : F)
(ζ : 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 := restrict_roots_of_unity σ.to_ring_hom n,
inv_fun :=restrict_roots_of_unity σ.symm.to_ring_hom n,
left_inv := λ ξ, by { ext, exact σ.symm_apply_apply ξ },
right_inv := λ ξ, by { ext, exact σ.apply_symm_apply ξ },
map_mul' := (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
variables [is_domain R]
lemma mem_roots_of_unity_iff_mem_nth_roots {ζ : 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,
tsub_add_cancel_of_le (show 1 ≤ (k : ℕ), from k.one_le)] },
{ show (_ : 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_is_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}
lemma map_root_of_unity_eq_pow_self [ring_hom_class F R R] (σ : F) (ζ : 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, zpow_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 ζ)))),
zpow_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)
/-- Turn a primitive root μ into a member of the `roots_of_unity` subgroup. -/
@[simps] def is_primitive_root.to_roots_of_unity {μ : M} {n : ℕ+} (h : is_primitive_root μ n) :
roots_of_unity n M := roots_of_unity.mk_of_pow_eq μ h.pow_eq_one
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*) [comm_ring R] [is_domain R] : finset R :=
(nth_roots k (1 : R)).to_finset.filter (λ ζ, is_primitive_root ζ k)
variables [comm_ring R] [is_domain R]
@[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)
@[nontriviality] lemma of_subsingleton [subsingleton M] (x : M) : is_primitive_root x 1 :=
⟨subsingleton.elim _ _, λ _ _, one_dvd _⟩
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, tsub_add_cancel_of_le h0.nat_succ_le, 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 ← tsub_eq_zero_iff_le,
apply nat.eq_zero_of_dvd_of_lt _ (lt_of_le_of_lt tsub_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, tsub_add_cancel_of_le 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 {ζ : 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 ζ, ← zpow_coe_nat ζ, ← hi.gcd_eq_one, nat.gcd_eq_gcd_ab, zpow_add,
mul_pow, ← zpow_coe_nat, ← zpow_mul, mul_right_comm],
simp only [zpow_mul, hl, h.pow_eq_one, one_zpow, one_pow, one_mul, zpow_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
protected lemma order_of (ζ : M) : is_primitive_root ζ (order_of ζ) :=
⟨pow_order_of_eq_one ζ, λ l, order_of_dvd_of_pow_eq_one⟩
lemma unique {ζ : M} (hk : is_primitive_root ζ k) (hl : is_primitive_root ζ l) : k = l :=
begin
wlog hkl : k ≤ l,
rcases hkl.eq_or_lt with rfl | hkl,
{ refl },
rcases k.eq_zero_or_pos with rfl | hk',
{ exact (zero_dvd_iff.mp $ hk.dvd_of_pow_eq_one l hl.pow_eq_one).symm },
exact absurd hk.pow_eq_one (hl.pow_ne_one_of_pos_of_lt hk' hkl)
end
lemma eq_order_of : k = order_of ζ := h.unique (is_primitive_root.order_of ζ)
protected lemma iff (hk : 0 < k) :
is_primitive_root ζ k ↔ ζ ^ k = 1 ∧ ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1 :=
begin
refine ⟨λ h, ⟨h.pow_eq_one, λ l hl' hl, _⟩, λ ⟨hζ, hl⟩, is_primitive_root.mk_of_lt ζ hk hζ hl⟩,
rw h.eq_order_of at hl,
exact pow_ne_one_of_lt_order_of' hl'.ne' hl,
end
protected lemma not_iff : ¬ is_primitive_root ζ k ↔ order_of ζ ≠ k :=
⟨λ h hk, h $ hk ▸ is_primitive_root.order_of ζ,
λ h hk, h.symm $ hk.unique $ is_primitive_root.order_of ζ⟩
lemma pow_of_dvd (h : is_primitive_root ζ k) {p : ℕ} (hp : p ≠ 0) (hdiv : p ∣ k) :
is_primitive_root (ζ ^ p) (k / p) :=
begin
suffices : order_of (ζ ^ p) = k / p,
{ exact this ▸ is_primitive_root.order_of (ζ ^ p) },
rw [order_of_pow' _ hp, ← eq_order_of h, nat.gcd_eq_right hdiv]
end
end comm_monoid
section comm_monoid_with_zero
variables {M₀ : Type*} [comm_monoid_with_zero M₀]
lemma zero [nontrivial M₀] : is_primitive_root (0 : M₀) 0 :=
⟨pow_zero 0, λ l hl, by simpa [zero_pow_eq, show ∀ p, ¬p → false ↔ p, from @not_not] using hl⟩
end comm_monoid_with_zero
section comm_group
variables {ζ : G}
lemma zpow_eq_one (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 :=
by { rw zpow_coe_nat, exact h.pow_eq_one }
lemma zpow_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 [zpow_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, ← zpow_neg, ← hl', zpow_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 zpow_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 zpow_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, ← zpow_neg, ← hi', zpow_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 zpow_eq_one₀ (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 :=
by { rw zpow_coe_nat, exact h.pow_eq_one }
lemma zpow_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 [zpow_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₀, ← zpow_neg₀, ← hl', zpow_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 zpow_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 zpow_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', ← zpow_neg₀, ← hi', zpow_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 comm_semiring
variables [comm_semiring R] [comm_semiring S] {f : F} {ζ : R}
open function
lemma map_of_injective [monoid_hom_class F R S] (h : is_primitive_root ζ k) (hf : injective f) :
is_primitive_root (f ζ) k :=
{ pow_eq_one := by rw [←map_pow, h.pow_eq_one, _root_.map_one],
dvd_of_pow_eq_one := begin
rw h.eq_order_of,
intros l hl,
rw [←map_pow, ←map_one f] at hl,
exact order_of_dvd_of_pow_eq_one (hf hl)
end }
lemma of_map_of_injective [monoid_hom_class F R S] (h : is_primitive_root (f ζ) k)
(hf : injective f) : is_primitive_root ζ k :=
{ pow_eq_one := by { apply_fun f, rw [map_pow, _root_.map_one, h.pow_eq_one] },
dvd_of_pow_eq_one := begin
rw h.eq_order_of,
intros l hl,
apply_fun f at hl,
rw [map_pow, _root_.map_one] at hl,
exact order_of_dvd_of_pow_eq_one hl
end }
lemma map_iff_of_injective [monoid_hom_class F R S] (hf : injective f) :
is_primitive_root (f ζ) k ↔ is_primitive_root ζ k :=
⟨λ h, h.of_map_of_injective hf, λ h, h.map_of_injective hf⟩
end comm_semiring
section is_domain
variables {ζ : R}
variables [comm_ring R] [is_domain 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 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 is_domain
section is_domain
variables [comm_ring R]
variables {ζ : Rˣ} (h : is_primitive_root ζ k)
lemma neg_one (p : ℕ) [nontrivial R] [h : char_p R p] (hp : p ≠ 2) : is_primitive_root (-1 : R) 2 :=
begin
convert is_primitive_root.order_of (-1 : R),
rw [order_of_neg_one, if_neg],
rwa ring_char.eq_iff.mpr h
end
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_zpowers (h : is_primitive_root ζ k) : zmod k ≃+ additive (subgroup.zpowers ζ) :=
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.zpowers ζ),
map_zero' := by { simp only [zpow_zero], refl },
map_add' := by { intros i j, simp only [zpow_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 [zpow_mul, h.pow_eq_one, one_zpow, zpow_coe_nat],
refl
end)⟩)
begin
split,
{ rw add_monoid_hom.injective_iff,
intros i hi,
rw subtype.ext_iff at hi,
have := (h.zpow_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_zpowers_apply_coe_int (i : ℤ) :
h.zmod_equiv_zpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ) :=
add_monoid_hom.lift_of_right_inverse_comp_apply _ _ zmod.int_cast_right_inverse _ _
@[simp] lemma zmod_equiv_zpowers_apply_coe_nat (i : ℕ) :
h.zmod_equiv_zpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ) :=
begin
have : (i : zmod k) = (i : ℤ), by norm_cast,
simp only [this, zmod_equiv_zpowers_apply_coe_int, zpow_coe_nat],
refl
end
@[simp] lemma zmod_equiv_zpowers_symm_apply_zpow (i : ℤ) :
h.zmod_equiv_zpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ)) = i :=
by rw [← h.zmod_equiv_zpowers.symm_apply_apply i, zmod_equiv_zpowers_apply_coe_int]
@[simp] lemma zmod_equiv_zpowers_symm_apply_zpow' (i : ℤ) :
h.zmod_equiv_zpowers.symm ⟨ζ ^ i, i, rfl⟩ = i :=
h.zmod_equiv_zpowers_symm_apply_zpow i
@[simp] lemma zmod_equiv_zpowers_symm_apply_pow (i : ℕ) :
h.zmod_equiv_zpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ)) = i :=
by rw [← h.zmod_equiv_zpowers.symm_apply_apply i, zmod_equiv_zpowers_apply_coe_nat]
@[simp] lemma zmod_equiv_zpowers_symm_apply_pow' (i : ℕ) :
h.zmod_equiv_zpowers.symm ⟨ζ ^ i, i, rfl⟩ = i :=
h.zmod_equiv_zpowers_symm_apply_pow i
/-- 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
variables [is_domain R]
lemma zpowers_eq {k : ℕ+} {ζ : Rˣ} (h : is_primitive_root ζ k) :
subgroup.zpowers ζ = roots_of_unity k R :=
begin
apply set_like.coe_injective,
haveI : fact (0 < (k : ℕ)) := ⟨k.pos⟩,
haveI F : fintype (subgroup.zpowers ζ) := fintype.of_equiv _ (h.zmod_equiv_zpowers).to_equiv,
refine @set.eq_of_subset_of_card_le Rˣ (subgroup.zpowers ζ) (roots_of_unity k R)
F (roots_of_unity.fintype R k)
(subgroup.zpowers_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.zpowers ζ) : fintype.card_congr (h.zmod_equiv_zpowers).to_equiv
end
lemma eq_pow_of_mem_roots_of_unity {k : ℕ+} {ζ ξ : 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.zpowers_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.zpow_eq_one, rw [← coe_coe] at aux,
rw [← zpow_coe_nat, hi₀, ← int.mod_add_div n k, zpow_add, zpow_mul,
aux, one_zpow, 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 : ℕ+} {ζ ξ : 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_zpowers,
haveI F : fintype (subgroup.zpowers ζ) := fintype.of_equiv _ e.to_equiv,
calc fintype.card (roots_of_unity n R)
= fintype.card (subgroup.zpowers ζ) : fintype.card_congr $ by rw h.zpowers_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) :
(primitive_roots k R).card = φ k :=
begin
by_cases h0 : k = 0,
{ simp [h0], },
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 (nat.pos_of_ne_zero 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 (nat.pos_of_ne_zero h0),
h.is_primitive_root_iff (nat.pos_of_ne_zero 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 : ℕ} (h : k ≠ l) :
disjoint (primitive_roots k R) (primitive_roots l R) :=
begin
by_cases hk : k = 0, { simp [hk], },
by_cases hl : l = 0, { simp [hl], },
intro z,
simp only [finset.inf_eq_inter, finset.mem_inter, mem_primitive_roots,
nat.pos_of_ne_zero hk, nat.pos_of_ne_zero hl, iff_def],
rintro ⟨⟨hzk, Hzk⟩, ⟨hzl, Hzl⟩⟩,
apply_rules [h, nat.dvd_antisymm, Hzk, Hzl, hzk, hzl]
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`.
This holds for any `nat`, not just `pnat`, see `nth_roots_one_eq_bUnion_primitive_roots`. -/
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 },
{ intros i hi j hj hdiff,
exact disjoint 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 : ℕ}
(h : is_primitive_root ζ n) :
nth_roots_finset n R = (nat.divisors n).bUnion (λ i, (primitive_roots i R)) :=
begin
by_cases hn : n = 0,
{ simp [hn], },
exact @nth_roots_one_eq_bUnion_primitive_roots' _ _ _ _ ⟨n, nat.pos_of_ne_zero hn⟩ h
end
end is_domain
section minpoly
open minpoly
section comm_ring
variables {n : ℕ} {K : Type*} [comm_ring 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
end comm_ring
variables {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n)
include n μ h hpos
variables [char_zero K]
omit hpos
/--The minimal polynomial of a root of unity `μ` divides `X ^ n - 1`. -/
lemma minpoly_dvd_X_pow_sub_one : minpoly ℤ μ ∣ X ^ n - 1 :=
begin
by_cases hpos : n = 0, { simp [hpos], },
apply minpoly.gcd_domain_dvd ℚ (is_integral h (nat.pos_of_ne_zero hpos))
(polynomial.monic.is_primitive (monic_X_pow_sub_C 1 (ne_of_lt (nat.pos_of_ne_zero 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 [polynomial.map_pow, map_X, polynomial.map_one, polynomial.map_sub] using
ring_hom.map_dvd (map_ring_hom (int.cast_ring_hom (zmod p)))
(minpoly_dvd_X_pow_sub_one h) },
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 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 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
by_cases hn : n = 0, { simp * at *, },
have hpos := nat.pos_of_ne_zero hn,
apply minpoly.gcd_domain_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, polynomial.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],
rw [hfrob],
apply ring_hom.map_dvd (map_ring_hom (int.cast_ring_hom (zmod p))),
exact minpoly_dvd_expand h 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
hdiv) hprime.1.ne_zero).1 (minpoly_dvd_pow_mod h 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_cases hn : n = 0, { simp * at *, },
have hpos := nat.pos_of_ne_zero hn,
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), polynomial.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 (Pirr.dvd_symm Qirr hdiv) },
{ apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic).2,
exact minpoly_dvd_X_pow_sub_one h },
{ 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) } },
replace prod := ring_hom.map_dvd ((map_ring_hom (int.cast_ring_hom (zmod p)))) prod,
rw [coe_map_ring_hom, polynomial.map_mul, polynomial.map_sub,
polynomial.map_one, polynomial.map_pow, map_X] at prod,
obtain ⟨R, hR⟩ := minpoly_dvd_mod_p h hdiv,
rw [hR, ← mul_assoc, ← polynomial.map_mul, ← sq, polynomial.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)),
{ exact (separable_X_pow_sub_C 1
(λ h, hdiv $ (zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 h) one_ne_zero).squarefree },
cases (multiplicity.squarefree_iff_multiplicity_le_one (X ^ n - 1)).1 hfree
(map (int.cast_ring_hom (zmod p)) P) with hle hunit,
{ rw nat.cast_one at habs, exact hle.not_lt habs },
{ replace hunit := degree_eq_zero_of_is_unit hunit,
rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom (zmod p)) _ at hunit,
{ exact (minpoly.degree_pos (is_integral h hpos)).ne' 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,
congr,
simpa [(nat.coprime_zero_left n).mp hn] using h },
{ intros u hunit n hcop h,
congr,
simp [nat.is_unit_iff.mp hunit] },
{ intros a p ha hprime hind n hcop h,
rw hind (nat.coprime.coprime_mul_left hcop) h, clear hind,
replace hprime := nat.prime_iff.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)) 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 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
by_cases hn : n = 0, { simp * at *, },
have hpos := nat.pos_of_ne_zero hn,
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 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.symm
... ≤ P_K.roots.to_finset.card : finset.card_le_of_subset (is_roots_of_minpoly h)
... ≤ P_K.roots.card : multiset.to_finset_card_le _
... ≤ P_K.nat_degree : card_roots' _
... ≤ P.nat_degree : nat_degree_map_le _ _
end minpoly
end is_primitive_root
|
efa2da2a98f5c514bff983d66cca8afe6dbadba5 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/set_theory/cardinal.lean | c99e2b194898ad47a1a5ed44e4aadcc3fc683d7a | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 56,564 | 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, Floris van Doorn
-/
import data.set.countable
import set_theory.schroeder_bernstein
import data.fintype.card
import data.nat.enat
/-!
# Cardinal Numbers
We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity.
## Main definitions
* `cardinal` the type of cardinal numbers (in a given universe).
* `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale
`cardinal`.
* There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`.
* Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`.
* Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`.
* The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`.
* Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`.
* `cardinal.omega` the cardinality of `ℕ`. This definition is universe polymorphic:
`cardinal.omega.{u} : cardinal.{u}`
(contrast with `ℕ : Type`, which lives in a specific universe).
In some cases the universe level has to be given explicitly.
* `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`.
* `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`.
* `cardinal.sum` is the sum of a collection of cardinals.
* `cardinal.sup` is the supremum of a collection of cardinals.
* `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`.
## Main Statements
* Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`.
* König's theorem: `cardinal.sum_lt_prod`
## Implementation notes
* There is a type of cardinal numbers in every universe level:
`cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`.
The operation `cardinal.lift` lifts cardinal numbers to a higher level.
* Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file
`set_theory/cardinal_ordinal.lean`.
* There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both
the base and the exponent live in the same universe. As a workaround, you can add
```
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
```
to a file. This notation will work even if Lean doesn't know yet that the base and the exponent
live in the same universe (but no exponents in other types can be used).
## References
* <https://en.wikipedia.org/wiki/Cardinal_number>
## Tags
cardinal number, cardinal arithmetic, cardinal exponentiation, omega,
Cantor's theorem, König's theorem, Konig's theorem
-/
open function set
open_locale classical
universes u v w x
variables {α β : Type u}
/-- The equivalence relation on types given by equivalence (bijective correspondence) of types.
Quotienting by this equivalence relation gives the cardinal numbers.
-/
instance cardinal.is_equivalent : setoid (Type u) :=
{ r := λα β, nonempty (α ≃ β),
iseqv := ⟨λα,
⟨equiv.refl α⟩,
λα β ⟨e⟩, ⟨e.symm⟩,
λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `cardinal.{u}` is the type of cardinal numbers in `Type u`,
defined as the quotient of `Type u` by existence of an equivalence
(a bijection with explicit inverse). -/
def cardinal : Type (u + 1) := quotient cardinal.is_equivalent
namespace cardinal
/-- The cardinal number of a type -/
def mk : Type u → cardinal := quotient.mk
localized "notation `#` := cardinal.mk" in cardinal
protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq
@[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl
@[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _
/-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if
there exists an embedding (injective function) from α to β. -/
instance : has_le cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $
assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩
theorem le_def (α β : Type u) : mk α ≤ mk β ↔ nonempty (α ↪ β) :=
iff.rfl
theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β :=
⟨⟨f, hf⟩⟩
theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α :=
⟨embedding.of_surjective f hf⟩
theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} :
c ≤ mk α ↔ ∃ p : set α, mk p = c :=
⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩,
⟨set.range f, eq.symm $ quot.sound ⟨equiv.of_injective f hf⟩⟩,
λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩
theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) :=
by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl }
protected lemma eq_congr : α ≃ β → # α = # β :=
λ h, quot.sound ⟨h⟩
noncomputable instance : linear_order cardinal.{u} :=
{ le := (≤),
le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩,
le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩,
le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂),
le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total,
decidable_le := classical.dec_rel _ }
-- short-circuit type class inference
noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance
instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩
instance : inhabited cardinal.{u} := ⟨0⟩
@[simp]
lemma eq_zero_of_is_empty {α : Type u} [is_empty α] : mk α = 0 :=
quotient.sound ⟨equiv.equiv_pempty α⟩
lemma eq_zero_iff_is_empty {α : Type u} : mk α = 0 ↔ is_empty α :=
⟨λ e, let ⟨h⟩ := quotient.exact e in
equiv.equiv_empty_equiv α $ h.trans equiv.empty_equiv_pempty.symm,
@eq_zero_of_is_empty _⟩
theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α :=
(not_iff_not.2 eq_zero_iff_is_empty).trans not_is_empty_iff
instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩
instance : nontrivial cardinal.{u} :=
⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩
theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α :=
⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩,
λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩
theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α :=
by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp }
instance : has_add cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩
@[simp] theorem add_def (α β : Type u) : mk α + mk β = mk (α ⊕ β) := rfl
instance : has_mul cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩
@[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl
private theorem add_comm (a b : cardinal.{u}) : a + b = b + a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩
private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩
private theorem zero_add (a : cardinal.{u}) : 0 + a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.empty_sum pempty α⟩
private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩
private theorem one_mul (a : cardinal.{u}) : 1 * a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩
private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} :
a * b = 0 → a = 0 ∨ b = 0 :=
begin
refine quotient.induction_on b _,
refine quotient.induction_on a _,
intros a b h,
contrapose h,
simp_rw [not_or_distrib, ← ne.def] at h,
have := @prod.nonempty a b (ne_zero_iff_nonempty.mp h.1) (ne_zero_iff_nonempty.mp h.2),
exact ne_zero_iff_nonempty.mpr this
end
instance : comm_semiring cardinal.{u} :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
zero_add := zero_add,
add_zero := assume a, by rw [add_comm a 0, zero_add a],
add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_assoc α β γ⟩,
add_comm := add_comm,
zero_mul := zero_mul,
mul_zero := assume a, by rw [mul_comm a 0, zero_mul a],
one_mul := one_mul,
mul_one := assume a, by rw [mul_comm a 1, one_mul a],
mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.prod_assoc α β γ⟩,
mul_comm := mul_comm,
left_distrib := left_distrib,
right_distrib := assume a b c,
by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] }
/-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/
protected def power (a b : cardinal.{u}) : cardinal.{u} :=
quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩
instance : has_pow cardinal cardinal := ⟨cardinal.power⟩
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
@[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl
@[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.pempty_arrow_equiv_punit α⟩
@[simp] theorem power_one {a : cardinal} : a ^ 1 = a :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.punit_arrow_equiv α⟩
@[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.arrow_punit_equiv_punit α⟩
@[simp] theorem prop_eq_two : mk (ulift Prop) = 2 :=
quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 :=
quotient.induction_on a $ assume α heq,
(ne_zero_iff_nonempty.1 heq).elim $ assume a,
by { haveI : nonempty α := ⟨a⟩, exact quotient.sound ⟨equiv.equiv_pempty _⟩ }
theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 :=
quotient.induction_on₂ a b $ λ α β h,
let ⟨a⟩ := ne_zero_iff_nonempty.1 h in
ne_zero_iff_nonempty.2 ⟨λ _, a⟩
theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩
theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩
theorem power_mul {a b c : cardinal} : a ^ (b * c) = (a ^ b) ^ c :=
by rw [_root_.mul_comm b c];
from (quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.curry γ β α⟩)
@[simp] lemma pow_cast_right (κ : cardinal.{u}) :
∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n
| 0 := by simp
| (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right]
section order_properties
open sum
protected theorem zero_le : ∀(a : cardinal), 0 ≤ a :=
by rintro ⟨α⟩; exact ⟨embedding.of_is_empty⟩
protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩
protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c :=
cardinal.add_le_add (le_refl _)
protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c :=
⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩,
have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from
(equiv.sum_congr (equiv.of_injective f hf) (equiv.refl _)).trans $
(equiv.set.sum_compl (range f)),
⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩,
λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩
instance : order_bot cardinal.{u} :=
{ bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order }
instance : canonically_ordered_comm_semiring cardinal.{u} :=
{ add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h,
le_iff_exists_add := @cardinal.le_iff_exists_add,
eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero,
..cardinal.order_bot,
..cardinal.comm_semiring, ..cardinal.linear_order }
noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} :=
{ .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}),
.. cardinal.linear_order }
@[simp] theorem zero_lt_one : (0 : cardinal) < 1 :=
lt_of_le_of_ne (zero_le _) zero_ne_one
lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 :=
by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le }
theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact
let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in
⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩
theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 :=
begin
by_cases ha : a = 0,
simp [ha, zero_power_le],
exact le_trans (power_le_power_left ha h) (le_max_left _ _)
end
theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩
end order_properties
/-- **Cantor's theorem** -/
theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a :=
by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨
⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩,
λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $
λ s t h, by funext a; injection congr_fun (hf h) a⟩
instance : no_top_order cardinal.{u} :=
{ no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order }
/-- The minimum cardinal in a family of cardinals (the existence
of which is provided by `injective_min`). -/
noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal :=
f $ classical.some $
@embedding.min_injective _ (λ i, (f i).out) I
theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i :=
⟨_, rfl⟩
theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i :=
by rw [← mk_out (min I f), ← mk_out (f i)]; exact
let ⟨g⟩ := classical.some_spec
(@embedding.min_injective _ (λ i, (f i).out) I) in
⟨g i⟩
theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i :=
⟨λ h i, le_trans h (min_le _ _),
λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩
protected theorem wf : @well_founded cardinal.{u} (<) :=
⟨λ a, classical.by_contradiction $ λ h,
let ι := {c :cardinal // ¬ acc (<) c},
f : ι → cardinal := subtype.val,
⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in
hc (acc.intro _ (λ j ⟨_, h'⟩,
classical.by_contradiction $ λ hj, h' $
by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩
instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩
instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩
/-- The successor cardinal - the smallest cardinal greater than
`c`. This is not the same as `c + 1` except in the case of finite `c`. -/
noncomputable def succ (c : cardinal) : cardinal :=
@min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val
theorem lt_succ_self (c : cardinal) : c < succ c :=
by cases min_eq _ _ with s e; rw [succ, e]; exact s.2
theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (lt_succ_self _), λ h,
by exact min_le _ (subtype.mk b h)⟩
theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c :=
begin
refine quot.induction_on c (λ α, _) (lt_succ_self c),
refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _),
cases h.left with f,
have : ¬ surjective f := λ hn,
ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩),
cases not_forall.1 this with b nex,
refine ⟨⟨sum.rec (by exact f) _, _⟩⟩,
{ exact λ _, b },
{ intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩,
{ rw f.injective h },
{ exact nex.elim ⟨_, h⟩ },
{ exact nex.elim ⟨_, h.symm⟩ },
{ refl } }
end
lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 :=
by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le }
/-- The indexed sum of cardinals is the cardinality of the
indexed disjoint union, i.e. sigma type. -/
def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out
theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f :=
by rw ← quotient.out_eq (f i); exact
⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩
@[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) :=
quot.sound ⟨equiv.sigma_congr_right $ λ i,
classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩
theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a :=
quotient.induction_on a $ λ α, by simp; exact
quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩
theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g :=
⟨(embedding.refl _).sigma_map $ λ i, classical.choice $
by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩
/-- The indexed supremum of cardinals is the smallest cardinal above
everything in the family. -/
noncomputable def sup {ι} (f : ι → cardinal) : cardinal :=
@min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1)
theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f :=
by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i
theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h,
λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩
theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g :=
sup_le.2 $ λ i, le_trans (H i) (le_sup _ _)
theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f :=
sup_le.2 $ le_sum _
theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f :=
by rw ← sum_const; exact sum_le_sum _ _ (le_sup _)
theorem sup_eq_zero {ι} {f : ι → cardinal} [is_empty ι] : sup f = 0 :=
by { rw [← nonpos_iff_eq_zero, sup_le], exact is_empty_elim }
/-- The indexed product of cardinals is the cardinality of the Pi type
(dependent product). -/
def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out)
@[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) :=
quot.sound ⟨equiv.Pi_congr_right $ λ i,
classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩
theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι :=
quotient.induction_on a $ by simp
theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g :=
⟨embedding.Pi_congr_right $ λ i, classical.choice $
by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩
theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 :=
begin
suffices : nonempty (Π i, (f i).out) ↔ ∀ i, nonempty (f i).out,
{ simpa [← ne_zero_iff_nonempty, prod] },
exact classical.nonempty_pi
end
theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 :=
not_iff_not.1 $ by simpa using prod_ne_zero f
/-- The universe lift operation on cardinals. You can specify the universes explicitly with
`lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/
def lift (c : cardinal.{u}) : cardinal.{max u v} :=
quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩,
quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩
theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ λ a, quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_id' (a : cardinal) : lift a = a :=
quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : cardinal) :
lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_mk_le {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) :=
⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩,
λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩
/-- A variant of `lift_mk_le` with specialized universes.
Because Lean often can not realize it should use this specialization itself,
we provide this statement separately so you don't have to solve the specialization problem either.
-/
theorem lift_mk_le' {α : Type u} {β : Type v} :
lift.{u v} (mk α) ≤ lift.{v u} (mk β) ↔ nonempty (α ↪ β) :=
lift_mk_le.{u v 0}
theorem lift_mk_eq {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩,
λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩
/-- A variant of `lift_mk_eq` with specialized universes.
Because Lean often can not realize it should use this specialization itself,
we provide this statement separately so you don't have to solve the specialization problem either.
-/
theorem lift_mk_eq' {α : Type u} {β : Type v} :
lift.{u v} (mk α) = lift.{v u} (mk β) ↔ nonempty (α ≃ β) :=
lift_mk_eq.{u v 0}
@[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b :=
quotient.induction_on₂ a b $ λ α β,
by rw ← lift_umax; exact lift_mk_le
@[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b :=
by simp [le_antisymm_iff]
@[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a :=
by simp [bit0]
@[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) :=
le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $
let ⟨i, e⟩ := min_eq I (lift ∘ f) in
by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $
by have := min_le (lift ∘ f) j; rwa e at this)
theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a → ∃ a', lift a' = b :=
quotient.induction_on₂ a b $ λ α β,
by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact
λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2
⟨embedding.equiv_of_surjective
(embedding.cod_restrict _ f set.mem_range_self)
$ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩
theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a :=
⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩
theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b < lift a ↔ ∃ a', lift a' = b ∧ a' < a :=
⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
⟨a', e, lift_lt.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
le_antisymm
(le_of_not_gt $ λ h, begin
rcases lt_lift_iff.1 h with ⟨b, e, h⟩,
rw [lt_succ, ← lift_le, e] at h,
exact not_lt_of_le h (lt_succ_self _)
end)
(succ_le.2 $ lift_lt.2 $ lt_succ_self _)
@[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} :
lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b :=
calc lift.{u (max v w)} a = lift.{v (max u w)} b
↔ lift.{(max u v) w} (lift.{u v} a)
= lift.{(max u v) w} (lift.{v u} b) : by simp
... ↔ lift.{u v} a = lift.{v u} b : lift_inj
theorem mk_prod {α : Type u} {β : Type v} :
mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) :=
quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩
theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) :
sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a :=
begin
apply quotient.induction_on a,
intro α,
simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id],
convert mk_prod using 1,
exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩,
end
protected lemma le_sup_iff {ι : Type v} {f : ι → cardinal.{max v w}} {c : cardinal} :
(c ≤ sup f) ↔ (∀ b, (∀ i, f i ≤ b) → c ≤ b) :=
⟨λ h b hb, le_trans h (sup_le.mpr hb), λ h, h _ $ λ i, le_sup f i⟩
/-- The lift of a supremum is the supremum of the lifts. -/
lemma lift_sup {ι : Type v} (f : ι → cardinal.{max v w}) :
lift.{(max v w) u} (sup.{v w} f) =
sup.{v (max u w)} (λ i : ι, lift.{(max v w) u} (f i)) :=
begin
apply le_antisymm,
{ rw [cardinal.le_sup_iff], intros c hc, by_contra h,
obtain ⟨d, rfl⟩ := cardinal.lift_down (not_le.mp h).le,
simp only [lift_le, sup_le] at h hc,
exact h hc },
{ simp only [cardinal.sup_le, lift_le, le_sup, implies_true_iff] }
end
/-- To prove that the lift of a supremum is bounded by some cardinal `t`,
it suffices to show that the lift of each cardinal is bounded by `t`. -/
lemma lift_sup_le {ι : Type v} (f : ι → cardinal.{max v w})
(t : cardinal.{max u v w}) (w : ∀ i, lift.{_ u} (f i) ≤ t) :
lift.{(max v w) u} (sup f) ≤ t :=
by { rw lift_sup, exact sup_le.mpr w, }
@[simp] lemma lift_sup_le_iff {ι : Type v} (f : ι → cardinal.{max v w}) (t : cardinal.{max u v w}) :
lift.{(max v w) u} (sup f) ≤ t ↔ ∀ i, lift.{_ u} (f i) ≤ t :=
⟨λ h i, (lift_le.mpr (le_sup f i)).trans h,
λ h, lift_sup_le f t h⟩
universes v' w'
/--
To prove an inequality between the lifts to a common universe of two different supremums,
it suffices to show that the lift of each cardinal from the smaller supremum
if bounded by the lift of some cardinal from the larger supremum.
-/
lemma lift_sup_le_lift_sup
{ι : Type v} {ι' : Type v'} (f : ι → cardinal.{max v w}) (f' : ι' → cardinal.{max v' w'})
(g : ι → ι') (h : ∀ i, lift.{_ (max v' w')} (f i) ≤ lift.{_ (max v w)} (f' (g i))) :
lift.{_ (max v' w')} (sup f) ≤ lift.{_ (max v w)} (sup f') :=
begin
apply lift_sup_le.{(max v' w')} f,
intro i,
apply le_trans (h i),
simp only [lift_le],
apply le_sup,
end
/-- A variant of `lift_sup_le_lift_sup` with universes specialized via `w = v` and `w' = v'`.
This is sometimes necessary to avoid universe unification issues. -/
lemma lift_sup_le_lift_sup'
{ι : Type v} {ι' : Type v'} (f : ι → cardinal.{v}) (f' : ι' → cardinal.{v'})
(g : ι → ι') (h : ∀ i, lift.{_ v'} (f i) ≤ lift.{_ v} (f' (g i))) :
lift.{_ v'} (sup.{v v} f) ≤ lift.{_ v} (sup.{v' v'} f') :=
lift_sup_le_lift_sup f f' g h
/-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/
def omega : cardinal.{u} := lift (mk ℕ)
lemma mk_nat : mk nat = omega := (lift_id _).symm
theorem omega_ne_zero : omega ≠ 0 :=
ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩
theorem omega_pos : 0 < omega :=
pos_iff_ne_zero.2 omega_ne_zero
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
/- properties about the cast from nat -/
@[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n
| 0 := quotient.sound ⟨equiv.equiv_pempty _⟩
| (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact
quotient.sound (fintype.card_eq.1 $ by simp)
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n; simp *
lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} :
(n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp
theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α :=
by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}];
exact fintype.card_eq.1 (by simp)
theorem card_le_of_finset {α} (s : finset α) :
(s.card : cardinal) ≤ cardinal.mk α :=
begin
rw (_ : (s.card : cardinal) = cardinal.mk s),
{ exact ⟨function.embedding.subtype _⟩ },
rw [cardinal.fintype_card, fintype.card_coe]
end
@[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n :=
by induction n; simp [pow_succ', -_root_.add_comm, power_add, *]
@[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n :=
by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact
⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf,
λ h, ⟨(fin.cast_le h).to_embedding⟩⟩
@[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n :=
by simp [lt_iff_le_not_le, -not_le]
@[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n :=
by simp [le_antisymm_iff]
@[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n :=
le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _)
@[simp] theorem succ_zero : succ 0 = 1 :=
by norm_cast
theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) :
# α ≤ n :=
begin
refine lt_succ.1 (lt_of_not_ge $ λ hn, _),
rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn,
cases hn with f,
refine not_lt_of_le (H $ finset.univ.map f) _,
rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin],
exact n.lt_succ_self
end
theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a :=
by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb;
exact lt_of_lt_of_le (cantor _) (power_le_power_right hb)
theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega :=
succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact
⟨⟨coe, λ a b, fin.ext⟩⟩
@[simp] theorem one_lt_omega : 1 < omega :=
by simpa using nat_lt_omega 1
theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n :=
⟨λ h, begin
rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩,
rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩,
suffices : finite S,
{ cases this, resetI,
existsi fintype.card S,
rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] },
by_contra nf,
have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a :=
λ n IH,
let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in
not_forall.1 (λ h, nf
⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩),
let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)),
refine not_le_of_lt h' ⟨⟨F, _⟩⟩,
suffices : ∀ (n : ℕ) (m < n), F m ≠ F n,
{ refine λ m n, not_imp_not.1 (λ ne, _),
rcases lt_trichotomy m n with h|h|h,
{ exact this n m h },
{ contradiction },
{ exact (this m n h).symm } },
intros n m h,
have := classical.some_spec (P n (λ y _, F y)),
rw [← show F n = classical.some (P n (λ y _, F y)),
from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this,
exact λ e, this ⟨m, h, e⟩,
end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩
theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ h, le_of_not_lt $ λ hn, begin
rcases lt_omega.1 hn with ⟨n, rfl⟩,
exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1)))
end⟩
theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) :=
lt_omega.trans ⟨λ ⟨n, e⟩, begin
rw [← lift_mk_fin n] at e,
cases quotient.exact e with f,
exact ⟨fintype.of_equiv _ f.symm⟩
end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩
theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S :=
lt_omega_iff_fintype
instance can_lift_cardinal_nat : can_lift cardinal ℕ :=
⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩
theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega :=
⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩,
λ⟨h1, h2⟩, add_lt_omega h1 h2⟩
theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega
end
lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega :=
begin
split,
{ intro h, by_cases ha : a = 0, { left, exact ha },
right, by_cases hb : b = 0, { left, exact hb },
right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split,
{ rw [← mul_one a],
refine lt_of_le_of_lt (mul_le_mul' (le_refl a) hb) h },
{ rw [← _root_.one_mul b],
refine lt_of_le_of_lt (mul_le_mul' ha (le_refl b)) h }},
rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero]
end
lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) :
a * b < omega ↔ a < omega ∧ b < omega :=
by simp [mul_lt_omega_iff, ha, hb]
theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega
end
lemma eq_one_iff_unique {α : Type*} :
mk α = 1 ↔ subsingleton α ∧ nonempty α :=
calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt
... ↔ subsingleton α ∧ nonempty α :
begin
apply and_congr le_one_iff_subsingleton,
push_neg,
rw [one_le_iff_ne_zero, ne_zero_iff_nonempty]
end
theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α :=
by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_iff, is_empty_fintype]
lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega :=
⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩,
λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩
lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega :=
begin
rw [countable_iff_exists_injective], split,
rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩,
rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩
end
/-- This function sends finite cardinals to the corresponding natural, and infinite cardinals
to 0. -/
noncomputable def to_nat : zero_hom cardinal ℕ :=
⟨λ c, if h : c < omega.{v} then classical.some (lt_omega.1 h) else 0,
begin
have h : 0 < omega := nat_lt_omega 0,
rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_omega.1 h), nat.cast_zero],
end⟩
lemma to_nat_apply_of_lt_omega {c : cardinal} (h : c < omega) :
c.to_nat = classical.some (lt_omega.1 h) :=
dif_pos h
@[simp]
lemma to_nat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) :
c.to_nat = 0 :=
dif_neg (not_lt_of_le h)
@[simp]
lemma cast_to_nat_of_lt_omega {c : cardinal} (h : c < omega) :
↑c.to_nat = c :=
by rw [to_nat_apply_of_lt_omega h, ← classical.some_spec (lt_omega.1 h)]
@[simp]
lemma cast_to_nat_of_omega_le {c : cardinal} (h : omega ≤ c) :
↑c.to_nat = (0 : cardinal) :=
by rw [to_nat_apply_of_omega_le h, nat.cast_zero]
@[simp]
lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n :=
begin
rw [to_nat_apply_of_lt_omega (nat_lt_omega n), ← nat_cast_inj],
exact (classical.some_spec (lt_omega.1 (nat_lt_omega n))).symm,
end
/-- `to_nat` has a right-inverse: coercion. -/
lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast
lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective
lemma nat_cast_injective : injective (coe : ℕ → cardinal) :=
to_nat_right_inverse.left_inverse.injective
@[simp]
lemma mk_to_nat_of_infinite [h : infinite α] : (mk α).to_nat = 0 :=
dif_neg (not_lt_of_le (infinite_iff.1 h))
@[simp]
lemma mk_to_nat_eq_card [fintype α] : (mk α).to_nat = fintype.card α :=
by simp [fintype_card]
@[simp]
lemma zero_to_nat : cardinal.to_nat 0 = 0 :=
by rw [← to_nat_cast 0, nat.cast_zero]
@[simp]
lemma one_to_nat : cardinal.to_nat 1 = 1 :=
by rw [← to_nat_cast 1, nat.cast_one]
lemma to_nat_mul (x y : cardinal) : (x * y).to_nat = x.to_nat * y.to_nat :=
begin
by_cases hx1 : x = 0,
{ rw [comm_semiring.mul_comm, hx1, mul_zero, zero_to_nat, nat.zero_mul] },
by_cases hy1 : y = 0,
{ rw [hy1, zero_to_nat, mul_zero, mul_zero, zero_to_nat] },
refine nat_cast_injective (eq.trans _ (nat.cast_mul _ _).symm),
cases lt_or_ge x omega with hx2 hx2,
{ cases lt_or_ge y omega with hy2 hy2,
{ rw [cast_to_nat_of_lt_omega, cast_to_nat_of_lt_omega hx2, cast_to_nat_of_lt_omega hy2],
exact mul_lt_omega hx2 hy2 },
{ rw [cast_to_nat_of_omega_le hy2, mul_zero, cast_to_nat_of_omega_le],
exact not_lt.mp (mt (mul_lt_omega_iff_of_ne_zero hx1 hy1).mp (λ h, not_lt.mpr hy2 h.2)) } },
{ rw [cast_to_nat_of_omega_le hx2, _root_.zero_mul, cast_to_nat_of_omega_le],
exact not_lt.mp (mt (mul_lt_omega_iff_of_ne_zero hx1 hy1).mp (λ h, not_lt.mpr hx2 h.1)) },
end
/-- This function sends finite cardinals to the corresponding natural, and infinite cardinals
to `⊤`. -/
noncomputable def to_enat : cardinal →+ enat :=
{ to_fun := λ c, if c < omega.{v} then c.to_nat else ⊤,
map_zero' := by simp [if_pos (lt_trans zero_lt_one one_lt_omega)],
map_add' := λ x y, begin
by_cases hx : x < omega,
{ obtain ⟨x0, rfl⟩ := lt_omega.1 hx,
by_cases hy : y < omega,
{ obtain ⟨y0, rfl⟩ := lt_omega.1 hy,
simp only [add_lt_omega hx hy, hx, hy, to_nat_cast, if_true],
rw [← nat.cast_add, to_nat_cast, nat.cast_add] },
{ rw [if_neg hy, if_neg, enat.add_top],
contrapose! hy,
apply lt_of_le_of_lt le_add_self hy } },
{ rw [if_neg hx, if_neg, enat.top_add],
contrapose! hx,
apply lt_of_le_of_lt le_self_add hx },
end }
@[simp]
lemma to_enat_apply_of_lt_omega {c : cardinal} (h : c < omega) :
c.to_enat = c.to_nat :=
if_pos h
@[simp]
lemma to_enat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) :
c.to_enat = ⊤ :=
if_neg (not_lt_of_le h)
@[simp]
lemma to_enat_cast (n : ℕ) : cardinal.to_enat n = n :=
by rw [to_enat_apply_of_lt_omega (nat_lt_omega n), to_nat_cast]
@[simp]
lemma mk_to_enat_of_infinite [h : infinite α] : (mk α).to_enat = ⊤ :=
to_enat_apply_of_omega_le (infinite_iff.1 h)
lemma to_enat_surjective : surjective to_enat :=
begin
intro x,
exact enat.cases_on x ⟨omega, to_enat_apply_of_omega_le (le_refl omega)⟩
(λ n, ⟨n, to_enat_cast n⟩),
end
@[simp]
lemma mk_to_enat_eq_coe_card [fintype α] : (mk α).to_enat = fintype.card α :=
by simp [fintype_card]
lemma mk_int : mk ℤ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma mk_pnat : mk ℕ+ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y :=
begin
split,
{ rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h },
{ rintro ⟨x, y, h⟩, by_contra h',
rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h',
apply h, exactI subsingleton.elim _ _ }
end
lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y :=
begin
rw [two_le_iff],
split,
{ rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩),
rw [←h'] at h, exact ⟨z, h⟩ },
{ rintro ⟨y, h⟩, exact ⟨x, y, h⟩ }
end
/-- **König's theorem** -/
theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g :=
lt_of_not_ge $ λ ⟨F⟩, begin
have : inhabited (Π (i : ι), (g i).out),
{ refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩,
rw mk_out,
exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI,
let G := inv_fun F,
have sG : surjective G := inv_fun_surjective F.2,
choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b,
{ assume i,
simp only [- not_exists, not_exists.symm, not_forall.symm],
refine λ h, not_le_of_lt (H i) _,
rw [← mk_out (f i), ← mk_out (g i)],
exact ⟨embedding.of_surjective _ h⟩ },
exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _))
end
@[simp] theorem mk_empty : mk empty = 0 :=
fintype_card empty
@[simp] theorem mk_pempty : mk pempty = 0 :=
fintype_card pempty
@[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 :=
by { haveI : is_empty p := ⟨h⟩, exact quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty _⟩ }
theorem mk_unit : mk unit = 1 :=
(fintype_card unit).trans nat.cast_one
@[simp] theorem mk_punit : mk punit = 1 :=
(fintype_card punit).trans nat.cast_one
@[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 :=
quotient.sound ⟨equiv.set.singleton x⟩
@[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 :=
quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩
@[simp] theorem mk_bool : mk bool = 2 :=
quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem mk_Prop : mk Prop = 2 :=
(quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool
@[simp] theorem mk_set {α : Type u} : mk (set α) = 2 ^ mk α :=
begin
rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq],
exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩,
end
@[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 :=
quotient.sound ⟨equiv.option_equiv_sum_punit α⟩
theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :=
calc mk (list α)
= mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩
... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩
... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩
... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :
by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk]
theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α :=
mk_le_of_surjective quot.exists_rep
theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α :=
mk_quot_le
theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α :=
⟨embedding.subtype p⟩
theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) :
mk (subtype p) ≤ mk (subtype q) :=
⟨embedding.subtype_map (embedding.refl α) h⟩
@[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 :=
quotient.sound ⟨equiv.set.pempty α⟩
lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ :=
begin
split,
{ intro h,
have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h],
refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _),
rcases cardinal.eq.mp h2 with ⟨f, _⟩,
cases f ⟨_, hx⟩ },
{ intro, convert mk_emptyc _ }
end
theorem mk_univ {α : Type u} : mk (@univ α) = mk α :=
quotient.sound ⟨equiv.set.univ α⟩
theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s :=
mk_le_of_surjective surjective_onto_image
theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} :
lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) :=
lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩
theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α :=
mk_le_of_surjective surjective_onto_range
theorem mk_range_le_lift {α : Type u} {β : Type v} {f : α → β} :
lift.{v u} (mk (range f)) ≤ lift.{u v} (mk α) :=
lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_range⟩
lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α :=
quotient.sound ⟨(equiv.of_injective f h).symm⟩
lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v u} (mk (range f)) = lift.{u v} (mk α) :=
begin
have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.of_injective f hf).symm⟩,
simp only [lift_umax.{u v}, lift_umax.{v u}] at this,
exact this
end
lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) :=
lift_mk_eq.mpr ⟨(equiv.of_injective f hf).symm⟩
theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image f s hf).symm⟩
theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f)
... = sum (λ i, mk (f i)) : (sum_mk _).symm
theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) :
mk (⋃ i, f i) = sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩
... = sum (λi, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le {α ι : Type u} (f : ι → set α) :
mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) :=
le_trans mk_Union_le_sum_mk (sum_le_sup _)
lemma mk_sUnion_le {α : Type u} (A : set (set α)) :
mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) :=
by { rw [sUnion_eq_Union], apply mk_Union_le }
lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) :
mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) :=
by { rw [bUnion_eq_Union], apply mk_Union_le }
@[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk s :=
by rw [fintype_card, nat_cast_inj, fintype.card_coe]
lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega :=
by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ }
theorem mk_eq_nat_iff_finset {α} {s : set α} {n : ℕ} :
mk s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n :=
begin
split,
{ intro h,
have : # s < omega, by { rw h, exact nat_lt_omega n },
refine ⟨(lt_omega_iff_finite.1 this).to_finset, finite.coe_to_finset _, nat_cast_inj.1 _⟩,
rwa [finset_card, finite.coe_sort_to_finset] },
{ rintro ⟨t, rfl, rfl⟩,
exact finset_card.symm }
end
theorem mk_union_add_mk_inter {α : Type u} {S T : set α} :
mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union_sum_inter S T⟩
/-- The cardinality of a union is at most the sum of the cardinalities
of the two sets. -/
lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T :=
@mk_union_add_mk_inter α S T ▸ self_le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α))
theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) :
mk (S ∪ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union H⟩
lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α :=
quotient.sound ⟨equiv.set.sum_compl s⟩
lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t :=
⟨set.embedding_of_subset s t h⟩
lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} :=
⟨embedding_of_subset _ _ h⟩
lemma mk_set_le (s : set α) : mk s ≤ mk α :=
mk_subtype_le s
lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) :
lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩
lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α)
(h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) :
mk {a : α // p (e a)} = mk {b : β // p b} :=
quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩
lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } :=
quotient.sound ⟨equiv.set.sep s t⟩
lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) :=
begin
rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2),
apply subtype.coind_injective, exact h.comp subtype.val_injective
end
lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) :=
begin
rw lift_mk_le.{v u 0},
refine ⟨⟨_, _⟩⟩,
{ rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ },
rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp,
rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩,
rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩,
simp, intro hxx', rw hxx'
end
lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) :=
le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2)
lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) :
mk (f ⁻¹' s) ≤ mk s :=
by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_subset_range (f : α → β) (s : set β)
(h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) :=
by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s :=
by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] }
lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α}
{t : set β} (h : t ⊆ f '' s) :
lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1,
rw [mk_sep], refl }
lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) :
mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1,
rw [mk_sep], refl }
theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} :
c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c :=
begin
rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype],
apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective
end
/-- The function α^{<β}, defined to be sup_{γ < β} α^γ.
We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a
higher universe -/
noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} :=
sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s)
infix ` ^< `:80 := powerlt
theorem powerlt_aux {c c' : cardinal} (h : c < c') :
∃(s : {s : set c'.out // mk s < c'}), mk s = c :=
begin
cases out_embedding.mp (le_of_lt h) with f,
have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 },
exact ⟨⟨range f, by convert h⟩, this⟩
end
lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ :=
by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s }
lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ :=
begin
rw [powerlt, sup_le],
split,
{ intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s },
intros h s, exact h _ s.2
end
lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c :=
by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h }
lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ :=
begin
apply le_antisymm,
{ rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] },
{ apply le_powerlt, apply lt_succ_self }
end
lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) :=
by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] }
lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 :=
begin
apply le_antisymm,
{ rw [powerlt_le], intros c hc, apply zero_power_le },
convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero]
end
lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 :=
begin
convert sup_eq_zero,
exact subtype.is_empty_of_false (λ x, (zero_le _).not_lt),
end
end cardinal
lemma equiv.cardinal_eq {α β} : α ≃ β → cardinal.mk α = cardinal.mk β :=
cardinal.eq_congr
|
90ce25a6dd767985be14cc959b1478aa392cb393 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/topology/category/TopCommRing.lean | 7a2813a07a1d90d72d572d6b55f5263c2cf6318f | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 3,587 | 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 algebra.category.Ring.basic
import topology.category.Top.basic
import topology.algebra.ring.basic
/-!
# Category of topological commutative rings
We introduce the category `TopCommRing` of topological commutative rings together with the relevant
forgetful functors to topological spaces and commutative rings.
-/
universes u
open category_theory
/-- A bundled topological commutative ring. -/
structure TopCommRing :=
(α : Type u)
[is_comm_ring : comm_ring α]
[is_topological_space : topological_space α]
[is_topological_ring : topological_ring α]
namespace TopCommRing
instance : inhabited TopCommRing := ⟨⟨punit⟩⟩
instance : has_coe_to_sort TopCommRing (Type u) := ⟨TopCommRing.α⟩
attribute [instance] is_comm_ring is_topological_space is_topological_ring
instance : category TopCommRing.{u} :=
{ hom := λ R S, {f : R →+* S // continuous f },
id := λ R, ⟨ring_hom.id R, by obviously⟩, -- TODO remove obviously?
comp := λ R S T f g, ⟨g.val.comp f.val,
begin -- TODO automate
cases f, cases g,
dsimp, apply continuous.comp ; assumption
end⟩ }
instance : concrete_category TopCommRing.{u} :=
{ forget := { obj := λ R, R, map := λ R S f, f.val },
forget_faithful := { } }
/-- Construct a bundled `TopCommRing` from the underlying type and the appropriate typeclasses. -/
def of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] : TopCommRing := ⟨X⟩
@[simp] lemma coe_of (X : Type u) [comm_ring X] [topological_space X] [topological_ring X] :
(of X : Type u) = X := rfl
instance forget_topological_space (R : TopCommRing) :
topological_space ((forget TopCommRing).obj R) :=
R.is_topological_space
instance forget_comm_ring (R : TopCommRing) :
comm_ring ((forget TopCommRing).obj R) :=
R.is_comm_ring
instance forget_topological_ring (R : TopCommRing) :
topological_ring ((forget TopCommRing).obj R) :=
R.is_topological_ring
instance has_forget_to_CommRing : has_forget₂ TopCommRing CommRing :=
has_forget₂.mk'
(λ R, CommRing.of R)
(λ x, rfl)
(λ R S f, f.val)
(λ R S f, heq.rfl)
instance forget_to_CommRing_topological_space (R : TopCommRing) :
topological_space ((forget₂ TopCommRing CommRing).obj R) :=
R.is_topological_space
/-- The forgetful functor to Top. -/
instance has_forget_to_Top : has_forget₂ TopCommRing Top :=
has_forget₂.mk'
(λ R, Top.of R)
(λ x, rfl)
(λ R S f, ⟨⇑f.1, f.2⟩)
(λ R S f, heq.rfl)
instance forget_to_Top_comm_ring (R : TopCommRing) :
comm_ring ((forget₂ TopCommRing Top).obj R) :=
R.is_comm_ring
instance forget_to_Top_topological_ring (R : TopCommRing) :
topological_ring ((forget₂ TopCommRing Top).obj R) :=
R.is_topological_ring
/--
The forgetful functors to `Type` do not reflect isomorphisms,
but the forgetful functor from `TopCommRing` to `Top` does.
-/
instance : reflects_isomorphisms (forget₂ TopCommRing.{u} Top.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
-- We have an isomorphism in `Top`,
let i_Top := as_iso ((forget₂ TopCommRing Top).map f),
-- and a `ring_equiv`.
let e_Ring : X ≃+* Y := { ..f.1, ..((forget Top).map_iso i_Top).to_equiv },
-- Putting these together we obtain the isomorphism we're after:
exact
⟨⟨⟨e_Ring.symm, i_Top.inv.2⟩,
⟨by { ext x, exact e_Ring.left_inv x, }, by { ext x, exact e_Ring.right_inv x, }⟩⟩⟩
end }
end TopCommRing
|
79b6e3507bc303930eedcad0c3a4d979d388497c | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/ring/equiv.lean | 2e33e967e2b2fbb24cce1d0238beb934443abc99 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 23,701 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov
-/
import algebra.group.opposite
import algebra.hom.ring
import logic.equiv.set
import tactic.assert_exists
/-!
# (Semi)ring equivs
In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an
isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the
corresponding group of automorphisms `ring_aut`.
## Notations
* ``infix ` ≃+* `:25 := ring_equiv``
The extended equiv have coercions to functions, and the coercion is the canonical notation when
treating the isomorphism as maps.
## Implementation notes
The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are
deprecated.
Definition of multiplication in the groups of automorphisms agrees with function composition,
multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with
`category_theory.comp`.
## Tags
equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut
-/
variables {F α β R S S' : Type*}
set_option old_structure_cmd true
/-- An equivalence between two (non-unital non-associative semi)rings that preserves the
algebraic structure. -/
structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S]
extends R ≃ S, R ≃* S, R ≃+ S
infix ` ≃+* `:25 := ring_equiv
/-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_equiv
/-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_add_equiv
/-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/
add_decl_doc ring_equiv.to_mul_equiv
/-- `ring_equiv_class F R S` states that `F` is a type of ring structure preserving equivalences.
You should extend this class when you extend `ring_equiv`. -/
class ring_equiv_class (F : Type*) (R S : out_param Type*)
[has_mul R] [has_add R] [has_mul S] [has_add S]
extends mul_equiv_class F R S :=
(map_add : ∀ (f : F) a b, f (a + b) = f a + f b)
namespace ring_equiv_class
@[priority 100] -- See note [lower instance priority]
instance to_add_equiv_class (F R S : Type*)
[has_mul R] [has_add R] [has_mul S] [has_add S] [h : ring_equiv_class F R S] :
add_equiv_class F R S :=
{ coe := coe_fn,
.. h }
@[priority 100] -- See note [lower instance priority]
instance to_ring_hom_class (F R S : Type*)
[non_assoc_semiring R] [non_assoc_semiring S] [h : ring_equiv_class F R S] :
ring_hom_class F R S :=
{ coe := coe_fn,
coe_injective' := fun_like.coe_injective,
map_zero := map_zero,
map_one := map_one,
.. h }
@[priority 100] -- See note [lower instance priority]
instance to_non_unital_ring_hom_class (F R S : Type*)
[non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] [h : ring_equiv_class F R S] :
non_unital_ring_hom_class F R S :=
{ coe := coe_fn,
coe_injective' := fun_like.coe_injective,
map_zero := map_zero,
.. h }
end ring_equiv_class
instance [has_mul α] [has_add α] [has_mul β] [has_add β] [ring_equiv_class F α β] :
has_coe_t F (α ≃+* β) :=
⟨λ f, { to_fun := f, inv_fun := equiv_like.inv f, left_inv := equiv_like.left_inv f,
right_inv := equiv_like.right_inv f, map_mul' := map_mul f, map_add' := map_add f }⟩
namespace ring_equiv
section basic
variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S']
instance : ring_equiv_class (R ≃+* S) R S :=
{ coe := to_fun,
inv := inv_fun,
coe_injective' := λ e f h₁ h₂, by { cases e, cases f, congr' },
map_add := map_add',
map_mul := map_mul',
left_inv := ring_equiv.left_inv,
right_inv := ring_equiv.right_inv }
instance : has_coe_to_fun (R ≃+* S) (λ _, R → S) := ⟨ring_equiv.to_fun⟩
@[simp] lemma to_equiv_eq_coe (f : R ≃+* S) : f.to_equiv = f := rfl
@[simp] lemma to_fun_eq_coe (f : R ≃+* S) : f.to_fun = f := rfl
@[simp] lemma coe_to_equiv (f : R ≃+* S) : ⇑(f : R ≃ S) = f := rfl
/-- A ring isomorphism preserves multiplication. -/
protected lemma map_mul (e : R ≃+* S) (x y : R) : e (x * y) = e x * e y := map_mul e x y
/-- A ring isomorphism preserves addition. -/
protected lemma map_add (e : R ≃+* S) (x y : R) : e (x + y) = e x + e y := map_add e x y
/-- Two ring isomorphisms agree if they are defined by the
same underlying function. -/
@[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h
@[simp] theorem coe_mk (e e' h₁ h₂ h₃ h₄) :
⇑(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := rfl
@[simp] theorem mk_coe (e : R ≃+* S) (e' h₁ h₂ h₃ h₄) :
(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := ext $ λ _, rfl
protected lemma congr_arg {f : R ≃+* S} {x x' : R} : x = x' → f x = f x' := fun_like.congr_arg f
protected lemma congr_fun {f g : R ≃+* S} (h : f = g) (x : R) : f x = g x := fun_like.congr_fun h x
protected lemma ext_iff {f g : R ≃+* S} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff
@[simp] lemma to_add_equiv_eq_coe (f : R ≃+* S) : f.to_add_equiv = ↑f := rfl
@[simp] lemma to_mul_equiv_eq_coe (f : R ≃+* S) : f.to_mul_equiv = ↑f := rfl
@[simp, norm_cast] lemma coe_to_mul_equiv (f : R ≃+* S) : ⇑(f : R ≃* S) = f := rfl
@[simp, norm_cast] lemma coe_to_add_equiv (f : R ≃+* S) : ⇑(f : R ≃+ S) = f := rfl
/-- The `ring_equiv` between two semirings with a unique element. -/
def ring_equiv_of_unique {M N}
[unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : M ≃+* N :=
{ ..add_equiv.add_equiv_of_unique,
..mul_equiv.mul_equiv_of_unique}
instance {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] :
unique (M ≃+* N) :=
{ default := ring_equiv_of_unique,
uniq := λ _, ext $ λ x, subsingleton.elim _ _ }
variable (R)
/-- The identity map is a ring isomorphism. -/
@[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R }
@[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl
@[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl
@[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl
instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩
variables {R}
/-- The inverse of a ring isomorphism is a ring isomorphism. -/
@[symm] protected def symm (e : R ≃+* S) : S ≃+* R :=
{ .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm }
/-- See Note [custom simps projection] -/
def simps.symm_apply (e : R ≃+* S) : S → R := e.symm
initialize_simps_projections ring_equiv (to_fun → apply, inv_fun → symm_apply)
@[simp] lemma inv_fun_eq_symm (f : R ≃+* S) : f.inv_fun = f.symm := rfl
@[simp] lemma symm_symm (e : R ≃+* S) : e.symm.symm = e := ext $ λ x, rfl
@[simp]
lemma coe_to_equiv_symm (e : R ≃+* S) : (e.symm : S ≃ R) = (e : R ≃ S).symm := rfl
lemma symm_bijective : function.bijective (ring_equiv.symm : (R ≃+* S) → (S ≃+* R)) :=
equiv.bijective ⟨ring_equiv.symm, ring_equiv.symm, symm_symm, symm_symm⟩
@[simp] lemma mk_coe' (e : R ≃+* S) (f h₁ h₂ h₃ h₄) :
(ring_equiv.mk f ⇑e h₁ h₂ h₃ h₄ : S ≃+* R) = e.symm :=
symm_bijective.injective $ ext $ λ x, rfl
@[simp] lemma symm_mk (f : R → S) (g h₁ h₂ h₃ h₄) :
(mk f g h₁ h₂ h₃ h₄).symm =
{ to_fun := g, inv_fun := f, ..(mk f g h₁ h₂ h₃ h₄).symm} := rfl
/-- Transitivity of `ring_equiv`. -/
@[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' :=
{ .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) }
lemma trans_apply (e₁ : R ≃+* S) (e₂ : S ≃+* S') (a : R) :
e₁.trans e₂ a = e₂ (e₁ a) := rfl
@[simp] lemma coe_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂ : R → S') = e₂ ∘ e₁ := rfl
@[simp]
lemma symm_trans_apply (e₁ : R ≃+* S) (e₂ : S ≃+* S') (a : S') :
(e₁.trans e₂).symm a = e₁.symm (e₂.symm a) := rfl
lemma symm_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂).symm = e₂.symm.trans (e₁.symm) := rfl
protected lemma bijective (e : R ≃+* S) : function.bijective e := equiv_like.bijective e
protected lemma injective (e : R ≃+* S) : function.injective e := equiv_like.injective e
protected lemma surjective (e : R ≃+* S) : function.surjective e := equiv_like.surjective e
@[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply
lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s :=
e.to_equiv.image_eq_preimage s
@[simp] lemma coe_mul_equiv_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂ : R ≃* S') = (e₁ : R ≃* S).trans ↑e₂:= rfl
@[simp] lemma coe_add_equiv_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂ : R ≃+ S') = (e₁ : R ≃+ S).trans ↑e₂:= rfl
end basic
section opposite
open mul_opposite
/-- A ring iso `α ≃+* β` can equivalently be viewed as a ring iso `αᵐᵒᵖ ≃+* βᵐᵒᵖ`. -/
@[simps]
protected def op {α β} [has_add α] [has_mul α] [has_add β] [has_mul β] :
(α ≃+* β) ≃ (αᵐᵒᵖ ≃+* βᵐᵒᵖ) :=
{ to_fun := λ f, { ..f.to_add_equiv.mul_op, ..f.to_mul_equiv.op},
inv_fun := λ f, { ..add_equiv.mul_op.symm f.to_add_equiv, ..mul_equiv.op.symm f.to_mul_equiv },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- The 'unopposite' of a ring iso `αᵐᵒᵖ ≃+* βᵐᵒᵖ`. Inverse to `ring_equiv.op`. -/
@[simp] protected def unop {α β} [has_add α] [has_mul α] [has_add β] [has_mul β] :
(αᵐᵒᵖ ≃+* βᵐᵒᵖ) ≃ (α ≃+* β) := ring_equiv.op.symm
section non_unital_comm_semiring
variables (R) [non_unital_comm_semiring R]
/-- A non-unital commutative ring is isomorphic to its opposite. -/
def to_opposite : R ≃+* Rᵐᵒᵖ :=
{ map_add' := λ x y, rfl,
map_mul' := λ x y, mul_comm (op y) (op x),
.. mul_opposite.op_equiv }
@[simp]
lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl
@[simp]
lemma to_opposite_symm_apply (r : Rᵐᵒᵖ) : (to_opposite R).symm r = unop r := rfl
end non_unital_comm_semiring
end opposite
section non_unital_semiring
variables [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S]
(f : R ≃+* S) (x y : R)
/-- A ring isomorphism sends zero to zero. -/
protected lemma map_zero : f 0 = 0 := map_zero f
variable {x}
protected lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := add_equiv_class.map_eq_zero_iff f
lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := add_equiv_class.map_ne_zero_iff f
/-- Produce a ring isomorphism from a bijective ring homomorphism. -/
noncomputable def of_bijective [non_unital_ring_hom_class F R S] (f : F)
(hf : function.bijective f) : R ≃+* S :=
{ map_mul' := map_mul f,
map_add' := map_add f,
.. equiv.of_bijective f hf,}
@[simp] lemma coe_of_bijective [non_unital_ring_hom_class F R S] (f : F)
(hf : function.bijective f) : (of_bijective f hf : R → S) = f := rfl
lemma of_bijective_apply [non_unital_ring_hom_class F R S] (f : F)
(hf : function.bijective f) (x : R) : of_bijective f hf x = f x := rfl
/-- A family of ring isomorphisms `Π j, (R j ≃+* S j)` generates a
ring isomorphisms between `Π j, R j` and `Π j, S j`.
This is the `ring_equiv` version of `equiv.Pi_congr_right`, and the dependent version of
`ring_equiv.arrow_congr`.
-/
@[simps apply]
def Pi_congr_right {ι : Type*} {R S : ι → Type*}
[Π i, non_unital_non_assoc_semiring (R i)] [Π i, non_unital_non_assoc_semiring (S i)]
(e : Π i, R i ≃+* S i) : (Π i, R i) ≃+* Π i, S i :=
{ to_fun := λ x j, e j (x j),
inv_fun := λ x j, (e j).symm (x j),
.. @mul_equiv.Pi_congr_right ι R S _ _ (λ i, (e i).to_mul_equiv),
.. @add_equiv.Pi_congr_right ι R S _ _ (λ i, (e i).to_add_equiv) }
@[simp]
lemma Pi_congr_right_refl {ι : Type*} {R : ι → Type*} [Π i, non_unital_non_assoc_semiring (R i)] :
Pi_congr_right (λ i, ring_equiv.refl (R i)) = ring_equiv.refl _ := rfl
@[simp]
lemma Pi_congr_right_symm {ι : Type*} {R S : ι → Type*}
[Π i, non_unital_non_assoc_semiring (R i)] [Π i, non_unital_non_assoc_semiring (S i)]
(e : Π i, R i ≃+* S i) : (Pi_congr_right e).symm = (Pi_congr_right $ λ i, (e i).symm) := rfl
@[simp]
lemma Pi_congr_right_trans {ι : Type*} {R S T : ι → Type*}
[Π i, non_unital_non_assoc_semiring (R i)] [Π i, non_unital_non_assoc_semiring (S i)]
[Π i, non_unital_non_assoc_semiring (T i)]
(e : Π i, R i ≃+* S i) (f : Π i, S i ≃+* T i) :
(Pi_congr_right e).trans (Pi_congr_right f) = (Pi_congr_right $ λ i, (e i).trans (f i)) := rfl
end non_unital_semiring
section semiring
variables [non_assoc_semiring R] [non_assoc_semiring S] (f : R ≃+* S) (x y : R)
/-- A ring isomorphism sends one to one. -/
protected lemma map_one : f 1 = 1 := map_one f
variable {x}
protected lemma map_eq_one_iff : f x = 1 ↔ x = 1 := mul_equiv_class.map_eq_one_iff f
lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := mul_equiv_class.map_ne_one_iff f
lemma coe_monoid_hom_refl : (ring_equiv.refl R : R →* R) = monoid_hom.id R := rfl
@[simp] lemma coe_add_monoid_hom_refl : (ring_equiv.refl R : R →+ R) = add_monoid_hom.id R := rfl
/-! `ring_equiv.coe_mul_equiv_refl` and `ring_equiv.coe_add_equiv_refl` are proved above
in higher generality -/
@[simp] lemma coe_ring_hom_refl : (ring_equiv.refl R : R →* R) = ring_hom.id R := rfl
@[simp] lemma coe_monoid_hom_trans [non_assoc_semiring S'] (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂ : R →* S') = (e₂ : S →* S').comp ↑e₁ := rfl
@[simp] lemma coe_add_monoid_hom_trans [non_assoc_semiring S'] (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂ : R →+ S') = (e₂ : S →+ S').comp ↑e₁ := rfl
/-! `ring_equiv.coe_mul_equiv_trans` and `ring_equiv.coe_add_equiv_trans` are proved above
in higher generality -/
@[simp] lemma coe_ring_hom_trans [non_assoc_semiring S'] (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂ : R →+* S') = (e₂ : S →+* S').comp ↑e₁ := rfl
@[simp] lemma comp_symm (e : R ≃+* S) :
(e : R →+* S).comp (e.symm : S →+* R) = ring_hom.id S :=
ring_hom.ext e.apply_symm_apply
@[simp] lemma symm_comp (e : R ≃+* S) :
(e.symm : S →+* R).comp (e : R →+* S) = ring_hom.id R :=
ring_hom.ext e.symm_apply_apply
end semiring
section non_unital_ring
variables [non_unital_non_assoc_ring R] [non_unital_non_assoc_ring S] (f : R ≃+* S) (x y : R)
protected lemma map_neg : f (-x) = -f x := map_neg f x
protected lemma map_sub : f (x - y) = f x - f y := map_sub f x y
end non_unital_ring
section ring
variables [non_assoc_ring R] [non_assoc_ring S] (f : R ≃+* S) (x y : R)
@[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1
end ring
section non_unital_semiring_hom
variables [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S]
[non_unital_non_assoc_semiring S']
/-- Reinterpret a ring equivalence as a non-unital ring homomorphism. -/
def to_non_unital_ring_hom (e : R ≃+* S) : R →ₙ+* S :=
{ .. e.to_mul_equiv.to_mul_hom, .. e.to_add_equiv.to_add_monoid_hom }
lemma to_non_unital_ring_hom_injective :
function.injective (to_non_unital_ring_hom : (R ≃+* S) → R →ₙ+* S) :=
λ f g h, ring_equiv.ext (non_unital_ring_hom.ext_iff.1 h)
/- The instance priority is lowered here so that in the case when `R` and `S` are both unital, Lean
will first find and use `ring_equiv.has_coe_to_ring_hom`. -/
@[priority 900]
instance has_coe_to_non_unital_ring_hom : has_coe (R ≃+* S) (R →ₙ+* S) :=
⟨ring_equiv.to_non_unital_ring_hom⟩
lemma to_non_unital_ring_hom_eq_coe (f : R ≃+* S) : f.to_non_unital_ring_hom = ↑f := rfl
@[simp, norm_cast] lemma coe_to_non_unital_ring_hom (f : R ≃+* S) : ⇑(f : R →ₙ+* S) = f := rfl
lemma coe_non_unital_ring_hom_inj_iff {R S : Type*}
[non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S]
(f g : R ≃+* S) :
f = g ↔ (f : R →ₙ+* S) = g :=
⟨congr_arg _, λ h, ext $ non_unital_ring_hom.ext_iff.mp h⟩
@[simp]
lemma to_non_unital_ring_hom_refl :
(ring_equiv.refl R).to_non_unital_ring_hom = non_unital_ring_hom.id R := rfl
@[simp]
lemma to_non_unital_ring_hom_apply_symm_to_non_unital_ring_hom_apply (e : R ≃+* S) :
∀ (y : S), e.to_non_unital_ring_hom (e.symm.to_non_unital_ring_hom y) = y :=
e.to_equiv.apply_symm_apply
@[simp]
lemma symm_to_non_unital_ring_hom_apply_to_non_unital_ring_hom_apply (e : R ≃+* S) :
∀ (x : R), e.symm.to_non_unital_ring_hom (e.to_non_unital_ring_hom x) = x :=
equiv.symm_apply_apply (e.to_equiv)
@[simp]
lemma to_non_unital_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂).to_non_unital_ring_hom = e₂.to_non_unital_ring_hom.comp e₁.to_non_unital_ring_hom :=
rfl
@[simp]
lemma to_non_unital_ring_hom_comp_symm_to_non_unital_ring_hom (e : R ≃+* S) :
e.to_non_unital_ring_hom.comp e.symm.to_non_unital_ring_hom = non_unital_ring_hom.id _ :=
by { ext, simp }
@[simp]
lemma symm_to_non_unital_ring_hom_comp_to_non_unital_ring_hom (e : R ≃+* S) :
e.symm.to_non_unital_ring_hom.comp e.to_non_unital_ring_hom = non_unital_ring_hom.id _ :=
by { ext, simp }
end non_unital_semiring_hom
section semiring_hom
variables [non_assoc_semiring R] [non_assoc_semiring S] [non_assoc_semiring S']
/-- Reinterpret a ring equivalence as a ring homomorphism. -/
def to_ring_hom (e : R ≃+* S) : R →+* S :=
{ .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom }
lemma to_ring_hom_injective : function.injective (to_ring_hom : (R ≃+* S) → R →+* S) :=
λ f g h, ring_equiv.ext (ring_hom.ext_iff.1 h)
instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩
lemma to_ring_hom_eq_coe (f : R ≃+* S) : f.to_ring_hom = ↑f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : R ≃+* S) : ⇑(f : R →+* S) = f := rfl
lemma coe_ring_hom_inj_iff {R S : Type*} [non_assoc_semiring R] [non_assoc_semiring S]
(f g : R ≃+* S) :
f = g ↔ (f : R →+* S) = g :=
⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩
/-- The two paths coercion can take to a `non_unital_ring_hom` are equivalent -/
@[simp, norm_cast] lemma to_non_unital_ring_hom_commutes (f : R ≃+* S) :
((f : R →+* S) : R →ₙ+* S) = (f : R →ₙ+* S) :=
rfl
/-- Reinterpret a ring equivalence as a monoid homomorphism. -/
abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom
/-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/
abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom
/-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/
lemma to_add_monoid_hom_commutes (f : R ≃+* S) :
(f : R →+* S).to_add_monoid_hom = (f : R ≃+ S).to_add_monoid_hom :=
rfl
/-- The two paths coercion can take to an `monoid_hom` are equivalent -/
lemma to_monoid_hom_commutes (f : R ≃+* S) :
(f : R →+* S).to_monoid_hom = (f : R ≃* S).to_monoid_hom :=
rfl
/-- The two paths coercion can take to an `equiv` are equivalent -/
lemma to_equiv_commutes (f : R ≃+* S) :
(f : R ≃+ S).to_equiv = (f : R ≃* S).to_equiv :=
rfl
@[simp]
lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl
@[simp]
lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl
@[simp]
lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl
@[simp]
lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) :
∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y :=
e.to_equiv.apply_symm_apply
@[simp]
lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) :
∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x :=
equiv.symm_apply_apply (e.to_equiv)
@[simp]
lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl
@[simp]
lemma to_ring_hom_comp_symm_to_ring_hom (e : R ≃+* S) :
e.to_ring_hom.comp e.symm.to_ring_hom = ring_hom.id _ :=
by { ext, simp }
@[simp]
lemma symm_to_ring_hom_comp_to_ring_hom (e : R ≃+* S) :
e.symm.to_ring_hom.comp e.to_ring_hom = ring_hom.id _ :=
by { ext, simp }
/--
Construct an equivalence of rings from homomorphisms in both directions, which are inverses.
-/
@[simps]
def of_hom_inv' {R S F G : Type*} [non_unital_non_assoc_semiring R]
[non_unital_non_assoc_semiring S] [non_unital_ring_hom_class F R S]
[non_unital_ring_hom_class G S R] (hom : F) (inv : G)
(hom_inv_id : (inv : S →ₙ+* R).comp (hom : R →ₙ+* S) = non_unital_ring_hom.id R)
(inv_hom_id : (hom : R →ₙ+* S).comp (inv : S →ₙ+* R) = non_unital_ring_hom.id S) :
R ≃+* S :=
{ to_fun := hom,
inv_fun := inv,
left_inv := fun_like.congr_fun hom_inv_id,
right_inv := fun_like.congr_fun inv_hom_id,
map_mul' := map_mul hom,
map_add' := map_add hom, }
/--
Construct an equivalence of rings from unital homomorphisms in both directions, which are inverses.
-/
@[simps]
def of_hom_inv {R S F G : Type*} [non_assoc_semiring R] [non_assoc_semiring S]
[ring_hom_class F R S] [ring_hom_class G S R] (hom : F) (inv : G)
(hom_inv_id : (inv : S →+* R).comp (hom : R →+* S) = ring_hom.id R)
(inv_hom_id : (hom : R →+* S).comp (inv : S →+* R) = ring_hom.id S) :
R ≃+* S :=
{ to_fun := hom,
inv_fun := inv,
left_inv := fun_like.congr_fun hom_inv_id,
right_inv := fun_like.congr_fun inv_hom_id,
map_mul' := map_mul hom,
map_add' := map_add hom, }
end semiring_hom
section group_power
variables [semiring R] [semiring S]
protected lemma map_pow (f : R ≃+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := map_pow f a
end group_power
end ring_equiv
namespace mul_equiv
/-- Gives a `ring_equiv` from an element of a `mul_equiv_class` preserving addition.-/
def to_ring_equiv {R S F : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S]
[mul_equiv_class F R S] (f : F) (H : ∀ x y : R, f (x + y) = f x + f y) : R ≃+* S :=
{ ..(f : R ≃* S).to_equiv, ..(f : R ≃* S), ..add_equiv.mk' (f : R ≃* S).to_equiv H }
end mul_equiv
namespace add_equiv
/-- Gives a `ring_equiv` from an element of an `add_equiv_class` preserving addition.-/
def to_ring_equiv {R S F : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S]
[add_equiv_class F R S] (f : F) (H : ∀ x y : R, f (x * y) = f x * f y) : R ≃+* S :=
{ ..(f : R ≃+ S).to_equiv, ..(f : R ≃+ S), ..mul_equiv.mk' (f : R ≃+ S).to_equiv H }
end add_equiv
namespace ring_equiv
variables [has_add R] [has_add S] [has_mul R] [has_mul S]
@[simp] theorem self_trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3
@[simp] theorem symm_trans_self (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4
/-- If two rings are isomorphic, and the second is a domain, then so is the first. -/
protected lemma is_domain
{A : Type*} (B : Type*) [ring A] [ring B] [is_domain B]
(e : A ≃+* B) : is_domain A :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy,
have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero],
by simpa using eq_zero_or_eq_zero_of_mul_eq_zero this,
exists_pair_ne := ⟨e.symm 0, e.symm 1, e.symm.injective.ne zero_ne_one⟩ }
end ring_equiv
-- Guard against import creep
assert_not_exists fintype
|
ece37ac178d4c757f82d1784cdc0c7a8fb13a292 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/field_theory/subfield.lean | 6a9328d78504fa0b4e29e56600e2c14d057ee01b | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 24,227 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors : Anne Baanen
-/
import ring_theory.subring
/-!
# Subfields
Let `K` be a field. This file defines the "bundled" subfield type `subfield K`, a type
whose terms correspond to subfields of `K`. This is the preferred way to talk
about subfields in mathlib. Unbundled subfields (`s : set K` and `is_subfield s`)
are not in this file, and they will ultimately be deprecated.
We prove that subfields are a complete lattice, and that you can `map` (pushforward) and
`comap` (pull back) them along ring homomorphisms.
We define the `closure` construction from `set R` to `subfield R`, sending a subset of `R`
to the subfield it generates, and prove that it is a Galois insertion.
## Main definitions
Notation used here:
`(K : Type u) [field K] (L : Type u) [field L] (f g : K →+* L)`
`(A : subfield K) (B : subfield L) (s : set K)`
* `subfield R` : the type of subfields of a ring `R`.
* `instance : complete_lattice (subfield R)` : the complete lattice structure on the subfields.
* `subfield.closure` : subfield closure of a set, i.e., the smallest subfield that includes the set.
* `subfield.gi` : `closure : set M → subfield M` and coercion `coe : subfield M → set M`
form a `galois_insertion`.
* `comap f B : subfield K` : the preimage of a subfield `B` along the ring homomorphism `f`
* `map f A : subfield L` : the image of a subfield `A` along the ring homomorphism `f`.
* `prod A B : subfield (K × L)` : the product of subfields
* `f.field_range : subfield B` : the range of the ring homomorphism `f`.
* `eq_locus_field f g : subfield K` : given ring homomorphisms `f g : K →+* R`,
the subfield of `K` where `f x = g x`
## Implementation notes
A subfield is implemented as a subring which is is closed under `⁻¹`.
Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although
`∈` is defined as membership of a subfield's underlying set.
## Tags
subfield, subfields
-/
open_locale big_operators
universes u v w
variables {K : Type u} {L : Type v} {M : Type w} [field K] [field L] [field M]
set_option old_structure_cmd true
/-- `subfield R` is the type of subfields of `R`. A subfield of `R` is a subset `s` that is a
multiplicative submonoid and an additive subgroup. Note in particular that it shares the
same 0 and 1 as R. -/
structure subfield (K : Type u) [field K] extends subring K :=
(inv_mem' : ∀ x ∈ carrier, x⁻¹ ∈ carrier)
/-- Reinterpret a `subfield` as a `subring`. -/
add_decl_doc subfield.to_subring
namespace subfield
/-- The underlying `add_subgroup` of a subfield. -/
def to_add_subgroup (s : subfield K) : add_subgroup K :=
{ ..s.to_subring.to_add_subgroup }
/-- The underlying submonoid of a subfield. -/
def to_submonoid (s : subfield K) : submonoid K :=
{ ..s.to_subring.to_submonoid }
instance : has_coe (subfield K) (set K) := ⟨subfield.carrier⟩
@[simp] lemma coe_to_subring (s : subfield K) : (s.to_subring : set K) = s :=
rfl
instance : has_coe_to_sort (subfield K) := ⟨Type*, λ S, S.carrier⟩
instance : has_mem K (subfield K) := ⟨λ m S, m ∈ (S : set K)⟩
@[simp] lemma mem_mk (s : set K) (ho hm hz ha hn hi) (x : K) :
x ∈ subfield.mk s ho hm hz ha hn hi ↔ x ∈ s := iff.rfl
@[simp] lemma mem_to_subring (s : subfield K) (x : K) :
x ∈ s.to_subring ↔ x ∈ s := iff.rfl
end subfield
protected lemma subfield.exists {s : subfield K} {p : s → Prop} :
(∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ :=
set_coe.exists
protected lemma subfield.forall {s : subfield K} {p : s → Prop} :
(∀ x : s, p x) ↔ ∀ x ∈ s, p ⟨x, ‹x ∈ s›⟩ :=
set_coe.forall
/-- A `subring` containing inverses is a `subfield`. -/
def subring.to_subfield (s : subring K) (hinv : ∀ x ∈ s, x⁻¹ ∈ s) : subfield K :=
{ inv_mem' := hinv
..s }
namespace subfield
variables (s t : subfield K)
/-- Two subfields are equal if the underlying subsets are equal. -/
theorem ext' ⦃s t : subfield K⦄ (h : (s : set K) = t) : s = t :=
by { cases s, cases t, congr' }
/-- Two subfields are equal if and only if the underlying subsets are equal. -/
protected theorem ext'_iff {s t : subfield K} : s = t ↔ (s : set K) = t :=
⟨λ h, h ▸ rfl, λ h, ext' h⟩
/-- Two subfields are equal if they have the same elements. -/
@[ext] theorem ext {S T : subfield K} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h
/-- A subfield contains the ring's 1. -/
theorem one_mem : (1 : K) ∈ s := s.one_mem'
/-- A subfield contains the ring's 0. -/
theorem zero_mem : (0 : K) ∈ s := s.zero_mem'
/-- A subfield is closed under multiplication. -/
theorem mul_mem : ∀ {x y : K}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem'
/-- A subfield is closed under addition. -/
theorem add_mem : ∀ {x y : K}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem'
/-- A subfield is closed under negation. -/
theorem neg_mem : ∀ {x : K}, x ∈ s → -x ∈ s := s.neg_mem'
/-- A subfield is closed under subtraction. -/
theorem sub_mem {x y : K} : x ∈ s → y ∈ s → x - y ∈ s := s.to_subring.sub_mem
/-- A subfield is closed under inverses. -/
theorem inv_mem : ∀ {x : K}, x ∈ s → x⁻¹ ∈ s := s.inv_mem'
/-- A subfield is closed under division. -/
theorem div_mem {x y : K} (hx : x ∈ s) (hy : y ∈ s) : x / y ∈ s :=
by { rw div_eq_mul_inv, exact s.mul_mem hx (s.inv_mem hy) }
/-- Product of a list of elements in a subfield is in the subfield. -/
lemma list_prod_mem {l : list K} : (∀ x ∈ l, x ∈ s) → l.prod ∈ s :=
s.to_submonoid.list_prod_mem
/-- Sum of a list of elements in a subfield is in the subfield. -/
lemma list_sum_mem {l : list K} : (∀ x ∈ l, x ∈ s) → l.sum ∈ s :=
s.to_add_subgroup.list_sum_mem
/-- Product of a multiset of elements in a subfield is in the subfield. -/
lemma multiset_prod_mem (m : multiset K) :
(∀ a ∈ m, a ∈ s) → m.prod ∈ s :=
s.to_submonoid.multiset_prod_mem m
/-- Sum of a multiset of elements in a `subfield` is in the `subfield`. -/
lemma multiset_sum_mem (m : multiset K) :
(∀ a ∈ m, a ∈ s) → m.sum ∈ s :=
s.to_add_subgroup.multiset_sum_mem m
/-- Product of elements of a subfield indexed by a `finset` is in the subfield. -/
lemma prod_mem {ι : Type*} {t : finset ι} {f : ι → K} (h : ∀ c ∈ t, f c ∈ s) :
∏ i in t, f i ∈ s :=
s.to_submonoid.prod_mem h
/-- Sum of elements in a `subfield` indexed by a `finset` is in the `subfield`. -/
lemma sum_mem {ι : Type*} {t : finset ι} {f : ι → K} (h : ∀ c ∈ t, f c ∈ s) :
∑ i in t, f i ∈ s :=
s.to_add_subgroup.sum_mem h
lemma pow_mem {x : K} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n
lemma gsmul_mem {x : K} (hx : x ∈ s) (n : ℤ) :
n •ℤ x ∈ s := s.to_add_subgroup.gsmul_mem hx n
lemma coe_int_mem (n : ℤ) : (n : K) ∈ s :=
by simp only [← gsmul_one, gsmul_mem, one_mem]
/-- A subfield inherits a field structure -/
instance to_field : field s :=
{ inv := λ x, ⟨x⁻¹, s.inv_mem x.2⟩,
inv_zero := subtype.ext inv_zero,
mul_inv_cancel := λ x hx, subtype.ext (mul_inv_cancel (mt s.to_subring.coe_eq_zero_iff.mp hx)),
exists_pair_ne := ⟨⟨0, s.zero_mem⟩, ⟨1, s.one_mem⟩, mt subtype.mk_eq_mk.mp zero_ne_one⟩,
..subring.subring.domain s.to_subring }
@[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : K) = ↑x + ↑y := rfl
@[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : K) = -↑x := rfl
@[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : K) = ↑x * ↑y := rfl
@[simp, norm_cast] lemma coe_inv (x : s) : (↑(x⁻¹) : K) = (↑x)⁻¹ := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : s) : K) = 0 := rfl
@[simp, norm_cast] lemma coe_one : ((1 : s) : K) = 1 := rfl
/-- The embedding from a subfield of the field `K` to `K`. -/
def subtype (s : subfield K) : s →+* K :=
{ to_fun := coe,
.. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype }
@[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl
/-! # Partial order -/
instance : partial_order (subfield K) :=
{ le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t,
.. partial_order.lift (coe : subfield K → set K) ext' }
variables {s t}
lemma le_def : s ≤ t ↔ ∀ ⦃x : K⦄, x ∈ s → x ∈ t := iff.rfl
@[simp, norm_cast] lemma coe_subset_coe : (s : set K) ⊆ t ↔ s ≤ t := iff.rfl
@[simp, norm_cast] lemma coe_ssubset_coe : (s : set K) ⊂ t ↔ s < t := iff.rfl
@[simp, norm_cast]
lemma mem_coe {m : K} : m ∈ (s : set K) ↔ m ∈ s := iff.rfl
variables (s t)
@[simp, norm_cast]
lemma coe_coe (s : subfield K) : ↥(s : set K) = s := rfl
@[simp] lemma mem_to_submonoid {s : subfield K} {x : K} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_submonoid : (s.to_submonoid : set K) = s := rfl
@[simp] lemma mem_to_add_subgroup {s : subfield K} {x : K} :
x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl
@[simp] lemma coe_to_add_subgroup : (s.to_add_subgroup : set K) = s := rfl
/-! # top -/
/-- The subfield of `K` containing all elements of `K`. -/
instance : has_top (subfield K) :=
⟨{ inv_mem' := λ x _, subring.mem_top x, .. (⊤ : subring K)}⟩
instance : inhabited (subfield K) := ⟨⊤⟩
@[simp] lemma mem_top (x : K) : x ∈ (⊤ : subfield K) := set.mem_univ x
@[simp] lemma coe_top : ((⊤ : subfield K) : set K) = set.univ := rfl
/-! # comap -/
variables (f : K →+* L)
/-- The preimage of a subfield along a ring homomorphism is a subfield. -/
def comap (s : subfield L) : subfield K :=
{ inv_mem' := λ x hx, show f (x⁻¹) ∈ s, by { rw f.map_inv, exact s.inv_mem hx },
.. s.to_subring.comap f }
@[simp] lemma coe_comap (s : subfield L) : (s.comap f : set K) = f ⁻¹' s := rfl
@[simp]
lemma mem_comap {s : subfield L} {f : K →+* L} {x : K} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl
lemma comap_comap (s : subfield M) (g : L →+* M) (f : K →+* L) :
(s.comap g).comap f = s.comap (g.comp f) :=
rfl
/-! # map -/
/-- The image of a subfield along a ring homomorphism is a subfield. -/
def map (s : subfield K) : subfield L :=
{ inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, s.inv_mem hx, f.map_inv x⟩ },
.. s.to_subring.map f }
@[simp] lemma coe_map : (s.map f : set L) = f '' s := rfl
@[simp] lemma mem_map {f : K →+* L} {s : subfield K} {y : L} :
y ∈ s.map f ↔ ∃ x ∈ s, f x = y :=
set.mem_image_iff_bex
lemma map_map (g : L →+* M) (f : K →+* L) : (s.map f).map g = s.map (g.comp f) :=
ext' $ set.image_image _ _ _
lemma map_le_iff_le_comap {f : K →+* L} {s : subfield K} {t : subfield L} :
s.map f ≤ t ↔ s ≤ t.comap f :=
set.image_subset_iff
lemma gc_map_comap (f : K →+* L) : galois_connection (map f) (comap f) :=
λ S T, map_le_iff_le_comap
end subfield
namespace ring_hom
variables (g : L →+* M) (f : K →+* L)
/-! # range -/
/-- The range of a ring homomorphism, as a subfield of the target. -/
def field_range : subfield L := (⊤ : subfield K).map f
@[simp] lemma coe_field_range : (f.field_range : set L) = set.range f := set.image_univ
@[simp] lemma mem_field_range {f : K →+* L} {y : L} : y ∈ f.range ↔ ∃ x, f x = y :=
by simp [range]
lemma map_field_range : f.field_range.map g = (g.comp f).field_range :=
(⊤ : subfield K).map_map g f
end ring_hom
namespace subfield
/-! # inf -/
/-- The inf of two subfields is their intersection. -/
instance : has_inf (subfield K) :=
⟨λ s t,
{ inv_mem' := λ x hx, subring.mem_inf.mpr
⟨s.inv_mem (subring.mem_inf.mp hx).1,
t.inv_mem (subring.mem_inf.mp hx).2⟩,
.. s.to_subring ⊓ t.to_subring }⟩
@[simp] lemma coe_inf (p p' : subfield K) : ((p ⊓ p' : subfield K) : set K) = p ∩ p' := rfl
@[simp] lemma mem_inf {p p' : subfield K} {x : K} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
instance : has_Inf (subfield K) :=
⟨λ S,
{ inv_mem' := begin
rintros x hx,
apply subring.mem_Inf.mpr,
rintro _ ⟨p, p_mem, rfl⟩,
exact p.inv_mem (subring.mem_Inf.mp hx p.to_subring ⟨p, p_mem, rfl⟩),
end,
.. Inf (subfield.to_subring '' S) }⟩
@[simp, norm_cast] lemma coe_Inf (S : set (subfield K)) :
((Inf S : subfield K) : set K) = ⋂ s ∈ S, ↑s :=
show ((Inf (subfield.to_subring '' S) : subring K) : set K) = ⋂ s ∈ S, ↑s,
begin
ext x,
rw [subring.coe_Inf, set.mem_Inter, set.mem_Inter],
exact ⟨λ h s s' ⟨s_mem, s'_eq⟩, h s.to_subring _ ⟨⟨s, s_mem, rfl⟩, s'_eq⟩,
λ h s s' ⟨⟨s'', s''_mem, s_eq⟩, (s'_eq : ↑s = s')⟩,
h s'' _ ⟨s''_mem, by simp [←s_eq, ← s'_eq]⟩⟩
end
lemma mem_Inf {S : set (subfield K)} {x : K} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p :=
subring.mem_Inf.trans
⟨λ h p hp, h p.to_subring ⟨p, hp, rfl⟩,
λ h p ⟨p', hp', p_eq⟩, p_eq ▸ h p' hp'⟩
@[simp] lemma Inf_to_subring (s : set (subfield K)) :
(Inf s).to_subring = ⨅ t ∈ s, subfield.to_subring t :=
begin
ext x,
rw [mem_to_subring, mem_Inf],
erw subring.mem_Inf,
exact ⟨λ h p ⟨p', hp⟩, hp ▸ subring.mem_Inf.mpr (λ p ⟨hp', hp⟩, hp ▸ h _ hp'),
λ h p hp, h p.to_subring ⟨p, subring.ext (λ x,
⟨λ hx, subring.mem_Inf.mp hx _ ⟨hp, rfl⟩,
λ hx, subring.mem_Inf.mpr (λ p' ⟨hp, p'_eq⟩, p'_eq ▸ hx)⟩)⟩⟩
end
lemma is_glb_Inf (S : set (subfield K)) : is_glb S (Inf S) :=
begin
refine is_glb.of_image (λ s t, show (s : set K) ≤ t ↔ s ≤ t, from coe_subset_coe) _,
convert is_glb_binfi,
exact coe_Inf _
end
/-- Subfields of a ring form a complete lattice. -/
instance : complete_lattice (subfield K) :=
{ top := ⊤,
le_top := λ s x hx, trivial,
inf := (⊓),
inf_le_left := λ s t x, and.left,
inf_le_right := λ s t x, and.right,
le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩,
.. complete_lattice_of_Inf (subfield K) is_glb_Inf }
/-! # subfield closure of a subset -/
/-- The `subfield` generated by a set. -/
def closure (s : set K) : subfield K :=
{ carrier := { (x / y) | (x ∈ subring.closure s) (y ∈ subring.closure s) },
zero_mem' := ⟨0, subring.zero_mem _, 1, subring.one_mem _, div_one _⟩,
one_mem' := ⟨1, subring.one_mem _, 1, subring.one_mem _, div_one _⟩,
neg_mem' := λ x ⟨y, hy, z, hz, x_eq⟩, ⟨-y, subring.neg_mem _ hy, z, hz, x_eq ▸ neg_div _ _⟩,
inv_mem' := λ x ⟨y, hy, z, hz, x_eq⟩, ⟨z, hz, y, hy, x_eq ▸ inv_div.symm⟩,
add_mem' := λ x y x_mem y_mem, begin
obtain ⟨nx, hnx, dx, hdx, rfl⟩ := id x_mem,
obtain ⟨ny, hny, dy, hdy, rfl⟩ := id y_mem,
by_cases hx0 : dx = 0, { rwa [hx0, div_zero, zero_add] },
by_cases hy0 : dy = 0, { rwa [hy0, div_zero, add_zero] },
exact ⟨nx * dy + dx * ny,
subring.add_mem _ (subring.mul_mem _ hnx hdy) (subring.mul_mem _ hdx hny),
dx * dy, subring.mul_mem _ hdx hdy,
(div_add_div nx ny hx0 hy0).symm⟩
end,
mul_mem' := λ x y x_mem y_mem, begin
obtain ⟨nx, hnx, dx, hdx, rfl⟩ := id x_mem,
obtain ⟨ny, hny, dy, hdy, rfl⟩ := id y_mem,
exact ⟨nx * ny, subring.mul_mem _ hnx hny,
dx * dy, subring.mul_mem _ hdx hdy,
(div_mul_div _ _ _ _).symm⟩
end }
lemma mem_closure_iff {s : set K} {x} :
x ∈ closure s ↔ ∃ (y ∈ subring.closure s) (z ∈ subring.closure s), y / z = x := iff.rfl
lemma subring_closure_le (s : set K) : subring.closure s ≤ (closure s).to_subring :=
λ x hx, ⟨x, hx, 1, subring.one_mem _, div_one x⟩
/-- The subfield generated by a set includes the set. -/
@[simp] lemma subset_closure {s : set K} : s ⊆ closure s :=
set.subset.trans subring.subset_closure (subring_closure_le s)
lemma mem_closure {x : K} {s : set K} : x ∈ closure s ↔ ∀ S : subfield K, s ⊆ S → x ∈ S :=
⟨λ ⟨y, hy, z, hz, x_eq⟩ t le, x_eq ▸
t.div_mem
(subring.mem_closure.mp hy t.to_subring le)
(subring.mem_closure.mp hz t.to_subring le),
λ h, h (closure s) subset_closure⟩
/-- A subfield `t` includes `closure s` if and only if it includes `s`. -/
@[simp]
lemma closure_le {s : set K} {t : subfield K} : closure s ≤ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, λ h x hx, mem_closure.mp hx t h⟩
/-- Subfield closure of a set is monotone in its argument: if `s ⊆ t`,
then `closure s ≤ closure t`. -/
lemma closure_mono ⦃s t : set K⦄ (h : s ⊆ t) : closure s ≤ closure t :=
closure_le.2 $ set.subset.trans h subset_closure
lemma closure_eq_of_le {s : set K} {t : subfield K} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) :
closure s = t :=
le_antisymm (closure_le.2 h₁) h₂
/-- An induction principle for closure membership. If `p` holds for `1`, and all elements
of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements
of the closure of `s`. -/
@[elab_as_eliminator]
lemma closure_induction {s : set K} {p : K → Prop} {x} (h : x ∈ closure s)
(Hs : ∀ x ∈ s, p x) (H1 : p 1)
(Hadd : ∀ x y, p x → p y → p (x + y))
(Hneg : ∀ x, p x → p (-x))
(Hinv : ∀ x, p x → p (x⁻¹))
(Hmul : ∀ x y, p x → p y → p (x * y)) : p x :=
(@closure_le _ _ _ ⟨p, H1, Hmul,
@add_neg_self K _ 1 ▸ Hadd _ _ H1 (Hneg _ H1), Hadd, Hneg, Hinv⟩).2 Hs h
variable (K)
/-- `closure` forms a Galois insertion with the coercion to set. -/
protected def gi : galois_insertion (@closure K _) coe :=
{ choice := λ s _, closure s,
gc := λ s t, closure_le,
le_l_u := λ s, subset_closure,
choice_eq := λ s h, rfl }
variable {K}
/-- Closure of a subfield `S` equals `S`. -/
lemma closure_eq (s : subfield K) : closure (s : set K) = s := (subfield.gi K).l_u_eq s
@[simp] lemma closure_empty : closure (∅ : set K) = ⊥ := (subfield.gi K).gc.l_bot
@[simp] lemma closure_univ : closure (set.univ : set K) = ⊤ := @coe_top K _ ▸ closure_eq ⊤
lemma closure_union (s t : set K) : closure (s ∪ t) = closure s ⊔ closure t :=
(subfield.gi K).gc.l_sup
lemma closure_Union {ι} (s : ι → set K) : closure (⋃ i, s i) = ⨆ i, closure (s i) :=
(subfield.gi K).gc.l_supr
lemma closure_sUnion (s : set (set K)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t :=
(subfield.gi K).gc.l_Sup
lemma map_sup (s t : subfield K) (f : K →+* L) : (s ⊔ t).map f = s.map f ⊔ t.map f :=
(gc_map_comap f).l_sup
lemma map_supr {ι : Sort*} (f : K →+* L) (s : ι → subfield K) :
(supr s).map f = ⨆ i, (s i).map f :=
(gc_map_comap f).l_supr
lemma comap_inf (s t : subfield L) (f : K →+* L) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f :=
(gc_map_comap f).u_inf
lemma comap_infi {ι : Sort*} (f : K →+* L) (s : ι → subfield L) :
(infi s).comap f = ⨅ i, (s i).comap f :=
(gc_map_comap f).u_infi
@[simp] lemma map_bot (f : K →+* L) : (⊥ : subfield K).map f = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma comap_top (f : K →+* L) : (⊤ : subfield L).comap f = ⊤ :=
(gc_map_comap f).u_top
/-- The underlying set of a non-empty directed Sup of subfields is just a union of the subfields.
Note that this fails without the directedness assumption (the union of two subfields is
typically not a subfield) -/
lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subfield K} (hS : directed (≤) S)
{x : K} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i :=
begin
refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩,
suffices : x ∈ closure (⋃ i, (S i : set K)) → ∃ i, x ∈ S i,
by simpa only [closure_Union, closure_eq],
refine λ hx, closure_induction hx (λ x, set.mem_Union.mp) _ _ _ _ _,
{ exact hι.elim (λ i, ⟨i, (S i).one_mem⟩) },
{ rintros x y ⟨i, hi⟩ ⟨j, hj⟩,
obtain ⟨k, hki, hkj⟩ := hS i j,
exact ⟨k, (S k).add_mem (hki hi) (hkj hj)⟩ },
{ rintros x ⟨i, hi⟩,
exact ⟨i, (S i).neg_mem hi⟩ },
{ rintros x ⟨i, hi⟩,
exact ⟨i, (S i).inv_mem hi⟩ },
{ rintros x y ⟨i, hi⟩ ⟨j, hj⟩,
obtain ⟨k, hki, hkj⟩ := hS i j,
exact ⟨k, (S k).mul_mem (hki hi) (hkj hj)⟩ }
end
lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subfield K} (hS : directed (≤) S) :
((⨆ i, S i : subfield K) : set K) = ⋃ i, ↑(S i) :=
set.ext $ λ x, by simp [mem_supr_of_directed hS]
lemma mem_Sup_of_directed_on {S : set (subfield K)} (Sne : S.nonempty)
(hS : directed_on (≤) S) {x : K} :
x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s :=
begin
haveI : nonempty S := Sne.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk]
end
lemma coe_Sup_of_directed_on {S : set (subfield K)} (Sne : S.nonempty) (hS : directed_on (≤) S) :
(↑(Sup S) : set K) = ⋃ s ∈ S, ↑s :=
set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS]
end subfield
namespace ring_hom
variables {s : subfield K}
open subfield
/-- Restrict the codomain of a ring homomorphism to a subfield that includes the range. -/
def cod_restrict_field (f : K →+* L)
(s : subfield L) (h : ∀ x, f x ∈ s) : K →+* s :=
{ to_fun := λ x, ⟨f x, h x⟩,
map_add' := λ x y, subtype.eq $ f.map_add x y,
map_zero' := subtype.eq f.map_zero,
map_mul' := λ x y, subtype.eq $ f.map_mul x y,
map_one' := subtype.eq f.map_one }
/-- Restriction of a ring homomorphism to a subfield of the domain. -/
def restrict_field (f : K →+* L) (s : subfield K) : s →+* L := f.comp s.subtype
@[simp] lemma restrict_field_apply (f : K →+* L) (x : s) : f.restrict_field s x = f x := rfl
/-- Restriction of a ring homomorphism to its range interpreted as a subfield. -/
def range_restrict_field (f : K →+* L) : K →+* f.range :=
f.cod_restrict' f.range $ λ x, ⟨x, subfield.mem_top x, rfl⟩
@[simp] lemma coe_range_restrict_field (f : K →+* L) (x : K) :
(f.range_restrict_field x : L) = f x := rfl
/-- The subfield of elements `x : R` such that `f x = g x`, i.e.,
the equalizer of f and g as a subfield of R -/
def eq_locus_field (f g : K →+* L) : subfield K :=
{ inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx],
carrier := {x | f x = g x}, .. (f : K →+* L).eq_locus g }
/-- If two ring homomorphisms are equal on a set, then they are equal on its subfield closure. -/
lemma eq_on_field_closure {f g : K →+* L} {s : set K} (h : set.eq_on f g s) :
set.eq_on f g (closure s) :=
show closure s ≤ f.eq_locus_field g, from closure_le.2 h
lemma eq_of_eq_on_subfield_top {f g : K →+* L} (h : set.eq_on f g (⊤ : subfield K)) :
f = g :=
ext $ λ x, h trivial
lemma eq_of_eq_on_of_field_closure_eq_top {s : set K} (hs : closure s = ⊤) {f g : K →+* L}
(h : s.eq_on f g) : f = g :=
eq_of_eq_on_subfield_top $ hs ▸ eq_on_field_closure h
lemma field_closure_preimage_le (f : K →+* L) (s : set L) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx
/-- The image under a ring homomorphism of the subfield generated by a set equals
the subfield generated by the image of the set. -/
lemma map_field_closure (f : K →+* L) (s : set K) :
(closure s).map f = closure (f '' s) :=
le_antisymm
(map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _)
(field_closure_preimage_le _ _))
(closure_le.2 $ set.image_subset _ subset_closure)
end ring_hom
namespace subfield
open ring_hom
/-- The ring homomorphism associated to an inclusion of subfields. -/
def inclusion {S T : subfield K} (h : S ≤ T) : S →+* T :=
S.subtype.cod_restrict_field _ (λ x, h x.2)
@[simp] lemma field_range_subtype (s : subfield K) : s.subtype.field_range = s :=
ext' $ (coe_srange _).trans subtype.range_coe
end subfield
namespace ring_equiv
variables {s t : subfield K}
/-- Makes the identity isomorphism from a proof two subfields of a multiplicative
monoid are equal. -/
def subfield_congr (h : s = t) : s ≃+* t :=
{ map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ subfield.ext'_iff.1 h }
end ring_equiv
namespace subfield
variables {s : set K}
lemma closure_preimage_le (f : K →+* L) (s : set L) :
closure (f ⁻¹' s) ≤ (closure s).comap f :=
closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx
end subfield
|
9859c717e0feb52c0c7fc74f4477855ccba3101e | 35b83be3126daae10419b573c55e1fed009d3ae8 | /_target/deps/mathlib/analysis/limits.lean | 3c34a00f9a39bcaf5c3e7446b50de67e85bdbdbe | [] | no_license | AHassan1024/Lean_Playground | ccb25b72029d199c0d23d002db2d32a9f2689ebc | a00b004c3a2eb9e3e863c361aa2b115260472414 | refs/heads/master | 1,586,221,905,125 | 1,544,951,310,000 | 1,544,951,310,000 | 157,934,290 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,723 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
A collection of limit properties.
-/
import algebra.big_operators algebra.group_power tactic.norm_num
analysis.ennreal analysis.topology.infinite_sum
noncomputable theory
open classical finset function filter
local attribute [instance] prop_decidable
section real
lemma has_sum_of_absolute_convergence {f : ℕ → ℝ}
(hf : ∃r, tendsto (λn, (range n).sum (λi, abs (f i))) at_top (nhds r)) : has_sum f :=
let f' := λs:finset ℕ, s.sum (λi, abs (f i)) in
suffices cauchy (map (λs:finset ℕ, s.sum f) at_top),
from complete_space.complete this,
cauchy_iff.mpr $ and.intro (map_ne_bot at_top_ne_bot) $
assume s hs,
let ⟨ε, hε, hsε⟩ := mem_uniformity_dist.mp hs, ⟨r, hr⟩ := hf in
have hε' : {p : ℝ × ℝ | dist p.1 p.2 < ε / 2} ∈ (@uniformity ℝ _).sets,
from mem_uniformity_dist.mpr ⟨ε / 2, div_pos_of_pos_of_pos hε two_pos, assume a b h, h⟩,
have cauchy (at_top.map $ λn, f' (range n)),
from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hr,
have ∃n, ∀{n'}, n ≤ n' → dist (f' (range n)) (f' (range n')) < ε / 2,
by simp [cauchy_iff, mem_at_top_sets] at this;
from let ⟨t, ⟨u, hu⟩, ht⟩ := this _ hε' in
⟨u, assume n' hn, ht $ set.prod_mk_mem_set_prod_eq.mpr ⟨hu _ (le_refl _), hu _ hn⟩⟩,
let ⟨n, hn⟩ := this in
have ∀{s}, range n ⊆ s → abs ((s \ range n).sum f) < ε / 2,
from assume s hs,
let ⟨n', hn'⟩ := @exists_nat_subset_range s in
have range n ⊆ range n', from finset.subset.trans hs hn',
have f'_nn : 0 ≤ f' (range n' \ range n), from zero_le_sum $ assume _ _, abs_nonneg _,
calc abs ((s \ range n).sum f) ≤ f' (s \ range n) : abs_sum_le_sum_abs
... ≤ f' (range n' \ range n) : sum_le_sum_of_subset_of_nonneg
(finset.sdiff_subset_sdiff hn' (finset.subset.refl _))
(assume _ _ _, abs_nonneg _)
... = abs (f' (range n' \ range n)) : (abs_of_nonneg f'_nn).symm
... = abs (f' (range n') - f' (range n)) :
by simp [f', (sum_sdiff ‹range n ⊆ range n'›).symm]
... = abs (f' (range n) - f' (range n')) : abs_sub _ _
... < ε / 2 : hn $ range_subset.mp this,
have ∀{s t}, range n ⊆ s → range n ⊆ t → dist (s.sum f) (t.sum f) < ε,
from assume s t hs ht,
calc abs (s.sum f - t.sum f) = abs ((s \ range n).sum f + - (t \ range n).sum f) :
by rw [←sum_sdiff hs, ←sum_sdiff ht]; simp
... ≤ abs ((s \ range n).sum f) + abs ((t \ range n).sum f) :
le_trans (abs_add_le_abs_add_abs _ _) $ by rw [abs_neg]; exact le_refl _
... < ε / 2 + ε / 2 : add_lt_add (this hs) (this ht)
... = ε : by rw [←add_div, add_self_div_two],
⟨(λs:finset ℕ, s.sum f) '' {s | range n ⊆ s}, image_mem_map $ mem_at_top (range n),
assume ⟨a, b⟩ ⟨⟨t, ht, ha⟩, ⟨s, hs, hb⟩⟩, by simp at ha hb; exact ha ▸ hb ▸ hsε (this ht hs)⟩
lemma is_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} {r : ℝ} (hf : ∀n, 0 ≤ f n) :
is_sum f r ↔ tendsto (λn, (range n).sum f) at_top (nhds r) :=
⟨tendsto_sum_nat_of_is_sum,
assume hr,
have tendsto (λn, (range n).sum (λn, abs (f n))) at_top (nhds r),
by simp [(λi, abs_of_nonneg (hf i)), hr],
let ⟨p, h⟩ := has_sum_of_absolute_convergence ⟨r, this⟩ in
have hp : tendsto (λn, (range n).sum f) at_top (nhds p), from tendsto_sum_nat_of_is_sum h,
have p = r, from tendsto_nhds_unique at_top_ne_bot hp hr,
this ▸ h⟩
end real
lemma mul_add_one_le_pow {r : ℝ} (hr : 0 ≤ r) : ∀{n:ℕ}, (n:ℝ) * r + 1 ≤ (r + 1) ^ n
| 0 := by simp; exact le_refl 1
| (n + 1) :=
let h : (n:ℝ) ≥ 0 := nat.cast_nonneg n in
calc ↑(n + 1) * r + 1 ≤ ((n + 1) * r + 1) + r * r * n :
le_add_of_le_of_nonneg (le_refl _) (mul_nonneg (mul_nonneg hr hr) h)
... = (r + 1) * (n * r + 1) : by simp [mul_add, add_mul, mul_comm, mul_assoc]
... ≤ (r + 1) * (r + 1) ^ n : mul_le_mul (le_refl _) mul_add_one_le_pow
(add_nonneg (mul_nonneg h hr) zero_le_one) (add_nonneg hr zero_le_one)
lemma tendsto_pow_at_top_at_top_of_gt_1 {r : ℝ} (h : r > 1) : tendsto (λn:ℕ, r ^ n) at_top at_top :=
tendsto_infi.2 $ assume p, tendsto_principal.2 $
let ⟨n, hn⟩ := exists_nat_gt (p / (r - 1)) in
have hn_nn : (0:ℝ) ≤ n, from nat.cast_nonneg n,
have r - 1 > 0, from sub_lt_iff_lt_add.mp $ by simp; assumption,
have p ≤ r ^ n,
from calc p = (p / (r - 1)) * (r - 1) : (div_mul_cancel _ $ ne_of_gt this).symm
... ≤ n * (r - 1) : mul_le_mul (le_of_lt hn) (le_refl _) (le_of_lt this) hn_nn
... ≤ n * (r - 1) + 1 : le_add_of_le_of_nonneg (le_refl _) zero_le_one
... ≤ ((r - 1) + 1) ^ n : mul_add_one_le_pow $ le_of_lt this
... ≤ r ^ n : by simp; exact le_refl _,
show {n | p ≤ r ^ n} ∈ at_top.sets,
from mem_at_top_sets.mpr ⟨n, assume m hnm, le_trans this (pow_le_pow (le_of_lt h) hnm)⟩
lemma tendsto_inverse_at_top_nhds_0 : tendsto (λr:ℝ, r⁻¹) at_top (nhds 0) :=
tendsto_orderable_unbounded (no_top 0) (no_bot 0) $ assume l u hl hu,
mem_at_top_sets.mpr ⟨u⁻¹ + 1, assume b hb,
have u⁻¹ < b, from lt_of_lt_of_le (lt_add_of_pos_right _ zero_lt_one) hb,
⟨lt_trans hl $ inv_pos $ lt_trans (inv_pos hu) this,
lt_of_one_div_lt_one_div hu $
begin
rw [inv_eq_one_div],
simp [-one_div_eq_inv, div_div_eq_mul_div, div_one],
simp [this]
end⟩⟩
lemma map_succ_at_top_eq : map nat.succ at_top = at_top :=
le_antisymm
(assume s hs,
let ⟨b, hb⟩ := mem_at_top_sets.mp hs in
mem_at_top_sets.mpr ⟨b, assume c hc, hb (c + 1) $ le_trans hc $ nat.le_succ _⟩)
(assume s hs,
let ⟨b, hb⟩ := mem_at_top_sets.mp hs in
mem_at_top_sets.mpr ⟨b + 1, assume c,
match c with
| 0 := assume h,
have 0 > 0, from lt_of_lt_of_le (lt_add_of_le_of_pos (nat.zero_le _) zero_lt_one) h,
(lt_irrefl 0 this).elim
| (c+1) := assume h, hb _ (nat.le_of_succ_le_succ h)
end⟩)
lemma tendsto_comp_succ_at_top_iff {α : Type*} {f : ℕ → α} {x : filter α} :
tendsto (λn, f (nat.succ n)) at_top x ↔ tendsto f at_top x :=
calc tendsto (f ∘ nat.succ) at_top x ↔ tendsto f (map nat.succ at_top) x : by simp [tendsto, filter.map_map]
... ↔ _ : by rw [map_succ_at_top_eq]
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (nhds 0) :=
by_cases
(assume : r = 0, tendsto_comp_succ_at_top_iff.mp $ by simp [pow_succ, this, tendsto_const_nhds])
(assume : r ≠ 0,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (nhds 0),
from (tendsto_pow_at_top_at_top_of_gt_1 $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂).comp
tendsto_inverse_at_top_nhds_0,
tendsto_cong this $ univ_mem_sets' $ by simp *)
lemma tendsto_coe_iff {f : ℕ → ℕ} : tendsto (λ n, (f n : ℝ)) at_top at_top ↔ tendsto f at_top at_top :=
⟨ λ h, tendsto_infi.2 $ λ i, tendsto_principal.2
(have _, from tendsto_infi.1 h i, by simpa using tendsto_principal.1 this),
λ h, tendsto.comp h tendsto_of_nat_at_top_at_top ⟩
lemma tendsto_pow_at_top_at_top_of_gt_1_nat {k : ℕ} (h : k > 1) : tendsto (λn:ℕ, k ^ n) at_top at_top :=
tendsto_coe_iff.1 $
have hr : (k : ℝ) > 1, from show (k : ℝ) > (1 : ℕ), from nat.cast_lt.2 h,
by simpa using tendsto_pow_at_top_at_top_of_gt_1 hr
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (nhds 0) :=
tendsto.comp (tendsto_coe_iff.2 tendsto_id) tendsto_inverse_at_top_nhds_0
lemma tendsto_one_div_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1/(n : ℝ)) at_top (nhds 0) :=
by simpa only [inv_eq_one_div] using tendsto_inverse_at_top_nhds_0_nat
lemma sum_geometric' {r : ℝ} (h : r ≠ 0) :
∀{n}, (finset.range n).sum (λi, (r + 1) ^ i) = ((r + 1) ^ n - 1) / r
| 0 := by simp [zero_div]
| (n+1) :=
by simp [@sum_geometric' n, h, pow_succ, add_div_eq_mul_add_div, add_mul, mul_comm, mul_assoc]
lemma sum_geometric {r : ℝ} {n : ℕ} (h : r ≠ 1) :
(range n).sum (λi, r ^ i) = (r ^ n - 1) / (r - 1) :=
calc (range n).sum (λi, r ^ i) = (range n).sum (λi, ((r - 1) + 1) ^ i) :
by simp
... = (((r - 1) + 1) ^ n - 1) / (r - 1) :
sum_geometric' $ by simp [sub_eq_iff_eq_add, -sub_eq_add_neg, h]
... = (r ^ n - 1) / (r - 1) :
by simp
lemma is_sum_geometric {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
is_sum (λn:ℕ, r ^ n) (1 / (1 - r)) :=
have r ≠ 1, from ne_of_lt h₂,
have r + -1 ≠ 0,
by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption,
have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (nhds ((0 - 1) * (r - 1)⁻¹)),
from tendsto_mul
(tendsto_sub (tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂) tendsto_const_nhds) tendsto_const_nhds,
(is_sum_iff_tendsto_nat_of_nonneg $ pow_nonneg h₁).mpr $
by simp [neg_inv, sum_geometric, div_eq_mul_inv, *] at *
lemma is_sum_geometric_two (a : ℝ) : is_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert is_sum_mul_left (a / 2) (is_sum_geometric
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp,
rw ← pow_inv; [refl, exact two_ne_zero] },
{ norm_num, rw div_mul_cancel _ two_ne_zero }
end
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, is_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : is_sum f ε := is_sum_geometric_two _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
let g : ℕ → ℝ := λ n, option.cases_on (encodable.decode2 ι n) 0 (f ∘ encodable.encode),
have : ∀ n, g n = 0 ∨ g n = f n,
{ intro n, dsimp [g], cases e : encodable.decode2 ι n with a,
{ exact or.inl rfl },
{ simp [encodable.mem_decode2.1 e] } },
cases has_sum_of_has_sum_of_sub ⟨_, hf⟩ this with c hg,
have cε : c ≤ ε,
{ refine is_sum_le (λ n, _) hg hf,
cases this n; rw h, exact le_of_lt (f0 _) },
have hs : ∀ n, g n ≠ 0 → (encodable.decode2 ι n).is_some,
{ intros n h, dsimp [g] at h,
cases encodable.decode2 ι n,
exact (h rfl).elim, exact rfl },
refine ⟨c, _, cε⟩,
refine is_sum_of_is_sum_ne_zero
(λ n h, option.get (hs n h)) (λ n _, ne_of_gt (f0 _))
(λ i _, encodable.encode i) (λ n h, ne_of_gt _)
(λ n h, _) (λ i _, _) (λ i _, _) hg,
{ dsimp [g], rw encodable.encodek2, exact f0 _ },
{ exact encodable.mem_decode2.1 (option.get_mem _) },
{ exact option.get_of_mem _ (encodable.encodek2 _) },
{ dsimp [g], rw encodable.encodek2 }
end
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, is_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := dense hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, (nnreal.coe_lt _ _).2 $ hε' i,
⟨c, is_sum_le (assume i, le_of_lt $ hε' i) is_sum_zero hc ⟩, nnreal.is_sum_coe.1 hc,
lt_of_le_of_lt ((nnreal.coe_le _ _).1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑ i, (ε' i : ennreal)) < ε :=
begin
rcases dense hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal |
77b3e2a57783dc5822d35eb1de20b4150fd73a74 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Data/Json/FromToJson.lean | 6b47212aef48f30de6b7eec02c3fc8a0280f1a1d | [
"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 | 6,315 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Marc Huisinga
-/
import Lean.Data.Json.Basic
import Lean.Data.Json.Printer
namespace Lean
universe u
class FromJson (α : Type u) where
fromJson? : Json → Except String α
export FromJson (fromJson?)
class ToJson (α : Type u) where
toJson : α → Json
export ToJson (toJson)
instance : FromJson Json := ⟨Except.ok⟩
instance : ToJson Json := ⟨id⟩
instance : FromJson JsonNumber := ⟨Json.getNum?⟩
instance : ToJson JsonNumber := ⟨Json.num⟩
-- looks like id, but there are coercions happening
instance : FromJson Bool := ⟨Json.getBool?⟩
instance : ToJson Bool := ⟨fun b => b⟩
instance : FromJson Nat := ⟨Json.getNat?⟩
instance : ToJson Nat := ⟨fun n => n⟩
instance : FromJson Int := ⟨Json.getInt?⟩
instance : ToJson Int := ⟨fun n => Json.num n⟩
instance : FromJson String := ⟨Json.getStr?⟩
instance : ToJson String := ⟨fun s => s⟩
instance : FromJson System.FilePath := ⟨fun j => System.FilePath.mk <$> Json.getStr? j⟩
instance : ToJson System.FilePath := ⟨fun p => p.toString⟩
instance [FromJson α] : FromJson (Array α) where
fromJson?
| Json.arr a => a.mapM fromJson?
| j => throw s!"expected JSON array, got '{j}'"
instance [ToJson α] : ToJson (Array α) :=
⟨fun a => Json.arr (a.map toJson)⟩
instance [FromJson α] : FromJson (List α) where
fromJson? j := (fromJson? j (α := Array α)).map Array.toList
instance [ToJson α] : ToJson (List α) where
toJson xs := toJson xs.toArray
instance [FromJson α] : FromJson (Option α) where
fromJson?
| Json.null => Except.ok none
| j => some <$> fromJson? j
instance [ToJson α] : ToJson (Option α) :=
⟨fun
| none => Json.null
| some a => toJson a⟩
instance {α : Type u} {β : Type v} [FromJson α] [FromJson β] : FromJson (α × β) where
fromJson?
| Json.arr #[ja, jb] => do
let ⟨a⟩ : ULift.{v} α := ← (fromJson? ja).map ULift.up
let ⟨b⟩ : ULift.{u} β := ← (fromJson? jb).map ULift.up
return (a, b)
| j => throw s!"expected pair, got '{j}'"
instance [ToJson α] [ToJson β] : ToJson (α × β) where
toJson := fun (a, b) => Json.arr #[toJson a, toJson b]
instance : FromJson Name where
fromJson? j := do
let s ← j.getStr?
if s == "[anonymous]" then
return Name.anonymous
else
let n := s.toName
if n.isAnonymous then throw s!"expected a `Name`, got '{j}'"
return n
instance : ToJson Name where
toJson n := toString n
/-- Note that `USize`s and `UInt64`s are stored as strings because JavaScript
cannot represent 64-bit numbers. -/
def bignumFromJson? (j : Json) : Except String Nat := do
let s ← j.getStr?
let some v := Syntax.decodeNatLitVal? s -- TODO maybe this should be in Std
| throw s!"expected a string-encoded number, got '{j}'"
return v
def bignumToJson (n : Nat) : Json :=
toString n
instance : FromJson USize where
fromJson? j := do
let n ← bignumFromJson? j
if n ≥ USize.size then
throw "value '{j}' is too large for `USize`"
return USize.ofNat n
instance : ToJson USize where
toJson v := bignumToJson (USize.toNat v)
instance : FromJson UInt64 where
fromJson? j := do
let n ← bignumFromJson? j
if n ≥ UInt64.size then
throw "value '{j}' is too large for `UInt64`"
return UInt64.ofNat n
instance : ToJson UInt64 where
toJson v := bignumToJson (UInt64.toNat v)
instance : ToJson Float where
toJson x :=
match JsonNumber.fromFloat? x with
| Sum.inl e => Json.str e
| Sum.inr n => Json.num n
instance : FromJson Float where
fromJson? := fun
| (Json.str "Infinity") => Except.ok (1.0 / 0.0)
| (Json.str "-Infinity") => Except.ok (-1.0 / 0.0)
| (Json.str "NaN") => Except.ok (0.0 / 0.0)
| (Json.num jn) => Except.ok jn.toFloat
| _ => Except.error "Expected a number or a string 'Infinity', '-Infinity', 'NaN'."
instance [ToJson α] : ToJson (RBMap String α cmp) where
toJson m := Json.obj <| RBNode.map (fun _ => toJson) <| m.val
instance {cmp} [FromJson α] : FromJson (RBMap String α cmp) where
fromJson? j := do
let o ← j.getObj?
o.foldM (fun x k v => x.insert k <$> fromJson? v) ∅
namespace Json
instance : FromJson Structured := ⟨fun
| arr a => return Structured.arr a
| obj o => return Structured.obj o
| j => throw s!"expected structured object, got '{j}'"⟩
instance : ToJson Structured := ⟨fun
| Structured.arr a => arr a
| Structured.obj o => obj o⟩
def toStructured? [ToJson α] (v : α) : Except String Structured :=
fromJson? (toJson v)
def getObjValAs? (j : Json) (α : Type u) [FromJson α] (k : String) : Except String α :=
fromJson? <| j.getObjValD k
def setObjValAs! (j : Json) {α : Type u} [ToJson α] (k : String) (v : α) : Json :=
j.setObjVal! k <| toJson v
def opt [ToJson α] (k : String) : Option α → List (String × Json)
| none => []
| some o => [⟨k, toJson o⟩]
/-- Parses a JSON-encoded `structure` or `inductive` constructor. Used mostly by `deriving FromJson`. -/
def parseTagged
(json : Json)
(tag : String)
(nFields : Nat)
(fieldNames? : Option (Array Name)) : Except String (Array Json) :=
if nFields == 0 then
match getStr? json with
| Except.ok s => if s == tag then Except.ok #[] else throw s!"incorrect tag: {s} ≟ {tag}"
| Except.error err => Except.error err
else
match getObjVal? json tag with
| Except.ok payload =>
match fieldNames? with
| some fieldNames =>
do
let mut fields := #[]
for fieldName in fieldNames do
fields := fields.push (←getObjVal? payload fieldName.getString!)
Except.ok fields
| none =>
if nFields == 1 then
Except.ok #[payload]
else
match getArr? payload with
| Except.ok fields =>
if fields.size == nFields then
Except.ok fields
else
Except.error s!"incorrect number of fields: {fields.size} ≟ {nFields}"
| Except.error err => Except.error err
| Except.error err => Except.error err
end Json
end Lean
|
2d45745cdfd03ac1a9ebaaf9e9cd837baaff2417 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /tests/lean/run/doNotation2.lean | d3843b889a52cec67606dceb5597c6b20a784f52 | [
"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 | 4,083 | lean | def f (x : Nat) : IO Nat := do
IO.println "hello world"
let aux (y : Nat) (z : Nat) : IO Nat := do
IO.println "aux started"
IO.println s!"y: {y}, z: {z}"
pure (x+y)
discard <| aux x
(x + 1) -- It is part of the application since it is indented
discard <| aux x (x -- parentheses use `withoutPosition`
-1)
discard <| aux x x;
aux x
x
#eval f 10
def g (xs : List Nat) : StateT Nat Id Nat := do
let mut xs := xs
if xs.isEmpty then
xs := [← get]
dbg_trace ">>> xs: {xs}"
return xs.length
#eval g [1, 2, 3] |>.run' 10
#eval g [] |>.run' 10
theorem ex1 : (g [1, 2, 4, 5] |>.run' 0) = 4 :=
rfl
theorem ex2 : (g [] |>.run' 0) = 1 :=
rfl
def h (x : Nat) (y : Nat) : Nat := do
let mut x := x
let mut y := y
if x > 0 then
let y := x + 1 -- this is a new `y` that shadows the one above
x := y
else
y := y + 1
return x + y
theorem ex3 (y : Nat) : h 0 y = 0 + (y + 1) :=
rfl
theorem ex4 (y : Nat) : h 1 y = (1 + 1) + y :=
rfl
def sumOdd (xs : List Nat) (threshold : Nat) : Nat := do
let mut sum := 0
for x in xs do
if x % 2 == 1 then
sum := sum + x
if sum > threshold then
break
unless x % 2 == 1 do
continue
dbg_trace ">> x: {x}"
return sum
#eval sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10
theorem ex5 : sumOdd [1, 2, 3, 4, 5, 6, 7, 9, 11, 101] 10 = 16 :=
rfl
-- We need `Id.run` because we still have `Monad Option`
def find? (xs : List Nat) (p : Nat → Bool) : Option Nat := Id.run do
let mut result := none
for x in xs do
if p x then
result := x
break
return result
def sumDiff (ps : List (Nat × Nat)) : Nat := do
let mut sum := 0
for (x, y) in ps do
sum := sum + x - y
return sum
theorem ex7 : sumDiff [(2, 1), (10, 5)] = 6 :=
rfl
def f1 (x : Nat) : IO Unit := do
let rec loop : Nat → IO Unit
| 0 => pure ()
| x+1 => do IO.println x; loop x
loop x
#eval f1 10
partial def f2 (x : Nat) : IO Unit := do
let rec
isEven : Nat → Bool
| 0 => true
| x+1 => isOdd x,
isOdd : Nat → Bool
| 0 => false
| x+1 => isEven x
IO.println ("isOdd(" ++ toString x ++ "): " ++ toString (isOdd x))
#eval f2 11
#eval f2 10
def split (xs : List Nat) : List Nat × List Nat := do
let mut evens := []
let mut odds := []
for x in xs.reverse do
if x % 2 == 0 then
evens := x :: evens
else
odds := x :: odds
return (evens, odds)
theorem ex8 : split [1, 2, 3, 4] = ([2, 4], [1, 3]) :=
rfl
def f3 (x : Nat) : IO Bool := do
let y ← cond (x == 0) (do IO.println "hello"; true) false;
!y
def f4 (x y : Nat) : Nat × Nat := do
let mut (x, y) := (x, y)
match x with
| 0 => y := y + 1
| _ => x := x + y
return (x, y)
#eval f4 0 10
#eval f4 5 10
theorem ex9 (y : Nat) : f4 0 y = (0, y+1) :=
rfl
theorem ex10 (x y : Nat) : f4 (x+1) y = ((x+1)+y, y) :=
rfl
def f5 (x y : Nat) : Nat × Nat := do
let mut (x, y) := (x, y)
match x with
| 0 => y := y + 1
| z+1 => dbg_trace "z: {z}"; x := x + y
return (x, y)
#eval f5 5 6
theorem ex11 (x y : Nat) : f5 (x+1) y = ((x+1)+y, y) :=
rfl
def f6 (x : Nat) : Nat := do
let mut x := x
if x > 10 then
return 0
x := x + 1
return x
theorem ex12 : f6 11 = 0 :=
rfl
theorem ex13 : f6 5 = 6 :=
rfl
def findOdd (xs : List Nat) : Nat := do
for x in xs do
if x % 2 == 1 then
return x
return 0
theorem ex14 : findOdd [2, 4, 5, 8, 7] = 5 :=
rfl
theorem ex15 : findOdd [2, 4, 8, 10] = 0 :=
rfl
def f7 (ref : IO.Ref (Option (Nat × Nat))) : IO Nat := do
let some (x, y) ← ref.get | pure 100
IO.println (toString x ++ ", " ++ toString y)
return x+y
def f7Test : IO Unit := do
unless (← f7 (← IO.mkRef (some (10, 20)))) == 30 do throw $ IO.userError "unexpected"
unless (← f7 (← IO.mkRef none)) == 100 do throw $ IO.userError "unexpected"
#eval f7Test
def f8 (x : Nat) : IO Nat := do
let y ←
if x == 0 then
IO.println "x is zero"
return 100 -- returns from the `do`-block
else
pure (x + 1)
IO.println ("y: " ++ toString y)
return y
def f8Test : IO Unit := do
unless (← f8 0) == 100 do throw $ IO.userError "unexpected"
unless (← f8 1) == 2 do throw $ IO.userError "unexpected"
#eval f8Test
|
faaf34d3d05f968b4b45479c1808bacda4d02d89 | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/topology/metric_space/gromov_hausdorff_realized.lean | 539c18c82600d4b2fd0805fad3753d75099019c1 | [
"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 | 27,473 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
Construction of a good coupling between nonempty compact metric spaces, minimizing
their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff
distance between nonempty compact metric spaces -/
import topology.bounded_continuous_function topology.metric_space.gluing
topology.metric_space.hausdorff_distance
noncomputable theory
open_locale classical
universes u v w
open classical lattice set function topological_space filter metric quotient
open bounded_continuous_function
open sum (inl inr)
set_option class.instance_max_depth 50
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section Gromov_Hausdorff_realized
/- This section shows that the Gromov-Hausdorff distance
is realized. For this, we consider candidate distances on the disjoint union
α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff
distance, and show that they form a compact family by applying Arzela-Ascoli
theorem. The existence of a minimizer follows. -/
section definitions
variables (α : Type u) (β : Type v)
[metric_space α] [compact_space α] [nonempty α]
[metric_space β] [compact_space β] [nonempty β]
@[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ
@[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ
private def max_var : ℝ := 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β)
private lemma one_le_max_var : 1 ≤ max_var α β := calc
(1 : real) = 2 * 0 + 1 + 2 * 0 : by simp
... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) :
by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg, diam_nonneg]; norm_num
/-- The set of functions on α ⊕ β that are candidates distances to realize the
minimum of the Hausdorff distances between α and β in a coupling -/
def candidates : set (prod_space_fun α β) :=
{f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y)
∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y))
∧ (∀x y, f (x, y) = f (y, x)))
∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z)))
∧ (∀x, f (x, x) = 0))
∧ (∀x y, f (x, y) ≤ max_var α β) }
/-- Version of the set of candidates in bounded_continuous_functions, to apply
Arzela-Ascoli -/
private def candidates_b : set (Cb α β) := {f : Cb α β | f.val ∈ candidates α β}
end definitions --section
section constructions
variables {α : Type u} {β : Type v}
[metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β]
{f : prod_space_fun α β} {x y z t : α ⊕ β}
local attribute [instance, priority 10] inhabited_of_nonempty'
private lemma max_var_bound : dist x y ≤ max_var α β := calc
dist x y ≤ diam (univ : set (α ⊕ β)) :
dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _)
... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) :
by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self]
... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) :
diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _))
... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) :
by { rw [isometry.diam_image isometry_on_inl, isometry.diam_image isometry_on_inr], refl }
... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp
... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) :
begin
apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, diam_nonneg, le_refl],
norm_num, norm_num
end
private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y
private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) :=
fA.1.1.2 x y z
private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x
private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) :=
begin
have : 0 ≤ 2 * f (x, y) := calc
0 = f (x, x) : (candidates_refl fA).symm
... ≤ f (x, y) + f (y, x) : candidates_triangle fA
... = f (x, y) + f (x, y) : by rw [candidates_symm fA]
... = 2 * f (x, y) : by ring,
by linarith
end
private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y :=
fA.1.1.1.1.1 x y
private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y :=
fA.1.1.1.1.2 x y
private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β :=
fA.2 x y
/-- candidates are bounded by max_var α β -/
private lemma candidates_dist_bound (fA : f ∈ candidates α β) :
∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y
| (inl x) (inl y) := calc
f (inl x, inl y) = dist x y : candidates_dist_inl fA x y
... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl }
... = 1 * dist (inl x) (inl y) : by simp
... ≤ max_var α β * dist (inl x) (inl y) :
mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg
| (inl x) (inr y) := calc
f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA
... = max_var α β * 1 : by simp
... ≤ max_var α β * dist (inl x) (inr y) :
mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β))
| (inr x) (inl y) := calc
f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA
... = max_var α β * 1 : by simp
... ≤ max_var α β * dist (inl x) (inr y) :
mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β))
| (inr x) (inr y) := calc
f (inr x, inr y) = dist x y : candidates_dist_inr fA x y
... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl }
... = 1 * dist (inr x) (inr y) : by simp
... ≤ max_var α β * dist (inr x) (inr y) :
mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg
/-- Technical lemma to prove that candidates are Lipschitz -/
private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) :=
calc
f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : add_le_add_right (candidates_triangle fA) _
... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) :
add_le_add_right (add_le_add_right (candidates_triangle fA) _ ) _
... = f (x, z) + f (t, y) : by simp
... ≤ max_var α β * dist x z + max_var α β * dist t y :
add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA)
... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) :
begin
apply add_le_add,
apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)),
apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (le_trans zero_le_one (one_le_max_var α β)),
end
... = 2 * max_var α β * max (dist x z) (dist y t) :
by { simp [dist_comm], ring }
... = 2 * max_var α β * dist (x, y) (z, t) : by refl
/-- Candidates are Lipschitz -/
private lemma candidates_lipschitz (fA : f ∈ candidates α β) (p q : (α ⊕ β) × (α ⊕ β)) :
dist (f p) (f q) ≤ 2 * max_var α β * dist p q :=
begin
rcases p with ⟨x, y⟩,
rcases q with ⟨z, t⟩,
rw real.dist_eq,
apply abs_le_of_le_of_neg_le,
{ exact candidates_lipschitz_aux fA },
{ have : -(f (x, y) - f (z, t)) = f (z, t) - f (x, y), by ring,
rw [this, dist_comm],
exact candidates_lipschitz_aux fA }
end
/-- candidates give rise to elements of bounded_continuous_functions -/
def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β :=
bounded_continuous_function.mk_of_compact f (continuous_of_lipschitz (candidates_lipschitz fA))
lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) :
candidates_b_of_candidates f fA ∈ candidates_b α β := fA
/-- The distance on α ⊕ β is a candidate -/
private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β :=
begin
simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true,
and_self, sum.forall, set.mem_set_of_eq, dist_self],
repeat { split
<|> exact (λa y z, dist_triangle_left _ _ _)
<|> exact (λx y, by refl)
<|> exact (λx y, max_var_bound) }
end
def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α]
[metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates
lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β :=
candidates_b_of_candidates_mem _ _
private lemma candidates_b_ne_empty : candidates_b α β ≠ ∅ :=
ne_empty_of_mem candidates_b_dist_mem_candidates_b
/-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous.
Equicontinuity follows from the Lipschitz control, we check closedness -/
private lemma closed_candidates_b : is_closed (candidates_b α β) :=
begin
have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} :=
λx y, is_closed_eq continuous_evalx continuous_const,
have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } :=
λx y, is_closed_eq continuous_evalx continuous_const,
have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} :=
λx y, is_closed_eq continuous_evalx continuous_evalx,
have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} :=
λx y z, is_closed_le continuous_evalx (continuous_add continuous_evalx continuous_evalx),
have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} :=
λx, is_closed_eq continuous_evalx continuous_const,
have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} :=
λx y, is_closed_le continuous_evalx continuous_const,
have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y})
∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y})
∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)})
∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)})
∩ (⋂x, {f : Cb α β | f (x, x) = 0})
∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) :=
begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end,
rw this,
repeat { apply is_closed_inter _ _
<|> apply is_closed_Inter _
<|> apply I1 _ _
<|> apply I2 _ _
<|> apply I3 _ _
<|> apply I4 _ _ _
<|> apply I5 _
<|> apply I6 _ _
<|> assume x },
end
/-- Compactness of candidates (in bounded_continuous_functions) follows -/
private lemma compact_candidates_b : compact (candidates_b α β) :=
begin
refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _,
{ rintros f ⟨x1, x2⟩ hf,
simp only [set.mem_Icc],
exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ },
{ refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _,
{ have : tendsto (λ (t : ℝ), 2 * max_var α β * t) (nhds 0) (nhds (2 * max_var α β * 0)) :=
tendsto_mul tendsto_const_nhds tendsto_id,
simpa using this },
{ assume x y f hf,
exact candidates_lipschitz hf _ _ } }
end
/-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not
in a metric space setting, so we need to define our custom version of Hausdorff distance,
called HD, and prove its basic properties. -/
def HD (f : Cb α β) := max (supr (λx:α, infi (λy:β, f (inl x, inr y))))
(supr (λy:β, infi (λx:α, f (inl x, inr y))))
/- We will show that HD is continuous on bounded_continuous_functions, to deduce that its
minimum on the compact set candidates_b is attained. Since it is defined in terms of
infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time
to check that the defining sets are bounded below or above. This is done in the next few
technical lemmas -/
lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) :=
let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in
⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (f x) (mem_range_self _)) _) _)⟩
private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), infi (λy:β, f (inl x, inr y) + C))) :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩,
refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩,
calc infi (λy:β, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C :
cinfi_le (HD_below_aux1 C)
... ≤ Cf + C : add_le_add ((λx, hCf (f x) (mem_range_self _)) _) (le_refl _)
end
lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) :=
let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in
⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (f x) (mem_range_self _)) _) _)⟩
private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), infi (λx:α, f (inl x, inr y) + C))) :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩,
refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩,
calc infi (λx:α, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C :
cinfi_le (HD_below_aux2 C)
... ≤ Cf + C : add_le_add ((λx, hCf (f x) (mem_range_self _)) _) (le_refl _)
end
/-- Explicit bound on HD (dist). This means that when looking for minimizers it will
be sufficient to look for functions with HD(f) bounded by this bound. -/
lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) :=
begin
refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)),
{ have A : infi (λy:β, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) :=
cinfi_le (by simpa using HD_below_aux1 0),
have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc
dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl
... ≤ diam (univ : set α) + 1 + diam (univ : set β) :
begin
apply add_le_add (add_le_add _ (le_refl _)),
exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _),
exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _)
end,
exact le_trans A B },
{ have A : infi (λx:α, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) :=
cinfi_le (by simpa using HD_below_aux2 0),
have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc
dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl
... ≤ diam (univ : set α) + 1 + diam (univ : set β) :
begin
apply add_le_add (add_le_add _ (le_refl _)),
exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _),
exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _)
end,
exact le_trans A B },
end
/- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we
prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/
private lemma HD_lipschitz_aux1 (f g : Cb α β) :
supr (λx:α, infi (λy:β, f (inl x, inr y))) ≤ supr (λx:α, infi (λy:β, g (inl x, inr y))) + dist f g :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩,
have Hcg : ∀x, cg ≤ g x := λx, hcg (g x) (mem_range_self _),
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩,
have Hcf : ∀x, cf ≤ f x := λx, hcf (f x) (mem_range_self _),
-- prove the inequality but with `dist f g` inside, by using inequalities comparing
-- supr to supr and infi to infi
have Z : supr (λx:α, infi (λy:β, f (inl x, inr y))) ≤ supr (λx:α, infi (λy:β, g (inl x, inr y) + dist f g)) :=
csupr_le_csupr (HD_bound_aux1 _ (dist f g))
(λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)),
-- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps
-- (here the addition of `dist f g`) preserve infimum and supremum
have E1 : ∀x, infi (λy:β, g (inl x, inr y)) + dist f g =
infi ((λz, z + dist f g) ∘ (λy:β, (g (inl x, inr y)))),
{ assume x,
refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _,
{ exact continuous_add continuous_id continuous_const },
{ assume x y hx, simpa },
{ show bdd_below (range (λ (y : β), g (inl x, inr y))),
from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } },
have E2 : supr (λx:α, infi (λy:β, g (inl x, inr y))) + dist f g =
supr ((λz, z + dist f g) ∘ (λx:α, infi (λy:β, g (inl x, inr y)))),
{ refine csupr_of_csupr_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _,
{ exact continuous_add continuous_id continuous_const },
{ assume x y hx, simpa },
{ by simpa using HD_bound_aux1 _ 0 } },
-- deduce the result from the above two steps
simp only [add_comm] at Z,
simpa [E2, E1, function.comp]
end
private lemma HD_lipschitz_aux2 (f g : Cb α β) :
supr (λy:β, infi (λx:α, f (inl x, inr y))) ≤ supr (λy:β, infi (λx:α, g (inl x, inr y))) + dist f g :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩,
have Hcg : ∀x, cg ≤ g x := λx, hcg (g x) (mem_range_self _),
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩,
have Hcf : ∀x, cf ≤ f x := λx, hcf (f x) (mem_range_self _),
-- prove the inequality but with `dist f g` inside, by using inequalities comparing
-- supr to supr and infi to infi
have Z : supr (λy:β, infi (λx:α, f (inl x, inr y))) ≤ supr (λy:β, infi (λx:α, g (inl x, inr y) + dist f g)) :=
csupr_le_csupr (HD_bound_aux2 _ (dist f g))
(λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)),
-- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps
-- (here the addition of `dist f g`) preserve infimum and supremum
have E1 : ∀y, infi (λx:α, g (inl x, inr y)) + dist f g =
infi ((λz, z + dist f g) ∘ (λx:α, (g (inl x, inr y)))),
{ assume y,
refine cinfi_of_cinfi_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _,
{ exact continuous_add continuous_id continuous_const },
{ assume x y hx, simpa },
{ show bdd_below (range (λx:α, g (inl x, inr y))),
from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } },
have E2 : supr (λy:β, infi (λx:α, g (inl x, inr y))) + dist f g =
supr ((λz, z + dist f g) ∘ (λy:β, infi (λx:α, g (inl x, inr y)))),
{ refine csupr_of_csupr_of_monotone_of_continuous (_ : continuous (λ (z : ℝ), z + dist f g)) _ _,
{ exact continuous_add continuous_id continuous_const },
{ assume x y hx, simpa },
{ by simpa using HD_bound_aux2 _ 0 } },
-- deduce the result from the above two steps
simp only [add_comm] at Z,
simpa [E2, E1, function.comp]
end
private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g :=
max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _))
(le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _))
/-- Conclude that HD, being Lipschitz, is continuous -/
private lemma HD_continuous : continuous (HD : Cb α β → ℝ) :=
uniform_continuous.continuous $ uniform_continuous_of_le_add 1 $
λf g, begin simp, exact HD_lipschitz_aux3 _ _ end
end constructions --section
section consequences
variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β]
/- Now that we have proved that the set of candidates is compact, and that HD is continuous,
we can finally select a candidate minimizing HD. This will be the candidate realizing the
optimal coupling. -/
private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g :=
exists_forall_le_of_compact_of_continuous _ HD_continuous _ compact_candidates_b candidates_b_ne_empty
private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β)
private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β :=
by cases (classical.some_spec (exists_minimizer α β)); assumption
private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g :=
let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg
/-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the
predistance is given by the candidate. Then, we will identify points at 0 predistance
to obtain a genuine metric space -/
def premetric_optimal_GH_dist : premetric_space (α ⊕ β) :=
{ dist := λp q, optimal_GH_dist α β (p, q),
dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β),
dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β),
dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) }
local attribute [instance] premetric_optimal_GH_dist premetric.dist_setoid
/-- A metric space which realizes the optimal coupling between α and β -/
@[reducible] definition optimal_GH_coupling : Type* :=
premetric.metric_quot (α ⊕ β)
instance : metric_space (optimal_GH_coupling α β) := by apply_instance
private lemma optimal_GH_dist.dist_eq (p q : α ⊕ β) : dist ⟦p⟧ ⟦q⟧ = (optimal_GH_dist α β).val (p, q) := rfl
/-- Injection of α in the optimal coupling between α and β -/
def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧
/-- The injection of α in the optimal coupling between α and β is an isometry. -/
lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y,
rw [optimal_GH_dist.dist_eq α β],
exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _,
end
/-- Injection of β in the optimal coupling between α and β -/
def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧
/-- The injection of β in the optimal coupling between α and β is an isometry. -/
lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y,
rw [optimal_GH_dist.dist_eq α β],
exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _,
end
/-- The optimal coupling between two compact spaces α and β is still a compact space -/
instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) :=
⟨begin
have : (univ : set (optimal_GH_coupling α β)) =
(optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ),
{ refine subset.antisymm (λxc hxc, _) (subset_univ _),
rcases quotient.exists_rep xc with ⟨x, hx⟩,
cases x; rw ← hx,
{ have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl,
rw this,
exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) },
{ have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl,
rw this,
exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } },
rw this,
exact compact_union_of_compact
(compact_image (compact_univ) (isometry_optimal_GH_injl α β).continuous)
(compact_image (compact_univ) (isometry_optimal_GH_injr α β).continuous)
end⟩
/-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the
optimal coupling. This follows from the fact that HD of the optimal candidate is exactly
the Hausdorff distance in the optimal coupling, although we only prove here the inequality
we need. -/
lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) :
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f :=
begin
refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h),
have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r,
{ assume x hx,
rcases mem_range.1 hx with ⟨z, hz⟩,
rw ← hz,
have I1 : supr (λx:α, infi (λy:β, optimal_GH_dist α β (inl x, inr y))) < r :=
lt_of_le_of_lt (le_max_left _ _) hr,
have I2 : infi (λy:β, optimal_GH_dist α β (inl z, inr y)) ≤
supr (λx:α, infi (λy:β, optimal_GH_dist α β (inl x, inr y))) :=
le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _),
have I : infi (λy:β, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1,
rcases exists_lt_of_cInf_lt (by simpa) I with ⟨r', r'range, hr'⟩,
rcases mem_range.1 r'range with ⟨z', hz'⟩,
existsi [optimal_GH_injr α β z', mem_range_self _],
have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end,
exact this },
refine Hausdorff_dist_le_of_mem_dist _ A _,
{ rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _,
rcases A _ this with ⟨y, yrange, hy⟩,
exact le_trans dist_nonneg hy },
{ assume y hy,
rcases mem_range.1 hy with ⟨z, hz⟩,
rw ← hz,
have I1 : supr (λy:β, infi (λx:α, optimal_GH_dist α β (inl x, inr y))) < r :=
lt_of_le_of_lt (le_max_right _ _) hr,
have I2 : infi (λx:α, optimal_GH_dist α β (inl x, inr z)) ≤
supr (λy:β, infi (λx:α, optimal_GH_dist α β (inl x, inr y))) :=
le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _),
have I : infi (λx:α, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1,
rcases exists_lt_of_cInf_lt (by simpa) I with ⟨r', r'range, hr'⟩,
rcases mem_range.1 r'range with ⟨z', hz'⟩,
existsi [optimal_GH_injl α β z', mem_range_self _],
have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end,
rw dist_comm,
exact this }
end
end consequences
/- We are done with the construction of the optimal coupling -/
end Gromov_Hausdorff_realized
end Gromov_Hausdorff
|
5c6662d034bdac60f992090bbf8b190cb6d8ff63 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /analysis/topology/topological_groups.lean | 4d3511d835d36b8f275b7686348a7f4e101bdaa5 | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 6,978 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
Basic constructions for topological groups:
* `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to
construct a canonical uniformity for a topological add group.
* `add_group_with_zero_nhd`: construct the topological structure from a group with a neighbourhood
around zero. Then with `topological_add_group.to_uniform_space` one can derive a `uniform_space`.
-/
import data.set.basic data.set.function
import algebra.pi_instances
import analysis.topology.completion
noncomputable theory
open filter
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
section topological_add_comm_group
variables {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G]
variable (G)
def topological_add_group.to_uniform_space : uniform_space G :=
{ uniformity := comap (λp:G×G, p.2 - p.1) (nhds 0),
refl :=
by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 0));
simp [set.subset_def] {contextual := tt},
symm :=
begin
suffices : tendsto ((λp, -p) ∘ (λp:G×G, p.2 - p.1)) (comap (λp:G×G, p.2 - p.1) (nhds 0)) (nhds (-0)),
{ simpa [(∘), tendsto_comap_iff] },
exact tendsto.comp tendsto_comap (tendsto_neg tendsto_id)
end,
comp :=
begin
intros D H,
rw mem_lift'_sets,
{ rcases H with ⟨U, U_nhds, U_sub⟩,
rcases exists_nhds_half U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩,
existsi ((λp:G×G, p.2 - p.1) ⁻¹' V),
have H : (λp:G×G, p.2 - p.1) ⁻¹' V ∈ (comap (λp:G×G, p.2 - p.1) (nhds (0 : G))).sets,
by existsi [V, V_nhds] ; refl,
existsi H,
have comp_rel_sub : comp_rel ((λp:G×G, p.2 - p.1) ⁻¹' V) ((λp:G×G, p.2 - p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 - p.1) ⁻¹' U,
begin
intros p p_comp_rel,
rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩,
simpa using V_sum _ _ Hz1 Hz2
end,
exact set.subset.trans comp_rel_sub U_sub },
{ exact monotone_comp_rel monotone_id monotone_id }
end,
is_open_uniformity :=
begin
intro S,
let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S},
show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ (comap (λp:G×G, p.2 - p.1) (nhds (0 : G))).sets,
rw [is_open_iff_mem_nhds],
refine forall_congr (assume a, forall_congr (assume ha, _)),
rw [← nhds_translation a, mem_comap_sets, mem_comap_sets],
refine exists_congr (assume t, exists_congr (assume ht, _)),
show (λ (y : G), y - a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd - p.fst) ⁻¹' t ⊆ S' a,
split,
{ rintros h ⟨x, y⟩ hx rfl, exact h hx },
{ rintros h x hx, exact @h (a, x) hx rfl }
end }
section
local attribute [instance] topological_add_group.to_uniform_space
lemma uniformity_eq_comap_nhds_zero' : uniformity = comap (λp:G×G, p.2 - p.1) (nhds (0 : G)) := rfl
variable {G}
lemma topological_add_group_is_uniform : uniform_add_group G :=
have tendsto
((λp:(G×G), p.1 - p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)))
(comap (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((nhds 0).prod (nhds 0)))
(nhds (0 - 0)) :=
tendsto_comap.comp (tendsto_sub tendsto_fst tendsto_snd),
begin
constructor,
rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff,
uniformity_eq_comap_nhds_zero' G, tendsto_comap_iff, prod_comap_comap_eq],
simpa [(∘)]
end
end
lemma to_uniform_space_eq [u : uniform_space α] [add_comm_group α] [uniform_add_group α]:
topological_add_group.to_uniform_space α = u :=
begin
ext : 1,
show @uniformity α (topological_add_group.to_uniform_space α) = uniformity,
rw [uniformity_eq_comap_nhds_zero' α, uniformity_eq_comap_nhds_zero α]
end
end topological_add_comm_group
/-- β additive group with a neighbourhood around 0.
Only used to construct a topology and uniform space.
This is currently only available for commutative groups, but it can be extended to
non-commutative groups too.
-/
class add_group_with_zero_nhd (α : Type u) extends add_comm_group α :=
(Z : filter α)
(zero_Z {} : pure 0 ≤ Z)
(sub_Z {} : tendsto (λp:α×α, p.1 - p.2) (Z.prod Z) Z)
namespace add_group_with_zero_nhd
variables (α) [add_group_with_zero_nhd α]
local notation `Z` := add_group_with_zero_nhd.Z
instance : topological_space α :=
topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α)
variables {α}
lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) :=
have tendsto (λa, (0:α)) (Z α) (Z α),
by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt},
have tendsto (λa:α, 0 - a) (Z α) (Z α), from
(tendsto.prod_mk this tendsto_id).comp sub_Z,
by simpa
lemma add_Z : tendsto (λp:α×α, p.1 + p.2) ((Z α).prod (Z α)) (Z α) :=
suffices tendsto (λp:α×α, p.1 - -p.2) ((Z α).prod (Z α)) (Z α),
by simpa,
(tendsto.prod_mk tendsto_fst (tendsto_snd.comp neg_Z)).comp sub_Z
lemma exists_Z_half {s : set α} (hs : s ∈ (Z α).sets) : ∃ V ∈ (Z α).sets, ∀ v w ∈ V, v + w ∈ s :=
begin
have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ ((Z α).prod (Z α)).sets := add_Z (by simpa using hs),
rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩,
exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩
end
lemma nhds_eq (a : α) : nhds a = map (λx, x + a) (Z α) :=
topological_space.nhds_mk_of_nhds _ _
(assume a, calc pure a = map (λx, x + a) (pure 0) : by simp
... ≤ _ : map_mono zero_Z)
(assume b s hs,
let ⟨t, ht, eqt⟩ := exists_Z_half hs in
have t0 : (0:α) ∈ t, by simpa using zero_Z ht,
begin
refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩,
{ refine set.image_subset_iff.2 (assume b hbt, _),
simpa using eqt 0 b t0 hbt },
{ rintros _ ⟨c, hb, rfl⟩,
refine (Z α).sets_of_superset ht (assume x hxt, _),
simpa using eqt _ _ hxt hb }
end)
lemma nhds_zero_eq_Z : nhds 0 = Z α := by simp [nhds_eq]; exact filter.map_id
instance : topological_add_monoid α :=
⟨ continuous_iff_tendsto.2 $ assume ⟨a, b⟩,
begin
rw [nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq,
tendsto_map'_iff],
suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (filter.prod (Z α) (Z α))
(map (λx:α, (a + b) + x) (Z α)),
{ simpa [(∘)] },
exact add_Z.comp tendsto_map
end⟩
instance : topological_add_group α :=
⟨continuous_iff_tendsto.2 $ assume a,
begin
rw [nhds_eq, nhds_eq, tendsto_map'_iff],
suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)),
{ simpa [(∘)] },
exact neg_Z.comp tendsto_map
end⟩
end add_group_with_zero_nhd
|
911799646d3ab1d0b80e458e065bda032d0a9771 | 130c49f47783503e462c16b2eff31933442be6ff | /src/Lean/Data/Json/Basic.lean | 72041a9be64fcb208feb4fadc0a7d2de80cb38fe | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,480 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Marc Huisinga
-/
import Std.Data.RBTree
namespace Lean
-- mantissa * 10^-exponent
structure JsonNumber where
mantissa : Int
exponent : Nat
deriving DecidableEq
namespace JsonNumber
protected def fromNat (n : Nat) : JsonNumber := ⟨n, 0⟩
protected def fromInt (n : Int) : JsonNumber := ⟨n, 0⟩
instance : Coe Nat JsonNumber := ⟨JsonNumber.fromNat⟩
instance : Coe Int JsonNumber := ⟨JsonNumber.fromInt⟩
private partial def countDigits (n : Nat) : Nat :=
let rec loop (n digits : Nat) : Nat :=
if n ≤ 9 then
digits
else
loop (n/10) (digits+1)
loop n 1
-- convert mantissa * 10^-exponent to 0.mantissa * 10^exponent
protected def normalize : JsonNumber → Int × Nat × Int
| ⟨m, e⟩ => do
if m = 0 then (0, 0, 0)
else
let sign : Int := if m > 0 then 1 else -1
let mut mAbs := m.natAbs
let nDigits := countDigits mAbs
-- eliminate trailing zeros
for _ in [0:nDigits] do
if mAbs % 10 = 0 then
mAbs := mAbs / 10
else
break
(sign, mAbs, -(e : Int) + nDigits)
-- todo (Dany): We should have an Ordering version of this.
def lt (a b : JsonNumber) : Bool :=
let (as, am, ae) := a.normalize
let (bs, bm, be) := b.normalize
match (as, bs) with
| (-1, 1) => true
| (1, -1) => false
| _ =>
let ((am, ae), (bm, be)) :=
if as = -1 && bs = -1 then
((bm, be), (am, ae))
else
((am, ae), (bm, be))
let amDigits := countDigits am
let bmDigits := countDigits bm
-- align the mantissas
let (am, bm) :=
if amDigits < bmDigits then
(am * 10^(bmDigits - amDigits), bm)
else
(am, bm * 10^(amDigits - bmDigits))
if ae < be then true
else if ae > be then false
else am < bm
def ltProp : LT JsonNumber :=
⟨fun a b => lt a b = true⟩
instance : LT JsonNumber :=
ltProp
instance (a b : JsonNumber) : Decidable (a < b) :=
inferInstanceAs (Decidable (lt a b = true))
instance : Ord JsonNumber where
compare x y :=
if x < y then Ordering.lt
else if x > y then Ordering.gt
else Ordering.eq
protected def toString : JsonNumber → String
| ⟨m, 0⟩ => m.repr
| ⟨m, e⟩ =>
let sign := if m ≥ 0 then "" else "-"
let m := m.natAbs
-- if there are too many zeroes after the decimal, we
-- use exponents to compress the representation.
-- this is mostly done for memory usage reasons:
-- the size of the representation would otherwise
-- grow exponentially in the value of exponent.
let exp : Int := 9 + countDigits m - (e : Int)
let exp := if exp < 0 then exp else 0
let e' := (10 : Int) ^ (e - exp.natAbs)
let left := (m / e').repr
let right := e' + coe m % e'
|>.repr.toSubstring.drop 1
|>.dropRightWhile (fun c => c = '0')
|>.toString
let exp := if exp = 0 then "" else "e" ++ exp.repr
s!"{sign}{left}.{right}{exp}"
-- shift a JsonNumber by a specified amount of places to the left
protected def shiftl : JsonNumber → Nat → JsonNumber
-- if s ≤ e, then 10 ^ (s - e) = 1, and hence the mantissa remains unchanged.
-- otherwise, the expression pads the mantissa with zeroes
-- to accomodate for the remaining places to shift.
| ⟨m, e⟩, s => ⟨m * (10 ^ (s - e) : Nat), e - s⟩
-- shift a JsonNumber by a specified amount of places to the right
protected def shiftr : JsonNumber → Nat → JsonNumber
| ⟨m, e⟩, s => ⟨m, e + s⟩
instance : ToString JsonNumber := ⟨JsonNumber.toString⟩
instance : Repr JsonNumber where
reprPrec | ⟨m, e⟩, _ => Std.Format.bracket "⟨" (repr m ++ "," ++ repr e) "⟩"
end JsonNumber
def strLt (a b : String) := Decidable.decide (a < b)
open Std (RBNode RBNode.leaf)
inductive Json where
| null
| bool (b : Bool)
| num (n : JsonNumber)
| str (s : String)
| arr (elems : Array Json)
-- uses RBNode instead of RBMap because RBMap is a def
-- and thus currently cannot be used to define a type that
-- is recursive in one of its parameters
| obj (kvPairs : RBNode String (fun _ => Json))
deriving Inhabited
namespace Json
-- HACK(Marc): temporary ugliness until we can use RBMap for JSON objects
def mkObj (o : List (String × Json)) : Json :=
obj $ do
let mut kvPairs := RBNode.leaf
for ⟨k, v⟩ in o do
kvPairs := kvPairs.insert compare k v
kvPairs
instance : Coe Nat Json := ⟨fun n => Json.num n⟩
instance : Coe Int Json := ⟨fun n => Json.num n⟩
instance : Coe String Json := ⟨Json.str⟩
instance : Coe Bool Json := ⟨Json.bool⟩
def isNull : Json -> Bool
| null => true
| _ => false
def getObj? : Json → Except String (RBNode String (fun _ => Json))
| obj kvs => kvs
| _ => throw "object expected"
def getArr? : Json → Except String (Array Json)
| arr a => a
| _ => throw "array expected"
def getStr? : Json → Except String String
| str s => s
| _ => throw "String expected"
def getNat? : Json → Except String Nat
| (n : Nat) => n
| _ => throw "Natural number expected"
def getInt? : Json → Except String Int
| (i : Int) => i
| _ => throw "Integer expected"
def getBool? : Json → Except String Bool
| (b : Bool) => b
| _ => throw "Bool expected"
def getNum? : Json → Except String JsonNumber
| num n => n
| _ => throw "number expected"
def getObjVal? : Json → String → Except String Json
| obj kvs, k =>
match kvs.find compare k with
| some v => v
| none => throw s!"property not found: {k}"
| _ , _ => throw "object expected"
def getArrVal? : Json → Nat → Except String Json
| arr a, i =>
match a.get? i with
| some v => v
| none => throw s!"index out of bounds: {i}"
| _ , _ => throw "array expected"
def getObjValD (j : Json) (k : String) : Json :=
(j.getObjVal? k).toOption.getD null
def setObjVal! : Json → String → Json → Json
| obj kvs, k, v => obj <| kvs.insert compare k v
| j , _, _ => panic! "Json.setObjVal!: not an object: {j}"
inductive Structured where
| arr (elems : Array Json)
| obj (kvPairs : RBNode String (fun _ => Json))
instance : Coe (Array Json) Structured := ⟨Structured.arr⟩
instance : Coe (RBNode String (fun _ => Json)) Structured := ⟨Structured.obj⟩
end Json
end Lean
|
e55692e99ed41acc2ca3cbe3622120952b3c5659 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/unify_fo_approx_bug1.lean | 98e1eb7a103240fb59c406e5d6312884191f6e8f | [
"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 | 340 | lean | check ( return (1, 1) : list (nat × nat) )
constant A : Type
constant B : Type
set_option pp.binder_types true
set_option pp.universes true
check λ (A : Type) (B : Type) (a : A) (b : B), (return (a, b) : list (A × B))
check λ (A : Type) (B : Type) (C : Type) (a : A) (b : B) (c : C), (return (a, b, a, c) : list (A × B × A × C))
|
795d215fde97e7099b49d0a820be4a6780d1bf2d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/splitIssue.lean | 68d3eee2d6551c1c84f01e084de78013ee8be402 | [
"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 | 309 | lean | def g (x : Nat) := 2*x + 1
def f (x : Nat) : Nat :=
match g x with
| 0 => 1
| y + 1 => g x
example : f x = 2*x + 1 := by
unfold f
split
next h => simp_arith [g] at h
next y h =>
trace_state
-- split tactic should *not* rewrite `g x` to `Nat.succ y`
show g x = 2*x + 1
simp [g]
|
4e6310a2826bfa8c3933d3fd0f1c321a4d25d849 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/separation.lean | 73ec638f59bb9ae11c8b1981584d6523066d5410 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 84,647 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import topology.subset_properties
import topology.connected
import topology.nhds_set
import topology.inseparable
/-!
# Separation properties of topological spaces.
This file defines the predicate `separated`, and common separation axioms
(under the Kolmogorov classification).
## Main definitions
* `separated`: Two `set`s are separated if they are contained in disjoint open sets.
* `t0_space`: A T₀/Kolmogorov space is a space where, for every two points `x ≠ y`,
there is an open set that contains one, but not the other.
* `t1_space`: A T₁/Fréchet space is a space where every singleton set is closed.
This is equivalent to, for every pair `x ≠ y`, there existing an open set containing `x`
but not `y` (`t1_space_iff_exists_open` shows that these conditions are equivalent.)
* `t2_space`: A T₂/Hausdorff space is a space where, for every two points `x ≠ y`,
there is two disjoint open sets, one containing `x`, and the other `y`.
* `t2_5_space`: A T₂.₅/Urysohn space is a space where, for every two points `x ≠ y`,
there is two open sets, one containing `x`, and the other `y`, whose closures are disjoint.
* `t3_space`: A T₃ space, is one where given any closed `C` and `x ∉ C`,
there is disjoint open sets containing `x` and `C` respectively. In `mathlib`, T₃ implies T₂.₅.
* `normal_space`: A T₄ space (sometimes referred to as normal, but authors vary on
whether this includes T₂; `mathlib` does), is one where given two disjoint closed sets,
we can find two open sets that separate them. In `mathlib`, T₄ implies T₃.
* `t5_space`: A T₅ space, also known as a *completely normal Hausdorff space*
## Main results
### T₀ spaces
* `is_closed.exists_closed_singleton` Given a closed set `S` in a compact T₀ space,
there is some `x ∈ S` such that `{x}` is closed.
* `exists_open_singleton_of_open_finset` Given an open `finset` `S` in a T₀ space,
there is some `x ∈ S` such that `{x}` is open.
### T₁ spaces
* `is_closed_map_const`: The constant map is a closed map.
* `discrete_of_t1_of_finite`: A finite T₁ space must have the discrete topology.
### T₂ spaces
* `t2_iff_nhds`: A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter.
* `t2_iff_is_closed_diagonal`: A space is T₂ iff the `diagonal` of `α` (that is, the set of all
points of the form `(a, a) : α × α`) is closed under the product topology.
* `finset_disjoint_finset_opens_of_t2`: Any two disjoint finsets are `separated`.
* Most topological constructions preserve Hausdorffness;
these results are part of the typeclass inference system (e.g. `embedding.t2_space`)
* `set.eq_on.closure`: If two functions are equal on some set `s`, they are equal on its closure.
* `is_compact.is_closed`: All compact sets are closed.
* `locally_compact_of_compact_nhds`: If every point has a compact neighbourhood,
then the space is locally compact.
* `totally_separated_space_of_t1_of_basis_clopen`: If `α` has a clopen basis, then
it is a `totally_separated_space`.
* `loc_compact_t2_tot_disc_iff_tot_sep`: A locally compact T₂ space is totally disconnected iff
it is totally separated.
If the space is also compact:
* `normal_of_compact_t2`: A compact T₂ space is a `normal_space`.
* `connected_components_eq_Inter_clopen`: The connected component of a point
is the intersection of all its clopen neighbourhoods.
* `compact_t2_tot_disc_iff_tot_sep`: Being a `totally_disconnected_space`
is equivalent to being a `totally_separated_space`.
* `connected_components.t2`: `connected_components α` is T₂ for `α` T₂ and compact.
### T₃ spaces
* `disjoint_nested_nhds`: Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and
`y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint.
### Discrete spaces
* `discrete_topology_iff_nhds`: Discrete topological spaces are those whose neighbourhood
filters are the `pure` filter (which is the principal filter at a singleton).
* `induced_bot`/`discrete_topology_induced`: The pullback of the discrete topology
under an inclusion is the discrete topology.
## References
https://en.wikipedia.org/wiki/Separation_axiom
-/
open function set filter topological_space
open_locale topological_space filter classical
universes u v
variables {α : Type u} {β : Type v} [topological_space α]
section separation
/--
`separated` is a predicate on pairs of sub`set`s of a topological space. It holds if the two
sub`set`s are contained in disjoint open sets.
-/
def separated : set α → set α → Prop :=
λ (s t : set α), ∃ U V : (set α), (is_open U) ∧ is_open V ∧
(s ⊆ U) ∧ (t ⊆ V) ∧ disjoint U V
lemma separated_iff_disjoint {s t : set α} :
separated s t ↔ disjoint (𝓝ˢ s) (𝓝ˢ t) :=
by simp only [(has_basis_nhds_set s).disjoint_iff (has_basis_nhds_set t), separated, exists_prop,
← exists_and_distrib_left, and.assoc, and.comm, and.left_comm]
namespace separated
open separated
@[symm] lemma symm {s t : set α} : separated s t → separated t s :=
λ ⟨U, V, oU, oV, aU, bV, UV⟩, ⟨V, U, oV, oU, bV, aU, disjoint.symm UV⟩
lemma comm (s t : set α) : separated s t ↔ separated t s :=
⟨symm, symm⟩
lemma preimage [topological_space β] {f : α → β} {s t : set β} (h : separated s t)
(hf : continuous f) : separated (f ⁻¹' s) (f ⁻¹' t) :=
let ⟨U, V, oU, oV, sU, tV, UV⟩ := h in
⟨f ⁻¹' U, f ⁻¹' V, oU.preimage hf, oV.preimage hf, preimage_mono sU, preimage_mono tV,
UV.preimage f⟩
protected lemma disjoint {s t : set α} (h : separated s t) : disjoint s t :=
let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in hd.mono hsU htV
lemma disjoint_closure_left {s t : set α} (h : separated s t) : disjoint (closure s) t :=
let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h
in (hd.closure_left hV).mono (closure_mono hsU) htV
lemma disjoint_closure_right {s t : set α} (h : separated s t) : disjoint s (closure t) :=
h.symm.disjoint_closure_left.symm
lemma empty_right (a : set α) : separated a ∅ :=
⟨_, _, is_open_univ, is_open_empty, λ a h, mem_univ a, λ a h, by cases h, disjoint_empty _⟩
lemma empty_left (a : set α) : separated ∅ a :=
(empty_right _).symm
lemma mono {s₁ s₂ t₁ t₂ : set α} (h : separated s₂ t₂) (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) :
separated s₁ t₁ :=
let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in ⟨U, V, hU, hV, hs.trans hsU, ht.trans htV, hd⟩
lemma union_left {a b c : set α} : separated a c → separated b c → separated (a ∪ b) c :=
by simpa only [separated_iff_disjoint, nhds_set_union, disjoint_sup_left] using and.intro
lemma union_right {a b c : set α} (ab : separated a b) (ac : separated a c) :
separated a (b ∪ c) :=
(ab.symm.union_left ac.symm).symm
end separated
/-- A T₀ space, also known as a Kolmogorov space, is a topological space such that for every pair
`x ≠ y`, there is an open set containing one but not the other. We formulate the definition in terms
of the `inseparable` relation. -/
class t0_space (α : Type u) [topological_space α] : Prop :=
(t0 : ∀ ⦃x y : α⦄, inseparable x y → x = y)
lemma t0_space_iff_inseparable (α : Type u) [topological_space α] :
t0_space α ↔ ∀ (x y : α), inseparable x y → x = y :=
⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩
lemma t0_space_iff_not_inseparable (α : Type u) [topological_space α] :
t0_space α ↔ ∀ (x y : α), x ≠ y → ¬inseparable x y :=
by simp only [t0_space_iff_inseparable, ne.def, not_imp_not]
lemma inseparable.eq [t0_space α] {x y : α} (h : inseparable x y) : x = y :=
t0_space.t0 h
lemma t0_space_iff_nhds_injective (α : Type u) [topological_space α] :
t0_space α ↔ injective (𝓝 : α → filter α) :=
t0_space_iff_inseparable α
lemma nhds_injective [t0_space α] : injective (𝓝 : α → filter α) :=
(t0_space_iff_nhds_injective α).1 ‹_›
lemma inseparable_iff_eq [t0_space α] {x y : α} : inseparable x y ↔ x = y :=
nhds_injective.eq_iff
@[simp] lemma nhds_eq_nhds_iff [t0_space α] {a b : α} : 𝓝 a = 𝓝 b ↔ a = b :=
nhds_injective.eq_iff
@[simp] lemma inseparable_eq_eq [t0_space α] : inseparable = @eq α :=
funext₂ $ λ x y, propext inseparable_iff_eq
lemma t0_space_iff_exists_is_open_xor_mem (α : Type u) [topological_space α] :
t0_space α ↔ ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U)) :=
by simp only [t0_space_iff_not_inseparable, xor_iff_not_iff, not_forall, exists_prop,
inseparable_iff_forall_open]
lemma exists_is_open_xor_mem [t0_space α] {x y : α} (h : x ≠ y) :
∃ U : set α, is_open U ∧ xor (x ∈ U) (y ∈ U) :=
(t0_space_iff_exists_is_open_xor_mem α).1 ‹_› x y h
/-- Specialization forms a partial order on a t0 topological space. -/
def specialization_order (α : Type*) [topological_space α] [t0_space α] : partial_order α :=
{ .. specialization_preorder α,
.. partial_order.lift (order_dual.to_dual ∘ 𝓝) nhds_injective }
instance : t0_space (separation_quotient α) :=
⟨λ x' y', quotient.induction_on₂' x' y' $
λ x y h, separation_quotient.mk_eq_mk.2 $ separation_quotient.inducing_mk.inseparable_iff.1 h⟩
theorem minimal_nonempty_closed_subsingleton [t0_space α] {s : set α} (hs : is_closed s)
(hmin : ∀ t ⊆ s, t.nonempty → is_closed t → t = s) :
s.subsingleton :=
begin
refine λ x hx y hy, of_not_not (λ hxy, _),
rcases exists_is_open_xor_mem hxy with ⟨U, hUo, hU⟩,
wlog h : x ∈ U ∧ y ∉ U := hU using [x y, y x], cases h with hxU hyU,
have : s \ U = s := hmin (s \ U) (diff_subset _ _) ⟨y, hy, hyU⟩ (hs.sdiff hUo),
exact (this.symm.subset hx).2 hxU
end
theorem minimal_nonempty_closed_eq_singleton [t0_space α] {s : set α} (hs : is_closed s)
(hne : s.nonempty) (hmin : ∀ t ⊆ s, t.nonempty → is_closed t → t = s) :
∃ x, s = {x} :=
exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_closed_subsingleton hs hmin⟩
/-- Given a closed set `S` in a compact T₀ space,
there is some `x ∈ S` such that `{x}` is closed. -/
theorem is_closed.exists_closed_singleton {α : Type*} [topological_space α]
[t0_space α] [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) :
∃ (x : α), x ∈ S ∧ is_closed ({x} : set α) :=
begin
obtain ⟨V, Vsub, Vne, Vcls, hV⟩ := hS.exists_minimal_nonempty_closed_subset hne,
rcases minimal_nonempty_closed_eq_singleton Vcls Vne hV with ⟨x, rfl⟩,
exact ⟨x, Vsub (mem_singleton x), Vcls⟩
end
theorem minimal_nonempty_open_subsingleton [t0_space α] {s : set α} (hs : is_open s)
(hmin : ∀ t ⊆ s, t.nonempty → is_open t → t = s) :
s.subsingleton :=
begin
refine λ x hx y hy, of_not_not (λ hxy, _),
rcases exists_is_open_xor_mem hxy with ⟨U, hUo, hU⟩,
wlog h : x ∈ U ∧ y ∉ U := hU using [x y, y x], cases h with hxU hyU,
have : s ∩ U = s := hmin (s ∩ U) (inter_subset_left _ _) ⟨x, hx, hxU⟩ (hs.inter hUo),
exact hyU (this.symm.subset hy).2
end
theorem minimal_nonempty_open_eq_singleton [t0_space α] {s : set α} (hs : is_open s)
(hne : s.nonempty) (hmin : ∀ t ⊆ s, t.nonempty → is_open t → t = s) :
∃ x, s = {x} :=
exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_open_subsingleton hs hmin⟩
/-- Given an open finite set `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. -/
theorem exists_open_singleton_of_open_finite [t0_space α] {s : set α} (hfin : s.finite)
(hne : s.nonempty) (ho : is_open s) :
∃ x ∈ s, is_open ({x} : set α) :=
begin
lift s to finset α using hfin,
induction s using finset.strong_induction_on with s ihs,
rcases em (∃ t ⊂ s, t.nonempty ∧ is_open (t : set α)) with ⟨t, hts, htne, hto⟩|ht,
{ rcases ihs t hts htne hto with ⟨x, hxt, hxo⟩,
exact ⟨x, hts.1 hxt, hxo⟩ },
{ rcases minimal_nonempty_open_eq_singleton ho hne _ with ⟨x, hx⟩,
{ exact ⟨x, hx.symm ▸ rfl, hx ▸ ho⟩ },
refine λ t hts htne hto, of_not_not (λ hts', ht _),
lift t to finset α using s.finite_to_set.subset hts,
exact ⟨t, ssubset_iff_subset_ne.2 ⟨hts, mt finset.coe_inj.2 hts'⟩, htne, hto⟩ }
end
theorem exists_open_singleton_of_fintype [t0_space α] [finite α] [nonempty α] :
∃ x : α, is_open ({x} : set α) :=
let ⟨x, _, h⟩ := exists_open_singleton_of_open_finite (set.to_finite _) univ_nonempty
is_open_univ in ⟨x, h⟩
lemma t0_space_of_injective_of_continuous [topological_space β] {f : α → β}
(hf : function.injective f) (hf' : continuous f) [t0_space β] : t0_space α :=
⟨λ x y h, hf $ (h.map hf').eq⟩
protected lemma embedding.t0_space [topological_space β] [t0_space β] {f : α → β}
(hf : embedding f) : t0_space α :=
t0_space_of_injective_of_continuous hf.inj hf.continuous
instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) :=
embedding_subtype_coe.t0_space
theorem t0_space_iff_or_not_mem_closure (α : Type u) [topological_space α] :
t0_space α ↔ (∀ a b : α, a ≠ b → (a ∉ closure ({b} : set α) ∨ b ∉ closure ({a} : set α))) :=
by simp only [t0_space_iff_not_inseparable, inseparable_iff_mem_closure, not_and_distrib]
instance [topological_space β] [t0_space α] [t0_space β] : t0_space (α × β) :=
⟨λ x y h, prod.ext (h.map continuous_fst).eq (h.map continuous_snd).eq⟩
instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t0_space (π i)] :
t0_space (Π i, π i) :=
⟨λ x y h, funext $ λ i, (h.map (continuous_apply i)).eq⟩
lemma t0_space.of_cover (h : ∀ x y, inseparable x y → ∃ s : set α, x ∈ s ∧ y ∈ s ∧ t0_space s) :
t0_space α :=
begin
refine ⟨λ x y hxy, _⟩,
rcases h x y hxy with ⟨s, hxs, hys, hs⟩, resetI,
lift x to s using hxs, lift y to s using hys,
rw ← subtype_inseparable_iff at hxy,
exact congr_arg coe hxy.eq
end
lemma t0_space.of_open_cover (h : ∀ x, ∃ s : set α, x ∈ s ∧ is_open s ∧ t0_space s) : t0_space α :=
t0_space.of_cover $ λ x y hxy,
let ⟨s, hxs, hso, hs⟩ := h x in ⟨s, hxs, (hxy.mem_open_iff hso).1 hxs, hs⟩
/-- A T₁ space, also known as a Fréchet space, is a topological space
where every singleton set is closed. Equivalently, for every pair
`x ≠ y`, there is an open set containing `x` and not `y`. -/
class t1_space (α : Type u) [topological_space α] : Prop :=
(t1 : ∀x, is_closed ({x} : set α))
lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) :=
t1_space.t1 x
lemma is_open_compl_singleton [t1_space α] {x : α} : is_open ({x}ᶜ : set α) :=
is_closed_singleton.is_open_compl
lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} :=
is_open_compl_singleton
lemma ne.nhds_within_compl_singleton [t1_space α] {x y : α} (h : x ≠ y) :
𝓝[{y}ᶜ] x = 𝓝 x :=
is_open_ne.nhds_within_eq h
lemma ne.nhds_within_diff_singleton [t1_space α] {x y : α} (h : x ≠ y) (s : set α) :
𝓝[s \ {y}] x = 𝓝[s] x :=
begin
rw [diff_eq, inter_comm, nhds_within_inter_of_mem],
exact mem_nhds_within_of_mem_nhds (is_open_ne.mem_nhds h)
end
protected lemma set.finite.is_closed [t1_space α] {s : set α} (hs : set.finite s) :
is_closed s :=
begin
rw ← bUnion_of_singleton s,
exact is_closed_bUnion hs (λ i hi, is_closed_singleton)
end
lemma topological_space.is_topological_basis.exists_mem_of_ne
[t1_space α] {b : set (set α)} (hb : is_topological_basis b) {x y : α} (h : x ≠ y) :
∃ a ∈ b, x ∈ a ∧ y ∉ a :=
begin
rcases hb.is_open_iff.1 is_open_ne x h with ⟨a, ab, xa, ha⟩,
exact ⟨a, ab, xa, λ h, ha h rfl⟩,
end
lemma filter.coclosed_compact_le_cofinite [t1_space α] :
filter.coclosed_compact α ≤ filter.cofinite :=
λ s hs, compl_compl s ▸ hs.is_compact.compl_mem_coclosed_compact_of_is_closed hs.is_closed
variable (α)
/-- In a `t1_space`, relatively compact sets form a bornology. Its cobounded filter is
`filter.coclosed_compact`. See also `bornology.in_compact` the bornology of sets contained
in a compact set. -/
def bornology.relatively_compact [t1_space α] : bornology α :=
{ cobounded := filter.coclosed_compact α,
le_cofinite := filter.coclosed_compact_le_cofinite }
variable {α}
lemma bornology.relatively_compact.is_bounded_iff [t1_space α] {s : set α} :
@bornology.is_bounded _ (bornology.relatively_compact α) s ↔ is_compact (closure s) :=
begin
change sᶜ ∈ filter.coclosed_compact α ↔ _,
rw filter.mem_coclosed_compact,
split,
{ rintros ⟨t, ht₁, ht₂, hst⟩,
rw compl_subset_compl at hst,
exact compact_of_is_closed_subset ht₂ is_closed_closure (closure_minimal hst ht₁) },
{ intros h,
exact ⟨closure s, is_closed_closure, h, compl_subset_compl.mpr subset_closure⟩ }
end
protected lemma finset.is_closed [t1_space α] (s : finset α) : is_closed (s : set α) :=
s.finite_to_set.is_closed
lemma t1_space_tfae (α : Type u) [topological_space α] :
tfae [t1_space α,
∀ x, is_closed ({x} : set α),
∀ x, is_open ({x}ᶜ : set α),
continuous (@cofinite_topology.of α),
∀ ⦃x y : α⦄, x ≠ y → {y}ᶜ ∈ 𝓝 x,
∀ ⦃x y : α⦄, x ≠ y → ∃ s ∈ 𝓝 x, y ∉ s,
∀ ⦃x y : α⦄, x ≠ y → ∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U,
∀ ⦃x y : α⦄, x ≠ y → disjoint (𝓝 x) (pure y),
∀ ⦃x y : α⦄, x ≠ y → disjoint (pure x) (𝓝 y),
∀ ⦃x y : α⦄, x ⤳ y → x = y] :=
begin
tfae_have : 1 ↔ 2, from ⟨λ h, h.1, λ h, ⟨h⟩⟩,
tfae_have : 2 ↔ 3, by simp only [is_open_compl_iff],
tfae_have : 5 ↔ 3,
{ refine forall_swap.trans _,
simp only [is_open_iff_mem_nhds, mem_compl_iff, mem_singleton_iff] },
tfae_have : 5 ↔ 6,
by simp only [← subset_compl_singleton_iff, exists_mem_subset_iff],
tfae_have : 5 ↔ 7,
by simp only [(nhds_basis_opens _).mem_iff, subset_compl_singleton_iff, exists_prop, and.assoc,
and.left_comm],
tfae_have : 5 ↔ 8,
by simp only [← principal_singleton, disjoint_principal_right],
tfae_have : 8 ↔ 9, from forall_swap.trans (by simp only [disjoint.comm, ne_comm]),
tfae_have : 1 → 4,
{ simp only [continuous_def, cofinite_topology.is_open_iff'],
rintro H s (rfl|hs),
exacts [is_open_empty, compl_compl s ▸ (@set.finite.is_closed _ _ H _ hs).is_open_compl] },
tfae_have : 4 → 2,
from λ h x, (cofinite_topology.is_closed_iff.2 $ or.inr (finite_singleton _)).preimage h,
tfae_have : 2 ↔ 10,
{ simp only [← closure_subset_iff_is_closed, specializes_iff_mem_closure, subset_def,
mem_singleton_iff, eq_comm] },
tfae_finish
end
lemma t1_space_iff_continuous_cofinite_of {α : Type*} [topological_space α] :
t1_space α ↔ continuous (@cofinite_topology.of α) :=
(t1_space_tfae α).out 0 3
lemma cofinite_topology.continuous_of [t1_space α] : continuous (@cofinite_topology.of α) :=
t1_space_iff_continuous_cofinite_of.mp ‹_›
lemma t1_space_iff_exists_open : t1_space α ↔
∀ (x y), x ≠ y → (∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U) :=
(t1_space_tfae α).out 0 6
lemma t1_space_iff_disjoint_pure_nhds : t1_space α ↔ ∀ ⦃x y : α⦄, x ≠ y → disjoint (pure x) (𝓝 y) :=
(t1_space_tfae α).out 0 8
lemma t1_space_iff_disjoint_nhds_pure : t1_space α ↔ ∀ ⦃x y : α⦄, x ≠ y → disjoint (𝓝 x) (pure y) :=
(t1_space_tfae α).out 0 7
lemma t1_space_iff_specializes_imp_eq : t1_space α ↔ ∀ ⦃x y : α⦄, x ⤳ y → x = y :=
(t1_space_tfae α).out 0 9
lemma disjoint_pure_nhds [t1_space α] {x y : α} (h : x ≠ y) : disjoint (pure x) (𝓝 y) :=
t1_space_iff_disjoint_pure_nhds.mp ‹_› h
lemma disjoint_nhds_pure [t1_space α] {x y : α} (h : x ≠ y) : disjoint (𝓝 x) (pure y) :=
t1_space_iff_disjoint_nhds_pure.mp ‹_› h
lemma specializes.eq [t1_space α] {x y : α} (h : x ⤳ y) : x = y :=
t1_space_iff_specializes_imp_eq.1 ‹_› h
lemma specializes_iff_eq [t1_space α] {x y : α} : x ⤳ y ↔ x = y :=
⟨specializes.eq, λ h, h ▸ specializes_rfl⟩
@[simp] lemma specializes_eq_eq [t1_space α] : (⤳) = @eq α :=
funext₂ $ λ x y, propext specializes_iff_eq
@[simp] lemma pure_le_nhds_iff [t1_space α] {a b : α} : pure a ≤ 𝓝 b ↔ a = b :=
specializes_iff_pure.symm.trans specializes_iff_eq
@[simp] lemma nhds_le_nhds_iff [t1_space α] {a b : α} : 𝓝 a ≤ 𝓝 b ↔ a = b :=
specializes_iff_eq
instance {α : Type*} : t1_space (cofinite_topology α) :=
t1_space_iff_continuous_cofinite_of.mpr continuous_id
lemma t1_space_antitone {α : Type*} : antitone (@t1_space α) :=
begin
simp only [antitone, t1_space_iff_continuous_cofinite_of, continuous_iff_le_induced],
exact λ t₁ t₂ h, h.trans
end
lemma continuous_within_at_update_of_ne [t1_space α] [decidable_eq α] [topological_space β]
{f : α → β} {s : set α} {x y : α} {z : β} (hne : y ≠ x) :
continuous_within_at (function.update f x z) s y ↔ continuous_within_at f s y :=
eventually_eq.congr_continuous_within_at
(mem_nhds_within_of_mem_nhds $ mem_of_superset (is_open_ne.mem_nhds hne) $
λ y' hy', function.update_noteq hy' _ _)
(function.update_noteq hne _ _)
lemma continuous_at_update_of_ne [t1_space α] [decidable_eq α] [topological_space β]
{f : α → β} {x y : α} {z : β} (hne : y ≠ x) :
continuous_at (function.update f x z) y ↔ continuous_at f y :=
by simp only [← continuous_within_at_univ, continuous_within_at_update_of_ne hne]
lemma continuous_on_update_iff [t1_space α] [decidable_eq α] [topological_space β]
{f : α → β} {s : set α} {x : α} {y : β} :
continuous_on (function.update f x y) s ↔
continuous_on f (s \ {x}) ∧ (x ∈ s → tendsto f (𝓝[s \ {x}] x) (𝓝 y)) :=
begin
rw [continuous_on, ← and_forall_ne x, and_comm],
refine and_congr ⟨λ H z hz, _, λ H z hzx hzs, _⟩ (forall_congr $ λ hxs, _),
{ specialize H z hz.2 hz.1,
rw continuous_within_at_update_of_ne hz.2 at H,
exact H.mono (diff_subset _ _) },
{ rw continuous_within_at_update_of_ne hzx,
refine (H z ⟨hzs, hzx⟩).mono_of_mem (inter_mem_nhds_within _ _),
exact is_open_ne.mem_nhds hzx },
{ exact continuous_within_at_update_same }
end
lemma t1_space_of_injective_of_continuous [topological_space β] {f : α → β}
(hf : function.injective f) (hf' : continuous f) [t1_space β] : t1_space α :=
t1_space_iff_specializes_imp_eq.2 $ λ x y h, hf (h.map hf').eq
protected lemma embedding.t1_space [topological_space β] [t1_space β] {f : α → β}
(hf : embedding f) : t1_space α :=
t1_space_of_injective_of_continuous hf.inj hf.continuous
instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} :
t1_space (subtype p) :=
embedding_subtype_coe.t1_space
instance [topological_space β] [t1_space α] [t1_space β] : t1_space (α × β) :=
⟨λ ⟨a, b⟩, @singleton_prod_singleton _ _ a b ▸ is_closed_singleton.prod is_closed_singleton⟩
instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t1_space (π i)] :
t1_space (Π i, π i) :=
⟨λ f, univ_pi_singleton f ▸ is_closed_set_pi (λ i hi, is_closed_singleton)⟩
@[priority 100] -- see Note [lower instance priority]
instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, h.specializes.eq⟩
@[simp] lemma compl_singleton_mem_nhds_iff [t1_space α] {x y : α} : {x}ᶜ ∈ 𝓝 y ↔ y ≠ x :=
is_open_compl_singleton.mem_nhds_iff
lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y :=
compl_singleton_mem_nhds_iff.mpr h
@[simp] lemma closure_singleton [t1_space α] {a : α} :
closure ({a} : set α) = {a} :=
is_closed_singleton.closure_eq
lemma set.subsingleton.closure [t1_space α] {s : set α} (hs : s.subsingleton) :
(closure s).subsingleton :=
hs.induction_on (by simp) $ λ x, by simp
@[simp] lemma subsingleton_closure [t1_space α] {s : set α} :
(closure s).subsingleton ↔ s.subsingleton :=
⟨λ h, h.anti subset_closure, λ h, h.closure⟩
lemma is_closed_map_const {α β} [topological_space α] [topological_space β] [t1_space β] {y : β} :
is_closed_map (function.const α y) :=
is_closed_map.of_nonempty $ λ s hs h2s, by simp_rw [h2s.image_const, is_closed_singleton]
lemma bInter_basis_nhds [t1_space α] {ι : Sort*} {p : ι → Prop} {s : ι → set α} {x : α}
(h : (𝓝 x).has_basis p s) : (⋂ i (h : p i), s i) = {x} :=
begin
simp only [eq_singleton_iff_unique_mem, mem_Inter],
refine ⟨λ i hi, mem_of_mem_nhds $ h.mem_of_mem hi, λ y hy, _⟩,
contrapose! hy,
rcases h.mem_iff.1 (compl_singleton_mem_nhds hy.symm) with ⟨i, hi, hsub⟩,
exact ⟨i, hi, λ h, hsub h rfl⟩
end
@[simp] lemma compl_singleton_mem_nhds_set_iff [t1_space α] {x : α} {s : set α} :
{x}ᶜ ∈ 𝓝ˢ s ↔ x ∉ s :=
by rwa [is_open_compl_singleton.mem_nhds_set, subset_compl_singleton_iff]
@[simp] lemma nhds_set_le_iff [t1_space α] {s t : set α} : 𝓝ˢ s ≤ 𝓝ˢ t ↔ s ⊆ t :=
begin
refine ⟨_, λ h, monotone_nhds_set h⟩,
simp_rw [filter.le_def], intros h x hx,
specialize h {x}ᶜ,
simp_rw [compl_singleton_mem_nhds_set_iff] at h,
by_contra hxt,
exact h hxt hx,
end
@[simp] lemma nhds_set_inj_iff [t1_space α] {s t : set α} : 𝓝ˢ s = 𝓝ˢ t ↔ s = t :=
by { simp_rw [le_antisymm_iff], exact and_congr nhds_set_le_iff nhds_set_le_iff }
lemma injective_nhds_set [t1_space α] : function.injective (𝓝ˢ : set α → filter α) :=
λ s t hst, nhds_set_inj_iff.mp hst
lemma strict_mono_nhds_set [t1_space α] : strict_mono (𝓝ˢ : set α → filter α) :=
monotone_nhds_set.strict_mono_of_injective injective_nhds_set
@[simp] lemma nhds_le_nhds_set [t1_space α] {s : set α} {x : α} : 𝓝 x ≤ 𝓝ˢ s ↔ x ∈ s :=
by rw [← nhds_set_singleton, nhds_set_le_iff, singleton_subset_iff]
/-- Removing a non-isolated point from a dense set, one still obtains a dense set. -/
lemma dense.diff_singleton [t1_space α] {s : set α} (hs : dense s) (x : α) [ne_bot (𝓝[≠] x)] :
dense (s \ {x}) :=
hs.inter_of_open_right (dense_compl_singleton x) is_open_compl_singleton
/-- Removing a finset from a dense set in a space without isolated points, one still
obtains a dense set. -/
lemma dense.diff_finset [t1_space α] [∀ (x : α), ne_bot (𝓝[≠] x)]
{s : set α} (hs : dense s) (t : finset α) :
dense (s \ t) :=
begin
induction t using finset.induction_on with x s hxs ih hd,
{ simpa using hs },
{ rw [finset.coe_insert, ← union_singleton, ← diff_diff],
exact ih.diff_singleton _, }
end
/-- Removing a finite set from a dense set in a space without isolated points, one still
obtains a dense set. -/
lemma dense.diff_finite [t1_space α] [∀ (x : α), ne_bot (𝓝[≠] x)]
{s : set α} (hs : dense s) {t : set α} (ht : t.finite) :
dense (s \ t) :=
begin
convert hs.diff_finset ht.to_finset,
exact (finite.coe_to_finset _).symm,
end
/-- If a function to a `t1_space` tends to some limit `b` at some point `a`, then necessarily
`b = f a`. -/
lemma eq_of_tendsto_nhds [topological_space β] [t1_space β] {f : α → β} {a : α} {b : β}
(h : tendsto f (𝓝 a) (𝓝 b)) : f a = b :=
by_contra $ assume (hfa : f a ≠ b),
have fact₁ : {f a}ᶜ ∈ 𝓝 b := compl_singleton_mem_nhds hfa.symm,
have fact₂ : tendsto f (pure a) (𝓝 b) := h.comp (tendsto_id'.2 $ pure_le_nhds a),
fact₂ fact₁ (eq.refl $ f a)
lemma filter.tendsto.eventually_ne [topological_space β] [t1_space β] {α : Type*} {g : α → β}
{l : filter α} {b₁ b₂ : β} (hg : tendsto g l (𝓝 b₁)) (hb : b₁ ≠ b₂) :
∀ᶠ z in l, g z ≠ b₂ :=
hg.eventually (is_open_compl_singleton.eventually_mem hb)
lemma continuous_at.eventually_ne [topological_space β] [t1_space β] {g : α → β}
{a : α} {b : β} (hg1 : continuous_at g a) (hg2 : g a ≠ b) :
∀ᶠ z in 𝓝 a, g z ≠ b :=
hg1.tendsto.eventually_ne hg2
/-- To prove a function to a `t1_space` is continuous at some point `a`, it suffices to prove that
`f` admits *some* limit at `a`. -/
lemma continuous_at_of_tendsto_nhds [topological_space β] [t1_space β] {f : α → β} {a : α} {b : β}
(h : tendsto f (𝓝 a) (𝓝 b)) : continuous_at f a :=
show tendsto f (𝓝 a) (𝓝 $ f a), by rwa eq_of_tendsto_nhds h
lemma tendsto_const_nhds_iff [t1_space α] {l : filter α} [ne_bot l] {c d : α} :
tendsto (λ x, c) l (𝓝 d) ↔ c = d :=
by simp_rw [tendsto, filter.map_const, pure_le_nhds_iff]
/-- If the punctured neighborhoods of a point form a nontrivial filter, then any neighborhood is
infinite. -/
lemma infinite_of_mem_nhds {α} [topological_space α] [t1_space α] (x : α) [hx : ne_bot (𝓝[≠] x)]
{s : set α} (hs : s ∈ 𝓝 x) : set.infinite s :=
begin
intro hsf,
have A : {x} ⊆ s, by simp only [singleton_subset_iff, mem_of_mem_nhds hs],
have B : is_closed (s \ {x}) := (hsf.subset (diff_subset _ _)).is_closed,
have C : (s \ {x})ᶜ ∈ 𝓝 x, from B.is_open_compl.mem_nhds (λ h, h.2 rfl),
have D : {x} ∈ 𝓝 x, by simpa only [← diff_eq, diff_diff_cancel_left A] using inter_mem hs C,
rwa [← mem_interior_iff_mem_nhds, interior_singleton] at D
end
lemma discrete_of_t1_of_finite {X : Type*} [topological_space X] [t1_space X] [finite X] :
discrete_topology X :=
begin
apply singletons_open_iff_discrete.mp,
intros x,
rw [← is_closed_compl_iff],
exact (set.to_finite _).is_closed
end
lemma singleton_mem_nhds_within_of_mem_discrete {s : set α} [discrete_topology s]
{x : α} (hx : x ∈ s) :
{x} ∈ 𝓝[s] x :=
begin
have : ({⟨x, hx⟩} : set s) ∈ 𝓝 (⟨x, hx⟩ : s), by simp [nhds_discrete],
simpa only [nhds_within_eq_map_subtype_coe hx, image_singleton]
using @image_mem_map _ _ _ (coe : s → α) _ this
end
/-- The neighbourhoods filter of `x` within `s`, under the discrete topology, is equal to
the pure `x` filter (which is the principal filter at the singleton `{x}`.) -/
lemma nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) :
𝓝[s] x = pure x :=
le_antisymm (le_pure_iff.2 $ singleton_mem_nhds_within_of_mem_discrete hx) (pure_le_nhds_within hx)
lemma filter.has_basis.exists_inter_eq_singleton_of_mem_discrete
{ι : Type*} {p : ι → Prop} {t : ι → set α} {s : set α} [discrete_topology s] {x : α}
(hb : (𝓝 x).has_basis p t) (hx : x ∈ s) :
∃ i (hi : p i), t i ∩ s = {x} :=
begin
rcases (nhds_within_has_basis hb s).mem_iff.1 (singleton_mem_nhds_within_of_mem_discrete hx)
with ⟨i, hi, hix⟩,
exact ⟨i, hi, subset.antisymm hix $ singleton_subset_iff.2
⟨mem_of_mem_nhds $ hb.mem_of_mem hi, hx⟩⟩
end
/-- A point `x` in a discrete subset `s` of a topological space admits a neighbourhood
that only meets `s` at `x`. -/
lemma nhds_inter_eq_singleton_of_mem_discrete {s : set α} [discrete_topology s]
{x : α} (hx : x ∈ s) :
∃ U ∈ 𝓝 x, U ∩ s = {x} :=
by simpa using (𝓝 x).basis_sets.exists_inter_eq_singleton_of_mem_discrete hx
/-- For point `x` in a discrete subset `s` of a topological space, there is a set `U`
such that
1. `U` is a punctured neighborhood of `x` (ie. `U ∪ {x}` is a neighbourhood of `x`),
2. `U` is disjoint from `s`.
-/
lemma disjoint_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ U ∈ 𝓝[≠] x, disjoint U s :=
let ⟨V, h, h'⟩ := nhds_inter_eq_singleton_of_mem_discrete hx in
⟨{x}ᶜ ∩ V, inter_mem_nhds_within _ h,
(disjoint_iff_inter_eq_empty.mpr (by { rw [inter_assoc, h', compl_inter_self] }))⟩
/-- Let `X` be a topological space and let `s, t ⊆ X` be two subsets. If there is an inclusion
`t ⊆ s`, then the topological space structure on `t` induced by `X` is the same as the one
obtained by the induced topological space structure on `s`. -/
lemma topological_space.subset_trans {X : Type*} [tX : topological_space X]
{s t : set X} (ts : t ⊆ s) :
(subtype.topological_space : topological_space t) =
(subtype.topological_space : topological_space s).induced (set.inclusion ts) :=
begin
change tX.induced ((coe : s → X) ∘ (set.inclusion ts)) =
topological_space.induced (set.inclusion ts) (tX.induced _),
rw ← induced_compose,
end
/-- This lemma characterizes discrete topological spaces as those whose singletons are
neighbourhoods. -/
lemma discrete_topology_iff_nhds {X : Type*} [topological_space X] :
discrete_topology X ↔ (nhds : X → filter X) = pure :=
begin
split,
{ introI hX,
exact nhds_discrete X },
{ intro h,
constructor,
apply eq_of_nhds_eq_nhds,
simp [h, nhds_bot] }
end
/-- The topology pulled-back under an inclusion `f : X → Y` from the discrete topology (`⊥`) is the
discrete topology.
This version does not assume the choice of a topology on either the source `X`
nor the target `Y` of the inclusion `f`. -/
lemma induced_bot {X Y : Type*} {f : X → Y} (hf : function.injective f) :
topological_space.induced f ⊥ = ⊥ :=
eq_of_nhds_eq_nhds (by simp [nhds_induced, ← set.image_singleton, hf.preimage_image, nhds_bot])
/-- The topology induced under an inclusion `f : X → Y` from the discrete topological space `Y`
is the discrete topology on `X`. -/
lemma discrete_topology_induced {X Y : Type*} [tY : topological_space Y] [discrete_topology Y]
{f : X → Y} (hf : function.injective f) : @discrete_topology X (topological_space.induced f tY) :=
by apply discrete_topology.mk; by rw [discrete_topology.eq_bot Y, induced_bot hf]
lemma embedding.discrete_topology {X Y : Type*} [topological_space X] [tY : topological_space Y]
[discrete_topology Y] {f : X → Y} (hf : embedding f) : discrete_topology X :=
⟨by rw [hf.induced, discrete_topology.eq_bot Y, induced_bot hf.inj]⟩
/-- Let `s, t ⊆ X` be two subsets of a topological space `X`. If `t ⊆ s` and the topology induced
by `X`on `s` is discrete, then also the topology induces on `t` is discrete. -/
lemma discrete_topology.of_subset {X : Type*} [topological_space X] {s t : set X}
(ds : discrete_topology s) (ts : t ⊆ s) :
discrete_topology t :=
begin
rw [topological_space.subset_trans ts, ds.eq_bot],
exact {eq_bot := induced_bot (set.inclusion_injective ts)}
end
/-- A T₂ space, also known as a Hausdorff space, is one in which for every
`x ≠ y` there exists disjoint open sets around `x` and `y`. This is
the most widely used of the separation axioms. -/
@[mk_iff] class t2_space (α : Type u) [topological_space α] : Prop :=
(t2 : ∀ x y, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v)
/-- Two different points can be separated by open sets. -/
lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) :
∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v :=
t2_space.t2 x y h
lemma t2_space_iff_disjoint_nhds : t2_space α ↔ ∀ x y : α, x ≠ y → disjoint (𝓝 x) (𝓝 y) :=
begin
refine (t2_space_iff α).trans (forall₃_congr $ λ x y hne, _),
simp only [(nhds_basis_opens x).disjoint_iff (nhds_basis_opens y), exists_prop,
← exists_and_distrib_left, and.assoc, and_comm, and.left_comm]
end
@[simp] lemma disjoint_nhds_nhds [t2_space α] {x y : α} : disjoint (𝓝 x) (𝓝 y) ↔ x ≠ y :=
⟨λ hd he, by simpa [he, nhds_ne_bot.ne] using hd, t2_space_iff_disjoint_nhds.mp ‹_› x y⟩
/-- A finite set can be separated by open sets. -/
lemma t2_separation_finset [t2_space α] (s : finset α) :
∃ f : α → set α, set.pairwise_disjoint ↑s f ∧ ∀ x ∈ s, x ∈ f x ∧ is_open (f x) :=
finset.induction_on s (by simp) begin
rintros t s ht ⟨f, hf, hf'⟩,
have hty : ∀ y : s, t ≠ y := by { rintros y rfl, exact ht y.2 },
choose u v hu hv htu hxv huv using λ {x} (h : t ≠ x), t2_separation h,
refine ⟨λ x, if ht : t = x then ⋂ y : s, u (hty y) else f x ∩ v ht, _, _⟩,
{ rintros x hx₁ y hy₁ hxy a ⟨hx, hy⟩,
rw [finset.mem_coe, finset.mem_insert, eq_comm] at hx₁ hy₁,
rcases eq_or_ne t x with rfl | hx₂;
rcases eq_or_ne t y with rfl | hy₂,
{ exact hxy rfl },
{ simp_rw [dif_pos rfl, mem_Inter] at hx,
simp_rw [dif_neg hy₂] at hy,
exact huv hy₂ ⟨hx ⟨y, hy₁.resolve_left hy₂⟩, hy.2⟩ },
{ simp_rw [dif_neg hx₂] at hx,
simp_rw [dif_pos rfl, mem_Inter] at hy,
exact huv hx₂ ⟨hy ⟨x, hx₁.resolve_left hx₂⟩, hx.2⟩ },
{ simp_rw [dif_neg hx₂] at hx,
simp_rw [dif_neg hy₂] at hy,
exact hf (hx₁.resolve_left hx₂) (hy₁.resolve_left hy₂) hxy ⟨hx.1, hy.1⟩ } },
{ intros x hx,
split_ifs with ht,
{ refine ⟨mem_Inter.2 (λ y, _), is_open_Inter (λ y, hu (hty y))⟩,
rw ←ht,
exact htu (hty y) },
{ have hx := hf' x ((finset.mem_insert.1 hx).resolve_left (ne.symm ht)),
exact ⟨⟨hx.1, hxv ht⟩, is_open.inter hx.2 (hv ht)⟩ } }
end
@[priority 100] -- see Note [lower instance priority]
instance t2_space.t1_space [t2_space α] : t1_space α :=
t1_space_iff_disjoint_pure_nhds.mpr $ λ x y hne, (disjoint_nhds_nhds.2 hne).mono_left $
pure_le_nhds _
/-- A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. -/
lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, ne_bot (𝓝 x ⊓ 𝓝 y) → x = y :=
by simp only [t2_space_iff_disjoint_nhds, disjoint_iff, ne_bot_iff, ne.def, not_imp_comm]
lemma eq_of_nhds_ne_bot [t2_space α] {x y : α} (h : ne_bot (𝓝 x ⊓ 𝓝 y)) : x = y :=
t2_iff_nhds.mp ‹_› h
lemma t2_space_iff_nhds : t2_space α ↔ ∀ {x y : α}, x ≠ y → ∃ (U ∈ 𝓝 x) (V ∈ 𝓝 y), disjoint U V :=
by simp only [t2_space_iff_disjoint_nhds, filter.disjoint_iff]
lemma t2_separation_nhds [t2_space α] {x y : α} (h : x ≠ y) :
∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ disjoint u v :=
let ⟨u, v, open_u, open_v, x_in, y_in, huv⟩ := t2_separation h in
⟨u, v, open_u.mem_nhds x_in, open_v.mem_nhds y_in, huv⟩
lemma t2_separation_compact_nhds [locally_compact_space α] [t2_space α] {x y : α} (h : x ≠ y) :
∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ is_compact u ∧ is_compact v ∧ disjoint u v :=
by simpa only [exists_prop, ← exists_and_distrib_left, and_comm, and.assoc, and.left_comm]
using ((compact_basis_nhds x).disjoint_iff (compact_basis_nhds y)).1 (disjoint_nhds_nhds.2 h)
lemma t2_iff_ultrafilter :
t2_space α ↔ ∀ {x y : α} (f : ultrafilter α), ↑f ≤ 𝓝 x → ↑f ≤ 𝓝 y → x = y :=
t2_iff_nhds.trans $ by simp only [←exists_ultrafilter_iff, and_imp, le_inf_iff, exists_imp_distrib]
lemma t2_iff_is_closed_diagonal : t2_space α ↔ is_closed (diagonal α) :=
by simp only [t2_space_iff_disjoint_nhds, ← is_open_compl_iff, is_open_iff_mem_nhds, prod.forall,
nhds_prod_eq, compl_diagonal_mem_prod, mem_compl_iff, mem_diagonal_iff]
lemma is_closed_diagonal [t2_space α] : is_closed (diagonal α) :=
t2_iff_is_closed_diagonal.mp ‹_›
section separated
open separated finset
lemma finset_disjoint_finset_opens_of_t2 [t2_space α] :
∀ (s t : finset α), disjoint s t → separated (s : set α) t :=
begin
refine induction_on_union _ (λ a b hi d, (hi d.symm).symm) (λ a d, empty_right a) (λ a b ab, _) _,
{ obtain ⟨U, V, oU, oV, aU, bV, UV⟩ := t2_separation (finset.disjoint_singleton.1 ab),
refine ⟨U, V, oU, oV, _, _, UV⟩;
exact singleton_subset_set_iff.mpr ‹_› },
{ intros a b c ac bc d,
apply_mod_cast union_left (ac (disjoint_of_subset_left (a.subset_union_left b) d)) (bc _),
exact disjoint_of_subset_left (a.subset_union_right b) d },
end
lemma point_disjoint_finset_opens_of_t2 [t2_space α] {x : α} {s : finset α} (h : x ∉ s) :
separated ({x} : set α) s :=
by exact_mod_cast finset_disjoint_finset_opens_of_t2 {x} s (finset.disjoint_singleton_left.mpr h)
end separated
lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α}
[ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b :=
eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb
lemma tendsto_nhds_unique' [t2_space α] {f : β → α} {l : filter β} {a b : α}
(hl : ne_bot l) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b :=
eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb
lemma tendsto_nhds_unique_of_eventually_eq [t2_space α] {f g : β → α} {l : filter β} {a b : α}
[ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto g l (𝓝 b)) (hfg : f =ᶠ[l] g) :
a = b :=
tendsto_nhds_unique (ha.congr' hfg) hb
lemma tendsto_nhds_unique_of_frequently_eq [t2_space α] {f g : β → α} {l : filter β} {a b : α}
(ha : tendsto f l (𝓝 a)) (hb : tendsto g l (𝓝 b)) (hfg : ∃ᶠ x in l, f x = g x) :
a = b :=
have ∃ᶠ z : α × α in 𝓝 (a, b), z.1 = z.2 := (ha.prod_mk_nhds hb).frequently hfg,
not_not.1 $ λ hne, this (is_closed_diagonal.is_open_compl.mem_nhds hne)
/-- A T₂.₅ space, also known as a Urysohn space, is a topological space
where for every pair `x ≠ y`, there are two open sets, with the intersection of closures
empty, one containing `x` and the other `y` . -/
class t2_5_space (α : Type u) [topological_space α]: Prop :=
(t2_5 : ∀ x y (h : x ≠ y), ∃ (U V: set α), is_open U ∧ is_open V ∧
disjoint (closure U) (closure V) ∧ x ∈ U ∧ y ∈ V)
@[priority 100] -- see Note [lower instance priority]
instance t2_5_space.t2_space [t2_5_space α] : t2_space α :=
⟨λ x y hxy,
let ⟨U, V, hU, hV, hUV, hh⟩ := t2_5_space.t2_5 x y hxy in
⟨U, V, hU, hV, hh.1, hh.2, hUV.mono subset_closure subset_closure⟩⟩
section lim
variables [t2_space α] {f : filter α}
/-!
### Properties of `Lim` and `lim`
In this section we use explicit `nonempty α` instances for `Lim` and `lim`. This way the lemmas
are useful without a `nonempty α` instance.
-/
lemma Lim_eq {a : α} [ne_bot f] (h : f ≤ 𝓝 a) :
@Lim _ _ ⟨a⟩ f = a :=
tendsto_nhds_unique (le_nhds_Lim ⟨a, h⟩) h
lemma Lim_eq_iff [ne_bot f] (h : ∃ (a : α), f ≤ nhds a) {a} : @Lim _ _ ⟨a⟩ f = a ↔ f ≤ 𝓝 a :=
⟨λ c, c ▸ le_nhds_Lim h, Lim_eq⟩
lemma ultrafilter.Lim_eq_iff_le_nhds [compact_space α] {x : α} {F : ultrafilter α} :
F.Lim = x ↔ ↑F ≤ 𝓝 x :=
⟨λ h, h ▸ F.le_nhds_Lim, Lim_eq⟩
lemma is_open_iff_ultrafilter' [compact_space α] (U : set α) :
is_open U ↔ (∀ F : ultrafilter α, F.Lim ∈ U → U ∈ F.1) :=
begin
rw is_open_iff_ultrafilter,
refine ⟨λ h F hF, h F.Lim hF F F.le_nhds_Lim, _⟩,
intros cond x hx f h,
rw [← (ultrafilter.Lim_eq_iff_le_nhds.2 h)] at hx,
exact cond _ hx
end
lemma filter.tendsto.lim_eq {a : α} {f : filter β} [ne_bot f] {g : β → α} (h : tendsto g f (𝓝 a)) :
@lim _ _ _ ⟨a⟩ f g = a :=
Lim_eq h
lemma filter.lim_eq_iff {f : filter β} [ne_bot f] {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) {a} :
@lim _ _ _ ⟨a⟩ f g = a ↔ tendsto g f (𝓝 a) :=
⟨λ c, c ▸ tendsto_nhds_lim h, filter.tendsto.lim_eq⟩
lemma continuous.lim_eq [topological_space β] {f : β → α} (h : continuous f) (a : β) :
@lim _ _ _ ⟨f a⟩ (𝓝 a) f = f a :=
(h.tendsto a).lim_eq
@[simp] lemma Lim_nhds (a : α) : @Lim _ _ ⟨a⟩ (𝓝 a) = a :=
Lim_eq le_rfl
@[simp] lemma lim_nhds_id (a : α) : @lim _ _ _ ⟨a⟩ (𝓝 a) id = a :=
Lim_nhds a
@[simp] lemma Lim_nhds_within {a : α} {s : set α} (h : a ∈ closure s) :
@Lim _ _ ⟨a⟩ (𝓝[s] a) = a :=
by haveI : ne_bot (𝓝[s] a) := mem_closure_iff_cluster_pt.1 h;
exact Lim_eq inf_le_left
@[simp] lemma lim_nhds_within_id {a : α} {s : set α} (h : a ∈ closure s) :
@lim _ _ _ ⟨a⟩ (𝓝[s] a) id = a :=
Lim_nhds_within h
end lim
/-!
### `t2_space` constructions
We use two lemmas to prove that various standard constructions generate Hausdorff spaces from
Hausdorff spaces:
* `separated_by_continuous` says that two points `x y : α` can be separated by open neighborhoods
provided that there exists a continuous map `f : α → β` with a Hausdorff codomain such that
`f x ≠ f y`. We use this lemma to prove that topological spaces defined using `induced` are
Hausdorff spaces.
* `separated_by_open_embedding` says that for an open embedding `f : α → β` of a Hausdorff space
`α`, the images of two distinct points `x y : α`, `x ≠ y` can be separated by open neighborhoods.
We use this lemma to prove that topological spaces defined using `coinduced` are Hausdorff spaces.
-/
@[priority 100] -- see Note [lower instance priority]
instance discrete_topology.to_t2_space {α : Type*} [topological_space α] [discrete_topology α] :
t2_space α :=
⟨λ x y h, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, rfl, rfl, disjoint_singleton.2 h⟩⟩
lemma separated_by_continuous {α : Type*} {β : Type*}
[topological_space α] [topological_space β] [t2_space β]
{f : α → β} (hf : continuous f) {x y : α} (h : f x ≠ f y) :
∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v :=
let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in
⟨f ⁻¹' u, f ⁻¹' v, uo.preimage hf, vo.preimage hf, xu, yv, uv.preimage _⟩
lemma separated_by_open_embedding {α β : Type*} [topological_space α] [topological_space β]
[t2_space α] {f : α → β} (hf : open_embedding f) {x y : α} (h : x ≠ y) :
∃ u v : set β, is_open u ∧ is_open v ∧ f x ∈ u ∧ f y ∈ v ∧ disjoint u v :=
let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in
⟨f '' u, f '' v, hf.is_open_map _ uo, hf.is_open_map _ vo,
mem_image_of_mem _ xu, mem_image_of_mem _ yv, disjoint_image_of_injective hf.inj uv⟩
instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) :=
⟨assume x y h, separated_by_continuous continuous_subtype_val (mt subtype.eq h)⟩
instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α]
[t₂ : topological_space β] [t2_space β] : t2_space (α × β) :=
⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h,
or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h))
(λ h₁, separated_by_continuous continuous_fst h₁)
(λ h₂, separated_by_continuous continuous_snd h₂)⟩
lemma embedding.t2_space [topological_space β] [t2_space β] {f : α → β} (hf : embedding f) :
t2_space α :=
⟨λ x y h, separated_by_continuous hf.continuous (hf.inj.ne h)⟩
instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α]
[t₂ : topological_space β] [t2_space β] : t2_space (α ⊕ β) :=
begin
constructor,
rintros (x|x) (y|y) h,
{ replace h : x ≠ y := λ c, (c.subst h) rfl,
exact separated_by_open_embedding open_embedding_inl h },
{ exact ⟨_, _, is_open_range_inl, is_open_range_inr, ⟨x, rfl⟩, ⟨y, rfl⟩,
is_compl_range_inl_range_inr.disjoint⟩ },
{ exact ⟨_, _, is_open_range_inr, is_open_range_inl, ⟨x, rfl⟩, ⟨y, rfl⟩,
is_compl_range_inl_range_inr.disjoint.symm⟩ },
{ replace h : x ≠ y := λ c, (c.subst h) rfl,
exact separated_by_open_embedding open_embedding_inr h }
end
instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)]
[∀a, t2_space (β a)] :
t2_space (Πa, β a) :=
⟨assume x y h,
let ⟨i, hi⟩ := not_forall.mp (mt funext h) in
separated_by_continuous (continuous_apply i) hi⟩
instance sigma.t2_space {ι : Type*} {α : ι → Type*} [Πi, topological_space (α i)]
[∀a, t2_space (α a)] :
t2_space (Σi, α i) :=
begin
constructor,
rintros ⟨i, x⟩ ⟨j, y⟩ neq,
rcases em (i = j) with (rfl|h),
{ replace neq : x ≠ y := λ c, (c.subst neq) rfl,
exact separated_by_open_embedding open_embedding_sigma_mk neq },
{ exact ⟨_, _, is_open_range_sigma_mk, is_open_range_sigma_mk, ⟨x, rfl⟩, ⟨y, rfl⟩, by tidy⟩ }
end
variables {γ : Type*} [topological_space β] [topological_space γ]
lemma is_closed_eq [t2_space α] {f g : β → α}
(hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} :=
continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal
lemma is_open_ne_fun [t2_space α] {f g : β → α}
(hf : continuous f) (hg : continuous g) : is_open {x:β | f x ≠ g x} :=
is_open_compl_iff.mpr $ is_closed_eq hf hg
/-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. See also
`set.eq_on.of_subset_closure` for a more general version. -/
lemma set.eq_on.closure [t2_space α] {s : set β} {f g : β → α} (h : eq_on f g s)
(hf : continuous f) (hg : continuous g) :
eq_on f g (closure s) :=
closure_minimal h (is_closed_eq hf hg)
/-- If two continuous functions are equal on a dense set, then they are equal. -/
lemma continuous.ext_on [t2_space α] {s : set β} (hs : dense s) {f g : β → α}
(hf : continuous f) (hg : continuous g) (h : eq_on f g s) :
f = g :=
funext $ λ x, h.closure hf hg (hs x)
lemma eq_on_closure₂' [t2_space α] {s : set β} {t : set γ} {f g : β → γ → α}
(h : ∀ (x ∈ s) (y ∈ t), f x y = g x y)
(hf₁ : ∀ x, continuous (f x)) (hf₂ : ∀ y, continuous (λ x, f x y))
(hg₁ : ∀ x, continuous (g x)) (hg₂ : ∀ y, continuous (λ x, g x y)) :
∀ (x ∈ closure s) (y ∈ closure t), f x y = g x y :=
suffices closure s ⊆ ⋂ y ∈ closure t, {x | f x y = g x y}, by simpa only [subset_def, mem_Inter],
closure_minimal (λ x hx, mem_Inter₂.2 $ set.eq_on.closure (h x hx) (hf₁ _) (hg₁ _)) $
is_closed_bInter $ λ y hy, is_closed_eq (hf₂ _) (hg₂ _)
lemma eq_on_closure₂ [t2_space α] {s : set β} {t : set γ} {f g : β → γ → α}
(h : ∀ (x ∈ s) (y ∈ t), f x y = g x y)
(hf : continuous (uncurry f)) (hg : continuous (uncurry g)) :
∀ (x ∈ closure s) (y ∈ closure t), f x y = g x y :=
eq_on_closure₂' h (λ x, continuous_uncurry_left x hf) (λ x, continuous_uncurry_right x hf)
(λ y, continuous_uncurry_left y hg) (λ y, continuous_uncurry_right y hg)
/-- If `f x = g x` for all `x ∈ s` and `f`, `g` are continuous on `t`, `s ⊆ t ⊆ closure s`, then
`f x = g x` for all `x ∈ t`. See also `set.eq_on.closure`. -/
lemma set.eq_on.of_subset_closure [t2_space α] {s t : set β} {f g : β → α} (h : eq_on f g s)
(hf : continuous_on f t) (hg : continuous_on g t) (hst : s ⊆ t) (hts : t ⊆ closure s) :
eq_on f g t :=
begin
intros x hx,
haveI : (𝓝[s] x).ne_bot, from mem_closure_iff_cluster_pt.mp (hts hx),
exact tendsto_nhds_unique_of_eventually_eq ((hf x hx).mono_left $ nhds_within_mono _ hst)
((hg x hx).mono_left $ nhds_within_mono _ hst) (h.eventually_eq_of_mem self_mem_nhds_within)
end
lemma function.left_inverse.closed_range [t2_space α] {f : α → β} {g : β → α}
(h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) :
is_closed (range g) :=
have eq_on (g ∘ f) id (closure $ range g),
from h.right_inv_on_range.eq_on.closure (hg.comp hf) continuous_id,
is_closed_of_closure_subset $ λ x hx,
calc x = g (f x) : (this hx).symm
... ∈ _ : mem_range_self _
lemma function.left_inverse.closed_embedding [t2_space α] {f : α → β} {g : β → α}
(h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) :
closed_embedding g :=
⟨h.embedding hf hg, h.closed_range hf hg⟩
lemma compact_compact_separated [t2_space α] {s t : set α}
(hs : is_compact s) (ht : is_compact t) (hst : disjoint s t) :
∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v :=
by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst;
exact generalized_tube_lemma hs ht is_closed_diagonal.is_open_compl hst
/-- In a `t2_space`, every compact set is closed. -/
lemma is_compact.is_closed [t2_space α] {s : set α} (hs : is_compact s) : is_closed s :=
is_open_compl_iff.1 $ is_open_iff_forall_mem_open.mpr $ assume x hx,
let ⟨u, v, uo, vo, su, xv, uv⟩ :=
compact_compact_separated hs is_compact_singleton (disjoint_singleton_right.2 hx) in
⟨v, (uv.mono_left $ show s ≤ u, from su).subset_compl_left, vo, by simpa using xv⟩
@[simp] lemma filter.coclosed_compact_eq_cocompact [t2_space α] :
coclosed_compact α = cocompact α :=
by simp [coclosed_compact, cocompact, infi_and', and_iff_right_of_imp is_compact.is_closed]
@[simp] lemma bornology.relatively_compact_eq_in_compact [t2_space α] :
bornology.relatively_compact α = bornology.in_compact α :=
by rw bornology.ext_iff; exact filter.coclosed_compact_eq_cocompact
/-- If `V : ι → set α` is a decreasing family of compact sets then any neighborhood of
`⋂ i, V i` contains some `V i`. This is a version of `exists_subset_nhd_of_compact'` where we
don't need to assume each `V i` closed because it follows from compactness since `α` is
assumed to be Hausdorff. -/
lemma exists_subset_nhd_of_compact [t2_space α] {ι : Type*} [nonempty ι] {V : ι → set α}
(hV : directed (⊇) V) (hV_cpct : ∀ i, is_compact (V i)) {U : set α}
(hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U :=
exists_subset_nhd_of_compact' hV hV_cpct (λ i, (hV_cpct i).is_closed) hU
lemma compact_exhaustion.is_closed [t2_space α] (K : compact_exhaustion α) (n : ℕ) :
is_closed (K n) :=
(K.is_compact n).is_closed
lemma is_compact.inter [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) :
is_compact (s ∩ t) :=
hs.inter_right $ ht.is_closed
lemma compact_closure_of_subset_compact [t2_space α] {s t : set α} (ht : is_compact t) (h : s ⊆ t) :
is_compact (closure s) :=
compact_of_is_closed_subset ht is_closed_closure (closure_minimal h ht.is_closed)
@[simp]
lemma exists_compact_superset_iff [t2_space α] {s : set α} :
(∃ K, is_compact K ∧ s ⊆ K) ↔ is_compact (closure s) :=
⟨λ ⟨K, hK, hsK⟩, compact_closure_of_subset_compact hK hsK, λ h, ⟨closure s, h, subset_closure⟩⟩
lemma image_closure_of_compact [t2_space β]
{s : set α} (hs : is_compact (closure s)) {f : α → β} (hf : continuous_on f (closure s)) :
f '' closure s = closure (f '' s) :=
subset.antisymm hf.image_closure $ closure_minimal (image_subset f subset_closure)
(hs.image_of_continuous_on hf).is_closed
/-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/
lemma is_compact.binary_compact_cover [t2_space α] {K U V : set α} (hK : is_compact K)
(hU : is_open U) (hV : is_open V) (h2K : K ⊆ U ∪ V) :
∃ K₁ K₂ : set α, is_compact K₁ ∧ is_compact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ :=
begin
obtain ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩ := compact_compact_separated (hK.diff hU) (hK.diff hV)
(by rwa [disjoint_iff_inter_eq_empty, diff_inter_diff, diff_eq_empty]),
exact ⟨_, _, hK.diff h1O₁, hK.diff h1O₂, by rwa [diff_subset_comm], by rwa [diff_subset_comm],
by rw [← diff_inter, hO.inter_eq, diff_empty]⟩
end
lemma continuous.is_closed_map [compact_space α] [t2_space β] {f : α → β} (h : continuous f) :
is_closed_map f :=
λ s hs, (hs.is_compact.image h).is_closed
lemma continuous.closed_embedding [compact_space α] [t2_space β] {f : α → β} (h : continuous f)
(hf : function.injective f) : closed_embedding f :=
closed_embedding_of_continuous_injective_closed h hf h.is_closed_map
section
open finset function
/-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/
lemma is_compact.finite_compact_cover [t2_space α] {s : set α} (hs : is_compact s)
{ι} (t : finset ι) (U : ι → set α) (hU : ∀ i ∈ t, is_open (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) :
∃ K : ι → set α, (∀ i, is_compact (K i)) ∧ (∀i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i :=
begin
classical,
induction t using finset.induction with x t hx ih generalizing U hU s hs hsC,
{ refine ⟨λ _, ∅, λ i, is_compact_empty, λ i, empty_subset _, _⟩,
simpa only [subset_empty_iff, Union_false, Union_empty] using hsC },
simp only [finset.set_bUnion_insert] at hsC,
simp only [finset.mem_insert] at hU,
have hU' : ∀ i ∈ t, is_open (U i) := λ i hi, hU i (or.inr hi),
rcases hs.binary_compact_cover (hU x (or.inl rfl)) (is_open_bUnion hU') hsC
with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩,
rcases ih U hU' h1K₂ h2K₂ with ⟨K, h1K, h2K, h3K⟩,
refine ⟨update K x K₁, _, _, _⟩,
{ intros i, by_cases hi : i = x,
{ simp only [update_same, hi, h1K₁] },
{ rw [← ne.def] at hi, simp only [update_noteq hi, h1K] }},
{ intros i, by_cases hi : i = x,
{ simp only [update_same, hi, h2K₁] },
{ rw [← ne.def] at hi, simp only [update_noteq hi, h2K] }},
{ simp only [set_bUnion_insert_update _ hx, hK, h3K] }
end
end
lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ is_compact s) :
locally_compact_space α :=
⟨assume x n hn,
let ⟨u, un, uo, xu⟩ := mem_nhds_iff.mp hn in
let ⟨k, kx, kc⟩ := h x in
-- K is compact but not necessarily contained in N.
-- K \ U is again compact and doesn't contain x, so
-- we may find open sets V, W separating x from K \ U.
-- Then K \ W is a compact neighborhood of x contained in U.
let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated is_compact_singleton (kc.diff uo)
(disjoint_singleton_left.2 $ λ h, h.2 xu) in
have wn : wᶜ ∈ 𝓝 x, from
mem_nhds_iff.mpr ⟨v, vw.subset_compl_right, vo, singleton_subset_iff.mp xv⟩,
⟨k \ w,
filter.inter_mem kx wn,
subset.trans (diff_subset_comm.mp kuw) un,
kc.diff wo⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α :=
locally_compact_of_compact_nhds (assume x, ⟨univ, is_open_univ.mem_nhds trivial, compact_univ⟩)
/-- In a locally compact T₂ space, every point has an open neighborhood with compact closure -/
lemma exists_open_with_compact_closure [locally_compact_space α] [t2_space α] (x : α) :
∃ (U : set α), is_open U ∧ x ∈ U ∧ is_compact (closure U) :=
begin
rcases exists_compact_mem_nhds x with ⟨K, hKc, hxK⟩,
rcases mem_nhds_iff.1 hxK with ⟨t, h1t, h2t, h3t⟩,
exact ⟨t, h2t, h3t, compact_closure_of_subset_compact hKc h1t⟩
end
/--
In a locally compact T₂ space, every compact set has an open neighborhood with compact closure.
-/
lemma exists_open_superset_and_is_compact_closure [locally_compact_space α] [t2_space α]
{K : set α} (hK : is_compact K) : ∃ V, is_open V ∧ K ⊆ V ∧ is_compact (closure V) :=
begin
rcases exists_compact_superset hK with ⟨K', hK', hKK'⟩,
refine ⟨interior K', is_open_interior, hKK',
compact_closure_of_subset_compact hK' interior_subset⟩,
end
/--
In a locally compact T₂ space, given a compact set `K` inside an open set `U`, we can find a
open set `V` between these sets with compact closure: `K ⊆ V` and the closure of `V` is inside `U`.
-/
lemma exists_open_between_and_is_compact_closure [locally_compact_space α] [t2_space α]
{K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) :
∃ V, is_open V ∧ K ⊆ V ∧ closure V ⊆ U ∧ is_compact (closure V) :=
begin
rcases exists_compact_between hK hU hKU with ⟨V, hV, hKV, hVU⟩,
exact ⟨interior V, is_open_interior, hKV,
(closure_minimal interior_subset hV.is_closed).trans hVU,
compact_closure_of_subset_compact hV interior_subset⟩,
end
lemma is_preirreducible_iff_subsingleton [t2_space α] (S : set α) :
is_preirreducible S ↔ S.subsingleton :=
begin
refine ⟨λ h x hx y hy, _, set.subsingleton.is_preirreducible⟩,
by_contradiction e,
obtain ⟨U, V, hU, hV, hxU, hyV, h'⟩ := t2_separation e,
exact ((h U V hU hV ⟨x, hx, hxU⟩ ⟨y, hy, hyV⟩).mono $ inter_subset_right _ _).not_disjoint h',
end
lemma is_irreducible_iff_singleton [t2_space α] (S : set α) :
is_irreducible S ↔ ∃ x, S = {x} :=
by rw [is_irreducible, is_preirreducible_iff_subsingleton,
exists_eq_singleton_iff_nonempty_subsingleton]
end separation
section t3
/-- A T₃ space is a T₀ space in which for every closed `C` and `x ∉ C`, there exist
disjoint open sets containing `x` and `C` respectively. -/
class t3_space (α : Type u) [topological_space α] extends t0_space α : Prop :=
(regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝[t] a = ⊥)
lemma t3_space.of_lift'_closure [t0_space α] (h : ∀ x : α, (𝓝 x).lift' closure = 𝓝 x) :
t3_space α :=
begin
refine ⟨λ s a hs ha, _⟩,
have : sᶜ ∈ (𝓝 a).lift' closure,
{ rw [h], exact hs.is_open_compl.mem_nhds ha },
rcases (𝓝 a).basis_sets.lift'_closure.mem_iff.mp this with ⟨U, haU, hU⟩,
refine ⟨(closure U)ᶜ, is_closed_closure.is_open_compl, subset_compl_comm.mp hU, not_not.mp _⟩,
rw [← ne, ← ne_bot_iff, ← mem_closure_iff_nhds_within_ne_bot, closure_compl, mem_compl_iff,
not_not, mem_interior_iff_mem_nhds],
exact mem_of_superset haU subset_closure
end
@[priority 100] -- see Note [lower instance priority]
instance t3_space.t1_space [t3_space α] : t1_space α :=
begin
rw t1_space_iff_exists_open,
intros x y hxy,
obtain ⟨U, hU, h⟩ := exists_is_open_xor_mem hxy,
cases h,
{ exact ⟨U, hU, h⟩ },
{ obtain ⟨R, hR, hh⟩ := t3_space.regular (is_closed_compl_iff.mpr hU) (not_not.mpr h.1),
obtain ⟨V, hV, hhh⟩ := mem_nhds_iff.1 (filter.inf_principal_eq_bot.1 hh.2),
exact ⟨R, hR, hh.1 (mem_compl h.2), hV hhh.2⟩ }
end
lemma nhds_is_closed [t3_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) :
∃ t ∈ 𝓝 a, t ⊆ s ∧ is_closed t :=
let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_iff.mp h in
have ∃t, is_open t ∧ s'ᶜ ⊆ t ∧ 𝓝[t] a = ⊥,
from t3_space.regular h₂.is_closed_compl (not_not_intro h₃),
let ⟨t, ht₁, ht₂, ht₃⟩ := this in
⟨tᶜ,
mem_of_eq_bot $ by rwa [compl_compl],
subset.trans (compl_subset_comm.1 ht₂) h₁,
is_closed_compl_iff.mpr ht₁⟩
lemma closed_nhds_basis [t3_space α] (a : α) :
(𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_closed s) id :=
⟨λ t, ⟨λ t_in, let ⟨s, s_in, h_st, h⟩ := nhds_is_closed t_in in ⟨s, ⟨s_in, h⟩, h_st⟩,
λ ⟨s, ⟨s_in, hs⟩, hst⟩, mem_of_superset s_in hst⟩⟩
lemma topological_space.is_topological_basis.exists_closure_subset [t3_space α]
{B : set (set α)} (hB : topological_space.is_topological_basis B) {a : α} {s : set α}
(h : s ∈ 𝓝 a) :
∃ t ∈ B, a ∈ t ∧ closure t ⊆ s :=
begin
rcases nhds_is_closed h with ⟨t, hat, hts, htc⟩,
rcases hB.mem_nhds_iff.1 hat with ⟨u, huB, hau, hut⟩,
exact ⟨u, huB, hau, (closure_minimal hut htc).trans hts⟩
end
lemma topological_space.is_topological_basis.nhds_basis_closure [t3_space α]
{B : set (set α)} (hB : topological_space.is_topological_basis B) (a : α) :
(𝓝 a).has_basis (λ s : set α, a ∈ s ∧ s ∈ B) closure :=
⟨λ s, ⟨λ h, let ⟨t, htB, hat, hts⟩ := hB.exists_closure_subset h in ⟨t, ⟨hat, htB⟩, hts⟩,
λ ⟨t, ⟨hat, htB⟩, hts⟩, mem_of_superset (hB.mem_nhds htB hat) (subset_closure.trans hts)⟩⟩
protected lemma embedding.t3_space [topological_space β] [t3_space β] {f : α → β}
(hf : embedding f) : t3_space α :=
{ to_t0_space := hf.t0_space,
regular :=
begin
intros s a hs ha,
rcases hf.to_inducing.is_closed_iff.1 hs with ⟨s, hs', rfl⟩,
rcases t3_space.regular hs' ha with ⟨t, ht, hst, hat⟩,
refine ⟨f ⁻¹' t, ht.preimage hf.continuous, preimage_mono hst, _⟩,
rw [nhds_within, hf.to_inducing.nhds_eq_comap, ← comap_principal, ← comap_inf,
← nhds_within, hat, comap_bot]
end }
instance subtype.t3_space [t3_space α] {p : α → Prop} : t3_space (subtype p) :=
embedding_subtype_coe.t3_space
variable (α)
@[priority 100] -- see Note [lower instance priority]
instance t3_space.t2_space [t3_space α] : t2_space α :=
⟨λ x y hxy,
let ⟨s, hs, hys, hxs⟩ := t3_space.regular is_closed_singleton
(mt mem_singleton_iff.1 hxy),
⟨t, hxt, u, hsu, htu⟩ := empty_mem_iff_bot.2 hxs,
⟨v, hvt, hv, hxv⟩ := mem_nhds_iff.1 hxt in
⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys,
(disjoint_iff_inter_eq_empty.2 htu.symm).mono hvt hsu⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance t3_space.t2_5_space [t3_space α] : t2_5_space α :=
⟨λ x y hxy,
let ⟨U, V, hU, hV, hh_1, hh_2, hUV⟩ := t2_separation hxy,
hxcV := not_not.mpr (interior_maximal hUV.subset_compl_right hU hh_1),
⟨R, hR, hh⟩ := t3_space.regular is_closed_closure (by rwa closure_eq_compl_interior_compl),
⟨A, hA, hhh⟩ := mem_nhds_iff.1 (filter.inf_principal_eq_bot.1 hh.2) in
⟨A, V, hhh.1, hV, disjoint_compl_left.mono_left ((closure_minimal hA hR.is_closed_compl).trans $
compl_subset_compl.mpr hh.1), hhh.2, hh_2⟩⟩
variable {α}
/-- Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`,
with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. -/
lemma disjoint_nested_nhds [t3_space α] {x y : α} (h : x ≠ y) :
∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧
V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ disjoint U₁ U₂ :=
begin
rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩,
rcases nhds_is_closed (is_open.mem_nhds U₁_op x_in) with ⟨V₁, V₁_in, h₁, V₁_closed⟩,
rcases nhds_is_closed (is_open.mem_nhds U₂_op y_in) with ⟨V₂, V₂_in, h₂, V₂_closed⟩,
use [U₁, mem_of_superset V₁_in h₁, V₁, V₁_in,
U₂, mem_of_superset V₂_in h₂, V₂, V₂_in],
tauto
end
end t3
section normality
/-- A T₄ space, also known as a normal space (although this condition sometimes
omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`,
there exist disjoint open sets containing `C` and `D` respectively. -/
class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop :=
(normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t →
∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v)
theorem normal_separation [normal_space α] {s t : set α}
(H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) :
∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v :=
normal_space.normal s t H1 H2 H3
theorem normal_exists_closure_subset [normal_space α] {s t : set α} (hs : is_closed s)
(ht : is_open t) (hst : s ⊆ t) :
∃ u, is_open u ∧ s ⊆ u ∧ closure u ⊆ t :=
begin
have : disjoint s tᶜ, from λ x ⟨hxs, hxt⟩, hxt (hst hxs),
rcases normal_separation hs (is_closed_compl_iff.2 ht) this
with ⟨s', t', hs', ht', hss', htt', hs't'⟩,
refine ⟨s', hs', hss',
subset.trans (closure_minimal _ (is_closed_compl_iff.2 ht')) (compl_subset_comm.1 htt')⟩,
exact λ x hxs hxt, hs't' ⟨hxs, hxt⟩
end
@[priority 100] -- see Note [lower instance priority]
instance normal_space.t3_space [normal_space α] : t3_space α :=
{ regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ :=
normal_separation hs is_closed_singleton
(λ _ ⟨hx, hy⟩, hxs $ mem_of_eq_of_mem (eq_of_mem_singleton hy).symm hx) in
⟨u, hu, hsu, filter.empty_mem_iff_bot.1 $ filter.mem_inf_iff.2
⟨v, is_open.mem_nhds hv (singleton_subset_iff.1 hxv), u, filter.mem_principal_self u,
by rwa [eq_comm, inter_comm, ← disjoint_iff_inter_eq_empty]⟩⟩ }
-- We can't make this an instance because it could cause an instance loop.
lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α :=
⟨λ s t hs ht, compact_compact_separated hs.is_compact ht.is_compact⟩
protected lemma closed_embedding.normal_space [topological_space β] [normal_space β] {f : α → β}
(hf : closed_embedding f) : normal_space α :=
{ to_t1_space := hf.to_embedding.t1_space,
normal :=
begin
intros s t hs ht hst,
rcases normal_space.normal (f '' s) (f '' t) (hf.is_closed_map s hs) (hf.is_closed_map t ht)
(disjoint_image_of_injective hf.inj hst) with ⟨u, v, hu, hv, hsu, htv, huv⟩,
rw image_subset_iff at hsu htv,
exact ⟨f ⁻¹' u, f ⁻¹' v, hu.preimage hf.continuous, hv.preimage hf.continuous,
hsu, htv, huv.preimage f⟩
end }
variable (α)
/-- A T₃ topological space with second countable topology is a normal space.
This lemma is not an instance to avoid a loop. -/
lemma normal_space_of_t3_second_countable [second_countable_topology α] [t3_space α] :
normal_space α :=
begin
have key : ∀ {s t : set α}, is_closed t → disjoint s t →
∃ U : set (countable_basis α), (s ⊆ ⋃ u ∈ U, ↑u) ∧
(∀ u ∈ U, disjoint (closure ↑u) t) ∧
∀ n : ℕ, is_closed (⋃ (u ∈ U) (h : encodable.encode u ≤ n), closure (u : set α)),
{ intros s t hc hd,
rw disjoint_left at hd,
have : ∀ x ∈ s, ∃ U ∈ countable_basis α, x ∈ U ∧ disjoint (closure U) t,
{ intros x hx,
rcases (is_basis_countable_basis α).exists_closure_subset (hc.is_open_compl.mem_nhds (hd hx))
with ⟨u, hu, hxu, hut⟩,
exact ⟨u, hu, hxu, disjoint_left.2 hut⟩ },
choose! U hu hxu hd,
set V : s → countable_basis α := maps_to.restrict _ _ _ hu,
refine ⟨range V, _, forall_range_iff.2 $ subtype.forall.2 hd, λ n, _⟩,
{ rw bUnion_range,
exact λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxu x hx⟩ },
{ simp only [← supr_eq_Union, supr_and'],
exact is_closed_bUnion (((finite_le_nat n).preimage_embedding (encodable.encode' _)).subset $
inter_subset_right _ _) (λ u hu, is_closed_closure) } },
refine ⟨λ s t hs ht hd, _⟩,
rcases key ht hd with ⟨U, hsU, hUd, hUc⟩,
rcases key hs hd.symm with ⟨V, htV, hVd, hVc⟩,
refine ⟨⋃ u ∈ U, ↑u \ ⋃ (v ∈ V) (hv : encodable.encode v ≤ encodable.encode u), closure ↑v,
⋃ v ∈ V, ↑v \ ⋃ (u ∈ U) (hu : encodable.encode u ≤ encodable.encode v), closure ↑u,
is_open_bUnion $ λ u hu, (is_open_of_mem_countable_basis u.2).sdiff (hVc _),
is_open_bUnion $ λ v hv, (is_open_of_mem_countable_basis v.2).sdiff (hUc _),
λ x hx, _, λ x hx, _, _⟩,
{ rcases mem_Union₂.1 (hsU hx) with ⟨u, huU, hxu⟩,
refine mem_bUnion huU ⟨hxu, _⟩,
simp only [mem_Union],
rintro ⟨v, hvV, -, hxv⟩,
exact hVd v hvV ⟨hxv, hx⟩ },
{ rcases mem_Union₂.1 (htV hx) with ⟨v, hvV, hxv⟩,
refine mem_bUnion hvV ⟨hxv, _⟩,
simp only [mem_Union],
rintro ⟨u, huU, -, hxu⟩,
exact hUd u huU ⟨hxu, hx⟩ },
{ simp only [disjoint_left, mem_Union, mem_diff, not_exists, not_and, not_forall, not_not],
rintro a ⟨u, huU, hau, haV⟩ v hvV hav,
cases le_total (encodable.encode u) (encodable.encode v) with hle hle,
exacts [⟨u, huU, hle, subset_closure hau⟩, (haV _ hvV hle $ subset_closure hav).elim] }
end
end normality
section completely_normal
/-- A topological space `α` is a *completely normal Hausdorff space* if each subspace `s : set α` is
a normal Hausdorff space. Equivalently, `α` is a `T₁` space and for any two sets `s`, `t` such that
`closure s` is disjoint with `t` and `s` is disjoint with `closure t`, there exist disjoint
neighbourhoods of `s` and `t`. -/
class t5_space (α : Type u) [topological_space α] extends t1_space α : Prop :=
(completely_normal : ∀ ⦃s t : set α⦄, disjoint (closure s) t → disjoint s (closure t) →
disjoint (𝓝ˢ s) (𝓝ˢ t))
export t5_space (completely_normal)
lemma embedding.t5_space [topological_space β] [t5_space β] {e : α → β} (he : embedding e) :
t5_space α :=
begin
haveI := he.t1_space,
refine ⟨λ s t hd₁ hd₂, _⟩,
simp only [he.to_inducing.nhds_set_eq_comap],
refine disjoint_comap (completely_normal _ _),
{ rwa [← subset_compl_iff_disjoint_left, image_subset_iff, preimage_compl,
← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_left] },
{ rwa [← subset_compl_iff_disjoint_right, image_subset_iff, preimage_compl,
← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_right] }
end
/-- A subspace of a `T₅` space is a `T₅` space. -/
instance [t5_space α] {p : α → Prop} : t5_space {x // p x} := embedding_subtype_coe.t5_space
/-- A `T₅` space is a `T₄` space. -/
@[priority 100] -- see Note [lower instance priority]
instance t5_space.to_normal_space [t5_space α] : normal_space α :=
⟨λ s t hs ht hd, separated_iff_disjoint.2 $
completely_normal (by rwa [hs.closure_eq]) (by rwa [ht.closure_eq])⟩
end completely_normal
/-- In a compact t2 space, the connected component of a point equals the intersection of all
its clopen neighbourhoods. -/
lemma connected_component_eq_Inter_clopen [t2_space α] [compact_space α] (x : α) :
connected_component x = ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z :=
begin
apply eq_of_subset_of_subset connected_component_subset_Inter_clopen,
-- Reduce to showing that the clopen intersection is connected.
refine is_preconnected.subset_connected_component _ (mem_Inter.2 (λ Z, Z.2.2)),
-- We do this by showing that any disjoint cover by two closed sets implies
-- that one of these closed sets must contain our whole thing.
-- To reduce to the case where the cover is disjoint on all of `α` we need that `s` is closed
have hs : @is_closed α _ (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), Z) :=
is_closed_Inter (λ Z, Z.2.1.2),
rw (is_preconnected_iff_subset_of_fully_disjoint_closed hs),
intros a b ha hb hab ab_disj,
haveI := @normal_of_compact_t2 α _ _ _,
-- Since our space is normal, we get two larger disjoint open sets containing the disjoint
-- closed sets. If we can show that our intersection is a subset of any of these we can then
-- "descend" this to show that it is a subset of either a or b.
rcases normal_separation ha hb ab_disj with ⟨u, v, hu, hv, hau, hbv, huv⟩,
-- If we can find a clopen set around x, contained in u ∪ v, we get a disjoint decomposition
-- Z = Z ∩ u ∪ Z ∩ v of clopen sets. The intersection of all clopen neighbourhoods will then lie
-- in whichever of u or v x lies in and hence will be a subset of either a or b.
rsuffices ⟨Z, H⟩ : ∃ (Z : set α), is_clopen Z ∧ x ∈ Z ∧ Z ⊆ u ∪ v,
{ have H1 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hu hv huv,
rw [union_comm] at H,
have H2 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hv hu huv.symm,
by_cases (x ∈ u),
-- The x ∈ u case.
{ left,
suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ u,
{ replace hab : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ a ∪ b := hab,
replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ u := this,
exact disjoint.left_le_of_le_sup_right hab (huv.mono this hbv) },
{ apply subset.trans _ (inter_subset_right Z u),
apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z)
⟨Z ∩ u, H1, mem_inter H.2.1 h⟩ } },
-- If x ∉ u, we get x ∈ v since x ∈ u ∪ v. The rest is then like the x ∈ u case.
have h1 : x ∈ v,
{ cases (mem_union x u v).1 (mem_of_subset_of_mem (subset.trans hab
(union_subset_union hau hbv)) (mem_Inter.2 (λ i, i.2.2))) with h1 h1,
{ exfalso, exact h h1},
{ exact h1} },
right,
suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ v,
{ replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ v := this,
exact (huv.symm.mono this hau).left_le_of_le_sup_left hab },
{ apply subset.trans _ (inter_subset_right Z v),
apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z)
⟨Z ∩ v, H2, mem_inter H.2.1 h1⟩ } },
-- Now we find the required Z. We utilize the fact that X \ u ∪ v will be compact,
-- so there must be some finite intersection of clopen neighbourhoods of X disjoint to it,
-- but a finite intersection of clopen sets is clopen so we let this be our Z.
have H1 := (hu.union hv).is_closed_compl.is_compact.inter_Inter_nonempty
(λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z) (λ Z, Z.2.1.2),
rw [←not_disjoint_iff_nonempty_inter, imp_not_comm, not_forall] at H1,
cases H1 (disjoint_compl_left_iff_subset.2 $ hab.trans $ union_subset_union hau hbv) with Zi H2,
refine ⟨(⋂ (U ∈ Zi), subtype.val U), _, _, _⟩,
{ exact is_clopen_bInter_finset (λ Z hZ, Z.2.1) },
{ exact mem_Inter₂.2 (λ Z hZ, Z.2.2) },
{ rwa [←disjoint_compl_left_iff_subset, disjoint_iff_inter_eq_empty, ←not_nonempty_iff_eq_empty] }
end
section profinite
/-- A T1 space with a clopen basis is totally separated. -/
lemma totally_separated_space_of_t1_of_basis_clopen [t1_space α]
(h : is_topological_basis {s : set α | is_clopen s}) :
totally_separated_space α :=
begin
constructor,
rintros x - y - hxy,
rcases h.mem_nhds_iff.mp (is_open_ne.mem_nhds hxy) with ⟨U, hU, hxU, hyU⟩,
exact ⟨U, Uᶜ, hU.is_open, hU.compl.is_open, hxU, λ h, hyU h rfl,
(union_compl_self U).superset, disjoint_compl_right⟩
end
variables [t2_space α] [compact_space α]
/-- A compact Hausdorff space is totally disconnected if and only if it is totally separated, this
is also true for locally compact spaces. -/
theorem compact_t2_tot_disc_iff_tot_sep :
totally_disconnected_space α ↔ totally_separated_space α :=
begin
split,
{ intro h, constructor,
rintros x - y -,
contrapose!,
intros hyp,
suffices : x ∈ connected_component y,
by simpa [totally_disconnected_space_iff_connected_component_singleton.1 h y,
mem_singleton_iff],
rw [connected_component_eq_Inter_clopen, mem_Inter],
rintro ⟨w : set α, hw : is_clopen w, hy : y ∈ w⟩,
by_contra hx,
exact hyp wᶜ w hw.2.is_open_compl hw.1 hx hy (@is_compl_compl _ w _).symm.2
disjoint_compl_left },
apply totally_separated_space.totally_disconnected_space,
end
variables [totally_disconnected_space α]
lemma nhds_basis_clopen (x : α) : (𝓝 x).has_basis (λ s : set α, x ∈ s ∧ is_clopen s) id :=
⟨λ U, begin
split,
{ have : connected_component x = {x},
from totally_disconnected_space_iff_connected_component_singleton.mp ‹_› x,
rw connected_component_eq_Inter_clopen at this,
intros hU,
let N := {Z // is_clopen Z ∧ x ∈ Z},
rsuffices ⟨⟨s, hs, hs'⟩, hs''⟩ : ∃ Z : N, Z.val ⊆ U,
{ exact ⟨s, ⟨hs', hs⟩, hs''⟩ },
haveI : nonempty N := ⟨⟨univ, is_clopen_univ, mem_univ x⟩⟩,
have hNcl : ∀ Z : N, is_closed Z.val := (λ Z, Z.property.1.2),
have hdir : directed superset (λ Z : N, Z.val),
{ rintros ⟨s, hs, hxs⟩ ⟨t, ht, hxt⟩,
exact ⟨⟨s ∩ t, hs.inter ht, ⟨hxs, hxt⟩⟩, inter_subset_left s t, inter_subset_right s t⟩ },
have h_nhd: ∀ y ∈ (⋂ Z : N, Z.val), U ∈ 𝓝 y,
{ intros y y_in,
erw [this, mem_singleton_iff] at y_in,
rwa y_in },
exact exists_subset_nhd_of_compact_space hdir hNcl h_nhd },
{ rintro ⟨V, ⟨hxV, V_op, -⟩, hUV : V ⊆ U⟩,
rw mem_nhds_iff,
exact ⟨V, hUV, V_op, hxV⟩ }
end⟩
lemma is_topological_basis_clopen : is_topological_basis {s : set α | is_clopen s} :=
begin
apply is_topological_basis_of_open_of_nhds (λ U (hU : is_clopen U), hU.1),
intros x U hxU U_op,
have : U ∈ 𝓝 x,
from is_open.mem_nhds U_op hxU,
rcases (nhds_basis_clopen x).mem_iff.mp this with ⟨V, ⟨hxV, hV⟩, hVU : V ⊆ U⟩,
use V,
tauto
end
/-- Every member of an open set in a compact Hausdorff totally disconnected space
is contained in a clopen set contained in the open set. -/
lemma compact_exists_clopen_in_open {x : α} {U : set α} (is_open : is_open U) (memU : x ∈ U) :
∃ (V : set α) (hV : is_clopen V), x ∈ V ∧ V ⊆ U :=
(is_topological_basis.mem_nhds_iff is_topological_basis_clopen).1 (is_open.mem_nhds memU)
end profinite
section locally_compact
variables {H : Type*} [topological_space H] [locally_compact_space H] [t2_space H]
/-- A locally compact Hausdorff totally disconnected space has a basis with clopen elements. -/
lemma loc_compact_Haus_tot_disc_of_zero_dim [totally_disconnected_space H] :
is_topological_basis {s : set H | is_clopen s} :=
begin
refine is_topological_basis_of_open_of_nhds (λ u hu, hu.1) _,
rintros x U memU hU,
obtain ⟨s, comp, xs, sU⟩ := exists_compact_subset hU memU,
obtain ⟨t, h, ht, xt⟩ := mem_interior.1 xs,
let u : set s := (coe : s → H)⁻¹' (interior s),
have u_open_in_s : is_open u := is_open_interior.preimage continuous_subtype_coe,
let X : s := ⟨x, h xt⟩,
have Xu : X ∈ u := xs,
haveI : compact_space s := is_compact_iff_compact_space.1 comp,
obtain ⟨V : set s, clopen_in_s, Vx, V_sub⟩ := compact_exists_clopen_in_open u_open_in_s Xu,
have V_clopen : is_clopen ((coe : s → H) '' V),
{ refine ⟨_, (comp.is_closed.closed_embedding_subtype_coe.closed_iff_image_closed).1
clopen_in_s.2⟩,
let v : set u := (coe : u → s)⁻¹' V,
have : (coe : u → H) = (coe : s → H) ∘ (coe : u → s) := rfl,
have f0 : embedding (coe : u → H) := embedding_subtype_coe.comp embedding_subtype_coe,
have f1 : open_embedding (coe : u → H),
{ refine ⟨f0, _⟩,
{ have : set.range (coe : u → H) = interior s,
{ rw [this, set.range_comp, subtype.range_coe, subtype.image_preimage_coe],
apply set.inter_eq_self_of_subset_left interior_subset, },
rw this,
apply is_open_interior } },
have f2 : is_open v := clopen_in_s.1.preimage continuous_subtype_coe,
have f3 : (coe : s → H) '' V = (coe : u → H) '' v,
{ rw [this, image_comp coe coe, subtype.image_preimage_coe,
inter_eq_self_of_subset_left V_sub] },
rw f3,
apply f1.is_open_map v f2 },
refine ⟨coe '' V, V_clopen, by simp [Vx, h xt], _⟩,
transitivity s,
{ simp },
assumption
end
/-- A locally compact Hausdorff space is totally disconnected
if and only if it is totally separated. -/
theorem loc_compact_t2_tot_disc_iff_tot_sep :
totally_disconnected_space H ↔ totally_separated_space H :=
begin
split,
{ introI h,
exact totally_separated_space_of_t1_of_basis_clopen loc_compact_Haus_tot_disc_of_zero_dim },
apply totally_separated_space.totally_disconnected_space,
end
end locally_compact
/-- `connected_components α` is Hausdorff when `α` is Hausdorff and compact -/
instance connected_components.t2 [t2_space α] [compact_space α] :
t2_space (connected_components α) :=
begin
-- Proof follows that of: https://stacks.math.columbia.edu/tag/0900
-- Fix 2 distinct connected components, with points a and b
refine ⟨connected_components.surjective_coe.forall₂.2 $ λ a b ne, _⟩,
rw connected_components.coe_ne_coe at ne,
have h := connected_component_disjoint ne,
-- write ↑b as the intersection of all clopen subsets containing it
rw [connected_component_eq_Inter_clopen b, disjoint_iff_inter_eq_empty] at h,
-- Now we show that this can be reduced to some clopen containing `↑b` being disjoint to `↑a`
obtain ⟨U, V, hU, ha, hb, rfl⟩ : ∃ (U : set α) (V : set (connected_components α)), is_clopen U ∧
connected_component a ∩ U = ∅ ∧ connected_component b ⊆ U ∧ coe ⁻¹' V = U,
{ cases is_closed_connected_component.is_compact.elim_finite_subfamily_closed _ _ h with fin_a ha,
swap, { exact λ Z, Z.2.1.2 },
-- This clopen and its complement will separate the connected components of `a` and `b`
set U : set α := (⋂ (i : {Z // is_clopen Z ∧ b ∈ Z}) (H : i ∈ fin_a), i),
have hU : is_clopen U := is_clopen_bInter_finset (λ i j, i.2.1),
exact ⟨U, coe '' U, hU, ha, subset_Inter₂ (λ Z _, Z.2.1.connected_component_subset Z.2.2),
(connected_components_preimage_image U).symm ▸ hU.bUnion_connected_component_eq⟩ },
rw connected_components.quotient_map_coe.is_clopen_preimage at hU,
refine ⟨Vᶜ, V, hU.compl.is_open, hU.is_open, _, hb mem_connected_component, disjoint_compl_left⟩,
exact λ h, flip set.nonempty.ne_empty ha ⟨a, mem_connected_component, h⟩,
end
|
71e40804e87545d1fdcf04457084783e46f914fa | 37da0369b6c03e380e057bf680d81e6c9fdf9219 | /hott/types/nat/hott.hlean | 4cc9ac044e74164d644c7c94a69a3b298d572664 | [
"Apache-2.0"
] | permissive | kodyvajjha/lean2 | 72b120d95c3a1d77f54433fa90c9810e14a931a4 | 227fcad22ab2bc27bb7471be7911075d101ba3f9 | refs/heads/master | 1,627,157,512,295 | 1,501,855,676,000 | 1,504,809,427,000 | 109,317,326 | 0 | 0 | null | 1,509,839,253,000 | 1,509,655,713,000 | C++ | UTF-8 | Lean | false | false | 9,679 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about the natural numbers specific to HoTT
-/
import .order types.pointed .sub
open is_trunc unit empty eq equiv algebra pointed is_equiv equiv function
namespace nat
definition is_prop_le [instance] (n m : ℕ) : is_prop (n ≤ m) :=
begin
have lem : Π{n m : ℕ} (p : n ≤ m) (q : n = m), p = q ▸ le.refl n,
begin
intros, cases p,
{ have H' : q = idp, by apply is_set.elim,
cases H', reflexivity},
{ cases q, exfalso, apply not_succ_le_self a}
end,
apply is_prop.mk, intro H1 H2, induction H2,
{ apply lem},
{ cases H1,
{ exfalso, apply not_succ_le_self a},
{ exact ap le.step !v_0}},
end
definition is_prop_lt [instance] (n m : ℕ) : is_prop (n < m) := !is_prop_le
definition le_equiv_succ_le_succ (n m : ℕ) : (n ≤ m) ≃ (succ n ≤ succ m) :=
equiv_of_is_prop succ_le_succ le_of_succ_le_succ
definition le_succ_equiv_pred_le (n m : ℕ) : (n ≤ succ m) ≃ (pred n ≤ m) :=
equiv_of_is_prop pred_le_pred le_succ_of_pred_le
theorem lt_by_cases_lt {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P)
(H3 : a > b → P) (H : a < b) : lt.by_cases H1 H2 H3 = H1 H :=
begin
unfold lt.by_cases, induction (lt.trichotomy a b) with H' H',
{ esimp, exact ap H1 !is_prop.elim},
{ exfalso, cases H' with H' H', apply lt.irrefl, exact H' ▸ H, exact lt.asymm H H'}
end
theorem lt_by_cases_eq {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P)
(H3 : a > b → P) (H : a = b) : lt.by_cases H1 H2 H3 = H2 H :=
begin
unfold lt.by_cases, induction (lt.trichotomy a b) with H' H',
{ exfalso, apply lt.irrefl, exact H ▸ H'},
{ cases H' with H' H', esimp, exact ap H2 !is_prop.elim, exfalso, apply lt.irrefl, exact H ▸ H'}
end
theorem lt_by_cases_ge {a b : ℕ} {P : Type} (H1 : a < b → P) (H2 : a = b → P)
(H3 : a > b → P) (H : a > b) : lt.by_cases H1 H2 H3 = H3 H :=
begin
unfold lt.by_cases, induction (lt.trichotomy a b) with H' H',
{ exfalso, exact lt.asymm H H'},
{ cases H' with H' H', exfalso, apply lt.irrefl, exact H' ▸ H, esimp, exact ap H3 !is_prop.elim}
end
theorem lt_ge_by_cases_lt {n m : ℕ} {P : Type} (H1 : n < m → P) (H2 : n ≥ m → P)
(H : n < m) : lt_ge_by_cases H1 H2 = H1 H :=
by apply lt_by_cases_lt
theorem lt_ge_by_cases_ge {n m : ℕ} {P : Type} (H1 : n < m → P) (H2 : n ≥ m → P)
(H : n ≥ m) : lt_ge_by_cases H1 H2 = H2 H :=
begin
unfold [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H',
{ exfalso, apply lt.irrefl, exact lt_of_le_of_lt H H'},
{ cases H' with H' H'; all_goals (esimp; apply ap H2 !is_prop.elim)}
end
theorem lt_ge_by_cases_le {n m : ℕ} {P : Type} {H1 : n ≤ m → P} {H2 : n ≥ m → P}
(H : n ≤ m) (Heq : Π(p : n = m), H1 (le_of_eq p) = H2 (le_of_eq p⁻¹))
: lt_ge_by_cases (λH', H1 (le_of_lt H')) H2 = H1 H :=
begin
unfold [lt_ge_by_cases,lt.by_cases], induction (lt.trichotomy n m) with H' H',
{ esimp, apply ap H1 !is_prop.elim},
{ cases H' with H' H',
{ esimp, induction H', esimp, symmetry,
exact ap H1 !is_prop.elim ⬝ Heq idp ⬝ ap H2 !is_prop.elim},
{ exfalso, apply lt.irrefl, apply lt_of_le_of_lt H H'}}
end
protected definition code [reducible] [unfold 1 2] : ℕ → ℕ → Type₀
| code 0 0 := unit
| code 0 (succ m) := empty
| code (succ n) 0 := empty
| code (succ n) (succ m) := code n m
protected definition refl : Πn, nat.code n n
| refl 0 := star
| refl (succ n) := refl n
protected definition encode [unfold 3] {n m : ℕ} (p : n = m) : nat.code n m :=
p ▸ nat.refl n
protected definition decode : Π(n m : ℕ), nat.code n m → n = m
| decode 0 0 := λc, idp
| decode 0 (succ l) := λc, empty.elim c _
| decode (succ k) 0 := λc, empty.elim c _
| decode (succ k) (succ l) := λc, ap succ (decode k l c)
definition nat_eq_equiv (n m : ℕ) : (n = m) ≃ nat.code n m :=
equiv.MK nat.encode
!nat.decode
begin
revert m, induction n, all_goals (intro m;induction m;all_goals intro c),
all_goals try contradiction,
induction c, reflexivity,
xrewrite [↑nat.decode,-tr_compose,v_0],
end
begin
intro p, induction p, esimp, induction n,
reflexivity,
rewrite [↑nat.decode,↑nat.refl,v_0]
end
definition pointed_nat [instance] [constructor] : pointed ℕ :=
pointed.mk 0
open sigma sum
definition eq_even_or_eq_odd (n : ℕ) : (Σk, 2 * k = n) ⊎ (Σk, 2 * k + 1 = n) :=
begin
induction n with n IH,
{ exact inl ⟨0, idp⟩},
{ induction IH with H H: induction H with k p: induction p,
{ exact inr ⟨k, idp⟩},
{ refine inl ⟨k+1, idp⟩}}
end
definition rec_on_even_odd {P : ℕ → Type} (n : ℕ) (H : Πk, P (2 * k)) (H2 : Πk, P (2 * k + 1))
: P n :=
begin
cases eq_even_or_eq_odd n with v v: induction v with k p: induction p,
{ exact H k},
{ exact H2 k}
end
/- this inequality comes up a couple of times when using the freudenthal suspension theorem -/
definition add_mul_le_mul_add (n m k : ℕ) : n + (succ m) * k ≤ (succ m) * (n + k) :=
calc
n + (succ m) * k ≤ (m * n + n) + (succ m) * k : add_le_add_right !le_add_left _
... = (succ m) * n + (succ m) * k : by rewrite -succ_mul
... = (succ m) * (n + k) : !left_distrib⁻¹
/-
Some operations work only for successors. For example fin (succ n) has a 0 and a 1, but fin 0
doesn't. However, we want a bit more, because sometimes we want a zero of (fin a)
where a is either
- equal to a successor, but not definitionally a successor (e.g. (0 : fin (3 + n)))
- definitionally equal to a successor, but not in a way that type class inference can infer.
(e.g. (0 : fin 4). Note that 4 is bit0 (bit0 one), but (bit0 x) (defined as x + x),
is not always a successor)
To solve this we use an auxillary class `is_succ` which can solve whether a number is a
successor.
-/
inductive is_succ [class] : ℕ → Type :=
| mk : Π(n : ℕ), is_succ (succ n)
attribute is_succ.mk [instance]
definition is_succ_1 [instance] : is_succ 1 := is_succ.mk 0
definition is_succ_add_right [instance] [constructor] (n m : ℕ) [H : is_succ m] : is_succ (n+m) :=
by induction H with m; constructor
definition is_succ_add_left [instance] [priority 900] [constructor] (n m : ℕ) [H : is_succ n] :
is_succ (n+m) :=
by induction H with n; cases m with m: constructor
definition is_succ_bit0 [constructor] (n : ℕ) [H : is_succ n] : is_succ (bit0 n) :=
by exact _
-- level 2 is useful for abelian homotopy groups, which only exist at level 2 and higher
inductive is_at_least_two [class] : ℕ → Type :=
| mk : Π(n : ℕ), is_at_least_two (succ (succ n))
attribute is_at_least_two.mk [instance]
definition is_at_least_two_add_right [instance] [constructor] (n m : ℕ) [H : is_at_least_two m] :
is_at_least_two (n+m) :=
by induction H with m; constructor
definition is_at_least_two_add_left [instance] [constructor] (n m : ℕ) [H : is_at_least_two n] :
is_at_least_two (n+m) :=
by induction H with n; cases m with m: try cases m with m: constructor
definition is_at_least_two_add_both [instance] [priority 900] [constructor] (n m : ℕ)
[H : is_succ n] [K : is_succ m] : is_at_least_two (n+m) :=
by induction H with n; induction K with m; cases m with m: constructor
definition is_at_least_two_bit0 [constructor] (n : ℕ) [H : is_succ n] : is_at_least_two (bit0 n) :=
by exact _
definition is_at_least_two_bit1 [constructor] (n : ℕ) [H : is_succ n] : is_at_least_two (bit1 n) :=
by exact _
/- some facts about iterate -/
definition iterate_succ {A : Type} (f : A → A) (n : ℕ) (x : A) :
f^[succ n] x = f^[n] (f x) :=
by induction n with n p; reflexivity; exact ap f p
lemma iterate_sub {A : Type} (f : A ≃ A) {n m : ℕ} (h : n ≥ m) (a : A) :
iterate f (n - m) a = iterate f n (iterate f⁻¹ m a) :=
begin
revert n h, induction m with m p: intro n h,
{ reflexivity },
{ cases n with n, exfalso, apply not_succ_le_zero _ h,
rewrite [succ_sub_succ], refine p n (le_of_succ_le_succ h) ⬝ _,
refine ap (f^[n]) _ ⬝ !iterate_succ⁻¹, exact !to_right_inv⁻¹ }
end
definition iterate_commute {A : Type} {f g : A → A} (n : ℕ) (h : f ∘ g ~ g ∘ f) :
iterate f n ∘ g ~ g ∘ iterate f n :=
by induction n with n IH; reflexivity; exact λx, ap f (IH x) ⬝ !h
definition iterate_equiv {A : Type} (f : A ≃ A) (n : ℕ) : A ≃ A :=
equiv.mk (iterate f n)
(by induction n with n IH; apply is_equiv_id; exact is_equiv_compose f (iterate f n))
definition iterate_inv {A : Type} (f : A ≃ A) (n : ℕ) :
(iterate_equiv f n)⁻¹ ~ iterate f⁻¹ n :=
begin
induction n with n p: intro a,
reflexivity,
exact p (f⁻¹ a) ⬝ !iterate_succ⁻¹
end
definition iterate_left_inv {A : Type} (f : A ≃ A) (n : ℕ) (a : A) : f⁻¹ᵉ^[n] (f^[n] a) = a :=
(iterate_inv f n (f^[n] a))⁻¹ ⬝ to_left_inv (iterate_equiv f n) a
definition iterate_right_inv {A : Type} (f : A ≃ A) (n : ℕ) (a : A) : f^[n] (f⁻¹ᵉ^[n] a) = a :=
ap (f^[n]) (iterate_inv f n a)⁻¹ ⬝ to_right_inv (iterate_equiv f n) a
end nat
|
84095702f643cc15e752233d970923f4fbdbeeca | 6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b | /stage0/src/Lean/Elab/StructInst.lean | 8d0c6c16ed28c3ac2e04e71820ce87ac3645fcf8 | [
"Apache-2.0"
] | permissive | pbrinkmeier/lean4 | d31991fd64095e64490cb7157bcc6803f9c48af4 | 32fd82efc2eaf1232299e930ec16624b370eac39 | refs/heads/master | 1,681,364,001,662 | 1,618,425,427,000 | 1,618,425,427,000 | 358,314,562 | 0 | 0 | Apache-2.0 | 1,618,504,558,000 | 1,618,501,999,000 | null | UTF-8 | Lean | false | false | 34,259 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.FindExpr
import Lean.Parser.Term
import Lean.Elab.App
import Lean.Elab.Binders
namespace Lean.Elab.Term.StructInst
open Std (HashMap)
open Meta
/-
Structure instances are of the form:
"{" >> optional (atomic (termParser >> " with "))
>> manyIndent (group (structInstField >> optional ", "))
>> optEllipsis
>> optional (" : " >> termParser)
>> " }"
-/
@[builtinMacro Lean.Parser.Term.structInst] def expandStructInstExpectedType : Macro := fun stx =>
let expectedArg := stx[4]
if expectedArg.isNone then
Macro.throwUnsupported
else
let expected := expectedArg[1]
let stxNew := stx.setArg 4 mkNullNode
`(($stxNew : $expected))
/-
If `stx` is of the form `{ s with ... }` and `s` is not a local variable, expand into `let src := s; { src with ... }`.
Note that this one is not a `Macro` because we need to access the local context.
-/
private def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) :=
withFreshMacroScope do
let sourceOpt := stx[1]
if sourceOpt.isNone then
pure none
else
let source := sourceOpt[0]
match (← isLocalIdent? source) with
| some _ => pure none
| none =>
let src ← `(src)
let sourceOpt := sourceOpt.setArg 0 src
let stxNew := stx.setArg 1 sourceOpt
`(let src := $source; $stxNew)
inductive Source where
| none -- structure instance source has not been provieded
| implicit (stx : Syntax) -- `..`
| explicit (stx : Syntax) (src : Expr) -- `src with`
deriving Inhabited
def Source.isNone : Source → Bool
| Source.none => true
| _ => false
def setStructSourceSyntax (structStx : Syntax) : Source → Syntax
| Source.none => (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode
| Source.implicit stx => (structStx.setArg 1 mkNullNode).setArg 3 stx
| Source.explicit stx _ => (structStx.setArg 1 stx).setArg 3 mkNullNode
private def getStructSource (stx : Syntax) : TermElabM Source :=
withRef stx do
let explicitSource := stx[1]
let implicitSource := stx[3]
if explicitSource.isNone && implicitSource[0].isNone then
return Source.none
else if explicitSource.isNone then
return Source.implicit implicitSource
else if implicitSource[0].isNone then
let fvar? ← isLocalIdent? explicitSource[0]
match fvar? with
| none => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here
| some src => return Source.explicit explicitSource src
else
throwError "invalid structure instance `with` and `..` cannot be used together"
/-
We say a `{ ... }` notation is a `modifyOp` if it contains only one
```
def structInstArrayRef := leading_parser "[" >> termParser >>"]"
```
-/
private def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do
let s? ← stx[2].getArgs.foldlM (init := none) fun s? p =>
/- p is of the form `(group (structInstField >> optional ", "))` -/
let arg := p[0]
/- Remark: the syntax for `structInstField` is
```
def structInstLVal := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (group ("." >> (ident <|> numLit)) <|> structInstArrayRef)
def structInstField := leading_parser structInstLVal >> " := " >> termParser
```
-/
let lval := arg[0]
let k := lval[0].getKind
if k == `Lean.Parser.Term.structInstArrayRef then
match s? with
| none => pure (some arg)
| some s =>
if s.getKind == `Lean.Parser.Term.structInstArrayRef then
throwErrorAt arg "invalid \{...} notation, at most one `[..]` at a given level"
else
throwErrorAt arg "invalid \{...} notation, can't mix field and `[..]` at a given level"
else
match s? with
| none => pure (some arg)
| some s =>
if s.getKind == `Lean.Parser.Term.structInstArrayRef then
throwErrorAt arg "invalid \{...} notation, can't mix field and `[..]` at a given level"
else
pure s?
match s? with
| none => pure none
| some s => if s[0][0].getKind == `Lean.Parser.Term.structInstArrayRef then pure s? else pure none
private def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
let cont (val : Syntax) : TermElabM Expr := do
let lval := modifyOp[0][0]
let idx := lval[1]
let self := source[0]
let stxNew ← `($(self).modifyOp (idx := $idx) (fun s => $val))
trace[Elab.struct.modifyOp] "{stx}\n===>\n{stxNew}"
withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
trace[Elab.struct.modifyOp] "{modifyOp}\nSource: {source}"
let rest := modifyOp[0][1]
if rest.isNone then
cont modifyOp[2]
else
let s ← `(s)
let valFirst := rest[0]
let valFirst := if valFirst.getKind == `Lean.Parser.Term.structInstArrayRef then valFirst else valFirst[1]
let restArgs := rest.getArgs
let valRest := mkNullNode restArgs[1:restArgs.size]
let valField := modifyOp.setArg 0 <| Syntax.node ``Parser.Term.structInstLVal #[valFirst, valRest]
let valSource := source.modifyArg 0 fun _ => s
let val := stx.setArg 1 valSource
let val := val.setArg 2 <| mkNullNode #[mkNullNode #[valField, mkNullNode]]
trace[Elab.struct.modifyOp] "{stx}\nval: {val}"
cont val
/- Get structure name and elaborate explicit source (if available) -/
private def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM (Name × Expr) := do
tryPostponeIfNoneOrMVar expectedType?
let useSource : Unit → TermElabM (Name × Expr) := fun _ =>
match sourceView, expectedType? with
| Source.explicit _ src, _ => do
let srcType ← inferType src
let srcType ← whnf srcType
tryPostponeIfMVar srcType
match srcType.getAppFn with
| Expr.const constName _ _ => return (constName, srcType)
| _ => throwUnexpectedExpectedType srcType "source"
| _, some expectedType => throwUnexpectedExpectedType expectedType
| _, none => throwUnknownExpectedType
match expectedType? with
| none => useSource ()
| some expectedType =>
let expectedType ← whnf expectedType
match expectedType.getAppFn with
| Expr.const constName _ _ => return (constName, expectedType)
| _ => useSource ()
where
throwUnknownExpectedType :=
throwError "invalid \{...} notation, expected type is not known"
throwUnexpectedExpectedType type (kind := "expected") := do
let type ← instantiateMVars type
if type.getAppFn.isMVar then
throwUnknownExpectedType
else
throwError "invalid \{...} notation, {kind} type is not of the form (C ...){indentExpr type}"
inductive FieldLHS where
| fieldName (ref : Syntax) (name : Name)
| fieldIndex (ref : Syntax) (idx : Nat)
| modifyOp (ref : Syntax) (index : Syntax)
deriving Inhabited
instance : ToFormat FieldLHS := ⟨fun lhs =>
match lhs with
| FieldLHS.fieldName _ n => fmt n
| FieldLHS.fieldIndex _ i => fmt i
| FieldLHS.modifyOp _ i => "[" ++ i.prettyPrint ++ "]"⟩
inductive FieldVal (σ : Type) where
| term (stx : Syntax) : FieldVal σ
| nested (s : σ) : FieldVal σ
| default : FieldVal σ -- mark that field must be synthesized using default value
deriving Inhabited
structure Field (σ : Type) where
ref : Syntax
lhs : List FieldLHS
val : FieldVal σ
expr? : Option Expr := none
deriving Inhabited
def Field.isSimple {σ} : Field σ → Bool
| { lhs := [_], .. } => true
| _ => false
inductive Struct where
| mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source)
deriving Inhabited
abbrev Fields := List (Field Struct)
/- true if all fields of the given structure are marked as `default` -/
partial def Struct.allDefault : Struct → Bool
| ⟨_, _, fields, _⟩ => fields.all fun ⟨_, _, val, _⟩ => match val with
| FieldVal.term _ => false
| FieldVal.default => true
| FieldVal.nested s => allDefault s
def Struct.ref : Struct → Syntax
| ⟨ref, _, _, _⟩ => ref
def Struct.structName : Struct → Name
| ⟨_, structName, _, _⟩ => structName
def Struct.fields : Struct → Fields
| ⟨_, _, fields, _⟩ => fields
def Struct.source : Struct → Source
| ⟨_, _, _, s⟩ => s
def formatField (formatStruct : Struct → Format) (field : Field Struct) : Format :=
Format.joinSep field.lhs " . " ++ " := " ++
match field.val with
| FieldVal.term v => v.prettyPrint
| FieldVal.nested s => formatStruct s
| FieldVal.default => "<default>"
partial def formatStruct : Struct → Format
| ⟨_, structName, fields, source⟩ =>
let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) ", "
match source with
| Source.none => "{" ++ fieldsFmt ++ "}"
| Source.implicit _ => "{" ++ fieldsFmt ++ " .. }"
| Source.explicit _ src => "{" ++ format src ++ " with " ++ fieldsFmt ++ "}"
instance : ToFormat Struct := ⟨formatStruct⟩
instance : ToString Struct := ⟨toString ∘ format⟩
instance : ToFormat (Field Struct) := ⟨formatField formatStruct⟩
instance : ToString (Field Struct) := ⟨toString ∘ format⟩
/-
Recall that `structInstField` elements have the form
```
def structInstField := leading_parser structInstLVal >> " := " >> termParser
def structInstLVal := leading_parser (ident <|> numLit <|> structInstArrayRef) >> many (("." >> (ident <|> numLit)) <|> structInstArrayRef)
def structInstArrayRef := leading_parser "[" >> termParser >>"]"
```
-/
-- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName`
def FieldLHS.toSyntax (first : Bool) : FieldLHS → Syntax
| FieldLHS.modifyOp stx _ => stx
| FieldLHS.fieldName stx name => if first then mkIdentFrom stx name else mkGroupNode #[mkAtomFrom stx ".", mkIdentFrom stx name]
| FieldLHS.fieldIndex stx _ => if first then stx else mkGroupNode #[mkAtomFrom stx ".", stx]
def FieldVal.toSyntax : FieldVal Struct → Syntax
| FieldVal.term stx => stx
| _ => unreachable!
def Field.toSyntax : Field Struct → Syntax
| field =>
let stx := field.ref
let stx := stx.setArg 2 field.val.toSyntax
match field.lhs with
| first::rest => stx.setArg 0 <| mkNullNode #[first.toSyntax true, mkNullNode <| rest.toArray.map (FieldLHS.toSyntax false) ]
| _ => unreachable!
private def toFieldLHS (stx : Syntax) : Except String FieldLHS :=
if stx.getKind == `Lean.Parser.Term.structInstArrayRef then
return FieldLHS.modifyOp stx stx[1]
else
-- Note that the representation of the first field is different.
let stx := if stx.getKind == groupKind then stx[1] else stx
if stx.isIdent then
return FieldLHS.fieldName stx stx.getId.eraseMacroScopes
else match stx.isFieldIdx? with
| some idx => return FieldLHS.fieldIndex stx idx
| none => throw "unexpected structure syntax"
private def mkStructView (stx : Syntax) (structName : Name) (source : Source) : Except String Struct := do
/- Recall that `stx` is of the form
```
leading_parser "{" >> optional (atomic (termParser >> " with "))
>> manyIndent (group (structInstField >> optional ", "))
>> optional ".."
>> optional (" : " >> termParser)
>> " }"
```
-/
let fieldsStx := stx[2].getArgs.map (·[0])
let fields ← fieldsStx.toList.mapM fun fieldStx => do
let val := fieldStx[2]
let first ← toFieldLHS fieldStx[0][0]
let rest ← fieldStx[0][1].getArgs.toList.mapM toFieldLHS
pure { ref := fieldStx, lhs := first :: rest, val := FieldVal.term val : Field Struct }
pure ⟨stx, structName, fields, source⟩
def Struct.modifyFieldsM {m : Type → Type} [Monad m] (s : Struct) (f : Fields → m Fields) : m Struct :=
match s with
| ⟨ref, structName, fields, source⟩ => return ⟨ref, structName, (← f fields), source⟩
@[inline] def Struct.modifyFields (s : Struct) (f : Fields → Fields) : Struct :=
Id.run <| s.modifyFieldsM f
def Struct.setFields (s : Struct) (fields : Fields) : Struct :=
s.modifyFields fun _ => fields
private def expandCompositeFields (s : Struct) : Struct :=
s.modifyFields fun fields => fields.map fun field => match field with
| { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field
| { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } =>
let newEntries := n.components.map <| FieldLHS.fieldName ref
{ field with lhs := newEntries ++ rest }
| _ => field
private def expandNumLitFields (s : Struct) : TermElabM Struct :=
s.modifyFieldsM fun fields => do
let env ← getEnv
let fieldNames := getStructureFields env s.structName
fields.mapM fun field => match field with
| { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } =>
if idx == 0 then throwErrorAt ref "invalid field index, index must be greater than 0"
else if idx > fieldNames.size then throwErrorAt ref "invalid field index, structure has only #{fieldNames.size} fields"
else pure { field with lhs := FieldLHS.fieldName ref fieldNames[idx - 1] :: rest }
| _ => pure field
/- For example, consider the following structures:
```
structure A where
x : Nat
structure B extends A where
y : Nat
structure C extends B where
z : Bool
```
This method expands parent structure fields using the path to the parent structure.
For example,
```
{ x := 0, y := 0, z := true : C }
```
is expanded into
```
{ toB.toA.x := 0, toB.y := 0, z := true : C }
```
-/
private def expandParentFields (s : Struct) : TermElabM Struct := do
let env ← getEnv
s.modifyFieldsM fun fields => fields.mapM fun field => match field with
| { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } =>
match findField? env s.structName fieldName with
| none => throwErrorAt ref "'{fieldName}' is not a field of structure '{s.structName}'"
| some baseStructName =>
if baseStructName == s.structName then pure field
else match getPathToBaseStructure? env baseStructName s.structName with
| some path => do
let path := path.map fun funName => match funName with
| Name.str _ s _ => FieldLHS.fieldName ref (Name.mkSimple s)
| _ => unreachable!
pure { field with lhs := path ++ field.lhs }
| _ => throwErrorAt ref "failed to access field '{fieldName}' in parent structure"
| _ => pure field
private abbrev FieldMap := HashMap Name Fields
private def mkFieldMap (fields : Fields) : TermElabM FieldMap :=
fields.foldlM (init := {}) fun fieldMap field =>
match field.lhs with
| FieldLHS.fieldName _ fieldName :: rest =>
match fieldMap.find? fieldName with
| some (prevField::restFields) =>
if field.isSimple || prevField.isSimple then
throwErrorAt field.ref "field '{fieldName}' has already beed specified"
else
return fieldMap.insert fieldName (field::prevField::restFields)
| _ => return fieldMap.insert fieldName [field]
| _ => unreachable!
private def isSimpleField? : Fields → Option (Field Struct)
| [field] => if field.isSimple then some field else none
| _ => none
private def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do
match fieldNames.findIdx? fun n => n == fieldName with
| some idx => pure idx
| none => throwError "field '{fieldName}' is not a valid field of '{structName}'"
private def mkProjStx (s : Syntax) (fieldName : Name) : Syntax :=
Syntax.node `Lean.Parser.Term.proj #[s, mkAtomFrom s ".", mkIdentFrom s fieldName]
private def mkSubstructSource (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source :=
match src with
| Source.explicit stx src => do
let idx ← getFieldIdx structName fieldNames fieldName
let stx := stx.modifyArg 0 fun stx => mkProjStx stx fieldName
return Source.explicit stx (mkProj structName idx src)
| s => return s
@[specialize] private def groupFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do
let env ← getEnv
let fieldNames := getStructureFields env s.structName
withRef s.ref do
s.modifyFieldsM fun fields => do
let fieldMap ← mkFieldMap fields
fieldMap.toList.mapM fun ⟨fieldName, fields⟩ => do
match isSimpleField? fields with
| some field => pure field
| none =>
let substructFields := fields.map fun field => { field with lhs := field.lhs.tail! }
let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source
let field := fields.head!
match Lean.isSubobjectField? env s.structName fieldName with
| some substructName =>
let substruct := Struct.mk s.ref substructName substructFields substructSource
let substruct ← expandStruct substruct
pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct }
| none => do
-- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them.
let valStx := s.ref -- construct substructure syntax using s.ref as template
let valStx := valStx.setArg 4 mkNullNode -- erase optional expected type
let args := substructFields.toArray.map fun field => mkNullNode #[field.toSyntax, mkNullNode]
let valStx := valStx.setArg 2 (mkNullNode args)
let valStx := setStructSourceSyntax valStx substructSource
pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx }
def findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) :=
fields.find? fun field =>
match field.lhs with
| [FieldLHS.fieldName _ n] => n == fieldName
| _ => false
@[specialize] private def addMissingFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do
let env ← getEnv
let fieldNames := getStructureFields env s.structName
let ref := s.ref
withRef ref do
let fields ← fieldNames.foldlM (init := []) fun fields fieldName => do
match findField? s.fields fieldName with
| some field => return field::fields
| none =>
let addField (val : FieldVal Struct) : TermElabM Fields := do
return { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields
match Lean.isSubobjectField? env s.structName fieldName with
| some substructName => do
let substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source
let substruct := Struct.mk s.ref substructName [] substructSource
let substruct ← expandStruct substruct
addField (FieldVal.nested substruct)
| none =>
match s.source with
| Source.none => addField FieldVal.default
| Source.implicit _ => addField (FieldVal.term (mkHole s.ref))
| Source.explicit stx _ =>
-- stx is of the form `optional (try (termParser >> "with"))`
let src := stx[0]
let val := mkProjStx src fieldName
addField (FieldVal.term val)
return s.setFields fields.reverse
private partial def expandStruct (s : Struct) : TermElabM Struct := do
let s := expandCompositeFields s
let s ← expandNumLitFields s
let s ← expandParentFields s
let s ← groupFields expandStruct s
addMissingFields expandStruct s
structure CtorHeaderResult where
ctorFn : Expr
ctorFnType : Expr
instMVars : Array MVarId := #[]
private def mkCtorHeaderAux : Nat → Expr → Expr → Array MVarId → TermElabM CtorHeaderResult
| 0, type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars }
| n+1, type, ctorFn, instMVars => do
let type ← whnfForall type
match type with
| Expr.forallE _ d b c =>
match c.binderInfo with
| BinderInfo.instImplicit =>
let a ← mkFreshExprMVar d MetavarKind.synthetic
mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!)
| _ =>
let a ← mkFreshExprMVar d
mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars
| _ => throwError "unexpected constructor type"
private partial def getForallBody : Nat → Expr → Option Expr
| i+1, Expr.forallE _ _ b _ => getForallBody i b
| i+1, _ => none
| 0, type => type
private def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit :=
match expectedType? with
| none => pure ()
| some expectedType => do
match getForallBody numFields type with
| none => pure ()
| some typeBody =>
unless typeBody.hasLooseBVars do
discard <| isDefEq expectedType typeBody
private def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do
let us ← mkFreshLevelMVars ctorVal.levelParams.length
let val := Lean.mkConst ctorVal.name us
let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams us
let r ← mkCtorHeaderAux ctorVal.numParams type val #[]
propagateExpectedType r.ctorFnType ctorVal.numFields expectedType?
synthesizeAppInstMVars r.instMVars
pure r
def markDefaultMissing (e : Expr) : Expr :=
mkAnnotation `structInstDefault e
def defaultMissing? (e : Expr) : Option Expr :=
annotation? `structInstDefault e
def throwFailedToElabField {α} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM α :=
throwError "failed to elaborate field '{fieldName}' of '{structName}, {msgData}"
def trySynthStructInstance? (s : Struct) (expectedType : Expr) : TermElabM (Option Expr) := do
if !s.allDefault then
pure none
else
try synthInstance? expectedType catch _ => pure none
private partial def elabStruct (s : Struct) (expectedType? : Option Expr) : TermElabM (Expr × Struct) := withRef s.ref do
let env ← getEnv
let ctorVal := getStructureCtor env s.structName
let { ctorFn := ctorFn, ctorFnType := ctorFnType, .. } ← mkCtorHeader ctorVal expectedType?
let (e, _, fields) ← s.fields.foldlM (init := (ctorFn, ctorFnType, [])) fun (e, type, fields) field =>
match field.lhs with
| [FieldLHS.fieldName ref fieldName] => do
let type ← whnfForall type
match type with
| Expr.forallE _ d b c =>
let cont (val : Expr) (field : Field Struct) : TermElabM (Expr × Expr × Fields) := do
pushInfoTree <| InfoTree.node (children := {}) <| Info.ofFieldInfo { lctx := (← getLCtx), val := val, name := fieldName, stx := ref }
let e := mkApp e val
let type := b.instantiate1 val
let field := { field with expr? := some val }
pure (e, type, field::fields)
match field.val with
| FieldVal.term stx => cont (← elabTermEnsuringType stx d) field
| FieldVal.nested s => do
-- if all fields of `s` are marked as `default`, then try to synthesize instance
match (← trySynthStructInstance? s d) with
| some val => cont val { field with val := FieldVal.term (mkHole field.ref) }
| none => do let (val, sNew) ← elabStruct s (some d); let val ← ensureHasType d val; cont val { field with val := FieldVal.nested sNew }
| FieldVal.default => do let val ← withRef field.ref <| mkFreshExprMVar (some d); cont (markDefaultMissing val) field
| _ => withRef field.ref <| throwFailedToElabField fieldName s.structName m!"unexpected constructor type{indentExpr type}"
| _ => throwErrorAt field.ref "unexpected unexpanded structure field"
pure (e, s.setFields fields.reverse)
namespace DefaultFields
structure Context where
-- We must search for default values overriden in derived structures
structs : Array Struct := #[]
allStructNames : Array Name := #[]
/--
Consider the following example:
```
structure A where
x : Nat := 1
structure B extends A where
y : Nat := x + 1
x := y + 1
structure C extends B where
z : Nat := 2*y
x := z + 3
```
And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`.
We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2.
The field `maxDistance` specifies the maximum distance considered in a round of Default field computation.
Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0.
The fixpoint for setting default values works in the following way.
- Keep computing default values using `maxDistance == 0`.
- We increase `maxDistance` whenever we failed to compute a new default value in a round.
- If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value.
We use depth-first search.
- We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above).
-/
maxDistance : Nat := 0
structure State where
progress : Bool := false
partial def collectStructNames (struct : Struct) (names : Array Name) : Array Name :=
let names := names.push struct.structName
struct.fields.foldl (init := names) fun names field =>
match field.val with
| FieldVal.nested struct => collectStructNames struct names
| _ => names
partial def getHierarchyDepth (struct : Struct) : Nat :=
struct.fields.foldl (init := 0) fun max field =>
match field.val with
| FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1)
| _ => max
partial def findDefaultMissing? (mctx : MetavarContext) (struct : Struct) : Option (Field Struct) :=
struct.fields.findSome? fun field =>
match field.val with
| FieldVal.nested struct => findDefaultMissing? mctx struct
| _ => match field.expr? with
| none => unreachable!
| some expr => match defaultMissing? expr with
| some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field
| _ => none
def getFieldName (field : Field Struct) : Name :=
match field.lhs with
| [FieldLHS.fieldName _ fieldName] => fieldName
| _ => unreachable!
abbrev M := ReaderT Context (StateRefT State TermElabM)
def isRoundDone : M Bool := do
return (← get).progress && (← read).maxDistance > 0
def getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr :=
struct.fields.findSome? fun field =>
if getFieldName field == fieldName then
field.expr?
else
none
partial def mkDefaultValueAux? (struct : Struct) : Expr → TermElabM (Option Expr)
| Expr.lam n d b c => withRef struct.ref do
if c.binderInfo.isExplicit then
let fieldName := n
match getFieldValue? struct fieldName with
| none => pure none
| some val =>
let valType ← inferType val
if (← isDefEq valType d) then
mkDefaultValueAux? struct (b.instantiate1 val)
else
pure none
else
let arg ← mkFreshExprMVar d
mkDefaultValueAux? struct (b.instantiate1 arg)
| e =>
if e.isAppOfArity `id 2 then
pure (some e.appArg!)
else
pure (some e)
def mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) :=
withRef struct.ref do
let us ← mkFreshLevelMVarsFor cinfo
mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us)
/-- If `e` is a projection function of one of the given structures, then reduce it -/
def reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do
if !e.isApp then pure none
else match e.getAppFn with
| Expr.const name _ _ => do
let env ← getEnv
match env.getProjectionStructureName? name with
| some structName =>
if structNames.contains structName then
Meta.unfoldDefinition? e
else
pure none
| none => pure none
| _ => pure none
/-- Reduce default value. It performs beta reduction and projections of the given structures. -/
partial def reduce (structNames : Array Name) : Expr → MetaM Expr
| e@(Expr.lam _ _ _ _) => lambdaLetTelescope e fun xs b => do mkLambdaFVars xs (← reduce structNames b)
| e@(Expr.forallE _ _ _ _) => forallTelescope e fun xs b => do mkForallFVars xs (← reduce structNames b)
| e@(Expr.letE _ _ _ _ _) => lambdaLetTelescope e fun xs b => do mkLetFVars xs (← reduce structNames b)
| e@(Expr.proj _ i b _) => do
match (← Meta.project? b i) with
| some r => reduce structNames r
| none => return e.updateProj! (← reduce structNames b)
| e@(Expr.app f _ _) => do
match (← reduceProjOf? structNames e) with
| some r => reduce structNames r
| none =>
let f := f.getAppFn
let f' ← reduce structNames f
if f'.isLambda then
let revArgs := e.getAppRevArgs
reduce structNames (f'.betaRev revArgs)
else
let args ← e.getAppArgs.mapM (reduce structNames)
return (mkAppN f' args)
| e@(Expr.mdata _ b _) => do
let b ← reduce structNames b
if (defaultMissing? e).isSome && !b.isMVar then
return b
else
return e.updateMData! b
| e@(Expr.mvar mvarId _) => do
match (← getExprMVarAssignment? mvarId) with
| some val => if val.isMVar then reduce structNames val else pure val
| none => return e
| e => return e
partial def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool :=
let rec loop (i : Nat) (dist : Nat) := do
if dist > maxDistance then
pure false
else if h : i < structs.size then do
let struct := structs.get ⟨i, h⟩
let defaultName := struct.structName ++ fieldName ++ `_default
let env ← getEnv
match env.find? defaultName with
| some cinfo@(ConstantInfo.defnInfo defVal) => do
let mctx ← getMCtx
let val? ← mkDefaultValue? struct cinfo
match val? with
| none => do setMCtx mctx; loop (i+1) (dist+1)
| some val => do
let val ← reduce allStructNames val
match val.find? fun e => (defaultMissing? e).isSome with
| some _ => setMCtx mctx; loop (i+1) (dist+1)
| none =>
let mvarDecl ← getMVarDecl mvarId
let val ← ensureHasType mvarDecl.type val
assignExprMVar mvarId val
pure true
| _ => loop (i+1) dist
else
pure false
loop 0 0
partial def step (struct : Struct) : M Unit :=
unless (← isRoundDone) do
withReader (fun ctx => { ctx with structs := ctx.structs.push struct }) do
for field in struct.fields do
match field.val with
| FieldVal.nested struct => step struct
| _ => match field.expr? with
| none => unreachable!
| some expr => match defaultMissing? expr with
| some (Expr.mvar mvarId _) =>
unless (← isExprMVarAssigned mvarId) do
let ctx ← read
if (← withRef field.ref <| tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) then
modify fun s => { s with progress := true }
| _ => pure ()
partial def propagateLoop (hierarchyDepth : Nat) (d : Nat) (struct : Struct) : M Unit := do
match findDefaultMissing? (← getMCtx) struct with
| none => pure () -- Done
| some field =>
if d > hierarchyDepth then
throwErrorAt field.ref "field '{getFieldName field}' is missing"
else withReader (fun ctx => { ctx with maxDistance := d }) do
modify fun s => { s with progress := false }
step struct
if (← get).progress then do
propagateLoop hierarchyDepth 0 struct
else
propagateLoop hierarchyDepth (d+1) struct
def propagate (struct : Struct) : TermElabM Unit :=
let hierarchyDepth := getHierarchyDepth struct
let structNames := collectStructNames struct #[]
(propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {}
end DefaultFields
private def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do
let (structName, structType) ← getStructName stx expectedType? source
unless isStructureLike (← getEnv) structName do
throwError "invalid \{...} notation, structure type expected{indentExpr structType}"
match mkStructView stx structName source with
| Except.error ex => throwError ex
| Except.ok struct =>
let struct ← expandStruct struct
trace[Elab.struct] "{struct}"
let (r, struct) ← elabStruct struct expectedType?
DefaultFields.propagate struct
pure r
@[builtinTermElab structInst] def elabStructInst : TermElab := fun stx expectedType? => do
match (← expandNonAtomicExplicitSource stx) with
| some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
| none =>
let sourceView ← getStructSource stx
match (← isModifyOp? stx), sourceView with
| some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType?
| some _, _ => throwError "invalid \{...} notation, explicit source is required when using '[<index>] := <value>'"
| _, _ => elabStructInstAux stx expectedType? sourceView
builtin_initialize registerTraceClass `Elab.struct
end Lean.Elab.Term.StructInst
|
bac8e0d2756b57f450e80de04e4106f2f3a402b0 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/preadditive/schur_auto.lean | 3e8022a98983734148193d974c4a3f2af957dd58 | [] | 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,830 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.simple
import Mathlib.category_theory.preadditive.default
import Mathlib.PostPort
universes u v
namespace Mathlib
/-!
# Schur's lemma
We prove the part of Schur's Lemma that holds in any preadditive category with kernels,
that any nonzero morphism between simple objects
is an isomorphism.
## TODO
If the category is enriched over finite dimensional vector spaces
over an algebraically closed field, then we can further prove that
`dim (X ⟶ Y) ≤ 1`.
(Probably easiest to prove this for endomorphisms first:
some polynomial `p` in `f : X ⟶ X` vanishes by finite dimensionality,
that polynomial factors linearly,
and at least one factor must be non-invertible, hence zero,
so `f` is a scalar multiple of the identity.
Then for any two nonzero `f g : X ⟶ Y`,
observe `f ≫ g⁻¹` is a multiple of the identity.)
-/
namespace category_theory
/--
Schur's Lemma (for a general preadditive category),
that a nonzero morphism between simple objects is an isomorphism.
-/
def is_iso_of_hom_simple {C : Type u} [category C] [preadditive C] [limits.has_kernels C] {X : C}
{Y : C} [simple X] [simple Y] {f : X ⟶ Y} (w : f ≠ 0) : is_iso f :=
is_iso_of_mono_of_nonzero w
/--
As a corollary of Schur's lemma,
any morphism between simple objects is (exclusively) either an isomorphism or zero.
-/
def is_iso_equiv_nonzero {C : Type u} [category C] [preadditive C] [limits.has_kernels C] {X : C}
{Y : C} [simple X] [simple Y] {f : X ⟶ Y} : is_iso f ≃ f ≠ 0 :=
equiv.mk sorry (fun (w : f ≠ 0) => is_iso_of_hom_simple w) sorry sorry
end Mathlib |
48180b24277fdd354c4b821a109aa5b2391a0ebf | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/init/function.lean | d360a257e04741a68f42872af5eced89bea35383 | [
"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 | 5,627 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad, Haitao Zhang
General operations on functions.
-/
prelude
import init.data.prod init.funext init.logic
universes u₁ u₂ u₃ u₄
namespace function
variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁}
@[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ :=
λ x, f (g x)
@[inline, reducible] def dcomp {β : α → Sort u₂} {φ : Π {x : α}, β x → Sort u₃}
(f : Π {x : α} (y : β x), φ y) (g : Π x, β x) : Π x, φ (g x) :=
λ x, f (g x)
infixr ` ∘ ` := function.comp
infixr ` ∘' `:80 := function.dcomp
@[reducible] def comp_right (f : β → β → β) (g : α → β) : β → α → β :=
λ b a, f b (g a)
@[reducible] def comp_left (f : β → β → β) (g : α → β) : α → β → β :=
λ a b, f (g a) b
@[reducible] def on_fun (f : β → β → φ) (g : α → β) : α → α → φ :=
λ x y, f (g x) (g y)
@[reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ)
: α → β → ζ :=
λ x y, op (f x y) (g x y)
@[reducible] def const (β : Sort u₂) (a : α) : β → α :=
λ x, a
@[reducible] def swap {φ : α → β → Sort u₃} (f : Π x y, φ x y) : Π y x, φ x y :=
λ y x, f x y
@[reducible] def app {β : α → Sort u₂} (f : Π x, β x) (x : α) : β x :=
f x
infixl ` on `:2 := on_fun
notation f ` -[` op `]- ` g := combine f op g
lemma left_id (f : α → β) : id ∘ f = f := rfl
lemma right_id (f : α → β) : f ∘ id = f := rfl
@[simp] lemma comp_app (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl
lemma comp.assoc (f : φ → δ) (g : β → φ) (h : α → β) : (f ∘ g) ∘ h = f ∘ (g ∘ h) := rfl
@[simp] lemma comp.left_id (f : α → β) : id ∘ f = f := rfl
@[simp] lemma comp.right_id (f : α → β) : f ∘ id = f := rfl
lemma comp_const_right (f : β → φ) (b : β) : f ∘ (const α b) = const α (f b) := rfl
@[reducible] def injective (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, f a₁ = f a₂ → a₁ = a₂
lemma injective_comp {g : β → φ} {f : α → β} (hg : injective g) (hf : injective f) : injective (g ∘ f) :=
assume a₁ a₂, assume h, hf (hg h)
@[reducible] def surjective (f : α → β) : Prop := ∀ b, ∃ a, f a = b
lemma surjective_comp {g : β → φ} {f : α → β} (hg : surjective g) (hf : surjective f) : surjective (g ∘ f) :=
λ (c : φ), exists.elim (hg c) (λ b hb, exists.elim (hf b) (λ a ha,
exists.intro a (show g (f a) = c, from (eq.trans (congr_arg g ha) hb))))
def bijective (f : α → β) := injective f ∧ surjective f
lemma bijective_comp {g : β → φ} {f : α → β} : bijective g → bijective f → bijective (g ∘ f)
| ⟨h_ginj, h_gsurj⟩ ⟨h_finj, h_fsurj⟩ := ⟨injective_comp h_ginj h_finj, surjective_comp h_gsurj h_fsurj⟩
/-- `left_inverse g f` means that g is a left inverse to f. That is, `g ∘ f = id`. -/
def left_inverse (g : β → α) (f : α → β) : Prop := ∀ x, g (f x) = x
def has_left_inverse (f : α → β) : Prop := ∃ finv : β → α, left_inverse finv f
/-- `right_inverse g f` means that g is a right inverse to f. That is, `f ∘ g = id`. -/
def right_inverse (g : β → α) (f : α → β) : Prop := left_inverse f g
def has_right_inverse (f : α → β) : Prop := ∃ finv : β → α, right_inverse finv f
lemma injective_of_left_inverse {g : β → α} {f : α → β} : left_inverse g f → injective f :=
assume h, assume a b, assume faeqfb,
have h₁ : a = g (f a), from eq.symm (h a),
have h₂ : g (f b) = b, from h b,
have h₃ : g (f a) = g (f b), from congr_arg g faeqfb,
eq.trans h₁ (eq.trans h₃ h₂)
lemma injective_of_has_left_inverse {f : α → β} : has_left_inverse f → injective f :=
assume h, exists.elim h (λ finv inv, injective_of_left_inverse inv)
lemma right_inverse_of_injective_of_left_inverse {f : α → β} {g : β → α}
(injf : injective f) (lfg : left_inverse f g) :
right_inverse f g :=
assume x,
have h : f (g (f x)) = f x, from lfg (f x),
injf h
lemma surjective_of_has_right_inverse {f : α → β} : has_right_inverse f → surjective f
| ⟨finv, inv⟩ b := ⟨finv b, inv b⟩
lemma left_inverse_of_surjective_of_right_inverse {f : α → β} {g : β → α}
(surjf : surjective f) (rfg : right_inverse f g) :
left_inverse f g :=
assume y, exists.elim (surjf y) (λ x hx, calc
f (g y) = f (g (f x)) : hx ▸ rfl
... = f x : eq.symm (rfg x) ▸ rfl
... = y : hx)
lemma injective_id : injective (@id α) := assume a₁ a₂ h, h
lemma surjective_id : surjective (@id α) := assume a, ⟨a, rfl⟩
lemma bijective_id : bijective (@id α) := ⟨injective_id, surjective_id⟩
end function
namespace function
variables {α : Type u₁} {β : Type u₂} {φ : Type u₃}
@[inline] def curry : (α × β → φ) → α → β → φ :=
λ f a b, f (a, b)
@[inline] def uncurry : (α → β → φ) → α × β → φ :=
λ f ⟨a, b⟩, f a b
@[simp] lemma curry_uncurry (f : α → β → φ) : curry (uncurry f) = f :=
rfl
@[simp] lemma uncurry_curry (f : α × β → φ) : uncurry (curry f) = f :=
funext (λ ⟨a, b⟩, rfl)
def id_of_left_inverse {g : β → α} {f : α → β} : left_inverse g f → g ∘ f = id :=
assume h, funext h
def id_of_right_inverse {g : β → α} {f : α → β} : right_inverse g f → f ∘ g = id :=
assume h, funext h
end function
|
374fcba3d0fc41fe2131825a3d565d2115c6c56a | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/logic/equiv/option.lean | 4e5b76afdd7712be87220e1eb241e5975a30a201 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 7,570 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import control.equiv_functor
import logic.equiv.basic
/-!
# Equivalences for `option α`
We define
* `equiv.option_congr`: the `option α ≃ option β` constructed from `e : α ≃ β` by sending `none` to
`none`, and applying a `e` elsewhere.
* `equiv.remove_none`: the `α ≃ β` constructed from `option α ≃ option β` by removing `none` from
both sides.
-/
namespace equiv
open option
variables {α β γ : Type*}
section option_congr
/-- A universe-polymorphic version of `equiv_functor.map_equiv option e`. -/
@[simps apply]
def option_congr (e : α ≃ β) : option α ≃ option β :=
{ to_fun := option.map e,
inv_fun := option.map e.symm,
left_inv := λ x, (option.map_map _ _ _).trans $
e.symm_comp_self.symm ▸ congr_fun option.map_id x,
right_inv := λ x, (option.map_map _ _ _).trans $
e.self_comp_symm.symm ▸ congr_fun option.map_id x }
@[simp] lemma option_congr_refl : option_congr (equiv.refl α) = equiv.refl _ :=
ext $ congr_fun option.map_id
@[simp] lemma option_congr_symm (e : α ≃ β) : (option_congr e).symm = option_congr e.symm := rfl
@[simp] lemma option_congr_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) :
(option_congr e₁).trans (option_congr e₂) = option_congr (e₁.trans e₂) :=
ext $ option.map_map _ _
/-- When `α` and `β` are in the same universe, this is the same as the result of
`equiv_functor.map_equiv`. -/
lemma option_congr_eq_equiv_function_map_equiv {α β : Type*} (e : α ≃ β) :
option_congr e = equiv_functor.map_equiv option e := rfl
end option_congr
section remove_none
variables (e : option α ≃ option β)
private def remove_none_aux (x : α) : β :=
if h : (e (some x)).is_some
then option.get h
else option.get $ show (e none).is_some, from
begin
rw ←option.ne_none_iff_is_some,
intro hn,
rw [option.not_is_some_iff_eq_none, ←hn] at h,
simpa only using e.injective h,
end
private lemma remove_none_aux_some {x : α} (h : ∃ x', e (some x) = some x') :
some (remove_none_aux e x) = e (some x) :=
by simp [remove_none_aux, option.is_some_iff_exists.mpr h]
private lemma remove_none_aux_none {x : α} (h : e (some x) = none) :
some (remove_none_aux e x) = e none :=
by simp [remove_none_aux, option.not_is_some_iff_eq_none.mpr h]
private lemma remove_none_aux_inv (x : α) : remove_none_aux e.symm (remove_none_aux e x) = x :=
option.some_injective _ begin
cases h1 : e.symm (some (remove_none_aux e x)); cases h2 : (e (some x)),
{ rw remove_none_aux_none _ h1,
exact (e.eq_symm_apply.mpr h2).symm },
{ rw remove_none_aux_some _ ⟨_, h2⟩ at h1,
simpa using h1, },
{ rw remove_none_aux_none _ h2 at h1,
simpa using h1, },
{ rw remove_none_aux_some _ ⟨_, h1⟩,
rw remove_none_aux_some _ ⟨_, h2⟩,
simp },
end
/-- Given an equivalence between two `option` types, eliminate `none` from that equivalence by
mapping `e.symm none` to `e none`. -/
def remove_none : α ≃ β :=
{ to_fun := remove_none_aux e,
inv_fun := remove_none_aux e.symm,
left_inv := remove_none_aux_inv e,
right_inv := remove_none_aux_inv e.symm, }
@[simp]
lemma remove_none_symm : (remove_none e).symm = remove_none e.symm := rfl
lemma remove_none_some {x : α} (h : ∃ x', e (some x) = some x') :
some (remove_none e x) = e (some x) := remove_none_aux_some e h
lemma remove_none_none {x : α} (h : e (some x) = none) :
some (remove_none e x) = e none := remove_none_aux_none e h
@[simp] lemma option_symm_apply_none_iff : e.symm none = none ↔ e none = none :=
⟨λ h, by simpa using (congr_arg e h).symm, λ h, by simpa using (congr_arg e.symm h).symm⟩
lemma some_remove_none_iff {x : α} :
some (remove_none e x) = e none ↔ e.symm none = some x :=
begin
cases h : e (some x) with a,
{ rw remove_none_none _ h,
simpa using (congr_arg e.symm h).symm },
{ rw remove_none_some _ ⟨a, h⟩,
have := (congr_arg e.symm h),
rw [symm_apply_apply] at this,
simp only [false_iff, apply_eq_iff_eq],
simp [this] }
end
@[simp]
lemma remove_none_option_congr (e : α ≃ β) : remove_none e.option_congr = e :=
equiv.ext $ λ x, option.some_injective _ $ remove_none_some _ ⟨e x, by simp [equiv_functor.map]⟩
end remove_none
lemma option_congr_injective : function.injective (option_congr : α ≃ β → option α ≃ option β) :=
function.left_inverse.injective remove_none_option_congr
/-- Equivalences between `option α` and `β` that send `none` to `x` are equivalent to
equivalences between `α` and `{y : β // y ≠ x}`. -/
def option_subtype [decidable_eq β] (x : β) :
{e : option α ≃ β // e none = x} ≃ (α ≃ {y : β // y ≠ x}) :=
{ to_fun := λ e,
{ to_fun := λ a, ⟨e a, ((equiv_like.injective _).ne_iff' e.property).2 (some_ne_none _)⟩,
inv_fun := λ b, get (ne_none_iff_is_some.1 (((equiv_like.injective _).ne_iff'
(((apply_eq_iff_eq_symm_apply _).1 e.property).symm)).2 b.property)),
left_inv := λ a, begin
rw [←some_inj, some_get, ←coe_def],
exact symm_apply_apply (e : option α ≃ β) a
end,
right_inv := λ b, begin
ext,
simp,
exact apply_symm_apply _ _
end },
inv_fun := λ e,
⟨{ to_fun := λ a, cases_on' a x (coe ∘ e),
inv_fun := λ b, if h : b = x then none else e.symm ⟨b, h⟩,
left_inv := λ a, begin
cases a, { simp },
simp only [cases_on'_some, function.comp_app, subtype.coe_eta, symm_apply_apply,
dite_eq_ite],
exact if_neg (e a).property
end,
right_inv := λ b, begin
by_cases h : b = x;
simp [h]
end},
rfl⟩,
left_inv := λ e, begin
ext a,
cases a,
{ simpa using e.property.symm },
{ simpa }
end,
right_inv := λ e, begin
ext a,
refl
end }
@[simp] lemma option_subtype_apply_apply [decidable_eq β] (x : β)
(e : {e : option α ≃ β // e none = x}) (a : α) (h) :
option_subtype x e a = ⟨(e : option α ≃ β) a, h⟩ :=
rfl
@[simp] lemma coe_option_subtype_apply_apply [decidable_eq β] (x : β)
(e : {e : option α ≃ β // e none = x}) (a : α) :
↑(option_subtype x e a) = (e : option α ≃ β) a :=
rfl
@[simp] lemma option_subtype_apply_symm_apply [decidable_eq β] (x : β)
(e : {e : option α ≃ β // e none = x}) (b : {y : β // y ≠ x}) :
↑((option_subtype x e).symm b) = (e : option α ≃ β).symm b :=
begin
dsimp only [option_subtype],
simp
end
@[simp] lemma option_subtype_symm_apply_apply_coe [decidable_eq β] (x : β)
(e : α ≃ {y : β // y ≠ x}) (a : α) : (option_subtype x).symm e a = e a :=
rfl
@[simp] lemma option_subtype_symm_apply_apply_some [decidable_eq β] (x : β)
(e : α ≃ {y : β // y ≠ x}) (a : α) : (option_subtype x).symm e (some a) = e a :=
rfl
@[simp] lemma option_subtype_symm_apply_apply_none [decidable_eq β] (x : β)
(e : α ≃ {y : β // y ≠ x}) : (option_subtype x).symm e none = x :=
rfl
@[simp] lemma option_subtype_symm_apply_symm_apply [decidable_eq β] (x : β)
(e : α ≃ {y : β // y ≠ x}) (b : {y : β // y ≠ x}) :
((option_subtype x).symm e : option α ≃ β).symm b = e.symm b :=
begin
simp only [option_subtype, coe_fn_symm_mk, subtype.coe_mk, subtype.coe_eta, dite_eq_ite,
ite_eq_right_iff],
exact λ h, false.elim (b.property h),
end
end equiv
|
32b537d05b4b08b51c188edec4daadae4f913d91 | b2fe74b11b57d362c13326bc5651244f111fa6f4 | /src/category_theory/equivalence.lean | 4f24a8e514f6189a3db3764d852340a5b753be05 | [
"Apache-2.0"
] | permissive | midfield/mathlib | c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7 | 775edc615ecec631d65b6180dbcc7bc26c3abc26 | refs/heads/master | 1,675,330,551,921 | 1,608,304,514,000 | 1,608,304,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,277 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn
-/
import category_theory.fully_faithful
import category_theory.whiskering
import tactic.slice
/-!
# Equivalence of categories
An equivalence of categories `C` and `D` is a pair of functors `F : C ⥤ D` and `G : D ⥤ C` such
that `η : 𝟭 C ≅ F ⋙ G` and `ε : G ⋙ F ≅ 𝟭 D`. In many situations, equivalences are a better
notion of "sameness" of categories than the stricter isomorphims of categories.
Recall that one way to express that two functors `F : C ⥤ D` and `G : D ⥤ C` are adjoint is using
two natural transformations `η : 𝟭 C ⟶ F ⋙ G` and `ε : G ⋙ F ⟶ 𝟭 D`, called the unit and the
counit, such that the compositions `F ⟶ FGF ⟶ F` and `G ⟶ GFG ⟶ G` are the identity. Unfortunately,
it is not the case that the natural isomorphisms `η` and `ε` in the definition of an equivalence
automatically give an adjunction. However, it is true that
* if one of the two compositions is the identity, then so is the other, and
* given an equivalence of categories, it is always possible to refine `η` in such a way that the
identities are satisfied.
For this reason, in mathlib we define an equivalence to be a "half-adjoint equivalence", which is
a tuple `(F, G, η, ε)` as in the first paragraph such that the composite `F ⟶ FGF ⟶ F` is the
identity. By the remark above, this already implies that the tuple is an "adjoint equivalence",
i.e., that the composite `G ⟶ GFG ⟶ G` is also the identity.
We also define essentially surjective functors and show that a functor is an equivalence if and only
if it is full, faithful and essentially surjective.
## Main definitions
* `equivalence`: bundled (half-)adjoint equivalences of categories
* `is_equivalence`: type class on a functor `F` containing the data of the inverse `G` as well as
the natural isomorphisms `η` and `ε`.
* `ess_surj`: type class on a functor `F` containing the data of the preimages and the isomorphisms
`F.obj (preimage d) ≅ d`.
## Main results
* `equivalence.mk`: upgrade an equivalence to a (half-)adjoint equivalence
* `equivalence_of_fully_faithfully_ess_surj`: a fully faithful essentially surjective functor is an
equivalence.
## Notations
We write `C ≌ D` (`\backcong`, not to be confused with `≅`/`\cong`) for a bundled equivalence.
-/
namespace category_theory
open category_theory.functor nat_iso category
universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation
/-- We define an equivalence as a (half)-adjoint equivalence, a pair of functors with
a unit and counit which are natural isomorphisms and the triangle law `Fη ≫ εF = 1`, or in other
words the composite `F ⟶ FGF ⟶ F` is the identity.
In `unit_inverse_comp`, we show that this is actually an adjoint equivalence, i.e., that the
composite `G ⟶ GFG ⟶ G` is also the identity.
The triangle equation is written as a family of equalities between morphisms, it is more
complicated if we write it as an equality of natural transformations, because then we would have
to insert natural transformations like `F ⟶ F1`.
See https://stacks.math.columbia.edu/tag/001J
-/
structure equivalence (C : Type u₁) [category.{v₁} C] (D : Type u₂) [category.{v₂} D] :=
mk' ::
(functor : C ⥤ D)
(inverse : D ⥤ C)
(unit_iso : 𝟭 C ≅ functor ⋙ inverse)
(counit_iso : inverse ⋙ functor ≅ 𝟭 D)
(functor_unit_iso_comp' : ∀(X : C), functor.map ((unit_iso.hom : 𝟭 C ⟶ functor ⋙ inverse).app X) ≫
counit_iso.hom.app (functor.obj X) = 𝟙 (functor.obj X) . obviously)
restate_axiom equivalence.functor_unit_iso_comp'
infixr ` ≌ `:10 := equivalence
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
namespace equivalence
/-- The unit of an equivalence of categories. -/
abbreviation unit (e : C ≌ D) : 𝟭 C ⟶ e.functor ⋙ e.inverse := e.unit_iso.hom
/-- The counit of an equivalence of categories. -/
abbreviation counit (e : C ≌ D) : e.inverse ⋙ e.functor ⟶ 𝟭 D := e.counit_iso.hom
/-- The inverse of the unit of an equivalence of categories. -/
abbreviation unit_inv (e : C ≌ D) : e.functor ⋙ e.inverse ⟶ 𝟭 C := e.unit_iso.inv
/-- The inverse of the counit of an equivalence of categories. -/
abbreviation counit_inv (e : C ≌ D) : 𝟭 D ⟶ e.inverse ⋙ e.functor := e.counit_iso.inv
/- While these abbreviations are convenient, they also cause some trouble,
preventing structure projections from unfolding. -/
@[simp] lemma equivalence_mk'_unit (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit = unit_iso.hom := rfl
@[simp] lemma equivalence_mk'_counit (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit = counit_iso.hom := rfl
@[simp] lemma equivalence_mk'_unit_inv (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).unit_inv = unit_iso.inv := rfl
@[simp] lemma equivalence_mk'_counit_inv (functor inverse unit_iso counit_iso f) :
(⟨functor, inverse, unit_iso, counit_iso, f⟩ : C ≌ D).counit_inv = counit_iso.inv := rfl
@[simp] lemma functor_unit_comp (e : C ≌ D) (X : C) :
e.functor.map (e.unit.app X) ≫ e.counit.app (e.functor.obj X) = 𝟙 (e.functor.obj X) :=
e.functor_unit_iso_comp X
@[simp] lemma counit_inv_functor_comp (e : C ≌ D) (X : C) :
e.counit_inv.app (e.functor.obj X) ≫ e.functor.map (e.unit_inv.app X) = 𝟙 (e.functor.obj X) :=
begin
erw [iso.inv_eq_inv
(e.functor.map_iso (e.unit_iso.app X) ≪≫ e.counit_iso.app (e.functor.obj X)) (iso.refl _)],
exact e.functor_unit_comp X
end
lemma counit_inv_app_functor (e : C ≌ D) (X : C) :
e.counit_inv.app (e.functor.obj X) = e.functor.map (e.unit.app X) :=
by { symmetry, erw [←iso.comp_hom_eq_id (e.counit_iso.app _), functor_unit_comp], refl }
lemma counit_app_functor (e : C ≌ D) (X : C) :
e.counit.app (e.functor.obj X) = e.functor.map (e.unit_inv.app X) :=
by { erw [←iso.hom_comp_eq_id (e.functor.map_iso (e.unit_iso.app X)), functor_unit_comp], refl }
/-- The other triangle equality. The proof follows the following proof in Globular:
http://globular.science/1905.001 -/
@[simp] lemma unit_inverse_comp (e : C ≌ D) (Y : D) :
e.unit.app (e.inverse.obj Y) ≫ e.inverse.map (e.counit.app Y) = 𝟙 (e.inverse.obj Y) :=
begin
rw [←id_comp (e.inverse.map _), ←map_id e.inverse, ←counit_inv_functor_comp, map_comp,
←iso.hom_inv_id_assoc (e.unit_iso.app _) (e.inverse.map (e.functor.map _)),
app_hom, app_inv],
slice_lhs 2 3 { erw [e.unit.naturality] },
slice_lhs 1 2 { erw [e.unit.naturality] },
slice_lhs 4 4
{ rw [←iso.hom_inv_id_assoc (e.inverse.map_iso (e.counit_iso.app _)) (e.unit_inv.app _)] },
slice_lhs 3 4 { erw [←map_comp e.inverse, e.counit.naturality],
erw [(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp],
slice_lhs 2 3 { erw [←map_comp e.inverse, e.counit_iso.inv.naturality, map_comp] },
slice_lhs 3 4 { erw [e.unit_inv.naturality] },
slice_lhs 4 5 { erw [←map_comp (e.functor ⋙ e.inverse), (e.unit_iso.app _).hom_inv_id, map_id] },
erw [id_comp],
slice_lhs 3 4 { erw [←e.unit_inv.naturality] },
slice_lhs 2 3 { erw [←map_comp e.inverse, ←e.counit_iso.inv.naturality,
(e.counit_iso.app _).hom_inv_id, map_id] }, erw [id_comp, (e.unit_iso.app _).hom_inv_id], refl
end
@[simp] lemma inverse_counit_inv_comp (e : C ≌ D) (Y : D) :
e.inverse.map (e.counit_inv.app Y) ≫ e.unit_inv.app (e.inverse.obj Y) = 𝟙 (e.inverse.obj Y) :=
begin
erw [iso.inv_eq_inv
(e.unit_iso.app (e.inverse.obj Y) ≪≫ e.inverse.map_iso (e.counit_iso.app Y)) (iso.refl _)],
exact e.unit_inverse_comp Y
end
lemma unit_app_inverse (e : C ≌ D) (Y : D) :
e.unit.app (e.inverse.obj Y) = e.inverse.map (e.counit_inv.app Y) :=
by { erw [←iso.comp_hom_eq_id (e.inverse.map_iso (e.counit_iso.app Y)), unit_inverse_comp], refl }
lemma unit_inv_app_inverse (e : C ≌ D) (Y : D) :
e.unit_inv.app (e.inverse.obj Y) = e.inverse.map (e.counit.app Y) :=
by { symmetry, erw [←iso.hom_comp_eq_id (e.unit_iso.app _), unit_inverse_comp], refl }
@[simp] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) :
e.functor.map (e.inverse.map f) = e.counit.app X ≫ f ≫ e.counit_inv.app Y :=
(nat_iso.naturality_2 (e.counit_iso) f).symm
@[simp] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) :
e.inverse.map (e.functor.map f) = e.unit_inv.app X ≫ f ≫ e.unit.app Y :=
(nat_iso.naturality_1 (e.unit_iso) f).symm
section
-- In this section we convert an arbitrary equivalence to a half-adjoint equivalence.
variables {F : C ⥤ D} {G : D ⥤ C} (η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D)
/-- If `η : 𝟭 C ≅ F ⋙ G` is part of a (not necessarily half-adjoint) equivalence, we can upgrade it
to a refined natural isomorphism `adjointify_η η : 𝟭 C ≅ F ⋙ G` which exhibits the properties
required for a half-adjoint equivalence. See `equivalence.mk`. -/
def adjointify_η : 𝟭 C ≅ F ⋙ G :=
calc
𝟭 C ≅ F ⋙ G : η
... ≅ F ⋙ (𝟭 D ⋙ G) : iso_whisker_left F (left_unitor G).symm
... ≅ F ⋙ ((G ⋙ F) ⋙ G) : iso_whisker_left F (iso_whisker_right ε.symm G)
... ≅ F ⋙ (G ⋙ (F ⋙ G)) : iso_whisker_left F (associator G F G)
... ≅ (F ⋙ G) ⋙ (F ⋙ G) : (associator F G (F ⋙ G)).symm
... ≅ 𝟭 C ⋙ (F ⋙ G) : iso_whisker_right η.symm (F ⋙ G)
... ≅ F ⋙ G : left_unitor (F ⋙ G)
lemma adjointify_η_ε (X : C) :
F.map ((adjointify_η η ε).hom.app X) ≫ ε.hom.app (F.obj X) = 𝟙 (F.obj X) :=
begin
dsimp [adjointify_η], simp,
have := ε.hom.naturality (F.map (η.inv.app X)), dsimp at this, rw [this], clear this,
rw [←assoc _ _ (F.map _)],
have := ε.hom.naturality (ε.inv.app $ F.obj X), dsimp at this, rw [this], clear this,
have := (ε.app $ F.obj X).hom_inv_id, dsimp at this, rw [this], clear this,
rw [id_comp], have := (F.map_iso $ η.app X).hom_inv_id, dsimp at this, rw [this]
end
end
/-- Every equivalence of categories consisting of functors `F` and `G` such that `F ⋙ G` and
`G ⋙ F` are naturally isomorphic to identity functors can be transformed into a half-adjoint
equivalence without changing `F` or `G`. -/
protected definition mk (F : C ⥤ D) (G : D ⥤ C)
(η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : C ≌ D :=
⟨F, G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩
/-- Equivalence of categories is reflexive. -/
@[refl, simps] def refl : C ≌ C :=
⟨𝟭 C, 𝟭 C, iso.refl _, iso.refl _, λ X, category.id_comp _⟩
instance : inhabited (C ≌ C) :=
⟨refl⟩
/-- Equivalence of categories is symmetric. -/
@[symm, simps] def symm (e : C ≌ D) : D ≌ C :=
⟨e.inverse, e.functor, e.counit_iso.symm, e.unit_iso.symm, e.inverse_counit_inv_comp⟩
variables {E : Type u₃} [category.{v₃} E]
/-- Equivalence of categories is transitive. -/
@[trans, simps] def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E :=
{ functor := e.functor ⋙ f.functor,
inverse := f.inverse ⋙ e.inverse,
unit_iso :=
begin
refine iso.trans e.unit_iso _,
exact iso_whisker_left e.functor (iso_whisker_right f.unit_iso e.inverse) ,
end,
counit_iso :=
begin
refine iso.trans _ f.counit_iso,
exact iso_whisker_left f.inverse (iso_whisker_right e.counit_iso f.functor)
end,
-- We wouldn't have needed to give this proof if we'd used `equivalence.mk`,
-- but we choose to avoid using that here, for the sake of good structure projection `simp` lemmas.
functor_unit_iso_comp' := λ X,
begin
dsimp,
rw [← f.functor.map_comp_assoc, e.functor.map_comp, ←counit_inv_app_functor, fun_inv_map,
iso.inv_hom_id_app_assoc, assoc, iso.inv_hom_id_app, counit_app_functor, ← functor.map_comp],
erw [comp_id, iso.hom_inv_id_app, functor.map_id],
end }
/-- Composing a functor with both functors of an equivalence yields a naturally isomorphic functor. -/
def fun_inv_id_assoc (e : C ≌ D) (F : C ⥤ E) : e.functor ⋙ e.inverse ⋙ F ≅ F :=
(functor.associator _ _ _).symm ≪≫ iso_whisker_right e.unit_iso.symm F ≪≫ F.left_unitor
@[simp] lemma fun_inv_id_assoc_hom_app (e : C ≌ D) (F : C ⥤ E) (X : C) :
(fun_inv_id_assoc e F).hom.app X = F.map (e.unit_inv.app X) :=
by { dsimp [fun_inv_id_assoc], tidy }
@[simp] lemma fun_inv_id_assoc_inv_app (e : C ≌ D) (F : C ⥤ E) (X : C) :
(fun_inv_id_assoc e F).inv.app X = F.map (e.unit.app X) :=
by { dsimp [fun_inv_id_assoc], tidy }
/-- Composing a functor with both functors of an equivalence yields a naturally isomorphic functor. -/
def inv_fun_id_assoc (e : C ≌ D) (F : D ⥤ E) : e.inverse ⋙ e.functor ⋙ F ≅ F :=
(functor.associator _ _ _).symm ≪≫ iso_whisker_right e.counit_iso F ≪≫ F.left_unitor
@[simp] lemma inv_fun_id_assoc_hom_app (e : C ≌ D) (F : D ⥤ E) (X : D) :
(inv_fun_id_assoc e F).hom.app X = F.map (e.counit.app X) :=
by { dsimp [inv_fun_id_assoc], tidy }
@[simp] lemma inv_fun_id_assoc_inv_app (e : C ≌ D) (F : D ⥤ E) (X : D) :
(inv_fun_id_assoc e F).inv.app X = F.map (e.counit_inv.app X) :=
by { dsimp [inv_fun_id_assoc], tidy }
/-- If `C` is equivalent to `D`, then `C ⥤ E` is equivalent to `D ⥤ E`. -/
@[simps functor inverse unit_iso counit_iso {rhs_md:=semireducible}]
def congr_left (e : C ≌ D) : (C ⥤ E) ≌ (D ⥤ E) :=
equivalence.mk
((whiskering_left _ _ _).obj e.inverse)
((whiskering_left _ _ _).obj e.functor)
(nat_iso.of_components (λ F, (e.fun_inv_id_assoc F).symm) (by tidy))
(nat_iso.of_components (λ F, e.inv_fun_id_assoc F) (by tidy))
/-- If `C` is equivalent to `D`, then `E ⥤ C` is equivalent to `E ⥤ D`. -/
@[simps functor inverse unit_iso counit_iso {rhs_md:=semireducible}]
def congr_right (e : C ≌ D) : (E ⥤ C) ≌ (E ⥤ D) :=
equivalence.mk
((whiskering_right _ _ _).obj e.functor)
((whiskering_right _ _ _).obj e.inverse)
(nat_iso.of_components
(λ F, F.right_unitor.symm ≪≫ iso_whisker_left F e.unit_iso ≪≫ functor.associator _ _ _)
(by tidy))
(nat_iso.of_components
(λ F, functor.associator _ _ _ ≪≫ iso_whisker_left F e.counit_iso ≪≫ F.right_unitor)
(by tidy))
section cancellation_lemmas
variables (e : C ≌ D)
-- We need special forms of `cancel_nat_iso_hom_right(_assoc)` and `cancel_nat_iso_inv_right(_assoc)`
-- for units and counits, because neither `simp` or `rw` will apply those lemmas in this
-- setting without providing `e.unit_iso` (or similar) as an explicit argument.
-- We also provide the lemmas for length four compositions, since they're occasionally useful.
-- (e.g. in proving that equivalences take monos to monos)
@[simp] lemma cancel_unit_right {X Y : C}
(f f' : X ⟶ Y) :
f ≫ e.unit.app Y = f' ≫ e.unit.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_unit_inv_right {X Y : C}
(f f' : X ⟶ e.inverse.obj (e.functor.obj Y)) :
f ≫ e.unit_inv.app Y = f' ≫ e.unit_inv.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_counit_right {X Y : D}
(f f' : X ⟶ e.functor.obj (e.inverse.obj Y)) :
f ≫ e.counit.app Y = f' ≫ e.counit.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_counit_inv_right {X Y : D}
(f f' : X ⟶ Y) :
f ≫ e.counit_inv.app Y = f' ≫ e.counit_inv.app Y ↔ f = f' :=
by simp only [cancel_mono]
@[simp] lemma cancel_unit_right_assoc {W X X' Y : C}
(f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) :
f ≫ g ≫ e.unit.app Y = f' ≫ g' ≫ e.unit.app Y ↔ f ≫ g = f' ≫ g' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_counit_inv_right_assoc {W X X' Y : D}
(f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) :
f ≫ g ≫ e.counit_inv.app Y = f' ≫ g' ≫ e.counit_inv.app Y ↔ f ≫ g = f' ≫ g' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_unit_right_assoc' {W X X' Y Y' Z : C}
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) :
f ≫ g ≫ h ≫ e.unit.app Z = f' ≫ g' ≫ h' ≫ e.unit.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' :=
by simp only [←category.assoc, cancel_mono]
@[simp] lemma cancel_counit_inv_right_assoc' {W X X' Y Y' Z : D}
(f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) :
f ≫ g ≫ h ≫ e.counit_inv.app Z = f' ≫ g' ≫ h' ≫ e.counit_inv.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' :=
by simp only [←category.assoc, cancel_mono]
end cancellation_lemmas
section
-- There's of course a monoid structure on `C ≌ C`,
-- but let's not encourage using it.
-- The power structure is nevertheless useful.
/-- Powers of an auto-equivalence. -/
def pow (e : C ≌ C) : ℤ → (C ≌ C)
| (int.of_nat 0) := equivalence.refl
| (int.of_nat 1) := e
| (int.of_nat (n+2)) := e.trans (pow (int.of_nat (n+1)))
| (int.neg_succ_of_nat 0) := e.symm
| (int.neg_succ_of_nat (n+1)) := e.symm.trans (pow (int.neg_succ_of_nat n))
instance : has_pow (C ≌ C) ℤ := ⟨pow⟩
@[simp] lemma pow_zero (e : C ≌ C) : e^(0 : ℤ) = equivalence.refl := rfl
@[simp] lemma pow_one (e : C ≌ C) : e^(1 : ℤ) = e := rfl
@[simp] lemma pow_minus_one (e : C ≌ C) : e^(-1 : ℤ) = e.symm := rfl
-- TODO as necessary, add the natural isomorphisms `(e^a).trans e^b ≅ e^(a+b)`.
-- At this point, we haven't even defined the category of equivalences.
end
end equivalence
/-- A functor that is part of a (half) adjoint equivalence -/
class is_equivalence (F : C ⥤ D) :=
mk' ::
(inverse : D ⥤ C)
(unit_iso : 𝟭 C ≅ F ⋙ inverse)
(counit_iso : inverse ⋙ F ≅ 𝟭 D)
(functor_unit_iso_comp' : ∀ (X : C), F.map ((unit_iso.hom : 𝟭 C ⟶ F ⋙ inverse).app X) ≫
counit_iso.hom.app (F.obj X) = 𝟙 (F.obj X) . obviously)
restate_axiom is_equivalence.functor_unit_iso_comp'
namespace is_equivalence
instance of_equivalence (F : C ≌ D) : is_equivalence F.functor :=
{ ..F }
instance of_equivalence_inverse (F : C ≌ D) : is_equivalence F.inverse :=
is_equivalence.of_equivalence F.symm
open equivalence
/-- To see that a functor is an equivalence, it suffices to provide an inverse functor `G` such that
`F ⋙ G` and `G ⋙ F` are naturally isomorphic to identity functors. -/
protected definition mk {F : C ⥤ D} (G : D ⥤ C)
(η : 𝟭 C ≅ F ⋙ G) (ε : G ⋙ F ≅ 𝟭 D) : is_equivalence F :=
⟨G, adjointify_η η ε, ε, adjointify_η_ε η ε⟩
end is_equivalence
namespace functor
/-- Interpret a functor that is an equivalence as an equivalence. -/
def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D :=
⟨F, is_equivalence.inverse F, is_equivalence.unit_iso, is_equivalence.counit_iso,
is_equivalence.functor_unit_iso_comp⟩
instance is_equivalence_refl : is_equivalence (𝟭 C) :=
is_equivalence.of_equivalence equivalence.refl
/-- The inverse functor of a functor that is an equivalence. -/
def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C :=
is_equivalence.inverse F
instance is_equivalence_inv (F : C ⥤ D) [is_equivalence F] : is_equivalence F.inv :=
is_equivalence.of_equivalence F.as_equivalence.symm
@[simp] lemma as_equivalence_functor (F : C ⥤ D) [is_equivalence F] :
F.as_equivalence.functor = F := rfl
@[simp] lemma as_equivalence_inverse (F : C ⥤ D) [is_equivalence F] :
F.as_equivalence.inverse = inv F := rfl
@[simp] lemma inv_inv (F : C ⥤ D) [is_equivalence F] :
inv (inv F) = F := rfl
/-- The composition of functor that is an equivalence with its inverse is naturally isomorphic to
the identity functor. -/
def fun_inv_id (F : C ⥤ D) [is_equivalence F] : F ⋙ F.inv ≅ 𝟭 C :=
is_equivalence.unit_iso.symm
/-- The composition of functor that is an equivalence with its inverse is naturally isomorphic to
the identity functor. -/
def inv_fun_id (F : C ⥤ D) [is_equivalence F] : F.inv ⋙ F ≅ 𝟭 D :=
is_equivalence.counit_iso
variables {E : Type u₃} [category.{v₃} E]
instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] :
is_equivalence (F ⋙ G) :=
is_equivalence.of_equivalence (equivalence.trans (as_equivalence F) (as_equivalence G))
end functor
namespace equivalence
@[simp]
lemma functor_inv (E : C ≌ D) : E.functor.inv = E.inverse := rfl
@[simp]
lemma inverse_inv (E : C ≌ D) : E.inverse.inv = E.functor := rfl
@[simp]
lemma functor_as_equivalence (E : C ≌ D) : E.functor.as_equivalence = E :=
by { cases E, congr, }
@[simp]
lemma inverse_as_equivalence (E : C ≌ D) : E.inverse.as_equivalence = E.symm :=
by { cases E, congr, }
end equivalence
namespace is_equivalence
@[simp] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) :
F.map (F.inv.map f) = F.inv_fun_id.hom.app X ≫ f ≫ F.inv_fun_id.inv.app Y :=
begin
erw [nat_iso.naturality_2],
refl
end
@[simp] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) :
F.inv.map (F.map f) = F.fun_inv_id.hom.app X ≫ f ≫ F.fun_inv_id.inv.app Y :=
begin
erw [nat_iso.naturality_2],
refl
end
-- We should probably restate many of the lemmas about `equivalence` for `is_equivalence`,
-- but these are the only ones I need for now.
@[simp] lemma functor_unit_comp (E : C ⥤ D) [is_equivalence E] (Y) :
E.map (E.fun_inv_id.inv.app Y) ≫ E.inv_fun_id.hom.app (E.obj Y) = 𝟙 _ :=
equivalence.functor_unit_comp E.as_equivalence Y
@[simp] lemma inv_fun_id_inv_comp (E : C ⥤ D) [is_equivalence E] (Y) :
E.inv_fun_id.inv.app (E.obj Y) ≫ E.map (E.fun_inv_id.hom.app Y) = 𝟙 _ :=
eq_of_inv_eq_inv (functor_unit_comp _ _)
end is_equivalence
/--
A functor `F : C ⥤ D` is essentially surjective if for every `d : D`, there is some `c : C`
so `F.obj c ≅ D`.
See https://stacks.math.columbia.edu/tag/001C.
-/
class ess_surj (F : C ⥤ D) : Prop :=
(obj_preimage [] (d : D) : ∃ c, nonempty (F.obj c ≅ d))
namespace functor
/-- Given an essentially surjective functor, we can find a preimage for every object `d` in the
codomain. Applying the functor to this preimage will yield an object isomorphic to `d`, see
`fun_obj_preimage_iso`. -/
noncomputable def obj_preimage (F : C ⥤ D) [sF : ess_surj F] (d : D) : C :=
classical.some (ess_surj.obj_preimage F d)
/-- Applying an essentially surjective functor to a preimage of `d` yields an object that is
isomorphic to `d`. -/
noncomputable def fun_obj_preimage_iso (F : C ⥤ D) [sF : ess_surj F] (d : D) :
F.obj (F.obj_preimage d) ≅ d :=
classical.choice (classical.some_spec (ess_surj.obj_preimage F d))
end functor
namespace equivalence
/--
An equivalence is essentially surjective.
See https://stacks.math.columbia.edu/tag/02C3.
-/
lemma ess_surj_of_equivalence (F : C ⥤ D) [is_equivalence F] : ess_surj F :=
⟨λ Y, ⟨F.inv.obj Y, ⟨F.inv_fun_id.app Y⟩⟩⟩
/--
An equivalence is faithful.
See https://stacks.math.columbia.edu/tag/02C3.
-/
@[priority 100] -- see Note [lower instance priority]
instance faithful_of_equivalence (F : C ⥤ D) [is_equivalence F] : faithful F :=
{ map_injective' := λ X Y f g w,
begin
have p := congr_arg (@category_theory.functor.map _ _ _ _ F.inv _ _) w,
simpa only [cancel_epi, cancel_mono, is_equivalence.inv_fun_map] using p
end }.
/--
An equivalence is full.
See https://stacks.math.columbia.edu/tag/02C3.
-/
@[priority 100] -- see Note [lower instance priority]
instance full_of_equivalence (F : C ⥤ D) [is_equivalence F] : full F :=
{ preimage := λ X Y f, F.fun_inv_id.inv.app X ≫ F.inv.map f ≫ F.fun_inv_id.hom.app Y,
witness' := λ X Y f, F.inv.map_injective
(by simpa only [is_equivalence.inv_fun_map, assoc, iso.hom_inv_id_app_assoc, iso.hom_inv_id_app] using comp_id _) }
@[simps] private noncomputable def equivalence_inverse (F : C ⥤ D) [full F] [faithful F] [ess_surj F] : D ⥤ C :=
{ obj := λ X, F.obj_preimage X,
map := λ X Y f, F.preimage ((F.fun_obj_preimage_iso X).hom ≫ f ≫ (F.fun_obj_preimage_iso Y).inv),
map_id' := λ X, begin apply F.map_injective, tidy end,
map_comp' := λ X Y Z f g, by apply F.map_injective; simp }
/--
A functor which is full, faithful, and essentially surjective is an equivalence.
See https://stacks.math.columbia.edu/tag/02C3.
-/
noncomputable def equivalence_of_fully_faithfully_ess_surj
(F : C ⥤ D) [full F] [faithful F] [ess_surj F] : is_equivalence F :=
is_equivalence.mk (equivalence_inverse F)
(nat_iso.of_components
(λ X, (preimage_iso $ F.fun_obj_preimage_iso $ F.obj X).symm)
(λ X Y f, by { apply F.map_injective, obviously }))
(nat_iso.of_components F.fun_obj_preimage_iso (by tidy))
@[simp] lemma functor_map_inj_iff (e : C ≌ D) {X Y : C} (f g : X ⟶ Y) : e.functor.map f = e.functor.map g ↔ f = g :=
⟨λ h, e.functor.map_injective h, λ h, h ▸ rfl⟩
@[simp] lemma inverse_map_inj_iff (e : C ≌ D) {X Y : D} (f g : X ⟶ Y) : e.inverse.map f = e.inverse.map g ↔ f = g :=
functor_map_inj_iff e.symm f g
end equivalence
end category_theory
|
d17879023625335adad1b99a24c9d6abead2e84f | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/Util.lean | cc28a5b85b8178a29a0675eaa6336f52d8c09570 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 8,391 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.Trace
import Lean.Parser.Syntax
import Lean.Parser.Extension
import Lean.KeyedDeclsAttribute
import Lean.Elab.Exception
import Lean.DocString
import Lean.DeclarationRange
import Lean.Compiler.InitAttr
namespace Lean
def Syntax.prettyPrint (stx : Syntax) : Format :=
match stx.unsetTrailing.reprint with -- TODO use syntax pretty printer
| some str => format str.toFormat
| none => format stx
def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format :=
Std.format $
if view.scopes.isEmpty then
view.name
else if view.mainModule == mainModule then
view.scopes.foldl Name.mkNum (view.name ++ view.imported)
else
view.scopes.foldl Name.mkNum (view.name ++ view.imported ++ view.mainModule)
namespace Elab
def expandOptNamedPrio (stx : Syntax) : MacroM Nat :=
if stx.isNone then
return eval_prio default
else match stx[0] with
| `(Parser.Command.namedPrio| (priority := $prio)) => evalPrio prio
| _ => Macro.throwUnsupported
structure MacroStackElem where
before : Syntax
after : Syntax
abbrev MacroStack := List MacroStackElem
/- If `ref` does not have position information, then try to use macroStack -/
def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax :=
match ref.getPos? with
| some _ => ref
| none =>
match macroStack.find? (·.before.getPos? != none) with
| some elem => elem.before
| none => ref
register_builtin_option pp.macroStack : Bool := {
defValue := false
group := "pp"
descr := "dispaly macro expansion stack"
}
def addMacroStack {m} [Monad m] [MonadOptions m] (msgData : MessageData) (macroStack : MacroStack) : m MessageData := do
if !pp.macroStack.get (← getOptions) then pure msgData else
match macroStack with
| [] => pure msgData
| stack@(top::_) =>
let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ indentD top.after
pure $ stack.foldl
(fun (msgData : MessageData) (elem : MacroStackElem) =>
msgData ++ Format.line ++ "while expanding" ++ indentD elem.before)
msgData
def checkSyntaxNodeKind [Monad m] [MonadEnv m] [MonadError m] (k : Name) : m Name := do
if Parser.isValidSyntaxNodeKind (← getEnv) k then pure k
else throwError "failed"
def checkSyntaxNodeKindAtNamespaces [Monad m] [MonadEnv m] [MonadError m] (k : Name) : Name → m Name
| n@(Name.str p _ _) => checkSyntaxNodeKind (n ++ k) <|> checkSyntaxNodeKindAtNamespaces k p
| Name.anonymous => checkSyntaxNodeKind k
| _ => throwError "failed"
def checkSyntaxNodeKindAtCurrentNamespaces (k : Name) : AttrM Name := do
let ctx ← read
checkSyntaxNodeKindAtNamespaces k ctx.currNamespace
def syntaxNodeKindOfAttrParam (defaultParserNamespace : Name) (stx : Syntax) : AttrM SyntaxNodeKind := do
let k ← Attribute.Builtin.getId stx
checkSyntaxNodeKindAtCurrentNamespaces k
<|>
checkSyntaxNodeKind (defaultParserNamespace ++ k)
<|>
throwError "invalid syntax node kind '{k}'"
private unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax :=
env.evalConstCheck Syntax opts `Lean.Syntax constName
@[implementedBy evalSyntaxConstantUnsafe]
constant evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw ""
unsafe def mkElabAttribute (γ) (attrDeclName attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String)
: IO (KeyedDeclsAttribute γ) :=
KeyedDeclsAttribute.init {
builtinName := attrBuiltinName
name := attrName
descr := kind ++ " elaborator"
valueTypeName := typeName
evalKey := fun _ stx => syntaxNodeKindOfAttrParam parserNamespace stx
onAdded := fun builtin declName => do
if builtin then
if let some doc ← findDocString? (← getEnv) declName then
declareBuiltin (declName ++ `docString) (mkAppN (mkConst ``addBuiltinDocString) #[toExpr declName, toExpr doc])
if let some declRanges ← findDeclarationRanges? declName then
declareBuiltin (declName ++ `declRange) (mkAppN (mkConst ``addBuiltinDeclarationRanges) #[toExpr declName, toExpr declRanges])
} attrDeclName
unsafe def mkMacroAttributeUnsafe : IO (KeyedDeclsAttribute Macro) :=
mkElabAttribute Macro `Lean.Elab.macroAttribute `builtinMacro `macro Name.anonymous `Lean.Macro "macro"
@[implementedBy mkMacroAttributeUnsafe]
constant mkMacroAttribute : IO (KeyedDeclsAttribute Macro)
builtin_initialize macroAttribute : KeyedDeclsAttribute Macro ← mkMacroAttribute
/--
Try to expand macro at syntax tree root and return macro declaration name and new syntax if successful.
Return none if all macros threw `Macro.Exception.unsupportedSyntax`.
-/
def expandMacroImpl? (env : Environment) : Syntax → MacroM (Option (Name × Except Macro.Exception Syntax)) := fun stx => do
for e in macroAttribute.getEntries env stx.getKind do
try
let stx' ← withFreshMacroScope (e.value stx)
return (e.declName, Except.ok stx')
catch
| Macro.Exception.unsupportedSyntax => pure ()
| ex => return (e.declName, Except.error ex)
return none
class MonadMacroAdapter (m : Type → Type) where
getCurrMacroScope : m MacroScope
getNextMacroScope : m MacroScope
setNextMacroScope : MacroScope → m Unit
instance (m n) [MonadLift m n] [MonadMacroAdapter m] : MonadMacroAdapter n := {
getCurrMacroScope := liftM (MonadMacroAdapter.getCurrMacroScope : m _),
getNextMacroScope := liftM (MonadMacroAdapter.getNextMacroScope : m _),
setNextMacroScope := fun s => liftM (MonadMacroAdapter.setNextMacroScope s : m _)
}
def liftMacroM {α} {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (x : MacroM α) : m α := do
let env ← getEnv
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let methods := Macro.mkMethods {
-- TODO: record recursive expansions in info tree?
expandMacro? := fun stx => do
match (← expandMacroImpl? env stx) with
| some (_, Except.ok stx) => some stx
| _ => none
hasDecl := fun declName => return env.contains declName
getCurrNamespace := return currNamespace
resolveNamespace? := fun n => return ResolveName.resolveNamespace? env currNamespace openDecls n
resolveGlobalName := fun n => return ResolveName.resolveGlobalName env currNamespace openDecls n
}
match x { methods := methods
ref := ← getRef
currMacroScope := ← MonadMacroAdapter.getCurrMacroScope
mainModule := env.mainModule
currRecDepth := ← MonadRecDepth.getRecDepth
maxRecDepth := ← MonadRecDepth.getMaxRecDepth
} { macroScope := (← MonadMacroAdapter.getNextMacroScope) } with
| EStateM.Result.error Macro.Exception.unsupportedSyntax _ => throwUnsupportedSyntax
| EStateM.Result.error (Macro.Exception.error ref msg) _ => throwErrorAt ref msg
| EStateM.Result.ok a s =>
MonadMacroAdapter.setNextMacroScope s.macroScope
s.traceMsgs.reverse.forM fun (clsName, msg) => trace clsName fun _ => msg
pure a
@[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] (x : Macro) (stx : Syntax) : m Syntax :=
liftMacroM (x stx)
partial def mkUnusedBaseName (baseName : Name) : MacroM Name := do
let currNamespace ← Macro.getCurrNamespace
if ← Macro.hasDecl (currNamespace ++ baseName) then
let rec loop (idx : Nat) := do
let name := baseName.appendIndexAfter idx
if ← Macro.hasDecl (currNamespace ++ name) then
loop (idx+1)
else
name
loop 1
else
return baseName
builtin_initialize
registerTraceClass `Elab
registerTraceClass `Elab.step
end Lean.Elab
|
d9deb65cd71612c4693219a86dd5ca11340ac1b7 | d450724ba99f5b50b57d244eb41fef9f6789db81 | /src/instructor/lectures/lecture_25.lean | 1c39350eb87085f764fc7f18acbf60851dcdd274 | [] | no_license | jakekauff/CS2120F21 | 4f009adeb4ce4a148442b562196d66cc6c04530c | e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad | refs/heads/main | 1,693,841,880,030 | 1,637,604,848,000 | 1,637,604,848,000 | 399,946,698 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,493 | lean | import .lecture_24
/-
BASIC SETUP
-/
namespace relations
section relation
/-
Define relation, r, as two-place predicate on
a type, β, with notation, x ≺ y, for (r x y).
-/
variables {β : Type} (r : β → β → Prop)
local infix `≺`:50 := r
/-
ORDERING RELATIONS ON A TYPE, β
-/
def ordering :=
reflexive r ∧ transitive r ∧ anti_symmetric r
/-
An ordering is any relation in which (1) every
object a is related to itself (think "less then
or equal" to); (2) if an object a is "less than
or equal to" an object b, and b is less than or
equal to c, then a is "less than or equal to c",
and (3) crucially, if a is "less than or equal
to b" then the only way b can also be "less than
or equal to a is if and and b are in fact equal."
It's the anti_symmetry that prevents the case in
which you have both a ≺ b and b ≺ a where a ≠ b.
To have such a state would undermine the notion
that the relation puts the objects in a definite
"order." While the concept of anti-symmetry might
at first have seemed a but abstract, you can see
here how crucial it is to defining concepts that
we really care about, such as the concept of an
ordering.
-/
def partial_order := ordering r ∧ ¬strongly_connected r
def total_order := ordering r ∧ strongly_connected r
def strict_ordering := asymmetric r ∧ transitive r
/-
EXAMPLE:
The requirement of asymmetry in a strict ordering
implies that no object can be related to itself.
An example is < on the natural numbers. The only
exception is when a relation is defined on an empty
set. If you remove the condition that β be inhabited
in the next theorem, it is no longer true, insofar as
it's not true for all relations, r, on all types, β.
It's the existence of at least one value, b : β,
that enables one to derive a contradiction from the
combination of asymmetry (b cannot be related to b)
and reflexivity (b must be related to b). This is the
kind of "corner case" that can easily lead to serious
conceptual (not coding) errors in software design as
well as in mathematics, per se.
-/
/-
The next concept of importance, especially when it
comes to proofs of termination of recursive functions,
is that of a well order, aka wellorder, wellordering.
It's a combination of a total order (like ≤ but not
⊆) and this property that in any set of values there
is always a least element.
The nats are well ordered under ≤. Intuitively, every
possible set of natural numbers (even an infinite set)
will have a least element. The very least element of
all is 0, so no matter what set one picks, it will have
either zero or some direct or indirect successor of 0
as its least element.
The integers, on the other hand are not well ordered
under ≤. Think about and be sure you understand why.
If you get stuck thinking about this, go back to the
definition of well-order and revisit the idea that
every possible set of β values will have a least
element. What goes wrong when we pick ℤ rather than
ℕ under ≤?
This concept is important in enabling one to prove
that recursive functions are well founded: that no
matter what finite input they are given they will
stop running after some finite number of steps: i.e.,
they won't call themselves recursively without end.
The idea will be to show that each recursive call
that a function makes is given an argument value
that is "smaller" than the one that the function
received in the first place. As long as each time
an argument from a well ordered set is passed it
is smaller than the one that was received, then in
some finite number of recursive calls, a "least"
argument value will be encountered for which no
yet "smaller" value exits. Such a value is called
a "base case" in a recursive definition. We will
see more about this shortly.
-/
def well_order := total_order r ∧ (∀ (s : set β), -- for every
∃ (b : β), b ∈ s → -- non-empty set s
∃ (b : β), -- there is an element
b ∈ s ∧ -- in s
∀ b' : β, -- smaller than any other value in s
b' ∈ s →
b ≺ b')
/-
At this point in this course, we do expect you
to be able to read and make good sense of this
definition and others of this complexity.
-/
end relation
end relations
|
5068a7a12511782e230fd4f9563ede6e174f7f2d | c777c32c8e484e195053731103c5e52af26a25d1 | /archive/100-theorems-list/16_abel_ruffini.lean | b377089fa8056ccf66e3efa88026b75e7389c870 | [
"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 | 8,301 | 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 analysis.calculus.local_extr
import data.nat.prime_norm_num
import field_theory.abel_ruffini
import ring_theory.eisenstein_criterion
/-!
# Construction of an algebraic number that is not solvable by radicals.
The main ingredients are:
* `solvable_by_rad.is_solvable'` in `field_theory/abel_ruffini` :
an irreducible polynomial with an `is_solvable_by_rad` root has solvable Galois group
* `gal_action_hom_bijective_of_prime_degree'` in `field_theory/polynomial_galois_group` :
an irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group
* `equiv.perm.not_solvable` in `group_theory/solvable` : the symmetric group is not solvable
Then all that remains is the construction of a specific polynomial satisfying the conditions of
`gal_action_hom_bijective_of_prime_degree'`, which is done in this file.
-/
namespace abel_ruffini
open function polynomial polynomial.gal ideal
open_locale polynomial
local attribute [instance] splits_ℚ_ℂ
variables (R : Type*) [comm_ring R] (a b : ℕ)
/-- A quintic polynomial that we will show is irreducible -/
noncomputable def Φ : R[X] := X ^ 5 - C ↑a * X + C ↑b
variables {R}
@[simp] lemma map_Phi {S : Type*} [comm_ring S] (f : R →+* S) : (Φ R a b).map f = Φ S a b :=
by simp [Φ]
@[simp] lemma coeff_zero_Phi : (Φ R a b).coeff 0 = ↑b :=
by simp [Φ, coeff_X_pow]
@[simp] lemma coeff_five_Phi : (Φ R a b).coeff 5 = 1 :=
by simp [Φ, coeff_X, coeff_C, -C_eq_nat_cast, -map_nat_cast]
variables [nontrivial R]
lemma degree_Phi : (Φ R a b).degree = ↑5 :=
begin
suffices : degree (X ^ 5 - C ↑a * X) = ↑5,
{ rwa [Φ, degree_add_eq_left_of_degree_lt],
convert degree_C_le.trans_lt (with_bot.coe_lt_coe.mpr (nat.zero_lt_bit1 2)) },
rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow,
exact (degree_C_mul_X_le _).trans_lt (with_bot.coe_lt_coe.mpr (nat.one_lt_bit1 two_ne_zero)),
end
lemma nat_degree_Phi : (Φ R a b).nat_degree = 5 :=
nat_degree_eq_of_degree_eq_some (degree_Phi a b)
lemma leading_coeff_Phi : (Φ R a b).leading_coeff = 1 :=
by rw [polynomial.leading_coeff, nat_degree_Phi, coeff_five_Phi]
lemma monic_Phi : (Φ R a b).monic :=
leading_coeff_Phi a b
lemma irreducible_Phi (p : ℕ) (hp : p.prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬ p ^ 2 ∣ b) :
irreducible (Φ ℚ a b) :=
begin
rw [←map_Phi a b (int.cast_ring_hom ℚ), ←is_primitive.int.irreducible_iff_irreducible_map_cast],
apply irreducible_of_eisenstein_criterion,
{ rwa [span_singleton_prime (int.coe_nat_ne_zero.mpr hp.ne_zero), int.prime_iff_nat_abs_prime] },
{ rw [leading_coeff_Phi, mem_span_singleton],
exact_mod_cast mt nat.dvd_one.mp (hp.ne_one) },
{ intros n hn,
rw mem_span_singleton,
rw [degree_Phi, with_bot.coe_lt_coe] at hn,
interval_cases n with hn;
simp only [Φ, coeff_X_pow, coeff_C, int.coe_nat_dvd.mpr, hpb, if_true, coeff_C_mul, if_false,
nat.zero_ne_bit1, eq_self_iff_true, coeff_X_zero, hpa, coeff_add, zero_add, mul_zero,
coeff_sub, sub_self, nat.one_ne_zero, add_zero, coeff_X_one, mul_one,
zero_sub, dvd_neg, nat.one_eq_bit1, bit0_eq_zero, neg_zero, nat.bit0_ne_bit1,
dvd_mul_of_dvd_left, nat.bit1_eq_bit1, nat.one_ne_bit0, nat.bit1_ne_zero], },
{ simp only [degree_Phi, ←with_bot.coe_zero, with_bot.coe_lt_coe, nat.succ_pos'] },
{ rw [coeff_zero_Phi, span_singleton_pow, mem_span_singleton],
exact mt int.coe_nat_dvd.mp hp2b },
all_goals { exact monic.is_primitive (monic_Phi a b) },
end
lemma real_roots_Phi_le : fintype.card ((Φ ℚ a b).root_set ℝ) ≤ 3 :=
begin
rw [←map_Phi a b (algebra_map ℤ ℚ), Φ, ←one_mul (X ^ 5), ←C_1],
refine (card_root_set_le_derivative _).trans
(nat.succ_le_succ ((card_root_set_le_derivative _).trans (nat.succ_le_succ _))),
suffices : ((C ((algebra_map ℤ ℚ) 20) * X ^ 3).root_set ℝ).subsingleton,
{ norm_num [fintype.card_le_one_iff_subsingleton, ← mul_assoc, *] at * },
rw root_set_C_mul_X_pow; norm_num,
end
lemma real_roots_Phi_ge_aux (hab : b < a) :
∃ x y : ℝ, x ≠ y ∧ aeval x (Φ ℚ a b) = 0 ∧ aeval y (Φ ℚ a b) = 0 :=
begin
let f := λ x : ℝ, aeval x (Φ ℚ a b),
have hf : f = λ x, x ^ 5 - a * x + b := by simp [f, Φ],
have hc : ∀ s : set ℝ, continuous_on f s := λ s, (Φ ℚ a b).continuous_on_aeval,
have ha : (1 : ℝ) ≤ a := nat.one_le_cast.mpr (nat.one_le_of_lt hab),
have hle : (0 : ℝ) ≤ 1 := zero_le_one,
have hf0 : 0 ≤ f 0 := by norm_num [hf],
by_cases hb : (1 : ℝ) - a + b < 0,
{ have hf1 : f 1 < 0 := by norm_num [hf, hb],
have hfa : 0 ≤ f a,
{ simp_rw [hf, ←sq],
refine add_nonneg (sub_nonneg.mpr (pow_le_pow ha _)) _; norm_num },
obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Ico' hle (hc _) (set.mem_Ioc.mpr ⟨hf1, hf0⟩),
obtain ⟨y, ⟨hy1, -⟩, hy2⟩ := intermediate_value_Ioc ha (hc _) (set.mem_Ioc.mpr ⟨hf1, hfa⟩),
exact ⟨x, y, (hx1.trans hy1).ne, hx2, hy2⟩ },
{ replace hb : (b : ℝ) = a - 1 := by linarith [show (b : ℝ) + 1 ≤ a, by exact_mod_cast hab],
have hf1 : f 1 = 0 := by norm_num [hf, hb],
have hfa := calc f (-a) = a ^ 2 - a ^ 5 + b : by norm_num [hf, ← sq]
... ≤ a ^ 2 - a ^ 3 + (a - 1) : by refine add_le_add (sub_le_sub_left
(pow_le_pow ha _) _) _; linarith
... = -(a - 1) ^ 2 * (a + 1) : by ring
... ≤ 0 : by nlinarith,
have ha' := neg_nonpos.mpr (hle.trans ha),
obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Icc ha' (hc _) (set.mem_Icc.mpr ⟨hfa, hf0⟩),
exact ⟨x, 1, (hx1.trans_lt zero_lt_one).ne, hx2, hf1⟩ },
end
lemma real_roots_Phi_ge (hab : b < a) : 2 ≤ fintype.card ((Φ ℚ a b).root_set ℝ) :=
begin
have q_ne_zero : Φ ℚ a b ≠ 0 := (monic_Phi a b).ne_zero,
obtain ⟨x, y, hxy, hx, hy⟩ := real_roots_Phi_ge_aux a b hab,
have key : ↑({x, y} : finset ℝ) ⊆ (Φ ℚ a b).root_set ℝ,
{ simp [set.insert_subset, mem_root_set_of_ne q_ne_zero, hx, hy] },
convert fintype.card_le_of_embedding (set.embedding_of_subset _ _ key),
simp only [finset.coe_sort_coe, fintype.card_coe, finset.card_singleton,
finset.card_insert_of_not_mem (mt finset.mem_singleton.mp hxy)]
end
lemma complex_roots_Phi (h : (Φ ℚ a b).separable) : fintype.card ((Φ ℚ a b).root_set ℂ) = 5 :=
(card_root_set_eq_nat_degree h (is_alg_closed.splits_codomain _)).trans (nat_degree_Phi a b)
lemma gal_Phi (hab : b < a) (h_irred : irreducible (Φ ℚ a b)) :
bijective (gal_action_hom (Φ ℚ a b) ℂ) :=
begin
apply gal_action_hom_bijective_of_prime_degree' h_irred,
{ norm_num [nat_degree_Phi] },
{ rw [complex_roots_Phi a b h_irred.separable, nat.succ_le_succ_iff],
exact (real_roots_Phi_le a b).trans (nat.le_succ 3) },
{ simp_rw [complex_roots_Phi a b h_irred.separable, nat.succ_le_succ_iff],
exact real_roots_Phi_ge a b hab },
end
theorem not_solvable_by_rad (p : ℕ) (x : ℂ) (hx : aeval x (Φ ℚ a b) = 0) (hab : b < a)
(hp : p.prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬ p ^ 2 ∣ b) :
¬ is_solvable_by_rad ℚ x :=
begin
have h_irred := irreducible_Phi a b p hp hpa hpb hp2b,
apply mt (solvable_by_rad.is_solvable' h_irred hx),
introI h,
refine equiv.perm.not_solvable _ (le_of_eq _)
(solvable_of_surjective (gal_Phi a b hab h_irred).2),
rw_mod_cast [cardinal.mk_fintype, complex_roots_Phi a b h_irred.separable],
end
theorem not_solvable_by_rad' (x : ℂ) (hx : aeval x (Φ ℚ 4 2) = 0) :
¬ is_solvable_by_rad ℚ x :=
by apply not_solvable_by_rad 4 2 2 x hx; norm_num
/-- **Abel-Ruffini Theorem** -/
theorem exists_not_solvable_by_rad : ∃ x : ℂ, is_algebraic ℚ x ∧ ¬ is_solvable_by_rad ℚ x :=
begin
obtain ⟨x, hx⟩ := exists_root_of_splits (algebra_map ℚ ℂ)
(is_alg_closed.splits_codomain (Φ ℚ 4 2))
(ne_of_eq_of_ne (degree_Phi 4 2) (mt with_bot.coe_eq_coe.mp (nat.bit1_ne_zero 2))),
exact ⟨x, ⟨Φ ℚ 4 2, (monic_Phi 4 2).ne_zero, hx⟩, not_solvable_by_rad' x hx⟩,
end
end abel_ruffini
|
49f1ed5f18d30eaf5767b4c5982ac082b759317f | 3c9dc4ea6cc92e02634ef557110bde9eae393338 | /stage0/src/Lean/Util/Trace.lean | b294c5bfb4824d2ac1aa4dc12c389fe424d050a1 | [
"Apache-2.0"
] | permissive | shingtaklam1324/lean4 | 3d7efe0c8743a4e33d3c6f4adbe1300df2e71492 | 351285a2e8ad0cef37af05851cfabf31edfb5970 | refs/heads/master | 1,676,827,679,740 | 1,610,462,623,000 | 1,610,552,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,526 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich, Leonardo de Moura
-/
import Lean.Message
import Lean.MonadEnv
universe u
namespace Lean
open Std (PersistentArray)
structure TraceElem where
ref : Syntax
msg : MessageData
deriving Inhabited
structure TraceState where
enabled : Bool := true
traces : PersistentArray TraceElem := {}
deriving Inhabited
namespace TraceState
private def toFormat (traces : PersistentArray TraceElem) (sep : Format) : IO Format :=
traces.size.foldM
(fun i r => do
let curr ← (traces.get! i).msg.format
pure $ if i > 0 then r ++ sep ++ curr else r ++ curr)
Format.nil
end TraceState
class MonadTrace (m : Type → Type) where
modifyTraceState : (TraceState → TraceState) → m Unit
getTraceState : m TraceState
export MonadTrace (getTraceState modifyTraceState)
instance (m n) [MonadTrace m] [MonadLift m n] : MonadTrace n :=
{ modifyTraceState := fun f => liftM (modifyTraceState f : m _),
getTraceState := liftM (getTraceState : m _) }
variables {α : Type} {m : Type → Type} [Monad m] [MonadTrace m]
def printTraces {m} [Monad m] [MonadTrace m] [MonadLiftT IO m] : m Unit := do
let traceState ← getTraceState
traceState.traces.forM fun m => do
let d ← m.msg.format
IO.println d
def resetTraceState {m} [MonadTrace m] : m Unit :=
modifyTraceState (fun _ => {})
private def checkTraceOptionAux (opts : Options) : Name → Bool
| n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux opts p)
| _ => false
def checkTraceOption (opts : Options) (cls : Name) : Bool :=
if opts.isEmpty then false
else checkTraceOptionAux opts (`trace ++ cls)
private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool := do
let opts ← getOptions
pure $ checkTraceOption opts cls
@[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do
let s ← getTraceState
if !s.enabled then pure false
else checkTraceOptionM cls
@[inline] def enableTracing (b : Bool) : m Bool := do
let s ← getTraceState
let oldEnabled := s.enabled
modifyTraceState fun s => { s with enabled := b }
pure oldEnabled
@[inline] def getTraces : m (PersistentArray TraceElem) := do
let s ← getTraceState
pure s.traces
@[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit :=
modifyTraceState fun s => { s with traces := f s.traces }
@[inline] def setTraceState (s : TraceState) : m Unit :=
modifyTraceState fun _ => s
private def addNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) : m Unit :=
modifyTraces fun traces =>
if traces.isEmpty then
oldTraces
else
let d := MessageData.tagged cls (MessageData.node (traces.toArray.map fun elem => elem.msg))
oldTraces.push { ref := ref, msg := d }
private def getResetTraces : m (PersistentArray TraceElem) := do
let oldTraces ← getTraces
modifyTraces fun _ => {}
pure oldTraces
section
variables [MonadRef m] [AddMessageContext m] [MonadOptions m]
def addTrace (cls : Name) (msg : MessageData) : m Unit := do
let ref ← getRef
let msg ← addMessageContext msg
modifyTraces fun traces => traces.push { ref := ref, msg := MessageData.tagged cls msg }
@[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do
if (← isTracingEnabledFor cls) then
addTrace cls (msg ())
@[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do
if (← isTracingEnabledFor cls) then
let msg ← mkMsg
addTrace cls msg
@[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do
let b ← isTracingEnabledFor cls
if !b then
let old ← enableTracing false
try ctx finally enableTracing old
else
let ref ← getRef
let oldCurrTraces ← getResetTraces
try ctx finally addNode oldCurrTraces cls ref
-- TODO: delete after fix old frontend
def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit :=
Lean.trace cls msg
end
def registerTraceClass (traceClassName : Name) : IO Unit :=
registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" }
macro:max "trace!" id:term:max msg:term : term =>
`(trace $id fun _ => ($msg : MessageData))
syntax "trace[" ident "]!" (interpolatedStr(term) <|> term) : term
macro_rules
| `(trace[$id]! $s) =>
if s.getKind == interpolatedStrKind then
`(Lean.trace $(quote id.getId) fun _ => m! $s)
else
`(Lean.trace $(quote id.getId) fun _ => ($s : MessageData))
variables {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] [MonadOptions m] [MonadRef m]
def withNestedTraces [MonadFinally m] (x : m α) : m α := do
let s ← getTraceState
if !s.enabled then
x
else
let currTraces ← getTraces
modifyTraces fun _ => {}
let ref ← getRef
try
x
finally
modifyTraces fun traces =>
if traces.size == 0 then
currTraces
else if traces.size == 1 && traces[0].msg.isNest then
currTraces ++ traces -- No nest of nest
else
let d := traces.foldl (init := MessageData.nil) fun d elem =>
if d.isNil then elem.msg else m!"{d}\n{elem.msg}"
currTraces.push { ref := ref, msg := MessageData.nestD d }
end Lean
|
eb28b4f720f3b9262136afde5f724243b5585fd4 | 968e2f50b755d3048175f176376eff7139e9df70 | /examples/prop_logic_lean_summary/unnamed_546.lean | cd00c2701e61c2cb4d8e4561e029ed877ef6244e | [] | 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 | 145 | lean | variables p : Prop
-- BEGIN
example (h : ¬p) (k : p) : false :=
begin
apply h, -- This changes the goal to proving `p`.
exact k,
end
-- END |
df2d7076eb7bead2931be230f9caddbcf0c741e0 | 26bff4ed296b8373c92b6b025f5d60cdf02104b9 | /tests/lean/run/rewriter6.lean | b5d3e7bd543e3e6ae1d129d3efa9418773acfabb | [
"Apache-2.0"
] | permissive | guiquanz/lean | b8a878ea24f237b84b0e6f6be2f300e8bf028229 | 242f8ba0486860e53e257c443e965a82ee342db3 | refs/heads/master | 1,526,680,092,098 | 1,427,492,833,000 | 1,427,493,281,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 353 | lean | import data.int
open int
theorem abs_thm1 (a b : int) : a - b = a + -b :=
by rewrite ↑sub -- unfold sub
theorem abs_thm2 (a b : int) : a - b = a + -b :=
by rewrite ^sub -- unfold sub
definition double (x : int) := x + x
theorem double_zero (x : int) : double (0 + x) = (1 + 1)*x :=
by rewrite ⟨↑double, zero_add, mul.right_distrib, one_mul⟩
|
477eca33cd0e35b9f60eb65937d256208b25c3c2 | b9def12ac9858ba514e44c0758ebb4e9b73ae5ed | /src/monoidal_categories_reboot/monoidal_category.lean | c4bf9fdae6ff84f891857de5cda276c2d2af803b | [
"Apache-2.0"
] | permissive | cipher1024/monoidal-categories-reboot | 5f826017db2f71920336331739a0f84be2f97bf7 | 998f2a0553c22369d922195dc20a20fa7dccc6e5 | refs/heads/master | 1,586,710,273,395 | 1,543,592,573,000 | 1,543,592,573,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,197 | lean | -- Copyright (c) 2018 Michael Jendrusch. All rights reserved.
import category_theory.category
import category_theory.functor
import category_theory.products
import category_theory.natural_isomorphism
import category_theory.tactics.obviously -- Give ourselves access to `rewrite_search`
import .slice_tactic
import .tensor_product
open category_theory
open category_theory.slice
open tactic
universes u v
open category_theory.category
open category_theory.functor
open category_theory.prod
open category_theory.functor.category.nat_trans
open category_theory.nat_iso
namespace category_theory.monoidal
class monoidal_category (C : Type u) extends category.{u v} C :=
-- curried tensor product of objects:
(tensor_obj : C → C → C)
-- curried tensor product of morphisms:
(tensor_hom : Π {X₁ Y₁ X₂ Y₂ : C}, hom X₁ Y₁ → hom X₂ Y₂ → hom (tensor_obj X₁ X₂) (tensor_obj Y₁ Y₂))
-- tensor product laws:
(tensor_map_id' : ∀ (X₁ X₂ : C), tensor_hom (𝟙 X₁) (𝟙 X₂) = 𝟙 (tensor_obj X₁ X₂) . obviously)
(tensor_map_comp' : ∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂),
tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) = (tensor_hom f₁ f₂) ≫ (tensor_hom g₁ g₂) . obviously)
-- tensor unit:
(tensor_unit : C)
-- associator:
(associator : Π X Y Z : C, (tensor_obj (tensor_obj X Y) Z) ≅ (tensor_obj X (tensor_obj Y Z)))
(associator_naturality' : assoc_natural tensor_obj @tensor_hom associator . obviously)
-- left unitor:
(left_unitor : Π X : C, tensor_obj tensor_unit X ≅ X)
(left_unitor_naturality' : left_unitor_natural tensor_obj @tensor_hom tensor_unit left_unitor . obviously)
-- right unitor:
(right_unitor : Π X : C, tensor_obj X tensor_unit ≅ X)
(right_unitor_naturality' : right_unitor_natural tensor_obj @tensor_hom tensor_unit right_unitor . obviously)
-- pentagon identity:
(pentagon' : pentagon @tensor_hom associator . obviously)
-- triangle identity:
(triangle' : triangle @tensor_hom left_unitor right_unitor associator . obviously)
restate_axiom monoidal_category.tensor_map_id'
attribute [simp,search] monoidal_category.tensor_map_id
restate_axiom monoidal_category.tensor_map_comp'
attribute [simp,search] monoidal_category.tensor_map_comp
restate_axiom monoidal_category.associator_naturality'
attribute [search] monoidal_category.associator_naturality
restate_axiom monoidal_category.left_unitor_naturality'
attribute [search] monoidal_category.left_unitor_naturality
restate_axiom monoidal_category.right_unitor_naturality'
attribute [search] monoidal_category.right_unitor_naturality
restate_axiom monoidal_category.pentagon'
attribute [search] monoidal_category.pentagon
restate_axiom monoidal_category.triangle'
attribute [search] monoidal_category.triangle
section
open monoidal_category
def one {C : Type u} [monoidal_category.{u v} C] (X : C) : X ≅ X :=
{ hom := 𝟙 X,
inv := 𝟙 X }
def tensor_iso {C : Type u} {X Y X' Y' : C} [monoidal_category.{u v} C] (f : X ≅ Y) (g : X' ≅ Y') :
tensor_obj X X' ≅ tensor_obj Y Y' :=
{ hom := tensor_hom f.hom g.hom,
inv := tensor_hom f.inv g.inv }
end
section
variables (C : Type u) [𝒞 : monoidal_category.{u v} C]
include 𝒞
open monoidal_category
infixr ` ⊗ `:80 := tensor_obj
infixr ` ⊗ `:80 := tensor_hom
infixr ` ⊗ `:80 := tensor_iso
@[reducible] def monoidal_category.tensor : (C × C) ⥤ C :=
{ obj := λ X, X.1 ⊗ X.2,
map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 }
variables {U V W X Y Z : C}
@[search] definition interchange (f : U ⟶ V) (g : V ⟶ W) (h : X ⟶ Y) (k : Y ⟶ Z)
: (f ≫ g) ⊗ (h ≫ k) = (f ⊗ h) ≫ (g ⊗ k) :=
tensor_map_comp C f h g k
@[simp,search] lemma interchange_left_identity (f : W ⟶ X) (g : X ⟶ Y) :
(f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) = (f ≫ g) ⊗ (𝟙 Z) :=
begin
rw ←interchange,
simp
end
@[simp,search] lemma interchange_right_identity (f : W ⟶ X) (g : X ⟶ Y) :
(𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) = (𝟙 Z) ⊗ (f ≫ g) :=
begin
rw ←interchange,
simp
end
@[search] lemma interchange_identities (f : W ⟶ X) (g : Y ⟶ Z) :
((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = (g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) :=
begin
rw ←interchange,
rw ←interchange,
simp
end
open monoidal_category
@[reducible] def monoidal_category.left_assoc_functor : (C × C × C) ⥤ C :=
{ obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2,
map := λ {X Y : C × C × C} (f : X ⟶ Y),
(f.1 ⊗ f.2.1) ⊗ f.2.2 }
@[reducible] def monoidal_category.right_assoc_functor : (C × C × C) ⥤ C :=
{ obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2),
map := λ {X Y : C × C × C} (f : X ⟶ Y),
f.1 ⊗ (f.2.1 ⊗ f.2.2) }
@[reducible] def monoidal_category.left_unitor_functor : C ⥤ C :=
{ obj := λ X, tensor_unit C ⊗ X,
map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (tensor_unit C)) ⊗ f }
@[reducible] def monoidal_category.right_unitor_functor : C ⥤ C :=
{ obj := λ X, X ⊗ tensor_unit C,
map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (tensor_unit C)) }
open monoidal_category
-- natural isomorphisms for the associator and unitors.
@[reducible] def monoidal_category.associator_nat_iso :
left_assoc_functor C ≅ right_assoc_functor C :=
nat_iso.of_components
(by intros; simp; apply associator)
(by intros; simp; apply associator_naturality)
@[reducible] def monoidal_category.left_unitor_nat_iso :
left_unitor_functor C ≅ functor.id C :=
nat_iso.of_components
(by intros; simp; apply left_unitor)
(by intros; simp; apply left_unitor_naturality)
@[reducible] def monoidal_category.right_unitor_nat_iso :
right_unitor_functor C ≅ functor.id C :=
nat_iso.of_components
(by intros; simp; apply right_unitor)
(by intros; simp; apply right_unitor_naturality)
instance tensor_iso_of_iso
{X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y')
[is_iso f] [is_iso g] : is_iso (f ⊗ g) :=
{ inv := (is_iso.inv f) ⊗ (is_iso.inv g) }
@[simp,search] lemma tensor_left_equiv
{X Y : C} (f g : X ⟶ Y) :
((𝟙 (tensor_unit C)) ⊗ f = (𝟙 (tensor_unit C)) ⊗ g) ↔ (f = g) :=
sorry
@[simp,search] lemma tensor_right_equiv
{X Y : C} (f g : X ⟶ Y) :
(f ⊗ (𝟙 (tensor_unit C)) = g ⊗ (𝟙 (tensor_unit C))) ↔ (f = g) :=
sorry
-- proof following the nLab:
@[search] lemma left_unitor_product_aux_perimeter (X Y : C) :
((associator (tensor_unit C) (tensor_unit C) X).hom ⊗ (𝟙 Y)) ≫
(associator (tensor_unit C) ((tensor_unit C) ⊗ X) Y).hom ≫
((𝟙 (tensor_unit C)) ⊗ (associator (tensor_unit C) X Y).hom) ≫
((𝟙 (tensor_unit C)) ⊗ (left_unitor (X ⊗ Y)).hom)
= (((right_unitor (tensor_unit C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y)) ≫
(associator (tensor_unit C) X Y).hom := by obviously
@[search] lemma left_unitor_product_aux_triangle (X Y : C) :
((associator (tensor_unit C) (tensor_unit C) X).hom ⊗ (𝟙 Y)) ≫
(((𝟙 (tensor_unit C)) ⊗ (left_unitor X).hom) ⊗ (𝟙 Y))
= ((right_unitor (tensor_unit C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y) := by obviously
@[search] lemma left_unitor_product_aux_square (X Y : C) :
(associator (tensor_unit C) ((tensor_unit C) ⊗ X) Y).hom ≫
((𝟙 (tensor_unit C)) ⊗ (left_unitor X).hom ⊗ (𝟙 Y))
= (((𝟙 (tensor_unit C)) ⊗ (left_unitor X).hom) ⊗ (𝟙 Y)) ≫
(associator (tensor_unit C) X Y).hom := by obviously
@[search] lemma left_unitor_product_aux (X Y : C) :
((𝟙 (tensor_unit C)) ⊗ (associator (tensor_unit C) X Y).hom) ≫
((𝟙 (tensor_unit C)) ⊗ (left_unitor (X ⊗ Y)).hom)
= (𝟙 (tensor_unit C)) ⊗ ((left_unitor X).hom ⊗ (𝟙 Y)) :=
begin
rw <-(cancel_epi (associator (tensor_unit C) ((tensor_unit C) ⊗ X) Y).hom),
rw left_unitor_product_aux_square,
rw <-(cancel_epi ((associator (tensor_unit C) (tensor_unit C) X).hom ⊗ (𝟙 Y))),
conv {
to_rhs,
slice 1 2,
rw left_unitor_product_aux_triangle,
},
obviously
end
@[search] lemma right_unitor_product_aux_perimeter (X Y : C) :
((associator X Y (tensor_unit C)).hom ⊗ (𝟙 (tensor_unit C))) ≫
(associator X (Y ⊗ (tensor_unit C)) (tensor_unit C)).hom ≫
((𝟙 X) ⊗ (associator Y (tensor_unit C) (tensor_unit C)).hom) ≫
((𝟙 X) ⊗ (𝟙 Y) ⊗ (left_unitor (tensor_unit C)).hom)
= ((right_unitor (X ⊗ Y)).hom ⊗ (𝟙 (tensor_unit C))) ≫
(associator X Y (tensor_unit C)).hom := by obviously
@[search] lemma right_unitor_product_aux_triangle (X Y : C) :
((𝟙 X) ⊗ (associator Y (tensor_unit C) (tensor_unit C)).hom) ≫
((𝟙 X) ⊗ (𝟙 Y) ⊗ (left_unitor (tensor_unit C)).hom)
= (𝟙 X) ⊗ (right_unitor Y).hom ⊗ (𝟙 (tensor_unit C)) := by obviously
@[search] lemma right_unitor_product_aux_square (X Y : C) :
(associator X (Y ⊗ (tensor_unit C)) (tensor_unit C)).hom ≫
((𝟙 X) ⊗ (right_unitor Y).hom ⊗ (𝟙 (tensor_unit C)))
= (((𝟙 X) ⊗ (right_unitor Y).hom) ⊗ (𝟙 (tensor_unit C))) ≫
(associator X Y (tensor_unit C)).hom := by obviously
@[search] lemma right_unitor_product_aux (X Y : C) :
((associator X Y (tensor_unit C)).hom ⊗ (𝟙 (tensor_unit C))) ≫
(((𝟙 X) ⊗ (right_unitor Y).hom) ⊗ (𝟙 (tensor_unit C)))
= ((right_unitor (X ⊗ Y)).hom ⊗ (𝟙 (tensor_unit C))) :=
begin
rw <-(cancel_mono (associator X Y (tensor_unit C)).hom),
conv {
to_lhs,
slice 2 3,
rw <-right_unitor_product_aux_square,
},
obviously
end
@[search] lemma left_unitor_product (X Y : C) :
((associator (tensor_unit C) X Y).hom) ≫
((left_unitor (X ⊗ Y)).hom)
= ((left_unitor X).hom ⊗ (𝟙 Y)) :=
begin
rw <-tensor_left_equiv,
rw <-interchange_right_identity,
apply left_unitor_product_aux
end
@[search] lemma right_unitor_product (X Y : C) :
((associator X Y (tensor_unit C)).hom) ≫
((𝟙 X) ⊗ (right_unitor Y).hom)
= ((right_unitor (X ⊗ Y)).hom) :=
begin
rw <-tensor_right_equiv,
rw <-interchange_left_identity,
apply right_unitor_product_aux
end
end
end category_theory.monoidal
|
d70910fc0bcfe7131226659a1efa5701b9d8f5af | 439bc6c3e74a118aa51df633b8e1f24415804d86 | /site.lean | 645b42b516b7156dbe6f9c367a2646bbd5ac7e6e | [] | no_license | jcommelin/lt2019_slides | 4ca498db02b5187c5778c21b985126d52d260696 | 3234cd92920d3d4321cc2cef78b48e5fa55be413 | refs/heads/master | 1,586,718,101,957 | 1,546,930,855,000 | 1,546,930,855,000 | 162,697,592 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 74 | lean | class site (X : Type u) extends category.{u} X :=
(coverage : coverage X)
|
da847eee87aae67ea38e8e418e040417f1f6b77a | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/topology/homeomorph.lean | ef677042b1a6c3ec4e64ee5f1bdb43b37303111c | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 7,440 | lean | /-
Copyright (c) 2019 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import topology.dense_embedding
open set
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- α and β are homeomorph, also called topological isomoph -/
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun)
(continuous_inv_fun : continuous inv_fun)
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
lemma coe_eq_to_equiv (h : α ≃ₜ β) (a : α) : h a = h.to_equiv a := rfl
/-- Identity map is a homeomorphism. -/
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
.. equiv.trans h₁.to_equiv h₂.to_equiv }
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
.. h.to_equiv.symm }
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext $ assume a, h.to_equiv.left_inv a
lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext $ assume a, h.to_equiv.right_inv a
lemma range_coe (h : α ≃ₜ β) : range h = univ :=
eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
lemma induced_eq
{α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) :
tβ.induced h = tα :=
le_antisymm
(calc topological_space.induced ⇑h tβ ≤ _ : induced_mono (coinduced_le_iff_le_induced.1 h.symm.continuous)
... ≤ tα : by rw [induced_compose, symm_comp_self, induced_id] ; exact le_refl _)
(coinduced_le_iff_le_induced.1 h.continuous)
lemma coinduced_eq
{α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (h : α ≃ₜ β) :
tα.coinduced h = tβ :=
le_antisymm
h.continuous
begin
have : (tβ.coinduced h.symm).coinduced h ≤ tα.coinduced h := coinduced_mono h.symm.continuous,
rwa [coinduced_compose, self_comp_symm, coinduced_id] at this,
end
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨⟨h.induced_eq.symm⟩, h.to_equiv.injective⟩
lemma compact_image {s : set α} (h : α ≃ₜ β) : compact (h '' s) ↔ compact s :=
h.embedding.compact_iff_compact_image.symm
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : compact (h ⁻¹' s) ↔ compact s :=
by rw ← image_symm; exact h.symm.compact_image
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := assume a, by rw [h.range_coe, closure_univ]; trivial,
inj := h.to_equiv.injective,
induced := (induced_iff_nhds_eq _).2 (assume a, by rw [← nhds_induced, h.induced_eq]) }
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h :=
begin
assume s,
rw ← h.preimage_symm,
exact h.symm.continuous s
end
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h :=
begin
assume s,
rw ← h.preimage_symm,
exact continuous_iff_is_closed.1 (h.symm.continuous) _
end
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
.. e }
lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
begin
split,
{ assume H,
have : continuous_on (h.symm ∘ (h ∘ f)) s :=
h.symm.continuous.comp_continuous_on H,
rwa [← function.comp.assoc h.symm h f, symm_comp_self h] at this },
{ exact λ H, h.continuous.comp_continuous_on H }
end
lemma comp_continuous_iff (h : α ≃ₜ β) (f : γ → α) :
continuous (h ∘ f) ↔ continuous f :=
by simp [continuous_iff_continuous_on_univ, comp_continuous_on_iff]
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
⟨h.to_equiv.surjective, h.coinduced_eq.symm⟩
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val,
continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val,
.. equiv.set_congr h }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun :=
continuous.prod_mk (h₁.continuous.comp continuous_fst) (h₂.continuous.comp continuous_snd),
continuous_inv_fun :=
continuous.prod_mk (h₁.symm.continuous.comp continuous_fst) (h₂.symm.continuous.comp continuous_snd),
.. h₁.to_equiv.prod_congr h₂.to_equiv }
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous.prod_mk continuous_snd continuous_fst,
continuous_inv_fun := continuous.prod_mk continuous_snd continuous_fst,
.. equiv.prod_comm α β }
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun :=
continuous.prod_mk (continuous_fst.comp continuous_fst)
(continuous.prod_mk (continuous_snd.comp continuous_fst) continuous_snd),
continuous_inv_fun := continuous.prod_mk
(continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd))
(continuous_snd.comp continuous_snd),
.. equiv.prod_assoc α β γ }
end
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
.. equiv.ulift }
section distrib
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $
homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i,
continuous.prod_mk (continuous_sigma_mk.comp continuous_fst) continuous_snd)
(is_open_map_sigma $ λ i,
(open_embedding.prod open_embedding_sigma_mk open_embedding_id).is_open_map)
end distrib
end homeomorph
|
64a96af856e1945af2b138b4e335458f0e2fdfa3 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/probability/conditional_probability.lean | 83f94ecabc3cad53edacdad078e6c45826213b92 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 6,649 | lean | /-
Copyright (c) 2022 Rishikesh Vaishnav. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rishikesh Vaishnav
-/
import probability.independence
/-!
# Conditional Probability
This file defines conditional probability and includes basic results relating to it.
Given some measure `μ` defined on a measure space on some type `Ω` and some `s : set Ω`,
we define the measure of `μ` conditioned on `s` as the restricted measure scaled by
the inverse of the measure of `s`: `cond μ s = (μ s)⁻¹ • μ.restrict s`. The scaling
ensures that this is a probability measure (when `μ` is a finite measure).
From this definition, we derive the "axiomatic" definition of conditional probability
based on application: for any `s t : set Ω`, we have `μ[t|s] = (μ s)⁻¹ * μ (s ∩ t)`.
## Main Statements
* `cond_cond_eq_cond_inter`: conditioning on one set and then another is equivalent
to conditioning on their intersection.
* `cond_eq_inv_mul_cond_mul`: Bayes' Theorem, `μ[t|s] = (μ s)⁻¹ * μ[s|t] * (μ t)`.
## Notations
This file uses the notation `μ[|s]` the measure of `μ` conditioned on `s`,
and `μ[t|s]` for the probability of `t` given `s` under `μ` (equivalent to the
application `μ[|s] t`).
These notations are contained in the locale `probability_theory`.
## Implementation notes
Because we have the alternative measure restriction application principles
`measure.restrict_apply` and `measure.restrict_apply'`, which require
measurability of the restricted and restricting sets, respectively,
many of the theorems here will have corresponding alternatives as well.
For the sake of brevity, we've chosen to only go with `measure.restrict_apply'`
for now, but the alternative theorems can be added if needed.
Use of `@[simp]` generally follows the rule of removing conditions on a measure
when possible.
Hypotheses that are used to "define" a conditional distribution by requiring that
the conditioning set has non-zero measure should be named using the abbreviation
"c" (which stands for "conditionable") rather than "nz". For example `(hci : μ (s ∩ t) ≠ 0)`
(rather than `hnzi`) should be used for a hypothesis ensuring that `μ[|s ∩ t]` is defined.
## Tags
conditional, conditioned, bayes
-/
noncomputable theory
open_locale ennreal
open measure_theory measurable_space
variables {Ω : Type*} {m : measurable_space Ω} (μ : measure Ω) {s t : set Ω}
namespace probability_theory
section definitions
/-- The conditional probability measure of measure `μ` on set `s` is `μ` restricted to `s`
and scaled by the inverse of `μ s` (to make it a probability measure):
`(μ s)⁻¹ • μ.restrict s`. -/
def cond (s : set Ω) : measure Ω :=
(μ s)⁻¹ • μ.restrict s
end definitions
localized "notation (name := probability_theory.cond)
μ `[` s `|` t `]` := probability_theory.cond μ t s" in probability_theory
localized "notation (name := probability_theory.cond_fn)
μ `[|`:60 t`]` := probability_theory.cond μ t" in probability_theory
/-- The conditional probability measure of any finite measure on any set of positive measure
is a probability measure. -/
lemma cond_is_probability_measure [is_finite_measure μ] (hcs : μ s ≠ 0) :
is_probability_measure $ μ[|s] :=
⟨by { rw [cond, measure.smul_apply, measure.restrict_apply measurable_set.univ,
set.univ_inter], exact ennreal.inv_mul_cancel hcs (measure_ne_top _ s) }⟩
section bayes
@[simp] lemma cond_empty : μ[|∅] = 0 :=
by simp [cond]
@[simp] lemma cond_univ [is_probability_measure μ] :
μ[|set.univ] = μ :=
by simp [cond, measure_univ, measure.restrict_univ]
/-- The axiomatic definition of conditional probability derived from a measure-theoretic one. -/
lemma cond_apply (hms : measurable_set s) (t : set Ω) :
μ[t|s] = (μ s)⁻¹ * μ (s ∩ t) :=
by { rw [cond, measure.smul_apply, measure.restrict_apply' hms, set.inter_comm], refl }
lemma cond_inter_self (hms : measurable_set s) (t : set Ω) :
μ[s ∩ t|s] = μ[t|s] :=
by rw [cond_apply _ hms, ← set.inter_assoc, set.inter_self, ← cond_apply _ hms]
lemma inter_pos_of_cond_ne_zero (hms : measurable_set s) (hcst : μ[t|s] ≠ 0) :
0 < μ (s ∩ t) :=
begin
refine pos_iff_ne_zero.mpr (right_ne_zero_of_mul _),
{ exact (μ s)⁻¹ },
convert hcst,
simp [hms, set.inter_comm]
end
lemma cond_pos_of_inter_ne_zero [is_finite_measure μ]
(hms : measurable_set s) (hci : μ (s ∩ t) ≠ 0) :
0 < μ[|s] t :=
begin
rw cond_apply _ hms,
refine ennreal.mul_pos _ hci,
exact ennreal.inv_ne_zero.mpr (measure_ne_top _ _),
end
lemma cond_cond_eq_cond_inter'
(hms : measurable_set s) (hmt : measurable_set t) (hcs : μ s ≠ ∞) (hci : μ (s ∩ t) ≠ 0) :
μ[|s][|t] = μ[|s ∩ t] :=
begin
have hcs : μ s ≠ 0 := (μ.to_outer_measure.pos_of_subset_ne_zero
(set.inter_subset_left _ _) hci).ne',
ext u,
simp [*, hms.inter hmt, cond_apply, ← mul_assoc, ← set.inter_assoc,
ennreal.mul_inv, mul_comm, ← mul_assoc, ennreal.inv_mul_cancel],
end
/-- Conditioning first on `s` and then on `t` results in the same measure as conditioning
on `s ∩ t`. -/
lemma cond_cond_eq_cond_inter [is_finite_measure μ]
(hms : measurable_set s) (hmt : measurable_set t) (hci : μ (s ∩ t) ≠ 0) :
μ[|s][|t] = μ[|s ∩ t] :=
cond_cond_eq_cond_inter' μ hms hmt (measure_ne_top μ s) hci
lemma cond_mul_eq_inter'
(hms : measurable_set s) (hcs : μ s ≠ 0) (hcs' : μ s ≠ ∞) (t : set Ω) :
μ[t|s] * μ s = μ (s ∩ t) :=
by rw [cond_apply μ hms t, mul_comm, ←mul_assoc,
ennreal.mul_inv_cancel hcs hcs', one_mul]
lemma cond_mul_eq_inter [is_finite_measure μ]
(hms : measurable_set s) (hcs : μ s ≠ 0) (t : set Ω) :
μ[t|s] * μ s = μ (s ∩ t) :=
cond_mul_eq_inter' μ hms hcs (measure_ne_top _ s) t
/-- A version of the law of total probability. -/
lemma cond_add_cond_compl_eq [is_finite_measure μ]
(hms : measurable_set s) (hcs : μ s ≠ 0) (hcs' : μ sᶜ ≠ 0) :
μ[t|s] * μ s + μ[t|sᶜ] * μ sᶜ = μ t :=
begin
rw [cond_mul_eq_inter μ hms hcs, cond_mul_eq_inter μ hms.compl hcs', set.inter_comm _ t,
set.inter_comm _ t],
exact measure_inter_add_diff t hms,
end
/-- **Bayes' Theorem** -/
theorem cond_eq_inv_mul_cond_mul [is_finite_measure μ]
(hms : measurable_set s) (hmt : measurable_set t) :
μ[t|s] = (μ s)⁻¹ * μ[s|t] * (μ t) :=
begin
by_cases ht : μ t = 0,
{ simp [cond, ht, measure.restrict_apply hmt, or.inr (measure_inter_null_of_null_left s ht)] },
{ rw [mul_assoc, cond_mul_eq_inter μ hmt ht s, set.inter_comm, cond_apply _ hms] }
end
end bayes
end probability_theory
|
fe49d4987a972d308431685f04ee64dace654772 | 3863d2564418bccb1859e057bf5a4ef240e75fd7 | /hott/homotopy/red_susp.hlean | b46b65a3d456a79571352a261d09fba886b43ba5 | [
"Apache-2.0"
] | permissive | JacobGross/lean | 118bbb067ff4d4af48a266face2c7eb9868fa91c | eb26087df940c54337cb807b4bc6d345d1fc1085 | refs/heads/master | 1,582,735,011,532 | 1,462,557,826,000 | 1,462,557,826,000 | 46,451,196 | 0 | 0 | null | 1,462,557,826,000 | 1,447,885,161,000 | C++ | UTF-8 | Lean | false | false | 2,771 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Declaration of the reduced suspension
-/
import hit.two_quotient types.pointed algebra.e_closure
open simple_two_quotient eq unit pointed e_closure
namespace red_susp
section
parameter {A : pType}
inductive red_susp_R : unit → unit → Type :=
| Rmk : Π(a : A), red_susp_R star star
open red_susp_R
inductive red_susp_Q : Π⦃x : unit⦄, e_closure red_susp_R x x → Type :=
| Qmk : red_susp_Q [Rmk pt]
open red_susp_Q
local abbreviation R := red_susp_R
local abbreviation Q := red_susp_Q
definition red_susp : Type := simple_two_quotient R Q -- TODO: define this in root namespace
definition base : red_susp :=
incl0 R Q star
definition merid (a : A) : base = base :=
incl1 R Q (Rmk a)
definition merid_pt : merid pt = idp :=
incl2 R Q Qmk
-- protected definition rec {P : red_susp → Type} (Pb : P base) (Pm : Π(a : A), Pb =[merid a] Pb)
-- (Pe : Pm pt =[merid_pt] idpo) (x : red_susp) : P x :=
-- begin
-- induction x,
-- end
-- protected definition rec_on [reducible] {P : red_susp → Type} (x : red_susp) (Pb : P base)
-- (Pm : Π(a : A), Pb =[merid a] Pb) (Pe : Pm pt =[merid_pt] idpo) : P x :=
-- rec Pb Pm Pe x
-- definition rec_merid {P : red_susp → Type} (Pb : P base) (Pm : Π(a : A), Pb =[merid a] Pb)
-- (Pe : Pm pt =[merid_pt] idpo) (a : A)
-- : apd (rec Pb Pm Pe) (merid a) = Pm a :=
-- !rec_incl1
-- theorem elim_merid_pt {P : red_susp → Type} (Pb : P base) (Pm : Π(a : A), Pb =[merid a] Pb)
-- (Pe : Pm pt =[merid_pt] idpo)
-- : square (ap02 (rec Pb Pm Pe) merid_pt) Pe (rec_merid Pe pt) idp :=
-- !rec_incl2
protected definition elim {P : Type} (Pb : P) (Pm : Π(a : A), Pb = Pb)
(Pe : Pm pt = idp) (x : red_susp) : P :=
begin
induction x,
exact Pb,
induction s, exact Pm a,
induction q, exact Pe
end
protected definition elim_on [reducible] {P : Type} (x : red_susp) (Pb : P)
(Pm : Π(a : A), Pb = Pb) (Pe : Pm pt = idp) : P :=
elim Pb Pm Pe x
definition elim_merid {P : Type} {Pb : P} {Pm : Π(a : A), Pb = Pb}
(Pe : Pm pt = idp) (a : A)
: ap (elim Pb Pm Pe) (merid a) = Pm a :=
!elim_incl1
theorem elim_merid_pt {P : Type} (Pb : P) (Pm : Π(a : A), Pb = Pb)
(Pe : Pm pt = idp) : square (ap02 (elim Pb Pm Pe) merid_pt) Pe (elim_merid Pe pt) idp :=
!elim_incl2
end
end red_susp
attribute red_susp.base [constructor]
attribute /-red_susp.rec-/ red_susp.elim [unfold 6] [recursor 6]
--attribute red_susp.elim_type [unfold 9]
attribute /-red_susp.rec_on-/ red_susp.elim_on [unfold 3]
--attribute red_susp.elim_type_on [unfold 6]
|
9979b49691568383f9919722d4f8bc4c4a895f37 | 4b846d8dabdc64e7ea03552bad8f7fa74763fc67 | /library/tools/mini_crush/nano_crush.lean | 3651e09cf3acbc8792e0da3d214b351056c07610 | [
"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 | 3,882 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
We implement a crush-like strategy using simplifier,
SMT gadgets, and robust simplifier.
This is just a demo.
-/
namespace nano_crush
open tactic
meta def size (e : expr) : nat :=
e^.fold 1 (λ e _ n, n+1)
/- Collect relevant functions -/
meta def is_auto_construction : name → bool
| (name.mk_string "brec_on" p) := tt
| (name.mk_string "cases_on" p) := tt
| (name.mk_string "rec_on" p) := tt
| (name.mk_string "no_confusion" p) := tt
| (name.mk_string "below" p) := tt
| _ := ff
meta def is_relevant_fn (n : name) : tactic bool :=
do env ← get_env,
if ¬env^.is_definition n ∨ is_auto_construction n then return ff
else if env^.in_current_file n then return tt
else in_open_namespaces n
meta def collect_revelant_fns_aux : name_set → expr → tactic name_set
| s e :=
e^.mfold s $ λ t _ s,
match t with
| expr.const c _ :=
if s^.contains c then return s
else mcond (is_relevant_fn c)
(do new_s ← return $ if c^.is_internal then s else s^.insert c,
d ← get_decl c,
collect_revelant_fns_aux new_s d^.value)
(return s)
| _ := return s
end
meta def collect_revelant_fns : tactic name_set :=
do ctx ← local_context,
s₁ ← ctx^.mfoldl (λ s e, infer_type e >>= collect_revelant_fns_aux s) mk_name_set,
target >>= collect_revelant_fns_aux s₁
meta def add_relevant_eqns (hs : hinst_lemmas) : tactic hinst_lemmas :=
do fns ← collect_revelant_fns,
fns^.mfold hs (λ fn hs, get_eqn_lemmas_for tt fn >>= mfoldl (λ hs d, hs^.add <$> hinst_lemma.mk_from_decl d) hs)
/- Collect terms that are inductive datatypes -/
meta def is_inductive (e : expr) : tactic bool :=
do type ← infer_type e,
C ← return type^.get_app_fn,
env ← get_env,
return $ C^.is_constant && env^.is_inductive C^.const_name
open expr
meta def collect_inductive_aux : expr_set → expr → tactic expr_set
| S e :=
if S^.contains e then return S
else do
new_S ← mcond (is_inductive e) (return $ S^.insert e) (return S),
match e with
| app _ _ := fold_explicit_args e new_S collect_inductive_aux
| pi _ _ d b := if e^.is_arrow then collect_inductive_aux S d >>= flip collect_inductive_aux b else return new_S
| _ := return new_S
end
meta def collect_inductive : expr → tactic expr_set :=
collect_inductive_aux mk_expr_set
open list
meta def collect_inductive_from_target : tactic (list expr) :=
do S ← target >>= collect_inductive,
return $ qsort ((<) on size) S^.to_list
meta def collect_inductive_hyps : tactic (list expr) :=
local_context >>= mfoldl (λ r h, mcond (is_inductive h) (return $ h::r) (return r)) []
/- Induction -/
meta def try_list_aux {α} (s : tactic_state) (tac : α → tactic unit) : list α → tactic unit
| [] := failed
| (e::es) := (write s >> tac e >> now) <|> try_list_aux es
meta def try_list {α} (tac : α → tactic unit) (es : list α) : tactic unit :=
do s ← read, try_list_aux s tac es
meta def induct (tac : tactic unit) : tactic unit :=
collect_inductive_hyps >>= try_list (λ e, induction' e; tac)
meta def split (tac : tactic unit) : tactic unit :=
collect_inductive_from_target >>= try_list (λ e, cases e; tac)
meta def search (tac : tactic unit) : nat → tactic unit
| 0 := all_goals tac >> now
| (d+1) := all_goals (try tac) >> (now <|> split (search d))
meta def rsimp' (hs : hinst_lemmas) : tactic unit :=
rsimp {} hs
meta def mk_relevant_lemmas : tactic hinst_lemmas :=
add_relevant_eqns hinst_lemmas.mk
end nano_crush
open tactic nano_crush
meta def nano_crush (depth : nat := 1) :=
do hs ← mk_relevant_lemmas,
induct $ search (rsimp' hs) depth
|
76e17ede16774c5521fb9bb67e38c6b4dd440ee9 | 6065973b1fa7bbacba932011c9e2f32bf7bdd6c1 | /src/measure_theory/pi.lean | ea8e0c2845a7bf97c0ea204ead21ef03160b51f5 | [
"Apache-2.0"
] | permissive | khmacdonald/mathlib | 90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb | 3669cb35c578441812ad30fd967d21a94b6f387e | refs/heads/master | 1,675,863,801,090 | 1,609,761,876,000 | 1,609,761,876,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,576 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.prod
/-!
# Product measures
In this file we define and prove properties about finite products of measures
(and at some point, countable products of measures).
## Main definition
* `measure_theory.measure.pi`: The product of finitely many σ-finite measures.
Given `μ : Π i : ι, measure (α i)` for `[fintype ι]` it has type `measure (Π i : ι, α i)`.
## Implementation Notes
We define `measure_theory.outer_measure.pi`, the product of finitely many outer measures, as the
maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`,
where `pi univ s` is the product of the sets `{ s i | i : ι }`.
We then show that this induces a product of measures, called `measure_theory.measure.pi`.
For a collection of σ-finite measures `μ` and a collection of measurable sets `s` we show that
`measure.pi μ (pi univ s) = ∏ i, m i (s i)`. To do this, we follow the following steps:
* We know that there is some ordering on `ι`, given by an element of `[encodable ι]`.
* Using this, we have an equivalence `measurable_equiv.pi_measurable_equiv_tprod` between
`Π ι, α i` and an iterated product of `α i`, called `list.tprod α l` for some list `l`.
* On this iterated product we can easily define a product measure `measure_theory.measure.tprod`
by iterating `measure_theory.measure.prod`
* Using the previous two steps we construct `measure_theory.measure.pi'` on `Π ι, α i` for encodable
`ι`.
* We know that `measure_theory.measure.pi'` sends products of sets to products of measures, and
since `measure_theory.measure.pi` is the maximal such measure (or at least, it comes from an outer
measure which is the maximal such outer measure), we get the same rule for
`measure_theory.measure.pi`.
## Tags
finitary product measure
-/
noncomputable theory
open function set measure_theory.outer_measure
open_locale classical big_operators
namespace measure_theory
variables {ι : Type*} [fintype ι] {α : ι → Type*} {m : Π i, outer_measure (α i)}
/-- An upper bound for the measure in a finite product space.
It is defined to by taking the image of the set under all projections, and taking the product
of the measures of these images.
For measurable boxes it is equal to the correct measure. -/
@[simp] def pi_premeasure (m : Π i, outer_measure (α i)) (s : set (Π i, α i)) : ennreal :=
∏ i, m i (eval i '' s)
lemma pi_premeasure_pi {s : Π i, set (α i)} (hs : (pi univ s).nonempty) :
pi_premeasure m (pi univ s) = ∏ i, m i (s i) :=
by simp [hs]
lemma pi_premeasure_pi' [nonempty ι] {s : Π i, set (α i)} :
pi_premeasure m (pi univ s) = ∏ i, m i (s i) :=
begin
cases (pi univ s).eq_empty_or_nonempty with h h,
{ rcases univ_pi_eq_empty_iff.mp h with ⟨i, hi⟩,
have : ∃ i, m i (s i) = 0 := ⟨i, by simp [hi]⟩,
simpa [h, finset.card_univ, zero_pow (fintype.card_pos_iff.mpr _inst_2),
@eq_comm _ (0 : ennreal), finset.prod_eq_zero_iff] },
{ simp [h] }
end
lemma pi_premeasure_pi_mono {s t : set (Π i, α i)} (h : s ⊆ t) :
pi_premeasure m s ≤ pi_premeasure m t :=
finset.prod_le_prod' (λ i _, (m i).mono' (image_subset _ h))
lemma pi_premeasure_pi_eval [nonempty ι] {s : set (Π i, α i)} :
pi_premeasure m (pi univ (λ i, eval i '' s)) = pi_premeasure m s :=
by simp [pi_premeasure_pi']
namespace outer_measure
/-- `outer_measure.pi m` is the finite product of the outer measures `{m i | i : ι}`.
It is defined to be the maximal outer measure `n` with the property that
`n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets
`{ s i | i : ι }`. -/
protected def pi (m : Π i, outer_measure (α i)) : outer_measure (Π i, α i) :=
bounded_by (pi_premeasure m)
lemma pi_pi_le (m : Π i, outer_measure (α i)) (s : Π i, set (α i)) :
outer_measure.pi m (pi univ s) ≤ ∏ i, m i (s i) :=
by { cases (pi univ s).eq_empty_or_nonempty with h h, simp [h],
exact (bounded_by_le _).trans_eq (pi_premeasure_pi h) }
lemma le_pi {m : Π i, outer_measure (α i)} {n : outer_measure (Π i, α i)} :
n ≤ outer_measure.pi m ↔ ∀ (s : Π i, set (α i)), (pi univ s).nonempty →
n (pi univ s) ≤ ∏ i, m i (s i) :=
begin
rw [outer_measure.pi, le_bounded_by'], split,
{ intros h s hs, refine (h _ hs).trans_eq (pi_premeasure_pi hs) },
{ intros h s hs, refine le_trans (n.mono $ subset_pi_eval_image univ s) (h _ _),
simp [univ_pi_nonempty_iff, hs] }
end
end outer_measure
namespace measure
variables [Π i, measurable_space (α i)] (μ : Π i, measure (α i))
section tprod
open list
variables {δ : Type*} {π : δ → Type*} [∀ x, measurable_space (π x)]
/-- A product of measures in `tprod α l`. -/
-- for some reason the equation compiler doesn't like this definition
protected def tprod (l : list δ) (μ : Π i, measure (π i)) : measure (tprod π l) :=
by { induction l with i l ih, exact dirac punit.star, exact (μ i).prod ih }
@[simp] lemma tprod_nil (μ : Π i, measure (π i)) : measure.tprod [] μ = dirac punit.star := rfl
@[simp] lemma tprod_cons (i : δ) (l : list δ) (μ : Π i, measure (π i)) :
measure.tprod (i :: l) μ = (μ i).prod (measure.tprod l μ) := rfl
instance sigma_finite_tprod (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)] :
sigma_finite (measure.tprod l μ) :=
begin
induction l with i l ih,
{ rw [tprod_nil], apply_instance },
{ rw [tprod_cons], resetI, apply_instance }
end
lemma tprod_tprod (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)]
{s : Π i, set (π i)} (hs : ∀ i, is_measurable (s i)) :
measure.tprod l μ (set.tprod l s) = (l.map (λ i, (μ i) (s i))).prod :=
begin
induction l with i l ih, { simp },
simp_rw [tprod_cons, set.tprod, prod_prod (hs i) (is_measurable.tprod l hs), map_cons,
prod_cons, ih]
end
lemma tprod_tprod_le (l : list δ) (μ : Π i, measure (π i)) [∀ i, sigma_finite (μ i)]
(s : Π i, set (π i)) : measure.tprod l μ (set.tprod l s) ≤ (l.map (λ i, (μ i) (s i))).prod :=
begin
induction l with i l ih, { simp [le_refl] },
simp_rw [tprod_cons, set.tprod, map_cons, prod_cons],
refine (prod_prod_le _ _).trans _, exact ennreal.mul_left_mono ih
end
end tprod
section encodable
open list measurable_equiv
variables [encodable ι]
/-- The product measure on an encodable finite type, defined by mapping `measure.tprod` along the
equivalence `measurable_equiv.pi_measurable_equiv_tprod`.
The definition `measure_theory.measure.pi` should be used instead of this one. -/
def pi' : measure (Π i, α i) :=
measure.map (tprod.elim' encodable.mem_sorted_univ) (measure.tprod (encodable.sorted_univ ι) μ)
lemma pi'_pi [∀ i, sigma_finite (μ i)] {s : Π i, set (α i)}
(hs : ∀ i, is_measurable (s i)) : pi' μ (pi univ s) = ∏ i, μ i (s i) :=
begin
have hl := λ i : ι, encodable.mem_sorted_univ i,
have hnd := @encodable.sorted_univ_nodup ι _ _,
rw [pi', map_apply (measurable_tprod_elim' hl) (is_measurable.pi_fintype (λ i _, hs i)),
elim_preimage_pi hnd, tprod_tprod _ μ hs, ← list.prod_to_finset _ hnd],
congr' with i, simp [hl]
end
lemma pi'_pi_le [∀ i, sigma_finite (μ i)] {s : Π i, set (α i)} :
pi' μ (pi univ s) ≤ ∏ i, μ i (s i) :=
begin
have hl := λ i : ι, encodable.mem_sorted_univ i,
have hnd := @encodable.sorted_univ_nodup ι _ _,
apply ((pi_measurable_equiv_tprod hnd hl).symm.map_apply (pi univ s)).trans_le,
dsimp only [pi_measurable_equiv_tprod, tprod.pi_equiv_tprod, coe_symm_mk, equiv.coe_fn_symm_mk],
rw [elim_preimage_pi hnd],
refine (tprod_tprod_le _ _ _).trans_eq _,
rw [← list.prod_to_finset _ hnd],
congr' with i, simp [hl]
end
end encodable
lemma pi_caratheodory :
measurable_space.pi ≤ (outer_measure.pi (λ i, (μ i).to_outer_measure)).caratheodory :=
begin
refine supr_le _,
intros i s hs,
rw [measurable_space.comap] at hs,
rcases hs with ⟨s, hs, rfl⟩,
apply bounded_by_caratheodory,
intro t,
simp_rw [pi_premeasure],
refine finset.prod_add_prod_le' (finset.mem_univ i) _ _ _,
{ simp [image_inter_preimage, image_diff_preimage, (μ i).caratheodory hs, le_refl] },
{ rintro j - hj, apply mono', apply image_subset, apply inter_subset_left },
{ rintro j - hj, apply mono', apply image_subset, apply diff_subset }
end
/-- `measure.pi μ` is the finite product of the measures `{μ i | i : ι}`.
It is defined to be measure corresponding to `measure_theory.outer_measure.pi`. -/
protected def pi : measure (Π i, α i) :=
to_measure (outer_measure.pi (λ i, (μ i).to_outer_measure)) (pi_caratheodory μ)
local attribute [instance] encodable.fintype.encodable
lemma pi_pi [∀ i, sigma_finite (μ i)] (s : Π i, set (α i))
(hs : ∀ i, is_measurable (s i)) : measure.pi μ (pi univ s) = ∏ i, μ i (s i) :=
begin
refine le_antisymm _ _,
{ rw [measure.pi, to_measure_apply _ _ (is_measurable.pi_fintype (λ i _, hs i))],
apply outer_measure.pi_pi_le },
{ rw [← pi'_pi],
work_on_goal 1 { exact hs },
simp_rw [measure.pi, to_measure_apply _ _ (is_measurable.pi_fintype (λ i _, hs i)),
← to_outer_measure_apply],
suffices : (pi' μ).to_outer_measure ≤ outer_measure.pi (λ i, (μ i).to_outer_measure),
{ exact this _ },
clear hs s,
rw [outer_measure.le_pi],
intros s hs,
simp_rw [to_outer_measure_apply],
exact pi'_pi_le μ }
end
end measure
end measure_theory
|
3e047066ae65e7ec55ac75ce82921064e213ff16 | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20161026_ICTAC_Tutorial/ex36.lean | 3fa11b1200a5849629923fc78aef862434c792af | [
"Apache-2.0"
] | permissive | leanprover/presentations | dd031a05bcb12c8855676c77e52ed84246bd889a | 3ce2d132d299409f1de269fa8e95afa1333d644e | refs/heads/master | 1,688,703,388,796 | 1,686,838,383,000 | 1,687,465,742,000 | 29,750,158 | 12 | 9 | Apache-2.0 | 1,540,211,670,000 | 1,422,042,683,000 | Lean | UTF-8 | Lean | false | false | 529 | lean | /- Logical equivalence -/
print iff
variables p q : Prop
theorem and_swap : p ∧ q ↔ q ∧ p :=
iff.intro
(assume h : p ∧ q,
show q ∧ p, from and.intro (and.right h) (and.left h))
(assume h : q ∧ p,
show p ∧ q, from and.intro (and.right h) (and.left h))
check and_swap p q -- p ∧ q ↔ q ∧ p
premise h : p ∧ q
example : q ∧ p := iff.mp (and_swap p q) h
example : q ∧ p := (and_swap p q)^.mp h
check and_swap q p -- q ∧ p ↔ p ∧ q
example : q ∧ p := iff.mpr (and_swap q p) h
|
078652f4c3189e65b9236a45fdbeefcfdf5cffda | ce89339993655da64b6ccb555c837ce6c10f9ef4 | /bluejam/chap7/exercise7.1.lean | 3cb75f5e58d09ad492826b0bed5ba83584341c41 | [] | no_license | zeptometer/LearnLean | ef32dc36a22119f18d843f548d0bb42f907bff5d | bb84d5dbe521127ba134d4dbf9559b294a80b9f7 | refs/heads/master | 1,625,710,824,322 | 1,601,382,570,000 | 1,601,382,570,000 | 195,228,870 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,444 | lean | namespace hidden
inductive nat : Type
| zero : nat
| succ : nat → nat
namespace nat
def add (m n : nat) : nat :=
nat.rec_on n m (fun n add_m_n, succ add_m_n)
instance : has_zero nat := has_zero.mk zero
instance : has_add nat := has_add.mk add
theorem add_zero (m : nat) : m + nat.zero = m := rfl
theorem add_succ (m n : nat) : m + succ n = succ (m + n) := rfl
theorem zero_add (n : nat) : nat.zero + n = n :=
nat.rec_on n rfl (λ n ih, by rw [add_succ, ih])
theorem add_assoc (m n k : nat) : m + n + k = m + (n + k) :=
nat.rec_on k rfl (λ k ih, by simp only [add_succ, ih])
theorem succ_add (m n : nat) : succ m + n = succ (m + n) :=
nat.rec_on n rfl (λ n ih, by simp only [add_succ, ih])
theorem add_comm (m n : nat) : m + n = n + m :=
nat.rec_on n
(begin
simp only [zero_add, add_zero]
end)
(λ n ih, by simp only [add_succ, ih, succ_add])
-- Exercise
def mul (m n : nat) : nat :=
nat.rec_on n 0 (λ n mul_m_n, mul_m_n + m)
def pred (n : nat) : nat :=
nat.rec_on n 0 (λ n x, n)
def sub (m n : nat) : nat :=
nat.rec_on n m (λ n sub_m_n, pred sub_m_n)
instance : has_mul nat := has_mul.mk mul
instance : has_sub nat := has_sub.mk sub
instance : has_one nat := has_one.mk (succ zero)
def pow (m n : nat) : nat :=
nat.rec_on n (succ zero) (λ n pow_m_n, pow_m_n * m)
theorem mul_zero (n : nat) : n * zero = zero := rfl
theorem mul_succ (n m : nat) : n * (succ m) = (n * m) + n := rfl
theorem zero_mul (n : nat) : zero * n = zero :=
begin
induction n,
refl,
show zero * succ n_a = zero, from
calc zero * succ n_a
= (zero * n_a) + zero : by rw mul_succ
... = zero * n_a : by rw add_zero
... = zero : n_ih
end
theorem one_mul (n : nat) : (succ zero) * n = n :=
begin
induction n,
refl,
rw mul_succ,
rw n_ih,
refl
end
theorem mul_one (n : nat) : n * (succ zero) = n :=
begin
induction n,
rw zero_mul,
rw mul_succ,
rw [mul_zero, zero_add]
end
theorem mul_dist (m n k : nat) : m * n + m * k = m * (n + k) :=
begin
induction k,
simp [add_zero, mul_zero],
simp [mul_succ],
rw [←add_assoc],
rw k_ih,
rw ←mul_succ,
rw add_succ
end
theorem mul_assoc (m n k : nat) : (m * n) * k = m * (n * k) :=
begin
induction k,
simp [mul_zero],
simp [mul_succ, k_ih],
simp [mul_dist]
end
theorem succ_mul (n m : nat) : (succ n) * m = (n * m) + m :=
begin
induction m,
simp [mul_zero, add_zero],
simp [mul_succ, m_ih],
simp [add_succ],
simp [add_assoc, add_comm m_a n]
end
theorem mul_comm (m n : nat) : m * n = n * m :=
begin
induction n,
simp [mul_zero, zero_mul],
simp [mul_succ],
rw [n_ih],
simp [succ_mul]
end
theorem dist_mul (m n k : nat) : m * k + n * k = (m + n) * k :=
begin
simp [mul_comm],
rw ←mul_dist,
simp [mul_comm]
end
instance : has_pow nat nat := has_pow.mk pow
theorem pow_succ (m n : nat) : m ^ (succ n) = m ^ n * m := rfl
theorem pow_zero (m : nat) : m ^ zero = (succ zero) := rfl
theorem pow_mul (m n k : nat) : m ^ n * m ^ k = m ^ (n + k) :=
begin
induction k,
simp [add_zero, pow_zero, mul_one],
rw [pow_succ, ←mul_assoc],
rw k_ih,
rw [←pow_succ],
rw [add_succ]
end
theorem pow_pow (m n k : nat) : (m ^ n) ^ k = m ^ (n * k) :=
begin
induction k,
simp [mul_zero, pow_zero],
simp [pow_succ],
rw k_ih,
simp [pow_mul, mul_succ]
end
end nat
end hidden
|
0fe19199bfa42a6c2722cab9fc950a5df0bd8892 | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /data/hash_map.lean | 16a56127582496685cdb5a660a4eadc80082e556 | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 27,755 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import data.list.basic data.pnat data.array.lemmas
universes u v w
/-- `bucket_array α β` is the underlying data type for `hash_map α β`,
an array of linked lists of key-value pairs. -/
def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) :=
array n.1 (list Σ a, β a)
/-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/
def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n.1 :=
⟨i % n.1, nat.mod_lt _ n.2⟩
namespace bucket_array
section
parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat)
variables {n : ℕ+} (data : bucket_array α β n)
/-- Read the bucket corresponding to an element -/
def read (a : α) : list Σ a, β a :=
let bidx := hash_map.mk_idx n (hash_fn a) in
data.read bidx
/-- Write the bucket corresponding to an element -/
def write (a : α) (l : list Σ a, β a) : bucket_array α β n :=
let bidx := hash_map.mk_idx n (hash_fn a) in
data.write bidx l
/-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/
def modify (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n :=
let bidx := hash_map.mk_idx n (hash_fn a) in
array.write data bidx (f (array.read data bidx))
/-- The list of all key-value pairs in the bucket list -/
def as_list : list Σ a, β a := data.to_list.join
theorem mem_as_list {a : Σ a, β a} : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i :=
have (∃ (l : list (Σ (a : α), β a)) (i : fin (n.val)), a ∈ l ∧ array.read data i = l) ↔
∃ (i : fin (n.val)), a ∈ array.read data i,
by rw exists_swap; exact exists_congr (λ i, by simp),
by simp [as_list]; simpa [array.mem.def, and_comm]
/-- Fold a function `f` over the key-value pairs in the bucket list -/
def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ :=
data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d)
theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) :
data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d :=
by rw [foldl, as_list, list.foldl_join, ← array.to_list_foldl]
end
end bucket_array
namespace hash_map
section
parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat)
/-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array
(without checking for duplication) -/
def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n :=
data.modify hash_fn a (λl, ⟨a, b⟩ :: l)
parameter [decidable_eq α]
/-- Search a bucket for a key `a` and return the value -/
def find_aux (a : α) : list (Σ a, β a) → option (β a)
| [] := none
| (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t
theorem find_aux_iff {a : α} {b : β a} : Π {l : list Σ a, β a}, (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l)
| [] nd := ⟨λn, by injection n, false.elim⟩
| (⟨a',b'⟩::t) nd := begin
by_cases a' = a,
{ clear find_aux_iff, subst h,
suffices : b' = b ↔ b' = b ∨ sigma.mk a' b ∈ t, {simpa [find_aux, eq_comm]},
refine (or_iff_left_of_imp (λ m, _)).symm,
have : a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd,
exact this.elim (list.mem_map_of_mem sigma.fst m) },
{ have : sigma.mk a b ≠ ⟨a', b'⟩,
{ intro e, injection e with e, exact h e.symm },
simp at nd, simp [find_aux, h, ne.symm h, find_aux_iff, nd] }
end
/-- Returns `tt` if the bucket `l` contains the key `a` -/
def contains_aux (a : α) (l : list Σ a, β a) : bool :=
(find_aux a l).is_some
theorem contains_aux_iff {a : α} {l : list Σ a, β a} (nd : (l.map sigma.fst).nodup) : contains_aux a l ↔ a ∈ l.map sigma.fst :=
begin
unfold contains_aux,
cases h : find_aux a l with b; simp,
{ assume (b : β a) (m : sigma.mk a b ∈ l),
rw (find_aux_iff nd).2 m at h,
contradiction },
{ show ∃ (b : β a), sigma.mk a b ∈ l,
exact ⟨_, (find_aux_iff nd).1 h⟩ },
end
/-- Modify a bucket to replace a value in the list. Leaves the list
unchanged if the key is not found. -/
def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a)
| [] := []
| (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t
/-- Modify a bucket to remove a key, if it exists. -/
def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a)
| [] := []
| (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t
/-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map`
invariants: There are exactly `sz` elements in it, every pair is in the
bucket determined by its key and the hash function, and no key appears
multiple times in the list. -/
structure valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop :=
(len : bkts.as_list.length = sz)
(idx : ∀ {i} {a : Σ a, β a}, a ∈ array.read bkts i →
mk_idx n (hash_fn a.1) = i)
(nodup : ∀i, ((array.read bkts i).map sigma.fst).nodup)
theorem valid.idx_enum {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
{i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) :
∃ h, mk_idx n (hash_fn a) = ⟨i, h⟩ :=
(bkts.mem_to_list_enum.1 he).imp (λ h e, by subst e; exact v.idx hl)
theorem valid.idx_enum_1 {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz)
{i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) :
(mk_idx n (hash_fn a)).1 = i :=
let ⟨h, e⟩ := v.idx_enum _ he hl in by rw e; refl
theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : (bkts.as_list.map sigma.fst).nodup :=
begin
suffices : (bkts.to_list.map (list.map sigma.fst)).pairwise list.disjoint,
{ simp [bucket_array.as_list, list.nodup_join, this],
change ∀ l s, array.mem s bkts → list.map sigma.fst s = l → l.nodup,
introv m e, subst e, cases m with i e, subst e,
apply v.nodup },
rw [← list.enum_map_snd bkts.to_list, list.pairwise_map, list.pairwise_map],
have : (bkts.to_list.enum.map prod.fst).nodup := by simp [list.nodup_range],
refine list.pairwise.imp_of_mem _ ((list.pairwise_map _).1 this),
rw prod.forall, intros i l₁,
rw prod.forall, intros j l₂ me₁ me₂ ij,
simp [list.disjoint], intros a b ml₁ b' ml₂,
apply ij, rwa [← v.idx_enum_1 _ me₁ ml₁, ← v.idx_enum_1 _ me₂ ml₂]
end
theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n.1 [] : bucket_array α β n) = [] :=
list.eq_nil_of_forall_not_mem $ λ x m,
let ⟨i, h⟩ := (bucket_array.mem_as_list _).1 m in h
theorem mk_valid (n : ℕ+) : @valid n (mk_array n.1 []) 0 :=
⟨by simp [mk_as_list], λ i a h, by cases h, λ i, list.nodup_nil⟩
theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {a : α} {b : β a} :
find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list :=
(find_aux_iff (v.nodup _)).trans $
by rw bkts.mem_as_list; exact ⟨λ h, ⟨_, h⟩, λ ⟨i, h⟩, (v.idx h).symm ▸ h⟩
theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) :
contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst :=
by simp [contains_aux, option.is_some_iff_exists, v.find_aux_iff hash_fn]
section
parameters {n : ℕ+} {bkts : bucket_array α β n}
{bidx : fin n.1} {f : list (Σ a, β a) → list (Σ a, β a)}
(u v1 v2 w : list Σ a, β a)
local notation `L` := array.read bkts bidx
private def bkts' : bucket_array α β n := array.write bkts bidx (f L)
variables (hl : L = u ++ v1 ++ w)
(hfl : f L = u ++ v2 ++ w)
include hl hfl
theorem append_of_modify : ∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' :=
begin
unfold bucket_array.as_list,
have h : bidx.1 < bkts.to_list.length, {simp [bidx.2]},
refine ⟨(bkts.to_list.take bidx.1).join ++ u, w ++ (bkts.to_list.drop (bidx.1+1)).join, _, _⟩,
{ conv { to_lhs,
rw [← list.take_append_drop bidx.1 bkts.to_list, list.drop_eq_nth_le_cons h],
simp [hl] }, simp },
{ conv { to_lhs,
rw [bkts', array.write_to_list, list.update_nth_eq_take_cons_drop _ h],
simp [hfl] }, simp }
end
variables (hvnd : (v2.map sigma.fst).nodup)
(hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx)
(djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst))
(djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst))
include hvnd hal djuv djwv
theorem valid.modify {sz : ℕ} (v : valid bkts sz) : sz + v2.length ≥ v1.length ∧ valid bkts' (sz + v2.length - v1.length) :=
begin
rcases append_of_modify u v1 v2 w hl hfl with ⟨u', w', e₁, e₂⟩,
rw [← v.len, e₁],
suffices : valid bkts' (u' ++ v2 ++ w').length,
{ simpa [ge, nat.le_add_right, nat.add_sub_cancel_left] },
refine ⟨congr_arg _ e₂, λ i a, _, λ i, _⟩,
{ by_cases bidx = i,
{ subst i, rw [bkts', array.read_write, hfl],
have := @valid.idx _ _ _ v bidx a,
simp only [hl, list.mem_append, or_imp_distrib, forall_and_distrib] at this ⊢,
exact ⟨⟨this.1.1, hal _⟩, this.2⟩ },
{ rw [bkts', array.read_write_of_ne _ _ h], apply v.idx } },
{ by_cases bidx = i,
{ subst i, rw [bkts', array.read_write, hfl],
have := @valid.nodup _ _ _ v bidx,
simp [hl, list.nodup_append] at this,
simp [list.nodup_append, this, hvnd, djuv, djwv.symm] },
{ rw [bkts', array.read_write_of_ne _ _ h], apply v.nodup } }
end
end
theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst →
∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w
| [] := false.elim
| (⟨a', b'⟩::t) := begin
by_cases e : a' = a,
{ subst a',
suffices : ∃ u w (b'' : β a),
sigma.mk a b' :: t = u ++ ⟨a, b''⟩ :: w ∧
replace_aux a b (⟨a, b'⟩ :: t) = u ++ ⟨a, b⟩ :: w, {simpa},
refine ⟨[], t, b', _⟩, simp [replace_aux] },
{ suffices : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a),
sigma.mk a' b' :: t = u ++ ⟨a, b''⟩ :: w ∧
sigma.mk a' b' :: replace_aux a b t = u ++ ⟨a, b⟩ :: w,
{ simpa [replace_aux, ne.symm e, e] },
intros x m,
have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a),
t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b t = u ++ ⟨a, b⟩ :: w,
{ simpa using valid.replace_aux t },
rcases IH x m with ⟨u, w, b'', hl, hfl⟩,
exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm, ne.symm e]⟩ }
end
theorem valid.replace {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hc : contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u, w, b', hl, hfl⟩,
simp [hl, list.nodup_append] at nd,
refine (v.modify hash_fn
u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _)
(λa' e, by simp at e; rw e)
(λa' e1 e2, _)
(λa' e1 e2, _)).2;
{ revert e1, simp [-sigma.exists] at e2, subst a', simp [nd] }
end
theorem valid.insert {n : ℕ+}
{bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a)
(Hnc : ¬ contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
refine (v.modify hash_fn
[] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _)
(λa' e, by simp at e; rw e)
(λa', false.elim)
(λa' e1 e2, _)).2,
simp [-sigma.exists] at e2, subst a',
exact Hnc ((contains_aux_iff nd).2 e1)
end
theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst →
∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w
| [] := false.elim
| (⟨a', b'⟩::t) := begin
by_cases e : a' = a,
{ subst a',
simpa [erase_aux, and_comm] using show ∃ u w (x : β a),
t = u ++ w ∧ sigma.mk a b' :: t = u ++ ⟨a, x⟩ :: w, from ⟨[], t, b', by simp⟩ },
{ simp [erase_aux, e, ne.symm e],
suffices : ∀ (b : β a) (_ : sigma.mk a b ∈ t), ∃ u w (x : β a),
sigma.mk a' b' :: t = u ++ ⟨a, x⟩ :: w ∧
sigma.mk a' b' :: erase_aux a t = u ++ w,
{ simpa [replace_aux, ne.symm e, e] },
intros b m,
have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (x : β a),
t = u ++ ⟨a, x⟩ :: w ∧ erase_aux a t = u ++ w,
{ simpa using valid.erase_aux t },
rcases IH b m with ⟨u, w, b'', hl, hfl⟩,
exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm]⟩ }
end
theorem valid.erase {n} {bkts : bucket_array α β n} {sz}
(a : α) (Hc : contains_aux a (bkts.read hash_fn a))
(v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) :=
begin
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases hash_map.valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u, w, b, hl, hfl⟩,
refine (v.modify hash_fn u [⟨a, b⟩] [] w hl hfl list.nodup_nil _ _ _).2;
{ intros, simp at *; contradiction }
end
end
end hash_map
/-- A hash map data structure, representing a finite key-value map
with key type `α` and value type `β` (which may depend on `α`). -/
structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) :=
(hash_fn : α → nat)
(size : ℕ)
(nbuckets : ℕ+)
(buckets : bucket_array α β nbuckets)
(is_valid : hash_map.valid hash_fn buckets size)
/-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/
def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) : hash_map α β :=
let n := if nbuckets = 0 then 8 else nbuckets in
let nz : n > 0 := by abstract { cases nbuckets, {simp, tactic.comp_val}, simp [if_pos, nat.succ_ne_zero], apply nat.zero_lt_succ} in
{ hash_fn := hash_fn,
size := 0,
nbuckets := ⟨n, nz⟩,
buckets := mk_array n [],
is_valid := hash_map.mk_valid _ _ }
namespace hash_map
variables {α : Type u} {β : α → Type v} [decidable_eq α]
/-- Return the value corresponding to a key, or `none` if not found -/
def find (m : hash_map α β) (a : α) : option (β a) :=
find_aux a (m.buckets.read m.hash_fn a)
/-- Return `tt` if the key exists in the map -/
def contains (m : hash_map α β) (a : α) : bool :=
(m.find a).is_some
instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩
/-- Fold a function over the key-value pairs in the map -/
def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ :=
m.buckets.foldl d f
/-- The list of key-value pairs in the map -/
def entries (m : hash_map α β) : list Σ a, β a :=
m.buckets.as_list
/-- The list of keys in the map -/
def keys (m : hash_map α β) : list α :=
m.entries.map sigma.fst
theorem find_iff (m : hash_map α β) (a : α) (b : β a) :
m.find a = some b ↔ sigma.mk a b ∈ m.entries :=
m.is_valid.find_aux_iff _
theorem contains_iff (m : hash_map α β) (a : α) :
m.contains a ↔ a ∈ m.keys :=
m.is_valid.contains_aux_iff _ _
theorem entries_empty (hash_fn : α → nat) (n) :
(@mk_hash_map α _ β hash_fn n).entries = [] :=
by dsimp [entries, mk_hash_map]; rw mk_as_list
theorem keys_empty (hash_fn : α → nat) (n) :
(@mk_hash_map α _ β hash_fn n).keys = [] :=
by dsimp [keys]; rw entries_empty; refl
theorem find_empty (hash_fn : α → nat) (n a) :
(@mk_hash_map α _ β hash_fn n).find a = none :=
by induction h : (@mk_hash_map α _ β hash_fn n).find a; [refl,
{ have := (find_iff _ _ _).1 h, rw entries_empty at this, contradiction }]
theorem not_contains_empty (hash_fn : α → nat) (n a) :
¬ (@mk_hash_map α _ β hash_fn n).contains a :=
by apply bool_iff_false.2; dsimp [contains]; rw [find_empty]; refl
theorem insert_lemma (hash_fn : α → nat) {n n'}
{bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) :
valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz :=
begin
suffices : ∀ (l : list Σ a, β a) (t : bucket_array α β n') sz,
valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup →
valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length),
{ have p := this bkts.as_list _ _ (mk_valid _ _),
rw [mk_as_list, list.append_nil, zero_add, v.len] at p,
rw bucket_array.foldl_eq,
exact p (v.as_list_nodup _) },
intro l, induction l with c l IH; intros t sz v nd, {exact v},
rw show sz + (c :: l).length = sz + 1 + l.length, by simp,
rcases (show (l.map sigma.fst).nodup ∧
((bucket_array.as_list t).map sigma.fst).nodup ∧
c.fst ∉ l.map sigma.fst ∧
c.fst ∉ (bucket_array.as_list t).map sigma.fst ∧
(l.map sigma.fst).disjoint ((bucket_array.as_list t).map sigma.fst),
by simpa [list.nodup_append, not_or_distrib, and_comm, and.left_comm] using nd)
with ⟨nd1, nd2, nm1, nm2, dj⟩,
have v' := v.insert _ _ c.2 (λHc, nm2 $ (v.contains_aux_iff _ c.1).1 Hc),
apply IH _ _ v',
suffices : ∀ ⦃a : α⦄ (b : β a), sigma.mk a b ∈ l →
∀ (b' : β a), sigma.mk a b' ∈ (reinsert_aux hash_fn t c.1 c.2).as_list → false,
{ simpa [list.nodup_append, nd1, v'.as_list_nodup _, list.disjoint] },
intros a b m1 b' m2,
rcases (reinsert_aux hash_fn t c.1 c.2).mem_as_list.1 m2 with ⟨i, im⟩,
have : sigma.mk a b' ∉ array.read t i,
{ intro m3,
have : a ∈ list.map sigma.fst t.as_list :=
list.mem_map_of_mem sigma.fst (t.mem_as_list.2 ⟨_, m3⟩),
exact dj (list.mem_map_of_mem sigma.fst m1) this },
by_cases h : mk_idx n' (hash_fn c.1) = i,
{ subst h,
have e : sigma.mk a b' = ⟨c.1, c.2⟩,
{ simpa [reinsert_aux, bucket_array.modify, array.read_write, this] using im },
injection e with e, subst a,
exact nm1.elim (@list.mem_map_of_mem _ _ sigma.fst _ _ m1) },
{ apply this,
simpa [reinsert_aux, bucket_array.modify, array.read_write_of_ne _ _ h] using im }
end
/-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/
def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β
| ⟨hash_fn, size, n, buckets, v⟩ a b :=
let bkt := buckets.read hash_fn a in
if hc : contains_aux a bkt then
{ hash_fn := hash_fn,
size := size,
nbuckets := n,
buckets := buckets.modify hash_fn a (replace_aux a b),
is_valid := v.replace _ a b hc }
else
let size' := size + 1,
buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l),
valid' := v.insert _ a b hc in
if size' ≤ n.1 then
{ hash_fn := hash_fn,
size := size',
nbuckets := n,
buckets := buckets',
is_valid := valid' }
else
let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩,
buckets'' : bucket_array α β n' :=
buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in
{ hash_fn := hash_fn,
size := size',
nbuckets := n',
buckets := buckets'',
is_valid := insert_lemma _ valid' }
theorem mem_insert : Π (m : hash_map α β) (a b a' b'),
(sigma.mk a' b' : sigma β) ∈ (m.insert a b).entries ↔
if a = a' then b == b' else sigma.mk a' b' ∈ m.entries
| ⟨hash_fn, size, n, bkts, v⟩ a b a' b' := begin
let bkt := bkts.read hash_fn a,
have nd : (bkt.map sigma.fst).nodup := v.nodup (mk_idx n (hash_fn a)),
have lem : Π (bkts' : bucket_array α β n) (v1 u w)
(hl : bucket_array.as_list bkts = u ++ v1 ++ w)
(hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w)
(veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]),
sigma.mk a' b' ∈ bkts'.as_list ↔
if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list,
{ intros bkts' v1 u w hl hfl veq,
rw [hl, hfl],
by_cases h : a = a',
{ subst a',
suffices : b = b' ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b = b',
{ simpa [eq_comm, or.left_comm] },
refine or_iff_left_of_imp (not.elim $ not_or_distrib.2 _),
rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩,
{ have na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc,
simp [hl, not_or_distrib] at na, simp [na] },
{ have nd' := v.as_list_nodup _,
simp [hl, list.nodup_append] at nd', simp [nd'] } },
{ suffices : sigma.mk a' b' ∉ v1, {simp [h, ne.symm h, this]},
rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩; simp [ne.symm h] } },
by_cases Hc : (contains_aux a bkt : Prop),
{ rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a)))
((contains_aux_iff nd).1 Hc) with ⟨u', w', b'', hl', hfl'⟩,
rcases (append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl') with ⟨u, w, hl, hfl⟩,
simpa [insert, @dif_pos (contains_aux a bkt) _ Hc]
using lem _ _ u w hl hfl (or.inr ⟨b'', rfl⟩) },
{ let size' := size + 1,
let bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l),
have mi : sigma.mk a' b' ∈ bkts'.as_list ↔
if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list :=
let ⟨u, w, hl, hfl⟩ := append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in
lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hc⟩,
simp [insert, @dif_neg (contains_aux a bkt) _ Hc],
by_cases h : size' ≤ n.1,
-- TODO(Mario): Why does the by_cases assumption look different than the stated one?
{ simpa [show size' ≤ n.1, from h] using mi },
{ let n' : ℕ+ := ⟨n.1 * 2, mul_pos n.2 dec_trivial⟩,
let bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn),
suffices : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse,
{ simpa [show ¬ size' ≤ n.1, from h, mi] },
rw [show bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _,
← list.foldr_reverse],
induction bkts'.as_list.reverse with a l IH,
{ simp [mk_as_list] },
{ cases a with a'' b'',
let B := l.foldr (λ (y : sigma β) (x : bucket_array α β n'),
reinsert_aux hash_fn x y.1 y.2) (mk_array n'.1 []),
rcases append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl with ⟨u, w, hl, hfl⟩,
simp [IH.symm, or.left_comm, show B.as_list = _, from hl,
show (reinsert_aux hash_fn B a'' b'').as_list = _, from hfl] } } }
end
theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b :=
(find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl
theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') :
(m.insert a b).find a' = m.find a' :=
option.eq_of_eq_some $ λb',
let t := mem_insert m a b a' b' in
(find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm
theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) :
(m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' :=
if h : a = a' then by rw dif_pos h; exact
match a', h with ._, rfl := find_insert_eq m a b end
else by rw dif_neg h; exact find_insert_ne m a a' b h
/-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/
def insert_all (l : list (Σ a, β a)) (m : hash_map α β) : hash_map α β :=
l.foldl (λ m ⟨a, b⟩, insert m a b) m
/-- Construct a hash map from a list of key-value pairs. -/
def of_list (l : list (Σ a, β a)) (hash_fn) : hash_map α β :=
insert_all l (mk_hash_map hash_fn (2 * l.length))
/-- Remove a key from the map. (Modifies `m` in-place when applicable) -/
def erase (m : hash_map α β) (a : α) : hash_map α β :=
match m with ⟨hash_fn, size, n, buckets, v⟩ :=
if hc : contains_aux a (buckets.read hash_fn a) then
{ hash_fn := hash_fn,
size := size - 1,
nbuckets := n,
buckets := buckets.modify hash_fn a (erase_aux a),
is_valid := v.erase _ a hc }
else m
end
theorem mem_erase : Π (m : hash_map α β) (a a' b'),
(sigma.mk a' b' : sigma β) ∈ (m.erase a).entries ↔
a ≠ a' ∧ sigma.mk a' b' ∈ m.entries
| ⟨hash_fn, size, n, bkts, v⟩ a a' b' := begin
let bkt := bkts.read hash_fn a,
by_cases Hc : (contains_aux a bkt : Prop),
{ let bkts' := bkts.modify hash_fn a (erase_aux a),
suffices : sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list,
{ simpa [erase, @dif_pos (contains_aux a bkt) _ Hc] },
have nd := v.nodup (mk_idx n (hash_fn a)),
rcases valid.erase_aux a bkt ((contains_aux_iff nd).1 Hc) with ⟨u', w', b, hl', hfl'⟩,
rcases append_of_modify u' [⟨a, b⟩] [] _ hl' hfl' with ⟨u, w, hl, hfl⟩,
suffices : ∀_:sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w, a ≠ a',
{ have : sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w ↔ (¬a = a' ∧ a' = a) ∧ b' == b ∨
¬a = a' ∧ (sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w),
{ simp [eq_comm, not_and_self_iff, and_iff_right_of_imp this] },
simpa [hl, show bkts'.as_list = _, from hfl, and_or_distrib_left,
and_comm, and.left_comm, or.left_comm] },
intros m e, subst a', revert m, apply not_or_distrib.2,
have nd' := v.as_list_nodup _,
simp [hl, list.nodup_append] at nd', simp [nd'] },
{ suffices : ∀_:sigma.mk a' b' ∈ bucket_array.as_list bkts, a ≠ a',
{ simp [erase, @dif_neg (contains_aux a bkt) _ Hc, entries, and_iff_right_of_imp this] },
intros m e, subst a',
exact Hc ((v.contains_aux_iff _ _).2 (list.mem_map_of_mem sigma.fst m)) }
end
theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none :=
begin
cases h : (m.erase a).find a with b, {refl},
exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left
end
theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') :
(m.erase a).find a' = m.find a' :=
option.eq_of_eq_some $ λb',
(find_iff _ _ _).trans $ (mem_erase m a a' b').trans $
(and_iff_right h).trans (find_iff _ _ _).symm
theorem find_erase (m : hash_map α β) (a' a : α) :
(m.erase a).find a' = if a = a' then none else m.find a' :=
if h : a = a' then by subst a'; simp [find_erase_eq m a]
else by rw if_neg h; exact find_erase_ne m a a' h
section string
variables [has_to_string α] [∀ a, has_to_string (β a)]
open prod
private def key_data_to_string (a : α) (b : β a) (first : bool) : string :=
(if first then "" else ", ") ++ sformat!"{a} ← {b}"
private def to_string (m : hash_map α β) : string :=
"⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩"
instance : has_to_string (hash_map α β) :=
⟨to_string⟩
end string
section format
open format prod
variables [has_to_format α] [∀ a, has_to_format (β a)]
private meta def format_key_data (a : α) (b : β a) (first : bool) : format :=
(if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b
private meta def to_format (m : hash_map α β) : format :=
group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++
to_fmt "⟩"
meta instance : has_to_format (hash_map α β) :=
⟨to_format⟩
end format
end hash_map
|
04fcbfdb0df88c7cd575d8dae72474ec9b6c8068 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/normed_space/extend.lean | fd9f11ecc733020ce9ddc23c8079e8e8b6a2c17e | [
"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,714 | lean | /-
Copyright (c) 2020 Ruben Van de Velde. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ruben Van de Velde
-/
import algebra.algebra.restrict_scalars
import data.complex.is_R_or_C
/-!
# Extending a continuous `ℝ`-linear map to a continuous `𝕜`-linear map
In this file we provide a way to extend a continuous `ℝ`-linear map to a continuous `𝕜`-linear map
in a way that bounds the norm by the norm of the original map, when `𝕜` is either `ℝ` (the
extension is trivial) or `ℂ`. We formulate the extension uniformly, by assuming `is_R_or_C 𝕜`.
We motivate the form of the extension as follows. Note that `fc : F →ₗ[𝕜] 𝕜` is determined fully by
`Re fc`: for all `x : F`, `fc (I • x) = I * fc x`, so `Im (fc x) = -Re (fc (I • x))`. Therefore,
given an `fr : F →ₗ[ℝ] ℝ`, we define `fc x = fr x - fr (I • x) * I`.
## Main definitions
* `linear_map.extend_to_𝕜`
* `continuous_linear_map.extend_to_𝕜`
## Implementation details
For convenience, the main definitions above operate in terms of `restrict_scalars ℝ 𝕜 F`.
Alternate forms which operate on `[is_scalar_tower ℝ 𝕜 F]` instead are provided with a primed name.
-/
open is_R_or_C
variables {𝕜 : Type*} [is_R_or_C 𝕜] {F : Type*} [semi_normed_group F] [normed_space 𝕜 F]
local notation `abs𝕜` := @is_R_or_C.abs 𝕜 _
/-- Extend `fr : F →ₗ[ℝ] ℝ` to `F →ₗ[𝕜] 𝕜` in a way that will also be continuous and have its norm
bounded by `∥fr∥` if `fr` is continuous. -/
noncomputable def linear_map.extend_to_𝕜'
[module ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →ₗ[ℝ] ℝ) : F →ₗ[𝕜] 𝕜 :=
begin
let fc : F → 𝕜 := λ x, (fr x : 𝕜) - (I : 𝕜) * (fr ((I : 𝕜) • x)),
have add : ∀ x y : F, fc (x + y) = fc x + fc y,
{ assume x y,
simp only [fc],
simp only [smul_add, linear_map.map_add, of_real_add],
rw mul_add,
abel, },
have A : ∀ (c : ℝ) (x : F), (fr ((c : 𝕜) • x) : 𝕜) = (c : 𝕜) * (fr x : 𝕜),
{ assume c x,
rw [← of_real_mul],
congr' 1,
rw [is_R_or_C.of_real_alg, smul_assoc, fr.map_smul, algebra.id.smul_eq_mul, one_smul] },
have smul_ℝ : ∀ (c : ℝ) (x : F), fc ((c : 𝕜) • x) = (c : 𝕜) * fc x,
{ assume c x,
simp only [fc, A],
rw A c x,
rw [smul_smul, mul_comm I (c : 𝕜), ← smul_smul, A, mul_sub],
ring },
have smul_I : ∀ x : F, fc ((I : 𝕜) • x) = (I : 𝕜) * fc x,
{ assume x,
simp only [fc],
cases @I_mul_I_ax 𝕜 _ with h h, { simp [h] },
rw [mul_sub, ← mul_assoc, smul_smul, h],
simp only [neg_mul, linear_map.map_neg, one_mul, one_smul,
mul_neg, of_real_neg, neg_smul, sub_neg_eq_add, add_comm] },
have smul_𝕜 : ∀ (c : 𝕜) (x : F), fc (c • x) = c • fc x,
{ assume c x,
rw [← re_add_im c, add_smul, add_smul, add, smul_ℝ, ← smul_smul, smul_ℝ, smul_I, ← mul_assoc],
refl },
exact { to_fun := fc, map_add' := add, map_smul' := smul_𝕜 }
end
lemma linear_map.extend_to_𝕜'_apply [module ℝ F] [is_scalar_tower ℝ 𝕜 F]
(fr : F →ₗ[ℝ] ℝ) (x : F) :
fr.extend_to_𝕜' x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl
/-- The norm of the extension is bounded by `∥fr∥`. -/
lemma norm_bound [normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F] (fr : F →L[ℝ] ℝ) (x : F) :
∥(fr.to_linear_map.extend_to_𝕜' x : 𝕜)∥ ≤ ∥fr∥ * ∥x∥ :=
begin
let lm : F →ₗ[𝕜] 𝕜 := fr.to_linear_map.extend_to_𝕜',
-- We aim to find a `t : 𝕜` such that
-- * `lm (t • x) = fr (t • x)` (so `lm (t • x) = t * lm x ∈ ℝ`)
-- * `∥lm x∥ = ∥lm (t • x)∥` (so `t.abs` must be 1)
-- If `lm x ≠ 0`, `(lm x)⁻¹` satisfies the first requirement, and after normalizing, it
-- satisfies the second.
-- (If `lm x = 0`, the goal is trivial.)
classical,
by_cases h : lm x = 0,
{ rw [h, norm_zero],
apply mul_nonneg; exact norm_nonneg _ },
let fx := (lm x)⁻¹,
let t := fx / (abs𝕜 fx : 𝕜),
have ht : abs𝕜 t = 1, by field_simp [abs_of_real, of_real_inv, is_R_or_C.abs_inv,
is_R_or_C.abs_div, is_R_or_C.abs_abs, h],
have h1 : (fr (t • x) : 𝕜) = lm (t • x),
{ apply ext,
{ simp only [lm, of_real_re, linear_map.extend_to_𝕜'_apply, mul_re, I_re, of_real_im, zero_mul,
add_monoid_hom.map_sub, sub_zero, mul_zero],
refl },
{ symmetry,
calc im (lm (t • x))
= im (t * lm x) : by rw [lm.map_smul, smul_eq_mul]
... = im ((lm x)⁻¹ / (abs𝕜 (lm x)⁻¹) * lm x) : rfl
... = im (1 / (abs𝕜 (lm x)⁻¹ : 𝕜)) : by rw [div_mul_eq_mul_div, inv_mul_cancel h]
... = 0 : by rw [← of_real_one, ← of_real_div, of_real_im]
... = im (fr (t • x) : 𝕜) : by rw [of_real_im] } },
calc ∥lm x∥ = abs𝕜 t * ∥lm x∥ : by rw [ht, one_mul]
... = ∥t * lm x∥ : by rw [← norm_eq_abs, norm_mul]
... = ∥lm (t • x)∥ : by rw [←smul_eq_mul, lm.map_smul]
... = ∥(fr (t • x) : 𝕜)∥ : by rw h1
... = ∥fr (t • x)∥ : by rw [norm_eq_abs, abs_of_real, norm_eq_abs, abs_to_real]
... ≤ ∥fr∥ * ∥t • x∥ : continuous_linear_map.le_op_norm _ _
... = ∥fr∥ * (∥t∥ * ∥x∥) : by rw norm_smul
... ≤ ∥fr∥ * ∥x∥ : by rw [norm_eq_abs, ht, one_mul]
end
/-- Extend `fr : F →L[ℝ] ℝ` to `F →L[𝕜] 𝕜`. -/
noncomputable def continuous_linear_map.extend_to_𝕜' [normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F]
(fr : F →L[ℝ] ℝ) :
F →L[𝕜] 𝕜 :=
linear_map.mk_continuous _ (∥fr∥) (norm_bound _)
lemma continuous_linear_map.extend_to_𝕜'_apply [normed_space ℝ F] [is_scalar_tower ℝ 𝕜 F]
(fr : F →L[ℝ] ℝ) (x : F) :
fr.extend_to_𝕜' x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x) := rfl
/-- Extend `fr : restrict_scalars ℝ 𝕜 F →ₗ[ℝ] ℝ` to `F →ₗ[𝕜] 𝕜`. -/
noncomputable def linear_map.extend_to_𝕜 (fr : (restrict_scalars ℝ 𝕜 F) →ₗ[ℝ] ℝ) : F →ₗ[𝕜] 𝕜 :=
fr.extend_to_𝕜'
lemma linear_map.extend_to_𝕜_apply (fr : (restrict_scalars ℝ 𝕜 F) →ₗ[ℝ] ℝ) (x : F) :
fr.extend_to_𝕜 x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x : _) := rfl
/-- Extend `fr : restrict_scalars ℝ 𝕜 F →L[ℝ] ℝ` to `F →L[𝕜] 𝕜`. -/
noncomputable def continuous_linear_map.extend_to_𝕜 (fr : (restrict_scalars ℝ 𝕜 F) →L[ℝ] ℝ) :
F →L[𝕜] 𝕜 :=
fr.extend_to_𝕜'
lemma continuous_linear_map.extend_to_𝕜_apply (fr : (restrict_scalars ℝ 𝕜 F) →L[ℝ] ℝ) (x : F) :
fr.extend_to_𝕜 x = (fr x : 𝕜) - (I : 𝕜) * fr ((I : 𝕜) • x : _) := rfl
|
694c3c1d7750f790eaf079b711779ca97e57c75e | ab0adaad39f188556e3c9424418475ec3da0d252 | /src/local/ample.lean | 5d419101512686f95fcd2801f2e6aa11f228abeb | [] | no_license | b-mehta/sphere-eversion | 124e41231365ecd71a72eb7c8b9714af2e61e4e5 | 34363b4c6349bf585c3334d5dad38c7b8902bea5 | refs/heads/master | 1,668,601,715,154 | 1,592,337,409,000 | 1,592,337,409,000 | 274,816,682 | 0 | 0 | null | 1,593,053,712,000 | 1,593,053,711,000 | null | UTF-8 | Lean | false | false | 707 | lean | import analysis.convex.basic
import topology.subset_properties
/-!
# Ample subsets of real vector spaces
## Implementation notes
The definition of ample subset asks for a vector space structure and a topology on the ambiant type
without any link between those structures, but we will only be using these for finite dimensional
vector spaces with their natural topology.
-/
open set
variables {F : Type*} [add_comm_group F] [vector_space ℝ F] [topological_space F]
/-- A subset of a topological real vector space is ample if the convex hull of each of its
connected components is the full space. -/
def ample_set (s : set F) :=
∀ x : s, convex_hull (subtype.val '' (connected_component x)) = univ |
f49e65d8d2217c0892a8e60d695c73e2e154193d | e09201d437062e1f95e6e5360aab0c9f947901aa | /src/regular/regex_to_dfa.lean | 099bacb6ea0020b95acaff9ea00c40c48cbf4386 | [] | no_license | VArtem/lean-regular-languages | 34f4b093f28ef2f09ba7e684e642a0f97c901560 | e877243188253d0ac17ccf0ae2da7bf608686ff0 | refs/heads/master | 1,683,590,111,306 | 1,622,307,234,000 | 1,622,307,234,000 | 284,232,653 | 7 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,172 | lean | import tactic
import languages.basic
import languages.star
import regular.regex
import automata.dfa
import automata.epsnfa
import automata.epsnfa_append
import automata.epsnfa_star
import automata.epsnfa_triv
open languages regex DFA epsnfa
namespace regex.to_dfa
variables {S : Type} [fintype S]
theorem regex_to_dfa {L : set (list S)} : regex_lang L → dfa_lang L :=
begin
rintro ⟨r, rfl⟩,
induction r, {
rw regex_empty_is_empty_lang,
exact epsnfa_to_dfa_eq triv.empty_is_epsnfa_lang,
}, {
rw regex_eps_is_eps_lang,
exact epsnfa_to_dfa_eq triv.eps_is_epsnfa_lang,
}, {
rw regex_one_is_one_lang,
exact epsnfa_to_dfa_eq triv.one_is_epsnfa_lang,
}, {
rw regex_union_is_lang_union,
convert union_is_dfa _ _;
assumption,
}, {
rw regex_append_is_lang_append,
apply epsnfa_to_dfa_eq,
refine append.append_is_epsnfa (dfa_to_epsnfa_eq _) (dfa_to_epsnfa_eq _ );
assumption,
}, {
rw regex_star_is_kleene_star,
apply epsnfa_to_dfa_eq,
refine star.star_is_epsnfa (dfa_to_epsnfa_eq r_ih),
}
end
end regex.to_dfa |
62bb42bbd5f6fb51689dd4121e45280422433f35 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/category/Module/monoidal/closed.lean | 1f2577cf89c0fdb04583918c6c66cfbae7e30c43 | [
"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,343 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Buzzard, Scott Morrison, Jakob von Raumer
-/
import category_theory.closed.monoidal
import algebra.category.Module.monoidal.symmetric
/-!
# The monoidal closed structure on `Module R`.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
universes v w x u
open category_theory
open opposite
namespace Module
variables {R : Type u} [comm_ring R]
local attribute [ext] tensor_product.ext
/--
Auxiliary definition for the `monoidal_closed` instance on `Module R`.
(This is only a separate definition in order to speed up typechecking. )
-/
@[simps]
def monoidal_closed_hom_equiv (M N P : Module.{u} R) :
((monoidal_category.tensor_left M).obj N ⟶ P) ≃
(N ⟶ ((linear_coyoneda R (Module R)).obj (op M)).obj P) :=
{ to_fun := λ f, linear_map.compr₂ (tensor_product.mk R N M) ((β_ N M).hom ≫ f),
inv_fun := λ f, (β_ M N).hom ≫ tensor_product.lift f,
left_inv := λ f, begin ext m n,
simp only [tensor_product.mk_apply, tensor_product.lift.tmul, linear_map.compr₂_apply,
function.comp_app, coe_comp, monoidal_category.braiding_hom_apply],
end,
right_inv := λ f, begin ext m n,
simp only [tensor_product.mk_apply, tensor_product.lift.tmul, linear_map.compr₂_apply,
symmetric_category.symmetry_assoc],
end, }
instance : monoidal_closed (Module.{u} R) :=
{ closed' := λ M,
{ is_adj :=
{ right := (linear_coyoneda R (Module.{u} R)).obj (op M),
adj := adjunction.mk_of_hom_equiv
{ hom_equiv := λ N P, monoidal_closed_hom_equiv M N P, } } } }
lemma ihom_map_apply {M N P : Module.{u} R} (f : N ⟶ P) (g : Module.of R (M ⟶ N)) :
(ihom M).map f g = g ≫ f := rfl
-- I can't seem to express the function coercion here without writing `@coe_fn`.
@[simp]
lemma monoidal_closed_curry {M N P : Module.{u} R} (f : M ⊗ N ⟶ P) (x : M) (y : N) :
@coe_fn _ _ linear_map.has_coe_to_fun ((monoidal_closed.curry f : N →ₗ[R] (M →ₗ[R] P)) y) x =
f (x ⊗ₜ[R] y) :=
rfl
@[simp]
lemma monoidal_closed_uncurry {M N P : Module.{u} R}
(f : N ⟶ (M ⟶[Module.{u} R] P)) (x : M) (y : N) :
monoidal_closed.uncurry f (x ⊗ₜ[R] y) = (@coe_fn _ _ linear_map.has_coe_to_fun (f y)) x :=
rfl
/-- Describes the counit of the adjunction `M ⊗ - ⊣ Hom(M, -)`. Given an `R`-module `N` this
should give a map `M ⊗ Hom(M, N) ⟶ N`, so we flip the order of the arguments in the identity map
`Hom(M, N) ⟶ (M ⟶ N)` and uncurry the resulting map `M ⟶ Hom(M, N) ⟶ N.` -/
lemma ihom_ev_app (M N : Module.{u} R) :
(ihom.ev M).app N = tensor_product.uncurry _ _ _ _ linear_map.id.flip :=
begin
ext,
exact Module.monoidal_closed_uncurry _ _ _,
end
/-- Describes the unit of the adjunction `M ⊗ - ⊣ Hom(M, -)`. Given an `R`-module `N` this should
define a map `N ⟶ Hom(M, M ⊗ N)`, which is given by flipping the arguments in the natural
`R`-bilinear map `M ⟶ N ⟶ M ⊗ N`. -/
lemma ihom_coev_app (M N : Module.{u} R) :
(ihom.coev M).app N = (tensor_product.mk _ _ _).flip :=
rfl
lemma monoidal_closed_pre_app {M N : Module.{u} R} (P : Module.{u} R) (f : N ⟶ M) :
(monoidal_closed.pre f).app P = linear_map.lcomp R _ f :=
rfl
end Module
|
5322c6346592fdab16c4adca0c3ebad8c455cc18 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /tests/lean/run/record3.lean | a413feadf561f0a7faac326f8f9de68279e460ac | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 323 | lean | import logic data.unit
structure point (A : Type) (B : Type) :=
mk :: (x : A) (y : B)
inductive color :=
red, green, blue
structure color_point (A : Type) (B : Type) extends point A B :=
mk :: (c : color)
constant foo (p: point num num) : num
constant p : color_point num num
set_option pp.coercions true
check foo p
|
ba8615a57f46c866125bc2cf221040a60f259995 | d436468d80b739ba7e06843c4d0d2070e43448e5 | /src/algebra/module.lean | 4eeb3494abb33c6d42aab1847bd7829b98f9ba02 | [
"Apache-2.0"
] | permissive | roro47/mathlib | 761fdc002aef92f77818f3fef06bf6ec6fc1a28e | 80aa7d52537571a2ca62a3fdf71c9533a09422cf | refs/heads/master | 1,599,656,410,625 | 1,573,649,488,000 | 1,573,649,488,000 | 221,452,951 | 0 | 0 | Apache-2.0 | 1,573,647,693,000 | 1,573,647,692,000 | null | UTF-8 | Lean | false | false | 16,164 | lean | /-
Copyright (c) 2015 Nathaniel Thomas. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro
Modules over a ring.
## Implemetation notes
Throughout the `linear_map` section implicit `{}` brackets are often used instead of type class `[]` brackets.
This is done when the instances can be inferred because they are implicit arguments to the type `linear_map`.
When they can be inferred from the type it is faster to use this method than to use type class inference
-/
import algebra.ring algebra.big_operators group_theory.subgroup group_theory.group_action
open function
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
-- /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/
-- class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ)
-- infixr ` • `:73 := has_scalar.smul
/-- A semimodule is a generalization of vector spaces to a scalar semiring.
It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`,
connected by a "scalar multiplication" operation `r • x : β`
(where `r : α` and `x : β`) with some natural associativity and
distributivity axioms similar to those on a ring. -/
class semimodule (α : Type u) (β : Type v) [semiring α]
[add_comm_monoid β] extends distrib_mul_action α β :=
(add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x)
(zero_smul : ∀x : β, (0 : α) • x = 0)
section semimodule
variables [R:semiring α] [add_comm_monoid β] [semimodule α β] (r s : α) (x y : β)
include R
theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x
variables (α)
@[simp] theorem zero_smul : (0 : α) • x = 0 := semimodule.zero_smul α x
lemma smul_smul : r • s • x = (r * s) • x := (mul_smul _ _ _).symm
instance smul.is_add_monoid_hom {r : α} : is_add_monoid_hom (λ x : β, r • x) :=
{ map_add := smul_add _, map_zero := smul_zero _ }
lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : x = 0 :=
by rw [←one_smul α x, ←zero_eq_one, zero_smul]
end semimodule
/-- A module is a generalization of vector spaces to a scalar ring.
It consists of a scalar ring `α` and an additive group of "vectors" `β`,
connected by a "scalar multiplication" operation `r • x : β`
(where `r : α` and `x : β`) with some natural associativity and
distributivity axioms similar to those on a ring. -/
class module (α : Type u) (β : Type v) [ring α] [add_comm_group β] extends semimodule α β
structure module.core (α β) [ring α] [add_comm_group β] extends has_scalar α β :=
(smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y)
(add_smul : ∀(r s : α) (x : β), (r + s) • x = r • x + s • x)
(mul_smul : ∀(r s : α) (x : β), (r * s) • x = r • s • x)
(one_smul : ∀x : β, (1 : α) • x = x)
def module.of_core {α β} [ring α] [add_comm_group β] (M : module.core α β) : module α β :=
by letI := M.to_has_scalar; exact
{ zero_smul := λ x,
have (0 : α) • x + (0 : α) • x = (0 : α) • x + 0, by rw ← M.add_smul; simp,
add_left_cancel this,
smul_zero := λ r,
have r • (0:β) + r • 0 = r • 0 + 0, by rw ← M.smul_add; simp,
add_left_cancel this,
..M }
section module
variables [ring α] [add_comm_group β] [module α β] (r s : α) (x y : β)
@[simp] theorem neg_smul : -r • x = - (r • x) :=
eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul])
variables (α)
theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp
variables {α}
@[simp] theorem smul_neg : r • (-x) = -(r • x) :=
by rw [← neg_one_smul α, ← mul_smul, mul_neg_one, neg_smul]
theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y :=
by simp [smul_add]; rw smul_neg
theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y :=
by simp [add_smul]
end module
instance semiring.to_semimodule [r : semiring α] : semimodule α α :=
{ smul := (*),
smul_add := mul_add,
add_smul := add_mul,
mul_smul := mul_assoc,
one_smul := one_mul,
zero_smul := zero_mul,
smul_zero := mul_zero, ..r }
@[simp] lemma smul_eq_mul [semiring α] {a a' : α} : a • a' = a * a' := rfl
instance ring.to_module [r : ring α] : module α α :=
{ ..semiring.to_semimodule }
def is_ring_hom.to_module [ring α] [ring β] (f : α → β) [h : is_ring_hom f] : module α β :=
module.of_core
{ smul := λ r x, f r * x,
smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add],
add_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_add, add_mul],
mul_smul := λ r s x, by unfold has_scalar.smul; rw [h.map_mul, mul_assoc],
one_smul := λ x, show f 1 * x = _, by rw [h.map_one, one_mul] }
class is_linear_map (α : Type u) {β : Type v} {γ : Type w}
[ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ]
(f : β → γ) : Prop :=
(add : ∀x y, f (x + y) = f x + f y)
(smul : ∀(c : α) x, f (c • x) = c • f x)
structure linear_map (α : Type u) (β : Type v) (γ : Type w)
[ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ] :=
(to_fun : β → γ)
(add : ∀x y, to_fun (x + y) = to_fun x + to_fun y)
(smul : ∀(c : α) x, to_fun (c • x) = c • to_fun x)
infixr ` →ₗ `:25 := linear_map _
notation β ` →ₗ[`:25 α:25 `] `:0 γ:0 := linear_map α β γ
namespace linear_map
variables {rα : ring α} {gβ : add_comm_group β} {gγ : add_comm_group γ} {gδ : add_comm_group δ}
variables {mβ : module α β} {mγ : module α γ} {mδ : module α δ}
variables (f g : β →ₗ[α] γ)
include α mβ mγ
instance : has_coe_to_fun (β →ₗ[α] γ) := ⟨_, to_fun⟩
@[simp] lemma coe_mk (f : β → γ) (h₁ h₂) :
((linear_map.mk f h₁ h₂ : β →ₗ[α] γ) : β → γ) = f := rfl
theorem is_linear : is_linear_map α f := {..f}
@[ext] theorem ext {f g : β →ₗ[α] γ} (H : ∀ x, f x = g x) : f = g :=
by cases f; cases g; congr'; exact funext H
theorem ext_iff {f g : β →ₗ[α] γ} : f = g ↔ ∀ x, f x = g x :=
⟨by rintro rfl; simp, ext⟩
@[simp] lemma map_add (x y : β) : f (x + y) = f x + f y := f.add x y
@[simp] lemma map_smul (c : α) (x : β) : f (c • x) = c • f x := f.smul c x
@[simp] lemma map_zero : f 0 = 0 :=
by rw [← zero_smul α, map_smul f 0 0, zero_smul]
instance : is_add_group_hom f := { map_add := map_add f }
@[simp] lemma map_neg (x : β) : f (- x) = - f x :=
by rw [← neg_one_smul α, map_smul, neg_one_smul]
@[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y :=
by simp [map_neg, map_add]
@[simp] lemma map_sum {ι} {t : finset ι} {g : ι → β} :
f (t.sum g) = t.sum (λi, f (g i)) :=
(finset.sum_hom f).symm
include mδ
def comp (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) : β →ₗ[α] δ := ⟨f ∘ g, by simp, by simp⟩
@[simp] lemma comp_apply (f : γ →ₗ[α] δ) (g : β →ₗ[α] γ) (x : β) : f.comp g x = f (g x) := rfl
omit mγ mδ
variables [rα] [gβ] [mβ]
def id : β →ₗ[α] β := ⟨id, by simp, by simp⟩
@[simp] lemma id_apply (x : β) : @id α β _ _ _ x = x := rfl
end linear_map
namespace is_linear_map
variables [ring α] [add_comm_group β] [add_comm_group γ]
variables [module α β] [module α γ]
include α
def mk' (f : β → γ) (H : is_linear_map α f) : β →ₗ γ := {to_fun := f, ..H}
@[simp] theorem mk'_apply {f : β → γ} (H : is_linear_map α f) (x : β) :
mk' f H x = f x := rfl
lemma is_linear_map_neg :
is_linear_map α (λ (z : β), -z) :=
is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm)
lemma is_linear_map_smul {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (c : R) :
is_linear_map R (λ (z : α), c • z) :=
begin
refine is_linear_map.mk (smul_add c) _,
intros _ _,
simp [smul_smul],
ac_refl
end
--TODO: move
lemma is_linear_map_smul' {α R : Type*} [add_comm_group α] [comm_ring R] [module R α] (a : α) :
is_linear_map R (λ (c : R), c • a) :=
begin
refine is_linear_map.mk (λ x y, add_smul x y a) _,
intros _ _,
simp [smul_smul]
end
variables {f : β → γ} (lin : is_linear_map α f)
include β γ lin
@[simp] lemma map_zero : f (0 : β) = (0 : γ) :=
by rw [← zero_smul α (0 : β), lin.smul, zero_smul]
@[simp] lemma map_add (x y : β) : f (x + y) = f x + f y :=
by rw [lin.add]
@[simp] lemma map_neg (x : β) : f (- x) = - f x :=
by rw [← neg_one_smul α, lin.smul, neg_one_smul]
@[simp] lemma map_sub (x y : β) : f (x - y) = f x - f y :=
by simp [lin.map_neg, lin.map_add]
end is_linear_map
abbreviation module.End (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] := M →ₗ[R] M
/-- A submodule of a module is one which is closed under vector operations.
This is a sufficient condition for the subset of vectors in the submodule
to themselves form a module. -/
structure submodule (α : Type u) (β : Type v) [ring α]
[add_comm_group β] [module α β] : Type v :=
(carrier : set β)
(zero : (0:β) ∈ carrier)
(add : ∀ {x y}, x ∈ carrier → y ∈ carrier → x + y ∈ carrier)
(smul : ∀ (c:α) {x}, x ∈ carrier → c • x ∈ carrier)
namespace submodule
variables [ring α] [add_comm_group β] [add_comm_group γ]
variables [module α β] [module α γ]
variables (p p' : submodule α β)
variables {r : α} {x y : β}
instance : has_coe (submodule α β) (set β) := ⟨submodule.carrier⟩
instance : has_mem β (submodule α β) := ⟨λ x p, x ∈ (p : set β)⟩
@[simp] theorem mem_coe : x ∈ (p : set β) ↔ x ∈ p := iff.rfl
theorem ext' {s t : submodule α β} (h : (s : set β) = t) : s = t :=
by cases s; cases t; congr'
protected theorem ext'_iff {s t : submodule α β} : (s : set β) = t ↔ s = t :=
⟨ext', λ h, h ▸ rfl⟩
@[ext] theorem ext {s t : submodule α β}
(h : ∀ x, x ∈ s ↔ x ∈ t) : s = t := ext' $ set.ext h
@[simp] lemma zero_mem : (0 : β) ∈ p := p.zero
lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := p.add h₁ h₂
lemma smul_mem (r : α) (h : x ∈ p) : r • x ∈ p := p.smul r h
lemma neg_mem (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul α; exact p.smul_mem _ hx
lemma sub_mem (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := p.add_mem hx (p.neg_mem hy)
lemma neg_mem_iff : -x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa using neg_mem p h, neg_mem p⟩
lemma add_mem_iff_left (h₁ : y ∈ p) : x + y ∈ p ↔ x ∈ p :=
⟨λ h₂, by simpa using sub_mem _ h₂ h₁, λ h₂, add_mem _ h₂ h₁⟩
lemma add_mem_iff_right (h₁ : x ∈ p) : x + y ∈ p ↔ y ∈ p :=
⟨λ h₂, by simpa using sub_mem _ h₂ h₁, add_mem _ h₁⟩
lemma sum_mem {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} :
(∀c∈t, f c ∈ p) → t.sum f ∈ p :=
finset.induction_on t (by simp [p.zero_mem]) (by simp [p.add_mem] {contextual := tt})
instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem _ x.2 y.2⟩⟩
instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩
instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩
instance : has_scalar α p := ⟨λ c x, ⟨c • x.1, smul_mem _ c x.2⟩⟩
@[simp] lemma coe_add (x y : p) : (↑(x + y) : β) = ↑x + ↑y := rfl
@[simp] lemma coe_zero : ((0 : p) : β) = 0 := rfl
@[simp] lemma coe_neg (x : p) : ((-x : p) : β) = -x := rfl
@[simp] lemma coe_smul (r : α) (x : p) : ((r • x : p) : β) = r • ↑x := rfl
instance : add_comm_group p :=
by refine {add := (+), zero := 0, neg := has_neg.neg, ..};
{ intros, apply set_coe.ext, simp }
instance submodule_is_add_subgroup : is_add_subgroup (p : set β) :=
{ zero_mem := p.zero,
add_mem := p.add,
neg_mem := λ _, p.neg_mem }
lemma coe_sub (x y : p) : (↑(x - y) : β) = ↑x - ↑y := by simp
instance : module α p :=
by refine {smul := (•), ..};
{ intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] }
protected def subtype : p →ₗ[α] β :=
by refine {to_fun := coe, ..}; simp [coe_smul]
@[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl
lemma subtype_eq_val (p : submodule α β) :
((submodule.subtype p) : p → β) = subtype.val := rfl
end submodule
@[reducible] def ideal (α : Type u) [comm_ring α] := submodule α α
namespace ideal
variables [comm_ring α] (I : ideal α) {a b : α}
protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem
protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem
lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff
lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left
lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right
protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem
lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _
lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h
end ideal
/-- A vector space is the same as a module, except the scalar ring is actually
a field. (This adds commutativity of the multiplication and existence of inverses.)
This is the traditional generalization of spaces like `ℝ^n`, which have a natural
addition operation and a way to multiply them by real numbers, but no multiplication
operation between vectors. -/
class vector_space (α : Type u) (β : Type v) [discrete_field α] [add_comm_group β] extends module α β
instance discrete_field.to_vector_space {α : Type*} [discrete_field α] : vector_space α α :=
{ .. ring.to_module }
/-- Subspace of a vector space. Defined to equal `submodule`. -/
@[reducible] def subspace (α : Type u) (β : Type v)
[discrete_field α] [add_comm_group β] [vector_space α β] : Type v :=
submodule α β
instance subspace.vector_space {α β}
{f : discrete_field α} [add_comm_group β] [vector_space α β]
(p : subspace α β) : vector_space α p := {..submodule.module p}
namespace submodule
variables {R:discrete_field α} [add_comm_group β] [add_comm_group γ]
variables [vector_space α β] [vector_space α γ]
variables (p p' : submodule α β)
variables {r : α} {x y : β}
include R
set_option class.instance_max_depth 36
theorem smul_mem_iff (r0 : r ≠ 0) : r • x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa [smul_smul, inv_mul_cancel r0] using p.smul_mem (r⁻¹) h,
p.smul_mem r⟩
end submodule
namespace add_comm_monoid
open add_monoid
variables {M : Type*} [add_comm_monoid M]
instance : semimodule ℕ M :=
{ smul := smul,
smul_add := λ _ _ _, smul_add _ _ _,
add_smul := λ _ _ _, add_smul _ _ _,
mul_smul := λ _ _ _, mul_smul _ _ _,
one_smul := one_smul,
zero_smul := zero_smul,
smul_zero := smul_zero }
end add_comm_monoid
namespace add_comm_group
variables {M : Type*} [add_comm_group M]
instance : module ℤ M :=
{ smul := gsmul,
smul_add := λ _ _ _, gsmul_add _ _ _,
add_smul := λ _ _ _, add_gsmul _ _ _,
mul_smul := λ _ _ _, gsmul_mul _ _ _,
one_smul := one_gsmul,
zero_smul := zero_gsmul,
smul_zero := gsmul_zero }
end add_comm_group
def is_add_group_hom.to_linear_map [add_comm_group α] [add_comm_group β]
(f : α → β) [is_add_group_hom f] : α →ₗ[ℤ] β :=
{ to_fun := f,
add := is_add_hom.map_add f,
smul := λ i x, int.induction_on i (by rw [zero_smul, zero_smul, is_add_group_hom.map_zero f])
(λ i ih, by rw [add_smul, add_smul, is_add_hom.map_add f, ih, one_smul, one_smul])
(λ i ih, by rw [sub_smul, sub_smul, is_add_group_hom.map_sub f, ih, one_smul, one_smul]) }
lemma module.smul_eq_smul {R : Type*} [ring R] {β : Type*} [add_comm_group β] [module R β]
(n : ℕ) (b : β) : n • b = (n : R) • b :=
begin
induction n with n ih,
{ rw [nat.cast_zero, zero_smul, zero_smul] },
{ change (n + 1) • b = (n + 1 : R) • b,
rw [add_smul, add_smul, one_smul, ih, one_smul] }
end
lemma finset.sum_const' {α : Type*} (R : Type*) [ring R] {β : Type*}
[add_comm_group β] [module R β] {s : finset α} (b : β) :
finset.sum s (λ (a : α), b) = (finset.card s : R) • b :=
by rw [finset.sum_const, ← module.smul_eq_smul]; refl
|
a94d340b9e59e81643b5021622b2707bdd0841f2 | 67190c9aacc0cac64fb4463d93e84c696a5be896 | /Lists of exercises/List 2/vestidos-LucasDomingues.lean | 3d86ee0a4d41e368c81b7c0481a1682eb45dd518 | [] | no_license | lucasresck/Discrete-Mathematics | ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738 | 0a08081c5f393e5765259d3f1253c3a6dd043dac | refs/heads/master | 1,596,627,857,734 | 1,573,411,500,000 | 1,573,411,500,000 | 212,489,764 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,812 | lean | /-
Problema dos Vestidos
Três irmãs - Ana, Maria e Cláudia - foram a uma festa com vestidos de
cores diferentes. Uma vestia azul, a outra branco e a Terceira
preto. Chegando à festa, o anfitrião perguntou quem era cada uma
delas. As respostas foram:
- A de azul respondeu: “Ana é a que está de branco”
- A de branco falou: “Eu sou Maria”
- A de preto disse: “Cláudia é quem está de branco”
O anfitrião foi capaz de identificar corretamente quem era cada pessoa
considerando que:
- Ana sempre diz a verdade
- Maria às vezes diz a verdade
- Cláudia nunca diz a verdade
Pensando um pouco sobre o problema, pode-se concluir que a Ana estava
com o vestido preto, a Cláudia com o branco e a Maria com o
azul.
Formalizar o problema e usar algum método dedutivo para construir um
argumento formal a favor da conclusão.
Dica: A tabela verdade teria 512 linhas! Existem várias possiveis
formalizações, na que estamos interesados, todos os simbolos
proposicionais necessários estão declarados abaixo.
Vc deve interpretar as respostas e conclusões do anfitrião
considerando as possibilidades de quem poderia ter falado o que.
-/
variables AA AB AP MA MB MP CA CB CP : Prop
open classical
/- Vamos trabalhar as possibilidades de quem disse cada resposta para
concluirmos algumas hipóteses.
Se supormos que Ana estava de azul, encontramos que Ana estava de
branco, pois ela não mente. -/
variable h1 : AA → AB
/-Se supormos que Maria estava de branco, não concluimos nada. Na
verdade, não concluimos nada supondo que Maria estava usando alguma
cor, pois não temos certeza se ela mente ou fala a verdade.
Se supormos que Cláudia está vestindo azul, temos, pela sua resposta,
que Ana não está usando branco! -/
variable h2 : CA → ¬ AB
/- Suponhamos que Ana esteja de branco: então quem está de branco fala
sempre a verdade, de modo que Maria está de branco.-/
variable h3 : AB → MB
/- Se Cládia estava de branco, então a pessoa que estava de branco não
é a Maria, pois sempre mente. Porém, isso não significa que Maria não
estava de branco.
Suponhamos que Ana esteja de preto: então Cláudia está de branco:-/
variable h4 : AP → CB
/- Suponhamos que Cláudia esteja vestindo preto: a pessoa que está
vestindo preto está mentindo, logo Cláudia não está de branco:-/
variable h48 : CP -> ¬ CB
--Além disso, temos que: Ana está vestindo azul, branco ou preto:
variable h5 : AA ∨ AB ∨ AP
variable h6 : MA ∨ MB ∨ MP
variable h7 : CA ∨ CB ∨ CP
-- Ainda mais: cada vestido é realmente vestido por alguém:
variable h8 : AA ∨ MA ∨ CA
variable h9 : AB ∨ MB ∨ CB
variable h10 : AP ∨ MP ∨ CP
/- Sabemos também que uma pessoa vestir uma cor a impede de vestir
outras cores:-/
variable h20 : AA → (¬ AB ∧ ¬ AP)
variable h21 : AB → (¬ AA ∧ ¬ AP)
variable h22 : AP → (¬ AA ∧ ¬ AB)
variable h23 : MA → (¬ MB ∧ ¬ MP)
variable h24 : MB → (¬ MA ∧ ¬ MP)
variable h25 : MP → (¬ MA ∧ ¬ MB)
variable h26 : CA → (¬ CB ∧ ¬ CP)
variable h27 : CB → (¬ CA ∧ ¬ CP)
variable h28 : CP → (¬ CA ∧ ¬ CB)
/- Também é razoável assumir que apenas uma pessoa pode vestir uma
cor de vestido:-/
variable h38 : AA → (¬ MA ∧ ¬ CA)
variable h39 : AB → (¬ MB ∧ ¬ CB)
variable h40 : AP → (¬ MP ∧ ¬ CP)
variable h41 : MA → (¬ AA ∧ ¬ CA)
variable h42 : MB → (¬ AB ∧ ¬ CB)
variable h43 : MP → (¬ AP ∧ ¬ CP)
variable h44 : CA → (¬ AA ∧ ¬ MA)
variable h45 : CB → (¬ AB ∧ ¬ MB)
variable h46 : CP → (¬ AP ∧ ¬ MP)
example : AP ∧ MA ∧ CB :=
have h11 : AP, from
by_contradiction
(assume h13 : ¬ AP,
show false, from
or.elim h5
(assume h14 : AA,
have h36 : AA → false, from
(assume h37 : AA,
show false, from
(show ¬ AB, from and.left (h20 h37))
(show AB, from h1 h37)),
show false, from h36 h14)
(assume h15 : AB ∨ AP,
show false, from
or.elim h15
(assume h16 : AB,
have h37 : AB → false, from
(assume h47 : AB,
(show ¬ MB, from and.left (h39 h47))
(show MB, from h3 h47)),
show false, from h37 h16)
(assume h17 : AP,
show false, from h13 h17))),
have h19 : CB, from h4 h11,
have h18 : MA, from
by_contradiction
(assume h29: ¬ MA,
have h30 : ¬ AA, from and.left (h22 h11),
have h31 : ¬ CA, from and.left (h27 h19),
show false, from
or.elim h8
(assume h32 : AA, h30 h32)
(assume h33 : MA ∨ CA,
show false, from
or.elim h33
(assume h34 : MA, h29 h34)
(assume h35 : CA, h31 h35))),
have h12 : MA ∧ CB, from and.intro h18 h19,
and.intro h11 h12
|
71e2406b756ddae35eb5d306f1c30a21b35182c4 | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /instructor/types/prod/structure_photo.lean | d1f72e35d2d38b80f281d4a31e42fecd97769e91 | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 747 | lean | structure Photo : Type :=
mk :: (caption : string) (filename : string) (rating : ℕ)
open Photo
def change_rating : Photo → ℕ → Photo :=
λ p n,
Photo.mk p.caption p.filename n
def change_rating' (p : Photo) (n : ℕ) : Photo :=
Photo.mk p.caption p.filename n
def change_rating'' : Photo → ℕ → Photo
| p n := Photo.mk p.caption p.filename n
def change_caption : Photo → string → Photo :=
λ p s, Photo.mk s p.filename p.rating
def change_filename : Photo → string → Photo :=
λ p s, Photo.mk p.caption s p.rating
def p1 := Photo.mk "a caption" "a_file/foo.jpg" 5
def p2 := change_rating p1 3
#eval p1.caption
#eval p1.filename
#eval p1.rating
#eval p2.caption
#eval p2.filename
#eval p2.rating |
a4ebca92abaa54fb12ee80538aa0f8a1439e9a5a | 5cb186111bc6de231aef3b26698e9235da128bb0 | /macro.lean | 7f1308d810403096dec11d063473bb1ec7e76575 | [] | no_license | Kha/syntax | 2f96982b920a24d9bdbbb48ad6acce1817e62f26 | af05028581955d9fd5af99be9cbb82f5c9226551 | refs/heads/master | 1,631,456,662,519 | 1,523,806,396,000 | 1,523,978,266,000 | 110,000,924 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,233 | lean | import syntax
attribute [instance] name.has_lt_quick option.has_lt
@[irreducible] def parse_m (r σ) := except_t string $ reader_t r $ state σ
namespace parse_m
section
local attribute [reducible] parse_m
instance (r σ) : monad (parse_m r σ) := by apply_instance
instance (r σ) : monad_run _ (parse_m r σ) := by apply_instance
instance (r σ) : monad_except string (parse_m r σ) := by apply_instance
instance (r σ) : monad_reader r (parse_m r σ) := by apply_instance
instance (r σ) : monad_state σ (parse_m r σ) := by apply_instance
instance (r σ σ') : monad_state_adapter σ σ' (parse_m r σ) (parse_m r σ') := by apply_instance
instance (r r' σ) : monad_reader_adapter r r' (parse_m r σ) (parse_m r' σ) := by apply_instance
end
def run {r σ α} (cfg : r) (st : σ) (x : parse_m r σ α) :=
let r := monad_run.run x in r cfg st
def run' {r σ α} (cfg : r) (st : σ): parse_m r σ α → except string α :=
λ x, prod.fst $ parse_m.run cfg st x
end parse_m
structure resolved :=
-- local or global
(decl : syntax_id ⊕ name)
/- prefix of the reference that corresponds to the decl. All trailing name components
are field accesses. -/
(«prefix» : name)
meta instance : has_to_format resolved := ⟨λ r, to_fmt (r.decl, r.prefix)⟩
structure resolve_cfg :=
(global_scope : rbmap name syntax)
@[reducible] def resolve_map := rbmap syntax_id resolved
structure resolve_state :=
(resolve_map : resolve_map)
def scope := rbmap (name × option macro_scope_id) syntax_id
@[reducible] def resolve_m := parse_m resolve_cfg resolve_state
def exp_fuel := 1000
structure macro :=
(name : name)
-- (read : reader)
-- TODO: What else does an expander need? How to model recursive expansion?
(expand : option (syntax_node syntax → syntax) := none)
(resolve : option (scope → syntax_node syntax → resolve_m (list scope)) := none)
-- (elaborate : list syntax → expr → tactic expr)
structure parse_state :=
(macros : rbmap name macro)
(resolve_cfg : resolve_cfg)
-- identifiers in macro expansions are annotated with incremental tags
structure expand_state :=
(next_tag : ℕ)
@[reducible] def exp_m := parse_m parse_state expand_state
def mk_tag : exp_m ℕ :=
do st ← get,
put {st with next_tag := st.next_tag + 1},
pure st.next_tag
def flip_tag (tag : ℕ) : syntax → syntax
| (syntax.node node) := syntax.node {node with args := (node.args.map
-- flip_tag
(λ s, flip_tag s))}
| (syntax.list ls) := syntax.list (ls.map
-- flip_tag
(λ s, flip_tag s))
| (syntax.ident ident@{msc := none, ..}) := syntax.ident {ident with msc := some tag}
| (syntax.ident ident@{msc := some tag', ..}) :=
syntax.ident {ident with msc := if tag = tag' then none else some tag'}
| stx := stx
using_well_founded { dec_tac := tactic.admit } -- TODO
def expand : ℕ → syntax → exp_m syntax
| 0 _ := throw "macro expansion limit exceeded"
| (fuel + 1) (syntax.node node) :=
do cfg ← read,
some {expand := some exp, ..} ← pure $ cfg.macros.find node.m
| (λ args, syntax.node {node with args := args}) <$> node.args.mmap (expand fuel),
tag ← mk_tag,
let node := {node with args := node.args.map $ flip_tag tag},
-- expand recursively
expand fuel $ flip_tag tag $ exp node
| _ stx := pure stx
@[reducible] def resolve_m' := parse_m parse_state resolve_state
def resolve : scope → syntax → resolve_m' unit
| sc (syntax.node node) :=
do cfg ← read,
some {resolve := some res, ..} ← pure $ cfg.macros.find node.m
| node.args.mmap' $ resolve sc,
arg_scopes ← adapt_reader parse_state.resolve_cfg $ res sc node,
(arg_scopes.zip node.args).mmap' -- (uncurry resolve)
(λ ⟨sc, stx⟩, resolve sc stx)
| _ _ := pure ()
using_well_founded { dec_tac := tactic.admit }
def expand' (stx : syntax) : parse_m parse_state unit syntax :=
adapt_state (λ _, ({expand_state . next_tag := 0}, ())) (λ _, id) (expand 1000 stx)
def resolve' (stx : syntax) : parse_m parse_state unit (syntax × resolve_state) :=
let sc : scope := mk_rbmap _ _ _,
st : resolve_state := ⟨mk_rbmap _ _ _⟩ in
adapt_state (λ _, (st, ())) (λ _, id) $
do resolve sc stx,
rsm ← get,
pure (stx, rsm)
|
4f255b3c06cf1c9794cb044d9064d2c66e5d688b | 626e312b5c1cb2d88fca108f5933076012633192 | /src/set_theory/cardinal.lean | 54767d824eef67cdbdef84171a132512cd46a3fe | [
"Apache-2.0"
] | permissive | Bioye97/mathlib | 9db2f9ee54418d29dd06996279ba9dc874fd6beb | 782a20a27ee83b523f801ff34efb1a9557085019 | refs/heads/master | 1,690,305,956,488 | 1,631,067,774,000 | 1,631,067,774,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 56,564 | 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, Floris van Doorn
-/
import data.set.countable
import set_theory.schroeder_bernstein
import data.fintype.card
import data.nat.enat
/-!
# Cardinal Numbers
We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity.
## Main definitions
* `cardinal` the type of cardinal numbers (in a given universe).
* `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale
`cardinal`.
* There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`.
* Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`.
* Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`.
* The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`.
* Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`.
* `cardinal.omega` the cardinality of `ℕ`. This definition is universe polymorphic:
`cardinal.omega.{u} : cardinal.{u}`
(contrast with `ℕ : Type`, which lives in a specific universe).
In some cases the universe level has to be given explicitly.
* `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`.
* `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`.
* `cardinal.sum` is the sum of a collection of cardinals.
* `cardinal.sup` is the supremum of a collection of cardinals.
* `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`.
## Main Statements
* Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`.
* König's theorem: `cardinal.sum_lt_prod`
## Implementation notes
* There is a type of cardinal numbers in every universe level:
`cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`.
The operation `cardinal.lift` lifts cardinal numbers to a higher level.
* Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file
`set_theory/cardinal_ordinal.lean`.
* There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both
the base and the exponent live in the same universe. As a workaround, you can add
```
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
```
to a file. This notation will work even if Lean doesn't know yet that the base and the exponent
live in the same universe (but no exponents in other types can be used).
## References
* <https://en.wikipedia.org/wiki/Cardinal_number>
## Tags
cardinal number, cardinal arithmetic, cardinal exponentiation, omega,
Cantor's theorem, König's theorem, Konig's theorem
-/
open function set
open_locale classical
universes u v w x
variables {α β : Type u}
/-- The equivalence relation on types given by equivalence (bijective correspondence) of types.
Quotienting by this equivalence relation gives the cardinal numbers.
-/
instance cardinal.is_equivalent : setoid (Type u) :=
{ r := λα β, nonempty (α ≃ β),
iseqv := ⟨λα,
⟨equiv.refl α⟩,
λα β ⟨e⟩, ⟨e.symm⟩,
λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `cardinal.{u}` is the type of cardinal numbers in `Type u`,
defined as the quotient of `Type u` by existence of an equivalence
(a bijection with explicit inverse). -/
def cardinal : Type (u + 1) := quotient cardinal.is_equivalent
namespace cardinal
/-- The cardinal number of a type -/
def mk : Type u → cardinal := quotient.mk
localized "notation `#` := cardinal.mk" in cardinal
protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq
@[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl
@[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _
/-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if
there exists an embedding (injective function) from α to β. -/
instance : has_le cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $
assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩
theorem le_def (α β : Type u) : mk α ≤ mk β ↔ nonempty (α ↪ β) :=
iff.rfl
theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β :=
⟨⟨f, hf⟩⟩
theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α :=
⟨embedding.of_surjective f hf⟩
theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} :
c ≤ mk α ↔ ∃ p : set α, mk p = c :=
⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩,
⟨set.range f, eq.symm $ quot.sound ⟨equiv.of_injective f hf⟩⟩,
λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩
theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) :=
by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl }
protected lemma eq_congr : α ≃ β → # α = # β :=
λ h, quot.sound ⟨h⟩
noncomputable instance : linear_order cardinal.{u} :=
{ le := (≤),
le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩,
le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩,
le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂),
le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total,
decidable_le := classical.dec_rel _ }
-- short-circuit type class inference
noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance
instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩
instance : inhabited cardinal.{u} := ⟨0⟩
@[simp]
lemma eq_zero_of_is_empty {α : Type u} [is_empty α] : mk α = 0 :=
quotient.sound ⟨equiv.equiv_pempty α⟩
lemma eq_zero_iff_is_empty {α : Type u} : mk α = 0 ↔ is_empty α :=
⟨λ e, let ⟨h⟩ := quotient.exact e in
equiv.equiv_empty_equiv α $ h.trans equiv.empty_equiv_pempty.symm,
@eq_zero_of_is_empty _⟩
theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α :=
(not_iff_not.2 eq_zero_iff_is_empty).trans not_is_empty_iff
instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩
instance : nontrivial cardinal.{u} :=
⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩
theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α :=
⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩,
λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩
theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α :=
by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp }
instance : has_add cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩
@[simp] theorem add_def (α β : Type u) : mk α + mk β = mk (α ⊕ β) := rfl
instance : has_mul cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩
@[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl
private theorem add_comm (a b : cardinal.{u}) : a + b = b + a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩
private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩
private theorem zero_add (a : cardinal.{u}) : 0 + a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.empty_sum pempty α⟩
private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩
private theorem one_mul (a : cardinal.{u}) : 1 * a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩
private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} :
a * b = 0 → a = 0 ∨ b = 0 :=
begin
refine quotient.induction_on b _,
refine quotient.induction_on a _,
intros a b h,
contrapose h,
simp_rw [not_or_distrib, ← ne.def] at h,
have := @prod.nonempty a b (ne_zero_iff_nonempty.mp h.1) (ne_zero_iff_nonempty.mp h.2),
exact ne_zero_iff_nonempty.mpr this
end
instance : comm_semiring cardinal.{u} :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
zero_add := zero_add,
add_zero := assume a, by rw [add_comm a 0, zero_add a],
add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_assoc α β γ⟩,
add_comm := add_comm,
zero_mul := zero_mul,
mul_zero := assume a, by rw [mul_comm a 0, zero_mul a],
one_mul := one_mul,
mul_one := assume a, by rw [mul_comm a 1, one_mul a],
mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.prod_assoc α β γ⟩,
mul_comm := mul_comm,
left_distrib := left_distrib,
right_distrib := assume a b c,
by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] }
/-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/
protected def power (a b : cardinal.{u}) : cardinal.{u} :=
quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩
instance : has_pow cardinal cardinal := ⟨cardinal.power⟩
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
@[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl
@[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.pempty_arrow_equiv_punit α⟩
@[simp] theorem power_one {a : cardinal} : a ^ 1 = a :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.punit_arrow_equiv α⟩
@[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.arrow_punit_equiv_punit α⟩
@[simp] theorem prop_eq_two : mk (ulift Prop) = 2 :=
quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 :=
quotient.induction_on a $ assume α heq,
(ne_zero_iff_nonempty.1 heq).elim $ assume a,
by { haveI : nonempty α := ⟨a⟩, exact quotient.sound ⟨equiv.equiv_pempty _⟩ }
theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 :=
quotient.induction_on₂ a b $ λ α β h,
let ⟨a⟩ := ne_zero_iff_nonempty.1 h in
ne_zero_iff_nonempty.2 ⟨λ _, a⟩
theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩
theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩
theorem power_mul {a b c : cardinal} : a ^ (b * c) = (a ^ b) ^ c :=
by rw [_root_.mul_comm b c];
from (quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.curry γ β α⟩)
@[simp] lemma pow_cast_right (κ : cardinal.{u}) :
∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n
| 0 := by simp
| (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right]
section order_properties
open sum
protected theorem zero_le : ∀(a : cardinal), 0 ≤ a :=
by rintro ⟨α⟩; exact ⟨embedding.of_is_empty⟩
protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩
protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c :=
cardinal.add_le_add (le_refl _)
protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c :=
⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩,
have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from
(equiv.sum_congr (equiv.of_injective f hf) (equiv.refl _)).trans $
(equiv.set.sum_compl (range f)),
⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩,
λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩
instance : order_bot cardinal.{u} :=
{ bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order }
instance : canonically_ordered_comm_semiring cardinal.{u} :=
{ add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h,
le_iff_exists_add := @cardinal.le_iff_exists_add,
eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero,
..cardinal.order_bot,
..cardinal.comm_semiring, ..cardinal.linear_order }
noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} :=
{ .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}),
.. cardinal.linear_order }
@[simp] theorem zero_lt_one : (0 : cardinal) < 1 :=
lt_of_le_of_ne (zero_le _) zero_ne_one
lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 :=
by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le }
theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact
let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in
⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩
theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 :=
begin
by_cases ha : a = 0,
simp [ha, zero_power_le],
exact le_trans (power_le_power_left ha h) (le_max_left _ _)
end
theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩
end order_properties
/-- **Cantor's theorem** -/
theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a :=
by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨
⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩,
λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $
λ s t h, by funext a; injection congr_fun (hf h) a⟩
instance : no_top_order cardinal.{u} :=
{ no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order }
/-- The minimum cardinal in a family of cardinals (the existence
of which is provided by `injective_min`). -/
noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal :=
f $ classical.some $
@embedding.min_injective _ (λ i, (f i).out) I
theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i :=
⟨_, rfl⟩
theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i :=
by rw [← mk_out (min I f), ← mk_out (f i)]; exact
let ⟨g⟩ := classical.some_spec
(@embedding.min_injective _ (λ i, (f i).out) I) in
⟨g i⟩
theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i :=
⟨λ h i, le_trans h (min_le _ _),
λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩
protected theorem wf : @well_founded cardinal.{u} (<) :=
⟨λ a, classical.by_contradiction $ λ h,
let ι := {c :cardinal // ¬ acc (<) c},
f : ι → cardinal := subtype.val,
⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in
hc (acc.intro _ (λ j ⟨_, h'⟩,
classical.by_contradiction $ λ hj, h' $
by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩
instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩
instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩
/-- The successor cardinal - the smallest cardinal greater than
`c`. This is not the same as `c + 1` except in the case of finite `c`. -/
noncomputable def succ (c : cardinal) : cardinal :=
@min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val
theorem lt_succ_self (c : cardinal) : c < succ c :=
by cases min_eq _ _ with s e; rw [succ, e]; exact s.2
theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (lt_succ_self _), λ h,
by exact min_le _ (subtype.mk b h)⟩
theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c :=
begin
refine quot.induction_on c (λ α, _) (lt_succ_self c),
refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _),
cases h.left with f,
have : ¬ surjective f := λ hn,
ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩),
cases not_forall.1 this with b nex,
refine ⟨⟨sum.rec (by exact f) _, _⟩⟩,
{ exact λ _, b },
{ intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩,
{ rw f.injective h },
{ exact nex.elim ⟨_, h⟩ },
{ exact nex.elim ⟨_, h.symm⟩ },
{ refl } }
end
lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 :=
by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le }
/-- The indexed sum of cardinals is the cardinality of the
indexed disjoint union, i.e. sigma type. -/
def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out
theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f :=
by rw ← quotient.out_eq (f i); exact
⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩
@[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) :=
quot.sound ⟨equiv.sigma_congr_right $ λ i,
classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩
theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a :=
quotient.induction_on a $ λ α, by simp; exact
quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩
theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g :=
⟨(embedding.refl _).sigma_map $ λ i, classical.choice $
by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩
/-- The indexed supremum of cardinals is the smallest cardinal above
everything in the family. -/
noncomputable def sup {ι} (f : ι → cardinal) : cardinal :=
@min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1)
theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f :=
by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i
theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h,
λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩
theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g :=
sup_le.2 $ λ i, le_trans (H i) (le_sup _ _)
theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f :=
sup_le.2 $ le_sum _
theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f :=
by rw ← sum_const; exact sum_le_sum _ _ (le_sup _)
theorem sup_eq_zero {ι} {f : ι → cardinal} [is_empty ι] : sup f = 0 :=
by { rw [← nonpos_iff_eq_zero, sup_le], exact is_empty_elim }
/-- The indexed product of cardinals is the cardinality of the Pi type
(dependent product). -/
def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out)
@[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) :=
quot.sound ⟨equiv.Pi_congr_right $ λ i,
classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩
theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι :=
quotient.induction_on a $ by simp
theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g :=
⟨embedding.Pi_congr_right $ λ i, classical.choice $
by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩
theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 :=
begin
suffices : nonempty (Π i, (f i).out) ↔ ∀ i, nonempty (f i).out,
{ simpa [← ne_zero_iff_nonempty, prod] },
exact classical.nonempty_pi
end
theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 :=
not_iff_not.1 $ by simpa using prod_ne_zero f
/-- The universe lift operation on cardinals. You can specify the universes explicitly with
`lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/
def lift (c : cardinal.{u}) : cardinal.{max u v} :=
quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩,
quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩
theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ λ a, quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_id' (a : cardinal) : lift a = a :=
quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : cardinal) :
lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_mk_le {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) :=
⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩,
λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩
/-- A variant of `lift_mk_le` with specialized universes.
Because Lean often can not realize it should use this specialization itself,
we provide this statement separately so you don't have to solve the specialization problem either.
-/
theorem lift_mk_le' {α : Type u} {β : Type v} :
lift.{u v} (mk α) ≤ lift.{v u} (mk β) ↔ nonempty (α ↪ β) :=
lift_mk_le.{u v 0}
theorem lift_mk_eq {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩,
λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩
/-- A variant of `lift_mk_eq` with specialized universes.
Because Lean often can not realize it should use this specialization itself,
we provide this statement separately so you don't have to solve the specialization problem either.
-/
theorem lift_mk_eq' {α : Type u} {β : Type v} :
lift.{u v} (mk α) = lift.{v u} (mk β) ↔ nonempty (α ≃ β) :=
lift_mk_eq.{u v 0}
@[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b :=
quotient.induction_on₂ a b $ λ α β,
by rw ← lift_umax; exact lift_mk_le
@[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b :=
by simp [le_antisymm_iff]
@[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a :=
by simp [bit0]
@[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) :=
le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $
let ⟨i, e⟩ := min_eq I (lift ∘ f) in
by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $
by have := min_le (lift ∘ f) j; rwa e at this)
theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a → ∃ a', lift a' = b :=
quotient.induction_on₂ a b $ λ α β,
by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact
λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2
⟨embedding.equiv_of_surjective
(embedding.cod_restrict _ f set.mem_range_self)
$ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩
theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a :=
⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩
theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b < lift a ↔ ∃ a', lift a' = b ∧ a' < a :=
⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
⟨a', e, lift_lt.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
le_antisymm
(le_of_not_gt $ λ h, begin
rcases lt_lift_iff.1 h with ⟨b, e, h⟩,
rw [lt_succ, ← lift_le, e] at h,
exact not_lt_of_le h (lt_succ_self _)
end)
(succ_le.2 $ lift_lt.2 $ lt_succ_self _)
@[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} :
lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b :=
calc lift.{u (max v w)} a = lift.{v (max u w)} b
↔ lift.{(max u v) w} (lift.{u v} a)
= lift.{(max u v) w} (lift.{v u} b) : by simp
... ↔ lift.{u v} a = lift.{v u} b : lift_inj
theorem mk_prod {α : Type u} {β : Type v} :
mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) :=
quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩
theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) :
sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a :=
begin
apply quotient.induction_on a,
intro α,
simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id],
convert mk_prod using 1,
exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩,
end
protected lemma le_sup_iff {ι : Type v} {f : ι → cardinal.{max v w}} {c : cardinal} :
(c ≤ sup f) ↔ (∀ b, (∀ i, f i ≤ b) → c ≤ b) :=
⟨λ h b hb, le_trans h (sup_le.mpr hb), λ h, h _ $ λ i, le_sup f i⟩
/-- The lift of a supremum is the supremum of the lifts. -/
lemma lift_sup {ι : Type v} (f : ι → cardinal.{max v w}) :
lift.{(max v w) u} (sup.{v w} f) =
sup.{v (max u w)} (λ i : ι, lift.{(max v w) u} (f i)) :=
begin
apply le_antisymm,
{ rw [cardinal.le_sup_iff], intros c hc, by_contra h,
obtain ⟨d, rfl⟩ := cardinal.lift_down (not_le.mp h).le,
simp only [lift_le, sup_le] at h hc,
exact h hc },
{ simp only [cardinal.sup_le, lift_le, le_sup, implies_true_iff] }
end
/-- To prove that the lift of a supremum is bounded by some cardinal `t`,
it suffices to show that the lift of each cardinal is bounded by `t`. -/
lemma lift_sup_le {ι : Type v} (f : ι → cardinal.{max v w})
(t : cardinal.{max u v w}) (w : ∀ i, lift.{_ u} (f i) ≤ t) :
lift.{(max v w) u} (sup f) ≤ t :=
by { rw lift_sup, exact sup_le.mpr w, }
@[simp] lemma lift_sup_le_iff {ι : Type v} (f : ι → cardinal.{max v w}) (t : cardinal.{max u v w}) :
lift.{(max v w) u} (sup f) ≤ t ↔ ∀ i, lift.{_ u} (f i) ≤ t :=
⟨λ h i, (lift_le.mpr (le_sup f i)).trans h,
λ h, lift_sup_le f t h⟩
universes v' w'
/--
To prove an inequality between the lifts to a common universe of two different supremums,
it suffices to show that the lift of each cardinal from the smaller supremum
if bounded by the lift of some cardinal from the larger supremum.
-/
lemma lift_sup_le_lift_sup
{ι : Type v} {ι' : Type v'} (f : ι → cardinal.{max v w}) (f' : ι' → cardinal.{max v' w'})
(g : ι → ι') (h : ∀ i, lift.{_ (max v' w')} (f i) ≤ lift.{_ (max v w)} (f' (g i))) :
lift.{_ (max v' w')} (sup f) ≤ lift.{_ (max v w)} (sup f') :=
begin
apply lift_sup_le.{(max v' w')} f,
intro i,
apply le_trans (h i),
simp only [lift_le],
apply le_sup,
end
/-- A variant of `lift_sup_le_lift_sup` with universes specialized via `w = v` and `w' = v'`.
This is sometimes necessary to avoid universe unification issues. -/
lemma lift_sup_le_lift_sup'
{ι : Type v} {ι' : Type v'} (f : ι → cardinal.{v}) (f' : ι' → cardinal.{v'})
(g : ι → ι') (h : ∀ i, lift.{_ v'} (f i) ≤ lift.{_ v} (f' (g i))) :
lift.{_ v'} (sup.{v v} f) ≤ lift.{_ v} (sup.{v' v'} f') :=
lift_sup_le_lift_sup f f' g h
/-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/
def omega : cardinal.{u} := lift (mk ℕ)
lemma mk_nat : mk nat = omega := (lift_id _).symm
theorem omega_ne_zero : omega ≠ 0 :=
ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩
theorem omega_pos : 0 < omega :=
pos_iff_ne_zero.2 omega_ne_zero
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
/- properties about the cast from nat -/
@[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n
| 0 := quotient.sound ⟨equiv.equiv_pempty _⟩
| (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact
quotient.sound (fintype.card_eq.1 $ by simp)
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n; simp *
lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} :
(n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a :=
by rw [← lift_nat_cast.{u v} n, lift_inj]
theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp
theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α :=
by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}];
exact fintype.card_eq.1 (by simp)
theorem card_le_of_finset {α} (s : finset α) :
(s.card : cardinal) ≤ cardinal.mk α :=
begin
rw (_ : (s.card : cardinal) = cardinal.mk s),
{ exact ⟨function.embedding.subtype _⟩ },
rw [cardinal.fintype_card, fintype.card_coe]
end
@[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n :=
by induction n; simp [pow_succ', -_root_.add_comm, power_add, *]
@[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n :=
by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact
⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf,
λ h, ⟨(fin.cast_le h).to_embedding⟩⟩
@[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n :=
by simp [lt_iff_le_not_le, -not_le]
@[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n :=
by simp [le_antisymm_iff]
@[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n :=
le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _)
@[simp] theorem succ_zero : succ 0 = 1 :=
by norm_cast
theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) :
# α ≤ n :=
begin
refine lt_succ.1 (lt_of_not_ge $ λ hn, _),
rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn,
cases hn with f,
refine not_lt_of_le (H $ finset.univ.map f) _,
rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin],
exact n.lt_succ_self
end
theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a :=
by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb;
exact lt_of_lt_of_le (cantor _) (power_le_power_right hb)
theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega :=
succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact
⟨⟨coe, λ a b, fin.ext⟩⟩
@[simp] theorem one_lt_omega : 1 < omega :=
by simpa using nat_lt_omega 1
theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n :=
⟨λ h, begin
rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩,
rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩,
suffices : finite S,
{ cases this, resetI,
existsi fintype.card S,
rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] },
by_contra nf,
have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a :=
λ n IH,
let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in
not_forall.1 (λ h, nf
⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩),
let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)),
refine not_le_of_lt h' ⟨⟨F, _⟩⟩,
suffices : ∀ (n : ℕ) (m < n), F m ≠ F n,
{ refine λ m n, not_imp_not.1 (λ ne, _),
rcases lt_trichotomy m n with h|h|h,
{ exact this n m h },
{ contradiction },
{ exact (this m n h).symm } },
intros n m h,
have := classical.some_spec (P n (λ y _, F y)),
rw [← show F n = classical.some (P n (λ y _, F y)),
from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this,
exact λ e, this ⟨m, h, e⟩,
end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩
theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ h, le_of_not_lt $ λ hn, begin
rcases lt_omega.1 hn with ⟨n, rfl⟩,
exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1)))
end⟩
theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) :=
lt_omega.trans ⟨λ ⟨n, e⟩, begin
rw [← lift_mk_fin n] at e,
cases quotient.exact e with f,
exact ⟨fintype.of_equiv _ f.symm⟩
end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩
theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S :=
lt_omega_iff_fintype
instance can_lift_cardinal_nat : can_lift cardinal ℕ :=
⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩
theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega :=
⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩,
λ⟨h1, h2⟩, add_lt_omega h1 h2⟩
theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega
end
lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega :=
begin
split,
{ intro h, by_cases ha : a = 0, { left, exact ha },
right, by_cases hb : b = 0, { left, exact hb },
right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split,
{ rw [← mul_one a],
refine lt_of_le_of_lt (mul_le_mul' (le_refl a) hb) h },
{ rw [← _root_.one_mul b],
refine lt_of_le_of_lt (mul_le_mul' ha (le_refl b)) h }},
rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero]
end
lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) :
a * b < omega ↔ a < omega ∧ b < omega :=
by simp [mul_lt_omega_iff, ha, hb]
theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega
end
lemma eq_one_iff_unique {α : Type*} :
mk α = 1 ↔ subsingleton α ∧ nonempty α :=
calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt
... ↔ subsingleton α ∧ nonempty α :
begin
apply and_congr le_one_iff_subsingleton,
push_neg,
rw [one_le_iff_ne_zero, ne_zero_iff_nonempty]
end
theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α :=
by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_iff, is_empty_fintype]
lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega :=
⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩,
λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩
lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega :=
begin
rw [countable_iff_exists_injective], split,
rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩,
rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩
end
/-- This function sends finite cardinals to the corresponding natural, and infinite cardinals
to 0. -/
noncomputable def to_nat : zero_hom cardinal ℕ :=
⟨λ c, if h : c < omega.{v} then classical.some (lt_omega.1 h) else 0,
begin
have h : 0 < omega := nat_lt_omega 0,
rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_omega.1 h), nat.cast_zero],
end⟩
lemma to_nat_apply_of_lt_omega {c : cardinal} (h : c < omega) :
c.to_nat = classical.some (lt_omega.1 h) :=
dif_pos h
@[simp]
lemma to_nat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) :
c.to_nat = 0 :=
dif_neg (not_lt_of_le h)
@[simp]
lemma cast_to_nat_of_lt_omega {c : cardinal} (h : c < omega) :
↑c.to_nat = c :=
by rw [to_nat_apply_of_lt_omega h, ← classical.some_spec (lt_omega.1 h)]
@[simp]
lemma cast_to_nat_of_omega_le {c : cardinal} (h : omega ≤ c) :
↑c.to_nat = (0 : cardinal) :=
by rw [to_nat_apply_of_omega_le h, nat.cast_zero]
@[simp]
lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n :=
begin
rw [to_nat_apply_of_lt_omega (nat_lt_omega n), ← nat_cast_inj],
exact (classical.some_spec (lt_omega.1 (nat_lt_omega n))).symm,
end
/-- `to_nat` has a right-inverse: coercion. -/
lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast
lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective
lemma nat_cast_injective : injective (coe : ℕ → cardinal) :=
to_nat_right_inverse.left_inverse.injective
@[simp]
lemma mk_to_nat_of_infinite [h : infinite α] : (mk α).to_nat = 0 :=
dif_neg (not_lt_of_le (infinite_iff.1 h))
@[simp]
lemma mk_to_nat_eq_card [fintype α] : (mk α).to_nat = fintype.card α :=
by simp [fintype_card]
@[simp]
lemma zero_to_nat : cardinal.to_nat 0 = 0 :=
by rw [← to_nat_cast 0, nat.cast_zero]
@[simp]
lemma one_to_nat : cardinal.to_nat 1 = 1 :=
by rw [← to_nat_cast 1, nat.cast_one]
lemma to_nat_mul (x y : cardinal) : (x * y).to_nat = x.to_nat * y.to_nat :=
begin
by_cases hx1 : x = 0,
{ rw [comm_semiring.mul_comm, hx1, mul_zero, zero_to_nat, nat.zero_mul] },
by_cases hy1 : y = 0,
{ rw [hy1, zero_to_nat, mul_zero, mul_zero, zero_to_nat] },
refine nat_cast_injective (eq.trans _ (nat.cast_mul _ _).symm),
cases lt_or_ge x omega with hx2 hx2,
{ cases lt_or_ge y omega with hy2 hy2,
{ rw [cast_to_nat_of_lt_omega, cast_to_nat_of_lt_omega hx2, cast_to_nat_of_lt_omega hy2],
exact mul_lt_omega hx2 hy2 },
{ rw [cast_to_nat_of_omega_le hy2, mul_zero, cast_to_nat_of_omega_le],
exact not_lt.mp (mt (mul_lt_omega_iff_of_ne_zero hx1 hy1).mp (λ h, not_lt.mpr hy2 h.2)) } },
{ rw [cast_to_nat_of_omega_le hx2, _root_.zero_mul, cast_to_nat_of_omega_le],
exact not_lt.mp (mt (mul_lt_omega_iff_of_ne_zero hx1 hy1).mp (λ h, not_lt.mpr hx2 h.1)) },
end
/-- This function sends finite cardinals to the corresponding natural, and infinite cardinals
to `⊤`. -/
noncomputable def to_enat : cardinal →+ enat :=
{ to_fun := λ c, if c < omega.{v} then c.to_nat else ⊤,
map_zero' := by simp [if_pos (lt_trans zero_lt_one one_lt_omega)],
map_add' := λ x y, begin
by_cases hx : x < omega,
{ obtain ⟨x0, rfl⟩ := lt_omega.1 hx,
by_cases hy : y < omega,
{ obtain ⟨y0, rfl⟩ := lt_omega.1 hy,
simp only [add_lt_omega hx hy, hx, hy, to_nat_cast, if_true],
rw [← nat.cast_add, to_nat_cast, enat.coe_add] },
{ rw [if_neg hy, if_neg, enat.add_top],
contrapose! hy,
apply lt_of_le_of_lt le_add_self hy } },
{ rw [if_neg hx, if_neg, enat.top_add],
contrapose! hx,
apply lt_of_le_of_lt le_self_add hx },
end }
@[simp]
lemma to_enat_apply_of_lt_omega {c : cardinal} (h : c < omega) :
c.to_enat = c.to_nat :=
if_pos h
@[simp]
lemma to_enat_apply_of_omega_le {c : cardinal} (h : omega ≤ c) :
c.to_enat = ⊤ :=
if_neg (not_lt_of_le h)
@[simp]
lemma to_enat_cast (n : ℕ) : cardinal.to_enat n = n :=
by rw [to_enat_apply_of_lt_omega (nat_lt_omega n), to_nat_cast]
@[simp]
lemma mk_to_enat_of_infinite [h : infinite α] : (mk α).to_enat = ⊤ :=
to_enat_apply_of_omega_le (infinite_iff.1 h)
lemma to_enat_surjective : surjective to_enat :=
begin
intro x,
exact enat.cases_on x ⟨omega, to_enat_apply_of_omega_le (le_refl omega)⟩
(λ n, ⟨n, to_enat_cast n⟩),
end
@[simp]
lemma mk_to_enat_eq_coe_card [fintype α] : (mk α).to_enat = fintype.card α :=
by simp [fintype_card]
lemma mk_int : mk ℤ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma mk_pnat : mk ℕ+ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y :=
begin
split,
{ rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h },
{ rintro ⟨x, y, h⟩, by_contra h',
rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h',
apply h, exactI subsingleton.elim _ _ }
end
lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y :=
begin
rw [two_le_iff],
split,
{ rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩),
rw [←h'] at h, exact ⟨z, h⟩ },
{ rintro ⟨y, h⟩, exact ⟨x, y, h⟩ }
end
/-- **König's theorem** -/
theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g :=
lt_of_not_ge $ λ ⟨F⟩, begin
have : inhabited (Π (i : ι), (g i).out),
{ refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩,
rw mk_out,
exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI,
let G := inv_fun F,
have sG : surjective G := inv_fun_surjective F.2,
choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b,
{ assume i,
simp only [- not_exists, not_exists.symm, not_forall.symm],
refine λ h, not_le_of_lt (H i) _,
rw [← mk_out (f i), ← mk_out (g i)],
exact ⟨embedding.of_surjective _ h⟩ },
exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _))
end
@[simp] theorem mk_empty : mk empty = 0 :=
fintype_card empty
@[simp] theorem mk_pempty : mk pempty = 0 :=
fintype_card pempty
@[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 :=
by { haveI : is_empty p := ⟨h⟩, exact quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty _⟩ }
theorem mk_unit : mk unit = 1 :=
(fintype_card unit).trans nat.cast_one
@[simp] theorem mk_punit : mk punit = 1 :=
(fintype_card punit).trans nat.cast_one
@[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 :=
quotient.sound ⟨equiv.set.singleton x⟩
@[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 :=
quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩
@[simp] theorem mk_bool : mk bool = 2 :=
quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem mk_Prop : mk Prop = 2 :=
(quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool
@[simp] theorem mk_set {α : Type u} : mk (set α) = 2 ^ mk α :=
begin
rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq],
exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩,
end
@[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 :=
quotient.sound ⟨equiv.option_equiv_sum_punit α⟩
theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :=
calc mk (list α)
= mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩
... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩
... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩
... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :
by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk]
theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α :=
mk_le_of_surjective quot.exists_rep
theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α :=
mk_quot_le
theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α :=
⟨embedding.subtype p⟩
theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) :
mk (subtype p) ≤ mk (subtype q) :=
⟨embedding.subtype_map (embedding.refl α) h⟩
@[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 :=
quotient.sound ⟨equiv.set.pempty α⟩
lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ :=
begin
split,
{ intro h,
have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h],
refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _),
rcases cardinal.eq.mp h2 with ⟨f, _⟩,
cases f ⟨_, hx⟩ },
{ intro, convert mk_emptyc _ }
end
theorem mk_univ {α : Type u} : mk (@univ α) = mk α :=
quotient.sound ⟨equiv.set.univ α⟩
theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s :=
mk_le_of_surjective surjective_onto_image
theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} :
lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) :=
lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩
theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α :=
mk_le_of_surjective surjective_onto_range
theorem mk_range_le_lift {α : Type u} {β : Type v} {f : α → β} :
lift.{v u} (mk (range f)) ≤ lift.{u v} (mk α) :=
lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_range⟩
lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α :=
quotient.sound ⟨(equiv.of_injective f h).symm⟩
lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v u} (mk (range f)) = lift.{u v} (mk α) :=
begin
have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.of_injective f hf).symm⟩,
simp only [lift_umax.{u v}, lift_umax.{v u}] at this,
exact this
end
lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) :
lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) :=
lift_mk_eq.mpr ⟨(equiv.of_injective f hf).symm⟩
theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image f s hf).symm⟩
theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f)
... = sum (λ i, mk (f i)) : (sum_mk _).symm
theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) :
mk (⋃ i, f i) = sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩
... = sum (λi, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le {α ι : Type u} (f : ι → set α) :
mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) :=
le_trans mk_Union_le_sum_mk (sum_le_sup _)
lemma mk_sUnion_le {α : Type u} (A : set (set α)) :
mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) :=
by { rw [sUnion_eq_Union], apply mk_Union_le }
lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) :
mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) :=
by { rw [bUnion_eq_Union], apply mk_Union_le }
@[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk s :=
by rw [fintype_card, nat_cast_inj, fintype.card_coe]
lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega :=
by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ }
theorem mk_eq_nat_iff_finset {α} {s : set α} {n : ℕ} :
mk s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n :=
begin
split,
{ intro h,
have : # s < omega, by { rw h, exact nat_lt_omega n },
refine ⟨(lt_omega_iff_finite.1 this).to_finset, finite.coe_to_finset _, nat_cast_inj.1 _⟩,
rwa [finset_card, finite.coe_sort_to_finset] },
{ rintro ⟨t, rfl, rfl⟩,
exact finset_card.symm }
end
theorem mk_union_add_mk_inter {α : Type u} {S T : set α} :
mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union_sum_inter S T⟩
/-- The cardinality of a union is at most the sum of the cardinalities
of the two sets. -/
lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T :=
@mk_union_add_mk_inter α S T ▸ self_le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α))
theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) :
mk (S ∪ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union H⟩
lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α :=
quotient.sound ⟨equiv.set.sum_compl s⟩
lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t :=
⟨set.embedding_of_subset s t h⟩
lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} :=
⟨embedding_of_subset _ _ h⟩
lemma mk_set_le (s : set α) : mk s ≤ mk α :=
mk_subtype_le s
lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) :
lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩
lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α)
(h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) :
mk {a : α // p (e a)} = mk {b : β // p b} :=
quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩
lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } :=
quotient.sound ⟨equiv.set.sep s t⟩
lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) :=
begin
rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2),
apply subtype.coind_injective, exact h.comp subtype.val_injective
end
lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) :=
begin
rw lift_mk_le.{v u 0},
refine ⟨⟨_, _⟩⟩,
{ rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ },
rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp,
rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩,
rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩,
simp, intro hxx', rw hxx'
end
lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) :=
le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2)
lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) :
mk (f ⁻¹' s) ≤ mk s :=
by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_subset_range (f : α → β) (s : set β)
(h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) :=
by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s :=
by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] }
lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α}
{t : set β} (h : t ⊆ f '' s) :
lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1,
rw [mk_sep], refl }
lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) :
mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1,
rw [mk_sep], refl }
theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} :
c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c :=
begin
rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype],
apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective
end
/-- The function α^{<β}, defined to be sup_{γ < β} α^γ.
We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a
higher universe -/
noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} :=
sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s)
infix ` ^< `:80 := powerlt
theorem powerlt_aux {c c' : cardinal} (h : c < c') :
∃(s : {s : set c'.out // mk s < c'}), mk s = c :=
begin
cases out_embedding.mp (le_of_lt h) with f,
have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 },
exact ⟨⟨range f, by convert h⟩, this⟩
end
lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ :=
by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s }
lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ :=
begin
rw [powerlt, sup_le],
split,
{ intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s },
intros h s, exact h _ s.2
end
lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c :=
by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h }
lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ :=
begin
apply le_antisymm,
{ rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] },
{ apply le_powerlt, apply lt_succ_self }
end
lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) :=
by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] }
lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 :=
begin
apply le_antisymm,
{ rw [powerlt_le], intros c hc, apply zero_power_le },
convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero]
end
lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 :=
begin
convert sup_eq_zero,
exact subtype.is_empty_of_false (λ x, (zero_le _).not_lt),
end
end cardinal
lemma equiv.cardinal_eq {α β} : α ≃ β → cardinal.mk α = cardinal.mk β :=
cardinal.eq_congr
|
7bb08a39623b7c0c511995451981fe2434377ed0 | 30b14a7aeb43b837dc6a6062ece989d79ce7139c | /lamport-clock/lean/model.lean | 525605d80d0086349850ac8cb3be1ce2ebf22445 | [] | no_license | cartazio/formal-time | 69cc0eab65ce2db7bf62ab8a240dc82d2431133b | c8f2f1f20e43d7d379f3104db7542281467bb662 | refs/heads/master | 1,609,483,922,526 | 1,500,341,459,000 | 1,500,341,459,000 | 97,533,151 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 107 | lean | /-
this will be a simple modelling of some of the basic relations
from the lamport clock paper in lean
-/ |
baf321299963113ea2abd14b6e3c1c6da6eaffd1 | f3be49eddff7edf577d3d3666e314d995f7a6357 | /TBA/Solutions/Exercise3.lean | 1fc15310913299cd5bd18e7f2ffd6c281ad71efe | [] | no_license | IPDSnelting/tba-2021 | 8b930bcd2f4aae44a2ddc86e72b77f84e6d46e82 | b6390e55b768423d3266969e81d19290129c5914 | refs/heads/master | 1,686,754,693,583 | 1,625,135,602,000 | 1,625,136,365,000 | 355,124,341 | 50 | 7 | null | 1,625,133,762,000 | 1,617,699,824,000 | Lean | UTF-8 | Lean | false | false | 6,581 | lean | /- NATURAL NUMBERS
We saw the definition of the natural numbers `Nat` and the addition on them on the slides.
Since we want to define it ourselves and not use Lean's built-in version, we will call ours `Nat'`.
-/
inductive Nat' : Type
| zero : Nat'
| succ : Nat' → Nat'
open Nat'
def add (m n : Nat') : Nat' :=
match n with
| zero => m
| succ n => succ (add m n)
-- Let us now try to recursively define multiplication on the `Nat'`.
def mul (m n : Nat') : Nat' :=
match n with
| zero => zero
| succ n => add (mul m n) m
-- Let's define `≤` as an inductive predicate on `Nat'`s!
inductive LE' : Nat' → Nat' → Prop where
| refl (n : Nat') : LE' n n
-- TODO: We're off to a good start since `≤` is certainly reflexive, but something is still
-- missing (or else we'd just redefine `Eq` for `Nat'`s). Can you think of one more constructor
-- that makes it so `LE' n m` holds whenever we would intuitively expect `n ≤ m` to hold?
-- hint: it remains to be shown that `LE' n m` should hold when `m` is *greater* than `n`, so
-- the new constructor should probably involve `Nat'`'s `succ` constructor to reach those greater numbers.
-- hint: it should be an *inductive* case, meaning using another `LE'` application as an assumption
-- note: `LE'` could also be defined in terms of `add`, but that makes working with it awkward,
-- so let's not do that.
| succ : LE' m n → LE' m (succ n)
-- Now let's prove some things about `LE'`. But first we'll give it the standard notation.
infix:50 " ≤ " => LE'
example (n : Nat') : n ≤ succ (succ n) :=
LE'.succ (LE'.succ (LE'.refl n))
-- This one is a bit harder: we will need induction!
-- As described on the slides, induction is just a special case of recursion
theorem le_add (m n : Nat') : m ≤ add m n :=
match n with
-- This is the base case
| zero => LE'.refl m
-- This is the inductive case. You probably want to use `le_add m n` (the inductive hypothesis) somewhere inside of it!
| succ n =>
-- Lean automatically converts `add m (succ n)` to `succ (add m n)` for us when necessary, but it can help
-- to make the conversion explicit. `show` simply lets us restate the goal, using any definitionally equivalent type.
show m ≤ succ (add m n) from
LE'.succ (le_add m n)
-- Now try proving this theorem on `add` using the same induction scheme
theorem zero_add (n : Nat') : add zero n = add n zero :=
match n with
| zero => rfl
| succ n =>
show succ (add zero n) = succ (add n zero) from
zero_add n ▸ rfl
/-
LISTS
The type List α of lists on a Type α is defined to be the type on the constructors
nil : List α
and
cons : (x : α) → (xs : List α) → List α.
We can use [] as a notation for nil and x :: xs as a notation for cons x xs.
-/
open List
-- Let's define something we can't in most other functional languages:
-- a function returning the first element of a list given a proof that is is non-empty! (xs ≠ [] is shorthand for ¬ (xs = []))
-- hint: match on `xs` *before* using `fun` so that the `xs` in the assumption is replaced by the match!
def hd (xs : List α) : xs ≠ [] → α :=
match xs with
| [] => fun hf => False.elim (hf rfl)
| x :: xs => fun _ => x
/-
TREES
Define a type Tree α of binary trees with labels of type α. Each tree is either a labelled leaf or a labelled node with two trees attached to it.
-/
inductive Tree (α : Type) : Type where
| leaf : α → Tree α
| node : α → Tree α → Tree α → Tree α
open Tree
-- Now, let us define the depth and the size of a tree. You can use the function Nat.max to get the maximum of two natural numbers. The depth of a leaf is 1.
def depth (t : Tree α) : Nat :=
match t with
| leaf a => 1
| node a l r => Nat.max (depth l) (depth r) + 1
def size (t : Tree α) : Nat :=
match t with
| leaf a => 1
| node a l r => 1 + size l + size r
-- We can turn a tree into a list by traversing it in various ways, depending on whether we add the root
-- before its subtrees (preOrder), between its subtrees (inOrder) or after its subtrees (postOrder).
-- Define preOrder, inOrder, and postOrder as functions Tree α → List α.
def preOrder (t : Tree α) : List α :=
match t with
| leaf a => [a]
| node a l r => a :: preOrder l ++ preOrder r
def inOrder (t : Tree α) : List α :=
match t with
| leaf a => [a]
| node a l r => inOrder l ++ a :: inOrder r
def postOrder (t : Tree α) : List α :=
match t with
| leaf a => [a]
| node a l r => postOrder l ++ postOrder r ++ [a]
-- Define a function which returns the mirror image of a given tree.
def mirror (t : Tree α) : Tree α :=
match t with
| leaf a => leaf a
| node a l r => node a (mirror r) (mirror l)
-- Now we prove to facts about this function:
-- First, we prove that it is involutive (mirroring a tree twice returns the original tree).
-- Then, we prove that the mirror image of two trees is equal, if and only if the trees themselves are.
-- Useful lemmas, if you don't want to use ▸ as much (but it is also just as doable with some `have`s and ▸):
#check @Eq.trans
#check @Eq.symm
#check @congrArg
theorem mirror_involutive (t : Tree α) : mirror (mirror t) = t :=
match t with
| leaf a => rfl
| node a l r =>
show node _ _ _ = _ from
Eq.symm (mirror_involutive l) ▸ Eq.symm (mirror_involutive r) ▸ rfl
theorem mirror_eq (s t : Tree α) : mirror s = mirror t ↔ s = t :=
Iff.intro
(fun h =>
have mmsmmt : mirror (mirror s) = mirror (mirror t) := h ▸ rfl
mirror_involutive s ▸ mirror_involutive t ▸ mmsmmt)
(fun h => congrArg mirror h)
/- STRUCTURES -/
-- Define the structure `Semigroup α` for a semigroup on a type `α`.
-- Reminder: A semigroup is an algebraic structure with an associative binary operation `mul`.
structure Semigroup (α : Type) where
mul : α → α → α
assoc : mul (mul a b) c = mul a (mul b c)
-- Now extend the structure to one for a monoid on α.
-- Reminder : A monoid is a semigroup with an element which acts as the left and right identity on `mul`.
structure Monoid (α : Type) extends Semigroup α where
e : α
e_mul : mul e a = a
mul_e : mul a e = a
-- Now try to instantiate the type `Nat'` as a monoid.
-- Leave out the three proofs (associativiy, left and right inverse), we'll learn better ways to write such proofs next week.
def Nat'Monoid : Monoid Nat' :=
{ mul := mul,
assoc := sorry,
e := succ zero,
e_mul := sorry,
mul_e := sorry }
|
a4f7cc4b00b1167c5e7e07efa96e3fba902dbff8 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/set/intervals/basic_auto.lean | 66f691e4b097f923a85f8e8ed8dbf2387a4c9843 | [] | 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 | 51,861 | 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, Patrick Massot, Yury Kudryashov, Rémy Degenne
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.ordered_group
import Mathlib.data.set.basic
import Mathlib.PostPort
universes u
namespace Mathlib
/-!
# Intervals
In any preorder `α`, we define intervals (which on each side can be either infinite, open, or
closed) using the following naming conventions:
- `i`: infinite
- `o`: open
- `c`: closed
Each interval has the name `I` + letter for left side + letter for right side. For instance,
`Ioc a b` denotes the inverval `(a, b]`.
This file contains these definitions, and basic facts on inclusion, intersection, difference of
intervals (where the precise statements may depend on the properties of the order, in particular
for some statements it should be `linear_order` or `densely_ordered`).
TODO: This is just the beginning; a lot of rules are missing
-/
namespace set
/-- Left-open right-open interval -/
def Ioo {α : Type u} [preorder α] (a : α) (b : α) : set α := set_of fun (x : α) => a < x ∧ x < b
/-- Left-closed right-open interval -/
def Ico {α : Type u} [preorder α] (a : α) (b : α) : set α := set_of fun (x : α) => a ≤ x ∧ x < b
/-- Left-infinite right-open interval -/
def Iio {α : Type u} [preorder α] (a : α) : set α := set_of fun (x : α) => x < a
/-- Left-closed right-closed interval -/
def Icc {α : Type u} [preorder α] (a : α) (b : α) : set α := set_of fun (x : α) => a ≤ x ∧ x ≤ b
/-- Left-infinite right-closed interval -/
def Iic {α : Type u} [preorder α] (b : α) : set α := set_of fun (x : α) => x ≤ b
/-- Left-open right-closed interval -/
def Ioc {α : Type u} [preorder α] (a : α) (b : α) : set α := set_of fun (x : α) => a < x ∧ x ≤ b
/-- Left-closed right-infinite interval -/
def Ici {α : Type u} [preorder α] (a : α) : set α := set_of fun (x : α) => a ≤ x
/-- Left-open right-infinite interval -/
def Ioi {α : Type u} [preorder α] (a : α) : set α := set_of fun (x : α) => a < x
theorem Ioo_def {α : Type u} [preorder α] (a : α) (b : α) :
(set_of fun (x : α) => a < x ∧ x < b) = Ioo a b :=
rfl
theorem Ico_def {α : Type u} [preorder α] (a : α) (b : α) :
(set_of fun (x : α) => a ≤ x ∧ x < b) = Ico a b :=
rfl
theorem Iio_def {α : Type u} [preorder α] (a : α) : (set_of fun (x : α) => x < a) = Iio a := rfl
theorem Icc_def {α : Type u} [preorder α] (a : α) (b : α) :
(set_of fun (x : α) => a ≤ x ∧ x ≤ b) = Icc a b :=
rfl
theorem Iic_def {α : Type u} [preorder α] (b : α) : (set_of fun (x : α) => x ≤ b) = Iic b := rfl
theorem Ioc_def {α : Type u} [preorder α] (a : α) (b : α) :
(set_of fun (x : α) => a < x ∧ x ≤ b) = Ioc a b :=
rfl
theorem Ici_def {α : Type u} [preorder α] (a : α) : (set_of fun (x : α) => a ≤ x) = Ici a := rfl
theorem Ioi_def {α : Type u} [preorder α] (a : α) : (set_of fun (x : α) => a < x) = Ioi a := rfl
@[simp] theorem mem_Ioo {α : Type u} [preorder α] {a : α} {b : α} {x : α} :
x ∈ Ioo a b ↔ a < x ∧ x < b :=
iff.rfl
@[simp] theorem mem_Ico {α : Type u} [preorder α] {a : α} {b : α} {x : α} :
x ∈ Ico a b ↔ a ≤ x ∧ x < b :=
iff.rfl
@[simp] theorem mem_Iio {α : Type u} [preorder α] {b : α} {x : α} : x ∈ Iio b ↔ x < b := iff.rfl
@[simp] theorem mem_Icc {α : Type u} [preorder α] {a : α} {b : α} {x : α} :
x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b :=
iff.rfl
@[simp] theorem mem_Iic {α : Type u} [preorder α] {b : α} {x : α} : x ∈ Iic b ↔ x ≤ b := iff.rfl
@[simp] theorem mem_Ioc {α : Type u} [preorder α] {a : α} {b : α} {x : α} :
x ∈ Ioc a b ↔ a < x ∧ x ≤ b :=
iff.rfl
@[simp] theorem mem_Ici {α : Type u} [preorder α] {a : α} {x : α} : x ∈ Ici a ↔ a ≤ x := iff.rfl
@[simp] theorem mem_Ioi {α : Type u} [preorder α] {a : α} {x : α} : x ∈ Ioi a ↔ a < x := iff.rfl
@[simp] theorem left_mem_Ioo {α : Type u} [preorder α] {a : α} {b : α} : a ∈ Ioo a b ↔ False :=
sorry
@[simp] theorem left_mem_Ico {α : Type u} [preorder α] {a : α} {b : α} : a ∈ Ico a b ↔ a < b :=
sorry
@[simp] theorem left_mem_Icc {α : Type u} [preorder α] {a : α} {b : α} : a ∈ Icc a b ↔ a ≤ b :=
sorry
@[simp] theorem left_mem_Ioc {α : Type u} [preorder α] {a : α} {b : α} : a ∈ Ioc a b ↔ False :=
sorry
theorem left_mem_Ici {α : Type u} [preorder α] {a : α} : a ∈ Ici a :=
eq.mpr (id (propext mem_Ici)) (le_refl a)
@[simp] theorem right_mem_Ioo {α : Type u} [preorder α] {a : α} {b : α} : b ∈ Ioo a b ↔ False :=
sorry
@[simp] theorem right_mem_Ico {α : Type u} [preorder α] {a : α} {b : α} : b ∈ Ico a b ↔ False :=
sorry
@[simp] theorem right_mem_Icc {α : Type u} [preorder α] {a : α} {b : α} : b ∈ Icc a b ↔ a ≤ b :=
sorry
@[simp] theorem right_mem_Ioc {α : Type u} [preorder α] {a : α} {b : α} : b ∈ Ioc a b ↔ a < b :=
sorry
theorem right_mem_Iic {α : Type u} [preorder α] {a : α} : a ∈ Iic a :=
eq.mpr (id (propext mem_Iic)) (le_refl a)
@[simp] theorem dual_Ici {α : Type u} [preorder α] {a : α} : Ici a = Iic a := rfl
@[simp] theorem dual_Iic {α : Type u} [preorder α] {a : α} : Iic a = Ici a := rfl
@[simp] theorem dual_Ioi {α : Type u} [preorder α] {a : α} : Ioi a = Iio a := rfl
@[simp] theorem dual_Iio {α : Type u} [preorder α] {a : α} : Iio a = Ioi a := rfl
@[simp] theorem dual_Icc {α : Type u} [preorder α] {a : α} {b : α} : Icc a b = Icc b a :=
ext fun (x : order_dual α) => and_comm (a ≤ x) (x ≤ b)
@[simp] theorem dual_Ioc {α : Type u} [preorder α] {a : α} {b : α} : Ioc a b = Ico b a :=
ext fun (x : order_dual α) => and_comm (a < x) (x ≤ b)
@[simp] theorem dual_Ico {α : Type u} [preorder α] {a : α} {b : α} : Ico a b = Ioc b a :=
ext fun (x : order_dual α) => and_comm (a ≤ x) (x < b)
@[simp] theorem dual_Ioo {α : Type u} [preorder α] {a : α} {b : α} : Ioo a b = Ioo b a :=
ext fun (x : order_dual α) => and_comm (a < x) (x < b)
@[simp] theorem nonempty_Icc {α : Type u} [preorder α] {a : α} {b : α} :
set.nonempty (Icc a b) ↔ a ≤ b :=
sorry
@[simp] theorem nonempty_Ico {α : Type u} [preorder α] {a : α} {b : α} :
set.nonempty (Ico a b) ↔ a < b :=
sorry
@[simp] theorem nonempty_Ioc {α : Type u} [preorder α] {a : α} {b : α} :
set.nonempty (Ioc a b) ↔ a < b :=
sorry
@[simp] theorem nonempty_Ici {α : Type u} [preorder α] {a : α} : set.nonempty (Ici a) :=
Exists.intro a left_mem_Ici
@[simp] theorem nonempty_Iic {α : Type u} [preorder α] {a : α} : set.nonempty (Iic a) :=
Exists.intro a right_mem_Iic
@[simp] theorem nonempty_Ioo {α : Type u} [preorder α] {a : α} {b : α} [densely_ordered α] :
set.nonempty (Ioo a b) ↔ a < b :=
sorry
@[simp] theorem nonempty_Ioi {α : Type u} [preorder α] {a : α} [no_top_order α] :
set.nonempty (Ioi a) :=
no_top a
@[simp] theorem nonempty_Iio {α : Type u} [preorder α] {a : α} [no_bot_order α] :
set.nonempty (Iio a) :=
no_bot a
theorem nonempty_Icc_subtype {α : Type u} [preorder α] {a : α} {b : α} (h : a ≤ b) :
Nonempty ↥(Icc a b) :=
nonempty.to_subtype (iff.mpr nonempty_Icc h)
theorem nonempty_Ico_subtype {α : Type u} [preorder α] {a : α} {b : α} (h : a < b) :
Nonempty ↥(Ico a b) :=
nonempty.to_subtype (iff.mpr nonempty_Ico h)
theorem nonempty_Ioc_subtype {α : Type u} [preorder α] {a : α} {b : α} (h : a < b) :
Nonempty ↥(Ioc a b) :=
nonempty.to_subtype (iff.mpr nonempty_Ioc h)
/-- An interval `Ici a` is nonempty. -/
protected instance nonempty_Ici_subtype {α : Type u} [preorder α] {a : α} : Nonempty ↥(Ici a) :=
nonempty.to_subtype nonempty_Ici
/-- An interval `Iic a` is nonempty. -/
protected instance nonempty_Iic_subtype {α : Type u} [preorder α] {a : α} : Nonempty ↥(Iic a) :=
nonempty.to_subtype nonempty_Iic
theorem nonempty_Ioo_subtype {α : Type u} [preorder α] {a : α} {b : α} [densely_ordered α]
(h : a < b) : Nonempty ↥(Ioo a b) :=
nonempty.to_subtype (iff.mpr nonempty_Ioo h)
/-- In a `no_top_order`, the intervals `Ioi` are nonempty. -/
protected instance nonempty_Ioi_subtype {α : Type u} [preorder α] {a : α} [no_top_order α] :
Nonempty ↥(Ioi a) :=
nonempty.to_subtype nonempty_Ioi
/-- In a `no_bot_order`, the intervals `Iio` are nonempty. -/
protected instance nonempty_Iio_subtype {α : Type u} [preorder α] {a : α} [no_bot_order α] :
Nonempty ↥(Iio a) :=
nonempty.to_subtype nonempty_Iio
@[simp] theorem Ioo_eq_empty {α : Type u} [preorder α] {a : α} {b : α} (h : b ≤ a) : Ioo a b = ∅ :=
sorry
@[simp] theorem Ico_eq_empty {α : Type u} [preorder α] {a : α} {b : α} (h : b ≤ a) : Ico a b = ∅ :=
sorry
@[simp] theorem Icc_eq_empty {α : Type u} [preorder α] {a : α} {b : α} (h : b < a) : Icc a b = ∅ :=
sorry
@[simp] theorem Ioc_eq_empty {α : Type u} [preorder α] {a : α} {b : α} (h : b ≤ a) : Ioc a b = ∅ :=
sorry
@[simp] theorem Ioo_self {α : Type u} [preorder α] (a : α) : Ioo a a = ∅ := Ioo_eq_empty (le_refl a)
@[simp] theorem Ico_self {α : Type u} [preorder α] (a : α) : Ico a a = ∅ := Ico_eq_empty (le_refl a)
@[simp] theorem Ioc_self {α : Type u} [preorder α] (a : α) : Ioc a a = ∅ := Ioc_eq_empty (le_refl a)
theorem Ici_subset_Ici {α : Type u} [preorder α] {a : α} {b : α} : Ici a ⊆ Ici b ↔ b ≤ a :=
{ mp := fun (h : Ici a ⊆ Ici b) => h left_mem_Ici,
mpr := fun (h : b ≤ a) (x : α) (hx : x ∈ Ici a) => le_trans h hx }
theorem Iic_subset_Iic {α : Type u} [preorder α] {a : α} {b : α} : Iic a ⊆ Iic b ↔ a ≤ b :=
Ici_subset_Ici
theorem Ici_subset_Ioi {α : Type u} [preorder α] {a : α} {b : α} : Ici a ⊆ Ioi b ↔ b < a :=
{ mp := fun (h : Ici a ⊆ Ioi b) => h left_mem_Ici,
mpr := fun (h : b < a) (x : α) (hx : x ∈ Ici a) => lt_of_lt_of_le h hx }
theorem Iic_subset_Iio {α : Type u} [preorder α] {a : α} {b : α} : Iic a ⊆ Iio b ↔ a < b :=
{ mp := fun (h : Iic a ⊆ Iio b) => h right_mem_Iic,
mpr := fun (h : a < b) (x : α) (hx : x ∈ Iic a) => lt_of_le_of_lt hx h }
theorem Ioo_subset_Ioo {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α} (h₁ : a₂ ≤ a₁)
(h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ :=
sorry
theorem Ioo_subset_Ioo_left {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b : α} (h : a₁ ≤ a₂) :
Ioo a₂ b ⊆ Ioo a₁ b :=
Ioo_subset_Ioo h (le_refl b)
theorem Ioo_subset_Ioo_right {α : Type u} [preorder α] {a : α} {b₁ : α} {b₂ : α} (h : b₁ ≤ b₂) :
Ioo a b₁ ⊆ Ioo a b₂ :=
Ioo_subset_Ioo (le_refl a) h
theorem Ico_subset_Ico {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α} (h₁ : a₂ ≤ a₁)
(h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ :=
sorry
theorem Ico_subset_Ico_left {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b : α} (h : a₁ ≤ a₂) :
Ico a₂ b ⊆ Ico a₁ b :=
Ico_subset_Ico h (le_refl b)
theorem Ico_subset_Ico_right {α : Type u} [preorder α] {a : α} {b₁ : α} {b₂ : α} (h : b₁ ≤ b₂) :
Ico a b₁ ⊆ Ico a b₂ :=
Ico_subset_Ico (le_refl a) h
theorem Icc_subset_Icc {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α} (h₁ : a₂ ≤ a₁)
(h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ :=
sorry
theorem Icc_subset_Icc_left {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b : α} (h : a₁ ≤ a₂) :
Icc a₂ b ⊆ Icc a₁ b :=
Icc_subset_Icc h (le_refl b)
theorem Icc_subset_Icc_right {α : Type u} [preorder α] {a : α} {b₁ : α} {b₂ : α} (h : b₁ ≤ b₂) :
Icc a b₁ ⊆ Icc a b₂ :=
Icc_subset_Icc (le_refl a) h
theorem Icc_subset_Ioo {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α} (ha : a₂ < a₁)
(hb : b₁ < b₂) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ :=
fun (x : α) (hx : x ∈ Icc a₁ b₁) =>
{ left := lt_of_lt_of_le ha (and.left hx), right := lt_of_le_of_lt (and.right hx) hb }
theorem Icc_subset_Ici_self {α : Type u} [preorder α] {a : α} {b : α} : Icc a b ⊆ Ici a :=
fun (x : α) => and.left
theorem Icc_subset_Iic_self {α : Type u} [preorder α] {a : α} {b : α} : Icc a b ⊆ Iic b :=
fun (x : α) => and.right
theorem Ioc_subset_Iic_self {α : Type u} [preorder α] {a : α} {b : α} : Ioc a b ⊆ Iic b :=
fun (x : α) => and.right
theorem Ioc_subset_Ioc {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α} (h₁ : a₂ ≤ a₁)
(h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ :=
sorry
theorem Ioc_subset_Ioc_left {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b : α} (h : a₁ ≤ a₂) :
Ioc a₂ b ⊆ Ioc a₁ b :=
Ioc_subset_Ioc h (le_refl b)
theorem Ioc_subset_Ioc_right {α : Type u} [preorder α] {a : α} {b₁ : α} {b₂ : α} (h : b₁ ≤ b₂) :
Ioc a b₁ ⊆ Ioc a b₂ :=
Ioc_subset_Ioc (le_refl a) h
theorem Ico_subset_Ioo_left {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b : α} (h₁ : a₁ < a₂) :
Ico a₂ b ⊆ Ioo a₁ b :=
fun (x : α) => and.imp_left (lt_of_lt_of_le h₁)
theorem Ioc_subset_Ioo_right {α : Type u} [preorder α] {a : α} {b₁ : α} {b₂ : α} (h : b₁ < b₂) :
Ioc a b₁ ⊆ Ioo a b₂ :=
fun (x : α) => and.imp_right fun (h' : x ≤ b₁) => lt_of_le_of_lt h' h
theorem Icc_subset_Ico_right {α : Type u} [preorder α] {a : α} {b₁ : α} {b₂ : α} (h₁ : b₁ < b₂) :
Icc a b₁ ⊆ Ico a b₂ :=
fun (x : α) => and.imp_right fun (h₂ : x ≤ b₁) => lt_of_le_of_lt h₂ h₁
theorem Ioo_subset_Ico_self {α : Type u} [preorder α] {a : α} {b : α} : Ioo a b ⊆ Ico a b :=
fun (x : α) => and.imp_left le_of_lt
theorem Ioo_subset_Ioc_self {α : Type u} [preorder α] {a : α} {b : α} : Ioo a b ⊆ Ioc a b :=
fun (x : α) => and.imp_right le_of_lt
theorem Ico_subset_Icc_self {α : Type u} [preorder α] {a : α} {b : α} : Ico a b ⊆ Icc a b :=
fun (x : α) => and.imp_right le_of_lt
theorem Ioc_subset_Icc_self {α : Type u} [preorder α] {a : α} {b : α} : Ioc a b ⊆ Icc a b :=
fun (x : α) => and.imp_left le_of_lt
theorem Ioo_subset_Icc_self {α : Type u} [preorder α] {a : α} {b : α} : Ioo a b ⊆ Icc a b :=
subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self
theorem Ico_subset_Iio_self {α : Type u} [preorder α] {a : α} {b : α} : Ico a b ⊆ Iio b :=
fun (x : α) => and.right
theorem Ioo_subset_Iio_self {α : Type u} [preorder α] {a : α} {b : α} : Ioo a b ⊆ Iio b :=
fun (x : α) => and.right
theorem Ioc_subset_Ioi_self {α : Type u} [preorder α] {a : α} {b : α} : Ioc a b ⊆ Ioi a :=
fun (x : α) => and.left
theorem Ioo_subset_Ioi_self {α : Type u} [preorder α] {a : α} {b : α} : Ioo a b ⊆ Ioi a :=
fun (x : α) => and.left
theorem Ioi_subset_Ici_self {α : Type u} [preorder α] {a : α} : Ioi a ⊆ Ici a :=
fun (x : α) (hx : x ∈ Ioi a) => le_of_lt hx
theorem Iio_subset_Iic_self {α : Type u} [preorder α] {a : α} : Iio a ⊆ Iic a :=
fun (x : α) (hx : x ∈ Iio a) => le_of_lt hx
theorem Ico_subset_Ici_self {α : Type u} [preorder α] {a : α} {b : α} : Ico a b ⊆ Ici a :=
fun (x : α) => and.left
theorem Icc_subset_Icc_iff {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
sorry
theorem Icc_subset_Ioo_iff {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ :=
sorry
theorem Icc_subset_Ico_iff {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ :=
sorry
theorem Icc_subset_Ioc_iff {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ :=
sorry
theorem Icc_subset_Iio_iff {α : Type u} [preorder α] {a₁ : α} {b₁ : α} {b₂ : α} (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ :=
sorry
theorem Icc_subset_Ioi_iff {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ :=
sorry
theorem Icc_subset_Iic_iff {α : Type u} [preorder α] {a₁ : α} {b₁ : α} {b₂ : α} (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ :=
sorry
theorem Icc_subset_Ici_iff {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} (h₁ : a₁ ≤ b₁) :
Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ :=
sorry
theorem Icc_ssubset_Icc_left {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(hI : a₂ ≤ b₂) (ha : a₂ < a₁) (hb : b₁ ≤ b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ :=
sorry
theorem Icc_ssubset_Icc_right {α : Type u} [preorder α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(hI : a₂ ≤ b₂) (ha : a₂ ≤ a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ :=
sorry
/-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need
the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/
theorem Ioi_subset_Ioi {α : Type u} [preorder α] {a : α} {b : α} (h : a ≤ b) : Ioi b ⊆ Ioi a :=
fun (x : α) (hx : x ∈ Ioi b) => lt_of_le_of_lt h hx
/-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need
the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/
theorem Ioi_subset_Ici {α : Type u} [preorder α] {a : α} {b : α} (h : a ≤ b) : Ioi b ⊆ Ici a :=
subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self
/-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need
the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/
theorem Iio_subset_Iio {α : Type u} [preorder α] {a : α} {b : α} (h : a ≤ b) : Iio a ⊆ Iio b :=
fun (x : α) (hx : x ∈ Iio a) => lt_of_lt_of_le hx h
/-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need
the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/
theorem Iio_subset_Iic {α : Type u} [preorder α] {a : α} {b : α} (h : a ≤ b) : Iio a ⊆ Iic b :=
subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self
theorem Ici_inter_Iic {α : Type u} [preorder α] {a : α} {b : α} : Ici a ∩ Iic b = Icc a b := rfl
theorem Ici_inter_Iio {α : Type u} [preorder α] {a : α} {b : α} : Ici a ∩ Iio b = Ico a b := rfl
theorem Ioi_inter_Iic {α : Type u} [preorder α] {a : α} {b : α} : Ioi a ∩ Iic b = Ioc a b := rfl
theorem Ioi_inter_Iio {α : Type u} [preorder α] {a : α} {b : α} : Ioi a ∩ Iio b = Ioo a b := rfl
theorem mem_Icc_of_Ioo {α : Type u} [preorder α] {a : α} {b : α} {x : α} (h : x ∈ Ioo a b) :
x ∈ Icc a b :=
Ioo_subset_Icc_self h
theorem mem_Ico_of_Ioo {α : Type u} [preorder α] {a : α} {b : α} {x : α} (h : x ∈ Ioo a b) :
x ∈ Ico a b :=
Ioo_subset_Ico_self h
theorem mem_Ioc_of_Ioo {α : Type u} [preorder α] {a : α} {b : α} {x : α} (h : x ∈ Ioo a b) :
x ∈ Ioc a b :=
Ioo_subset_Ioc_self h
theorem mem_Icc_of_Ico {α : Type u} [preorder α] {a : α} {b : α} {x : α} (h : x ∈ Ico a b) :
x ∈ Icc a b :=
Ico_subset_Icc_self h
theorem mem_Icc_of_Ioc {α : Type u} [preorder α] {a : α} {b : α} {x : α} (h : x ∈ Ioc a b) :
x ∈ Icc a b :=
Ioc_subset_Icc_self h
theorem mem_Ici_of_Ioi {α : Type u} [preorder α] {a : α} {x : α} (h : x ∈ Ioi a) : x ∈ Ici a :=
Ioi_subset_Ici_self h
theorem mem_Iic_of_Iio {α : Type u} [preorder α] {a : α} {x : α} (h : x ∈ Iio a) : x ∈ Iic a :=
Iio_subset_Iic_self h
@[simp] theorem Icc_self {α : Type u} [partial_order α] (a : α) : Icc a a = singleton a := sorry
@[simp] theorem Icc_diff_left {α : Type u} [partial_order α] {a : α} {b : α} :
Icc a b \ singleton a = Ioc a b :=
sorry
@[simp] theorem Icc_diff_right {α : Type u} [partial_order α] {a : α} {b : α} :
Icc a b \ singleton b = Ico a b :=
sorry
@[simp] theorem Ico_diff_left {α : Type u} [partial_order α] {a : α} {b : α} :
Ico a b \ singleton a = Ioo a b :=
sorry
@[simp] theorem Ioc_diff_right {α : Type u} [partial_order α] {a : α} {b : α} :
Ioc a b \ singleton b = Ioo a b :=
sorry
@[simp] theorem Icc_diff_both {α : Type u} [partial_order α] {a : α} {b : α} :
Icc a b \ insert a (singleton b) = Ioo a b :=
sorry
@[simp] theorem Ici_diff_left {α : Type u} [partial_order α] {a : α} :
Ici a \ singleton a = Ioi a :=
sorry
@[simp] theorem Iic_diff_right {α : Type u} [partial_order α] {a : α} :
Iic a \ singleton a = Iio a :=
sorry
@[simp] theorem Ico_diff_Ioo_same {α : Type u} [partial_order α] {a : α} {b : α} (h : a < b) :
Ico a b \ Ioo a b = singleton a :=
sorry
@[simp] theorem Ioc_diff_Ioo_same {α : Type u} [partial_order α] {a : α} {b : α} (h : a < b) :
Ioc a b \ Ioo a b = singleton b :=
sorry
@[simp] theorem Icc_diff_Ico_same {α : Type u} [partial_order α] {a : α} {b : α} (h : a ≤ b) :
Icc a b \ Ico a b = singleton b :=
sorry
@[simp] theorem Icc_diff_Ioc_same {α : Type u} [partial_order α] {a : α} {b : α} (h : a ≤ b) :
Icc a b \ Ioc a b = singleton a :=
sorry
@[simp] theorem Icc_diff_Ioo_same {α : Type u} [partial_order α] {a : α} {b : α} (h : a ≤ b) :
Icc a b \ Ioo a b = insert a (singleton b) :=
sorry
@[simp] theorem Ici_diff_Ioi_same {α : Type u} [partial_order α] {a : α} :
Ici a \ Ioi a = singleton a :=
sorry
@[simp] theorem Iic_diff_Iio_same {α : Type u} [partial_order α] {a : α} :
Iic a \ Iio a = singleton a :=
sorry
@[simp] theorem Ioi_union_left {α : Type u} [partial_order α] {a : α} :
Ioi a ∪ singleton a = Ici a :=
sorry
@[simp] theorem Iio_union_right {α : Type u} [partial_order α] {a : α} :
Iio a ∪ singleton a = Iic a :=
ext fun (x : α) => iff.symm le_iff_lt_or_eq
theorem Ioo_union_left {α : Type u} [partial_order α] {a : α} {b : α} (hab : a < b) :
Ioo a b ∪ singleton a = Ico a b :=
sorry
theorem Ioo_union_right {α : Type u} [partial_order α] {a : α} {b : α} (hab : a < b) :
Ioo a b ∪ singleton b = Ioc a b :=
sorry
theorem Ioc_union_left {α : Type u} [partial_order α] {a : α} {b : α} (hab : a ≤ b) :
Ioc a b ∪ singleton a = Icc a b :=
sorry
theorem Ico_union_right {α : Type u} [partial_order α] {a : α} {b : α} (hab : a ≤ b) :
Ico a b ∪ singleton b = Icc a b :=
sorry
theorem mem_Ici_Ioi_of_subset_of_subset {α : Type u} [partial_order α] {a : α} {s : set α}
(ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) : s ∈ insert (Ici a) (singleton (Ioi a)) :=
sorry
theorem mem_Iic_Iio_of_subset_of_subset {α : Type u} [partial_order α] {a : α} {s : set α}
(ho : Iio a ⊆ s) (hc : s ⊆ Iic a) : s ∈ insert (Iic a) (singleton (Iio a)) :=
mem_Ici_Ioi_of_subset_of_subset ho hc
theorem mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {α : Type u} [partial_order α] {a : α} {b : α}
{s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) :
s ∈ insert (Icc a b) (insert (Ico a b) (insert (Ioc a b) (singleton (Ioo a b)))) :=
sorry
theorem mem_Ioo_or_eq_endpoints_of_mem_Icc {α : Type u} [partial_order α] {a : α} {b : α} {x : α}
(hmem : x ∈ Icc a b) : x = a ∨ x = b ∨ x ∈ Ioo a b :=
sorry
theorem mem_Ioo_or_eq_left_of_mem_Ico {α : Type u} [partial_order α] {a : α} {b : α} {x : α}
(hmem : x ∈ Ico a b) : x = a ∨ x ∈ Ioo a b :=
sorry
theorem mem_Ioo_or_eq_right_of_mem_Ioc {α : Type u} [partial_order α] {a : α} {b : α} {x : α}
(hmem : x ∈ Ioc a b) : x = b ∨ x ∈ Ioo a b :=
eq.mp (Eq._oldrec (Eq.refl (x ∈ Ico b a → x = b ∨ x ∈ Ioo a b)) dual_Ico)
(eq.mp (Eq._oldrec (Eq.refl (x ∈ Ico b a → x = b ∨ x ∈ Ioo b a)) dual_Ioo)
mem_Ioo_or_eq_left_of_mem_Ico)
hmem
theorem Ici_singleton_of_top {α : Type u} [partial_order α] {a : α} (h_top : ∀ (x : α), x ≤ a) :
Ici a = singleton a :=
ext
fun (x : α) =>
{ mp := fun (h : x ∈ Ici a) => le_antisymm (h_top x) h,
mpr := fun (h : x ∈ singleton a) => le_of_eq (Eq.symm h) }
theorem Iic_singleton_of_bot {α : Type u} [partial_order α] {a : α} (h_bot : ∀ (x : α), a ≤ x) :
Iic a = singleton a :=
Ici_singleton_of_top h_bot
@[simp] theorem Ici_top {α : Type u} [order_top α] : Ici ⊤ = singleton ⊤ :=
Ici_singleton_of_top fun (_x : α) => le_top
@[simp] theorem Iic_top {α : Type u} [order_top α] : Iic ⊤ = univ :=
eq_univ_of_forall fun (x : α) => le_top
@[simp] theorem Icc_top {α : Type u} [order_top α] {a : α} : Icc a ⊤ = Ici a := sorry
@[simp] theorem Ioc_top {α : Type u} [order_top α] {a : α} : Ioc a ⊤ = Ioi a := sorry
@[simp] theorem Iic_bot {α : Type u} [order_bot α] : Iic ⊥ = singleton ⊥ :=
Iic_singleton_of_bot fun (_x : α) => bot_le
@[simp] theorem Ici_bot {α : Type u} [order_bot α] : Ici ⊥ = univ := Iic_top
@[simp] theorem Icc_bot {α : Type u} [order_bot α] {a : α} : Icc ⊥ a = Iic a := sorry
@[simp] theorem Ico_bot {α : Type u} [order_bot α] {a : α} : Ico ⊥ a = Iio a := sorry
@[simp] theorem compl_Iic {α : Type u} [linear_order α] {a : α} : Iic aᶜ = Ioi a :=
ext fun (_x : α) => not_le
@[simp] theorem compl_Ici {α : Type u} [linear_order α] {a : α} : Ici aᶜ = Iio a :=
ext fun (_x : α) => not_le
@[simp] theorem compl_Iio {α : Type u} [linear_order α] {a : α} : Iio aᶜ = Ici a :=
ext fun (_x : α) => not_lt
@[simp] theorem compl_Ioi {α : Type u} [linear_order α] {a : α} : Ioi aᶜ = Iic a :=
ext fun (_x : α) => not_lt
@[simp] theorem Ici_diff_Ici {α : Type u} [linear_order α] {a : α} {b : α} :
Ici a \ Ici b = Ico a b :=
eq.mpr (id (Eq._oldrec (Eq.refl (Ici a \ Ici b = Ico a b)) (diff_eq (Ici a) (Ici b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ici a ∩ (Ici bᶜ) = Ico a b)) compl_Ici))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ici a ∩ Iio b = Ico a b)) Ici_inter_Iio))
(Eq.refl (Ico a b))))
@[simp] theorem Ici_diff_Ioi {α : Type u} [linear_order α] {a : α} {b : α} :
Ici a \ Ioi b = Icc a b :=
eq.mpr (id (Eq._oldrec (Eq.refl (Ici a \ Ioi b = Icc a b)) (diff_eq (Ici a) (Ioi b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ici a ∩ (Ioi bᶜ) = Icc a b)) compl_Ioi))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ici a ∩ Iic b = Icc a b)) Ici_inter_Iic))
(Eq.refl (Icc a b))))
@[simp] theorem Ioi_diff_Ioi {α : Type u} [linear_order α] {a : α} {b : α} :
Ioi a \ Ioi b = Ioc a b :=
eq.mpr (id (Eq._oldrec (Eq.refl (Ioi a \ Ioi b = Ioc a b)) (diff_eq (Ioi a) (Ioi b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ioi a ∩ (Ioi bᶜ) = Ioc a b)) compl_Ioi))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ioi a ∩ Iic b = Ioc a b)) Ioi_inter_Iic))
(Eq.refl (Ioc a b))))
@[simp] theorem Ioi_diff_Ici {α : Type u} [linear_order α] {a : α} {b : α} :
Ioi a \ Ici b = Ioo a b :=
eq.mpr (id (Eq._oldrec (Eq.refl (Ioi a \ Ici b = Ioo a b)) (diff_eq (Ioi a) (Ici b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ioi a ∩ (Ici bᶜ) = Ioo a b)) compl_Ici))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ioi a ∩ Iio b = Ioo a b)) Ioi_inter_Iio))
(Eq.refl (Ioo a b))))
@[simp] theorem Iic_diff_Iic {α : Type u} [linear_order α] {a : α} {b : α} :
Iic b \ Iic a = Ioc a b :=
sorry
@[simp] theorem Iio_diff_Iic {α : Type u} [linear_order α] {a : α} {b : α} :
Iio b \ Iic a = Ioo a b :=
sorry
@[simp] theorem Iic_diff_Iio {α : Type u} [linear_order α] {a : α} {b : α} :
Iic b \ Iio a = Icc a b :=
sorry
@[simp] theorem Iio_diff_Iio {α : Type u} [linear_order α] {a : α} {b : α} :
Iio b \ Iio a = Ico a b :=
sorry
theorem Ioo_eq_empty_iff {α : Type u} [linear_order α] {a : α} {b : α} [densely_ordered α] :
Ioo a b = ∅ ↔ b ≤ a :=
sorry
theorem Ico_eq_empty_iff {α : Type u} [linear_order α] {a : α} {b : α} : Ico a b = ∅ ↔ b ≤ a :=
sorry
theorem Icc_eq_empty_iff {α : Type u} [linear_order α] {a : α} {b : α} : Icc a b = ∅ ↔ b < a :=
sorry
theorem Ico_subset_Ico_iff {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
sorry
theorem Ioo_subset_Ioo_iff {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
[densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ :=
sorry
theorem Ico_eq_Ico_iff {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ :=
sorry
@[simp] theorem Ioi_subset_Ioi_iff {α : Type u} [linear_order α] {a : α} {b : α} :
Ioi b ⊆ Ioi a ↔ a ≤ b :=
{ mp :=
fun (h : Ioi b ⊆ Ioi a) =>
decidable.by_contradiction fun (ba : ¬a ≤ b) => lt_irrefl a (h (iff.mp not_le ba)),
mpr := fun (h : a ≤ b) => Ioi_subset_Ioi h }
@[simp] theorem Ioi_subset_Ici_iff {α : Type u} [linear_order α] {a : α} {b : α}
[densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b :=
sorry
@[simp] theorem Iio_subset_Iio_iff {α : Type u} [linear_order α] {a : α} {b : α} :
Iio a ⊆ Iio b ↔ a ≤ b :=
{ mp :=
fun (h : Iio a ⊆ Iio b) =>
decidable.by_contradiction fun (ab : ¬a ≤ b) => lt_irrefl b (h (iff.mp not_le ab)),
mpr := fun (h : a ≤ b) => Iio_subset_Iio h }
@[simp] theorem Iio_subset_Iic_iff {α : Type u} [linear_order α] {a : α} {b : α}
[densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b :=
eq.mpr (id (Eq._oldrec (Eq.refl (Iio a ⊆ Iic b ↔ a ≤ b)) (Eq.symm (propext diff_eq_empty))))
(eq.mpr (id (Eq._oldrec (Eq.refl (Iio a \ Iic b = ∅ ↔ a ≤ b)) Iio_diff_Iic))
(eq.mpr (id (Eq._oldrec (Eq.refl (Ioo b a = ∅ ↔ a ≤ b)) (propext Ioo_eq_empty_iff)))
(iff.refl (a ≤ b))))
/-! ### Unions of adjacent intervals -/
/-! #### Two infinite intervals -/
@[simp] theorem Iic_union_Ici {α : Type u} [linear_order α] {a : α} : Iic a ∪ Ici a = univ :=
eq_univ_of_forall fun (x : α) => le_total x a
@[simp] theorem Iio_union_Ici {α : Type u} [linear_order α] {a : α} : Iio a ∪ Ici a = univ :=
eq_univ_of_forall fun (x : α) => lt_or_le x a
@[simp] theorem Iic_union_Ioi {α : Type u} [linear_order α] {a : α} : Iic a ∪ Ioi a = univ :=
eq_univ_of_forall fun (x : α) => le_or_lt x a
/-! #### A finite and an infinite interval -/
theorem Ioo_union_Ioi' {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : c < b) :
Ioo a b ∪ Ioi c = Ioi (min a c) :=
sorry
theorem Ioo_union_Ioi {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h : c < max a b) :
Ioo a b ∪ Ioi c = Ioi (min a c) :=
sorry
theorem Ioi_subset_Ioo_union_Ici {α : Type u} [linear_order α] {a : α} {b : α} :
Ioi a ⊆ Ioo a b ∪ Ici b :=
fun (x : α) (hx : x ∈ Ioi a) =>
or.elim (lt_or_le x b) (fun (hxb : x < b) => Or.inl { left := hx, right := hxb })
fun (hxb : b ≤ x) => Or.inr hxb
@[simp] theorem Ioo_union_Ici_eq_Ioi {α : Type u} [linear_order α] {a : α} {b : α} (h : a < b) :
Ioo a b ∪ Ici b = Ioi a :=
subset.antisymm (fun (x : α) (hx : x ∈ Ioo a b ∪ Ici b) => or.elim hx and.left (lt_of_lt_of_le h))
Ioi_subset_Ioo_union_Ici
theorem Ici_subset_Ico_union_Ici {α : Type u} [linear_order α] {a : α} {b : α} :
Ici a ⊆ Ico a b ∪ Ici b :=
fun (x : α) (hx : x ∈ Ici a) =>
or.elim (lt_or_le x b) (fun (hxb : x < b) => Or.inl { left := hx, right := hxb })
fun (hxb : b ≤ x) => Or.inr hxb
@[simp] theorem Ico_union_Ici_eq_Ici {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
Ico a b ∪ Ici b = Ici a :=
subset.antisymm (fun (x : α) (hx : x ∈ Ico a b ∪ Ici b) => or.elim hx and.left (le_trans h))
Ici_subset_Ico_union_Ici
theorem Ico_union_Ici' {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : c ≤ b) :
Ico a b ∪ Ici c = Ici (min a c) :=
sorry
theorem Ico_union_Ici {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h : c ≤ max a b) :
Ico a b ∪ Ici c = Ici (min a c) :=
sorry
theorem Ioi_subset_Ioc_union_Ioi {α : Type u} [linear_order α] {a : α} {b : α} :
Ioi a ⊆ Ioc a b ∪ Ioi b :=
fun (x : α) (hx : x ∈ Ioi a) =>
or.elim (le_or_lt x b) (fun (hxb : x ≤ b) => Or.inl { left := hx, right := hxb })
fun (hxb : b < x) => Or.inr hxb
@[simp] theorem Ioc_union_Ioi_eq_Ioi {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
Ioc a b ∪ Ioi b = Ioi a :=
subset.antisymm (fun (x : α) (hx : x ∈ Ioc a b ∪ Ioi b) => or.elim hx and.left (lt_of_le_of_lt h))
Ioi_subset_Ioc_union_Ioi
theorem Ioc_union_Ioi' {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : c ≤ b) :
Ioc a b ∪ Ioi c = Ioi (min a c) :=
sorry
theorem Ioc_union_Ioi {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h : c ≤ max a b) :
Ioc a b ∪ Ioi c = Ioi (min a c) :=
sorry
theorem Ici_subset_Icc_union_Ioi {α : Type u} [linear_order α] {a : α} {b : α} :
Ici a ⊆ Icc a b ∪ Ioi b :=
fun (x : α) (hx : x ∈ Ici a) =>
or.elim (le_or_lt x b) (fun (hxb : x ≤ b) => Or.inl { left := hx, right := hxb })
fun (hxb : b < x) => Or.inr hxb
@[simp] theorem Icc_union_Ioi_eq_Ici {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
Icc a b ∪ Ioi b = Ici a :=
subset.antisymm
(fun (x : α) (hx : x ∈ Icc a b ∪ Ioi b) =>
or.elim hx and.left fun (hx : x ∈ Ioi b) => le_trans h (le_of_lt hx))
Ici_subset_Icc_union_Ioi
theorem Ioi_subset_Ioc_union_Ici {α : Type u} [linear_order α] {a : α} {b : α} :
Ioi a ⊆ Ioc a b ∪ Ici b :=
subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left (Ici b) Ioo_subset_Ioc_self)
@[simp] theorem Ioc_union_Ici_eq_Ioi {α : Type u} [linear_order α] {a : α} {b : α} (h : a < b) :
Ioc a b ∪ Ici b = Ioi a :=
subset.antisymm (fun (x : α) (hx : x ∈ Ioc a b ∪ Ici b) => or.elim hx and.left (lt_of_lt_of_le h))
Ioi_subset_Ioc_union_Ici
theorem Ici_subset_Icc_union_Ici {α : Type u} [linear_order α] {a : α} {b : α} :
Ici a ⊆ Icc a b ∪ Ici b :=
subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left (Ici b) Ico_subset_Icc_self)
@[simp] theorem Icc_union_Ici_eq_Ici {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
Icc a b ∪ Ici b = Ici a :=
subset.antisymm (fun (x : α) (hx : x ∈ Icc a b ∪ Ici b) => or.elim hx and.left (le_trans h))
Ici_subset_Icc_union_Ici
theorem Icc_union_Ici' {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h₁ : c ≤ b) :
Icc a b ∪ Ici c = Ici (min a c) :=
sorry
theorem Icc_union_Ici {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h : c ≤ max a b) :
Icc a b ∪ Ici c = Ici (min a c) :=
sorry
/-! #### An infinite and a finite interval -/
theorem Iic_subset_Iio_union_Icc {α : Type u} [linear_order α] {a : α} {b : α} :
Iic b ⊆ Iio a ∪ Icc a b :=
fun (x : α) (hx : x ∈ Iic b) =>
or.elim (lt_or_le x a) (fun (hxa : x < a) => Or.inl hxa)
fun (hxa : a ≤ x) => Or.inr { left := hxa, right := hx }
@[simp] theorem Iio_union_Icc_eq_Iic {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
Iio a ∪ Icc a b = Iic b :=
subset.antisymm
(fun (x : α) (hx : x ∈ Iio a ∪ Icc a b) =>
or.elim hx (fun (hx : x ∈ Iio a) => le_trans (le_of_lt hx) h) and.right)
Iic_subset_Iio_union_Icc
theorem Iio_subset_Iio_union_Ico {α : Type u} [linear_order α] {a : α} {b : α} :
Iio b ⊆ Iio a ∪ Ico a b :=
fun (x : α) (hx : x ∈ Iio b) =>
or.elim (lt_or_le x a) (fun (hxa : x < a) => Or.inl hxa)
fun (hxa : a ≤ x) => Or.inr { left := hxa, right := hx }
@[simp] theorem Iio_union_Ico_eq_Iio {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
Iio a ∪ Ico a b = Iio b :=
subset.antisymm
(fun (x : α) (hx : x ∈ Iio a ∪ Ico a b) =>
or.elim hx (fun (hx : x ∈ Iio a) => lt_of_lt_of_le hx h) and.right)
Iio_subset_Iio_union_Ico
theorem Iio_union_Ico' {α : Type u} [linear_order α] {b : α} {c : α} {d : α} (h₁ : c ≤ b) :
Iio b ∪ Ico c d = Iio (max b d) :=
sorry
theorem Iio_union_Ico {α : Type u} [linear_order α] {b : α} {c : α} {d : α} (h : min c d ≤ b) :
Iio b ∪ Ico c d = Iio (max b d) :=
sorry
theorem Iic_subset_Iic_union_Ioc {α : Type u} [linear_order α] {a : α} {b : α} :
Iic b ⊆ Iic a ∪ Ioc a b :=
fun (x : α) (hx : x ∈ Iic b) =>
or.elim (le_or_lt x a) (fun (hxa : x ≤ a) => Or.inl hxa)
fun (hxa : a < x) => Or.inr { left := hxa, right := hx }
@[simp] theorem Iic_union_Ioc_eq_Iic {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
Iic a ∪ Ioc a b = Iic b :=
subset.antisymm
(fun (x : α) (hx : x ∈ Iic a ∪ Ioc a b) =>
or.elim hx (fun (hx : x ∈ Iic a) => le_trans hx h) and.right)
Iic_subset_Iic_union_Ioc
theorem Iic_union_Ioc' {α : Type u} [linear_order α] {b : α} {c : α} {d : α} (h₁ : c < b) :
Iic b ∪ Ioc c d = Iic (max b d) :=
sorry
theorem Iic_union_Ioc {α : Type u} [linear_order α] {b : α} {c : α} {d : α} (h : min c d < b) :
Iic b ∪ Ioc c d = Iic (max b d) :=
sorry
theorem Iio_subset_Iic_union_Ioo {α : Type u} [linear_order α] {a : α} {b : α} :
Iio b ⊆ Iic a ∪ Ioo a b :=
fun (x : α) (hx : x ∈ Iio b) =>
or.elim (le_or_lt x a) (fun (hxa : x ≤ a) => Or.inl hxa)
fun (hxa : a < x) => Or.inr { left := hxa, right := hx }
@[simp] theorem Iic_union_Ioo_eq_Iio {α : Type u} [linear_order α] {a : α} {b : α} (h : a < b) :
Iic a ∪ Ioo a b = Iio b :=
subset.antisymm
(fun (x : α) (hx : x ∈ Iic a ∪ Ioo a b) =>
or.elim hx (fun (hx : x ∈ Iic a) => lt_of_le_of_lt hx h) and.right)
Iio_subset_Iic_union_Ioo
theorem Iio_union_Ioo' {α : Type u} [linear_order α] {b : α} {c : α} {d : α} (h₁ : c < b) :
Iio b ∪ Ioo c d = Iio (max b d) :=
sorry
theorem Iio_union_Ioo {α : Type u} [linear_order α] {b : α} {c : α} {d : α} (h : min c d < b) :
Iio b ∪ Ioo c d = Iio (max b d) :=
sorry
theorem Iic_subset_Iic_union_Icc {α : Type u} [linear_order α] {a : α} {b : α} :
Iic b ⊆ Iic a ∪ Icc a b :=
subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right (Iic a) Ioc_subset_Icc_self)
@[simp] theorem Iic_union_Icc_eq_Iic {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) :
Iic a ∪ Icc a b = Iic b :=
subset.antisymm
(fun (x : α) (hx : x ∈ Iic a ∪ Icc a b) =>
or.elim hx (fun (hx : x ∈ Iic a) => le_trans hx h) and.right)
Iic_subset_Iic_union_Icc
theorem Iic_union_Icc' {α : Type u} [linear_order α] {b : α} {c : α} {d : α} (h₁ : c ≤ b) :
Iic b ∪ Icc c d = Iic (max b d) :=
sorry
theorem Iic_union_Icc {α : Type u} [linear_order α] {b : α} {c : α} {d : α} (h : min c d ≤ b) :
Iic b ∪ Icc c d = Iic (max b d) :=
sorry
theorem Iio_subset_Iic_union_Ico {α : Type u} [linear_order α] {a : α} {b : α} :
Iio b ⊆ Iic a ∪ Ico a b :=
subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right (Iic a) Ioo_subset_Ico_self)
@[simp] theorem Iic_union_Ico_eq_Iio {α : Type u} [linear_order α] {a : α} {b : α} (h : a < b) :
Iic a ∪ Ico a b = Iio b :=
subset.antisymm
(fun (x : α) (hx : x ∈ Iic a ∪ Ico a b) =>
or.elim hx (fun (hx : x ∈ Iic a) => lt_of_le_of_lt hx h) and.right)
Iio_subset_Iic_union_Ico
/-! #### Two finite intervals, `I?o` and `Ic?` -/
theorem Ioo_subset_Ioo_union_Ico {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ioo a c ⊆ Ioo a b ∪ Ico b c :=
fun (x : α) (hx : x ∈ Ioo a c) =>
or.elim (lt_or_le x b) (fun (hxb : x < b) => Or.inl { left := and.left hx, right := hxb })
fun (hxb : b ≤ x) => Or.inr { left := hxb, right := and.right hx }
@[simp] theorem Ioo_union_Ico_eq_Ioo {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c :=
sorry
theorem Ico_subset_Ico_union_Ico {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ico a c ⊆ Ico a b ∪ Ico b c :=
fun (x : α) (hx : x ∈ Ico a c) =>
or.elim (lt_or_le x b) (fun (hxb : x < b) => Or.inl { left := and.left hx, right := hxb })
fun (hxb : b ≤ x) => Or.inr { left := hxb, right := and.right hx }
@[simp] theorem Ico_union_Ico_eq_Ico {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c :=
sorry
theorem Ico_union_Ico' {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} (h₁ : c ≤ b)
(h₂ : a ≤ d) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) :=
sorry
theorem Ico_union_Ico {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α}
(h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) :
Ico a b ∪ Ico c d = Ico (min a c) (max b d) :=
sorry
theorem Icc_subset_Ico_union_Icc {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Icc a c ⊆ Ico a b ∪ Icc b c :=
fun (x : α) (hx : x ∈ Icc a c) =>
or.elim (lt_or_le x b) (fun (hxb : x < b) => Or.inl { left := and.left hx, right := hxb })
fun (hxb : b ≤ x) => Or.inr { left := hxb, right := and.right hx }
@[simp] theorem Ico_union_Icc_eq_Icc {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c :=
sorry
theorem Ioc_subset_Ioo_union_Icc {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ioc a c ⊆ Ioo a b ∪ Icc b c :=
fun (x : α) (hx : x ∈ Ioc a c) =>
or.elim (lt_or_le x b) (fun (hxb : x < b) => Or.inl { left := and.left hx, right := hxb })
fun (hxb : b ≤ x) => Or.inr { left := hxb, right := and.right hx }
@[simp] theorem Ioo_union_Icc_eq_Ioc {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c :=
sorry
/-! #### Two finite intervals, `I?c` and `Io?` -/
theorem Ioo_subset_Ioc_union_Ioo {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ioo a c ⊆ Ioc a b ∪ Ioo b c :=
fun (x : α) (hx : x ∈ Ioo a c) =>
or.elim (le_or_lt x b) (fun (hxb : x ≤ b) => Or.inl { left := and.left hx, right := hxb })
fun (hxb : b < x) => Or.inr { left := hxb, right := and.right hx }
@[simp] theorem Ioc_union_Ioo_eq_Ioo {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c :=
sorry
theorem Ico_subset_Icc_union_Ioo {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ico a c ⊆ Icc a b ∪ Ioo b c :=
fun (x : α) (hx : x ∈ Ico a c) =>
or.elim (le_or_lt x b) (fun (hxb : x ≤ b) => Or.inl { left := and.left hx, right := hxb })
fun (hxb : b < x) => Or.inr { left := hxb, right := and.right hx }
@[simp] theorem Icc_union_Ioo_eq_Ico {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c :=
sorry
theorem Icc_subset_Icc_union_Ioc {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Icc a c ⊆ Icc a b ∪ Ioc b c :=
fun (x : α) (hx : x ∈ Icc a c) =>
or.elim (le_or_lt x b) (fun (hxb : x ≤ b) => Or.inl { left := and.left hx, right := hxb })
fun (hxb : b < x) => Or.inr { left := hxb, right := and.right hx }
@[simp] theorem Icc_union_Ioc_eq_Icc {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c :=
sorry
theorem Ioc_subset_Ioc_union_Ioc {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ioc a c ⊆ Ioc a b ∪ Ioc b c :=
fun (x : α) (hx : x ∈ Ioc a c) =>
or.elim (le_or_lt x b) (fun (hxb : x ≤ b) => Or.inl { left := and.left hx, right := hxb })
fun (hxb : b < x) => Or.inr { left := hxb, right := and.right hx }
@[simp] theorem Ioc_union_Ioc_eq_Ioc {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c :=
sorry
theorem Ioc_union_Ioc' {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} (h₁ : c ≤ b)
(h₂ : a ≤ d) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) :=
sorry
theorem Ioc_union_Ioc {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α}
(h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) :
Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) :=
sorry
/-! #### Two finite intervals with a common point -/
theorem Ioo_subset_Ioc_union_Ico {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ioo a c ⊆ Ioc a b ∪ Ico b c :=
subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right (Ioc a b) Ioo_subset_Ico_self)
@[simp] theorem Ioc_union_Ico_eq_Ioo {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c :=
sorry
theorem Ico_subset_Icc_union_Ico {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ico a c ⊆ Icc a b ∪ Ico b c :=
subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right (Icc a b) Ioo_subset_Ico_self)
@[simp] theorem Icc_union_Ico_eq_Ico {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c :=
sorry
theorem Icc_subset_Icc_union_Icc {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Icc a c ⊆ Icc a b ∪ Icc b c :=
subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right (Icc a b) Ioc_subset_Icc_self)
@[simp] theorem Icc_union_Icc_eq_Icc {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c :=
sorry
theorem Icc_union_Icc' {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} (h₁ : c ≤ b)
(h₂ : a ≤ d) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) :=
sorry
/--
We cannot replace `<` by `≤` in the hypotheses.
Otherwise for `b < a = d < c` the l.h.s. is `∅` and the r.h.s. is `{a}`.
-/
theorem Icc_union_Icc {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α}
(h₁ : min a b < max c d) (h₂ : min c d < max a b) :
Icc a b ∪ Icc c d = Icc (min a c) (max b d) :=
sorry
theorem Ioc_subset_Ioc_union_Icc {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ioc a c ⊆ Ioc a b ∪ Icc b c :=
subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right (Ioc a b) Ioc_subset_Icc_self)
@[simp] theorem Ioc_union_Icc_eq_Ioc {α : Type u} [linear_order α] {a : α} {b : α} {c : α}
(h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c :=
sorry
theorem Ioo_union_Ioo' {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} (h₁ : c < b)
(h₂ : a < d) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) :=
sorry
theorem Ioo_union_Ioo {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α}
(h₁ : min a b < max c d) (h₂ : min c d < max a b) :
Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) :=
sorry
@[simp] theorem Iic_inter_Iic {α : Type u} [semilattice_inf α] {a : α} {b : α} :
Iic a ∩ Iic b = Iic (a ⊓ b) :=
sorry
@[simp] theorem Iio_inter_Iio {α : Type u} [semilattice_inf α] [is_total α LessEq] {a : α} {b : α} :
Iio a ∩ Iio b = Iio (a ⊓ b) :=
sorry
@[simp] theorem Ici_inter_Ici {α : Type u} [semilattice_sup α] {a : α} {b : α} :
Ici a ∩ Ici b = Ici (a ⊔ b) :=
sorry
@[simp] theorem Ioi_inter_Ioi {α : Type u} [semilattice_sup α] [is_total α LessEq] {a : α} {b : α} :
Ioi a ∩ Ioi b = Ioi (a ⊔ b) :=
sorry
theorem Icc_inter_Icc {α : Type u} [lattice α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α} :
Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) :=
sorry
@[simp] theorem Icc_inter_Icc_eq_singleton {α : Type u} [lattice α] {a : α} {b : α} {c : α}
(hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = singleton b :=
sorry
theorem Ico_inter_Ico {α : Type u} [lattice α] [ht : is_total α LessEq] {a₁ : α} {a₂ : α} {b₁ : α}
{b₂ : α} : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) :=
sorry
theorem Ioc_inter_Ioc {α : Type u} [lattice α] [ht : is_total α LessEq] {a₁ : α} {a₂ : α} {b₁ : α}
{b₂ : α} : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) :=
sorry
theorem Ioo_inter_Ioo {α : Type u} [lattice α] [ht : is_total α LessEq] {a₁ : α} {a₂ : α} {b₁ : α}
{b₂ : α} : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) :=
sorry
theorem Ioc_inter_Ioo_of_left_lt {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h : b₁ < b₂) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioc (max a₁ a₂) b₁ :=
sorry
theorem Ioc_inter_Ioo_of_right_le {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h : b₂ ≤ b₁) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (max a₁ a₂) b₂ :=
sorry
theorem Ioo_inter_Ioc_of_left_le {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h : b₁ ≤ b₂) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioo (max a₁ a₂) b₁ :=
sorry
theorem Ioo_inter_Ioc_of_right_lt {α : Type u} [linear_order α] {a₁ : α} {a₂ : α} {b₁ : α} {b₂ : α}
(h : b₂ < b₁) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (max a₁ a₂) b₂ :=
sorry
@[simp] theorem Ico_diff_Iio {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ico a b \ Iio c = Ico (max a c) b :=
sorry
@[simp] theorem Ico_inter_Iio {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ico a b ∩ Iio c = Ico a (min b c) :=
sorry
@[simp] theorem Ioc_union_Ioc_right {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ioc a b ∪ Ioc a c = Ioc a (max b c) :=
sorry
@[simp] theorem Ioc_union_Ioc_left {α : Type u} [linear_order α] {a : α} {b : α} {c : α} :
Ioc a c ∪ Ioc b c = Ioc (min a b) c :=
sorry
@[simp] theorem Ioc_union_Ioc_symm {α : Type u} [linear_order α] {a : α} {b : α} :
Ioc a b ∪ Ioc b a = Ioc (min a b) (max a b) :=
eq.mpr (id (Eq._oldrec (Eq.refl (Ioc a b ∪ Ioc b a = Ioc (min a b) (max a b))) (max_comm a b)))
(Ioc_union_Ioc
(eq.mpr (id (Eq._oldrec (Eq.refl (min a b ≤ max b a)) (max_comm b a))) min_le_max)
(eq.mpr (id (Eq._oldrec (Eq.refl (min b a ≤ max a b)) (max_comm a b))) min_le_max))
@[simp] theorem Ioc_union_Ioc_union_Ioc_cycle {α : Type u} [linear_order α] {a : α} {b : α}
{c : α} : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc (min a (min b c)) (max a (max b c)) :=
sorry
/-- If we remove a smaller interval from a larger, the result is nonempty -/
theorem nonempty_Ico_sdiff {α : Type u} [linear_ordered_add_comm_group α] {x : α} {dx : α} {y : α}
{dy : α} (h : dy < dx) (hx : 0 < dx) : Nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) :=
sorry
end Mathlib |
e6af7a984958c0e584008195e102ac9ed4f2fe7d | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2020/sets/lean_lecture.lean | 1a70480dc0bc1bd584f3a0127e640ffad943ecea | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 656 | lean | import tactic
import data.real.basic
example : ∀ x : ℝ, ∃ y : ℝ, x + y > 0 :=
begin
intro x,
use 37 - x,
simp,
norm_num,
end
-- example : ∃ y : ℝ, ∀ x : ℝ, x + y > 0 :=
-- begin
-- use 10000000000,
-- intro x,
-- -- stuck!
-- sorry
-- end
example : ¬ (∃ y : ℝ, ∀ x : ℝ, x + y > 0) :=
begin
push_neg,
intro y,
use -37 - y,
simp,
norm_num,
end
variable (α : Type)
example : (α → Prop) ≃ set α :=
{ to_fun := λ P, {x : α | P x},
inv_fun := λ X, λ a, a ∈ X,
left_inv := begin
intro P,
dsimp,
refl,
end
,
right_inv := begin
intro X,
dsimp,
refl,
end }
|
3e68934fb966b62123d48ee2e7c610808fd85c36 | 94637389e03c919023691dcd05bd4411b1034aa5 | /src/inClassNotes/play.lean | 45f46a86ef0d0c324adad1c1e34e4998f59864f7 | [] | no_license | kevinsullivan/complogic-s21 | 7c4eef2105abad899e46502270d9829d913e8afc | 99039501b770248c8ceb39890be5dfe129dc1082 | refs/heads/master | 1,682,985,669,944 | 1,621,126,241,000 | 1,621,126,241,000 | 335,706,272 | 0 | 38 | null | 1,618,325,669,000 | 1,612,374,118,000 | Lean | UTF-8 | Lean | false | false | 1,505 | lean | /-
A total function
-- set theoretic representation of the squaring function
sqr : ℕ → ℕ := { (0,0), (1,1), (2,4), (3,9), ... }
-/
/-
Computational representation of the function
-/
def sqr : ℕ → ℕ := λ n, n*n
#eval sqr 3
/-
Logical, declarative, predicate that defines the same function
-/
inductive sqr_pred : ℕ → ℕ → Prop
| in_sqr_pred : ∀ (n1 n2 : ℕ), (n2 = n1 * n1) → sqr_pred n1 n2
-- h === in_sqr_pred n1 n2 k
theorem verification : ∀ (n1 n2 : ℕ), sqr_pred n1 n2 → sqr n1 = n2 :=
begin
assume n1 n2,
assume h,
cases h,
unfold sqr,
apply eq.symm _,
assumption,
end
--
#check sqr_pred
#check sqr_pred 3 8
open sqr_pred
-- explicit proof term
example : sqr_pred 3 9 := in_sqr_pred 3 9 (eq.refl 9)
example : sqr_pred 4 16 := in_sqr_pred _ _ (eq.refl _)
example : sqr_pred 3 9 :=
begin
apply in_sqr_pred _ _ _,
exact eq.refl _,
end
example : sqr_pred 4 16 :=
begin
apply in_sqr_pred _ _ _,
exact eq.refl _,
end
example : sqr_pred 3 15 := in_sqr_pred _ _ (eq.refl _)
/-
sqr_ev : ℕ → ℕ := { (0,0), (2,4), (4,16), ... }
-/
def evn : ℕ → bool := λ n, n%2 = 0
inductive sqr_ev_pred : ℕ → ℕ → Prop
| in_sqr_ev_pred : ∀ (n1 n2 : ℕ), (n1%2 = 0) → (n2 = n1 * n1) → sqr_ev_pred n1 n2
open sqr_ev_pred
example : sqr_ev_pred 4 16 :=
begin
apply in_sqr_ev_pred,
apply eq.refl _,
apply eq.refl 16,
end
example : sqr_ev_pred 3 9 :=
begin
apply in_sqr_ev_pred,
apply eq.refl _, -- stuck
end
|
c8aa08e57381cbe3d0b44faa5fc70b80ebfede0a | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/locally_constant/basic.lean | fecf679e4c45b29b2e2b4ee108d1808fa000b2d9 | [
"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 | 11,062 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import topology.subset_properties
import topology.connected
import topology.algebra.monoid
import tactic.tfae
/-!
# Locally constant functions
This file sets up the theory of locally constant function from a topological space to a type.
## Main definitions and constructions
* `is_locally_constant f` : a map `f : X → Y` where `X` is a topological space is locally
constant if every set in `Y` has an open preimage.
* `locally_constant X Y` : the type of locally constant maps from `X` to `Y`
* `locally_constant.map` : push-forward of locally constant maps
* `locally_constant.comap` : pull-back of locally constant maps
-/
variables {X Y Z α : Type*} [topological_space X]
open set filter
open_locale topological_space
/-- A function between topological spaces is locally constant if the preimage of any set is open. -/
def is_locally_constant (f : X → Y) : Prop := ∀ s : set Y, is_open (f ⁻¹' s)
namespace is_locally_constant
protected lemma tfae (f : X → Y) :
tfae [is_locally_constant f,
∀ x, ∀ᶠ x' in 𝓝 x, f x' = f x,
∀ x, is_open {x' | f x' = f x},
∀ y, is_open (f ⁻¹' {y}),
∀ x, ∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x] :=
begin
tfae_have : 1 → 4, from λ h y, h {y},
tfae_have : 4 → 3, from λ h x, h (f x),
tfae_have : 3 → 2, from λ h x, mem_nhds_sets (h x) rfl,
tfae_have : 2 → 5,
{ intros h x,
rcases mem_nhds_sets_iff.1 (h x) with ⟨U, eq, hU, hx⟩,
exact ⟨U, hU, hx, eq⟩ },
tfae_have : 5 → 1,
{ intros h s,
refine is_open_iff_forall_mem_open.2 (λ x hx, _),
rcases h x with ⟨U, hU, hxU, eq⟩,
exact ⟨U, λ x' hx', mem_preimage.2 $ (eq x' hx').symm ▸ hx, hU, hxU⟩ },
tfae_finish
end
@[nontriviality] lemma of_discrete [discrete_topology X] (f : X → Y) :
is_locally_constant f :=
λ s, is_open_discrete _
lemma is_open_fiber {f : X → Y} (hf : is_locally_constant f) (y : Y) :
is_open {x | f x = y} :=
hf {y}
lemma iff_exists_open (f : X → Y) :
is_locally_constant f ↔ ∀ x, ∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x :=
(is_locally_constant.tfae f).out 0 4
lemma iff_eventually_eq (f : X → Y) :
is_locally_constant f ↔ ∀ x, ∀ᶠ y in 𝓝 x, f y = f x :=
(is_locally_constant.tfae f).out 0 1
lemma exists_open {f : X → Y} (hf : is_locally_constant f) (x : X) :
∃ (U : set X) (hU : is_open U) (hx : x ∈ U), ∀ x' ∈ U, f x' = f x :=
(iff_exists_open f).1 hf x
protected lemma eventually_eq {f : X → Y} (hf : is_locally_constant f) (x : X) :
∀ᶠ y in 𝓝 x, f y = f x :=
(iff_eventually_eq f).1 hf x
protected lemma continuous [topological_space Y] {f : X → Y} (hf : is_locally_constant f) :
continuous f :=
⟨λ U hU, hf _⟩
lemma iff_continuous {_ : topological_space Y} [discrete_topology Y] (f : X → Y) :
is_locally_constant f ↔ continuous f :=
⟨is_locally_constant.continuous, λ h s, h.is_open_preimage s (is_open_discrete _)⟩
lemma iff_continuous_bot (f : X → Y) :
is_locally_constant f ↔ @continuous X Y _ ⊥ f :=
iff_continuous f
lemma of_constant (f : X → Y) (h : ∀ x y, f x = f y) :
is_locally_constant f :=
(iff_eventually_eq f).2 $ λ x, eventually_of_forall $ λ x', h _ _
lemma const (y : Y) : is_locally_constant (function.const X y) :=
of_constant _ $ λ _ _, rfl
lemma comp {f : X → Y} (hf : is_locally_constant f) (g : Y → Z) :
is_locally_constant (g ∘ f) :=
λ s, by { rw set.preimage_comp, exact hf _ }
lemma prod_mk {Y'} {f : X → Y} {f' : X → Y'} (hf : is_locally_constant f)
(hf' : is_locally_constant f') :
is_locally_constant (λ x, (f x, f' x)) :=
(iff_eventually_eq _).2 $ λ x, (hf.eventually_eq x).mp $ (hf'.eventually_eq x).mono $
λ x' hf' hf, prod.ext hf hf'
lemma comp₂ {Y₁ Y₂ Z : Type*} {f : X → Y₁} {g : X → Y₂}
(hf : is_locally_constant f) (hg : is_locally_constant g) (h : Y₁ → Y₂ → Z) :
is_locally_constant (λ x, h (f x) (g x)) :=
(hf.prod_mk hg).comp (λ x : Y₁ × Y₂, h x.1 x.2)
lemma comp_continuous [topological_space Y] {g : Y → Z} {f : X → Y}
(hg : is_locally_constant g) (hf : continuous f) :
is_locally_constant (g ∘ f) :=
λ s, by { rw set.preimage_comp, exact hf.is_open_preimage _ (hg _) }
/-- A locally constant function is constant on any preconnected set. -/
lemma apply_eq_of_is_preconnected {f : X → Y} (hf : is_locally_constant f)
{s : set X} (hs : is_preconnected s) {x y : X} (hx : x ∈ s) (hy : y ∈ s) :
f x = f y :=
begin
let U := f ⁻¹' {f y},
suffices : x ∉ Uᶜ, from not_not.1 this,
intro hxV,
specialize hs U Uᶜ (hf {f y}) (hf {f y}ᶜ) _ ⟨y, ⟨hy, rfl⟩⟩ ⟨x, ⟨hx, hxV⟩⟩,
{ simp only [union_compl_self, subset_univ] },
{ simpa only [inter_empty, not_nonempty_empty, inter_compl_self] using hs }
end
lemma iff_is_const [preconnected_space X] {f : X → Y} :
is_locally_constant f ↔ ∀ x y, f x = f y :=
⟨λ h x y, h.apply_eq_of_is_preconnected is_preconnected_univ trivial trivial, of_constant _⟩
lemma range_finite [compact_space X] {f : X → Y} (hf : is_locally_constant f) :
(set.range f).finite :=
begin
letI : topological_space Y := ⊥,
haveI : discrete_topology Y := ⟨rfl⟩,
rw @iff_continuous X Y ‹_› ‹_› at hf,
exact finite_of_is_compact_of_discrete _ (compact_range hf)
end
@[to_additive] lemma one [has_one Y] : is_locally_constant (1 : X → Y) := const 1
@[to_additive] lemma inv [has_inv Y] ⦃f : X → Y⦄ (hf : is_locally_constant f) :
is_locally_constant f⁻¹ :=
hf.comp (λ x, x⁻¹)
@[to_additive]
lemma mul [has_mul Y] ⦃f g : X → Y⦄ (hf : is_locally_constant f) (hg : is_locally_constant g) :
is_locally_constant (f * g) :=
hf.comp₂ hg (*)
@[to_additive]
lemma div [has_div Y] ⦃f g : X → Y⦄ (hf : is_locally_constant f) (hg : is_locally_constant g) :
is_locally_constant (f / g) :=
hf.comp₂ hg (/)
end is_locally_constant
/-- A (bundled) locally constant function from a topological space `X` to a type `Y`. -/
structure locally_constant (X Y : Type*) [topological_space X] :=
(to_fun : X → Y)
(is_locally_constant : is_locally_constant to_fun)
namespace locally_constant
instance [inhabited Y] : inhabited (locally_constant X Y) :=
⟨⟨_, is_locally_constant.const (default Y)⟩⟩
instance : has_coe_to_fun (locally_constant X Y) := ⟨_, locally_constant.to_fun⟩
initialize_simps_projections locally_constant (to_fun → apply)
@[simp] lemma to_fun_eq_coe (f : locally_constant X Y) : f.to_fun = f := rfl
@[simp] lemma coe_mk (f : X → Y) (h) : ⇑(⟨f, h⟩ : locally_constant X Y) = f := rfl
theorem congr_fun {f g : locally_constant X Y} (h : f = g) (x : X) : f x = g x :=
congr_arg (λ h : locally_constant X Y, h x) h
theorem congr_arg (f : locally_constant X Y) {x y : X} (h : x = y) : f x = f y :=
congr_arg (λ x : X, f x) h
theorem coe_injective : function.injective (λ (f : locally_constant X Y) (x : X), f x)
| ⟨f, hf⟩ ⟨g, hg⟩ h := have f = g, from h, by subst f
@[simp, norm_cast] theorem coe_inj {f g : locally_constant X Y} : (f : X → Y) = g ↔ f = g :=
coe_injective.eq_iff
@[ext] theorem ext ⦃f g : locally_constant X Y⦄ (h : ∀ x, f x = g x) : f = g :=
coe_injective (funext h)
theorem ext_iff {f g : locally_constant X Y} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
protected lemma continuous [topological_space Y] (f : locally_constant X Y) : continuous f :=
f.is_locally_constant.continuous
/-- The constant locally constant function on `X` with value `y : Y`. -/
def const (X : Type*) {Y : Type*} [topological_space X] (y : Y) :
locally_constant X Y :=
⟨function.const X y, is_locally_constant.const _⟩
lemma range_finite [compact_space X] (f : locally_constant X Y) :
(set.range f).finite :=
f.is_locally_constant.range_finite
lemma apply_eq_of_is_preconnected (f : locally_constant X Y) {s : set X} (hs : is_preconnected s)
{x y : X} (hx : x ∈ s) (hy : y ∈ s) :
f x = f y :=
f.is_locally_constant.apply_eq_of_is_preconnected hs hx hy
lemma apply_eq_of_preconnected_space [preconnected_space X] (f : locally_constant X Y) (x y : X) :
f x = f y :=
f.is_locally_constant.apply_eq_of_is_preconnected is_preconnected_univ trivial trivial
lemma eq_const [preconnected_space X] (f : locally_constant X Y) (x : X) :
f = const X (f x) :=
ext $ λ y, apply_eq_of_preconnected_space f _ _
lemma exists_eq_const [preconnected_space X] [nonempty Y] (f : locally_constant X Y) :
∃ y, f = const X y :=
begin
rcases classical.em (nonempty X) with ⟨⟨x⟩⟩|hX,
{ exact ⟨f x, f.eq_const x⟩ },
{ exact ⟨classical.arbitrary Y, ext $ λ x, (hX ⟨x⟩).elim⟩ }
end
/-- Push forward of locally constant maps under any map, by post-composition. -/
def map (f : Y → Z) : locally_constant X Y → locally_constant X Z :=
λ g, ⟨f ∘ g, λ s, by { rw set.preimage_comp, apply g.is_locally_constant }⟩
@[simp] lemma map_apply (f : Y → Z) (g : locally_constant X Y) : ⇑(map f g) = f ∘ g := rfl
@[simp] lemma map_id : @map X Y Y _ id = id := by { ext, refl }
@[simp] lemma map_comp {Y₁ Y₂ Y₃ : Type*} (g : Y₂ → Y₃) (f : Y₁ → Y₂) :
@map X _ _ _ g ∘ map f = map (g ∘ f) := by { ext, refl }
section comap
open_locale classical
variables [topological_space Y]
/-- Pull back of locally constant maps under any map, by pre-composition.
This definition only makes sense if `f` is continuous,
in which case it sends locally constant functions to their precomposition with `f`.
See also `locally_constant.coe_comap`. -/
noncomputable
def comap (f : X → Y) :
locally_constant Y Z → locally_constant X Z :=
if hf : continuous f
then λ g, ⟨g ∘ f, g.is_locally_constant.comp_continuous hf⟩
else
begin
by_cases H : nonempty X,
{ introsI g, exact const X (g $ f $ classical.arbitrary X) },
{ intro g, refine ⟨λ x, (H ⟨x⟩).elim, _⟩,
intro s, rw is_open_iff_nhds, intro x, exact (H ⟨x⟩).elim }
end
@[simp] lemma coe_comap (f : X → Y) (g : locally_constant Y Z) (hf : continuous f) :
⇑(comap f g) = g ∘ f :=
by { rw [comap, dif_pos hf], refl }
@[simp] lemma comap_id : @comap X X Z _ _ id = id :=
by { ext, simp only [continuous_id, id.def, function.comp.right_id, coe_comap] }
lemma comap_comp [topological_space Z]
(f : X → Y) (g : Y → Z) (hf : continuous f) (hg : continuous g) :
@comap _ _ α _ _ f ∘ comap g = comap (g ∘ f) :=
by { ext, simp only [hf, hg, hg.comp hf, coe_comap] }
lemma comap_const (f : X → Y) (y : Y) (h : ∀ x, f x = y) :
(comap f : locally_constant Y Z → locally_constant X Z) =
λ g, ⟨λ x, g y, is_locally_constant.const _⟩ :=
begin
ext, rw coe_comap,
{ simp only [h, coe_mk, function.comp_app] },
{ rw show f = λ x, y, by ext; apply h,
exact continuous_const }
end
end comap
end locally_constant
|
501d59e00b070991c7e37173dd1c1fd068b73696 | 6fbf10071e62af7238f2de8f9aa83d55d8763907 | /examples/disjunction_properties.lean | 2ea61dd605b5045c8954e53e0eb919eb2516bee4 | [] | no_license | HasanMukati/uva-cs-dm-s19 | ee5aad4568a3ca330c2738ed579c30e1308b03b0 | 3e7177682acdb56a2d16914e0344c10335583dcf | refs/heads/master | 1,596,946,213,130 | 1,568,221,949,000 | 1,568,221,949,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,448 | lean | theorem absorb_right_or: ∀(P : Prop), P ∨ true :=
begin
assume P,
exact or.inr true.intro
end
theorem absorb_right_or': ∀(P : Prop), P ∨ true :=
λ(P), or.inr true.intro
theorem absorb_left_or: ∀(P : Prop), true ∨ P :=
begin
assume P,
exact or.inl true.intro
end
theorem wet'' :
∀(R S W: Prop),
(R ∨ S) → (R → W) → (S → W) → W :=
begin
assume R S W,
assume pf_R_or_S,
assume pf_R_to_W,
assume pf_S_to_W,
exact or.elim pf_R_or_S pf_R_to_W pf_S_to_W,
end
theorem wet''' :
∀(R S W: Prop),
(R ∨ S) → (R → W) → (S → W) → W :=
begin
assume R S W,
assume pf_R_or_S,
assume pf_R_to_W,
assume pf_S_to_W,
cases pf_R_or_S with pf_R pf_S,
-- case R
exact pf_R_to_W pf_R,
-- case S
exact pf_S_to_W pf_S,
end
theorem id_right_or: ∀(P: Prop), P ∨ false ↔ P :=
begin
assume P,
split,
-- P ∨ false → P
assume pf_P_or_false,
cases pf_P_or_false with pf_P pf_false,
-- pf_P
assumption,
-- pf_false
exact false.elim pf_false,
-- P → P ∨ false
assume pf_P,
exact or.inl pf_P,
end
theorem id_left_or: ∀(P: Prop), false ∨ P ↔ P :=
begin
assume P,
split,
-- false ∨ P → P
assume pf_false_or_P,
cases pf_false_or_P with pf_false pf_P,
-- pf_false
exact false.elim pf_false,
-- pf_P
assumption,
-- P → false ∨ P
assume pf_P,
exact or.intro_right false pf_P,
end
theorem disjunctiveSyllogism:
∀(P Q: Prop), P ∨ Q → ¬Q → P :=
begin
assume P Q,
assume pfPOrQ,
assume pfNotQ,
cases pfPOrQ with pfP pfQ, -- now by cases
assumption, -- case where p is true,
exact false.elim (pfNotQ pfQ), -- or q true
end
axiom em: ∀(P: Prop), P ∨ ¬P
theorem DeMorganOne: ∀(P Q: Prop), ¬(P ∨ Q) ↔ ¬P ∧ ¬Q :=
begin
assume P Q,
split,
-- ¬(P ∨ Q) → ¬P ∧ ¬Q
assume pf_not__P_or_Q,
split,
-- prove ¬P
cases (em P) with pf_P pf_not_P,
-- pf_P
have pf_P_or_Q: P ∨ Q := or.inl pf_P,
exact false.elim (pf_not__P_or_Q pf_P_or_Q),
-- pf_not_P
assumption,
-- prove ¬Q
cases (em Q) with pf_Q pf_not_Q,
-- pf_Q
have pf_P_or_Q: P ∨ Q := or.inr pf_Q,
exact false.elim (pf_not__P_or_Q pf_P_or_Q),
-- pf_not_Q,
assumption,
-- ¬P ∧ ¬Q → ¬(P ∨ Q)
assume pf_not_P_and_not_Q,
assume pf_P_or_Q,
cases pf_P_or_Q with pf_P pf_Q,
-- pf_P
have pf_not_P: ¬P := pf_not_P_and_not_Q.left,
exact pf_not_P pf_P,
-- pf_Q
have pf_not_Q: ¬Q := pf_not_P_and_not_Q.right,
exact pf_not_Q pf_Q,
end
theorem DeMorganTwo: ∀(P Q: Prop), ¬(P ∧ Q) ↔ ¬P ∨ ¬Q :=
begin
assume P Q,
split,
-- ¬(P ∧ Q) → ¬P ∨ ¬Q
assume pf_not__P_and_Q,
cases (em P) with pf_P pf_not_P,
-- pf_P
cases (em Q) with pf_Q pf_not_Q,
-- pf_Q
have pf_P_and_Q := and.intro pf_P pf_Q,
exact false.elim (pf_not__P_and_Q pf_P_and_Q),
-- pf_not_Q
exact or.inr pf_not_Q,
-- pf_not_P
exact or.inl pf_not_P,
-- ¬P ∨ ¬Q → ¬(P ∧ Q)
assume pf_not_P_or_not_Q,
assume pf_P_and_Q,
cases pf_not_P_or_not_Q with pf_not_P pf_not_Q,
-- pf_not_P
have pf_P := pf_P_and_Q.left,
exact pf_not_P pf_P,
-- pf_not_Q
have pf_Q := pf_P_and_Q.right,
exact pf_not_Q pf_Q,
end
-- Is disjunction reflexive?
-- Is A ∨ A true?
-- No
example: ¬∀(A: Prop), A ∨ A :=
begin
assume pf_forall,
have pf_false_or_false := pf_forall false,
cases pf_false_or_false,
assumption, assumption,
end
-- Is disjunction symmetric?
-- Does A ∨ B imply B ∨ A?
example: ∀(A B: Prop),
(A ∨ B) → (B ∨ A) :=
begin
assume A B,
assume pf_A_or_B,
cases pf_A_or_B with pf_A pf_B,
exact or.inr pf_A,
exact or.inl pf_B,
end
-- Is disjunction associative?
-- Are (A ∨ B) ∨ C and A ∨ (B ∨ C) the same?
example: ∀(A B C: Prop),
(A ∨ B) ∨ C ↔ A ∨ (B ∨ C) :=
begin
assume A B C,
split,
-- (A ∨ B) ∨ C → A ∨ (B ∨ C)
assume pf_A_or_B__or_C,
cases pf_A_or_B__or_C with pf_A_or_B pf_C,
-- pf_A_or_B
cases pf_A_or_B with pf_A pf_B,
-- pf_A
exact or.inl pf_A,
-- pf_B
have pf_B_or_C: B ∨ C := or.inl pf_B,
exact or.inr pf_B_or_C,
-- pf_C
have pf_B_or_C: B ∨ C := or.inr pf_C,
exact or.inr pf_B_or_C,
-- A ∨ (B ∨ C) → (A ∨ B) ∨ C
assume pf_A_or__B_or_C,
cases pf_A_or__B_or_C with pf_A pf_B_or_C,
-- pf_A
have pf_A_or_B := or.intro_left B pf_A,
exact or.inl pf_A_or_B,
-- pf_B_or_C
cases pf_B_or_C with pf_B pf_C,
-- pf_B
have pf_A_or_B := or.intro_right A pf_B,
exact or.inl pf_A_or_B,
-- pf_C
exact or.inr pf_C,
end
-- Is disjunction transitive?
-- Does (A ∨ B) and (B ∨ C) imply (A ∨ C)?
-- No
example: ¬∀(A B C: Prop),
(A ∨ B) → (B ∨ C) → (A ∨ C) :=
begin
assume pf_forall,
have pf_falseness := pf_forall false true false,
have pf_f_or_t := or.intro_right false true.intro,
have pf_t_or_f := or.intro_left false true.intro,
have pf_f_or_f := (pf_falseness pf_f_or_t) pf_t_or_f,
cases pf_f_or_f with pf_f pf_f,
assumption, assumption,
end
-- Distribution over ∧
example: ∀(A B C: Prop),
A ∨ (B ∧ C) ↔ (A ∨ B) ∧ (A ∨ C) :=
begin
assume A B C,
split,
-- A ∨ (B ∧ C) → (A ∨ B) ∧ (A ∨ C)
assume pf_A_or__B_and_C,
cases pf_A_or__B_and_C with pf_A pf_B_and_C,
-- pf_A
have pf_A_or_B: A ∨ B := or.inl pf_A,
have pf_A_or_C := or.intro_left C pf_A,
exact and.intro pf_A_or_B pf_A_or_C,
-- pf_B_and_C
have pf_C := pf_B_and_C.left,
have pf_A_or_B: A ∨ B := or.inr pf_C,
have pf_B := pf_B_and_C.right,
have pf_A_or_C: A ∨ C := or.inr pf_B,
exact and.intro pf_A_or_B pf_A_or_C,
-- (A ∨ B) ∧ (A ∨ C) → A ∨ (B ∧ C)
assume pf_A_or_B__and__A_or_C,
cases pf_A_or_B__and__A_or_C.left with pf_A pf_B,
-- pf_A
exact or.inl pf_A,
-- pf_B
cases pf_A_or_B__and__A_or_C.right with pf_A pf_C,
-- pf_A
exact or.inl pf_A,
-- pf_C
have pf_B_and_C := and.intro pf_B pf_C,
exact or.inr pf_B_and_C,
end
-- Distribution over ∨
example: ∀(A B C: Prop),
A ∧ (B ∨ C) ↔ (A ∧ B) ∨ (A ∧ C) :=
begin
assume A B C,
split,
-- A ∧ (B ∨ C) → (A ∧ B) ∨ (A ∧ C)
assume pf_A__and_B_or_C,
cases pf_A__and_B_or_C.right with pf_B pf_C,
-- B
have pf_A := pf_A__and_B_or_C.left,
have pf_A_and_B := and.intro pf_A pf_B,
exact or.inl pf_A_and_B,
-- C
have pf_A := pf_A__and_B_or_C.left,
have pf_A_and_C := and.intro pf_A pf_C,
exact or.inr pf_A_and_C,
-- (A ∧ B) ∨ (A ∧ C) → A ∧ (B ∨ C)
assume pf_A_and_B__or__A_and_C,
cases pf_A_and_B__or__A_and_C with pf_A_and_B pf_A_and_C,
-- A ∧ B
have pf_B := pf_A_and_B.right,
have pf_B_or_C: B ∨ C := or.inl pf_B,
have pf_A := pf_A_and_B.left,
exact and.intro pf_A pf_B_or_C,
-- A ∧ C
have pf_C := pf_A_and_C.right,
have pf_B_or_C: B ∨ C := or.inr pf_C,
have pf_A := pf_A_and_C.left,
exact and.intro pf_A pf_B_or_C,
end
|
96c6f3274446a3634de4158a386cc56b155cf448 | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/match2.lean | 93d39368279d2a3d56a5290f860c8721b3fd615d | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,358 | lean | new_frontend
#print "---- Op"
inductive Op : Nat → Nat → Type
| mk : ∀ n, Op n n
structure Node : Type :=
(id₁ id₂ : Nat)
(o : Op id₁ id₂)
def h1 (x : List Node) : Bool :=
match x with
| _ :: Node.mk _ _ (Op.mk 0) :: _ => true
| _ => false
def mkNode (n : Nat) : Node := { id₁ := n, id₂ := n, o := Op.mk n }
#eval h1 [mkNode 1, mkNode 0, mkNode 3]
#eval h1 [mkNode 1, mkNode 1, mkNode 3]
#eval h1 [mkNode 0]
#eval h1 []
#print "---- Foo 1"
inductive Foo : Bool → Type
| bar : Foo false
| baz : Foo false
def h2 {b : Bool} (x : Foo b) : Bool :=
match b, x with
| _, Foo.bar => true
| _, Foo.baz => false
#eval h2 Foo.bar
#eval h2 Foo.baz
#print "---- Foo 2"
def h3 {b : Bool} (x : Foo b) : Bool :=
match b, x with
| _, Foo.bar => true
| _, _ => false
#eval h3 Foo.bar
#eval h3 Foo.baz
#print "---- Op 2"
def h4 (x : List Node) : Bool :=
match x with
| _ :: ⟨1, 1, Op.mk 1⟩ :: _ => true
| _ => false
#eval h4 [mkNode 1, mkNode 0, mkNode 3]
#eval h4 [mkNode 1, mkNode 1, mkNode 3]
#eval h4 [mkNode 0]
#eval h4 []
#print "---- Foo 3"
set_option pp.all true
def h5 {b : Bool} (x : Foo b) : Bool :=
match b, x with
| _, Foo.bar => true
| c, y => false
def h6 {b : Bool} (x : Foo b) : Bool :=
match b, x with
| _, Foo.bar => true
| b, x => false
|
74c3ee77020c5d41c0337d6109f803f48f8c64b6 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/deprecated/group.lean | fd86fa8ec942f588d3bcf5253ad73c8ef2775bf3 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 12,875 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import algebra.group.type_tags
import algebra.group.units_hom
import algebra.ring.basic
/-!
# Unbundled monoid and group homomorphisms (deprecated)
This file defines typeclasses for unbundled monoid and group homomorphisms. Though these classes are
deprecated, they are still widely used in mathlib, and probably will not go away before Lean 4
because Lean 3 often fails to coerce a bundled homomorphism to a function.
## main definitions
monoid_hom, is_monoid_hom (deprecated), is_group_hom (deprecated)
## implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `group_hom` -- the idea is that `monoid_hom` is used.
The constructor for `monoid_hom` needs a proof of `map_one` as well
as `map_mul`; a separate constructor `monoid_hom.mk'` will construct
group homs (i.e. monoid homs between groups) given only a proof
that multiplication is preserved,
Throughout the `monoid_hom` section implicit `{}` brackets are often used instead of type class `[]`
brackets. This is done when the instances can be inferred because they are implicit arguments to
the type `monoid_hom`. When they can be inferred from the type it is faster to use this method than
to use type class inference.
## Tags
is_group_hom, is_monoid_hom, monoid_hom
-/
/--
We have lemmas stating that the composition of two morphisms is again a morphism.
Since composition is reducible, type class inference will always succeed in applying these instances.
For example when the goal is just `⊢ is_mul_hom f` the instance `is_mul_hom.comp`
will still succeed, unifying `f` with `f ∘ (λ x, x)`. This causes type class inference to loop.
To avoid this, we do not make these lemmas instances.
-/
library_note "no instance on morphisms"
universes u v
variables {α : Type u} {β : Type v}
/-- Predicate for maps which preserve an addition. -/
class is_add_hom {α β : Type*} [has_add α] [has_add β] (f : α → β) : Prop :=
(map_add [] : ∀ x y, f (x + y) = f x + f y)
/-- Predicate for maps which preserve a multiplication. -/
@[to_additive]
class is_mul_hom {α β : Type*} [has_mul α] [has_mul β] (f : α → β) : Prop :=
(map_mul [] : ∀ x y, f (x * y) = f x * f y)
namespace is_mul_hom
variables [has_mul α] [has_mul β] {γ : Type*} [has_mul γ]
/-- The identity map preserves multiplication. -/
@[to_additive "The identity map preserves addition"]
instance id : is_mul_hom (id : α → α) := {map_mul := λ _ _, rfl}
/-- The composition of maps which preserve multiplication, also preserves multiplication. -/
-- see Note [no instance on morphisms]
@[to_additive "The composition of addition preserving maps also preserves addition"]
lemma comp (f : α → β) (g : β → γ) [is_mul_hom f] [hg : is_mul_hom g] : is_mul_hom (g ∘ f) :=
{ map_mul := λ x y, by simp only [function.comp, map_mul f, map_mul g] }
/-- A product of maps which preserve multiplication,
preserves multiplication when the target is commutative. -/
@[instance, priority 10, to_additive]
lemma mul {α β} [semigroup α] [comm_semigroup β]
(f g : α → β) [is_mul_hom f] [is_mul_hom g] :
is_mul_hom (λa, f a * g a) :=
{ map_mul := assume a b, by simp only [map_mul f, map_mul g, mul_comm, mul_assoc, mul_left_comm] }
/-- The inverse of a map which preserves multiplication,
preserves multiplication when the target is commutative. -/
@[instance, to_additive]
lemma inv {α β} [has_mul α] [comm_group β] (f : α → β) [is_mul_hom f] :
is_mul_hom (λa, (f a)⁻¹) :=
{ map_mul := assume a b, (map_mul f a b).symm ▸ mul_inv _ _ }
end is_mul_hom
/-- Predicate for add_monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/
class is_add_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) extends is_add_hom f : Prop :=
(map_zero [] : f 0 = 0)
/-- Predicate for monoid homomorphisms (deprecated -- use the bundled `monoid_hom` version). -/
@[to_additive]
class is_monoid_hom [monoid α] [monoid β] (f : α → β) extends is_mul_hom f : Prop :=
(map_one [] : f 1 = 1)
namespace monoid_hom
variables {M : Type*} {N : Type*} {P : Type*} [mM : monoid M] [mN : monoid N] {mP : monoid P}
variables {G : Type*} {H : Type*} [group G] [comm_group H]
include mM mN
/-- Interpret a map `f : M → N` as a homomorphism `M →* N`. -/
@[to_additive "Interpret a map `f : M → N` as a homomorphism `M →+ N`."]
def of (f : M → N) [h : is_monoid_hom f] : M →* N :=
{ to_fun := f,
map_one' := h.2,
map_mul' := h.1.1 }
variables {mM mN mP}
@[simp, to_additive]
lemma coe_of (f : M → N) [is_monoid_hom f] : ⇑ (monoid_hom.of f) = f :=
rfl
@[to_additive]
instance (f : M →* N) : is_monoid_hom (f : M → N) :=
{ map_mul := f.map_mul,
map_one := f.map_one }
end monoid_hom
namespace is_monoid_hom
variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
/-- A monoid homomorphism preserves multiplication. -/
@[to_additive]
lemma map_mul (x y) : f (x * y) = f x * f y :=
is_mul_hom.map_mul f x y
end is_monoid_hom
/-- A map to a group preserving multiplication is a monoid homomorphism. -/
@[to_additive]
theorem is_monoid_hom.of_mul [monoid α] [group β] (f : α → β) [is_mul_hom f] :
is_monoid_hom f :=
{ map_one := mul_self_iff_eq_one.1 $ by rw [← is_mul_hom.map_mul f, one_mul] }
namespace is_monoid_hom
variables [monoid α] [monoid β] (f : α → β) [is_monoid_hom f]
/-- The identity map is a monoid homomorphism. -/
@[to_additive]
instance id : is_monoid_hom (@id α) := { map_one := rfl }
/-- The composite of two monoid homomorphisms is a monoid homomorphism. -/
@[to_additive] -- see Note [no instance on morphisms]
lemma comp {γ} [monoid γ] (g : β → γ) [is_monoid_hom g] :
is_monoid_hom (g ∘ f) :=
{ map_one := show g _ = 1, by rw [map_one f, map_one g], ..is_mul_hom.comp _ _ }
end is_monoid_hom
namespace is_add_monoid_hom
/-- Left multiplication in a ring is an additive monoid morphism. -/
instance is_add_monoid_hom_mul_left {γ : Type*} [semiring γ] (x : γ) :
is_add_monoid_hom (λ y : γ, x * y) :=
{ map_zero := mul_zero x, map_add := λ y z, mul_add x y z }
/-- Right multiplication in a ring is an additive monoid morphism. -/
instance is_add_monoid_hom_mul_right {γ : Type*} [semiring γ] (x : γ) :
is_add_monoid_hom (λ y : γ, y * x) :=
{ map_zero := zero_mul x, map_add := λ y z, add_mul y z x }
end is_add_monoid_hom
/-- Predicate for additive group homomorphism (deprecated -- use bundled `monoid_hom`). -/
class is_add_group_hom [add_group α] [add_group β] (f : α → β) extends is_add_hom f : Prop
/-- Predicate for group homomorphisms (deprecated -- use bundled `monoid_hom`). -/
@[to_additive]
class is_group_hom [group α] [group β] (f : α → β) extends is_mul_hom f : Prop
@[to_additive]
instance monoid_hom.is_group_hom {G H : Type*} {_ : group G} {_ : group H} (f : G →* H) :
is_group_hom (f : G → H) :=
{ map_mul := f.map_mul }
/-- Construct `is_group_hom` from its only hypothesis. The default constructor tries to get
`is_mul_hom` from class instances, and this makes some proofs fail. -/
@[to_additive]
lemma is_group_hom.mk' [group α] [group β] {f : α → β} (hf : ∀ x y, f (x * y) = f x * f y) :
is_group_hom f :=
{ map_mul := hf }
namespace is_group_hom
variables [group α] [group β] (f : α → β) [is_group_hom f]
open is_mul_hom (map_mul)
/-- A group homomorphism is a monoid homomorphism. -/
@[priority 100, to_additive] -- see Note [lower instance priority]
instance to_is_monoid_hom : is_monoid_hom f :=
is_monoid_hom.of_mul f
/-- A group homomorphism sends 1 to 1. -/
@[to_additive]
lemma map_one : f 1 = 1 := is_monoid_hom.map_one f
/-- A group homomorphism sends inverses to inverses. -/
@[to_additive]
theorem map_inv (a : α) : f a⁻¹ = (f a)⁻¹ :=
eq_inv_of_mul_eq_one $ by rw [← map_mul f, inv_mul_self, map_one f]
/-- The identity is a group homomorphism. -/
@[to_additive]
instance id : is_group_hom (@id α) := { }
/-- The composition of two group homomomorphisms is a group homomorphism. -/
@[to_additive] -- see Note [no instance on morphisms]
lemma comp {γ} [group γ] (g : β → γ) [is_group_hom g] : is_group_hom (g ∘ f) :=
{ ..is_mul_hom.comp _ _ }
/-- A group homomorphism is injective iff its kernel is trivial. -/
@[to_additive]
lemma injective_iff (f : α → β) [is_group_hom f] :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h _, by rw ← is_group_hom.map_one f; exact @h _ _,
λ h x y hxy, by rw [← inv_inv (f x), inv_eq_iff_mul_eq_one, ← map_inv f,
← map_mul f] at hxy;
simpa using inv_eq_of_mul_eq_one (h _ hxy)⟩
/-- The product of group homomorphisms is a group homomorphism if the target is commutative. -/
@[instance, priority 10, to_additive]
lemma mul {α β} [group α] [comm_group β]
(f g : α → β) [is_group_hom f] [is_group_hom g] :
is_group_hom (λa, f a * g a) :=
{ }
/-- The inverse of a group homomorphism is a group homomorphism if the target is commutative. -/
@[instance, to_additive]
lemma inv {α β} [group α] [comm_group β] (f : α → β) [is_group_hom f] :
is_group_hom (λa, (f a)⁻¹) :=
{ }
end is_group_hom
namespace ring_hom
/-!
These instances look redundant, because `deprecated.ring` provides `is_ring_hom` for a `→+*`.
Nevertheless these are harmless, and helpful for stripping out dependencies on `deprecated.ring`.
-/
variables {R : Type*} {S : Type*}
section
variables [semiring R] [semiring S]
instance (f : R →+* S) : is_monoid_hom f :=
{ map_one := f.map_one,
map_mul := f.map_mul }
instance (f : R →+* S) : is_add_monoid_hom f :=
{ map_zero := f.map_zero,
map_add := f.map_add }
end
section
variables [ring R] [ring S]
instance (f : R →+* S) : is_add_group_hom f :=
{ map_add := f.map_add }
end
end ring_hom
/-- Inversion is a group homomorphism if the group is commutative. -/
@[instance, to_additive]
lemma inv.is_group_hom [comm_group α] : is_group_hom (has_inv.inv : α → α) :=
{ map_mul := mul_inv }
namespace is_add_group_hom
variables [add_group α] [add_group β] (f : α → β) [is_add_group_hom f]
/-- Additive group homomorphisms commute with subtraction. -/
lemma map_sub (a b) : f (a - b) = f a - f b :=
calc f (a + -b) = f a + f (-b) : is_add_hom.map_add f _ _
... = f a + -f b : by rw [map_neg f]
end is_add_group_hom
/-- The difference of two additive group homomorphisms is an additive group
homomorphism if the target is commutative. -/
@[instance]
lemma is_add_group_hom.sub {α β} [add_group α] [add_comm_group β]
(f g : α → β) [is_add_group_hom f] [is_add_group_hom g] :
is_add_group_hom (λa, f a - g a) :=
is_add_group_hom.add f (λa, - g a)
namespace units
variables {M : Type*} {N : Type*} [monoid M] [monoid N]
/-- The group homomorphism on units induced by a multiplicative morphism. -/
@[reducible] def map' (f : M → N) [is_monoid_hom f] : units M →* units N :=
map (monoid_hom.of f)
@[simp] lemma coe_map' (f : M → N) [is_monoid_hom f] (x : units M) :
↑((map' f : units M → units N) x) = f x :=
rfl
instance coe_is_monoid_hom : is_monoid_hom (coe : units M → M) := (coe_hom M).is_monoid_hom
end units
namespace is_unit
variables {M : Type*} {N : Type*} [monoid M] [monoid N] {x : M}
lemma map' (f : M → N) {x : M} (h : is_unit x) [is_monoid_hom f] :
is_unit (f x) :=
h.map (monoid_hom.of f)
end is_unit
lemma additive.is_add_hom [has_mul α] [has_mul β] (f : α → β) [is_mul_hom f] :
@is_add_hom (additive α) (additive β) _ _ f :=
{ map_add := @is_mul_hom.map_mul α β _ _ f _ }
lemma multiplicative.is_mul_hom [has_add α] [has_add β] (f : α → β) [is_add_hom f] :
@is_mul_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_mul := @is_add_hom.map_add α β _ _ f _ }
lemma additive.is_add_monoid_hom [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] :
@is_add_monoid_hom (additive α) (additive β) _ _ f :=
{ map_zero := @is_monoid_hom.map_one α β _ _ f _,
..additive.is_add_hom f }
lemma multiplicative.is_monoid_hom [add_monoid α] [add_monoid β] (f : α → β) [is_add_monoid_hom f] :
@is_monoid_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_one := @is_add_monoid_hom.map_zero α β _ _ f _,
..multiplicative.is_mul_hom f }
lemma additive.is_add_group_hom [group α] [group β] (f : α → β) [is_group_hom f] :
@is_add_group_hom (additive α) (additive β) _ _ f :=
{ map_add := @is_mul_hom.map_mul α β _ _ f _ }
lemma multiplicative.is_group_hom [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] :
@is_group_hom (multiplicative α) (multiplicative β) _ _ f :=
{ map_mul := @is_add_hom.map_add α β _ _ f _ }
|
adc1a0f81050a82c4822a890b5c4031bdc186692 | a338c3e75cecad4fb8d091bfe505f7399febfd2b | /src/algebra/invertible.lean | 9aeb112edb11f9fec940d507500784a3564f83f2 | [
"Apache-2.0"
] | permissive | bacaimano/mathlib | 88eb7911a9054874fba2a2b74ccd0627c90188af | f2edc5a3529d95699b43514d6feb7eb11608723f | refs/heads/master | 1,686,410,075,833 | 1,625,497,070,000 | 1,625,497,070,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,668 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import algebra.group.units
import algebra.ring.basic
/-!
# Invertible elements
This file defines a typeclass `invertible a` for elements `a` with a two-sided
multiplicative inverse.
The intent of the typeclass is to provide a way to write e.g. `⅟2` in a ring
like `ℤ[1/2]` where some inverses exist but there is no general `⁻¹` operator;
or to specify that a field has characteristic `≠ 2`.
It is the `Type`-valued analogue to the `Prop`-valued `is_unit`.
For constructions of the invertible element given a characteristic, see
`algebra/char_p/invertible` and other lemmas in that file.
## Notation
* `⅟a` is `invertible.inv_of a`, the inverse of `a`
## Implementation notes
The `invertible` class lives in `Type`, not `Prop`, to make computation easier.
If multiplication is associative, `invertible` is a subsingleton anyway.
The `simp` normal form tries to normalize `⅟a` to `a ⁻¹`. Otherwise, it pushes
`⅟` inside the expression as much as possible.
## Tags
invertible, inverse element, inv_of, a half, one half, a third, one third, ½, ⅓
-/
universes u
variables {α : Type u}
/-- `invertible a` gives a two-sided multiplicative inverse of `a`. -/
class invertible [has_mul α] [has_one α] (a : α) : Type u :=
(inv_of : α) (inv_of_mul_self : inv_of * a = 1) (mul_inv_of_self : a * inv_of = 1)
-- This notation has the same precedence as `has_inv.inv`.
notation `⅟`:1034 := invertible.inv_of
@[simp]
lemma inv_of_mul_self [has_mul α] [has_one α] (a : α) [invertible a] : ⅟a * a = 1 :=
invertible.inv_of_mul_self
@[simp]
lemma mul_inv_of_self [has_mul α] [has_one α] (a : α) [invertible a] : a * ⅟a = 1 :=
invertible.mul_inv_of_self
@[simp]
lemma inv_of_mul_self_assoc [monoid α] (a b : α) [invertible a] : ⅟a * (a * b) = b :=
by rw [←mul_assoc, inv_of_mul_self, one_mul]
@[simp]
lemma mul_inv_of_self_assoc [monoid α] (a b : α) [invertible a] : a * (⅟a * b) = b :=
by rw [←mul_assoc, mul_inv_of_self, one_mul]
@[simp]
lemma mul_inv_of_mul_self_cancel [monoid α] (a b : α) [invertible b] : a * ⅟b * b = a :=
by simp [mul_assoc]
@[simp]
lemma mul_mul_inv_of_self_cancel [monoid α] (a b : α) [invertible b] : a * b * ⅟b = a :=
by simp [mul_assoc]
lemma inv_of_eq_right_inv [monoid α] {a b : α} [invertible a] (hac : a * b = 1) : ⅟a = b :=
left_inv_eq_right_inv (inv_of_mul_self _) hac
lemma inv_of_eq_left_inv [monoid α] {a b : α} [invertible a] (hac : b * a = 1) : ⅟a = b :=
(left_inv_eq_right_inv hac (mul_inv_of_self _)).symm
lemma invertible_unique {α : Type u} [monoid α] (a b : α) (h : a = b)
[invertible a] [invertible b] :
⅟a = ⅟b :=
by { apply inv_of_eq_right_inv, rw [h, mul_inv_of_self], }
instance [monoid α] (a : α) : subsingleton (invertible a) :=
⟨ λ ⟨b, hba, hab⟩ ⟨c, hca, hac⟩, by { congr, exact left_inv_eq_right_inv hba hac } ⟩
/-- An `invertible` element is a unit. -/
def unit_of_invertible [monoid α] (a : α) [invertible a] : units α :=
{ val := a,
inv := ⅟a,
val_inv := by simp,
inv_val := by simp, }
@[simp] lemma unit_of_invertible_val [monoid α] (a : α) [invertible a] :
(unit_of_invertible a : α) = a := rfl
@[simp] lemma unit_of_invertible_inv [monoid α] (a : α) [invertible a] :
(↑(unit_of_invertible a)⁻¹ : α) = ⅟a := rfl
lemma is_unit_of_invertible [monoid α] (a : α) [invertible a] : is_unit a :=
⟨unit_of_invertible a, rfl⟩
/-- Units are invertible in their associated monoid. -/
def units.invertible [monoid α] (u : units α) : invertible (u : α) :=
{ inv_of := ↑(u⁻¹), inv_of_mul_self := u.inv_mul, mul_inv_of_self := u.mul_inv }
@[simp] lemma inv_of_units [monoid α] (u : units α) [invertible (u : α)] : ⅟(u : α) = ↑(u⁻¹) :=
inv_of_eq_right_inv u.mul_inv
/-- Each element of a group is invertible. -/
def invertible_of_group [group α] (a : α) : invertible a :=
⟨a⁻¹, inv_mul_self a, mul_inv_self a⟩
@[simp] lemma inv_of_eq_group_inv [group α] (a : α) [invertible a] : ⅟a = a⁻¹ :=
inv_of_eq_right_inv (mul_inv_self a)
/-- `1` is the inverse of itself -/
def invertible_one [monoid α] : invertible (1 : α) :=
⟨1, mul_one _, one_mul _⟩
@[simp] lemma inv_of_one [monoid α] [invertible (1 : α)] : ⅟(1 : α) = 1 :=
inv_of_eq_right_inv (mul_one _)
/-- `-⅟a` is the inverse of `-a` -/
def invertible_neg [ring α] (a : α) [invertible a] : invertible (-a) :=
⟨ -⅟a, by simp, by simp ⟩
@[simp] lemma inv_of_neg [ring α] (a : α) [invertible a] [invertible (-a)] : ⅟(-a) = -⅟a :=
inv_of_eq_right_inv (by simp)
@[simp] lemma one_sub_inv_of_two [ring α] [invertible (2:α)] : 1 - (⅟2:α) = ⅟2 :=
(is_unit_of_invertible (2:α)).mul_right_inj.1 $
by rw [mul_sub, mul_inv_of_self, mul_one, bit0, add_sub_cancel]
/-- `a` is the inverse of `⅟a`. -/
instance invertible_inv_of [has_one α] [has_mul α] {a : α} [invertible a] : invertible (⅟a) :=
⟨ a, mul_inv_of_self a, inv_of_mul_self a ⟩
@[simp] lemma inv_of_inv_of [monoid α] {a : α} [invertible a] [invertible (⅟a)] :
⅟(⅟a) = a :=
inv_of_eq_right_inv (inv_of_mul_self _)
/-- `⅟b * ⅟a` is the inverse of `a * b` -/
def invertible_mul [monoid α] (a b : α) [invertible a] [invertible b] : invertible (a * b) :=
⟨ ⅟b * ⅟a, by simp [←mul_assoc], by simp [←mul_assoc] ⟩
@[simp]
lemma inv_of_mul [monoid α] (a b : α) [invertible a] [invertible b] [invertible (a * b)] :
⅟(a * b) = ⅟b * ⅟a :=
inv_of_eq_right_inv (by simp [←mul_assoc])
/--
If `r` is invertible and `s = r`, then `s` is invertible.
-/
def invertible.copy [monoid α] {r : α} (hr : invertible r) (s : α) (hs : s = r) : invertible s :=
{ inv_of := ⅟r,
inv_of_mul_self := by rw [hs, inv_of_mul_self],
mul_inv_of_self := by rw [hs, mul_inv_of_self] }
theorem commute.inv_of_right [monoid α] {a b : α} [invertible b] (h : commute a b) :
commute a (⅟b) :=
calc a * (⅟b) = (⅟b) * (b * a * (⅟b)) : by simp [mul_assoc]
... = (⅟b) * (a * b * ((⅟b))) : by rw h.eq
... = (⅟b) * a : by simp [mul_assoc]
theorem commute.inv_of_left [monoid α] {a b : α} [invertible b] (h : commute b a) :
commute (⅟b) a :=
calc (⅟b) * a = (⅟b) * (a * b * (⅟b)) : by simp [mul_assoc]
... = (⅟b) * (b * a * (⅟b)) : by rw h.eq
... = a * (⅟b) : by simp [mul_assoc]
lemma commute_inv_of {M : Type*} [has_one M] [has_mul M] (m : M) [invertible m] :
commute m (⅟m) :=
calc m * ⅟m = 1 : mul_inv_of_self m
... = ⅟ m * m : (inv_of_mul_self m).symm
section group_with_zero
variable [group_with_zero α]
lemma nonzero_of_invertible (a : α) [invertible a] : a ≠ 0 :=
λ ha, zero_ne_one $ calc 0 = ⅟a * a : by simp [ha]
... = 1 : inv_of_mul_self a
/-- `a⁻¹` is an inverse of `a` if `a ≠ 0` -/
def invertible_of_nonzero {a : α} (h : a ≠ 0) : invertible a :=
⟨ a⁻¹, inv_mul_cancel h, mul_inv_cancel h ⟩
@[simp] lemma inv_of_eq_inv (a : α) [invertible a] : ⅟a = a⁻¹ :=
inv_of_eq_right_inv (mul_inv_cancel (nonzero_of_invertible a))
@[simp] lemma inv_mul_cancel_of_invertible (a : α) [invertible a] : a⁻¹ * a = 1 :=
inv_mul_cancel (nonzero_of_invertible a)
@[simp] lemma mul_inv_cancel_of_invertible (a : α) [invertible a] : a * a⁻¹ = 1 :=
mul_inv_cancel (nonzero_of_invertible a)
@[simp] lemma div_mul_cancel_of_invertible (a b : α) [invertible b] : a / b * b = a :=
div_mul_cancel a (nonzero_of_invertible b)
@[simp] lemma mul_div_cancel_of_invertible (a b : α) [invertible b] : a * b / b = a :=
mul_div_cancel a (nonzero_of_invertible b)
@[simp] lemma div_self_of_invertible (a : α) [invertible a] : a / a = 1 :=
div_self (nonzero_of_invertible a)
/-- `b / a` is the inverse of `a / b` -/
def invertible_div (a b : α) [invertible a] [invertible b] : invertible (a / b) :=
⟨b / a, by simp [←mul_div_assoc], by simp [←mul_div_assoc]⟩
@[simp] lemma inv_of_div (a b : α) [invertible a] [invertible b] [invertible (a / b)] :
⅟(a / b) = b / a :=
inv_of_eq_right_inv (by simp [←mul_div_assoc])
/-- `a` is the inverse of `a⁻¹` -/
def invertible_inv {a : α} [invertible a] : invertible (a⁻¹) :=
⟨ a, by simp, by simp ⟩
end group_with_zero
/--
Monoid homs preserve invertibility.
-/
def invertible.map {R : Type*} {S : Type*} [monoid R] [monoid S] (f : R →* S)
(r : R) [invertible r] :
invertible (f r) :=
{ inv_of := f (⅟r),
inv_of_mul_self := by rw [← f.map_mul, inv_of_mul_self, f.map_one],
mul_inv_of_self := by rw [← f.map_mul, mul_inv_of_self, f.map_one] }
|
b5921e467b531d3afa71866e895c13f20cda94e0 | 471bedbd023d35c9d078c2f936dd577ace7f5813 | /library/init/meta/tactic.lean | 8089b7708e78998ab96e0ec6eeac74e9954a4921 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean | e06f0fa503666df827edd9867d7f49ca017aae64 | fc13c8c72a15dab71a2c2b31410c2cadc3526bd7 | refs/heads/master | 1,666,785,407,985 | 1,666,153,673,000 | 1,666,153,673,000 | 310,165,986 | 0 | 0 | Apache-2.0 | 1,604,542,096,000 | 1,604,542,095,000 | null | UTF-8 | Lean | false | false | 76,450 | 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.function init.data.option.basic init.util
import init.control.combinators init.control.monad init.control.alternative init.control.monad_fail
import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment
import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad
import init.classical
open native
meta constant tactic_state : Type
universes u v
namespace tactic_state
meta constant env : tactic_state → environment
/-- Format the given tactic state. If `target_lhs_only` is true and the target
is of the form `lhs ~ rhs`, where `~` is a simplification relation,
then only the `lhs` is displayed.
Remark: the parameter `target_lhs_only` is a temporary hack used to implement
the `conv` monad. It will be removed in the future. -/
meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format
/-- Format expression with respect to the main goal in the tactic state.
If the tactic state does not contain any goals, then format expression
using an empty local context. -/
meta constant format_expr : tactic_state → expr → format
meta constant get_options : tactic_state → options
meta constant set_options : tactic_state → options → tactic_state
end tactic_state
meta instance : has_to_format tactic_state :=
⟨tactic_state.to_format⟩
meta instance : has_to_string tactic_state :=
⟨λ s, (to_fmt s).to_string s.get_options⟩
/-- `tactic` is the monad for building tactics.
You use this to:
- View and modify the local goals and hypotheses in the prover's state.
- Invoke type checking and elaboration of terms.
- View and modify the environment.
- Build new tactics out of existing ones such as `simp` and `rewrite`.
-/
@[reducible] meta def tactic := interaction_monad tactic_state
@[reducible] meta def tactic_result := interaction_monad.result tactic_state
namespace tactic
export interaction_monad (result result.success result.exception result.cases_on
result_to_string mk_exception silent_fail orelse' bracket)
/-- Cause the tactic to fail with no error message. -/
meta def failed {α : Type} : tactic α := interaction_monad.failed
meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α :=
interaction_monad.fail msg
end tactic
namespace tactic_result
export interaction_monad.result
end tactic_result
open tactic
open tactic_result
infixl ` >>=[tactic] `:2 := interaction_monad_bind
infixl ` >>[tactic] `:2 := interaction_monad_seq
meta instance : alternative tactic :=
{ failure := @interaction_monad.failed _,
orelse := @interaction_monad_orelse _,
..interaction_monad.monad }
meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) :=
λ s, match t s with
| success a s' := success (ulift.up a) s'
| exception t ref s := exception t ref s
end
meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α :=
λ s, match t s with
| success (ulift.up a) s' := success a s'
| exception t ref s := exception t ref s
end
namespace interactive
/-- Typeclass for custom interaction monads, which provides
the information required to convert an interactive-mode
construction to a `tactic` which can actually be executed.
Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end`
block, or a `by ...` statement into a `tactic α` which can actually be
executed. The `inhabited` first argument facilitates the passing of an
optional configuration parameter `config`, using the syntax:
```
begin [custom_monad] with config,
...
end
```
-/
meta class executor (m : Type → Type u) [monad m] :=
(config_type : Type)
[inhabited : inhabited config_type]
(execute_with : config_type → m unit → tactic unit)
attribute [inline] executor.execute_with
@[inline]
meta def executor.execute_explicit (m : Type → Type u)
[monad m] [e : executor m] : m unit → tactic unit :=
executor.execute_with e.inhabited.default
@[inline]
meta def executor.execute_with_explicit (m : Type → Type u)
[monad m] [executor m] : executor.config_type m → m unit → tactic unit :=
executor.execute_with
/-- Default `executor` instance for `tactic`s themselves -/
meta instance executor_tactic : executor tactic :=
{ config_type := unit,
inhabited := ⟨()⟩,
execute_with := λ _, id }
end interactive
namespace tactic
open interaction_monad.result
variables {α : Type u}
/-- Does nothing. -/
meta def skip : tactic unit :=
success ()
/--
`try_core t` acts like `t`, but succeeds even if `t` fails. It returns the
result of `t` if `t` succeeded and `none` otherwise.
-/
meta def try_core (t : tactic α) : tactic (option α) := λ s,
match t s with
| (exception _ _ _) := success none s
| (success a s') := success (some a) s'
end
/--
`try t` acts like `t`, but succeeds even if `t` fails.
-/
meta def try (t : tactic α) : tactic unit := λ s,
match t s with
| (exception _ _ _) := success () s
| (success _ s') := success () s'
end
meta def try_lst : list (tactic unit) → tactic unit
| [] := failed
| (tac :: tacs) := λ s,
match tac s with
| success _ s' := try (try_lst tacs) s'
| exception e p s' :=
match try_lst tacs s' with
| exception _ _ _ := exception e p s'
| r := r
end
end
/--
`fail_if_success t` acts like `t`, but succeeds if `t` fails and fails if `t`
succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t`
succeeds.
-/
meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s,
match (t s) with
| (success a s) := mk_exception "fail_if_success combinator failed, given tactic succeeded" none s
| (exception _ _ _) := success () s
end
/--
`success_if_fail t` acts like `t`, but succeeds if `t` fails and fails if `t`
succeeds. Changes made by `t` to the `tactic_state` are preserved only if `t`
succeeds.
-/
meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s,
match t s with
| (success a s) :=
mk_exception "success_if_fail combinator failed, given tactic succeeded" none s
| (exception _ _ _) := success () s
end
open nat
/--
`iterate_at_most n t` iterates `t` `n` times or until `t` fails, returning the
result of each successful iteration.
-/
meta def iterate_at_most : nat → tactic α → tactic (list α)
| 0 t := pure []
| (n + 1) t := do
(some a) ← try_core t | pure [],
as ← iterate_at_most n t,
pure $ a :: as
/--
`iterate_at_most' n t` repeats `t` `n` times or until `t` fails.
-/
meta def iterate_at_most' : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := do
(some _) ← try_core t | skip,
iterate_at_most' n t
/--
`iterate_exactly n t` iterates `t` `n` times, returning the result of
each iteration. If any iteration fails, the whole tactic fails.
-/
meta def iterate_exactly : nat → tactic α → tactic (list α)
| 0 t := pure []
| (n + 1) t := do
a ← t,
as ← iterate_exactly n t,
pure $ a ::as
/--
`iterate_exactly' n t` executes `t` `n` times. If any iteration fails, the whole
tactic fails.
-/
meta def iterate_exactly' : nat → tactic unit → tactic unit
| 0 t := skip
| (n + 1) t := t *> iterate_exactly' n t
/--
`iterate t` repeats `t` 100.000 times or until `t` fails, returning the
result of each iteration.
-/
meta def iterate : tactic α → tactic (list α) :=
iterate_at_most 100000
/--
`iterate' t` repeats `t` 100.000 times or until `t` fails.
-/
meta def iterate' : tactic unit → tactic unit :=
iterate_at_most' 100000
meta def returnopt (e : option α) : tactic α :=
λ s, match e with
| (some a) := success a s
| none := mk_exception "failed" none s
end
meta instance opt_to_tac : has_coe (option α) (tactic α) :=
⟨returnopt⟩
/-- Decorate t's exceptions with msg. -/
meta def decorate_ex (msg : format) (t : tactic α) : tactic α :=
λ s, result.cases_on (t s)
success
(λ opt_thunk,
match opt_thunk with
| some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u)))
| none := exception none
end)
/-- Set the tactic_state. -/
@[inline] meta def write (s' : tactic_state) : tactic unit :=
λ s, success () s'
/-- Get the tactic_state. -/
@[inline] meta def read : tactic tactic_state :=
λ s, success s s
/--
`capture t` acts like `t`, but succeeds with a result containing either the returned value
or the exception.
Changes made by `t` to the `tactic_state` are preserved in both cases.
The result can be used to inspect the error message, or passed to `unwrap` to rethrow the
failure later.
-/
meta def capture (t : tactic α) : tactic (tactic_result α) :=
λ s, match t s with
| (success r s') := success (success r s') s'
| (exception f p s') := success (exception f p s') s'
end
/--
`unwrap r` unwraps a result previously obtained using `capture`.
If the previous result was a success, this produces its wrapped value.
If the previous result was an exception, this "rethrows" the exception as if it came
from where it originated.
`do r ← capture t, unwrap r` is identical to `t`, but allows for intermediate tactics to be inserted.
-/
meta def unwrap {α : Type*} (t : tactic_result α) : tactic α :=
match t with
| (success r s') := return r
| e := λ s, e
end
/--
`resume r` continues execution from a result previously obtained using `capture`.
This is like `unwrap`, but the `tactic_state` is rolled back to point of capture even upon success.
-/
meta def resume {α : Type*} (t : tactic_result α) : tactic α :=
λ s, t
meta def get_options : tactic options :=
do s ← read, return s.get_options
meta def set_options (o : options) : tactic unit :=
do s ← read, write (s.set_options o)
meta def save_options {α : Type} (t : tactic α) : tactic α :=
do o ← get_options,
a ← t,
set_options o,
return a
meta def returnex {α : Type} (e : exceptional α) : tactic α :=
λ s, match e with
| exceptional.success a := success a s
| exceptional.exception f :=
match get_options s with
| success opt _ := exception (some (λ u, f opt)) none s
| exception _ _ _ := exception (some (λ u, f options.mk)) none s
end
end
meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) :=
⟨returnex⟩
end tactic
meta def tactic_format_expr (e : expr) : tactic format :=
do s ← tactic.read, return (tactic_state.format_expr s e)
meta class has_to_tactic_format (α : Type u) :=
(to_tactic_format : α → tactic format)
meta instance : has_to_tactic_format expr :=
⟨tactic_format_expr⟩
meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format :=
has_to_tactic_format.to_tactic_format
open tactic format
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) :=
⟨λ l, to_fmt <$> l.mmap pp⟩
meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] :
has_to_tactic_format (α × β) :=
⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩
meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format
| (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")")
| none := return "none"
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) :=
⟨option_to_tactic_format⟩
meta instance {α} (a : α) : has_to_tactic_format (reflected _ a) :=
⟨λ h, pp h.to_expr⟩
@[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α :=
⟨(λ x, return x) ∘ to_fmt⟩
namespace tactic
open tactic_state
meta def get_env : tactic environment :=
do s ← read,
return $ env s
meta def get_decl (n : name) : tactic declaration :=
do s ← read,
(env s).get n
meta constant get_trace_msg_pos : tactic pos
meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit :=
do fmt ← pp a,
return $ _root_.trace_fmt fmt (λ u, ())
meta def trace_call_stack : tactic unit :=
assume state, _root_.trace_call_stack (success () state)
meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α :=
λ s, timeit desc (t () s)
meta def trace_state : tactic unit :=
do s ← read,
trace $ to_fmt s
/-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal.
By default, theorem declarations are never unfolded.
- `all` will unfold everything, including macros and theorems. Except projection macros.
- `semireducible` will unfold everything except theorems and definitions tagged as irreducible.
- `instances` will unfold all class instance definitions and definitions tagged with reducible.
- `reducible` will only unfold definitions tagged with the `reducible` attribute.
- `none` will never unfold anything.
[NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes.
[NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems.
-/
inductive transparency
| all | semireducible | instances | reducible | none
export transparency (reducible semireducible)
/-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/
meta constant eval_expr (α : Type u) [reflected _ α] : expr → tactic α
/-- Return the partial term/proof constructed so far. Note that the resultant expression
may contain variables that are not declarate in the current main goal. -/
meta constant result : tactic expr
/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to
`do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect
to the current goal, and trace_result will do it with respect to the initial goal. -/
meta constant format_result : tactic format
/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/
meta constant target : tactic expr
meta constant intro_core : name → tactic expr
meta constant intron : nat → tactic unit
/-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/
meta constant clear : expr → tactic unit
/-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target.
If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants.
Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`.
-/
meta constant revert_lst : list expr → tactic nat
/-- Return `e` in weak head normal form with respect to the given transparency setting.
If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors
and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations
are compiled into primitive datatypes accepted by the Kernel. -/
meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr
/-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/
meta constant head_eta_expand : expr → tactic expr
/-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/
meta constant head_beta : expr → tactic expr
/-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/
meta constant head_zeta : expr → tactic expr
/-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/
meta constant zeta : expr → tactic expr
/-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/
meta constant head_eta : expr → tactic expr
/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/
meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit
/-- Similar to `unify`, but it treats metavariables as constants. -/
meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit
/-- Infer the type of the given expression.
Remark: transparency does not affect type inference -/
meta constant infer_type : expr → tactic expr
/-- Get the `local_const` expr for the given `name`. -/
meta constant get_local : name → tactic expr
/-- Resolve a name using the current local context, environment, aliases, etc. -/
meta constant resolve_name : name → tactic pexpr
/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/
meta constant local_context : tactic (list expr)
/-- Get a fresh name that is guaranteed to not be in use in the local context.
If `n` is provided and `n` is not in use, then `n` is returned.
Otherwise a number `i` is appended to give `"n_i"`.
-/
meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name
/-- Helper tactic for creating simple applications where some arguments are inferred using
type inference.
Example, given
```
rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop
nat : Type
real : Type
vec.{l} : Pi (α : Type l) (n : nat), Type.{l1}
f g : Pi (n : nat), vec real n
```
then
```
mk_app_core semireducible "rel" [f, g]
```
returns the application
```
rel.{1 2} nat (fun n : nat, vec real n) f g
```
The unification constraints due to type inference are solved using the transparency `md`.
-/
meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr
/-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit.
Example, given `(a b : nat)` then
```
mk_mapp "ite" [some (a > b), none, none, some a, some b]
```
returns the application
```
@ite.{1} nat (a > b) (nat.decidable_gt a b) a b
```
-/
meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr
/-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/
meta constant mk_congr_arg : expr → expr → tactic expr
/-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/
meta constant mk_congr_fun : expr → expr → tactic expr
/-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/
meta constant mk_congr : expr → expr → tactic expr
/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/
meta constant mk_eq_refl : expr → tactic expr
/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/
meta constant mk_eq_symm : expr → tactic expr
/-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/
meta constant mk_eq_trans : expr → expr → tactic expr
/-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/
meta constant mk_eq_mp : expr → expr → tactic expr
/-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/
meta constant mk_eq_mpr : expr → expr → tactic expr
/-- Given a local constant t, if t has type (lhs = rhs) apply substitution.
Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t).
The tactic fails if the given expression is not a local constant. -/
meta constant subst_core : expr → tactic unit
/-- Close the current goal using `e`. Fail if the type of `e` is not definitionally equal to
the target type. -/
meta constant exact (e : expr) (md := semireducible) : tactic unit
/-- Elaborate the given quoted expression with respect to the current main goal.
Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables.
If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/
meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr
/-- Return true if the given expression is a type class. -/
meta constant is_class : expr → tactic bool
/-- Try to create an instance of the given type class. -/
meta constant mk_instance : expr → tactic expr
/-- Change the target of the main goal.
The input expression must be definitionally equal to the current target.
If `check` is `ff`, then the tactic does not check whether `e`
is definitionally equal to the current target. If it is not,
then the error will only be detected by the kernel type checker. -/
meta constant change (e : expr) (check : bool := tt): tactic unit
/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/
meta constant assert_core : name → expr → tactic unit
/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/
meta constant assertv_core : name → expr → expr → tactic unit
/-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/
meta constant define_core : name → expr → tactic unit
/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/
meta constant definev_core : name → expr → expr → tactic unit
/-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/
meta constant rotate_left : nat → tactic unit
/-- Gets a list of metavariables, one for each goal. -/
meta constant get_goals : tactic (list expr)
/-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/
meta constant set_goals : list expr → tactic unit
/-- Convenience function for creating ` for proofs. -/
meta def mk_tagged_proof (prop : expr) (pr : expr) (tag : name) : expr :=
expr.mk_app (expr.const ``id_tag []) [expr.const tag [], prop, pr]
/-- How to order the new goals made from an `apply` tactic.
Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q`
- `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on.
- `non_dep_only` would produce goal `⊢ P(?m)`.
- `all` would produce goals `⊢ α`, `⊢ P(?m)`.
-/
inductive new_goals
| non_dep_first | non_dep_only | all
/-- Configuration options for the `apply` tactic.
- `md` sets how aggressively definitions are unfolded.
- `new_goals` is the strategy for ordering new goals.
- `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution.
- `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`.
- `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`.
- `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints.
For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration,
but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where
`?y` is a fresh metavariable.
-/
structure apply_cfg :=
(md := semireducible)
(approx := tt)
(new_goals := new_goals.non_dep_first)
(instances := tt)
(auto_param := tt)
(opt_param := tt)
(unify := tt)
/-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`.
Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`.
All of the metavariables that are not assigned are added as new metavariables.
If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification.
`cfg.new_goals` specifies which unassigned metavariables become new goals, and their order.
If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables.
The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`).
It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/
meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr))
/- Create a fresh meta universe variable. -/
meta constant mk_meta_univ : tactic level
/- Create a fresh meta-variable with the given type.
The scope of the new meta-variable is the local context of the main goal. -/
meta constant mk_meta_var : expr → tactic expr
/-- Return the value assigned to the given universe meta-variable.
Fail if argument is not an universe meta-variable or if it is not assigned. -/
meta constant get_univ_assignment : level → tactic level
/-- Return the value assigned to the given meta-variable.
Fail if argument is not a meta-variable or if it is not assigned. -/
meta constant get_assignment : expr → tactic expr
/-- Return true if the given meta-variable is assigned.
Fail if argument is not a meta-variable. -/
meta constant is_assigned : expr → tactic bool
/-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/
meta constant mk_fresh_name : tactic name
/-- Induction on `h` using recursor `rec`, names for the new hypotheses
are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names
in the recursor.
It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor),
a list of new hypotheses, and a list of substitutions for hypotheses
depending on `h`. The substitutions map internal names to their replacement terms. If the
replacement is again a hypothesis the user name stays the same. The internal names are only valid
in the original goal, not in the type context of the new goal.
Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of
constructor names.
If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/
meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`.
`h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of
substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the
number of constructors. Some goals may be discarded when the indices to not match.
See `induction` for information on the list of substitutions.
The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`.
Note: There is one "new hypothesis" for every constructor argument. These are
usually local constants, but due to dependent pattern matching, they can also
be arbitrary terms. -/
meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/
meta constant destruct (e : expr) (md := semireducible) : tactic unit
/-- Generalizes the target with respect to `e`. -/
meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit
/-- instantiate assigned metavariables in the given expression -/
meta constant instantiate_mvars : expr → tactic expr
/-- Add the given declaration to the environment -/
meta constant add_decl : declaration → tactic unit
/--
Changes the environment to the `new_env`.
The new environment does not need to be a descendant of the old one.
Use with care.
-/
meta constant set_env_core : environment → tactic unit
/-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/
meta constant set_env : environment → tactic unit
/-- `doc_string env d k` returns the doc string for `d` (if available) -/
meta constant doc_string : name → tactic string
/-- Set the docstring for the given declaration. -/
meta constant add_doc_string : name → string → tactic unit
/--
Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and
meta-variables. This function collects all dependencies (universe parameters, universe metavariables,
local constants (aka hypotheses) and metavariables).
It updates the environment in the tactic_state, and returns an expression of the form
(c.{l_1 ... l_n} a_1 ... a_m)
where l_i's and a_j's are the collected dependencies.
-/
meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr
/-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones.
The returned object is a list of modules, indexed by `(some filename)` for imported modules
and `none` for the active one, where each module in the list is paired with a list
of `(position_in_file, docstring)` pairs. -/
meta constant olean_doc_strings : tactic (list (option string × (list (pos × string))))
/-- Returns a list of docstrings in the active module. An entry in the list can be either:
- a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)`
- a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/
meta def module_doc_strings : tactic (list (option name × string)) :=
do
/- Obtain a list of top-level docs in current module. -/
mod_docs ← olean_doc_strings,
let mod_docs: list (list (option name × string)) :=
mod_docs.filter_map (λ d,
if d.1.is_none
then some (d.2.map
(λ pos_doc, ⟨none, pos_doc.2⟩))
else none),
let mod_docs := mod_docs.join,
/- Obtain list of declarations in current module. -/
e ← get_env,
let decls := environment.fold e ([]: list name)
(λ d acc, let n := d.to_name in
if (environment.decl_olean e n).is_none
then n::acc else acc),
/- Map declarations to those which have docstrings. -/
decls ← decls.mfoldl (λa n,
(doc_string n >>=
λ doc, pure $ (some n, doc) :: a)
<|> pure a) [],
pure (mod_docs ++ decls)
/-- Set attribute `attr_name` for constant `c_name` with the given priority.
If the priority is none, then use default -/
meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit
/-- `unset_attribute attr_name c_name` -/
meta constant unset_attribute : name → name → tactic unit
/-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name`
has the attribute `attr_name`. The result is the priority and whether or not
the attribute is persistent. -/
meta constant has_attribute : name → name → tactic (bool × nat)
/-- `copy_attribute attr_name c_name p d_name` copy attribute `attr_name` from
`src` to `tgt` if it is defined for `src`; make it persistent if `p` is `tt`;
if `p` is `none`, the copied attribute is made persistent iff it is persistent on `src` -/
meta def copy_attribute (attr_name : name) (src : name) (tgt : name) (p : option bool := none) : tactic unit :=
try $ do
(p', prio) ← has_attribute attr_name src,
let p := p.get_or_else p',
set_basic_attribute attr_name tgt p (some prio)
/-- Name of the declaration currently being elaborated. -/
meta constant decl_name : tactic name
/-- `save_type_info e ref` save (typeof e) at position associated with ref -/
meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit
meta constant save_info_thunk : pos → (unit → format) → tactic unit
/-- Return list of currently open namespaces -/
meta constant open_namespaces : tactic (list name)
/-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using
keyed matching with the given transparency setting.
We say `t` occurs in `e` by keyed matching iff there is a subterm `s`
s.t. `t` and `s` have the same head, and `is_def_eq t s md`
The main idea is to minimize the number of `is_def_eq` checks
performed. -/
meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool
/-- Abstracts all occurrences of the term `t` in `e` using keyed matching.
If `unify` is `ff`, then matching is used instead of unification.
That is, metavariables occurring in `e` are not assigned. -/
meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr
/-- Blocks the execution of the current thread for at least `msecs` milliseconds.
This tactic is used mainly for debugging purposes. -/
meta constant sleep (msecs : nat) : tactic unit
/-- Type check `e` with respect to the current goal.
Fails if `e` is not type correct. -/
meta constant type_check (e : expr) (md := semireducible) : tactic unit
open list nat
/-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/
def tag : Type := list name
/-- Enable/disable goal tagging. -/
meta constant enable_tags (b : bool) : tactic unit
/-- Return tt iff goal tagging is enabled. -/
meta constant tags_enabled : tactic bool
/-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled.
Remark: `set_goal g []` removes the tag -/
meta constant set_tag (g : expr) (t : tag) : tactic unit
/-- Return tag associated with `g`. Return `[]` if there is no tag. -/
meta constant get_tag (g : expr) : tactic tag
/-! By default, Lean only considers local instances in the header of declarations.
This has two main benefits.
1- Results produced by the type class resolution procedure can be easily cached.
2- The set of local instances does not have to be recomputed.
This approach has the following disadvantages:
1- Frozen local instances cannot be reverted.
2- Local instances defined inside of a declaration are not considered during type
class resolution.
-/
/--
Avoid this function! Use `unfreezingI`/`resetI`/etc. instead!
Unfreezes the current set of local instances.
After this tactic, the instance cache is disabled.
-/
meta constant unfreeze_local_instances : tactic unit
/--
Freeze the current set of local instances.
-/
meta constant freeze_local_instances : tactic unit
/- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/
meta constant frozen_local_instances : tactic (option (list expr))
/-- Run the provided tactic, associating it to the given AST node. -/
meta constant with_ast {α : Type u} (ast : ℕ) (t : tactic α) : tactic α
meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit :=
induction h ns rec md >> return ()
/-- Remark: set_goals will erase any solved goal -/
meta def cleanup : tactic unit :=
get_goals >>= set_goals
/-- Auxiliary definition used to implement begin ... end blocks -/
meta def step {α : Type u} (t : tactic α) : tactic unit :=
t >>[tactic] cleanup
meta def istep {α : Type u} (line0 col0 line col ast : ℕ) (t : tactic α) : tactic unit :=
λ s, (@scope_trace _ line col (λ _, with_ast ast (step t) s)).clamp_pos line0 line col
meta def is_prop (e : expr) : tactic bool :=
do t ← infer_type e,
return (t = `(Prop))
/-- Return true iff n is the name of declaration that is a proposition. -/
meta def is_prop_decl (n : name) : tactic bool :=
do env ← get_env,
d ← env.get n,
t ← return $ d.type,
is_prop t
meta def is_proof (e : expr) : tactic bool :=
infer_type e >>= is_prop
meta def whnf_no_delta (e : expr) : tactic expr :=
whnf e transparency.none
/-- Return `e` in weak head normal form with respect to the given transparency setting,
or `e` head is a generalized constructor or inductive datatype. -/
meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr :=
whnf e md ff
meta def whnf_target : tactic unit :=
target >>= whnf >>= change
/-- Change the target of the main goal.
The input expression must be definitionally equal to the current target.
The tactic does not check whether `e`
is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/
meta def unsafe_change (e : expr) : tactic unit :=
change e ff
/-- Pi or elet introduction.
Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`.
Returns the new local constant. Similarly for `elet` expressions.
If the target is not a Pi or elet it will try to put it in WHNF.
-/
meta def intro (n : name) : tactic expr :=
do t ← target,
if expr.is_pi t ∨ expr.is_let t then intro_core n
else whnf_target >> intro_core n
/--
A variant of `intro` which makes sure that the introduced hypothesis's name is
unique in the context. If there is no hypothesis named `n` in the context yet,
`intro_fresh n` is the same as `intro n`. If there is already a hypothesis named
`n`, the new hypothesis is named `n_1` (or `n_2` if `n_1` already exists, etc.).
If `offset` is given, the new names are `n_offset`, `n_offset+1` etc.
If `n` is `_`, `intro_fresh n` is the same as `intro1`. The `offset` is ignored
in this case.
-/
meta def intro_fresh (n : name) (offset : option nat := none) : tactic expr :=
if n = `_
then intro `_
else do
n ← get_unused_name n offset,
intro n
/-- Like `intro` except the name is derived from the bound name in the Π. -/
meta def intro1 : tactic expr :=
intro `_
/-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction. -/
meta def intros : tactic (list expr) :=
do t ← target,
match t with
| expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| _ := return []
end
/-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/
meta def intro_lst (ns : list name) : tactic (list expr) :=
ns.mmap intro
/--
A variant of `intro_lst` which makes sure that the introduced hypotheses' names
are unique in the context. See `intro_fresh`.
-/
meta def intro_lst_fresh (ns : list name) : tactic (list expr) :=
ns.mmap intro_fresh
/-- Introduces new hypotheses with forward dependencies. -/
meta def intros_dep : tactic (list expr) :=
do t ← target,
let proc (b : expr) :=
if b.has_var_idx 0 then
do h ← intro1, hs ← intros_dep, return (h::hs)
else
-- body doesn't depend on new hypothesis
return [],
match t with
| expr.pi _ _ _ b := proc b
| expr.elet _ _ _ b := proc b
| _ := return []
end
meta def introv : list name → tactic (list expr)
| [] := intros_dep
| (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs')
/--
`intron' n` introduces `n` hypotheses and returns the resulting local
constants. Fails if there are not at least `n` arguments to introduce. If you do
not need the return value, use `intron`.
-/
meta def intron' (n : ℕ) : tactic (list expr)
:= iterate_exactly n intro1
/--
Like `intron'` but the introduced hypotheses' names are derived from `base`,
i.e. `base`, `base_1` etc. The new names are unique in the context. If `offset`
is given, the new names will be `base_offset`, `base_offset+1` etc.
-/
meta def intron_base (n : ℕ) (base : name) (offset : option nat := none)
: tactic (list expr)
:= iterate_exactly n (intro_fresh base offset)
/--
`intron_with i ns base offset` introduces `i` hypotheses using the names from
`ns`. If `ns` contains less than `i` names, the remaining hypotheses' names are
derived from `base` and `offset` (as with `intron_base`). If `base` is `_`, the
names are derived from the Π binder names.
Returns the introduced local constants and the remaining names from `ns` (if
`ns` contains more than `i` names).
-/
meta def intron_with
: ℕ → list name → opt_param name `_ → opt_param (option ℕ) none
→ tactic (list expr × list name)
| 0 ns _ _ := pure ([], ns)
| (i + 1) [] base offset := do
hs ← intron_base (i + 1) base offset,
pure (hs, [])
| (i + 1) (n :: ns) base offset := do
h ← intro n,
⟨hs, rest⟩ ← intron_with i ns base offset,
pure (h :: hs, rest)
/-- Returns n fully qualified if it refers to a constant, or else fails. -/
meta def resolve_constant (n : name) : tactic name :=
do e ← resolve_name n,
match e with
| expr.const n _ := pure n
| _ := do
e ← to_expr e tt ff,
expr.const n _ ← pure $ e.get_app_fn,
pure n
end
meta def to_expr_strict (q : pexpr) : tactic expr :=
to_expr q
/--
Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`.
-/
meta def revert (l : expr) : tactic nat :=
revert_lst [l]
/- Revert "all" hypotheses. Actually, the tactic only reverts
hypotheses occurring after the last frozen local instance.
Recall that frozen local instances cannot be reverted,
use `unfreezing revert_all` instead. -/
meta def revert_all : tactic nat :=
do lctx ← local_context,
lis ← frozen_local_instances,
match lis with
| none := revert_lst lctx
| some [] := revert_lst lctx
/- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/
| some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) []
end
meta def clear_lst : list name → tactic unit
| [] := skip
| (n::ns) := do H ← get_local n, clear H, clear_lst ns
meta def match_not (e : expr) : tactic expr :=
match (expr.is_not e) with
| (some a) := return a
| none := fail "expression is not a negation"
end
meta def match_and (e : expr) : tactic (expr × expr) :=
match (expr.is_and e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a conjunction"
end
meta def match_or (e : expr) : tactic (expr × expr) :=
match (expr.is_or e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a disjunction"
end
meta def match_iff (e : expr) : tactic (expr × expr) :=
match (expr.is_iff e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an iff"
end
meta def match_eq (e : expr) : tactic (expr × expr) :=
match (expr.is_eq e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an equality"
end
meta def match_ne (e : expr) : tactic (expr × expr) :=
match (expr.is_ne e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not a disequality"
end
meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) :=
do match (expr.is_heq e) with
| (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs)
| none := fail "expression is not a heterogeneous equality"
end
meta def match_refl_app (e : expr) : tactic (name × expr × expr) :=
do env ← get_env,
match (environment.is_refl_app env e) with
| (some (R, lhs, rhs)) := return (R, lhs, rhs)
| none := fail "expression is not an application of a reflexive relation"
end
meta def match_app_of (e : expr) (n : name) : tactic (list expr) :=
guard (expr.is_app_of e n) >> return e.get_app_args
meta def get_local_type (n : name) : tactic expr :=
get_local n >>= infer_type
meta def trace_result : tactic unit :=
format_result >>= trace
meta def rexact (e : expr) : tactic unit :=
exact e reducible
meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α
| [] := failed
| (h :: hs) := f h <|> any_hyp_aux hs
meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α :=
local_context >>= any_hyp_aux f
/-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/
meta def find_same_type : expr → list expr → tactic expr
| e [] := failed
| e (H :: Hs) :=
do t ← infer_type H,
(unify e t >> return H) <|> find_same_type e Hs
meta def find_assumption (e : expr) : tactic expr :=
do ctx ← local_context, find_same_type e ctx
meta def assumption : tactic unit :=
do { ctx ← local_context,
t ← target,
H ← find_same_type t ctx,
exact H }
<|> fail "assumption tactic failed"
meta def save_info (p : pos) : tactic unit :=
do s ← read,
tactic.save_info_thunk p (λ _, tactic_state.to_format s)
notation `‹` p `›` := (by assumption : p)
/-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/
meta def swap : tactic unit :=
do gs ← get_goals,
match gs with
| (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs)
| e := skip
end
/-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/
meta def assert (h : name) (t : expr) : tactic expr :=
do assert_core h t, swap, e ← intro h, swap, return e
/-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/
meta def assertv (h : name) (t : expr) (v : expr) : tactic expr :=
assertv_core h t v >> intro h
/-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/
meta def define (h : name) (t : expr) : tactic expr :=
do define_core h t, swap, e ← intro h, swap, return e
/-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/
meta def definev (h : name) (t : expr) (v : expr) : tactic expr :=
definev_core h t v >> intro h
/-- Add `h : t := pr` to the current goal -/
meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, definev h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Add `h : t` to the current goal, given a proof `pr : t` -/
meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, assertv h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Return the number of goals that need to be solved -/
meta def num_goals : tactic nat :=
do gs ← get_goals,
return (length gs)
/-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times.
[NOTE] We have to provide the instance argument `[has_mod nat]` because
mod for nat was not defined yet -/
meta def rotate_right (n : nat) [has_mod nat] : tactic unit :=
do ng ← num_goals,
if ng = 0 then skip
else rotate_left (ng - n % ng)
/-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/
meta def rotate : nat → tactic unit :=
rotate_left
private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit
| [] r := set_goals r.reverse
| (g::gs) r := do
ok ← try_core (set_goals [g] >> t),
match ok with
| none := repeat_aux gs (g::r)
| _ := do
gs' ← get_goals,
repeat_aux (gs' ++ gs) r
end
/-- This tactic is applied to each goal. If the application succeeds,
the tactic is applied recursively to all the generated subgoals until it eventually fails.
The recursion stops in a subgoal when the tactic has failed to make progress.
The tactic `repeat` never fails. -/
meta def repeat (t : tactic unit) : tactic unit :=
do gs ← get_goals, repeat_aux t gs []
/-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail.
The tactic fails if all t_i's fail. -/
meta def first {α : Type u} : list (tactic α) → tactic α
| [] := fail "first tactic failed, no more alternatives"
| (t::ts) := t <|> first ts
/-- Applies the given tactic to the main goal and fails if it is not solved. -/
meta def solve1 {α} (tac : tactic α) : tactic α :=
do gs ← get_goals,
match gs with
| [] := fail "solve1 tactic failed, there isn't any goal left to focus"
| (g::rs) :=
do set_goals [g],
a ← tac,
gs' ← get_goals,
match gs' with
| [] := set_goals rs >> pure a
| gs := fail "solve1 tactic failed, focused goal has not been solved"
end
end
/-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/
meta def solve {α} (ts : list (tactic α)) : tactic α :=
first $ map solve1 ts
private meta def focus_aux {α} : list (tactic α) → list expr → list expr → tactic (list α)
| [] [] rs := set_goals rs *> pure []
| (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals"
| tts (g::gs) rs :=
mcond (is_assigned g) (focus_aux tts gs rs) $
do set_goals [g],
t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics",
a ← t,
rs' ← get_goals,
as ← focus_aux ts gs (rs ++ rs'),
pure $ a :: as
/--
`focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of
goals is not n. Returns the results of t_i (one per goal).
-/
meta def focus {α} (ts : list (tactic α)) : tactic (list α) :=
do gs ← get_goals, focus_aux ts gs []
private meta def focus'_aux : list (tactic unit) → list expr → list expr → tactic unit
| [] [] rs := set_goals rs
| (t::ts) [] rs := fail "focus' tactic failed, insufficient number of goals"
| tts (g::gs) rs :=
mcond (is_assigned g) (focus'_aux tts gs rs) $
do set_goals [g],
t::ts ← pure tts | fail "focus' tactic failed, insufficient number of tactics",
t,
rs' ← get_goals,
focus'_aux ts gs (rs ++ rs')
/-- `focus' [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/
meta def focus' (ts : list (tactic unit)) : tactic unit :=
do gs ← get_goals, focus'_aux ts gs []
meta def focus1 {α} (tac : tactic α) : tactic α :=
do g::gs ← get_goals,
match gs with
| [] := tac
| _ := do
set_goals [g],
a ← tac,
gs' ← get_goals,
set_goals (gs' ++ gs),
return a
end
private meta def all_goals_core {α} (tac : tactic α)
: list expr → list expr → tactic (list α)
| [] ac := set_goals ac *> pure []
| (g :: gs) ac :=
mcond (is_assigned g) (all_goals_core gs ac) $
do set_goals [g],
a ← tac,
new_gs ← get_goals,
as ← all_goals_core gs (ac ++ new_gs),
pure $ a :: as
/--
Apply the given tactic to all goals. Return one result per goal.
-/
meta def all_goals {α} (tac : tactic α) : tactic (list α) :=
do gs ← get_goals,
all_goals_core tac gs []
private meta def all_goals'_core (tac : tactic unit) : list expr → list expr → tactic unit
| [] ac := set_goals ac
| (g :: gs) ac :=
mcond (is_assigned g) (all_goals'_core gs ac) $
do set_goals [g],
tac,
new_gs ← get_goals,
all_goals'_core gs (ac ++ new_gs)
/-- Apply the given tactic to all goals. -/
meta def all_goals' (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
all_goals'_core tac gs []
private meta def any_goals_core {α} (tac : tactic α) : list expr → list expr → bool → tactic (list (option α))
| [] ac progress := guard progress *> set_goals ac *> pure []
| (g :: gs) ac progress :=
mcond (is_assigned g) (any_goals_core gs ac progress) $
do set_goals [g],
res ← try_core tac,
new_gs ← get_goals,
ress ← any_goals_core gs (ac ++ new_gs) (res.is_some || progress),
pure $ res :: ress
/--
Apply `tac` to any goal where it succeeds. The tactic succeeds if `tac`
succeeds for at least one goal. The returned list contains the result of `tac`
for each goal: `some a` if tac succeeded, or `none` if it did not.
-/
meta def any_goals {α} (tac : tactic α) : tactic (list (option α)) :=
do gs ← get_goals,
any_goals_core tac gs [] ff
private meta def any_goals'_core (tac : tactic unit) : list expr → list expr → bool → tactic unit
| [] ac progress := guard progress >> set_goals ac
| (g :: gs) ac progress :=
mcond (is_assigned g) (any_goals'_core gs ac progress) $
do set_goals [g],
succeeded ← try_core tac,
new_gs ← get_goals,
any_goals'_core gs (ac ++ new_gs) (succeeded.is_some || progress)
/-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if
tac succeeds for at least one goal. -/
meta def any_goals' (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
any_goals'_core tac gs [] ff
/--
LCF-style AND_THEN tactic. It applies `tac1` to the main goal, then applies
`tac2` to each goal produced by `tac1`.
-/
meta def seq {α β} (tac1 : tactic α) (tac2 : α → tactic β) : tactic (list β) :=
do g::gs ← get_goals,
set_goals [g],
a ← tac1,
bs ← all_goals $ tac2 a,
gs' ← get_goals,
set_goals (gs' ++ gs),
pure bs
/-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/
meta def seq' (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, all_goals' tac2,
gs' ← get_goals,
set_goals (gs' ++ gs)
/--
Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to
one of the produced subgoals (like `focus'`).
-/
meta def seq_focus {α β} (tac1 : tactic α) (tacs2 : α → list (tactic β)) : tactic (list β) :=
do g::gs ← get_goals,
set_goals [g],
a ← tac1,
bs ← focus $ tacs2 a,
gs' ← get_goals,
set_goals (gs' ++ gs),
pure bs
/--
Applies `tac1` to the main goal, then applies each of the tactics in `tacs2` to
one of the produced subgoals (like `focus`).
-/
meta def seq_focus' (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, focus tacs2,
gs' ← get_goals,
set_goals (gs' ++ gs)
meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) :=
⟨seq'⟩
meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) :=
⟨seq_focus'⟩
meta constant is_trace_enabled_for : name → bool
/-- Execute tac only if option trace.n is set to true. -/
meta def when_tracing (n : name) (tac : tactic unit) : tactic unit :=
when (is_trace_enabled_for n = tt) tac
/-- Fail if there are no remaining goals. -/
meta def fail_if_no_goals : tactic unit :=
do n ← num_goals,
when (n = 0) (fail "tactic failed, there are no goals to be solved")
/-- Fail if there are unsolved goals. -/
meta def done : tactic unit :=
do n ← num_goals,
when (n ≠ 0) (fail "done tactic failed, there are unsolved goals")
meta def apply_opt_param : tactic unit :=
do `(opt_param %%t %%v) ← target,
exact v
meta def apply_auto_param : tactic unit :=
do `(auto_param %%type %%tac_name_expr) ← target,
change type,
tac_name ← eval_expr name tac_name_expr,
tac ← eval_expr (tactic unit) (expr.const tac_name []),
tac
meta def has_opt_auto_param (ms : list expr) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit :=
when (cfg.auto_param || cfg.opt_param) $
mwhen (has_opt_auto_param ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $
set_goals [m] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m.2,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit :=
mwhen (has_opt_auto_param_for_apply ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $
set_goals [m.2] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) :=
do r ← apply_core e cfg,
try_apply_opt_auto_param_for_apply cfg r,
return r
/-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/
meta def fapply (e : expr) : tactic (list (name × expr)) :=
apply e {new_goals := new_goals.all}
/-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/
meta def eapply (e : expr) : tactic (list (name × expr)) :=
apply e {new_goals := new_goals.non_dep_only}
/-- Try to solve the main goal using type class resolution. -/
meta def apply_instance : tactic unit :=
do tgt ← target >>= instantiate_mvars,
b ← is_class tgt,
if b then mk_instance tgt >>= exact
else fail "apply_instance tactic fail, target is not a type class"
/-- Create a list of universe meta-variables of the given size. -/
meta def mk_num_meta_univs : nat → tactic (list level)
| 0 := return []
| (succ n) := do
l ← mk_meta_univ,
ls ← mk_num_meta_univs n,
return (l::ls)
/-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/
meta def mk_const (c : name) : tactic expr :=
do env ← get_env,
decl ← env.get c,
let num := decl.univ_params.length,
ls ← mk_num_meta_univs num,
return (expr.const c ls)
/-- Apply the constant `c` -/
meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit :=
do c ← mk_const c, apply c cfg, skip
meta def eapplyc (c : name) : tactic unit :=
do c ← mk_const c, eapply c, skip
meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit :=
try (do c ← mk_const n, save_type_info c ref)
/-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`,
and return metavariable `?M : ?T`.
This action can be used to create a meta-variable when
we don't know its type at creation time -/
meta def mk_mvar : tactic expr :=
do u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
mk_meta_var t
/-- Makes a sorry macro with a meta-variable as its type. -/
meta def mk_sorry : tactic expr := do
u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
return $ expr.mk_sorry t
/-- Closes the main goal using sorry. -/
meta def admit : tactic unit :=
target >>= exact ∘ expr.mk_sorry
meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do
uniq_name ← mk_fresh_name,
return $ expr.local_const uniq_name pp_name bi type
meta def mk_local_def (pp_name : name) (type : expr) : tactic expr :=
mk_local' pp_name binder_info.default type
meta def mk_local_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
private meta def get_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_pi_arity_aux new_b,
return (r + 1)
| e := return 0
/-- Compute the arity of the given (Pi-)type -/
meta def get_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_pi_arity_aux
/-- Compute the arity of the given function -/
meta def get_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_pi_arity
meta def triv : tactic unit := mk_const `trivial >>= exact
notation `dec_trivial` := of_as_true (by tactic.triv)
meta def by_contradiction (H : name) : tactic expr :=
do tgt ← target,
tgt_wh ← whnf tgt reducible, -- to ensure that `not` in `ne` is found
(match_not tgt_wh $> ()) <|>
(mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|>
(mk_mapp `classical.by_contradiction [some tgt] >>= eapply >> skip) <|>
fail "tactic by_contradiction failed, target is not a proposition",
intro H
private meta def generalizes_aux (md : transparency) : list expr → tactic unit
| [] := skip
| (e::es) := generalize e `x md >> generalizes_aux es
meta def generalizes (es : list expr) (md := semireducible) : tactic unit :=
generalizes_aux md es
private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr)
| [] r := return r
| (h::hs) r :=
do type ← infer_type h,
d ← kdepends_on type e md,
if d then kdependencies_core hs (h::r)
else kdependencies_core hs r
/-- Return all hypotheses that depends on `e`
The dependency test is performed using `kdepends_on` with the given transparency setting. -/
meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) :=
do ctx ← local_context, kdependencies_core e md ctx []
/-- Revert all hypotheses that depend on `e` -/
meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat :=
kdependencies e md >>= revert_lst
meta def revert_kdeps (e : expr) (md := reducible) :=
revert_kdependencies e md
/-- Postprocess the output of `cases_core`:
- The third component of each tuple in the input list (the list of
substitutions) is dropped since we don't use it anywhere.
- The second component (the list of new hypotheses) is filtered: any expression
that is not a local constant is dropped. We only use the new hypotheses for
the renaming functionality of `case`, so we want to keep only those
"new hypotheses" that are, in fact, local constants. -/
private meta def cases_postprocess (hs : list (name × list expr × list (name × expr)))
: list (name × list expr) :=
hs.map $ λ ⟨n, hs, _⟩, (n, hs.filter (λ h, h.is_local_constant))
/-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis.
Remark, it reverts dependencies using `revert_kdeps`.
Two different transparency modes are used `md` and `dmd`.
The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`.
It returns the constructor names associated with each new goal and the newly
introduced hypotheses. Note that while `cases_core` may return "new
hypotheses" that are not local constants, this tactic only returns local
constants.
-/
meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list (name × list expr)) :=
if e.is_local_constant then
do r ← cases_core e ids md, return $ cases_postprocess r
else do
n ← revert_kdependencies e dmd,
x ← get_unused_name,
(tactic.generalize e x dmd)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
return ()),
h ← tactic.intro1,
focus1 $ do
r ← cases_core h ids md,
hs' ← all_goals (intron' n),
return $ cases_postprocess $ r.map₂ (λ ⟨n, hs, x⟩ hs', (n, hs ++ hs', x)) hs'
/-- The same as `exact` except you can add proof holes. -/
meta def refine (e : pexpr) : tactic unit :=
do tgt : expr ← target,
to_expr ``(%%e : %%tgt) tt >>= exact
/--
`by_cases p h` splits the main goal into two cases, assuming `h : p` in the
first branch, and `h : ¬ p` in the second branch. The expression `p` needs to
be a proposition.
The produced proof term is `dite p ?m_1 ?m_2`.
-/
meta def by_cases (e : expr) (h : name) : tactic unit := do
dec_e ← mk_app ``decidable [e] <|> fail "by_cases tactic failed, type is not a proposition",
inst ← mk_instance dec_e <|> pure `(classical.prop_decidable %%e),
tgt ← target,
expr.sort tgt_u ← infer_type tgt >>= whnf,
g1 ← mk_meta_var (e.imp tgt),
g2 ← mk_meta_var (`(¬ %%e).imp tgt),
focus1 $ do
exact $ expr.const ``dite [tgt_u] tgt e inst g1 g2,
set_goals [g1, g2],
all_goals' $ intro h >> skip
meta def funext_core : list name → bool → tactic unit
| [] tt := return ()
| ids only_ids := try $
do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf),
applyc `funext,
id ← if ids.empty ∨ ids.head = `_ then do
(expr.lam n _ _ _) ← whnf lhs
| pure `_,
return n
else return ids.head,
intro id,
funext_core ids.tail only_ids
meta def funext : tactic unit :=
funext_core [] ff
meta def funext_lst (ids : list name) : tactic unit :=
funext_core ids tt
private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i :=
let n := base <.> ("_aux_" ++ repr i) in
if ¬env.contains n then n
else get_undeclared_const (i+1)
meta def new_aux_decl_name : tactic name := do
env ← get_env, n ← decl_name,
return $ get_undeclared_const env n 1
private meta def mk_aux_decl_name : option name → tactic name
| none := new_aux_decl_name
| (some suffix) := do p ← decl_name, return $ p ++ suffix
meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit :=
do fail_if_no_goals,
gs ← get_goals,
type ← if zeta_reduce then target >>= zeta else target,
is_lemma ← is_prop type,
m ← mk_meta_var type,
set_goals [m],
tac,
n ← num_goals,
when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"),
set_goals gs,
val ← instantiate_mvars m,
val ← if zeta_reduce then zeta val else return val,
c ← mk_aux_decl_name suffix,
e ← add_aux_decl c type val is_lemma,
exact e
/-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/
meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) :=
do m ← mk_meta_var type,
gs ← get_goals,
set_goals [m],
a ← tac,
set_goals gs,
return (a, m)
/-- Return tt iff 'd' is a declaration in one of the current open namespaces -/
meta def in_open_namespaces (d : name) : tactic bool :=
do ns ← open_namespaces,
env ← get_env,
return $ ns.any (λ n, n.is_prefix_of d) && env.contains d
/-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of
memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting
long running tactics. -/
meta def try_for {α} (max : nat) (tac : tactic α) : tactic α :=
λ s,
match _root_.try_for max (tac s) with
| some r := r
| none := mk_exception "try_for tactic failed, timeout" none s
end
/-- Execute `tac` for `max` milliseconds. Useful due to variance
in the number of heartbeats taken by various tactics. -/
meta def try_for_time {α} (max : nat) (tac : tactic α) : tactic α :=
λ s,
match _root_.try_for_time max (tac s) with
| some r := r
| none := mk_exception "try_for_time tactic failed, timeout" none s
end
meta def updateex_env (f : environment → exceptional environment) : tactic unit :=
do env ← get_env,
env ← returnex $ f env,
set_env env
/- Add a new inductive datatype to the environment
name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/
meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr))
(is_meta : bool := ff) : tactic unit :=
updateex_env $ λe, e.add_inductive n ls p ty is is_meta
meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit :=
add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff)
/-- add declaration `d` as a protected declaration -/
meta def add_protected_decl (d : declaration) : tactic unit :=
updateex_env $ λ e, e.add_protected d
/-- check if `n` is the name of a protected declaration -/
meta def is_protected_decl (n : name) : tactic bool :=
do env ← get_env,
return $ env.is_protected n
/-- `add_defn_equations` adds a definition specified by a list of equations.
The arguments:
* `lp`: list of universe parameters
* `params`: list of parameters (binders before the colon);
* `fn`: a local constant giving the name and type of the declaration
(with `params` in the local context);
* `eqns`: a list of equations, each of which is a list of patterns
(constructors applied to new local constants) and the branch
expression;
* `is_meta`: is the definition meta?
`add_defn_equations` can be used as:
do my_add ← mk_local_def `my_add `(ℕ → ℕ),
a ← mk_local_def `a ℕ,
b ← mk_local_def `b ℕ,
add_defn_equations [a] my_add
[ ([``(nat.zero)], a),
([``(nat.succ %%b)], my_add b) ])
ff -- non-meta
to create the following definition:
def my_add (a : ℕ) : ℕ → ℕ
| nat.zero := a
| (nat.succ b) := my_add b
-/
meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr)
(eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit :=
do opt ← get_options,
updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta
/-- Get the revertible part of the local context. These are the hypotheses that
appear after the last frozen local instance in the local context. We call them
revertible because `revert` can revert them, unlike those hypotheses which occur
before a frozen instance. -/
meta def revertible_local_context : tactic (list expr) :=
do ctx ← local_context,
frozen ← frozen_local_instances,
pure $
match frozen with
| none := ctx
| some [] := ctx
| some (h :: _) := ctx.after (eq h)
end
/--
Rename local hypotheses according to the given `name_map`. The `name_map`
contains as keys those hypotheses that should be renamed; the associated values
are the new names.
This tactic can only rename hypotheses which occur after the last frozen local
instance. If you need to rename earlier hypotheses, try
`unfreezing (rename_many ...)`.
If `strict` is true, we fail if `name_map` refers to hypotheses that do not
appear in the local context or that appear before a frozen local instance.
Conversely, if `strict` is false, some entries of `name_map` may be silently
ignored.
If `use_unique_names` is true, the keys of `name_map` should be the unique names
of hypotheses to be renamed. Otherwise, the keys should be display names.
Note that we allow shadowing, so renamed hypotheses may have the same name
as other hypotheses in the context. If `use_unique_names` is false and there are
multiple hypotheses with the same display name in the context, they are all
renamed.
-/
meta def rename_many (renames : name_map name) (strict := tt) (use_unique_names := ff)
: tactic unit :=
do let hyp_name : expr → name :=
if use_unique_names then expr.local_uniq_name else expr.local_pp_name,
ctx ← revertible_local_context,
-- The part of the context after (but including) the first hypthesis that
-- must be renamed.
let ctx_suffix := ctx.drop_while (λ h, (renames.find $ hyp_name h).is_none),
when strict $ do {
let ctx_names := rb_map.set_of_list (ctx_suffix.map hyp_name),
let invalid_renames :=
(renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h),
when ¬ invalid_renames.empty $ fail $ format.join
[ "Cannot rename these hypotheses:\n"
, format.join $ (invalid_renames.map to_fmt).intersperse ", "
, format.line
, "This is because these hypotheses either do not occur in the\n"
, "context or they occur before a frozen local instance.\n"
, "In the latter case, try `unfreezingI { ... }`."
]
},
-- The new names for all hypotheses in ctx_suffix.
let new_names :=
ctx_suffix.map $ λ h,
(renames.find $ hyp_name h).get_or_else h.local_pp_name,
revert_lst ctx_suffix,
intro_lst new_names,
pure ()
/--
Rename a local hypothesis. This is a special case of `rename_many`;
see there for caveats.
-/
meta def rename (curr : name) (new : name) : tactic unit :=
rename_many (rb_map.of_list [⟨curr, new⟩])
/--
Rename a local hypothesis. Unlike `rename` and `rename_many`, this tactic does
not preserve the order of hypotheses. Its implementation is simpler (and
therefore probably faster) than that of `rename`.
-/
meta def rename_unstable (curr : name) (new : name) : tactic unit :=
do h ← get_local curr,
n ← revert h,
intro new,
intron (n - 1)
/--
"Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof
that (type = new_type). The tactic actually creates a new hypothesis
with the same user facing name, and (tries to) clear `h`.
The `clear` step fails if `h` has forward dependencies. In this case, the old `h`
will remain in the local context. The tactic returns the new hypothesis. -/
meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) (tag : name := `unit.star) : tactic expr :=
do h_type ← infer_type h,
new_h ← assert h.local_pp_name new_type,
eq_pr_type ← mk_app `eq [h_type, new_type],
let eq_pr := mk_tagged_proof eq_pr_type eq_pr tag,
mk_eq_mp eq_pr h >>= exact,
try $ clear h,
return new_h
meta def main_goal : tactic expr :=
do g::gs ← get_goals, return g
/- Goal tagging support -/
meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α :=
do old ← tags_enabled,
enable_tags b,
r ← t,
enable_tags old,
return r
meta def get_main_tag : tactic tag :=
main_goal >>= get_tag
meta def set_main_tag (t : tag) : tactic unit :=
do g ← main_goal, set_tag g t
meta def subst (h : expr) : tactic unit :=
(do guard h.is_local_constant,
some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h,
is_def_eq α β,
new_h_type ← mk_app `eq [lhs, rhs],
new_h_pr ← mk_app `eq_of_heq [h],
new_h ← assertv h.local_pp_name new_h_type new_h_pr,
try (clear h),
subst_core new_h)
<|> subst_core h
end tactic
notation [parsing_only] `command`:max := tactic unit
open tactic
namespace list
meta def for_each {α} : list α → (α → tactic unit) → tactic unit
| [] fn := skip
| (e::es) fn := do fn e, for_each es fn
meta def any_of {α β} : list α → (α → tactic β) → tactic β
| [] fn := failed
| (e::es) fn := do opt_b ← try_core (fn e),
match opt_b with
| some b := return b
| none := any_of es fn
end
end list
/- Install monad laws tactic and use it to prove some instances. -/
/-- Try to prove with `iff.refl`.-/
meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact
meta def monad_from_pure_bind {m : Type u → Type v}
(pure : Π {α : Type u}, α → m α)
(bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m :=
{pure := @pure, bind := @bind}
meta instance : monad task :=
{map := @task.map, bind := @task.bind, pure := @task.pure}
namespace tactic
meta def replace_target (new_target : expr) (pr : expr) (tag : name := `unit.star) : tactic unit :=
do t ← target,
assert `htarget new_target, swap,
ht ← get_local `htarget,
pr_type ← mk_app `eq [t, new_target],
let locked_pr := mk_tagged_proof pr_type pr tag,
mk_eq_mpr locked_pr ht >>= exact
meta def eval_pexpr (α) [reflected _ α] (e : pexpr) : tactic α :=
to_expr ``(%%e : %%(reflect α)) ff ff >>= eval_expr α
meta def run_simple {α} : tactic_state → tactic α → option α
| ts t := match t ts with
| (interaction_monad.result.success a ts') := some a
| (interaction_monad.result.exception _ _ _) := none
end
end tactic
|
c587f3de5c2300278eb85564999f73f79baab9d9 | 649957717d58c43b5d8d200da34bf374293fe739 | /src/category_theory/limits/shapes/pullbacks.lean | 4c4ceed09c28ee60ca08ebe4af183db36e3d754f | [
"Apache-2.0"
] | permissive | Vtec234/mathlib | b50c7b21edea438df7497e5ed6a45f61527f0370 | fb1848bbbfce46152f58e219dc0712f3289d2b20 | refs/heads/master | 1,592,463,095,113 | 1,562,737,749,000 | 1,562,737,749,000 | 196,202,858 | 0 | 0 | Apache-2.0 | 1,562,762,338,000 | 1,562,762,337,000 | null | UTF-8 | Lean | false | false | 7,545 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.eq_to_hom
import category_theory.limits.cones
import category_theory.sparse
open category_theory
namespace category_theory.limits
universes v u
local attribute [tidy] tactic.case_bash
@[derive decidable_eq] inductive walking_cospan : Type v
| left | right | one
@[derive decidable_eq] inductive walking_span : Type v
| zero | left | right
namespace walking_cospan
inductive hom : walking_cospan → walking_cospan → Type v
| inl : hom left one
| inr : hom right one
| id : Π X : walking_cospan.{v}, hom X X
open hom
def hom.comp : Π (X Y Z : walking_cospan) (f : hom X Y) (g : hom Y Z), hom X Z
| _ _ _ (id _) h := h
| _ _ _ inl (id one) := inl
| _ _ _ inr (id one) := inr
.
instance category_struct : category_struct walking_cospan :=
{ hom := hom,
id := hom.id,
comp := hom.comp, }
instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy
-- We make this a @[simp] lemma later; if we do it now there's a mysterious
-- failure in `cospan`, below.
lemma hom_id (X : walking_cospan.{v}) : hom.id X = 𝟙 X := rfl
instance : small_category.{v} walking_cospan.{v} := sparse_category
end walking_cospan
namespace walking_span
inductive hom : walking_span → walking_span → Type v
| fst : hom zero left
| snd : hom zero right
| id : Π X : walking_span.{v}, hom X X
open hom
def hom.comp : Π (X Y Z : walking_span) (f : hom X Y) (g : hom Y Z), hom X Z
| _ _ _ (id _) h := h
| _ _ _ fst (id left) := fst
| _ _ _ snd (id right) := snd
.
instance category_struct : category_struct walking_span :=
{ hom := hom,
id := hom.id,
comp := hom.comp }
instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy
-- We make this a @[simp] lemma later; if we do it now there's a mysterious
-- failure in `span`, below.
lemma hom_id (X : walking_span.{v}) : hom.id X = 𝟙 X := rfl
instance : small_category.{v} walking_span.{v} := sparse_category
end walking_span
open walking_span walking_cospan walking_span.hom walking_cospan.hom
variables {C : Type u} [𝒞 : category.{v+1} C]
include 𝒞
def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan.{v} ⥤ C :=
{ obj := λ x, match x with
| left := X
| right := Y
| one := Z
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, inl := f
| _, _, inr := g
end }
def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span.{v} ⥤ C :=
{ obj := λ x, match x with
| zero := X
| left := Y
| right := Z
end,
map := λ x y h, match x, y, h with
| _, _, (id _) := 𝟙 _
| _, _, fst := f
| _, _, snd := g
end }
@[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).obj walking_cospan.left = X := rfl
@[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).obj walking_span.left = Y := rfl
@[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).obj walking_cospan.right = Y := rfl
@[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).obj walking_span.right = Z := rfl
@[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).obj walking_cospan.one = Z := rfl
@[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).obj walking_span.zero = X := rfl
@[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).map walking_cospan.hom.inl = f := rfl
@[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).map walking_span.hom.fst = f := rfl
@[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).map walking_cospan.hom.inr = g := rfl
@[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).map walking_span.hom.snd = g := rfl
@[simp] lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) :
(cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl
@[simp] lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) :
(span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl
variables {X Y Z : C}
attribute [simp] walking_cospan.hom_id walking_span.hom_id
abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g)
namespace pullback_cone
variables {f : X ⟶ Z} {g : Y ⟶ Z}
def π₁ (t : pullback_cone f g) : t.X ⟶ X := t.π.app left
def π₂ (t : pullback_cone f g) : t.X ⟶ Y := t.π.app right
def mk {W : C} (π₁ : W ⟶ X) (π₂ : W ⟶ Y) (eq : π₁ ≫ f = π₂ ≫ g) : pullback_cone f g :=
{ X := W,
π :=
{ app := λ j, walking_cospan.cases_on j π₁ π₂ (π₁ ≫ f),
naturality' := λ j j' f, by cases f; obviously } }
lemma condition (t : pullback_cone f g) : (π₁ t) ≫ f = (π₂ t) ≫ g :=
begin
erw [t.w inl, ← t.w inr], refl
end
end pullback_cone
abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g)
namespace pushout_cocone
variables {f : X ⟶ Y} {g : X ⟶ Z}
def ι₁ (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app left
def ι₂ (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app right
def mk {W : C} (ι₁ : Y ⟶ W) (ι₂ : Z ⟶ W) (eq : f ≫ ι₁ = g ≫ ι₂) : pushout_cocone f g :=
{ X := W,
ι :=
{ app := λ j, walking_span.cases_on j (f ≫ ι₁) ι₁ ι₂,
naturality' := λ j j' f, by cases f; obviously } }
lemma condition (t : pushout_cocone f g) : f ≫ (ι₁ t) = g ≫ (ι₂ t) :=
begin
erw [t.w fst, ← t.w snd], refl
end
end pushout_cocone
def cone.of_pullback_cone
{F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F :=
{ X := t.X,
π :=
{ app := λ X, t.π.app X ≫ eq_to_hom (by tidy),
naturality' := λ j j' g,
begin
cases j; cases j'; cases g; dsimp; simp,
erw ← t.w inl, refl,
erw ← t.w inr, refl,
end } }.
@[simp] lemma cone.of_pullback_cone_π
{F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) (j) :
(cone.of_pullback_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
def cocone.of_pushout_cocone
{F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F :=
{ X := t.X,
ι :=
{ app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X,
naturality' := λ j j' g,
begin
cases j; cases j'; cases g; dsimp; simp,
erw ← t.w fst, refl,
erw ← t.w snd, refl,
end } }.
@[simp] lemma cocone.of_pushout_cocone_ι
{F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) (j) :
(cocone.of_pushout_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
def pullback_cone.of_cone
{F : walking_cospan.{v} ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) :=
{ X := t.X,
π := { app := λ j, t.π.app j ≫ eq_to_hom (by tidy) } }
@[simp] lemma pullback_cone.of_cone_π {F : walking_cospan.{v} ⥤ C} (t : cone F) (j) :
(pullback_cone.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl
def pushout_cocone.of_cocone
{F : walking_span.{v} ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) :=
{ X := t.X,
ι := { app := λ j, eq_to_hom (by tidy) ≫ t.ι.app j } }
@[simp] lemma pushout_cocone.of_cocone_ι {F : walking_span.{v} ⥤ C} (t : cocone F) (j) :
(pushout_cocone.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl
end category_theory.limits
|
b4f0a209d184d8f410def6a6388f45c5eb5240c9 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/analysis/convex/integral.lean | 68afe11f98183c394ad53b9d1e7b7daae2a86307 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 7,017 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import analysis.convex.basic
import measure_theory.set_integral
/-!
# Jensen's inequality for integrals
In this file we prove four theorems:
* `convex.smul_integral_mem`: if `μ` is a non-zero finite measure on `α`, `s` is a convex closed set
in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value
of `f` belongs to `s`: `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem`
for a finite sum version of this lemma.
* `convex.integral_mem`: if `μ` is a probability measure on `α`, `s` is a convex closed set in `E`,
and `f` is an integrable function sending `μ`-a.e. points to `s`, then the expected value of `f`
belongs to `s`: `∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this
lemma.
* `convex_on.map_smul_integral_le`: Jensen's inequality: if a function `g : E → ℝ` is convex and
continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is
a function sending `μ`-a.e. points to `s`, then the value of `g` at the average value of `f` is
less than or equal to the average value of `g ∘ f` provided that both `f` and `g ∘ f` are
integrable. See also `convex.map_center_mass_le` for a finite sum version of this lemma.
* `convex_on.map_integral_le`: Jensen's inequality: if a function `g : E → ℝ` is convex and
continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a
function sending `μ`-a.e. points to `s`, then the value of `g` at the expected value of `f` is
less than or equal to the expected value of `g ∘ f` provided that both `f` and `g ∘ f` are
integrable. See also `convex.map_sum_le` for a finite sum version of this lemma.
## Tags
convex, integral, center mass, Jensen's inequality
-/
open measure_theory set filter
open_locale topological_space big_operators
variables {α E : Type*} [measurable_space α] {μ : measure α}
[normed_group E] [normed_space ℝ E] [complete_space E]
[topological_space.second_countable_topology E] [measurable_space E] [borel_space E]
/-- If `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an
integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`:
`(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version
of this lemma. -/
lemma convex.smul_integral_mem [finite_measure μ] {s : set E} (hs : convex s) (hsc : is_closed s)
(hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) :
(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s :=
begin
rcases eq_empty_or_nonempty s with rfl|⟨y₀, h₀⟩, { refine (hμ _).elim, simpa using hfs },
rw ← hsc.closure_eq at hfs,
have hc : integrable (λ _, y₀) μ := integrable_const _,
set F : ℕ → simple_func α E := simple_func.approx_on f hfi.measurable s y₀ h₀,
have : tendsto (λ n, (F n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ),
{ simp only [simple_func.integral_eq_integral _ (simple_func.integrable_approx_on hfi h₀ hc _)],
exact tendsto_integral_of_l1 _ hfi
(eventually_of_forall $ simple_func.integrable_approx_on hfi h₀ hc)
(simple_func.tendsto_approx_on_l1_edist hfi.1 h₀ hfs (hfi.sub hc).2) },
refine hsc.mem_of_tendsto (tendsto_const_nhds.smul this) (eventually_of_forall $ λ n, _),
have : ∑ y in (F n).range, (μ ((F n) ⁻¹' {y})).to_real = (μ univ).to_real,
by rw [← (F n).sum_range_measure_preimage_singleton, @ennreal.to_real_sum _ _
(λ y, μ ((F n) ⁻¹' {y})) (λ _ _, (measure_lt_top _ _))],
rw [← this, simple_func.integral],
refine hs.center_mass_mem (λ _ _, ennreal.to_real_nonneg) _ _,
{ rw [this, ennreal.to_real_pos_iff, zero_lt_iff_ne_zero, ne.def, measure.measure_univ_eq_zero],
exact ⟨hμ, measure_ne_top _ _⟩ },
{ simp only [simple_func.mem_range],
rintros _ ⟨x, rfl⟩,
exact simple_func.approx_on_mem hfi.1 h₀ n x }
end
/-- If `μ` is a probability measure on `α`, `s` is a convex closed set in `E`, and `f` is an
integrable function sending `μ`-a.e. points to `s`, then the expected value of `f` belongs to `s`:
`∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this lemma. -/
lemma convex.integral_mem [probability_measure μ] {s : set E} (hs : convex s) (hsc : is_closed s)
{f : α → E} (hf : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) :
∫ x, f x ∂μ ∈ s :=
by simpa [measure_univ] using hs.smul_integral_mem hsc (probability_measure.ne_zero μ) hf hfi
/-- Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set
`s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points
to `s`, then the value of `g` at the average value of `f` is less than or equal to the average value
of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_center_mass_le`
for a finite sum version of this lemma. -/
lemma convex_on.map_smul_integral_le [finite_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on s g)
(hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s)
(hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) :
g ((μ univ).to_real⁻¹ • ∫ x, f x ∂μ) ≤ (μ univ).to_real⁻¹ • ∫ x, g (f x) ∂μ :=
begin
set t := {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2},
have ht_conv : convex t := hg.convex_epigraph,
have ht_closed : is_closed t :=
(hsc.preimage continuous_fst).is_closed_le (hgc.comp continuous_on_fst (subset.refl _))
continuous_on_snd,
have ht_mem : ∀ᵐ x ∂μ, (f x, g (f x)) ∈ t := hfs.mono (λ x hx, ⟨hx, le_rfl⟩),
simpa [integral_pair hfi hgi]
using (ht_conv.smul_integral_mem ht_closed hμ ht_mem (hfi.prod_mk hgi)).2
end
/-- Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set
`s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to
`s`, then the value of `g` at the expected value of `f` is less than or equal to the expected value
of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_sum_le` for a
finite sum version of this lemma. -/
lemma convex_on.map_integral_le [probability_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on s g)
(hgc : continuous_on g s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s)
(hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) :
g (∫ x, f x ∂μ) ≤ ∫ x, g (f x) ∂μ :=
by simpa [measure_univ]
using hg.map_smul_integral_le hgc hsc (probability_measure.ne_zero μ) hfs hfi hgi
|
9e8bd5e8eb925da4a428f1b1714a43c64df7407a | 0dbd5f7001f62ee8d54ed48bada66bfeaf55e550 | /src/ent/xor.lean | 2cbdc6757068815202a02eb5ab8c6722fd902e02 | [] | no_license | rwbarton/lean-elementary-number-theory | 667203b08501792eef48217759539f6c1e2da25a | fabef0737fd2486e3f24f9e04652db4c182d5425 | refs/heads/master | 1,670,605,651,029 | 1,599,565,470,000 | 1,599,565,470,000 | 293,792,043 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 658 | lean | namespace xor
protected def mk {p q : Prop} : p ∨ q → ¬ (p ∧ q) → xor p q
| (or.inl Hp) Hpq := or.inl ⟨Hp, λ Hq, Hpq ⟨Hp,Hq⟩⟩
| (or.inr Hq) Hpq := or.inr ⟨Hq, λ Hp, Hpq ⟨Hp,Hq⟩⟩
protected def resolve_left {p q : Prop} : xor p q → (¬p ↔ q) := λ x,
iff.intro (λ Hp, (or.resolve_left x (mt and.left Hp)).left)
(λ Hq, (or.resolve_left x (mt and.right (not_not_intro Hq))).right)
protected def resolve_right {p q : Prop} : xor p q → (¬q ↔ p) := λ x,
iff.intro (λ Hq, (or.resolve_right x (mt and.left Hq)).left)
(λ Hp, (or.resolve_right x (mt and.right (not_not_intro Hp))).right)
end xor
|
6a861f51994883a745b58d7ce7acff11bacb47c2 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/sub/with_top.lean | 9068932b60cd79f836dc1ede175e9d35792f564d | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 1,652 | lean | /-
Copyright (c) 2021 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import algebra.order.sub.defs
import algebra.order.monoid.with_top
/-!
# Lemma about subtraction in ordered monoids with a top element adjoined.
-/
variables {α β : Type*}
namespace with_top
section
variables [has_sub α] [has_zero α]
/-- If `α` has subtraction and `0`, we can extend the subtraction to `with_top α`. -/
protected def sub : Π (a b : with_top α), with_top α
| _ ⊤ := 0
| ⊤ (x : α) := ⊤
| (x : α) (y : α) := (x - y : α)
instance : has_sub (with_top α) :=
⟨with_top.sub⟩
@[simp, norm_cast] lemma coe_sub {a b : α} : (↑(a - b) : with_top α) = ↑a - ↑b := rfl
@[simp] lemma top_sub_coe {a : α} : (⊤ : with_top α) - a = ⊤ := rfl
@[simp] lemma sub_top {a : with_top α} : a - ⊤ = 0 := by { cases a; refl }
lemma map_sub [has_sub β] [has_zero β] {f : α → β} (h : ∀ x y, f (x - y) = f x - f y)
(h₀ : f 0 = 0) :
∀ x y : with_top α, (x - y).map f = x.map f - y.map f
| _ ⊤ := by simp only [h₀, sub_top, with_top.map_zero, coe_zero, map_top]
| ⊤ (x : α) := rfl
| (x : α) (y : α) := by simp only [← coe_sub, map_coe, h]
end
variables [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α]
instance : has_ordered_sub (with_top α) :=
begin
constructor,
rintro x y z,
induction y using with_top.rec_top_coe, { simp },
induction x using with_top.rec_top_coe, { simp },
induction z using with_top.rec_top_coe, { simp },
norm_cast, exact tsub_le_iff_right
end
end with_top
|
646d36bd13068c11c4677647a16d5b847d925498 | 3b15c7b0b62d8ada1399c112ad88a529e6bfa115 | /stage0/src/Lean/Expr.lean | e15fb72017e910e8af8a37fdb50cad7e41c16e83 | [
"Apache-2.0"
] | permissive | stephenbrady/lean4 | 74bf5cae8a433e9c815708ce96c9e54a5caf2115 | b1bd3fc304d0f7bc6810ec78bfa4c51476d263f9 | refs/heads/master | 1,692,621,473,161 | 1,634,308,743,000 | 1,634,310,749,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 40,113 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.KVMap
import Lean.Level
namespace Lean
inductive Literal where
| natVal (val : Nat)
| strVal (val : String)
deriving Inhabited, BEq, Repr
protected def Literal.hash : Literal → UInt64
| Literal.natVal v => hash v
| Literal.strVal v => hash v
instance : Hashable Literal := ⟨Literal.hash⟩
def Literal.lt : Literal → Literal → Bool
| Literal.natVal _, Literal.strVal _ => true
| Literal.natVal v₁, Literal.natVal v₂ => v₁ < v₂
| Literal.strVal v₁, Literal.strVal v₂ => v₁ < v₂
| _, _ => false
instance : LT Literal := ⟨fun a b => a.lt b⟩
instance (a b : Literal) : Decidable (a < b) :=
inferInstanceAs (Decidable (a.lt b))
inductive BinderInfo where
| default | implicit | strictImplicit | instImplicit | auxDecl
deriving Inhabited, BEq, Repr
def BinderInfo.hash : BinderInfo → UInt64
| BinderInfo.default => 947
| BinderInfo.implicit => 1019
| BinderInfo.strictImplicit => 1087
| BinderInfo.instImplicit => 1153
| BinderInfo.auxDecl => 1229
def BinderInfo.isExplicit : BinderInfo → Bool
| BinderInfo.implicit => false
| BinderInfo.strictImplicit => false
| BinderInfo.instImplicit => false
| _ => true
instance : Hashable BinderInfo := ⟨BinderInfo.hash⟩
def BinderInfo.isInstImplicit : BinderInfo → Bool
| BinderInfo.instImplicit => true
| _ => false
def BinderInfo.isImplicit : BinderInfo → Bool
| BinderInfo.implicit => true
| _ => false
def BinderInfo.isStrictImplicit : BinderInfo → Bool
| BinderInfo.strictImplicit => true
| _ => false
def BinderInfo.isAuxDecl : BinderInfo → Bool
| BinderInfo.auxDecl => true
| _ => false
abbrev MData := KVMap
abbrev MData.empty : MData := {}
/--
Cached hash code, cached results, and other data for `Expr`.
hash : 32-bits
hasFVar : 1-bit
hasExprMVar : 1-bit
hasLevelMVar : 1-bit
hasLevelParam : 1-bit
nonDepLet : 1-bit
binderInfo : 3-bits
approxDepth : 8-bits -- the approximate depth is used to minimize the number of hash collisions
looseBVarRange : 16-bits -/
def Expr.Data := UInt64
instance: Inhabited Expr.Data :=
inferInstanceAs (Inhabited UInt64)
def Expr.Data.hash (c : Expr.Data) : UInt64 :=
c.toUInt32.toUInt64
instance : BEq Expr.Data where
beq (a b : UInt64) := a == b
def Expr.Data.approxDepth (c : Expr.Data) : UInt8 :=
((c.shiftRight 40).land 255).toUInt8
def Expr.Data.looseBVarRange (c : Expr.Data) : UInt32 :=
(c.shiftRight 48).toUInt32
def Expr.Data.hasFVar (c : Expr.Data) : Bool :=
((c.shiftRight 32).land 1) == 1
def Expr.Data.hasExprMVar (c : Expr.Data) : Bool :=
((c.shiftRight 33).land 1) == 1
def Expr.Data.hasLevelMVar (c : Expr.Data) : Bool :=
((c.shiftRight 34).land 1) == 1
def Expr.Data.hasLevelParam (c : Expr.Data) : Bool :=
((c.shiftRight 35).land 1) == 1
def Expr.Data.nonDepLet (c : Expr.Data) : Bool :=
((c.shiftRight 36).land 1) == 1
@[extern c inline "(uint8_t)((#1 << 24) >> 61)"]
def Expr.Data.binderInfo (c : Expr.Data) : BinderInfo :=
let bi := (c.shiftLeft 24).shiftRight 61
if bi == 0 then BinderInfo.default
else if bi == 1 then BinderInfo.implicit
else if bi == 2 then BinderInfo.strictImplicit
else if bi == 3 then BinderInfo.instImplicit
else BinderInfo.auxDecl
@[extern c inline "(uint64_t)#1"]
def BinderInfo.toUInt64 : BinderInfo → UInt64
| BinderInfo.default => 0
| BinderInfo.implicit => 1
| BinderInfo.strictImplicit => 2
| BinderInfo.instImplicit => 3
| BinderInfo.auxDecl => 4
@[inline] private def Expr.mkDataCore
(h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt8)
(hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) (bi : BinderInfo)
: Expr.Data :=
if looseBVarRange > Nat.pow 2 16 - 1 then panic! "bound variable index is too big"
else
let r : UInt64 :=
h.toUInt32.toUInt64 +
hasFVar.toUInt64.shiftLeft 32 +
hasExprMVar.toUInt64.shiftLeft 33 +
hasLevelMVar.toUInt64.shiftLeft 34 +
hasLevelParam.toUInt64.shiftLeft 35 +
nonDepLet.toUInt64.shiftLeft 36 +
bi.toUInt64.shiftLeft 37 +
approxDepth.toUInt64.shiftLeft 40 +
looseBVarRange.toUInt64.shiftLeft 48
r
def Expr.mkData (h : UInt64) (looseBVarRange : Nat := 0) (approxDepth : UInt8 := 0) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool := false) : Expr.Data :=
Expr.mkDataCore h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam false BinderInfo.default
def Expr.mkDataForBinder (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt8) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) (bi : BinderInfo) : Expr.Data :=
Expr.mkDataCore h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam false bi
def Expr.mkDataForLet (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt8) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) : Expr.Data :=
Expr.mkDataCore h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet BinderInfo.default
open Expr
structure FVarId where
name : Name
deriving Inhabited, BEq, Hashable
instance : Repr FVarId where
reprPrec n p := reprPrec n.name p
def FVarIdSet := Std.RBTree FVarId (Name.quickCmp ·.name ·.name)
deriving Inhabited, EmptyCollection
instance : ForIn m FVarIdSet FVarId := inferInstanceAs (ForIn _ (Std.RBTree ..) ..)
def FVarIdHashSet := Std.HashSet FVarId
deriving Inhabited, EmptyCollection
def FVarIdMap (α : Type) := Std.RBMap FVarId α (Name.quickCmp ·.name ·.name)
instance : EmptyCollection (FVarIdMap α) := inferInstanceAs (EmptyCollection (Std.RBMap ..))
instance : Inhabited (FVarIdMap α) where
default := {}
/- We use the `E` suffix (short for `Expr`) to avoid collision with keywords.
We considered using «...», but it is too inconvenient to use. -/
inductive Expr where
| bvar : Nat → Data → Expr -- bound variables
| fvar : FVarId → Data → Expr -- free variables
| mvar : MVarId → Data → Expr -- meta variables
| sort : Level → Data → Expr -- Sort
| const : Name → List Level → Data → Expr -- constants
| app : Expr → Expr → Data → Expr -- application
| lam : Name → Expr → Expr → Data → Expr -- lambda abstraction
| forallE : Name → Expr → Expr → Data → Expr -- (dependent) arrow
| letE : Name → Expr → Expr → Expr → Data → Expr -- let expressions
| lit : Literal → Data → Expr -- literals
| mdata : MData → Expr → Data → Expr -- metadata
| proj : Name → Nat → Expr → Data → Expr -- projection
deriving Inhabited
namespace Expr
@[inline] def data : Expr → Data
| bvar _ d => d
| fvar _ d => d
| mvar _ d => d
| sort _ d => d
| const _ _ d => d
| app _ _ d => d
| lam _ _ _ d => d
| forallE _ _ _ d => d
| letE _ _ _ _ d => d
| lit _ d => d
| mdata _ _ d => d
| proj _ _ _ d => d
def ctorName : Expr → String
| bvar _ _ => "bvar"
| fvar _ _ => "fvar"
| mvar _ _ => "mvar"
| sort _ _ => "sort"
| const _ _ _ => "const"
| app _ _ _ => "app"
| lam _ _ _ _ => "lam"
| forallE _ _ _ _ => "forallE"
| letE _ _ _ _ _ => "letE"
| lit _ _ => "lit"
| mdata _ _ _ => "mdata"
| proj _ _ _ _ => "proj"
protected def hash (e : Expr) : UInt64 :=
e.data.hash
instance : Hashable Expr := ⟨Expr.hash⟩
def hasFVar (e : Expr) : Bool :=
e.data.hasFVar
def hasExprMVar (e : Expr) : Bool :=
e.data.hasExprMVar
def hasLevelMVar (e : Expr) : Bool :=
e.data.hasLevelMVar
def hasMVar (e : Expr) : Bool :=
let d := e.data
d.hasExprMVar || d.hasLevelMVar
def hasLevelParam (e : Expr) : Bool :=
e.data.hasLevelParam
def approxDepth (e : Expr) : UInt8 :=
e.data.approxDepth
def looseBVarRange (e : Expr) : Nat :=
e.data.looseBVarRange.toNat
def binderInfo (e : Expr) : BinderInfo :=
e.data.binderInfo
@[export lean_expr_hash] def hashEx : Expr → UInt64 := hash
@[export lean_expr_has_fvar] def hasFVarEx : Expr → Bool := hasFVar
@[export lean_expr_has_expr_mvar] def hasExprMVarEx : Expr → Bool := hasExprMVar
@[export lean_expr_has_level_mvar] def hasLevelMVarEx : Expr → Bool := hasLevelMVar
@[export lean_expr_has_mvar] def hasMVarEx : Expr → Bool := hasMVar
@[export lean_expr_has_level_param] def hasLevelParamEx : Expr → Bool := hasLevelParam
@[export lean_expr_loose_bvar_range] def looseBVarRangeEx (e : Expr) : UInt32 := e.data.looseBVarRange
@[export lean_expr_binder_info] def binderInfoEx : Expr → BinderInfo := binderInfo
end Expr
def mkConst (n : Name) (lvls : List Level := []) : Expr :=
Expr.const n lvls $ mkData (mixHash 5 $ mixHash (hash n) (hash lvls)) 0 0 false false (lvls.any Level.hasMVar) (lvls.any Level.hasParam)
def Literal.type : Literal → Expr
| Literal.natVal _ => mkConst `Nat
| Literal.strVal _ => mkConst `String
@[export lean_lit_type]
def Literal.typeEx : Literal → Expr := Literal.type
def mkBVar (idx : Nat) : Expr :=
Expr.bvar idx $ mkData (mixHash 7 $ hash idx) (idx+1)
def mkSort (lvl : Level) : Expr :=
Expr.sort lvl $ mkData (mixHash 11 $ hash lvl) 0 0 false false lvl.hasMVar lvl.hasParam
def mkFVar (fvarId : FVarId) : Expr :=
Expr.fvar fvarId $ mkData (mixHash 13 $ hash fvarId) 0 0 true
def mkMVar (fvarId : MVarId) : Expr :=
Expr.mvar fvarId $ mkData (mixHash 17 $ hash fvarId) 0 0 false true
def mkMData (m : MData) (e : Expr) : Expr :=
let d := e.approxDepth+1
Expr.mdata m e $ mkData (mixHash d.toUInt64 $ hash e) e.looseBVarRange d e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam
def mkProj (s : Name) (i : Nat) (e : Expr) : Expr :=
let d := e.approxDepth+1
Expr.proj s i e $ mkData (mixHash d.toUInt64 $ mixHash (hash s) $ mixHash (hash i) (hash e))
e.looseBVarRange d e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam
def mkApp (f a : Expr) : Expr :=
let d := (max f.approxDepth a.approxDepth) + 1
Expr.app f a $ mkData (mixHash d.toUInt64 $ mixHash (hash f) (hash a))
(max f.looseBVarRange a.looseBVarRange)
d
(f.hasFVar || a.hasFVar)
(f.hasExprMVar || a.hasExprMVar)
(f.hasLevelMVar || a.hasLevelMVar)
(f.hasLevelParam || a.hasLevelParam)
def mkLambda (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr :=
let d := (max t.approxDepth b.approxDepth) + 1
-- let x := x.eraseMacroScopes
Expr.lam x t b $ mkDataForBinder (mixHash d.toUInt64 $ mixHash (hash t) (hash b))
(max t.looseBVarRange (b.looseBVarRange - 1))
d
(t.hasFVar || b.hasFVar)
(t.hasExprMVar || b.hasExprMVar)
(t.hasLevelMVar || b.hasLevelMVar)
(t.hasLevelParam || b.hasLevelParam)
bi
def mkForall (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr :=
let d := (max t.approxDepth b.approxDepth) + 1
-- let x := x.eraseMacroScopes
Expr.forallE x t b $ mkDataForBinder (mixHash d.toUInt64 $ mixHash (hash t) (hash b))
(max t.looseBVarRange (b.looseBVarRange - 1))
d
(t.hasFVar || b.hasFVar)
(t.hasExprMVar || b.hasExprMVar)
(t.hasLevelMVar || b.hasLevelMVar)
(t.hasLevelParam || b.hasLevelParam)
bi
/- Return `Unit -> type`. Do not confuse with `Thunk type` -/
def mkSimpleThunkType (type : Expr) : Expr :=
mkForall Name.anonymous BinderInfo.default (Lean.mkConst `Unit) type
/- Return `fun (_ : Unit), e` -/
def mkSimpleThunk (type : Expr) : Expr :=
mkLambda `_ BinderInfo.default (Lean.mkConst `Unit) type
def mkLet (x : Name) (t : Expr) (v : Expr) (b : Expr) (nonDep : Bool := false) : Expr :=
let d := (max (max t.approxDepth v.approxDepth) b.approxDepth) + 1
-- let x := x.eraseMacroScopes
Expr.letE x t v b $ mkDataForLet (mixHash d.toUInt64 $ mixHash (hash t) $ mixHash (hash v) (hash b))
(max (max t.looseBVarRange v.looseBVarRange) (b.looseBVarRange - 1))
d
(t.hasFVar || v.hasFVar || b.hasFVar)
(t.hasExprMVar || v.hasExprMVar || b.hasExprMVar)
(t.hasLevelMVar || v.hasLevelMVar || b.hasLevelMVar)
(t.hasLevelParam || v.hasLevelParam || b.hasLevelParam)
nonDep
def mkAppB (f a b : Expr) := mkApp (mkApp f a) b
def mkApp2 (f a b : Expr) := mkAppB f a b
def mkApp3 (f a b c : Expr) := mkApp (mkAppB f a b) c
def mkApp4 (f a b c d : Expr) := mkAppB (mkAppB f a b) c d
def mkApp5 (f a b c d e : Expr) := mkApp (mkApp4 f a b c d) e
def mkApp6 (f a b c d e₁ e₂ : Expr) := mkAppB (mkApp4 f a b c d) e₁ e₂
def mkApp7 (f a b c d e₁ e₂ e₃ : Expr) := mkApp3 (mkApp4 f a b c d) e₁ e₂ e₃
def mkApp8 (f a b c d e₁ e₂ e₃ e₄ : Expr) := mkApp4 (mkApp4 f a b c d) e₁ e₂ e₃ e₄
def mkApp9 (f a b c d e₁ e₂ e₃ e₄ e₅ : Expr) := mkApp5 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅
def mkApp10 (f a b c d e₁ e₂ e₃ e₄ e₅ e₆ : Expr) := mkApp6 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ e₆
def mkLit (l : Literal) : Expr :=
Expr.lit l $ mkData (mixHash 3 (hash l))
def mkRawNatLit (n : Nat) : Expr :=
mkLit (Literal.natVal n)
def mkNatLit (n : Nat) : Expr :=
let r := mkRawNatLit n
mkApp3 (mkConst ``OfNat.ofNat [levelZero]) (mkConst ``Nat) r (mkApp (mkConst ``instOfNatNat) r)
def mkStrLit (s : String) : Expr :=
mkLit (Literal.strVal s)
@[export lean_expr_mk_bvar] def mkBVarEx : Nat → Expr := mkBVar
@[export lean_expr_mk_fvar] def mkFVarEx : FVarId → Expr := mkFVar
@[export lean_expr_mk_mvar] def mkMVarEx : MVarId → Expr := mkMVar
@[export lean_expr_mk_sort] def mkSortEx : Level → Expr := mkSort
@[export lean_expr_mk_const] def mkConstEx (c : Name) (lvls : List Level) : Expr := mkConst c lvls
@[export lean_expr_mk_app] def mkAppEx : Expr → Expr → Expr := mkApp
@[export lean_expr_mk_lambda] def mkLambdaEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkLambda n bi d b
@[export lean_expr_mk_forall] def mkForallEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkForall n bi d b
@[export lean_expr_mk_let] def mkLetEx (n : Name) (t v b : Expr) : Expr := mkLet n t v b
@[export lean_expr_mk_lit] def mkLitEx : Literal → Expr := mkLit
@[export lean_expr_mk_mdata] def mkMDataEx : MData → Expr → Expr := mkMData
@[export lean_expr_mk_proj] def mkProjEx : Name → Nat → Expr → Expr := mkProj
def mkAppN (f : Expr) (args : Array Expr) : Expr :=
args.foldl mkApp f
private partial def mkAppRangeAux (n : Nat) (args : Array Expr) (i : Nat) (e : Expr) : Expr :=
if i < n then mkAppRangeAux n args (i+1) (mkApp e (args.get! i)) else e
/-- `mkAppRange f i j #[a_1, ..., a_i, ..., a_j, ... ]` ==> the expression `f a_i ... a_{j-1}` -/
def mkAppRange (f : Expr) (i j : Nat) (args : Array Expr) : Expr :=
mkAppRangeAux j args i f
def mkAppRev (fn : Expr) (revArgs : Array Expr) : Expr :=
revArgs.foldr (fun a r => mkApp r a) fn
namespace Expr
-- TODO: implement it in Lean
@[extern "lean_expr_dbg_to_string"]
constant dbgToString (e : @& Expr) : String
@[extern "lean_expr_quick_lt"]
constant quickLt (a : @& Expr) (b : @& Expr) : Bool
@[extern "lean_expr_lt"]
constant lt (a : @& Expr) (b : @& Expr) : Bool
/- Return true iff `a` and `b` are alpha equivalent.
Binder annotations are ignored. -/
@[extern "lean_expr_eqv"]
constant eqv (a : @& Expr) (b : @& Expr) : Bool
instance : BEq Expr where
beq := Expr.eqv
/- Return true iff `a` and `b` are equal.
Binder names and annotations are taking into account. -/
@[extern "lean_expr_equal"]
constant equal (a : @& Expr) (b : @& Expr) : Bool
def isSort : Expr → Bool
| sort _ _ => true
| _ => false
def isProp : Expr → Bool
| sort (Level.zero ..) _ => true
| _ => false
def isBVar : Expr → Bool
| bvar _ _ => true
| _ => false
def isMVar : Expr → Bool
| mvar _ _ => true
| _ => false
def isFVar : Expr → Bool
| fvar _ _ => true
| _ => false
def isApp : Expr → Bool
| app .. => true
| _ => false
def isProj : Expr → Bool
| proj .. => true
| _ => false
def isConst : Expr → Bool
| const .. => true
| _ => false
def isConstOf : Expr → Name → Bool
| const n _ _, m => n == m
| _, _ => false
def isForall : Expr → Bool
| forallE .. => true
| _ => false
def isLambda : Expr → Bool
| lam .. => true
| _ => false
def isBinding : Expr → Bool
| lam .. => true
| forallE .. => true
| _ => false
def isLet : Expr → Bool
| letE .. => true
| _ => false
def isMData : Expr → Bool
| mdata .. => true
| _ => false
def isLit : Expr → Bool
| lit .. => true
| _ => false
def getForallBody : Expr → Expr
| forallE _ _ b .. => getForallBody b
| e => e
def getAppFn : Expr → Expr
| app f a _ => getAppFn f
| e => e
def getAppNumArgsAux : Expr → Nat → Nat
| app f a _, n => getAppNumArgsAux f (n+1)
| e, n => n
def getAppNumArgs (e : Expr) : Nat :=
getAppNumArgsAux e 0
private def getAppArgsAux : Expr → Array Expr → Nat → Array Expr
| app f a _, as, i => getAppArgsAux f (as.set! i a) (i-1)
| _, as, _ => as
@[inline] def getAppArgs (e : Expr) : Array Expr :=
let dummy := mkSort levelZero
let nargs := e.getAppNumArgs
getAppArgsAux e (mkArray nargs dummy) (nargs-1)
private def getAppRevArgsAux : Expr → Array Expr → Array Expr
| app f a _, as => getAppRevArgsAux f (as.push a)
| _, as => as
@[inline] def getAppRevArgs (e : Expr) : Array Expr :=
getAppRevArgsAux e (Array.mkEmpty e.getAppNumArgs)
@[specialize] def withAppAux (k : Expr → Array Expr → α) : Expr → Array Expr → Nat → α
| app f a _, as, i => withAppAux k f (as.set! i a) (i-1)
| f, as, i => k f as
@[inline] def withApp (e : Expr) (k : Expr → Array Expr → α) : α :=
let dummy := mkSort levelZero
let nargs := e.getAppNumArgs
withAppAux k e (mkArray nargs dummy) (nargs-1)
@[specialize] private def withAppRevAux (k : Expr → Array Expr → α) : Expr → Array Expr → α
| app f a _, as => withAppRevAux k f (as.push a)
| f, as => k f as
@[inline] def withAppRev (e : Expr) (k : Expr → Array Expr → α) : α :=
withAppRevAux k e (Array.mkEmpty e.getAppNumArgs)
def getRevArgD : Expr → Nat → Expr → Expr
| app f a _, 0, _ => a
| app f _ _, i+1, v => getRevArgD f i v
| _, _, v => v
def getRevArg! : Expr → Nat → Expr
| app f a _, 0 => a
| app f _ _, i+1 => getRevArg! f i
| _, _ => panic! "invalid index"
@[inline] def getArg! (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr :=
getRevArg! e (n - i - 1)
@[inline] def getArgD (e : Expr) (i : Nat) (v₀ : Expr) (n := e.getAppNumArgs) : Expr :=
getRevArgD e (n - i - 1) v₀
def isAppOf (e : Expr) (n : Name) : Bool :=
match e.getAppFn with
| const c _ _ => c == n
| _ => false
def isAppOfArity : Expr → Name → Nat → Bool
| const c _ _, n, 0 => c == n
| app f _ _, n, a+1 => isAppOfArity f n a
| _, _, _ => false
def appFn! : Expr → Expr
| app f _ _ => f
| _ => panic! "application expected"
def appArg! : Expr → Expr
| app _ a _ => a
| _ => panic! "application expected"
def isNatLit : Expr → Bool
| lit (Literal.natVal _) _ => true
| _ => false
def natLit? : Expr → Option Nat
| lit (Literal.natVal v) _ => v
| _ => none
def isStringLit : Expr → Bool
| lit (Literal.strVal _) _ => true
| _ => false
def isCharLit (e : Expr) : Bool :=
e.isAppOfArity `Char.ofNat 1 && e.appArg!.isNatLit
def constName! : Expr → Name
| const n _ _ => n
| _ => panic! "constant expected"
def constName? : Expr → Option Name
| const n _ _ => some n
| _ => none
def constLevels! : Expr → List Level
| const _ ls _ => ls
| _ => panic! "constant expected"
def bvarIdx! : Expr → Nat
| bvar idx _ => idx
| _ => panic! "bvar expected"
def fvarId! : Expr → FVarId
| fvar n _ => n
| _ => panic! "fvar expected"
def mvarId! : Expr → MVarId
| mvar n _ => n
| _ => panic! "mvar expected"
def bindingName! : Expr → Name
| forallE n _ _ _ => n
| lam n _ _ _ => n
| _ => panic! "binding expected"
def bindingDomain! : Expr → Expr
| forallE _ d _ _ => d
| lam _ d _ _ => d
| _ => panic! "binding expected"
def bindingBody! : Expr → Expr
| forallE _ _ b _ => b
| lam _ _ b _ => b
| _ => panic! "binding expected"
def bindingInfo! : Expr → BinderInfo
| forallE _ _ _ c => c.binderInfo
| lam _ _ _ c => c.binderInfo
| _ => panic! "binding expected"
def letName! : Expr → Name
| letE n _ _ _ _ => n
| _ => panic! "let expression expected"
def consumeMData : Expr → Expr
| mdata _ e _ => consumeMData e
| e => e
def mdataExpr! : Expr → Expr
| mdata _ e _ => e
| _ => panic! "mdata expression expected"
def projExpr! : Expr → Expr
| proj _ _ e _ => e
| _ => panic! "proj expression expected"
def hasLooseBVars (e : Expr) : Bool :=
e.looseBVarRange > 0
/- Remark: the following function assumes `e` does not have loose bound variables. -/
def isArrow (e : Expr) : Bool :=
match e with
| forallE _ _ b _ => !b.hasLooseBVars
| _ => false
@[extern "lean_expr_has_loose_bvar"]
constant hasLooseBVar (e : @& Expr) (bvarIdx : @& Nat) : Bool
/-- Return true if `e` contains the loose bound variable `bvarIdx` in an explicit parameter, or in the range if `tryRange == true`. -/
def hasLooseBVarInExplicitDomain : Expr → Nat → Bool → Bool
| Expr.forallE _ d b c, bvarIdx, tryRange => (c.binderInfo.isExplicit && hasLooseBVar d bvarIdx) || hasLooseBVarInExplicitDomain b (bvarIdx+1) tryRange
| e, bvarIdx, tryRange => tryRange && hasLooseBVar e bvarIdx
/--
Lower the loose bound variables `>= s` in `e` by `d`.
That is, a loose bound variable `bvar i`.
`i >= s` is mapped into `bvar (i-d)`.
Remark: if `s < d`, then result is `e` -/
@[extern "lean_expr_lower_loose_bvars"]
constant lowerLooseBVars (e : @& Expr) (s d : @& Nat) : Expr
/--
Lift loose bound variables `>= s` in `e` by `d`. -/
@[extern "lean_expr_lift_loose_bvars"]
constant liftLooseBVars (e : @& Expr) (s d : @& Nat) : Expr
/--
`inferImplicit e numParams considerRange` updates the first `numParams` parameter binder annotations of the `e` forall type.
It marks any parameter with an explicit binder annotation if there is another explicit arguments that depends on it or
the resulting type if `considerRange == true`.
Remark: we use this function to infer the bind annotations of inductive datatype constructors, and structure projections.
When the `{}` annotation is used in these commands, we set `considerRange == false`.
-/
def inferImplicit : Expr → Nat → Bool → Expr
| Expr.forallE n d b c, i+1, considerRange =>
let b := inferImplicit b i considerRange
let newInfo := if c.binderInfo.isExplicit && hasLooseBVarInExplicitDomain b 0 considerRange then BinderInfo.implicit else c.binderInfo
mkForall n newInfo d b
| e, 0, _ => e
| e, _, _ => e
/-- Instantiate the loose bound variables in `e` using `subst`.
That is, a loose `Expr.bvar i` is replaced with `subst[i]`. -/
@[extern "lean_expr_instantiate"]
constant instantiate (e : @& Expr) (subst : @& Array Expr) : Expr
@[extern "lean_expr_instantiate1"]
constant instantiate1 (e : @& Expr) (subst : @& Expr) : Expr
/-- Similar to instantiate, but `Expr.bvar i` is replaced with `subst[subst.size - i - 1]` -/
@[extern "lean_expr_instantiate_rev"]
constant instantiateRev (e : @& Expr) (subst : @& Array Expr) : Expr
/-- Similar to `instantiate`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`.
Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/
@[extern "lean_expr_instantiate_range"]
constant instantiateRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr
/-- Similar to `instantiateRev`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`.
Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/
@[extern "lean_expr_instantiate_rev_range"]
constant instantiateRevRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr
/-- Replace free variables `xs` with loose bound variables. -/
@[extern "lean_expr_abstract"]
constant abstract (e : @& Expr) (xs : @& Array Expr) : Expr
/-- Similar to `abstract`, but consider only the first `min n xs.size` entries in `xs`. -/
@[extern "lean_expr_abstract_range"]
constant abstractRange (e : @& Expr) (n : @& Nat) (xs : @& Array Expr) : Expr
/-- Replace occurrences of the free variable `fvar` in `e` with `v` -/
def replaceFVar (e : Expr) (fvar : Expr) (v : Expr) : Expr :=
(e.abstract #[fvar]).instantiate1 v
/-- Replace occurrences of the free variable `fvarId` in `e` with `v` -/
def replaceFVarId (e : Expr) (fvarId : FVarId) (v : Expr) : Expr :=
replaceFVar e (mkFVar fvarId) v
/-- Replace occurrences of the free variables `fvars` in `e` with `vs` -/
def replaceFVars (e : Expr) (fvars : Array Expr) (vs : Array Expr) : Expr :=
(e.abstract fvars).instantiateRev vs
instance : ToString Expr where
toString := Expr.dbgToString
def isAtomic : Expr → Bool
| Expr.const _ _ _ => true
| Expr.sort _ _ => true
| Expr.bvar _ _ => true
| Expr.lit _ _ => true
| Expr.mvar _ _ => true
| Expr.fvar _ _ => true
| _ => false
end Expr
def mkDecIsTrue (pred proof : Expr) :=
mkAppB (mkConst `Decidable.isTrue) pred proof
def mkDecIsFalse (pred proof : Expr) :=
mkAppB (mkConst `Decidable.isFalse) pred proof
open Std (HashMap HashSet PHashMap PHashSet)
abbrev ExprMap (α : Type) := HashMap Expr α
abbrev PersistentExprMap (α : Type) := PHashMap Expr α
abbrev ExprSet := HashSet Expr
abbrev PersistentExprSet := PHashSet Expr
abbrev PExprSet := PersistentExprSet
/- Auxiliary type for forcing `==` to be structural equality for `Expr` -/
structure ExprStructEq where
val : Expr
deriving Inhabited
instance : Coe Expr ExprStructEq := ⟨ExprStructEq.mk⟩
namespace ExprStructEq
protected def beq : ExprStructEq → ExprStructEq → Bool
| ⟨e₁⟩, ⟨e₂⟩ => Expr.equal e₁ e₂
protected def hash : ExprStructEq → UInt64
| ⟨e⟩ => e.hash
instance : BEq ExprStructEq := ⟨ExprStructEq.beq⟩
instance : Hashable ExprStructEq := ⟨ExprStructEq.hash⟩
instance : ToString ExprStructEq := ⟨fun e => toString e.val⟩
end ExprStructEq
abbrev ExprStructMap (α : Type) := HashMap ExprStructEq α
abbrev PersistentExprStructMap (α : Type) := PHashMap ExprStructEq α
namespace Expr
private partial def mkAppRevRangeAux (revArgs : Array Expr) (start : Nat) (b : Expr) (i : Nat) : Expr :=
if i == start then b
else
let i := i - 1
mkAppRevRangeAux revArgs start (mkApp b (revArgs.get! i)) i
/-- `mkAppRevRange f b e args == mkAppRev f (revArgs.extract b e)` -/
def mkAppRevRange (f : Expr) (beginIdx endIdx : Nat) (revArgs : Array Expr) : Expr :=
mkAppRevRangeAux revArgs beginIdx f endIdx
private def betaRevAux (revArgs : Array Expr) (sz : Nat) : Expr → Nat → Expr
| Expr.lam _ _ b _, i =>
if i + 1 < sz then
betaRevAux revArgs sz b (i+1)
else
let n := sz - (i + 1)
mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs
| Expr.mdata _ b _, i => betaRevAux revArgs sz b i
| b, i =>
let n := sz - i
mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs
/-- If `f` is a lambda expression, than "beta-reduce" it using `revArgs`.
This function is often used with `getAppRev` or `withAppRev`.
Examples:
- `betaRev (fun x y => t x y) #[]` ==> `fun x y => t x y`
- `betaRev (fun x y => t x y) #[a]` ==> `fun y => t a y`
- `betaRev (fun x y => t x y) #[a, b]` ==> t b a`
- `betaRev (fun x y => t x y) #[a, b, c, d]` ==> t d c b a`
Suppose `t` is `(fun x y => t x y) a b c d`, then
`args := t.getAppRev` is `#[d, c, b, a]`,
and `betaRev (fun x y => t x y) #[d, c, b, a]` is `t a b c d`. -/
def betaRev (f : Expr) (revArgs : Array Expr) : Expr :=
if revArgs.size == 0 then f
else betaRevAux revArgs revArgs.size f 0
def isHeadBetaTargetFn : Expr → Bool
| Expr.lam _ _ _ _ => true
| Expr.mdata _ b _ => isHeadBetaTargetFn b
| _ => false
def headBeta (e : Expr) : Expr :=
let f := e.getAppFn
if f.isHeadBetaTargetFn then betaRev f e.getAppRevArgs else e
def isHeadBetaTarget (e : Expr) : Bool :=
e.getAppFn.isHeadBetaTargetFn
private def etaExpandedBody : Expr → Nat → Nat → Option Expr
| app f (bvar j _) _, n+1, i => if j == i then etaExpandedBody f n (i+1) else none
| _, n+1, _ => none
| f, 0, _ => if f.hasLooseBVars then none else some f
private def etaExpandedAux : Expr → Nat → Option Expr
| lam _ _ b _, n => etaExpandedAux b (n+1)
| e, n => etaExpandedBody e n 0
/--
If `e` is of the form `(fun x₁ ... xₙ => f x₁ ... xₙ)` and `f` does not contain `x₁`, ..., `xₙ`,
then return `some f`. Otherwise, return `none`.
It assumes `e` does not have loose bound variables.
Remark: `ₙ` may be 0 -/
def etaExpanded? (e : Expr) : Option Expr :=
etaExpandedAux e 0
/-- Similar to `etaExpanded?`, but only succeeds if `ₙ ≥ 1`. -/
def etaExpandedStrict? : Expr → Option Expr
| lam _ _ b _ => etaExpandedAux b 1
| _ => none
def getOptParamDefault? (e : Expr) : Option Expr :=
if e.isAppOfArity `optParam 2 then
some e.appArg!
else
none
def getAutoParamTactic? (e : Expr) : Option Expr :=
if e.isAppOfArity `autoParam 2 then
some e.appArg!
else
none
def isOptParam (e : Expr) : Bool :=
e.isAppOfArity `optParam 2
def isAutoParam (e : Expr) : Bool :=
e.isAppOfArity `autoParam 2
partial def consumeAutoOptParam (e : Expr) : Expr :=
if e.isOptParam || e.isAutoParam then
consumeAutoOptParam e.appFn!.appArg!
else
e
/-- Return true iff `e` contains a free variable which statisfies `p`. -/
@[inline] def hasAnyFVar (e : Expr) (p : FVarId → Bool) : Bool :=
let rec @[specialize] visit (e : Expr) := if !e.hasFVar then false else
match e with
| Expr.forallE _ d b _ => visit d || visit b
| Expr.lam _ d b _ => visit d || visit b
| Expr.mdata _ e _ => visit e
| Expr.letE _ t v b _ => visit t || visit v || visit b
| Expr.app f a _ => visit f || visit a
| Expr.proj _ _ e _ => visit e
| e@(Expr.fvar fvarId _) => p fvarId
| e => false
visit e
def containsFVar (e : Expr) (fvarId : FVarId) : Bool :=
e.hasAnyFVar (· == fvarId)
/- The update functions here are defined using C code. They will try to avoid
allocating new values using pointer equality.
The hypotheses `(h : e.is...)` are used to ensure Lean will not crash
at runtime.
The `update*!` functions are inlined and provide a convenient way of using the
update proofs without providing proofs.
Note that if they are used under a match-expression, the compiler will eliminate
the double-match. -/
@[extern "lean_expr_update_app"]
def updateApp (e : Expr) (newFn : Expr) (newArg : Expr) (h : e.isApp) : Expr :=
mkApp newFn newArg
@[inline] def updateApp! (e : Expr) (newFn : Expr) (newArg : Expr) : Expr :=
match e with
| app fn arg c => updateApp (app fn arg c) newFn newArg rfl
| _ => panic! "application expected"
@[extern "lean_expr_update_const"]
def updateConst (e : Expr) (newLevels : List Level) (h : e.isConst) : Expr :=
mkConst e.constName! newLevels
@[inline] def updateConst! (e : Expr) (newLevels : List Level) : Expr :=
match e with
| const n ls c => updateConst (const n ls c) newLevels rfl
| _ => panic! "constant expected"
@[extern "lean_expr_update_sort"]
def updateSort (e : Expr) (newLevel : Level) (h : e.isSort) : Expr :=
mkSort newLevel
@[inline] def updateSort! (e : Expr) (newLevel : Level) : Expr :=
match e with
| sort l c => updateSort (sort l c) newLevel rfl
| _ => panic! "level expected"
@[extern "lean_expr_update_proj"]
def updateProj (e : Expr) (newExpr : Expr) (h : e.isProj) : Expr :=
match e with
| proj s i _ _ => mkProj s i newExpr
| _ => e -- unreachable because of `h`
@[extern "lean_expr_update_mdata"]
def updateMData (e : Expr) (newExpr : Expr) (h : e.isMData) : Expr :=
match e with
| mdata d _ _ => mkMData d newExpr
| _ => e -- unreachable because of `h`
@[inline] def updateMData! (e : Expr) (newExpr : Expr) : Expr :=
match e with
| mdata d e c => updateMData (mdata d e c) newExpr rfl
| _ => panic! "mdata expected"
@[inline] def updateProj! (e : Expr) (newExpr : Expr) : Expr :=
match e with
| proj s i e c => updateProj (proj s i e c) newExpr rfl
| _ => panic! "proj expected"
@[extern "lean_expr_update_forall"]
def updateForall (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isForall) : Expr :=
mkForall e.bindingName! newBinfo newDomain newBody
@[inline] def updateForall! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| forallE n d b c => updateForall (forallE n d b c) newBinfo newDomain newBody rfl
| _ => panic! "forall expected"
@[inline] def updateForallE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| forallE n d b c => updateForall (forallE n d b c) c.binderInfo newDomain newBody rfl
| _ => panic! "forall expected"
@[extern "lean_expr_update_lambda"]
def updateLambda (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isLambda) : Expr :=
mkLambda e.bindingName! newBinfo newDomain newBody
@[inline] def updateLambda! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| lam n d b c => updateLambda (lam n d b c) newBinfo newDomain newBody rfl
| _ => panic! "lambda expected"
@[inline] def updateLambdaE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr :=
match e with
| lam n d b c => updateLambda (lam n d b c) c.binderInfo newDomain newBody rfl
| _ => panic! "lambda expected"
@[extern "lean_expr_update_let"]
def updateLet (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) (h : e.isLet) : Expr :=
mkLet e.letName! newType newVal newBody
@[inline] def updateLet! (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr :=
match e with
| letE n t v b c => updateLet (letE n t v b c) newType newVal newBody rfl
| _ => panic! "let expression expected"
def updateFn : Expr → Expr → Expr
| e@(app f a _), g => e.updateApp! (updateFn f g) a
| _, g => g
partial def eta (e : Expr) : Expr :=
match e with
| Expr.lam _ d b _ =>
let b' := b.eta
match b' with
| Expr.app f (Expr.bvar 0 _) _ =>
if !f.hasLooseBVar 0 then
f.lowerLooseBVars 1 1
else
e.updateLambdaE! d b'
| _ => e.updateLambdaE! d b'
| _ => e
/- Instantiate level parameters -/
@[inline] def instantiateLevelParamsCore (s : Name → Option Level) (e : Expr) : Expr :=
let rec @[specialize] visit (e : Expr) : Expr :=
if !e.hasLevelParam then e
else match e with
| lam n d b _ => e.updateLambdaE! (visit d) (visit b)
| forallE n d b _ => e.updateForallE! (visit d) (visit b)
| letE n t v b _ => e.updateLet! (visit t) (visit v) (visit b)
| app f a _ => e.updateApp! (visit f) (visit a)
| proj _ _ s _ => e.updateProj! (visit s)
| mdata _ b _ => e.updateMData! (visit b)
| const _ us _ => e.updateConst! (us.map (fun u => u.instantiateParams s))
| sort u _ => e.updateSort! (u.instantiateParams s)
| e => e
visit e
private def getParamSubst : List Name → List Level → Name → Option Level
| p::ps, u::us, p' => if p == p' then some u else getParamSubst ps us p'
| _, _, _ => none
def instantiateLevelParams (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr :=
instantiateLevelParamsCore (getParamSubst paramNames lvls) e
private partial def getParamSubstArray (ps : Array Name) (us : Array Level) (p' : Name) (i : Nat) : Option Level :=
if h : i < ps.size then
let p := ps.get ⟨i, h⟩
if h : i < us.size then
let u := us.get ⟨i, h⟩
if p == p' then some u else getParamSubstArray ps us p' (i+1)
else none
else none
def instantiateLevelParamsArray (e : Expr) (paramNames : Array Name) (lvls : Array Level) : Expr :=
instantiateLevelParamsCore (fun p => getParamSubstArray paramNames lvls p 0) e
/- Annotate `e` with the given option. -/
def setOption (e : Expr) (optionName : Name) [KVMap.Value α] (val : α) : Expr :=
mkMData (MData.empty.set optionName val) e
/- Annotate `e` with `pp.explicit := true`
The delaborator uses `pp` options. -/
def setPPExplicit (e : Expr) (flag : Bool) :=
e.setOption `pp.explicit flag
def setPPUniverses (e : Expr) (flag : Bool) :=
e.setOption `pp.universes flag
/- If `e` is an application `f a_1 ... a_n` annotate `f`, `a_1` ... `a_n` with `pp.explicit := false`,
and annotate `e` with `pp.explicit := true`. -/
def setAppPPExplicit (e : Expr) : Expr :=
match e with
| app .. =>
let f := e.getAppFn.setPPExplicit false
let args := e.getAppArgs.map (·.setPPExplicit false)
mkAppN f args |>.setPPExplicit true
| _ => e
/- Similar for `setAppPPExplicit`, but only annotate children with `pp.explicit := false` if
`e` does not contain metavariables. -/
def setAppPPExplicitForExposingMVars (e : Expr) : Expr :=
match e with
| app .. =>
let f := e.getAppFn.setPPExplicit false
let args := e.getAppArgs.map fun arg => if arg.hasMVar then arg else arg.setPPExplicit false
mkAppN f args |>.setPPExplicit true
| _ => e
end Expr
def mkAnnotation (kind : Name) (e : Expr) : Expr :=
mkMData (KVMap.empty.insert kind (DataValue.ofBool true)) e
def annotation? (kind : Name) (e : Expr) : Option Expr :=
match e with
| Expr.mdata d b _ => if d.size == 1 && d.getBool kind false then some b else none
| _ => none
def mkLetFunAnnotation (e : Expr) : Expr :=
mkAnnotation `let_fun e
def letFunAnnotation? (e : Expr) : Option Expr :=
annotation? `let_fun e
def isLetFun (e : Expr) : Bool :=
match letFunAnnotation? e with
| none => false
| some e => e.isApp && e.appFn!.isLambda
/--
Annotate `e` with the LHS annotation. The delaborator displays
expressions of the form `lhs = rhs` as `lhs` when they have this annotation.
-/
def mkLHSGoal (e : Expr) : Expr :=
mkAnnotation `_lhsGoal e
def isLHSGoal? (e : Expr) : Option Expr :=
match annotation? `_lhsGoal e with
| none => none
| some e =>
if e.isAppOfArity `Eq 3 then
some e.appFn!.appArg!
else
none
def mkFreshFVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m FVarId :=
return { name := (← mkFreshId) }
def mkFreshMVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m MVarId :=
return { name := (← mkFreshId) }
def mkNot (p : Expr) : Expr := mkApp (mkConst ``Not) p
def mkOr (p q : Expr) : Expr := mkApp2 (mkConst ``Or) p q
def mkAnd (p q : Expr) : Expr := mkApp2 (mkConst ``And) p q
def mkEM (p : Expr) : Expr := mkApp (mkConst ``Classical.em) p
end Lean
|
3293742a5181fcc4531f7b2cc71f29f8601081da | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/abstract_expr1.lean | 978c1c96ff1f59a74e1cff0a6401b106a56182bc | [
"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 | 141 | lean | #abstract_expr 0 @zero
#abstract_expr 0 ℕ
#abstract_expr 0 nat_has_zero
#abstract_expr 0 @zero ℕ
#abstract_expr 0 @zero ℕ nat_has_zero
|
7e3ca1a2fcc642c688f0ce5972137caa4cfc6018 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/monoidal/CommMon__auto.lean | f6f094389237b566b7cace7cc2fbb9a90610281e | [] | 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 | 9,341 | 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.category_theory.monoidal.braided
import Mathlib.category_theory.monoidal.Mon_
import Mathlib.PostPort
universes v₁ u₁ l u₂ v₂ u_1 u_2
namespace Mathlib
/-!
# The category of commutative monoids in a braided monoidal category.
-/
/--
A commutative monoid object internal to a monoidal category.
-/
structure CommMon_ (C : Type u₁) [category_theory.category C] [category_theory.monoidal_category C]
[category_theory.braided_category C]
extends Mon_ C where
mul_comm' :
autoParam (category_theory.iso.hom β_ ≫ Mon_.mul _to_Mon_ = Mon_.mul _to_Mon_)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
@[simp] theorem CommMon_.mul_comm {C : Type u₁} [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] (c : CommMon_ C) :
category_theory.iso.hom β_ ≫ Mon_.mul (CommMon_.to_Mon_ c) = Mon_.mul (CommMon_.to_Mon_ c) :=
sorry
@[simp] theorem CommMon_.mul_comm_assoc {C : Type u₁} [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] (c : CommMon_ C)
{X' : C} (f' : Mon_.X (CommMon_.to_Mon_ c) ⟶ X') :
category_theory.iso.hom β_ ≫ Mon_.mul (CommMon_.to_Mon_ c) ≫ f' =
Mon_.mul (CommMon_.to_Mon_ c) ≫ f' :=
sorry
namespace CommMon_
/--
The trivial commutative monoid object. We later show this is initial in `CommMon_ C`.
-/
def trivial (C : Type u₁) [category_theory.category C] [category_theory.monoidal_category C]
[category_theory.braided_category C] : CommMon_ C :=
mk (Mon_.mk (Mon_.X (Mon_.trivial C)) (Mon_.one (Mon_.trivial C)) (Mon_.mul (Mon_.trivial C)))
protected instance inhabited (C : Type u₁) [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] :
Inhabited (CommMon_ C) :=
{ default := trivial C }
protected instance category_theory.category {C : Type u₁} [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] :
category_theory.category (CommMon_ C) :=
category_theory.induced_category.category to_Mon_
@[simp] theorem id_hom {C : Type u₁} [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] (A : CommMon_ C) :
Mon_.hom.hom 𝟙 = 𝟙 :=
rfl
@[simp] theorem comp_hom {C : Type u₁} [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] {R : CommMon_ C}
{S : CommMon_ C} {T : CommMon_ C} (f : R ⟶ S) (g : S ⟶ T) :
Mon_.hom.hom (f ≫ g) = Mon_.hom.hom f ≫ Mon_.hom.hom g :=
rfl
/-- The forgetful functor from commutative monoid objects to monoid objects. -/
def forget₂_Mon_ (C : Type u₁) [category_theory.category C] [category_theory.monoidal_category C]
[category_theory.braided_category C] : CommMon_ C ⥤ Mon_ C :=
category_theory.induced_functor to_Mon_
@[simp] theorem forget₂_Mon_obj_one (C : Type u₁) [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] (A : CommMon_ C) :
Mon_.one (category_theory.functor.obj (forget₂_Mon_ C) A) = Mon_.one (to_Mon_ A) :=
rfl
@[simp] theorem forget₂_Mon_obj_mul (C : Type u₁) [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] (A : CommMon_ C) :
Mon_.mul (category_theory.functor.obj (forget₂_Mon_ C) A) = Mon_.mul (to_Mon_ A) :=
rfl
@[simp] theorem forget₂_Mon_map_hom (C : Type u₁) [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] {A : CommMon_ C}
{B : CommMon_ C} (f : A ⟶ B) :
Mon_.hom.hom (category_theory.functor.map (forget₂_Mon_ C) f) = Mon_.hom.hom f :=
rfl
protected instance unique_hom_from_trivial {C : Type u₁} [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] (A : CommMon_ C) :
unique (trivial C ⟶ A) :=
Mon_.unique_hom_from_trivial (to_Mon_ A)
protected instance category_theory.limits.has_initial {C : Type u₁} [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] :
category_theory.limits.has_initial (CommMon_ C) :=
category_theory.limits.has_initial_of_unique (trivial C)
end CommMon_
namespace category_theory.lax_braided_functor
/--
A lax braided functor takes commutative monoid objects to commutative monoid objects.
That is, a lax braided functor `F : C ⥤ D` induces a functor `CommMon_ C ⥤ CommMon_ D`.
-/
@[simp] theorem map_CommMon_map {C : Type u₁} [category C] [monoidal_category C]
[braided_category C] {D : Type u₂} [category D] [monoidal_category D] [braided_category D]
(F : lax_braided_functor C D) (A : CommMon_ C) (B : CommMon_ C) (f : A ⟶ B) :
functor.map (map_CommMon F) f =
functor.map (lax_monoidal_functor.map_Mon (to_lax_monoidal_functor F)) f :=
Eq.refl (functor.map (map_CommMon F) f)
/-- `map_CommMon` is functorial in the lax braided functor. -/
def map_CommMon_functor (C : Type u₁) [category C] [monoidal_category C] [braided_category C]
(D : Type u₂) [category D] [monoidal_category D] [braided_category D] :
lax_braided_functor C D ⥤ CommMon_ C ⥤ CommMon_ D :=
functor.mk map_CommMon
fun (F G : lax_braided_functor C D) (α : F ⟶ G) =>
nat_trans.mk
fun (A : CommMon_ C) =>
Mon_.hom.mk
(nat_trans.app (monoidal_nat_trans.to_nat_trans α) (Mon_.X (CommMon_.to_Mon_ A)))
end category_theory.lax_braided_functor
namespace CommMon_
namespace equiv_lax_braided_functor_punit
/-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/
@[simp] theorem lax_braided_to_CommMon_map (C : Type u₁) [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C]
(F : category_theory.lax_braided_functor (category_theory.discrete PUnit) C)
(G : category_theory.lax_braided_functor (category_theory.discrete PUnit) C) (α : F ⟶ G) :
category_theory.functor.map (lax_braided_to_CommMon C) α =
category_theory.nat_trans.app
(category_theory.functor.map
(category_theory.lax_braided_functor.map_CommMon_functor
(category_theory.discrete PUnit) C)
α)
(trivial (category_theory.discrete PUnit)) :=
Eq.refl (category_theory.functor.map (lax_braided_to_CommMon C) α)
/-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/
@[simp] theorem CommMon_to_lax_braided_obj_to_lax_monoidal_functor_to_functor_obj (C : Type u₁)
[category_theory.category C] [category_theory.monoidal_category C]
[category_theory.braided_category C] (A : CommMon_ C) (_x : category_theory.discrete PUnit) :
category_theory.functor.obj
(category_theory.lax_monoidal_functor.to_functor
(category_theory.lax_braided_functor.to_lax_monoidal_functor
(category_theory.functor.obj (CommMon_to_lax_braided C) A)))
_x =
Mon_.X (to_Mon_ A) :=
sorry
/-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/
@[simp] theorem unit_iso_hom_app_to_nat_trans_app (C : Type u₁) [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C]
(X : category_theory.lax_braided_functor (category_theory.discrete PUnit) C) :
∀ (X_1 : category_theory.discrete PUnit),
category_theory.nat_trans.app
(category_theory.monoidal_nat_trans.to_nat_trans
(category_theory.nat_trans.app (category_theory.iso.hom (unit_iso C)) X))
X_1 =
category_theory.eq_to_hom
(congr_arg
(category_theory.functor.obj
(category_theory.lax_monoidal_functor.to_functor
(category_theory.lax_braided_functor.to_lax_monoidal_functor X)))
(unit_iso._proof_1 X_1)) :=
sorry
/-- Implementation of `CommMon_.equiv_lax_braided_functor_punit`. -/
@[simp] theorem counit_iso_inv_app_hom (C : Type u₁) [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] (X : CommMon_ C) :
Mon_.hom.hom (category_theory.nat_trans.app (category_theory.iso.inv (counit_iso C)) X) = 𝟙 :=
Eq.refl 𝟙
end equiv_lax_braided_functor_punit
/--
Commutative monoid objects in `C` are "just" braided lax monoidal functors from the trivial
braided monoidal category to `C`.
-/
@[simp] theorem equiv_lax_braided_functor_punit_functor (C : Type u₁) [category_theory.category C]
[category_theory.monoidal_category C] [category_theory.braided_category C] :
category_theory.equivalence.functor (equiv_lax_braided_functor_punit C) =
equiv_lax_braided_functor_punit.lax_braided_to_CommMon C :=
Eq.refl (category_theory.equivalence.functor (equiv_lax_braided_functor_punit C))
end Mathlib |
dcf03beafceeb7fbb6ec9cf72895c31720079c6d | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Init/WF.lean | cad2c26329ad7a0d3de60f301ddd00d2ac9fd07f | [
"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 | 11,156 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.SizeOf
import Init.Data.Nat.Basic
universes u v
set_option codegen false
inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop where
| intro (x : α) (h : (y : α) → r y x → Acc r y) : Acc r x
abbrev Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1}
(m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x)
{a : α} (n : Acc r a) : C a :=
Acc.rec (motive := fun α _ => C α) m n
abbrev Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1}
{a : α} (n : Acc r a)
(m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x)
: C a :=
Acc.rec (motive := fun α _ => C α) m n
namespace Acc
variable {α : Sort u} {r : α → α → Prop}
def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y :=
Acc.recOn (motive := fun (x : α) _ => r y x → Acc r y)
h₁ (fun x₁ ac₁ ih h₂ => ac₁ y h₂) h₂
end Acc
inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop where
| intro (h : ∀ a, Acc r a) : WellFounded r
class WellFoundedRelation (α : Sort u) : Type u where
r : α → α → Prop
wf : WellFounded r
namespace WellFounded
def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) (a : α) : Acc r a :=
WellFounded.recOn (motive := fun x => (y : α) → Acc r y)
wf (fun p => p) a
section
variable {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r)
theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := by
induction (apply hwf a) with
| intro x₁ ac₁ ih => exact h x₁ ih
theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a :=
recursion hwf a h
variable {C : α → Sort v}
variable (F : ∀ x, (∀ y, r y x → C y) → C x)
def fixF (x : α) (a : Acc r x) : C x := by
induction a with
| intro x₁ ac₁ ih => exact F x₁ ih
def fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := by
induction acx with
| intro x r ih => exact rfl
end
variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop}
-- Well-founded fixpoint
def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x :=
fixF F x (apply hwf x)
-- Well-founded fixpoint satisfies fixpoint equation
theorem fixEq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) :
fix hwf F x = F x (fun y h => fix hwf F y) :=
fixFEq F x (apply hwf x)
end WellFounded
open WellFounded
-- Empty relation is well-founded
def emptyWf {α : Sort u} : WellFounded (@emptyRelation α) := by
apply WellFounded.intro
intro a
apply Acc.intro a
intro b h
cases h
-- Subrelation of a well-founded relation is well-founded
namespace Subrelation
variable {α : Sort u} {r q : α → α → Prop}
def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := by
induction ac with
| intro x ax ih =>
apply Acc.intro
intro y h
exact ih y (h₁ h)
def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q :=
⟨fun a => accessible @h₁ (apply h₂ a)⟩
end Subrelation
-- The inverse image of a well-founded relation is well-founded
namespace InvImage
variable {α : Sort u} {β : Sort v} {r : β → β → Prop}
private def accAux (f : α → β) {b : β} (ac : Acc r b) : (x : α) → f x = b → Acc (InvImage r f) x := by
induction ac with
| intro x acx ih =>
intro z e
apply Acc.intro
intro y lt
subst x
apply ih (f y) lt y rfl
def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a :=
accAux f ac a rfl
def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) :=
⟨fun a => accessible f (apply h (f a))⟩
end InvImage
-- The transitive closure of a well-founded relation is well-founded
namespace TC
variable {α : Sort u} {r : α → α → Prop}
def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := by
induction ac with
| intro x acx ih =>
apply Acc.intro x
intro y rel
induction rel with
| base a b rab => exact ih a rab
| trans a b c rab rbc ih₁ ih₂ => apply Acc.inv (ih₂ acx ih) rab
def wf (h : WellFounded r) : WellFounded (TC r) :=
⟨fun a => accessible (apply h a)⟩
end TC
-- less-than is well-founded
def Nat.ltWf : WellFounded Nat.lt := by
apply WellFounded.intro
intro n
induction n with
| zero =>
apply Acc.intro 0
intro _ h
apply absurd h (Nat.notLtZero _)
| succ n ih =>
apply Acc.intro (Nat.succ n)
intro m h
have m = n ∨ m < n from Nat.eqOrLtOfLe (Nat.leOfSuccLeSucc h)
match this with
| Or.inl e => subst e; assumption
| Or.inr e => exact Acc.inv ih e
def measure {α : Sort u} : (α → Nat) → α → α → Prop :=
InvImage (fun a b => a < b)
def measureWf {α : Sort u} (f : α → Nat) : WellFounded (measure f) :=
InvImage.wf f Nat.ltWf
def sizeofMeasure (α : Sort u) [SizeOf α] : α → α → Prop :=
measure sizeOf
def sizeofMeasureWf (α : Sort u) [SizeOf α] : WellFounded (sizeofMeasure α) :=
measureWf sizeOf
instance hasWellFoundedOfSizeOf (α : Sort u) [SizeOf α] : WellFoundedRelation α where
r := sizeofMeasure α
wf := sizeofMeasureWf α
namespace Prod
open WellFounded
section
variable {α : Type u} {β : Type v}
variable (ra : α → α → Prop)
variable (rb : β → β → Prop)
-- Lexicographical order based on ra and rb
inductive Lex : α × β → α × β → Prop where
| left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂)
| right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂)
-- relational product based on ra and rb
inductive Rprod : α × β → α × β → Prop where
| intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : Rprod (a₁, b₁) (a₂, b₂)
end
section
variable {α : Type u} {β : Type v}
variable {ra : α → α → Prop} {rb : β → β → Prop}
def lexAccessible (aca : (a : α) → Acc ra a) (acb : (b : β) → Acc rb b) (a : α) (b : β) : Acc (Lex ra rb) (a, b) := by
induction (aca a) generalizing b with
| intro xa aca iha =>
induction (acb b) with
| intro xb acb ihb =>
apply Acc.intro (xa, xb)
intro p lt
cases lt with
| left _ _ h => apply iha _ h
| right _ h => apply ihb _ h
-- The lexicographical order of well founded relations is well-founded
def lexWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Lex ra rb) :=
⟨fun (a, b) => lexAccessible (WellFounded.apply ha) (WellFounded.apply hb) a b⟩
-- relational product is a Subrelation of the Lex
def rprodSubLex (a : α × β) (b : α × β) (h : Rprod ra rb a b) : Lex ra rb a b := by
cases h with
| intro h₁ h₂ => exact Lex.left _ _ h₁
-- The relational product of well founded relations is well-founded
def rprodWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Rprod ra rb) := by
apply Subrelation.wf (r := Lex ra rb) (h₂ := lexWf ha hb)
intro a b h
exact rprodSubLex a b h
end
instance {α : Type u} {β : Type v} [s₁ : WellFoundedRelation α] [s₂ : WellFoundedRelation β] : WellFoundedRelation (α × β) where
r := Lex s₁.r s₂.r
wf := lexWf s₁.wf s₂.wf
end Prod
namespace PSigma
section
variable {α : Sort u} {β : α → Sort v}
variable (r : α → α → Prop)
variable (s : ∀ a, β a → β a → Prop)
-- Lexicographical order based on r and s
inductive Lex : PSigma β → PSigma β → Prop where
| left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
| right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩
end
section
variable {α : Sort u} {β : α → Sort v}
variable {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop}
def lexAccessible {a} (aca : Acc r a) (acb : (a : α) → WellFounded (s a)) (b : β a) : Acc (Lex r s) ⟨a, b⟩ := by
induction aca with
| intro xa aca iha =>
induction (WellFounded.apply (acb xa) b) with
| intro xb acb ihb =>
apply Acc.intro
intro p lt
cases lt with
| left => apply iha; assumption
| right => apply ihb; assumption
-- The lexicographical order of well founded relations is well-founded
def lexWf (ha : WellFounded r) (hb : (x : α) → WellFounded (s x)) : WellFounded (Lex r s) :=
WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b
end
section
variable {α : Sort u} {β : Sort v}
def lexNdep (r : α → α → Prop) (s : β → β → Prop) :=
Lex r (fun a => s)
def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) :=
WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun x => hb) b
end
section
variable {α : Sort u} {β : Sort v}
-- Reverse lexicographical order based on r and s
inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop where
| left : {a₁ a₂ : α} → (b : β) → r a₁ a₂ → RevLex r s ⟨a₁, b⟩ ⟨a₂, b⟩
| right : (a₁ : α) → {b₁ : β} → (a₂ : α) → {b₂ : β} → s b₁ b₂ → RevLex r s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
end
section
open WellFounded
variable {α : Sort u} {β : Sort v}
variable {r : α → α → Prop} {s : β → β → Prop}
def revLexAccessible {b} (acb : Acc s b) (aca : (a : α) → Acc r a): (a : α) → Acc (RevLex r s) ⟨a, b⟩ := by
induction acb with
| intro xb acb ihb =>
intro a
induction (aca a) with
| intro xa aca iha =>
apply Acc.intro
intro p lt
cases lt with
| left => apply iha; assumption
| right => apply ihb; assumption
def revLexWf (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) :=
WellFounded.intro fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a
end
section
def skipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop :=
RevLex emptyRelation s
def skipLeftWf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : WellFounded s) : WellFounded (skipLeft α s) :=
revLexWf emptyWf hb
def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : skipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ :=
RevLex.right _ _ h
end
instance WellFoundedRelation {α : Type u} {β : α → Type v} [s₁ : WellFoundedRelation α] [s₂ : ∀ a, WellFoundedRelation (β a)] : WellFoundedRelation (PSigma β) where
r := Lex s₁.r (fun a => (s₂ a).r)
wf := lexWf s₁.wf (fun a => (s₂ a).wf)
end PSigma
|
6132b46fcab6c51d0f1b2a9f986488d1d70dcd78 | e4def7044cdf5942eed78db25d2daa58d80eed64 | /_target/deps/mathlib/src/analysis/calculus/fderiv.lean | f8a2a4a86b736f6c6cc33fb102abb61b147b3ece | [
"Apache-2.0"
] | permissive | kevinsullivan/dm.s20.old | 3f8f736b9a792cca8dd44a73a98ade0b534ed084 | a240be0a53961ac25b5f4426fe7bc8d4dbe7013f | refs/heads/master | 1,607,522,498,471 | 1,579,058,084,000 | 1,579,058,084,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 60,043 | 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
-/
import analysis.asymptotics analysis.calculus.tangent_cone
/-!
# 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`
## 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
* 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)
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.
## 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.
## Tags
derivative, differentiable, Fréchet, calculus
-/
open filter asymptotics continuous_linear_map set
open_locale topological_space
noncomputable theory
local attribute [instance, priority 10] classical.decidable_inhabited classical.prop_decidable
set_option class.instance_max_depth 90
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]
/-- 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 = nhds_within x s` (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 (nhds_within x s)
/-- 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)
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)
{c : ℕ → 𝕜} {d : ℕ → E} {v : E} (dtop : {n : ℕ | x + d n ∈ s} ∈ (at_top : filter ℕ))
(clim : tendsto (λ (n : ℕ), ∥c n∥) at_top at_top)
(cdlim : tendsto (λ (n : ℕ), c n • d n) at_top (𝓝 v)) :
tendsto (λn, c n • (f (x + d n) - f x)) at_top (𝓝 (f' v)) :=
begin
have at_top_is_finer : at_top ≤ comap (λ (n : ℕ), x + d n) (nhds_within x s),
{ conv in (nhds_within x s) { rw ← add_zero x },
rw [← tendsto_iff_comap, nhds_within, tendsto_inf],
split,
{ apply tendsto_const_nhds.add (tangent_cone_at.lim_zero clim cdlim) },
{ rwa tendsto_principal } },
have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (nhds_within x s) := h,
have : is_o (λ n:ℕ, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x)
((nhds_within x s).comap (λn, x+ d n)) := is_o.comp this _,
have : is_o (λ n:ℕ, f (x + d n) - f x - f' (d n)) d
((nhds_within x s).comap (λn, x + d n)) := by simpa,
have : is_o (λn:ℕ, f (x + d n) - f x - f' (d n)) d at_top :=
is_o.mono at_top_is_finer this,
have : is_o (λn:ℕ, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) at_top :=
is_o_smul this,
have : is_o (λn:ℕ, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) at_top :=
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))) at_top (𝓝 0) :=
is_o_one_iff.1 this,
have L2 : tendsto (λn:ℕ, f' (c n • d n)) at_top (𝓝 (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)))
at_top (𝓝 (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] },
rwa [this, zero_add] at L3
end
/-- `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)
(h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' :=
begin
have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y,
{ rintros y ⟨c, d, dtop, clim, cdlim⟩,
exact tendsto_nhds_unique (by simp) (h.lim dtop clim cdlim) (h₁.lim dtop clim cdlim) },
have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y,
{ assume y hy,
apply submodule.span_induction hy,
{ exact λy hy, A y hy },
{ simp only [continuous_linear_map.map_zero] },
{ simp {contextual := tt} },
{ simp {contextual := tt} } },
have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y,
{ assume y hy,
let K := {y | f' y = f₁' y},
have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B,
have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K :=
closure_mono this,
have : y ∈ closure K := this hy,
rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this },
rw H.1 at C,
ext y,
exact C y (mem_univ _)
end
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₁' :=
unique_diff_within_at.eq (H x hx) 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 (x' - x)).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'r (λ _, 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)∥) (nhds_within x s) (𝓝 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
split,
{ assume H,
have : 𝓝 0 ≤ comap (λ (z : E), z + x) (𝓝 (0 + x)),
{ refine tendsto_iff_comap.mp _,
exact (continuous_id.add continuous_const).tendsto _ },
apply is_o.mono this,
convert is_o.comp H (λz, z + x) ; { try {ext}, simp } },
{ assume H,
have : 𝓝 x ≤ comap (λ (z : E), z - x) (𝓝 (x - x)),
{ refine tendsto_iff_comap.mp _,
exact (continuous_id.add continuous_const).tendsto _ },
apply is_o.mono this,
convert is_o.comp H (λz, z - x) ; { try {ext}, simp } }
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₁ :=
is_o.mono hst h
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 lattice.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 }
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 ∈ nhds_within x s) :
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.nhds_within (h : has_fderiv_within_at f f' s x)
(ht : s ∈ nhds_within x t) : has_fderiv_within_at f f' t x :=
(has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _))
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 has_fderiv_at_unique h h.differentiable_at.has_fderiv_at }
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' :=
by { ext, rw hxs.eq h h.differentiable_within_at.has_fderiv_within_at }
/-- 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 [mem_closure_iff_nhds_within_ne_bot] at h,
simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o]
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 :=
begin
simp [differentiable_within_at, has_fderiv_within_at, nhds_within_univ],
refl
end
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 ∈ nhds_within x s) :
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_within_at.differentiable_at
(h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x :=
begin
have : s = univ ∩ s, by rw univ_inter,
rwa [this, differentiable_within_at_inter hs, differentiable_within_at_univ] at h
end
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 _ (is_open_univ.unique_diff_within_at (mem_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
end fderiv_properties
section congr
/-! ### congr properties of the derivative -/
theorem has_fderiv_at_filter_congr_of_mem_sets
(hx : f₀ x = f₁ x) (h₀ : {x | f₀ x = f₁ x} ∈ L) (h₁ : ∀ x, f₀' x = f₁' x) :
has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L :=
by { rw (ext h₁), exact is_o_congr
(by filter_upwards [h₀] λ x (h : _ = _), by simp [h, hx])
(univ_mem_sets' $ λ _, rfl) }
lemma has_fderiv_at_filter.congr_of_mem_sets (h : has_fderiv_at_filter f f' x L)
(hL : {x | f₁ x = f x} ∈ L) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L :=
begin
apply (has_fderiv_at_filter_congr_of_mem_sets hx hL _).2 h,
exact λx, rfl
end
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_mem_sets (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx
lemma has_fderiv_within_at.congr_of_mem_nhds_within (h : has_fderiv_within_at f f' s x)
(h₁ : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x :=
has_fderiv_at_filter.congr_of_mem_sets h h₁ hx
lemma has_fderiv_at.congr_of_mem_nhds (h : has_fderiv_at f f' x)
(h₁ : {y | f₁ y = f y} ∈ 𝓝 x) : has_fderiv_at f₁ f' x :=
has_fderiv_at_filter.congr_of_mem_sets 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_mem_nhds_within
(h : differentiable_within_at 𝕜 f s x) (h₁ : {y | f₁ y = f y} ∈ nhds_within x s)
(hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x :=
(h.has_fderiv_within_at.congr_of_mem_nhds_within 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_at.congr_of_mem_nhds (h : differentiable_at 𝕜 f x)
(hL : {y | f₁ y = f y} ∈ 𝓝 x) : differentiable_at 𝕜 f₁ x :=
has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_mem_sets 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 fderiv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x)
(hL : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) :
fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x :=
begin
by_cases h : differentiable_within_at 𝕜 f s x ∨ differentiable_within_at 𝕜 f₁ s x,
{ cases h,
{ apply has_fderiv_within_at.fderiv_within _ hs,
exact has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at hL hx },
{ symmetry,
apply has_fderiv_within_at.fderiv_within _ hs,
apply has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at _ hx.symm,
convert hL,
ext y,
exact eq_comm } },
{ push_neg at h,
have A : fderiv_within 𝕜 f s x = 0,
by { unfold differentiable_within_at at h, simp [fderiv_within, h] },
have A₁ : fderiv_within 𝕜 f₁ s x = 0,
by { unfold differentiable_within_at at h, simp [fderiv_within, h] },
rw [A, A₁] }
end
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 fderiv_within_congr_of_mem_nhds_within hs _ hx,
apply mem_sets_of_superset self_mem_nhds_within,
exact hL
end
lemma fderiv_congr_of_mem_nhds (hL : {y | f₁ y = f y} ∈ 𝓝 x) :
fderiv 𝕜 f₁ x = fderiv 𝕜 f x :=
begin
have A : f₁ x = f x := (mem_of_nhds hL : _),
rw [← fderiv_within_univ, ← fderiv_within_univ],
rw ← nhds_within_univ at hL,
exact fderiv_within_congr_of_mem_nhds_within unique_diff_within_at_univ hL A
end
end congr
section id
/-! ### Derivative of the identity -/
theorem has_fderiv_at_filter_id (x : E) (L : filter E) :
has_fderiv_at_filter id (id : E →L[𝕜] 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 →L[𝕜] E) s x :=
has_fderiv_at_filter_id _ _
theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id : E →L[𝕜] E) x :=
has_fderiv_at_filter_id _ _
lemma differentiable_at_id : differentiable_at 𝕜 id 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
lemma differentiable_id : differentiable 𝕜 (id : E → E) :=
λx, differentiable_at_id
lemma differentiable_on_id : differentiable_on 𝕜 id s :=
differentiable_id.differentiable_on
lemma fderiv_id : fderiv 𝕜 id x = id :=
has_fderiv_at.fderiv (has_fderiv_at_id x)
lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 id s x = id :=
begin
rw differentiable_at.fderiv_within (differentiable_at_id) hxs,
exact fderiv_id
end
end id
section const
/-! ### derivative of a constant function -/
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 _ _ _
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 (c : F) : fderiv 𝕜 (λy, c) x = 0 :=
has_fderiv_at.fderiv (has_fderiv_at_const c x)
lemma fderiv_within_const (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 _
end
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. -/
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 :=
begin
have : (λ (x' : E), f x' - f x - h.to_continuous_linear_map (x' - x)) = λx', 0,
{ ext,
have : ∀a, h.to_continuous_linear_map a = f a := λa, rfl,
simp,
simp [this] },
rw [has_fderiv_at_filter, this],
exact asymptotics.is_o_zero _ _
end
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
lemma continuous_linear_map.has_fderiv_at_filter :
has_fderiv_at_filter e e x L :=
begin
have : (λ (x' : E), e x' - e x - e (x' - x)) = λx', 0, by { ext, simp },
rw [has_fderiv_at_filter, this],
exact asymptotics.is_o_zero _ _
end
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
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
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
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
end continuous_linear_map
section smul_const
/-! ### Derivative of a function multiplied by a constant -/
theorem has_fderiv_at_filter.smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) :
has_fderiv_at_filter (λ x, c • f x) (c • f') x L :=
(is_o_const_smul_left h c).congr_left $ λ x, by simp [smul_neg, smul_add]
theorem has_fderiv_within_at.smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) :
has_fderiv_within_at (λ x, c • f x) (c • f') s x :=
h.smul c
theorem has_fderiv_at.smul (h : has_fderiv_at f f' x) (c : 𝕜) :
has_fderiv_at (λ x, c • f x) (c • f') x :=
h.smul c
lemma differentiable_within_at.smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) :
differentiable_within_at 𝕜 (λy, c • f y) s x :=
(h.has_fderiv_within_at.smul c).differentiable_within_at
lemma differentiable_at.smul (h : differentiable_at 𝕜 f x) (c : 𝕜) :
differentiable_at 𝕜 (λy, c • f y) x :=
(h.has_fderiv_at.smul c).differentiable_at
lemma differentiable_on.smul (h : differentiable_on 𝕜 f s) (c : 𝕜) :
differentiable_on 𝕜 (λy, c • f y) s :=
λx hx, (h x hx).smul c
lemma differentiable.smul (h : differentiable 𝕜 f) (c : 𝕜) :
differentiable 𝕜 (λy, c • f y) :=
λx, (h x).smul c
lemma fderiv_within_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.smul c).fderiv_within hxs
lemma fderiv_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) :
fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x :=
(h.has_fderiv_at.smul c).fderiv
end smul_const
section add
/-! ### Derivative of the sum of two functions -/
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
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
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)
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
end add
section neg
/-! ### Derivative of the negative of a function -/
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 :=
(h.smul (-1:𝕜)).congr (by simp) (by simp)
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
lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) :
differentiable_at 𝕜 (λy, -f y) x :=
h.has_fderiv_at.neg.differentiable_at
lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) :
differentiable_on 𝕜 (λy, -f y) s :=
λx hx, (h x hx).neg
lemma differentiable.neg (h : differentiable 𝕜 f) :
differentiable 𝕜 (λy, -f y) :=
λx, (h x).neg
lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x)
(h : differentiable_within_at 𝕜 f s x) :
fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x :=
h.has_fderiv_within_at.neg.fderiv_within hxs
lemma fderiv_neg (h : differentiable_at 𝕜 f x) :
fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x :=
h.has_fderiv_at.neg.fderiv
end neg
section sub
/-! ### Derivative of the difference of two functions -/
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 :=
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
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)
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_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.to_is_O.congr_of_sub.2 (f'.is_O_sub _ _)
end sub
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_le_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 lattice.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
end continuous
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_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) :
has_fderiv_at b (h.deriv p) p :=
begin
have : (λ (x : E × F), b x - b p - (h.deriv p) (x - p)) = (λx, b (x.1 - p.1, x.2 - p.2)),
{ ext x,
delta is_bounded_bilinear_map.deriv,
change b x - b p - (b (p.1, x.2-p.2) + b (x.1-p.1, p.2))
= b (x.1 - p.1, x.2 - p.2),
have : b x = b (x.1, x.2), by { cases x, refl },
rw this,
have : b p = b (p.1, p.2), by { cases p, refl },
rw this,
simp only [h.map_sub_left, h.map_sub_right],
abel },
rw [has_fderiv_at, has_fderiv_at_filter, this],
rcases h.bound with ⟨C, Cpos, hC⟩,
have A : asymptotics.is_O (λx : E × F, b (x.1 - p.1, x.2 - p.2))
(λx, ∥x - p∥ * ∥x - p∥) (𝓝 p) :=
⟨C, Cpos, filter.univ_mem_sets' (λx, begin
simp only [mem_set_of_eq, norm_mul, norm_norm],
calc ∥b (x.1 - p.1, x.2 - p.2)∥ ≤ C * ∥x.1 - p.1∥ * ∥x.2 - p.2∥ : hC _ _
... ≤ C * ∥x-p∥ * ∥x-p∥ : by apply_rules [mul_le_mul, le_max_left, le_max_right, norm_nonneg,
le_of_lt Cpos, le_refl, mul_nonneg, norm_nonneg, norm_nonneg]
... = C * (∥x-p∥ * ∥x-p∥) : mul_assoc _ _ _ end)⟩,
have B : asymptotics.is_o (λ (x : E × F), ∥x - p∥ * ∥x - p∥)
(λx, 1 * ∥x - p∥) (𝓝 p),
{ apply asymptotics.is_o_mul_right _ (asymptotics.is_O_refl _ _),
rw [asymptotics.is_o_iff_tendsto],
{ simp only [div_one],
have : 0 = ∥p - p∥, by simp,
rw this,
have : continuous (λx, ∥x-p∥) :=
continuous_norm.comp (continuous_id.sub continuous_const),
exact this.tendsto p },
simp only [forall_prop_of_false, not_false_iff, one_ne_zero, forall_true_iff] },
simp only [one_mul, asymptotics.is_o_norm_right] at B,
exact A.trans_is_o B
end
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
section cartesian_product
/-! ### Derivative of the cartesian product of two functions -/
variables {f₂ : E → G} {f₂' : E →L[𝕜] G}
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)) (continuous_linear_map.prod f₁' f₂') x L :=
begin
have : (λ (x' : E), (f₁ x', f₂ x') - (f₁ x, f₂ x) - (continuous_linear_map.prod f₁' f₂') (x' -x)) =
(λ (x' : E), (f₁ x' - f₁ x - f₁' (x' - x), f₂ x' - f₂ x - f₂' (x' - x))) := rfl,
rw [has_fderiv_at_filter, this],
rw [asymptotics.is_o_prod_left],
exact ⟨hf₁, hf₂⟩
end
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)) (continuous_linear_map.prod f₁' 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
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)
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 =
continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 f₂ x) :=
has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at)
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 =
continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (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 cartesian_product
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 f).mono le_comap_map).trans_is_O hf.is_O_sub in
by { refine eq₂.tri (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 f).mono le_comap_map,
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₁.tri 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 (nhds_within x s)
≤ nhds_within (f x) (f '' s) : hf.continuous_within_at.tendsto_nhds_within_image
... ≤ nhds_within (f x) t : 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_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 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 : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) :
fderiv_within 𝕜 (g ∘ f) s x =
continuous_linear_map.comp (fderiv_within 𝕜 g t (f x)) (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 = continuous_linear_map.comp (fderiv 𝕜 g (f x)) (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 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)
end composition
section smul
/-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/
variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜}
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 :=
begin
have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul,
exact has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, f x)) (hc.prod hf)
end
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 :=
begin
have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul,
exact has_fderiv_at.comp x (this.has_fderiv_at (c x, f x)) (hc.prod hf)
end
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
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)
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
end smul
section mul
/-! ### Derivative of the product of two scalar-valued functions -/
set_option class.instance_max_depth 120
variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜}
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 :=
begin
have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul,
convert has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, d x)) (hc.prod hd),
ext z,
change c x * d' z + d x * c' z = c x * d' z + c' z * d x,
ring
end
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 :=
begin
have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul,
convert has_fderiv_at.comp x (this.has_fderiv_at (c x, d x)) (hc.prod hd),
ext z,
change c x * d' z + d x * c' z = c x * d' z + c' z * d x,
ring
end
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
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)
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
end mul
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 {G : Type*} [normed_group G] [normed_space ℝ G]
theorem has_fderiv_at_filter_real_equiv {f : E → F} {f' : E →L[ℝ] F} {x : E} {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'r (λ x', _),
have : ∥x' + -x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _),
simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this]
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.image_tangent_cone_subset {x : E} (h : has_fderiv_within_at f f' s x) :
f' '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (f '' s) (f x) :=
begin
rw image_subset_iff,
rintros v ⟨c, d, dtop, clim, cdlim⟩,
refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim 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' : closure (range f') = univ) :
unique_diff_within_at 𝕜 (f '' s) (f x) :=
begin
have A : ∀v ∈ tangent_cone_at 𝕜 s x, f' v ∈ tangent_cone_at 𝕜 (f '' s) (f x),
{ assume v hv,
have := h.image_tangent_cone_subset,
rw image_subset_iff at this,
exact this hv },
have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E),
f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F),
{ assume v hv,
apply submodule.span_induction hv,
{ exact λ w hw, submodule.subset_span (A w hw) },
{ simp },
{ assume w₁ w₂ hw₁ hw₂,
rw continuous_linear_map.map_add,
exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ },
{ assume a w hw,
rw continuous_linear_map.map_smul,
exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } },
rw [unique_diff_within_at, ← univ_subset_iff],
split,
show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2,
show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc
univ ⊆ closure (range f') : univ_subset_iff.2 h'
... = closure (f' '' univ) : by rw image_univ
... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1
... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) :
closure_mono (image_closure_subset_closure_image f'.cont)
... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure
... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) :
closure_mono (image_subset_iff.mpr B)
end
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 𝕜]
{𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
{E : Type*} [normed_group E] [normed_space 𝕜' E]
{F : Type*} [normed_group F] [normed_space 𝕜' F]
{f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E}
local attribute [instance] normed_space.restrict_scalars
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
|
6fa55911f48c9630f12742b2262a9217d8bce879 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/topology/algebra/module.lean | 5eb90c969a6ec738f3f46848e55ad0ce76753e6d | [
"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 | 58,232 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov
-/
import topology.algebra.ring
import topology.algebra.mul_action
import topology.uniform_space.uniform_embedding
import algebra.algebra.basic
import linear_algebra.projection
import linear_algebra.pi
/-!
# Theory of topological modules and continuous linear maps.
We use the class `has_continuous_smul` for topological (semi) modules and topological vector spaces.
In this file we define continuous linear maps, as linear maps between topological modules which are
continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is
denoted by `M →L[R] M₂`.
Continuous linear equivalences are denoted by `M ≃L[R] M₂`.
-/
open filter
open_locale topological_space big_operators
universes u v w u'
section
variables {R : Type*} {M : Type*}
[ring R] [topological_space R]
[topological_space M] [add_comm_group M]
[module R M] [has_continuous_smul R M]
/-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then
`⊤` is the only submodule of `M` with a nonempty interior.
This is the case, e.g., if `R` is a nondiscrete normed field. -/
lemma submodule.eq_top_of_nonempty_interior' [has_continuous_add M]
[ne_bot (𝓝[{x : R | is_unit x}] 0)]
(s : submodule R M) (hs : (interior (s:set M)).nonempty) :
s = ⊤ :=
begin
rcases hs with ⟨y, hy⟩,
refine (submodule.eq_top_iff'.2 $ λ x, _),
rw [mem_interior_iff_mem_nhds] at hy,
have : tendsto (λ c:R, y + c • x) (𝓝[{x : R | is_unit x}] 0) (𝓝 (y + (0:R) • x)),
from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul
tendsto_const_nhds),
rw [zero_smul, add_zero] at this,
rcases nonempty_of_mem_sets (inter_mem_sets (mem_map.1 (this hy)) self_mem_nhds_within)
with ⟨_, hu, u, rfl⟩,
have hy' : y ∈ ↑s := mem_of_mem_nhds hy,
exact (s.smul_mem_iff' _).1 ((s.add_mem_iff_right hy').1 hu)
end
end
section closure
variables {R : Type u} {M : Type v}
[semiring R] [topological_space R]
[topological_space M] [add_comm_monoid M]
[module R M] [has_continuous_smul R M]
lemma submodule.closure_smul_self_subset (s : submodule R M) :
(λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M)))
⊆ closure (s : set M) :=
calc
(λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M)))
= (λ p : R × M, p.1 • p.2) '' (closure ((set.univ : set R).prod s)) : by simp [closure_prod_eq]
... ⊆ closure ((λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod s)) :
image_closure_subset_closure_image continuous_smul
... = closure s : begin
congr,
ext x,
refine ⟨_, λ hx, ⟨⟨1, x⟩, ⟨set.mem_univ _, hx⟩, one_smul R _⟩⟩,
rintros ⟨⟨c, y⟩, ⟨hc, hy⟩, rfl⟩,
simp [s.smul_mem c hy]
end
lemma submodule.closure_smul_self_eq (s : submodule R M) :
(λ p : R × M, p.1 • p.2) '' ((set.univ : set R).prod (closure (s : set M)))
= closure (s : set M) :=
set.subset.antisymm s.closure_smul_self_subset
(λ x hx, ⟨⟨1, x⟩, ⟨set.mem_univ _, hx⟩, one_smul R _⟩)
variables [has_continuous_add M]
/-- The (topological-space) closure of a submodule of a topological `R`-module `M` is itself
a submodule. -/
def submodule.topological_closure (s : submodule R M) : submodule R M :=
{ carrier := closure (s : set M),
smul_mem' := λ c x hx, s.closure_smul_self_subset ⟨⟨c, x⟩, ⟨set.mem_univ _, hx⟩, rfl⟩,
..s.to_add_submonoid.topological_closure }
@[simp] lemma submodule.topological_closure_coe (s : submodule R M) :
(s.topological_closure : set M) = closure (s : set M) :=
rfl
instance submodule.topological_closure_has_continuous_smul (s : submodule R M) :
has_continuous_smul R (s.topological_closure) :=
{ continuous_smul :=
begin
apply continuous_induced_rng,
change continuous (λ p : R × s.topological_closure, p.1 • (p.2 : M)),
continuity,
end,
..s.to_add_submonoid.topological_closure_has_continuous_add }
lemma submodule.submodule_topological_closure (s : submodule R M) :
s ≤ s.topological_closure :=
subset_closure
lemma submodule.is_closed_topological_closure (s : submodule R M) :
is_closed (s.topological_closure : set M) :=
by convert is_closed_closure
lemma submodule.topological_closure_minimal
(s : submodule R M) {t : submodule R M} (h : s ≤ t) (ht : is_closed (t : set M)) :
s.topological_closure ≤ t :=
closure_minimal h ht
lemma submodule.topological_closure_mono {s : submodule R M} {t : submodule R M} (h : s ≤ t) :
s.topological_closure ≤ t.topological_closure :=
s.topological_closure_minimal (h.trans t.submodule_topological_closure)
t.is_closed_topological_closure
end closure
/-- Continuous linear maps between modules. We only put the type classes that are necessary for the
definition, although in applications `M` and `M₂` will be topological modules over the topological
ring `R`. -/
structure continuous_linear_map
(R : Type*) [semiring R]
(M : Type*) [topological_space M] [add_comm_monoid M]
(M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂]
[module R M] [module R M₂]
extends linear_map R M M₂ :=
(cont : continuous to_fun . tactic.interactive.continuity')
notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map R M M₂
/-- Continuous linear equivalences between modules. We only put the type classes that are necessary
for the definition, although in applications `M` and `M₂` will be topological modules over the
topological ring `R`. -/
@[nolint has_inhabited_instance]
structure continuous_linear_equiv
(R : Type*) [semiring R]
(M : Type*) [topological_space M] [add_comm_monoid M]
(M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂]
[module R M] [module R M₂]
extends linear_equiv R M M₂ :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂
namespace continuous_linear_map
section semiring
/-!
### Properties that hold for non-necessarily commutative semirings.
-/
variables
{R : Type*} [semiring R]
{M : Type*} [topological_space M] [add_comm_monoid M]
{M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄]
[module R M] [module R M₂] [module R M₃] [module R M₄]
/-- Coerce continuous linear maps to linear maps. -/
instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩
-- make the coercion the preferred form
@[simp] lemma to_linear_map_eq_coe (f : M →L[R] M₂) : f.to_linear_map = f := rfl
/-- Coerce continuous linear maps to functions. -/
-- see Note [function coercion]
instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨λ _, M → M₂, λ f, f⟩
@[simp] lemma coe_mk (f : M →ₗ[R] M₂) (h) : (mk f h : M →ₗ[R] M₂) = f := rfl
@[simp] lemma coe_mk' (f : M →ₗ[R] M₂) (h) : (mk f h : M → M₂) = f := rfl
@[continuity]
protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2
theorem coe_injective : function.injective (coe : (M →L[R] M₂) → (M →ₗ[R] M₂)) :=
by { intros f g H, cases f, cases g, congr' }
@[simp, norm_cast] lemma coe_inj {f g : M →L[R] M₂} :
(f : M →ₗ[R] M₂) = g ↔ f = g :=
coe_injective.eq_iff
theorem coe_fn_injective : function.injective (λ f : M →L[R] M₂, show M → M₂, from f) :=
linear_map.coe_injective.comp coe_injective
@[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g :=
coe_fn_injective $ funext h
theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, by rw h, by ext⟩
variables (f g : M →L[R] M₂) (c : R) (h : M₂ →L[R] M₃) (x y z : M)
-- make some straightforward lemmas available to `simp`.
@[simp] lemma map_zero : f (0 : M) = 0 := (to_linear_map _).map_zero
@[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _
@[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _
@[simp, priority 900]
lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M]
[module S M] [has_scalar R M₂] [module S M₂]
[linear_map.compatible_smul M M₂ R S] (f : M →L[S] M₂) (c : R) (x : M) :
f (c • x) = c • f x :=
linear_map.compatible_smul.map_smul f c x
lemma map_sum {ι : Type*} (s : finset ι) (g : ι → M) :
f (∑ i in s, g i) = ∑ i in s, f (g i) := f.to_linear_map.map_sum
@[simp, norm_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl
@[ext] theorem ext_ring [topological_space R] {f g : R →L[R] M} (h : f 1 = g 1) : f = g :=
coe_inj.1 $ linear_map.ext_ring h
theorem ext_ring_iff [topological_space R] {f g : R →L[R] M} : f = g ↔ f 1 = g 1 :=
⟨λ h, h ▸ rfl, ext_ring⟩
/-- If two continuous linear maps are equal on a set `s`, then they are equal on the closure
of the `submodule.span` of this set. -/
lemma eq_on_closure_span [t2_space M₂] {s : set M} {f g : M →L[R] M₂} (h : set.eq_on f g s) :
set.eq_on f g (closure (submodule.span R s : set M)) :=
(linear_map.eq_on_span' h).closure f.continuous g.continuous
/-- If the submodule generated by a set `s` is dense in the ambient module, then two continuous
linear maps equal on `s` are equal. -/
lemma ext_on [t2_space M₂] {s : set M} (hs : dense (submodule.span R s : set M)) {f g : M →L[R] M₂}
(h : set.eq_on f g s) :
f = g :=
ext $ λ x, eq_on_closure_span h (hs x)
/-- Under a continuous linear map, the image of the `topological_closure` of a submodule is
contained in the `topological_closure` of its image. -/
lemma _root_.submodule.topological_closure_map [topological_space R] [has_continuous_smul R M]
[has_continuous_add M] [has_continuous_smul R M₂] [has_continuous_add M₂] (f : M →L[R] M₂)
(s : submodule R M) :
(s.topological_closure.map f.to_linear_map) ≤ (s.map f.to_linear_map).topological_closure :=
image_closure_subset_closure_image f.continuous
/-- The continuous map that is constantly zero. -/
instance: has_zero (M →L[R] M₂) := ⟨⟨0, continuous_zero⟩⟩
instance : inhabited (M →L[R] M₂) := ⟨0⟩
@[simp] lemma default_def : default (M →L[R] M₂) = 0 := rfl
@[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl
@[simp, norm_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] M₂) = 0 := rfl
/- no simp attribute on the next line as simp does not always simplify `0 x` to `0`
when `0` is the zero function, while it does for the zero continuous linear map,
and this is the most important property we care about. -/
@[norm_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl
instance unique_of_left [subsingleton M] : unique (M →L[R] M₂) :=
coe_injective.unique
instance unique_of_right [subsingleton M₂] : unique (M →L[R] M₂) :=
coe_injective.unique
section
variables (R M)
/-- the identity map as a continuous linear map. -/
def id : M →L[R] M :=
⟨linear_map.id, continuous_id⟩
end
instance : has_one (M →L[R] M) := ⟨id R M⟩
lemma one_def : (1 : M →L[R] M) = id R M := rfl
lemma id_apply : id R M x = x := rfl
@[simp, norm_cast] lemma coe_id : (id R M : M →ₗ[R] M) = linear_map.id := rfl
@[simp, norm_cast] lemma coe_id' : (id R M : M → M) = _root_.id := rfl
@[simp, norm_cast] lemma coe_eq_id {f : M →L[R] M} :
(f : M →ₗ[R] M) = linear_map.id ↔ f = id _ _ :=
by rw [← coe_id, coe_inj]
@[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl
section add
variables [has_continuous_add M₂]
instance : has_add (M →L[R] M₂) :=
⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩
lemma continuous_nsmul (n : ℕ) : continuous (λ (x : M₂), n • x) :=
begin
induction n with n ih,
{ simp [continuous_const] },
{ simp [nat.succ_eq_add_one, add_smul], exact ih.add continuous_id }
end
@[continuity]
lemma continuous.nsmul {α : Type*} [topological_space α] {n : ℕ} {f : α → M₂} (hf : continuous f) :
continuous (λ (x : α), n • (f x)) :=
(continuous_nsmul n).comp hf
@[simp] lemma add_apply : (f + g) x = f x + g x := rfl
@[simp, norm_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = f + g := rfl
@[norm_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl
instance : add_comm_monoid (M →L[R] M₂) :=
{ zero := (0 : M →L[R] M₂),
add := (+),
zero_add := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm],
add_zero := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm],
add_comm := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm],
add_assoc := by intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm],
nsmul := λ n f,
{ to_fun := λ x, n • (f x),
map_add' := by simp,
map_smul' := by simp [smul_comm n] },
nsmul_zero' := λ f, by { ext, simp },
nsmul_succ' := λ n f, by { ext, simp [nat.succ_eq_one_add, add_smul], } }
@[simp, norm_cast] lemma coe_sum {ι : Type*} (t : finset ι) (f : ι → M →L[R] M₂) :
↑(∑ d in t, f d) = (∑ d in t, f d : M →ₗ[R] M₂) :=
(add_monoid_hom.mk (coe : (M →L[R] M₂) → (M →ₗ[R] M₂)) rfl (λ _ _, rfl)).map_sum _ _
@[simp, norm_cast] lemma coe_sum' {ι : Type*} (t : finset ι) (f : ι → M →L[R] M₂) :
⇑(∑ d in t, f d) = ∑ d in t, f d :=
by simp only [← coe_coe, coe_sum, linear_map.coe_fn_sum]
lemma sum_apply {ι : Type*} (t : finset ι) (f : ι → M →L[R] M₂) (b : M) :
(∑ d in t, f d) b = ∑ d in t, f d b :=
by simp only [coe_sum', finset.sum_apply]
end add
/-- Composition of bounded linear maps. -/
def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ :=
⟨(g : M₂ →ₗ[R] M₃).comp f, g.2.comp f.2⟩
@[simp, norm_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl
@[simp, norm_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl
@[simp] theorem comp_id : f.comp (id R M) = f :=
ext $ λ x, rfl
@[simp] theorem id_comp : (id R M₂).comp f = f :=
ext $ λ x, rfl
@[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 :=
by { ext, simp }
@[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 :=
by { ext, simp }
@[simp] lemma comp_add [has_continuous_add M₂] [has_continuous_add M₃]
(g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) :
g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ :=
by { ext, simp }
@[simp] lemma add_comp [has_continuous_add M₃]
(g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) :
(g₁ + g₂).comp f = g₁.comp f + g₂.comp f :=
by { ext, simp }
theorem comp_assoc (h : M₃ →L[R] M₄) (g : M₂ →L[R] M₃) (f : M →L[R] M₂) :
(h.comp g).comp f = h.comp (g.comp f) :=
rfl
instance : has_mul (M →L[R] M) := ⟨comp⟩
lemma mul_def (f g : M →L[R] M) : f * g = f.comp g := rfl
@[simp] lemma coe_mul (f g : M →L[R] M) : ⇑(f * g) = f ∘ g := rfl
lemma mul_apply (f g : M →L[R] M) (x : M) : (f * g) x = f (g x) := rfl
/-- The cartesian product of two bounded linear maps, as a bounded linear map. -/
protected def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) :=
⟨(f₁ : M →ₗ[R] M₂).prod f₂, f₁.2.prod_mk f₂.2⟩
@[simp, norm_cast] lemma coe_prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) :
(f₁.prod f₂ : M →ₗ[R] M₂ × M₃) = linear_map.prod f₁ f₂ :=
rfl
@[simp, norm_cast] lemma prod_apply (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) (x : M) :
f₁.prod f₂ x = (f₁ x, f₂ x) :=
rfl
section
variables (R M M₂)
/-- The left injection into a product is a continuous linear map. -/
def inl : M →L[R] M × M₂ := (id R M).prod 0
/-- The right injection into a product is a continuous linear map. -/
def inr : M₂ →L[R] M × M₂ := (0 : M₂ →L[R] M).prod (id R M₂)
end
@[simp] lemma inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl
@[simp] lemma inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl
@[simp, norm_cast] lemma coe_inl : (inl R M M₂ : M →ₗ[R] M × M₂) = linear_map.inl R M M₂ := rfl
@[simp, norm_cast] lemma coe_inr : (inr R M M₂ : M₂ →ₗ[R] M × M₂) = linear_map.inr R M M₂ := rfl
/-- Kernel of a continuous linear map. -/
def ker (f : M →L[R] M₂) : submodule R M := (f : M →ₗ[R] M₂).ker
@[norm_cast] lemma ker_coe : (f : M →ₗ[R] M₂).ker = f.ker := rfl
@[simp] lemma mem_ker {f : M →L[R] M₂} {x} : x ∈ f.ker ↔ f x = 0 := linear_map.mem_ker
lemma is_closed_ker [t1_space M₂] : is_closed (f.ker : set M) :=
continuous_iff_is_closed.1 f.cont _ is_closed_singleton
@[simp] lemma apply_ker (x : f.ker) : f x = 0 := mem_ker.1 x.2
lemma is_complete_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M']
[module R M'] [t1_space M₂] (f : M' →L[R] M₂) :
is_complete (f.ker : set M') :=
f.is_closed_ker.is_complete
instance complete_space_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M']
[module R M'] [t1_space M₂] (f : M' →L[R] M₂) :
complete_space f.ker :=
f.is_closed_ker.complete_space_coe
@[simp] lemma ker_prod (f : M →L[R] M₂) (g : M →L[R] M₃) :
ker (f.prod g) = ker f ⊓ ker g :=
linear_map.ker_prod f g
/-- Range of a continuous linear map. -/
def range (f : M →L[R] M₂) : submodule R M₂ := (f : M →ₗ[R] M₂).range
lemma range_coe : (f.range : set M₂) = set.range f := linear_map.range_coe _
lemma mem_range {f : M →L[R] M₂} {y} : y ∈ f.range ↔ ∃ x, f x = y := linear_map.mem_range
lemma mem_range_self (f : M →L[R] M₂) (x : M) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩
lemma range_prod_le (f : M →L[R] M₂) (g : M →L[R] M₃) :
range (f.prod g) ≤ (range f).prod (range g) :=
(f : M →ₗ[R] M₂).range_prod_le g
/-- Restrict codomain of a continuous linear map. -/
def cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) :
M →L[R] p :=
{ cont := continuous_subtype_mk h f.continuous,
to_linear_map := (f : M →ₗ[R] M₂).cod_restrict p h}
@[norm_cast] lemma coe_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) :
(f.cod_restrict p h : M →ₗ[R] p) = (f : M →ₗ[R] M₂).cod_restrict p h :=
rfl
@[simp] lemma coe_cod_restrict_apply (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) (x) :
(f.cod_restrict p h x : M₂) = f x :=
rfl
@[simp] lemma ker_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) :
ker (f.cod_restrict p h) = ker f :=
(f : M →ₗ[R] M₂).ker_cod_restrict p h
/-- Embedding of a submodule into the ambient space as a continuous linear map. -/
def subtype_val (p : submodule R M) : p →L[R] M :=
{ cont := continuous_subtype_val,
to_linear_map := p.subtype }
@[simp, norm_cast] lemma coe_subtype_val (p : submodule R M) :
(subtype_val p : p →ₗ[R] M) = p.subtype :=
rfl
@[simp, norm_cast] lemma subtype_val_apply (p : submodule R M) (x : p) :
(subtype_val p : p → M) x = x :=
rfl
variables (R M M₂)
/-- `prod.fst` as a `continuous_linear_map`. -/
def fst : M × M₂ →L[R] M :=
{ cont := continuous_fst, to_linear_map := linear_map.fst R M M₂ }
/-- `prod.snd` as a `continuous_linear_map`. -/
def snd : M × M₂ →L[R] M₂ :=
{ cont := continuous_snd, to_linear_map := linear_map.snd R M M₂ }
variables {R M M₂}
@[simp, norm_cast] lemma coe_fst : (fst R M M₂ : M × M₂ →ₗ[R] M) = linear_map.fst R M M₂ := rfl
@[simp, norm_cast] lemma coe_fst' : (fst R M M₂ : M × M₂ → M) = prod.fst := rfl
@[simp, norm_cast] lemma coe_snd : (snd R M M₂ : M × M₂ →ₗ[R] M₂) = linear_map.snd R M M₂ := rfl
@[simp, norm_cast] lemma coe_snd' : (snd R M M₂ : M × M₂ → M₂) = prod.snd := rfl
@[simp] lemma fst_prod_snd : (fst R M M₂).prod (snd R M M₂) = id R (M × M₂) := ext $ λ ⟨x, y⟩, rfl
@[simp] lemma fst_comp_prod (f : M →L[R] M₂) (g : M →L[R] M₃) :
(fst R M₂ M₃).comp (f.prod g) = f :=
ext $ λ x, rfl
@[simp] lemma snd_comp_prod (f : M →L[R] M₂) (g : M →L[R] M₃) :
(snd R M₂ M₃).comp (f.prod g) = g :=
ext $ λ x, rfl
/-- `prod.map` of two continuous linear maps. -/
def prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : (M × M₃) →L[R] (M₂ × M₄) :=
(f₁.comp (fst R M M₃)).prod (f₂.comp (snd R M M₃))
@[simp, norm_cast] lemma coe_prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) :
(f₁.prod_map f₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = ((f₁ : M →ₗ[R] M₂).prod_map (f₂ : M₃ →ₗ[R] M₄)) :=
rfl
@[simp, norm_cast] lemma coe_prod_map' (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) :
⇑(f₁.prod_map f₂) = prod.map f₁ f₂ :=
rfl
/-- The continuous linear map given by `(x, y) ↦ f₁ x + f₂ y`. -/
def coprod [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) :
(M × M₂) →L[R] M₃ :=
⟨linear_map.coprod f₁ f₂, (f₁.cont.comp continuous_fst).add (f₂.cont.comp continuous_snd)⟩
@[norm_cast, simp] lemma coe_coprod [has_continuous_add M₃]
(f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) :
(f₁.coprod f₂ : (M × M₂) →ₗ[R] M₃) = linear_map.coprod f₁ f₂ :=
rfl
@[simp] lemma coprod_apply [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) (x) :
f₁.coprod f₂ x = f₁ x.1 + f₂ x.2 := rfl
lemma range_coprod [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) :
(f₁.coprod f₂).range = f₁.range ⊔ f₂.range :=
linear_map.range_coprod _ _
section
variables {S : Type*} [semiring S] [module R S] [module S M₂] [is_scalar_tower R S M₂]
[topological_space S] [has_continuous_smul S M₂]
/-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of
`M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`).
See also `continuous_linear_map.smul_rightₗ` and `continuous_linear_map.smul_rightL`. -/
def smul_right (c : M →L[R] S) (f : M₂) : M →L[R] M₂ :=
{ cont := c.2.smul continuous_const,
..c.to_linear_map.smul_right f }
@[simp]
lemma smul_right_apply {c : M →L[R] S} {f : M₂} {x : M} :
(smul_right c f : M → M₂) x = c x • f :=
rfl
end
variables [topological_space R] [has_continuous_smul R M₂]
@[simp]
lemma smul_right_one_one (c : R →L[R] M₂) : smul_right (1 : R →L[R] R) (c 1) = c :=
by ext; simp [← continuous_linear_map.map_smul_of_tower]
@[simp]
lemma smul_right_one_eq_iff {f f' : M₂} :
smul_right (1 : R →L[R] R) f = smul_right (1 : R →L[R] R) f' ↔ f = f' :=
by simp only [ext_ring_iff, smul_right_apply, one_apply, one_smul]
lemma smul_right_comp [has_continuous_mul R] {x : M₂} {c : R} :
(smul_right (1 : R →L[R] R) x).comp (smul_right (1 : R →L[R] R) c) =
smul_right (1 : R →L[R] R) (c • x) :=
by { ext, simp [mul_smul] }
end semiring
section pi
variables
{R : Type*} [semiring R]
{M : Type*} [topological_space M] [add_comm_monoid M] [module R M]
{M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [module R M₂]
{ι : Type*} {φ : ι → Type*} [∀i, topological_space (φ i)] [∀i, add_comm_monoid (φ i)]
[∀i, module R (φ i)]
/-- `pi` construction for continuous linear functions. From a family of continuous linear functions
it produces a continuous linear function into a family of topological modules. -/
def pi (f : Πi, M →L[R] φ i) : M →L[R] (Πi, φ i) :=
⟨linear_map.pi (λ i, f i), continuous_pi (λ i, (f i).continuous)⟩
@[simp] lemma coe_pi' (f : Π i, M →L[R] φ i) : ⇑(pi f) = λ c i, f i c := rfl
@[simp] lemma coe_pi (f : Π i, M →L[R] φ i) :
(pi f : M →ₗ[R] Π i, φ i) = linear_map.pi (λ i, f i) :=
rfl
lemma pi_apply (f : Πi, M →L[R] φ i) (c : M) (i : ι) :
pi f c i = f i c := rfl
lemma pi_eq_zero (f : Πi, M →L[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) :=
by { simp only [ext_iff, pi_apply, function.funext_iff], exact forall_swap }
lemma pi_zero : pi (λi, 0 : Πi, M →L[R] φ i) = 0 := ext $ λ _, rfl
lemma pi_comp (f : Πi, M →L[R] φ i) (g : M₂ →L[R] M) : (pi f).comp g = pi (λi, (f i).comp g) := rfl
/-- The projections from a family of topological modules are continuous linear maps. -/
def proj (i : ι) : (Πi, φ i) →L[R] φ i :=
⟨linear_map.proj i, continuous_apply _⟩
@[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →L[R] φ i) b = b i := rfl
lemma proj_pi (f : Πi, M₂ →L[R] φ i) (i : ι) : (proj i).comp (pi f) = f i :=
ext $ assume c, rfl
lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ :=
linear_map.infi_ker_proj
variables (R φ)
/-- If `I` and `J` are complementary index sets, the product of the kernels of the `J`th projections
of `φ` is linearly equivalent to the product over `I`. -/
def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)]
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) :
(⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃L[R] (Πi:I, φ i) :=
⟨ linear_map.infi_ker_proj_equiv R φ hd hu,
continuous_pi (λ i, begin
have := @continuous_subtype_coe _ _ (λ x, x ∈ (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i))),
have := continuous.comp (by exact continuous_apply i) this,
exact this
end),
continuous_subtype_mk _ (continuous_pi (λ i, begin
dsimp, split_ifs; [apply continuous_apply, exact continuous_zero]
end)) ⟩
end pi
section ring
variables
{R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_group M₄]
[module R M] [module R M₂] [module R M₃] [module R M₄]
variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M)
@[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _
@[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _
@[simp] lemma sub_apply' (x : M) : ((f : M →ₗ[R] M₂) - g) x = f x - g x := rfl
lemma range_prod_eq {f : M →L[R] M₂} {g : M →L[R] M₃} (h : ker f ⊔ ker g = ⊤) :
range (f.prod g) = (range f).prod (range g) :=
linear_map.range_prod_eq h
lemma ker_prod_ker_le_ker_coprod [has_continuous_add M₃]
(f : M →L[R] M₃) (g : M₂ →L[R] M₃) :
(ker f).prod (ker g) ≤ ker (f.coprod g) :=
linear_map.ker_prod_ker_le_ker_coprod f.to_linear_map g.to_linear_map
lemma ker_coprod_of_disjoint_range [has_continuous_add M₃]
(f : M →L[R] M₃) (g : M₂ →L[R] M₃) (hd : disjoint f.range g.range) :
ker (f.coprod g) = (ker f).prod (ker g) :=
linear_map.ker_coprod_of_disjoint_range f.to_linear_map g.to_linear_map hd
section
variables [topological_add_group M₂]
instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩
@[simp] lemma neg_apply : (-f) x = - (f x) := rfl
@[simp, norm_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl
@[norm_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl
instance : has_sub (M →L[R] M₂) := ⟨λ f g, ⟨f - g, f.2.sub g.2⟩⟩
lemma continuous_gsmul : ∀ (n : ℤ), continuous (λ (x : M₂), n • x)
| (n : ℕ) := by { simp only [gsmul_coe_nat], exact continuous_nsmul _ }
| -[1+ n] := by { simp only [gsmul_neg_succ_of_nat], exact (continuous_nsmul _).neg }
@[continuity]
lemma continuous.gsmul {α : Type*} [topological_space α] {n : ℤ} {f : α → M₂} (hf : continuous f) :
continuous (λ (x : α), n • (f x)) :=
(continuous_gsmul n).comp hf
instance : add_comm_group (M →L[R] M₂) :=
by refine
{ zero := 0,
add := (+),
neg := has_neg.neg,
sub := has_sub.sub,
sub_eq_add_neg := _,
nsmul := λ n f,
{ to_fun := λ x, n • (f x),
map_add' := by simp,
map_smul' := by simp [smul_comm n] },
gsmul := λ n f,
{ to_fun := λ x, n • (f x),
map_add' := by simp,
map_smul' := by simp [smul_comm n] },
gsmul_zero' := λ f, by { ext, simp },
gsmul_succ' := λ n f, by { ext, simp [add_smul, add_comm] },
gsmul_neg' := λ n f, by { ext, simp [nat.succ_eq_add_one, add_smul], },
.. continuous_linear_map.add_comm_monoid, .. };
intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm, sub_eq_add_neg]
lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl
@[simp, norm_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = f - g := rfl
@[simp, norm_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl
end
instance [topological_add_group M] : ring (M →L[R] M) :=
{ mul := (*),
one := 1,
mul_one := λ _, ext $ λ _, rfl,
one_mul := λ _, ext $ λ _, rfl,
mul_assoc := λ _ _ _, ext $ λ _, rfl,
left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _,
right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _,
..continuous_linear_map.add_comm_group }
lemma smul_right_one_pow [topological_space R] [topological_ring R] (c : R) (n : ℕ) :
(smul_right (1 : R →L[R] R) c)^n = smul_right (1 : R →L[R] R) (c^n) :=
begin
induction n with n ihn,
{ ext, simp },
{ rw [pow_succ, ihn, mul_def, smul_right_comp, smul_eq_mul, pow_succ'] }
end
/-- Given a right inverse `f₂ : M₂ →L[R] M` to `f₁ : M →L[R] M₂`,
`proj_ker_of_right_inverse f₁ f₂ h` is the projection `M →L[R] f₁.ker` along `f₂.range`. -/
def proj_ker_of_right_inverse [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) :
M →L[R] f₁.ker :=
(id R M - f₂.comp f₁).cod_restrict f₁.ker $ λ x, by simp [h (f₁ x)]
@[simp] lemma coe_proj_ker_of_right_inverse_apply [topological_add_group M]
(f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) :
(f₁.proj_ker_of_right_inverse f₂ h x : M) = x - f₂ (f₁ x) :=
rfl
@[simp] lemma proj_ker_of_right_inverse_apply_idem [topological_add_group M]
(f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : f₁.ker) :
f₁.proj_ker_of_right_inverse f₂ h x = x :=
subtype.ext_iff_val.2 $ by simp
@[simp] lemma proj_ker_of_right_inverse_comp_inv [topological_add_group M]
(f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂) :
f₁.proj_ker_of_right_inverse f₂ h (f₂ y) = 0 :=
subtype.ext_iff_val.2 $ by simp [h y]
end ring
section smul
variables {R S : Type*} [ring R] [ring S] [topological_space S]
{M : Type*} [topological_space M] [add_comm_group M] [module R M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M₃]
[module S M₃] [smul_comm_class R S M₃] [has_continuous_smul S M₃]
instance : has_scalar S (M →L[R] M₃) :=
⟨λ c f, ⟨c • f, (continuous_const.smul f.2 : continuous (λ x, c • f x))⟩⟩
variables (c : S) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M)
@[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl
variables [module S M₂] [has_continuous_smul S M₂] [smul_comm_class R S M₂]
lemma smul_apply : (c • f) x = c • (f x) := rfl
@[simp, norm_cast] lemma coe_smul : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • f := rfl
@[simp, norm_cast] lemma coe_smul' : (((c • f) : M →L[R] M₂) : M → M₂) = c • f := rfl
@[simp] lemma comp_smul [linear_map.compatible_smul M₂ M₃ S R] : h.comp (c • f) = c • (h.comp f) :=
by { ext x, exact h.map_smul_of_tower c (f x) }
/-- `continuous_linear_map.prod` as an `equiv`. -/
@[simps apply] def prod_equiv : ((M →L[R] M₂) × (M →L[R] M₃)) ≃ (M →L[R] M₂ × M₃) :=
{ to_fun := λ f, f.1.prod f.2,
inv_fun := λ f, ⟨(fst _ _ _).comp f, (snd _ _ _).comp f⟩,
left_inv := λ f, by ext; refl,
right_inv := λ f, by ext; refl }
lemma prod_ext_iff {f g : M × M₂ →L[R] M₃} :
f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) :=
by { simp only [← coe_inj, linear_map.prod_ext_iff], refl }
@[ext] lemma prod_ext {f g : M × M₂ →L[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _))
(hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g :=
prod_ext_iff.2 ⟨hl, hr⟩
variables [has_continuous_add M₂]
instance : module S (M →L[R] M₂) :=
{ smul_zero := λ _, ext $ λ _, smul_zero _,
zero_smul := λ _, ext $ λ _, zero_smul _ _,
one_smul := λ _, ext $ λ _, by exact one_smul _ _,
mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _,
add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _,
smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ }
variables (S) [has_continuous_add M₃]
/-- `continuous_linear_map.prod` as a `linear_equiv`. -/
@[simps apply] def prodₗ : ((M →L[R] M₂) × (M →L[R] M₃)) ≃ₗ[S] (M →L[R] M₂ × M₃) :=
{ map_add' := λ f g, rfl,
map_smul' := λ c f, rfl,
.. prod_equiv }
end smul
section smul_rightₗ
variables {R S T M M₂ : Type*} [ring R] [ring S] [ring T] [module R S]
[add_comm_group M₂] [module R M₂] [module S M₂] [is_scalar_tower R S M₂]
[topological_space S] [topological_space M₂] [has_continuous_smul S M₂]
[topological_space M] [add_comm_group M] [module R M] [topological_add_group M₂]
[topological_space T] [module T M₂] [has_continuous_smul T M₂]
[smul_comm_class R T M₂] [smul_comm_class S T M₂]
/-- Given `c : E →L[𝕜] 𝕜`, `c.smul_rightₗ` is the linear map from `F` to `E →L[𝕜] F`
sending `f` to `λ e, c e • f`. See also `continuous_linear_map.smul_rightL`. -/
def smul_rightₗ (c : M →L[R] S) : M₂ →ₗ[T] (M →L[R] M₂) :=
{ to_fun := c.smul_right,
map_add' := λ x y, by { ext e, apply smul_add },
map_smul' := λ a x, by { ext e, dsimp, apply smul_comm } }
@[simp] lemma coe_smul_rightₗ (c : M →L[R] S) :
⇑(smul_rightₗ c : M₂ →ₗ[T] (M →L[R] M₂)) = c.smul_right := rfl
end smul_rightₗ
section comm_ring
variables
{R : Type*} [comm_ring R] [topological_space R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
[module R M] [module R M₂] [module R M₃] [has_continuous_smul R M₃]
variables [topological_add_group M₂] [has_continuous_smul R M₂]
instance : algebra R (M₂ →L[R] M₂) :=
algebra.of_module smul_comp (λ _ _ _, comp_smul _ _ _)
end comm_ring
section restrict_scalars
variables {A M M₂ : Type*} [ring A] [add_comm_group M] [add_comm_group M₂]
[module A M] [module A M₂] [topological_space M] [topological_space M₂]
(R : Type*) [ring R] [module R M] [module R M₂] [linear_map.compatible_smul M M₂ R A]
/-- If `A` is an `R`-algebra, then a continuous `A`-linear map can be interpreted as a continuous
`R`-linear map. We assume `linear_map.compatible_smul M M₂ R A` to match assumptions of
`linear_map.map_smul_of_tower`. -/
def restrict_scalars (f : M →L[A] M₂) : M →L[R] M₂ :=
⟨(f : M →ₗ[A] M₂).restrict_scalars R, f.continuous⟩
variable {R}
@[simp, norm_cast] lemma coe_restrict_scalars (f : M →L[A] M₂) :
(f.restrict_scalars R : M →ₗ[R] M₂) = (f : M →ₗ[A] M₂).restrict_scalars R := rfl
@[simp] lemma coe_restrict_scalars' (f : M →L[A] M₂) : ⇑(f.restrict_scalars R) = f := rfl
@[simp] lemma restrict_scalars_zero : (0 : M →L[A] M₂).restrict_scalars R = 0 := rfl
section
variable [topological_add_group M₂]
@[simp] lemma restrict_scalars_add (f g : M →L[A] M₂) :
(f + g).restrict_scalars R = f.restrict_scalars R + g.restrict_scalars R := rfl
@[simp] lemma restrict_scalars_neg (f : M →L[A] M₂) :
(-f).restrict_scalars R = -f.restrict_scalars R := rfl
end
variables {S : Type*} [ring S] [topological_space S] [module S M₂] [has_continuous_smul S M₂]
[smul_comm_class A S M₂] [smul_comm_class R S M₂]
@[simp] lemma restrict_scalars_smul (c : S) (f : M →L[A] M₂) :
(c • f).restrict_scalars R = c • f.restrict_scalars R := rfl
variables (A M M₂ R S) [topological_add_group M₂]
/-- `continuous_linear_map.restrict_scalars` as a `linear_map`. See also
`continuous_linear_map.restrict_scalarsL`. -/
def restrict_scalarsₗ : (M →L[A] M₂) →ₗ[S] (M →L[R] M₂) :=
{ to_fun := restrict_scalars R,
map_add' := restrict_scalars_add,
map_smul' := restrict_scalars_smul }
variables {A M M₂ R S}
@[simp] lemma coe_restrict_scalarsₗ : ⇑(restrict_scalarsₗ A M M₂ R S) = restrict_scalars R := rfl
end restrict_scalars
end continuous_linear_map
namespace continuous_linear_equiv
section add_comm_monoid
variables {R : Type*} [semiring R]
{M : Type*} [topological_space M] [add_comm_monoid M]
{M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄]
[module R M] [module R M₂] [module R M₃] [module R M₄]
/-- A continuous linear equivalence induces a continuous linear map. -/
def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] M₂ :=
{ cont := e.continuous_to_fun,
..e.to_linear_equiv.to_linear_map }
/-- Coerce continuous linear equivs to continuous linear maps. -/
instance : has_coe (M ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩
/-- Coerce continuous linear equivs to maps. -/
-- see Note [function coercion]
instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨λ _, M → M₂, λ f, f⟩
@[simp] theorem coe_def_rev (e : M ≃L[R] M₂) : e.to_continuous_linear_map = e := rfl
theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl
@[simp] lemma coe_to_linear_equiv (f : M ≃L[R] M₂) : ⇑f.to_linear_equiv = f := rfl
@[simp, norm_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl
lemma to_linear_equiv_injective : function.injective (to_linear_equiv : (M ≃L[R] M₂) → (M ≃ₗ[R] M₂))
| ⟨e, _, _⟩ ⟨e', _, _⟩ rfl := rfl
@[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g :=
to_linear_equiv_injective $ linear_equiv.ext $ congr_fun h
lemma coe_injective : function.injective (coe : (M ≃L[R] M₂) → (M →L[R] M₂)) :=
λ e e' h, ext $ funext $ continuous_linear_map.ext_iff.1 h
@[simp, norm_cast] lemma coe_inj {e e' : M ≃L[R] M₂} : (e : M →L[R] M₂) = e' ↔ e = e' :=
coe_injective.eq_iff
/-- A continuous linear equivalence induces a homeomorphism. -/
def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { to_equiv := e.to_linear_equiv.to_equiv, ..e }
@[simp] lemma coe_to_homeomorph (e : M ≃L[R] M₂) : ⇑e.to_homeomorph = e := rfl
lemma image_closure (e : M ≃L[R] M₂) (s : set M) : e '' closure s = closure (e '' s) :=
e.to_homeomorph.image_closure s
lemma preimage_closure (e : M ≃L[R] M₂) (s : set M₂) : e ⁻¹' closure s = closure (e ⁻¹' s) :=
e.to_homeomorph.preimage_closure s
@[simp] lemma is_closed_image (e : M ≃L[R] M₂) {s : set M} : is_closed (e '' s) ↔ is_closed s :=
e.to_homeomorph.is_closed_image
lemma map_nhds_eq (e : M ≃L[R] M₂) (x : M) : map e (𝓝 x) = 𝓝 (e x) :=
e.to_homeomorph.map_nhds_eq x
-- Make some straightforward lemmas available to `simp`.
@[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero
@[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y :=
(e : M →L[R] M₂).map_add x y
@[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) :=
(e : M →L[R] M₂).map_smul c x
@[simp] lemma map_eq_zero_iff (e : M ≃L[R] M₂) {x : M} : e x = 0 ↔ x = 0 :=
e.to_linear_equiv.map_eq_zero_iff
attribute [continuity]
continuous_linear_equiv.continuous_to_fun continuous_linear_equiv.continuous_inv_fun
@[continuity]
protected lemma continuous (e : M ≃L[R] M₂) : continuous (e : M → M₂) :=
e.continuous_to_fun
protected lemma continuous_on (e : M ≃L[R] M₂) {s : set M} : continuous_on (e : M → M₂) s :=
e.continuous.continuous_on
protected lemma continuous_at (e : M ≃L[R] M₂) {x : M} : continuous_at (e : M → M₂) x :=
e.continuous.continuous_at
protected lemma continuous_within_at (e : M ≃L[R] M₂) {s : set M} {x : M} :
continuous_within_at (e : M → M₂) s x :=
e.continuous.continuous_within_at
lemma comp_continuous_on_iff
{α : Type*} [topological_space α] (e : M ≃L[R] M₂) {f : α → M} {s : set α} :
continuous_on (e ∘ f) s ↔ continuous_on f s :=
e.to_homeomorph.comp_continuous_on_iff _ _
lemma comp_continuous_iff
{α : Type*} [topological_space α] (e : M ≃L[R] M₂) {f : α → M} :
continuous (e ∘ f) ↔ continuous f :=
e.to_homeomorph.comp_continuous_iff
/-- An extensionality lemma for `R ≃L[R] M`. -/
lemma ext₁ [topological_space R] {f g : R ≃L[R] M} (h : f 1 = g 1) : f = g :=
ext $ funext $ λ x, mul_one x ▸ by rw [← smul_eq_mul, map_smul, h, map_smul]
section
variables (R M)
/-- The identity map as a continuous linear equivalence. -/
@[refl] protected def refl : M ≃L[R] M :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
.. linear_equiv.refl R M }
end
@[simp, norm_cast] lemma coe_refl :
(continuous_linear_equiv.refl R M : M →L[R] M) = continuous_linear_map.id R M := rfl
@[simp, norm_cast] lemma coe_refl' :
(continuous_linear_equiv.refl R M : M → M) = id := rfl
/-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/
@[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M :=
{ continuous_to_fun := e.continuous_inv_fun,
continuous_inv_fun := e.continuous_to_fun,
.. e.to_linear_equiv.symm }
@[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) :
e.symm.to_linear_equiv = e.to_linear_equiv.symm :=
by { ext, refl }
@[simp] lemma symm_to_homeomorph (e : M ≃L[R] M₂) : e.to_homeomorph.symm = e.symm.to_homeomorph :=
rfl
lemma symm_map_nhds_eq (e : M ≃L[R] M₂) (x : M) : map e.symm (𝓝 (e x)) = 𝓝 x :=
e.to_homeomorph.symm_map_nhds_eq x
/-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/
@[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] M₃ :=
{ continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun,
continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun,
.. e₁.to_linear_equiv.trans e₂.to_linear_equiv }
@[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) :
(e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv :=
by { ext, refl }
/-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/
def prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) : (M × M₃) ≃L[R] (M₂ × M₄) :=
{ continuous_to_fun := e.continuous_to_fun.prod_map e'.continuous_to_fun,
continuous_inv_fun := e.continuous_inv_fun.prod_map e'.continuous_inv_fun,
.. e.to_linear_equiv.prod e'.to_linear_equiv }
@[simp, norm_cast] lemma prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (x) :
e.prod e' x = (e x.1, e' x.2) := rfl
@[simp, norm_cast] lemma coe_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) :
(e.prod e' : (M × M₃) →L[R] (M₂ × M₄)) = (e : M →L[R] M₂).prod_map (e' : M₃ →L[R] M₄) :=
rfl
theorem bijective (e : M ≃L[R] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective
theorem injective (e : M ≃L[R] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective
theorem surjective (e : M ≃L[R] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective
@[simp] theorem trans_apply (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) (c : M) :
(e₁.trans e₂) c = e₂ (e₁ c) :=
rfl
@[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.right_inv c
@[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.left_inv b
@[simp] theorem symm_trans_apply (e₁ : M₂ ≃L[R] M) (e₂ : M₃ ≃L[R] M₂) (c : M) :
(e₂.trans e₁).symm c = e₂.symm (e₁.symm c) :=
rfl
@[simp] theorem symm_image_image (e : M ≃L[R] M₂) (s : set M) : e.symm '' (e '' s) = s :=
e.to_linear_equiv.to_equiv.symm_image_image s
@[simp] theorem image_symm_image (e : M ≃L[R] M₂) (s : set M₂) : e '' (e.symm '' s) = s :=
e.symm.symm_image_image s
@[simp, norm_cast]
lemma comp_coe (f : M ≃L[R] M₂) (f' : M₂ ≃L[R] M₃) :
(f' : M₂ →L[R] M₃).comp (f : M →L[R] M₂) = (f.trans f' : M →L[R] M₃) :=
rfl
@[simp] theorem coe_comp_coe_symm (e : M ≃L[R] M₂) :
(e : M →L[R] M₂).comp (e.symm : M₂ →L[R] M) = continuous_linear_map.id R M₂ :=
continuous_linear_map.ext e.apply_symm_apply
@[simp] theorem coe_symm_comp_coe (e : M ≃L[R] M₂) :
(e.symm : M₂ →L[R] M).comp (e : M →L[R] M₂) = continuous_linear_map.id R M :=
continuous_linear_map.ext e.symm_apply_apply
@[simp] lemma symm_comp_self (e : M ≃L[R] M₂) :
(e.symm : M₂ → M) ∘ (e : M → M₂) = id :=
by{ ext x, exact symm_apply_apply e x }
@[simp] lemma self_comp_symm (e : M ≃L[R] M₂) :
(e : M → M₂) ∘ (e.symm : M₂ → M) = id :=
by{ ext x, exact apply_symm_apply e x }
@[simp] theorem symm_symm (e : M ≃L[R] M₂) : e.symm.symm = e :=
by { ext x, refl }
@[simp] lemma refl_symm :
(continuous_linear_equiv.refl R M).symm = continuous_linear_equiv.refl R M :=
rfl
theorem symm_symm_apply (e : M ≃L[R] M₂) (x : M) : e.symm.symm x = e x :=
rfl
lemma symm_apply_eq (e : M ≃L[R] M₂) {x y} : e.symm x = y ↔ x = e y :=
e.to_linear_equiv.symm_apply_eq
lemma eq_symm_apply (e : M ≃L[R] M₂) {x y} : y = e.symm x ↔ e y = x :=
e.to_linear_equiv.eq_symm_apply
protected lemma image_eq_preimage (e : M ≃L[R] M₂) (s : set M) : e '' s = e.symm ⁻¹' s :=
e.to_linear_equiv.to_equiv.image_eq_preimage s
protected lemma image_symm_eq_preimage (e : M ≃L[R] M₂) (s : set M₂) : e.symm '' s = e ⁻¹' s :=
by rw [e.symm.image_eq_preimage, e.symm_symm]
/-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are
inverse of each other. -/
def equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h₁ : function.left_inverse f₂ f₁)
(h₂ : function.right_inverse f₂ f₁) :
M ≃L[R] M₂ :=
{ to_fun := f₁,
continuous_to_fun := f₁.continuous,
inv_fun := f₂,
continuous_inv_fun := f₂.continuous,
left_inv := h₁,
right_inv := h₂,
.. f₁ }
@[simp] lemma equiv_of_inverse_apply (f₁ : M →L[R] M₂) (f₂ h₁ h₂ x) :
equiv_of_inverse f₁ f₂ h₁ h₂ x = f₁ x :=
rfl
@[simp] lemma symm_equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ h₁ h₂) :
(equiv_of_inverse f₁ f₂ h₁ h₂).symm = equiv_of_inverse f₂ f₁ h₂ h₁ :=
rfl
variable (M)
/-- The continuous linear equivalences from `M` to itself form a group under composition. -/
instance automorphism_group : group (M ≃L[R] M) :=
{ mul := λ f g, g.trans f,
one := continuous_linear_equiv.refl R M,
inv := λ f, f.symm,
mul_assoc := λ f g h, by {ext, refl},
mul_one := λ f, by {ext, refl},
one_mul := λ f, by {ext, refl},
mul_left_inv := λ f, by {ext, exact f.left_inv x} }
end add_comm_monoid
section add_comm_group
variables {R : Type*} [semiring R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂]
{M₃ : Type*} [topological_space M₃] [add_comm_group M₃]
{M₄ : Type*} [topological_space M₄] [add_comm_group M₄]
[module R M] [module R M₂] [module R M₃] [module R M₄]
variables [topological_add_group M₄]
/-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks,
and `f` is a rectangular block below the diagonal. -/
def skew_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) :
(M × M₃) ≃L[R] M₂ × M₄ :=
{ continuous_to_fun := (e.continuous_to_fun.comp continuous_fst).prod_mk
((e'.continuous_to_fun.comp continuous_snd).add $ f.continuous.comp continuous_fst),
continuous_inv_fun := (e.continuous_inv_fun.comp continuous_fst).prod_mk
(e'.continuous_inv_fun.comp $ continuous_snd.sub $ f.continuous.comp $
e.continuous_inv_fun.comp continuous_fst),
.. e.to_linear_equiv.skew_prod e'.to_linear_equiv ↑f }
@[simp] lemma skew_prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) :
e.skew_prod e' f x = (e x.1, e' x.2 + f x.1) := rfl
@[simp] lemma skew_prod_symm_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) :
(e.skew_prod e' f).symm x = (e.symm x.1, e'.symm (x.2 - f (e.symm x.1))) := rfl
end add_comm_group
section ring
variables {R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M] [module R M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂]
@[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y :=
(e : M →L[R] M₂).map_sub x y
@[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x
section
/-! The next theorems cover the identification between `M ≃L[𝕜] M`and the group of units of the ring
`M →L[R] M`. -/
variables [topological_add_group M]
/-- An invertible continuous linear map `f` determines a continuous equivalence from `M` to itself.
-/
def of_unit (f : units (M →L[R] M)) : (M ≃L[R] M) :=
{ to_linear_equiv :=
{ to_fun := f.val,
map_add' := by simp,
map_smul' := by simp,
inv_fun := f.inv,
left_inv := λ x, show (f.inv * f.val) x = x, by {rw f.inv_val, simp},
right_inv := λ x, show (f.val * f.inv) x = x, by {rw f.val_inv, simp}, },
continuous_to_fun := f.val.continuous,
continuous_inv_fun := f.inv.continuous }
/-- A continuous equivalence from `M` to itself determines an invertible continuous linear map. -/
def to_unit (f : (M ≃L[R] M)) : units (M →L[R] M) :=
{ val := f,
inv := f.symm,
val_inv := by {ext, simp},
inv_val := by {ext, simp} }
variables (R M)
/-- The units of the algebra of continuous `R`-linear endomorphisms of `M` is multiplicatively
equivalent to the type of continuous linear equivalences between `M` and itself. -/
def units_equiv : units (M →L[R] M) ≃* (M ≃L[R] M) :=
{ to_fun := of_unit,
inv_fun := to_unit,
left_inv := λ f, by {ext, refl},
right_inv := λ f, by {ext, refl},
map_mul' := λ x y, by {ext, refl} }
@[simp] lemma units_equiv_apply (f : units (M →L[R] M)) (x : M) :
units_equiv R M f x = f x := rfl
end
section
variables (R) [topological_space R] [has_continuous_mul R]
/-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `units R`. -/
def units_equiv_aut : units R ≃ (R ≃L[R] R) :=
{ to_fun := λ u, equiv_of_inverse
(continuous_linear_map.smul_right (1 : R →L[R] R) ↑u)
(continuous_linear_map.smul_right (1 : R →L[R] R) ↑u⁻¹)
(λ x, by simp) (λ x, by simp),
inv_fun := λ e, ⟨e 1, e.symm 1,
by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, symm_apply_apply],
by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, apply_symm_apply]⟩,
left_inv := λ u, units.ext $ by simp,
right_inv := λ e, ext₁ $ by simp }
variable {R}
@[simp] lemma units_equiv_aut_apply (u : units R) (x : R) : units_equiv_aut R u x = x * u := rfl
@[simp] lemma units_equiv_aut_apply_symm (u : units R) (x : R) :
(units_equiv_aut R u).symm x = x * ↑u⁻¹ := rfl
@[simp] lemma units_equiv_aut_symm_apply (e : R ≃L[R] R) :
↑((units_equiv_aut R).symm e) = e 1 :=
rfl
end
variables [topological_add_group M]
open continuous_linear_map (id fst snd subtype_val mem_ker)
/-- A pair of continuous linear maps such that `f₁ ∘ f₂ = id` generates a continuous
linear equivalence `e` between `M` and `M₂ × f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`,
`(e x).1 = f₁ x`, and `(e (f₂ y)).2 = 0`. The map is given by `e x = (f₁ x, x - f₂ (f₁ x))`. -/
def equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) :
M ≃L[R] M₂ × f₁.ker :=
equiv_of_inverse (f₁.prod (f₁.proj_ker_of_right_inverse f₂ h)) (f₂.coprod (subtype_val f₁.ker))
(λ x, by simp)
(λ ⟨x, y⟩, by simp [h x])
@[simp] lemma fst_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) (x : M) :
(equiv_of_right_inverse f₁ f₂ h x).1 = f₁ x := rfl
@[simp] lemma snd_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) (x : M) :
((equiv_of_right_inverse f₁ f₂ h x).2 : M) = x - f₂ (f₁ x) := rfl
@[simp] lemma equiv_of_right_inverse_symm_apply (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) (y : M₂ × f₁.ker) :
(equiv_of_right_inverse f₁ f₂ h).symm y = f₂ y.1 + y.2 := rfl
end ring
end continuous_linear_equiv
namespace continuous_linear_map
open_locale classical
variables {R : Type*} {M : Type*} {M₂ : Type*} [topological_space M] [topological_space M₂]
section
variables [semiring R]
variables [add_comm_monoid M₂] [module R M₂]
variables [add_comm_monoid M] [module R M]
/-- Introduce a function `inverse` from `M →L[R] M₂` to `M₂ →L[R] M`, which sends `f` to `f.symm` if
`f` is a continuous linear equivalence and to `0` otherwise. This definition is somewhat ad hoc,
but one needs a fully (rather than partially) defined inverse function for some purposes, including
for calculus. -/
noncomputable def inverse : (M →L[R] M₂) → (M₂ →L[R] M) :=
λ f, if h : ∃ (e : M ≃L[R] M₂), (e : M →L[R] M₂) = f then ((classical.some h).symm : M₂ →L[R] M)
else 0
/-- By definition, if `f` is invertible then `inverse f = f.symm`. -/
@[simp] lemma inverse_equiv (e : M ≃L[R] M₂) : inverse (e : M →L[R] M₂) = e.symm :=
begin
have h : ∃ (e' : M ≃L[R] M₂), (e' : M →L[R] M₂) = ↑e := ⟨e, rfl⟩,
simp only [inverse, dif_pos h],
congr,
exact_mod_cast (classical.some_spec h)
end
/-- By definition, if `f` is not invertible then `inverse f = 0`. -/
@[simp] lemma inverse_non_equiv (f : M →L[R] M₂) (h : ¬∃ (e' : M ≃L[R] M₂), ↑e' = f) :
inverse f = 0 :=
dif_neg h
end
section
variables [ring R]
variables [add_comm_group M] [topological_add_group M] [module R M]
variables [add_comm_group M₂] [module R M₂]
@[simp] lemma ring_inverse_equiv (e : M ≃L[R] M) :
ring.inverse ↑e = inverse (e : M →L[R] M) :=
begin
suffices :
ring.inverse ((((continuous_linear_equiv.units_equiv _ _).symm e) : M →L[R] M)) = inverse ↑e,
{ convert this },
simp,
refl,
end
/-- The function `continuous_linear_equiv.inverse` can be written in terms of `ring.inverse` for the
ring of self-maps of the domain. -/
lemma to_ring_inverse (e : M ≃L[R] M₂) (f : M →L[R] M₂) :
inverse f = (ring.inverse ((e.symm : (M₂ →L[R] M)).comp f)).comp e.symm :=
begin
by_cases h₁ : ∃ (e' : M ≃L[R] M₂), ↑e' = f,
{ obtain ⟨e', he'⟩ := h₁,
rw ← he',
ext,
simp },
{ suffices : ¬is_unit ((e.symm : M₂ →L[R] M).comp f),
{ simp [this, h₁] },
revert h₁,
contrapose!,
rintros ⟨F, hF⟩,
use (continuous_linear_equiv.units_equiv _ _ F).trans e,
ext,
simp [hF] }
end
lemma ring_inverse_eq_map_inverse : ring.inverse = @inverse R M M _ _ _ _ _ _ _ :=
begin
ext,
simp [to_ring_inverse (continuous_linear_equiv.refl R M)],
end
end
end continuous_linear_map
namespace submodule
variables
{R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M] [module R M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂]
open continuous_linear_map
/-- A submodule `p` is called *complemented* if there exists a continuous projection `M →ₗ[R] p`. -/
def closed_complemented (p : submodule R M) : Prop := ∃ f : M →L[R] p, ∀ x : p, f x = x
lemma closed_complemented.has_closed_complement {p : submodule R M} [t1_space p]
(h : closed_complemented p) :
∃ (q : submodule R M) (hq : is_closed (q : set M)), is_compl p q :=
exists.elim h $ λ f hf, ⟨f.ker, f.is_closed_ker, linear_map.is_compl_of_proj hf⟩
protected lemma closed_complemented.is_closed [topological_add_group M] [t1_space M]
{p : submodule R M} (h : closed_complemented p) :
is_closed (p : set M) :=
begin
rcases h with ⟨f, hf⟩,
have : ker (id R M - (subtype_val p).comp f) = p := linear_map.ker_id_sub_eq_of_proj hf,
exact this ▸ (is_closed_ker _)
end
@[simp] lemma closed_complemented_bot : closed_complemented (⊥ : submodule R M) :=
⟨0, λ x, by simp only [zero_apply, eq_zero_of_bot_submodule x]⟩
@[simp] lemma closed_complemented_top : closed_complemented (⊤ : submodule R M) :=
⟨(id R M).cod_restrict ⊤ (λ x, trivial), λ x, subtype.ext_iff_val.2 $ by simp⟩
end submodule
lemma continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type*} [ring R]
{M : Type*} [topological_space M] [add_comm_group M]
{M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂]
[topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M)
(h : function.right_inverse f₂ f₁) :
f₁.ker.closed_complemented :=
⟨f₁.proj_ker_of_right_inverse f₂ h, f₁.proj_ker_of_right_inverse_apply_idem f₂ h⟩
|
2e580dadac152b08175d47dbcbb987f04c32d4ac | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/logic/embedding.lean | ecc6520331aff89a39de559b08a98a6f547ba9cf | [
"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 | 10,022 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.equiv.basic
import data.sigma.basic
/-!
# Injective functions
-/
universes u v w x
namespace function
/-- `α ↪ β` is a bundled injective function. -/
structure embedding (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inj' : injective to_fun)
infixr ` ↪ `:25 := embedding
instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := ⟨_, embedding.to_fun⟩
end function
/-- Convert an `α ≃ β` to `α ↪ β`. -/
protected def equiv.to_embedding {α : Sort u} {β : Sort v} (f : α ≃ β) : α ↪ β :=
⟨f, f.injective⟩
@[simp] theorem equiv.to_embedding_coe_fn {α : Sort u} {β : Sort v} (f : α ≃ β) :
(f.to_embedding : α → β) = f := rfl
namespace function
namespace embedding
@[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g :=
by cases f; cases g; simpa using funext h
lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g :=
⟨ext, λ h _, by rw h⟩
@[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl
@[simp] theorem coe_fn_mk {α β} (f : α → β) (i) :
(@mk _ _ f i : α → β) = f := rfl
theorem injective {α β} (f : α ↪ β) : injective f := f.inj'
@[refl] protected def refl (α : Sort*) : α ↪ α :=
⟨id, injective_id⟩
@[trans] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ :=
⟨g ∘ f, g.injective.comp f.injective⟩
@[simp] theorem refl_apply {α} (x : α) : embedding.refl α x = x := rfl
@[simp] theorem trans_apply {α β γ} (f : α ↪ β) (g : β ↪ γ) (a : α) :
(f.trans g) a = g (f a) := rfl
@[simp]
lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) :
function.embedding.trans (e.to_embedding) (e.symm.to_embedding) = function.embedding.refl _ :=
by { ext, simp, }
@[simp]
lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) :
function.embedding.trans (e.symm.to_embedding) (e.to_embedding) = function.embedding.refl _ :=
by { ext, simp, }
protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x}
(e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) :=
(equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding)
/-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/
protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) :
α ↪ β :=
⟨surj_inv hf, injective_surj_inv _⟩
/-- Convert a surjective `embedding` to an `equiv` -/
protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) :
α ≃ β :=
equiv.of_bijective f ⟨f.injective, hf⟩
protected def of_not_nonempty {α β} (hα : ¬ nonempty α) : α ↪ β :=
⟨λa, (hα ⟨a⟩).elim, assume a, (hα ⟨a⟩).elim⟩
/-- Change the value of an embedding `f` at one point. If the prescribed image
is already occupied by some `f a'`, then swap the values at these two points. -/
def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)]
[∀ a', decidable (f a' = b)] : α ↪ β :=
⟨λ a', if a' = a then b else if f a' = b then f a else f a',
begin
intros x y h,
dsimp at h,
split_ifs at h; try { substI b }; try { simp only [f.injective.eq_iff] at * }; cc
end⟩
theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)]
[∀ a', decidable (f a' = b)] : set_value f a b a = b :=
by simp [set_value]
/-- Embedding into `option` -/
protected def some {α} : α ↪ option α :=
⟨some, option.some_injective α⟩
/-- Embedding of a `subtype`. -/
def subtype {α} (p : α → Prop) : subtype p ↪ α :=
⟨coe, λ _ _, subtype.ext_val⟩
@[simp] lemma coe_subtype {α} (p : α → Prop) : ⇑(subtype p) = coe := rfl
/-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/
def punit {β : Sort*} (b : β) : punit ↪ β :=
⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩
/-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/
def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β :=
⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩
/-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/
def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β :=
⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩
/-- Restrict the codomain of an embedding. -/
def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p :=
⟨λ a, ⟨f a, H a⟩, λ a b h, f.injective (@congr_arg _ _ _ _ subtype.val h)⟩
@[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) :
cod_restrict p f H a = ⟨f a, H a⟩ := rfl
/-- If `e₁` and `e₂` are embeddings, then so is `prod.map e₁ e₂ : (a, b) ↦ (e₁ a, e₂ b)`. -/
def prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ :=
⟨prod.map e₁ e₂, e₁.injective.prod_map e₂.injective⟩
@[simp] lemma coe_prod_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :
⇑(e₁.prod_map e₂) = prod.map e₁ e₂ :=
rfl
section sum
open sum
/-- If `e₁` and `e₂` are embeddings, then so is `sum.map e₁ e₂`. -/
def sum_map {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ :=
⟨sum.map e₁ e₂,
assume s₁ s₂ h, match s₁, s₂, h with
| inl a₁, inl a₂, h := congr_arg inl $ e₁.injective $ inl.inj h
| inr b₁, inr b₂, h := congr_arg inr $ e₂.injective $ inr.inj h
end⟩
@[simp] theorem coe_sum_map {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) :
⇑(sum_map e₁ e₂) = sum.map e₁ e₂ :=
rfl
/-- The embedding of `α` into the sum `α ⊕ β`. -/
def inl {α β : Type*} : α ↪ α ⊕ β :=
⟨sum.inl, λ a b, sum.inl.inj⟩
/-- The embedding of `β` into the sum `α ⊕ β`. -/
def inr {α β : Type*} : β ↪ α ⊕ β :=
⟨sum.inr, λ a b, sum.inr.inj⟩
end sum
section sigma
variables {α α' : Type*} {β : α → Type*} {β' : α' → Type*}
/-- If `f : α ↪ α'` is an embedding and `g : Π a, β α ↪ β' (f α)` is a family
of embeddings, then `sigma.map f g` is an embedding. -/
def sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) :
(Σ a, β a) ↪ Σ a', β' a' :=
⟨sigma.map f (λ a, g a), f.injective.sigma_map (λ a, (g a).injective)⟩
@[simp] lemma coe_sigma_map (f : α ↪ α') (g : Π a, β a ↪ β' (f a)) :
⇑(f.sigma_map g) = sigma.map f (λ a, g a) :=
rfl
end sigma
def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) :=
⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).injective (congr_fun h a)⟩
def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w}
(e : α ↪ β) : (γ → α) ↪ (γ → β) :=
Pi_congr_right (λ _, e)
noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ]
(e : α ↪ β) : (α → γ) ↪ (β → γ) :=
by haveI := classical.prop_decidable; exact
let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in
⟨f', assume f₁ f₂ h, funext $ assume c,
have ∃c', e c' = e c, from ⟨c, rfl⟩,
have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _,
have eq_b : classical.some this = c, from e.injective $ classical.some_spec this,
by simp [f', this, if_pos, eq_b] at eq'; assumption⟩
protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β)
(h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} :=
⟨subtype.map f h, subtype.map_injective h f.2⟩
open set
/-- `set.image` as an embedding `set α ↪ set β`. -/
protected def image {α β} (f : α ↪ β) : set α ↪ set β :=
⟨image f, f.2.image_injective⟩
@[simp] lemma coe_image {α β} (f : α ↪ β) : ⇑f.image = image f := rfl
end embedding
end function
namespace equiv
@[simp]
lemma refl_to_embedding {α : Type*} :
(equiv.refl α).to_embedding = function.embedding.refl α := rfl
@[simp]
lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) :
(e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl
end equiv
namespace set
/-- The injection map is an embedding between subsets. -/
def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t :=
⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by congr; injection h⟩
@[simp] lemma embedding_of_subset_apply_mk {α} {s t : set α} (h : s ⊆ t) (x : α) (hx : x ∈ s) :
embedding_of_subset s t h ⟨x, hx⟩ = ⟨x, h hx⟩ := rfl
@[simp] lemma coe_embedding_of_subset_apply {α} {s t : set α} (h : s ⊆ t) (x : s) :
(embedding_of_subset s t h x : α) = x := rfl
end set
/--
The embedding of a left cancellative semigroup into itself
by left multiplication by a fixed element.
-/
@[to_additive
"The embedding of a left cancellative additive semigroup into itself
by left translation by a fixed element."]
def mul_left_embedding {G : Type u} [left_cancel_semigroup G] (g : G) : G ↪ G :=
{ to_fun := λ h, g * h,
inj' := λ h h', (mul_right_inj g).mp, }
@[simp]
lemma mul_left_embedding_apply {G : Type u} [left_cancel_semigroup G] (g h : G) :
mul_left_embedding g h = g * h :=
rfl
/--
The embedding of a right cancellative semigroup into itself
by right multiplication by a fixed element.
-/
@[to_additive
"The embedding of a right cancellative additive semigroup into itself
by right translation by a fixed element."]
def mul_right_embedding {G : Type u} [right_cancel_semigroup G] (g : G) : G ↪ G :=
{ to_fun := λ h, h * g,
inj' := λ h h', (mul_left_inj g).mp, }
@[simp]
lemma mul_right_embedding_apply {G : Type u} [right_cancel_semigroup G] (g h : G) :
mul_right_embedding g h = h * g :=
rfl
|
10a545354fe25430dbe517316d954ae8b011f708 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/algebra/category/Algebra/basic.lean | e9574a58b266c601dcf82af491cbe75bd3ac6a37 | [
"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 | 5,708 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.algebra.basic
import algebra.algebra.subalgebra
import algebra.free_algebra
import algebra.category.CommRing.basic
import algebra.category.Module.basic
/-!
# Category instance for algebras over a commutative ring
We introduce the bundled category `Algebra` of algebras over a fixed commutative ring `R ` along
with the forgetful functors to `Ring` and `Module`. We furthermore show that the functor associating
to a type the free `R`-algebra on that type is left adjoint to the forgetful functor.
-/
open category_theory
open category_theory.limits
universes v u
variables (R : Type u) [comm_ring R]
/-- The category of R-algebras and their morphisms. -/
structure Algebra :=
(carrier : Type v)
[is_ring : ring carrier]
[is_algebra : algebra R carrier]
attribute [instance] Algebra.is_ring Algebra.is_algebra
namespace Algebra
instance : has_coe_to_sort (Algebra R) :=
{ S := Type v, coe := Algebra.carrier }
instance : category (Algebra.{v} R) :=
{ hom := λ A B, A →ₐ[R] B,
id := λ A, alg_hom.id R A,
comp := λ A B C f g, g.comp f }
instance : concrete_category.{v} (Algebra.{v} R) :=
{ forget := { obj := λ R, R, map := λ R S f, (f : R → S) },
forget_faithful := { } }
instance has_forget_to_Ring : has_forget₂ (Algebra.{v} R) Ring.{v} :=
{ forget₂ :=
{ obj := λ A, Ring.of A,
map := λ A₁ A₂ f, alg_hom.to_ring_hom f, } }
instance has_forget_to_Module : has_forget₂ (Algebra.{v} R) (Module.{v} R) :=
{ forget₂ :=
{ obj := λ M, Module.of R M,
map := λ M₁ M₂ f, alg_hom.to_linear_map f, } }
/-- The object in the category of R-algebras associated to a type equipped with the appropriate
typeclasses. -/
def of (X : Type v) [ring X] [algebra R X] : Algebra.{v} R := ⟨X⟩
/-- Typecheck a `alg_hom` as a morphism in `Algebra R`. -/
def of_hom {R : Type u} [comm_ring R] {X Y : Type v} [ring X] [algebra R X] [ring Y] [algebra R Y]
(f : X →ₐ[R] Y) : of R X ⟶ of R Y := f
instance : inhabited (Algebra R) := ⟨of R R⟩
@[simp]
lemma coe_of (X : Type u) [ring X] [algebra R X] : (of R X : Type u) = X := rfl
variables {R}
/-- Forgetting to the underlying type and then building the bundled object returns the original
algebra. -/
@[simps]
def of_self_iso (M : Algebra.{v} R) : Algebra.of R M ≅ M :=
{ hom := 𝟙 M, inv := 𝟙 M }
variables {R} {M N U : Module.{v} R}
@[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl
@[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) :
((f ≫ g) : M → U) = g ∘ f := rfl
variables (R)
/-- The "free algebra" functor, sending a type `S` to the free algebra on `S`. -/
@[simps]
def free : Type u ⥤ Algebra.{u} R :=
{ obj := λ S,
{ carrier := free_algebra R S,
is_ring := algebra.semiring_to_ring R },
map := λ S T f, free_algebra.lift _ $ (free_algebra.ι _) ∘ f,
-- obviously can fill the next two goals, but it is slow
map_id' := by { intros X, ext1, simp only [free_algebra.ι_comp_lift], refl },
map_comp' := by { intros, ext1, simp only [free_algebra.ι_comp_lift], ext1,
simp only [free_algebra.lift_ι_apply, category_theory.coe_comp, function.comp_app,
types_comp_apply] } }
/-- The free/forget adjunction for `R`-algebras. -/
def adj : free.{u} R ⊣ forget (Algebra.{u} R) :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ X A, (free_algebra.lift _).symm,
-- Relying on `obviously` to fill out these proofs is very slow :(
hom_equiv_naturality_left_symm' := by { intros, ext,
simp only [free_map, equiv.symm_symm, free_algebra.lift_ι_apply, category_theory.coe_comp,
function.comp_app, types_comp_apply] },
hom_equiv_naturality_right' := by { intros, ext,
simp only [forget_map_eq_coe, category_theory.coe_comp, function.comp_app,
free_algebra.lift_symm_apply, types_comp_apply] } }
instance : is_right_adjoint (forget (Algebra.{u} R)) := ⟨_, adj R⟩
end Algebra
variables {R}
variables {X₁ X₂ : Type u}
/-- Build an isomorphism in the category `Algebra R` from a `alg_equiv` between `algebra`s. -/
@[simps]
def alg_equiv.to_Algebra_iso
{g₁ : ring X₁} {g₂ : ring X₂} {m₁ : algebra R X₁} {m₂ : algebra R X₂} (e : X₁ ≃ₐ[R] X₂) :
Algebra.of R X₁ ≅ Algebra.of R X₂ :=
{ hom := (e : X₁ →ₐ[R] X₂),
inv := (e.symm : X₂ →ₐ[R] X₁),
hom_inv_id' := begin ext, exact e.left_inv x, end,
inv_hom_id' := begin ext, exact e.right_inv x, end, }
namespace category_theory.iso
/-- Build a `alg_equiv` from an isomorphism in the category `Algebra R`. -/
@[simps]
def to_alg_equiv {X Y : Algebra R} (i : X ≅ Y) : X ≃ₐ[R] Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
map_add' := by tidy,
map_mul' := by tidy,
commutes' := by tidy, }.
end category_theory.iso
/-- Algebra equivalences between `algebras`s are the same as (isomorphic to) isomorphisms in
`Algebra`. -/
@[simps]
def alg_equiv_iso_Algebra_iso {X Y : Type u}
[ring X] [ring Y] [algebra R X] [algebra R Y] :
(X ≃ₐ[R] Y) ≅ (Algebra.of R X ≅ Algebra.of R Y) :=
{ hom := λ e, e.to_Algebra_iso,
inv := λ i, i.to_alg_equiv, }
instance (X : Type u) [ring X] [algebra R X] : has_coe (subalgebra R X) (Algebra R) :=
⟨ λ N, Algebra.of R N ⟩
instance Algebra.forget_reflects_isos : reflects_isomorphisms (forget (Algebra.{u} R)) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget (Algebra.{u} R)).map f),
let e : X ≃ₐ[R] Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_Algebra_iso).1⟩,
end }
|
92ea9f8e9d836f3c76b34aa7ceed05f5d83fbc62 | ad0c7d243dc1bd563419e2767ed42fb323d7beea | /tactic/tauto.lean | fc21ba8f7ce0fbc1a72707564df7b3df97a7e8de | [
"Apache-2.0"
] | permissive | sebzim4500/mathlib | e0b5a63b1655f910dee30badf09bd7e191d3cf30 | 6997cafbd3a7325af5cb318561768c316ceb7757 | refs/heads/master | 1,585,549,958,618 | 1,538,221,723,000 | 1,538,221,723,000 | 150,869,076 | 0 | 0 | Apache-2.0 | 1,538,229,323,000 | 1,538,229,323,000 | null | UTF-8 | Lean | false | false | 7,552 | lean |
import logic.basic tactic.basic
namespace tactic
open expr
open tactic.interactive ( casesm constructor_matching )
/--
find all assumptions of the shape `¬ (p ∧ q)` or `¬ (p ∨ q)` and
replace them using de Morgan's law.
-/
meta def distrib_not : tactic unit :=
do hs ← local_context,
hs.for_each $ λ h,
all_goals $
iterate_at_most 3 $
do h ← get_local h.local_pp_name,
e ← infer_type h,
match e with
| `(¬ _ = _) := replace h.local_pp_name ``(mt iff.to_eq %%h)
| `(_ ≠ _) := replace h.local_pp_name ``(mt iff.to_eq %%h)
| `(_ = _) := replace h.local_pp_name ``(eq.to_iff %%h)
| `(¬ (_ ∧ _)) := replace h.local_pp_name ``(not_and_distrib'.mp %%h) <|>
replace h.local_pp_name ``(not_and_distrib.mp %%h)
| `(¬ (_ ∨ _)) := replace h.local_pp_name ``(not_or_distrib.mp %%h)
| `(¬ ¬ _) := replace h.local_pp_name ``(of_not_not %%h)
| `(¬ (_ → (_ : Prop))) := replace h.local_pp_name ``(not_imp.mp %%h)
| `(¬ (_ ↔ _)) := replace h.local_pp_name ``(not_iff.mp %%h)
| `(_ ↔ _) := replace h.local_pp_name ``(iff_iff_and_or_not_and_not.mp %%h) <|>
replace h.local_pp_name ``(iff_iff_and_or_not_and_not.mp (%%h).symm) <|>
() <$ tactic.cases h
| `(_ → _) := replace h.local_pp_name ``(not_or_of_imp %%h)
| _ := failed
end
meta def tauto_state := ref $ expr_map (option (expr × expr))
meta def modify_ref {α : Type} (r : ref α) (f : α → α) :=
read_ref r >>= write_ref r ∘ f
meta def add_refl (r : tauto_state) (e : expr) : tactic (expr × expr) :=
do m ← read_ref r,
p ← mk_mapp `rfl [none,e],
write_ref r $ m.insert e none,
return (e,p)
meta def add_symm_proof (r : tauto_state) (e : expr) : tactic (expr × expr) :=
do env ← get_env,
let rel := e.get_app_fn.const_name,
some symm ← pure $ environment.symm_for env rel
| add_refl r e,
(do e' ← mk_meta_var `(Prop),
iff_t ← to_expr ``(%%e = %%e'),
(_,p) ← solve_aux iff_t
(applyc `iff.to_eq ; () <$ split ; applyc symm),
e' ← instantiate_mvars e',
m ← read_ref r,
write_ref r $ (m.insert e (e',p)).insert e' none,
return (e',p) )
<|> add_refl r e
meta def add_edge (r : tauto_state) (x y p : expr) : tactic unit :=
modify_ref r $ λ m, m.insert x (y,p)
meta def root (r : tauto_state) : expr → tactic (expr × expr) | e :=
do m ← read_ref r,
let record_e : tactic (expr × expr) :=
match e with
| v@(expr.mvar _ _ _) :=
(do (e,p) ← get_assignment v >>= root,
add_edge r v e p,
return (e,p)) <|>
add_refl r e
| _ := add_refl r e
end,
some e' ← pure $ m.find e | record_e,
match e' with
| (some (e',p')) :=
do (e'',p'') ← root e',
p'' ← mk_app `eq.trans [p',p''],
add_edge r e e'' p'',
pure (e'',p'')
| none := prod.mk e <$> mk_mapp `rfl [none,some e]
end
meta def symm_eq (r : tauto_state) : expr → expr → tactic expr | a b :=
do m ← read_ref r,
(a',pa) ← root r a,
(b',pb) ← root r b,
(unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a]) <|>
do p ← match (a', b') with
| (`(¬ %%a₀), `(¬ %%b₀)) :=
do p ← symm_eq a₀ b₀,
p' ← mk_app `congr_arg [`(not),p],
add_edge r a' b' p',
return p'
| (`(%%a₀ ∧ %%a₁), `(%%b₀ ∧ %%b₁)) :=
do p₀ ← symm_eq a₀ b₀,
p₁ ← symm_eq a₁ b₁,
p' ← to_expr ``(congr (congr_arg and %%p₀) %%p₁),
add_edge r a' b' p',
return p'
| (`(%%a₀ ∨ %%a₁), `(%%b₀ ∨ %%b₁)) :=
do p₀ ← symm_eq a₀ b₀,
p₁ ← symm_eq a₁ b₁,
p' ← to_expr ``(congr (congr_arg or %%p₀) %%p₁),
add_edge r a' b' p',
return p'
| (`(%%a₀ ↔ %%a₁), `(%%b₀ ↔ %%b₁)) :=
(do p₀ ← symm_eq a₀ b₀,
p₁ ← symm_eq a₁ b₁,
p' ← to_expr ``(congr (congr_arg iff %%p₀) %%p₁),
add_edge r a' b' p',
return p') <|>
do p₀ ← symm_eq a₀ b₁,
p₁ ← symm_eq a₁ b₀,
p' ← to_expr ``(eq.trans (congr (congr_arg iff %%p₀) %%p₁)
(iff.to_eq iff.comm ) ),
add_edge r a' b' p',
return p'
| (`(%%a₀ → %%a₁), `(%%b₀ → %%b₁)) :=
if ¬ a₁.has_var ∧ ¬ b₁.has_var then
do p₀ ← symm_eq a₀ b₀,
p₁ ← symm_eq a₁ b₁,
p' ← mk_app `congr_arg [`(implies),p₀,p₁],
add_edge r a' b' p',
return p'
else unify a' b' >> add_refl r a' *> mk_mapp `rfl [none,a]
| (_, _) :=
(do guard $ a'.get_app_fn.is_constant ∧
a'.get_app_fn.const_name = b'.get_app_fn.const_name,
(a'',pa') ← add_symm_proof r a',
guard $ a'' =ₐ b',
pure pa' )
end,
p' ← mk_eq_trans pa p,
add_edge r a' b' p',
mk_eq_symm pb >>= mk_eq_trans p'
meta def find_eq_type (r : tauto_state) : expr → list expr → tactic (expr × expr)
| e [] := failed
| e (H :: Hs) :=
do t ← infer_type H,
t' ← infer_type e,
(prod.mk H <$> symm_eq r e t) <|> find_eq_type e Hs
private meta def contra_p_not_p (r : tauto_state) : list expr → list expr → tactic unit
| [] Hs := failed
| (H1 :: Rs) Hs :=
do t ← (extract_opt_auto_param <$> infer_type H1) >>= whnf,
(do a ← match_not t,
(H2,p) ← find_eq_type r a Hs,
H2 ← to_expr ``( (%%p).mpr %%H2 ),
tgt ← target,
pr ← mk_app `absurd [tgt, H2, H1],
tactic.exact pr)
<|> contra_p_not_p Rs Hs
meta def contradiction_with (r : tauto_state) : tactic unit :=
contradiction <|>
do tactic.try intro1,
ctx ← local_context,
contra_p_not_p r ctx ctx
meta def contradiction_symm :=
using_new_ref (native.rb_map.mk _ _) contradiction_with
meta def assumption_with (r : tauto_state) : tactic unit :=
do { ctx ← local_context,
t ← target,
(H,p) ← find_eq_type r t ctx,
mk_eq_mpr p H >>= tactic.exact }
<|> fail "assumption tactic failed"
meta def assumption_symm :=
using_new_ref (native.rb_map.mk _ _) assumption_with
meta def tautology : tactic unit :=
using_new_ref (expr_map.mk _) $ λ r,
do try (contradiction_with r);
try (assumption_with r);
repeat (do
gs ← get_goals,
() <$ tactic.intros;
distrib_not;
casesm (some ()) [``(_ ∧ _),``(_ ∨ _),``(Exists _),``(false)];
try (contradiction_with r);
try (target >>= match_or >> refine ``( or_iff_not_imp_left.mpr _));
try (target >>= match_or >> refine ``( or_iff_not_imp_right.mpr _));
() <$ tactic.intros;
constructor_matching (some ()) [``(_ ∧ _),``(_ ↔ _),``(true)];
try (assumption_with r),
gs' ← get_goals,
guard (gs ≠ gs') ) ;
repeat
(reflexivity <|> solve_by_elim <|>
constructor_matching none [``(_ ∧ _),``(_ ↔ _),``(Exists _),``(true)] ) ;
done
end tactic
|
6466b19b261771e287335f5608c3971dd5ebe50e | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/measure_theory/lp_space.lean | 679cdefe5997d0c729a81f28ba98f271e7a150a9 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 48,593 | lean | /-
Copyright (c) 2020 Rémy Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Rémy Degenne, Sébastien Gouëzel
-/
import measure_theory.ess_sup
import measure_theory.ae_eq_fun
import analysis.mean_inequalities
/-!
# ℒp space and Lp space
This file describes properties of almost everywhere measurable functions with finite seminorm,
denoted by `snorm f p μ` and defined for `p:ℝ≥0∞` as `0` if `p=0`, `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for
`0 < p < ∞` and `ess_sup ∥f∥ μ` for `p=∞`.
The Prop-valued `mem_ℒp f p μ` states that a function `f : α → E` has finite seminorm.
The space `Lp α E p μ` is the subtype of elements of `α →ₘ[μ] E` (see ae_eq_fun) such that
`snorm f p μ` is finite. For `1 ≤ p`, `snorm` defines a norm and `Lp` is a metric space.
TODO: prove that Lp is complete.
## Main definitions
* `snorm' f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F` and `p : ℝ`, where `α` is a measurable
space and `F` is a normed group.
* `snorm_ess_sup f μ` : seminorm in `ℒ∞`, equal to the essential supremum `ess_sup ∥f∥ μ`.
* `snorm f p μ` : for `p : ℝ≥0∞`, seminorm in `ℒp`, equal to `0` for `p=0`, to `snorm' f p μ`
for `0 < p < ∞` and to `snorm_ess_sup f μ` for `p = ∞`.
* `mem_ℒp f p μ` : property that the function `f` is almost everywhere measurable and has finite
p-seminorm for measure `μ` (`snorm f p μ < ∞`)
* `Lp E p μ` : elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. Defined
as an `add_subgroup` of `α →ₘ[μ] E`.
Lipschitz functions vanishing at zero act by composition on `Lp`. We define this action, and prove
that it is continuous. In particular,
* `continuous_linear_map.comp_Lp` defines the action on `Lp` of a continuous linear map.
* `Lp.pos_part` is the positive part of an `Lp` function.
* `Lp.neg_part` is the negative part of an `Lp` function.
## Implementation
Since `Lp` is defined as an `add_subgroup`, dot notation does not work. Use `Lp.measurable f` to
say that the coercion of `f` to a genuine function is measurable, instead of the non-working
`f.measurable`.
To prove that two `Lp` elements are equal, it suffices to show that their coercions to functions
coincide almost everywhere (this is registered as an `ext` rule). This can often be done using
`filter_upwards`. For instance, a proof from first principles that `f + (g + h) = (f + g) + h`
could read (in the `Lp` namespace)
```
example (f g h : Lp E p μ) : (f + g) + h = f + (g + h) :=
begin
ext1,
filter_upwards [coe_fn_add (f + g) h, coe_fn_add f g, coe_fn_add f (g + h), coe_fn_add g h],
assume a ha1 ha2 ha3 ha4,
simp only [ha1, ha2, ha3, ha4, add_assoc],
end
```
The lemma `coe_fn_add` states that the coercion of `f + g` coincides almost everywhere with the sum
of the coercions of `f` and `g`. All such lemmas use `coe_fn` in their name, to distinguish the
function coercion from the coercion to almost everywhere defined functions.
-/
noncomputable theory
open topological_space measure_theory
open_locale nnreal ennreal
lemma fact_one_le_one_ennreal : fact ((1 : ℝ≥0∞) ≤ 1) := le_refl _
lemma fact_one_le_two_ennreal : fact ((1 : ℝ≥0∞) ≤ 2) :=
ennreal.coe_le_coe.2 (show (1 : nnreal) ≤ 2, by norm_num)
lemma fact_one_le_top_ennreal : fact ((1 : ℝ≥0∞) ≤ ∞) := le_top
local attribute [instance] fact_one_le_one_ennreal fact_one_le_two_ennreal fact_one_le_top_ennreal
variables {α E F G : Type*} [measurable_space α] {p : ℝ≥0∞} {q : ℝ} {μ : measure α}
[measurable_space E] [normed_group E]
[normed_group F] [normed_group G]
open_locale ennreal
namespace measure_theory
section ℒp
/-!
### ℒp seminorm
We define the ℒp seminorm, denoted by `snorm f p μ`. For real `p`, it is given by an integral
formula (for which we use the notation `snorm' f p μ`), and for `p = ∞` it is the essential
supremum (for which we use the notation `snorm_ess_sup f μ`).
We also define a predicate `mem_ℒp f p μ`, requesting that a function is almost everywhere
measurable and has finite `snorm f p μ`.
This paragraph is devoted to the basic properties of these definitions. It is constructed as
follows: for a given property, we prove it for `snorm'` and `snorm_ess_sup` when it makes sense,
deduce it for `snorm`, and translate it in terms of `mem_ℒp`.
-/
section ℒp_space_definition
/-- `(∫ ∥f a∥^q ∂μ) ^ (1/q)`, which is a seminorm on the space of measurable functions for which
this quantity is finite -/
def snorm' (f : α → F) (q : ℝ) (μ : measure α) : ℝ≥0∞ := (∫⁻ a, (nnnorm (f a))^q ∂μ) ^ (1/q)
/-- seminorm for `ℒ∞`, equal to the essential supremum of `∥f∥`. -/
def snorm_ess_sup (f : α → F) (μ : measure α) := ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) μ
/-- `ℒp` seminorm, equal to `0` for `p=0`, to `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and to
`ess_sup ∥f∥ μ` for `p = ∞`. -/
def snorm (f : α → F) (p : ℝ≥0∞) (μ : measure α) : ℝ≥0∞ :=
if p = 0 then 0 else (if p = ∞ then snorm_ess_sup f μ else snorm' f (ennreal.to_real p) μ)
lemma snorm_eq_snorm' (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} :
snorm f p μ = snorm' f (ennreal.to_real p) μ :=
by simp [snorm, hp_ne_zero, hp_ne_top]
@[simp] lemma snorm_exponent_top {f : α → F} : snorm f ∞ μ = snorm_ess_sup f μ := by simp [snorm]
/-- The property that `f:α→E` is ae_measurable and `(∫ ∥f a∥^p ∂μ)^(1/p)` is finite if `p < ∞`, or
`ess_sup f < ∞` if `p = ∞`. -/
def mem_ℒp (f : α → E) (p : ℝ≥0∞) (μ : measure α) : Prop :=
ae_measurable f μ ∧ snorm f p μ < ∞
lemma mem_ℒp.ae_measurable {f : α → E} {p : ℝ≥0∞} {μ : measure α} (h : mem_ℒp f p μ) :
ae_measurable f μ := h.1
lemma lintegral_rpow_nnnorm_eq_rpow_snorm' {f : α → F} (hq0_lt : 0 < q) :
∫⁻ a, (nnnorm (f a)) ^ q ∂μ = (snorm' f q μ) ^ q :=
begin
rw [snorm', ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one],
exact (ne_of_lt hq0_lt).symm,
end
end ℒp_space_definition
section top
lemma mem_ℒp.snorm_lt_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ < ∞ := hfp.2
lemma mem_ℒp.snorm_ne_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ ≠ ∞ := ne_of_lt (hfp.2)
lemma lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top {f : α → F} (hq0_lt : 0 < q)
(hfq : snorm' f q μ < ∞) :
∫⁻ a, (nnnorm (f a)) ^ q ∂μ < ∞ :=
begin
rw lintegral_rpow_nnnorm_eq_rpow_snorm' hq0_lt,
exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hq0_lt) (ne_of_lt hfq),
end
end top
section zero
@[simp] lemma snorm'_exponent_zero {f : α → F} : snorm' f 0 μ = 1 :=
by rw [snorm', div_zero, ennreal.rpow_zero]
@[simp] lemma snorm_exponent_zero {f : α → F} : snorm f 0 μ = 0 :=
by simp [snorm]
lemma mem_ℒp_zero_iff_ae_measurable {f : α → E} : mem_ℒp f 0 μ ↔ ae_measurable f μ :=
by simp [mem_ℒp, snorm_exponent_zero]
@[simp] lemma snorm'_zero (hp0_lt : 0 < q) : snorm' (0 : α → F) q μ = 0 :=
by simp [snorm', hp0_lt]
@[simp] lemma snorm'_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) : snorm' (0 : α → F) q μ = 0 :=
begin
cases le_or_lt 0 q with hq0 hq_neg,
{ exact snorm'_zero (lt_of_le_of_ne hq0 hq0_ne.symm), },
{ simp [snorm', ennreal.rpow_eq_zero_iff, hμ, hq_neg], },
end
@[simp] lemma snorm_ess_sup_zero : snorm_ess_sup (0 : α → F) μ = 0 :=
begin
simp_rw [snorm_ess_sup, pi.zero_apply, nnnorm_zero, ennreal.coe_zero, ←ennreal.bot_eq_zero],
exact ess_sup_const_bot,
end
@[simp] lemma snorm_zero : snorm (0 : α → F) p μ = 0 :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp only [h_top, snorm_exponent_top, snorm_ess_sup_zero], },
rw ←ne.def at h0,
simp [snorm_eq_snorm' h0 h_top,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
lemma zero_mem_ℒp : mem_ℒp (0 : α → E) p μ :=
⟨measurable_zero.ae_measurable, by { rw snorm_zero, exact ennreal.coe_lt_top, } ⟩
lemma snorm'_measure_zero_of_pos {f : α → F} (hq_pos : 0 < q) : snorm' f q 0 = 0 :=
by simp [snorm', hq_pos]
lemma snorm'_measure_zero_of_exponent_zero {f : α → F} : snorm' f 0 0 = 1 := by simp [snorm']
lemma snorm'_measure_zero_of_neg {f : α → F} (hq_neg : q < 0) : snorm' f q 0 = ∞ :=
by simp [snorm', hq_neg]
@[simp] lemma snorm_ess_sup_measure_zero {f : α → F} : snorm_ess_sup f 0 = 0 :=
by simp [snorm_ess_sup]
@[simp] lemma snorm_measure_zero {f : α → F} : snorm f p 0 = 0 :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top], },
rw ←ne.def at h0,
simp [snorm_eq_snorm' h0 h_top, snorm',
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
end zero
section const
lemma snorm'_const (c : F) (hq_pos : 0 < q) :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) :=
begin
rw [snorm', lintegral_const, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [hq_pos.le])],
congr,
rw ←ennreal.rpow_mul,
suffices hq_cancel : q * (1/q) = 1, by rw [hq_cancel, ennreal.rpow_one],
rw [one_div, mul_inv_cancel (ne_of_lt hq_pos).symm],
end
lemma snorm'_const' [finite_measure μ] (c : F) (hc_ne_zero : c ≠ 0) (hq_ne_zero : q ≠ 0) :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) :=
begin
rw [snorm', lintegral_const, ennreal.mul_rpow_of_ne_top _ (measure_ne_top μ set.univ)],
{ congr,
rw ←ennreal.rpow_mul,
suffices hp_cancel : q * (1/q) = 1, by rw [hp_cancel, ennreal.rpow_one],
rw [one_div, mul_inv_cancel hq_ne_zero], },
{ rw [ne.def, ennreal.rpow_eq_top_iff, auto.not_or_eq, auto.not_and_eq, auto.not_and_eq],
split,
{ left,
rwa [ennreal.coe_eq_zero, nnnorm_eq_zero], },
{ exact or.inl ennreal.coe_ne_top, }, },
end
lemma snorm_ess_sup_const (c : F) (hμ : μ ≠ 0) :
snorm_ess_sup (λ x : α, c) μ = (nnnorm c : ℝ≥0∞) :=
by rw [snorm_ess_sup, ess_sup_const _ hμ]
lemma snorm'_const_of_probability_measure (c : F) (hq_pos : 0 < q) [probability_measure μ] :
snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) :=
by simp [snorm'_const c hq_pos, measure_univ]
lemma snorm_const (c : F) (h0 : p ≠ 0) (hμ : μ ≠ 0) :
snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) :=
begin
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup_const c hμ], },
simp [snorm_eq_snorm' h0 h_top, snorm'_const,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
lemma snorm_const' (c : F) (h0 : p ≠ 0) (h_top: p ≠ ∞) :
snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) :=
begin
simp [snorm_eq_snorm' h0 h_top, snorm'_const,
ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩],
end
lemma mem_ℒp_const (c : E) [finite_measure μ] : mem_ℒp (λ a:α, c) p μ :=
begin
refine ⟨measurable_const.ae_measurable, _⟩,
by_cases h0 : p = 0,
{ simp [h0], },
by_cases hμ : μ = 0,
{ simp [hμ], },
rw snorm_const c h0 hμ,
refine ennreal.mul_lt_top ennreal.coe_lt_top _,
refine ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ),
simp,
end
end const
lemma snorm'_mono_ae {f : α → F} {g : α → G} (hq : 0 ≤ q) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) :
snorm' f q μ ≤ snorm' g q μ :=
begin
rw [snorm'],
refine ennreal.rpow_le_rpow _ (one_div_nonneg.2 hq),
refine lintegral_mono_ae (h.mono $ λ x hx, _),
exact ennreal.rpow_le_rpow (ennreal.coe_le_coe.2 hx) hq
end
lemma snorm'_congr_norm_ae {f g : α → F} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) :
snorm' f q μ = snorm' g q μ :=
begin
have : (λ x, (nnnorm (f x) ^ q : ℝ≥0∞)) =ᵐ[μ] (λ x, nnnorm (g x) ^ q),
from hfg.mono (λ x hx, by { simp only [← coe_nnnorm, nnreal.coe_eq] at hx, simp [hx] }),
simp only [snorm', lintegral_congr_ae this]
end
lemma snorm'_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm' f q μ = snorm' g q μ :=
snorm'_congr_norm_ae (hfg.fun_comp _)
lemma snorm_ess_sup_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) :
snorm_ess_sup f μ = snorm_ess_sup g μ :=
ess_sup_congr_ae (hfg.fun_comp (coe ∘ nnnorm))
lemma snorm_mono_ae {f : α → F} {g : α → G} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) :
snorm f p μ ≤ snorm g p μ :=
begin
simp only [snorm],
split_ifs,
{ exact le_rfl },
{ refine ess_sup_mono_ae (h.mono $ λ x hx, _),
exact_mod_cast hx },
{ exact snorm'_mono_ae ennreal.to_real_nonneg h }
end
lemma snorm_congr_norm_ae {f : α → F} {g : α → G} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) :
snorm f p μ = snorm g p μ :=
le_antisymm (snorm_mono_ae $ filter.eventually_eq.le hfg)
(snorm_mono_ae $ (filter.eventually_eq.symm hfg).le)
@[simp] lemma snorm_norm (f : α → F) : snorm (λ x, ∥f x∥) p μ = snorm f p μ :=
snorm_congr_norm_ae $ filter.eventually_of_forall $ λ x, norm_norm _
lemma snorm_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm f p μ = snorm g p μ :=
snorm_congr_norm_ae $ hfg.mono (λ x hx, hx ▸ rfl)
lemma mem_ℒp_congr_ae {f g : α → E} (hfg : f =ᵐ[μ] g) : mem_ℒp f p μ ↔ mem_ℒp g p μ :=
by simp only [mem_ℒp, snorm_congr_ae hfg, ae_measurable_congr hfg]
lemma mem_ℒp.ae_eq {f g : α → E} (hfg : f =ᵐ[μ] g) (hf_Lp : mem_ℒp f p μ) : mem_ℒp g p μ :=
(mem_ℒp_congr_ae hfg).1 hf_Lp
lemma mem_ℒp.of_le [measurable_space F] {f : α → E} {g : α → F}
(hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : mem_ℒp f p μ :=
⟨hf, (snorm_mono_ae hfg).trans_lt hg.snorm_lt_top⟩
section opens_measurable_space
variable [opens_measurable_space E]
lemma mem_ℒp.norm {f : α → E} (h : mem_ℒp f p μ) : mem_ℒp (λ x, ∥f x∥) p μ :=
h.of_le h.ae_measurable.norm (filter.eventually_of_forall (λ x, by simp))
lemma snorm'_eq_zero_of_ae_zero {f : α → F} (hq0_lt : 0 < q) (hf_zero : f =ᵐ[μ] 0) :
snorm' f q μ = 0 :=
by rw [snorm'_congr_ae hf_zero, snorm'_zero hq0_lt]
lemma snorm'_eq_zero_of_ae_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) {f : α → F} (hf_zero : f =ᵐ[μ] 0) :
snorm' f q μ = 0 :=
by rw [snorm'_congr_ae hf_zero, snorm'_zero' hq0_ne hμ]
lemma ae_eq_zero_of_snorm'_eq_zero {f : α → E} (hq0 : 0 ≤ q) (hf : ae_measurable f μ)
(h : snorm' f q μ = 0) : f =ᵐ[μ] 0 :=
begin
rw [snorm', ennreal.rpow_eq_zero_iff] at h,
cases h,
{ rw lintegral_eq_zero_iff' hf.nnnorm.ennreal_coe.ennreal_rpow_const at h,
refine h.left.mono (λ x hx, _),
rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx,
cases hx,
{ cases hx with hx _,
rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, },
{ exact absurd hx.left ennreal.coe_ne_top, }, },
{ exfalso,
rw [one_div, inv_lt_zero] at h,
exact hq0.not_lt h.right },
end
lemma snorm'_eq_zero_iff (hq0_lt : 0 < q) {f : α → E} (hf : ae_measurable f μ) :
snorm' f q μ = 0 ↔ f =ᵐ[μ] 0 :=
⟨ae_eq_zero_of_snorm'_eq_zero (le_of_lt hq0_lt) hf, snorm'_eq_zero_of_ae_zero hq0_lt⟩
lemma coe_nnnorm_ae_le_snorm_ess_sup (f : α → F) (μ : measure α) :
∀ᵐ x ∂μ, (nnnorm (f x) : ℝ≥0∞) ≤ snorm_ess_sup f μ :=
ennreal.ae_le_ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞))
@[simp] lemma snorm_ess_sup_eq_zero_iff {f : α → F} : snorm_ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 :=
by simp [filter.eventually_eq, snorm_ess_sup]
lemma snorm_eq_zero_iff {f : α → E} (hf : ae_measurable f μ) (h0 : p ≠ 0) :
snorm f p μ = 0 ↔ f =ᵐ[μ] 0 :=
begin
by_cases h_top : p = ∞,
{ rw [h_top, snorm_exponent_top, snorm_ess_sup_eq_zero_iff], },
rw snorm_eq_snorm' h0 h_top,
exact snorm'_eq_zero_iff
(ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩) hf,
end
end opens_measurable_space
@[simp] lemma snorm'_neg {f : α → F} : snorm' (-f) q μ = snorm' f q μ := by simp [snorm']
@[simp] lemma snorm_neg {f : α → F} : snorm (-f) p μ = snorm f p μ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup], },
simp [snorm_eq_snorm' h0 h_top],
end
section borel_space
variable [borel_space E]
lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (-f) p μ :=
⟨ae_measurable.neg hf.1, by simp [hf.right]⟩
lemma snorm'_le_snorm'_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q)
{f : α → E} (hf : ae_measurable f μ) :
snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) :=
begin
have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq,
by_cases hpq_eq : p = q,
{ rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one],
exact le_refl _, },
have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq,
let g := λ a : α, (1 : ℝ≥0∞),
have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ,
from lintegral_congr (λ a, by simp),
repeat {rw snorm'},
rw h_rw,
let r := p * q / (q - p),
have hpqr : 1/p = 1/q + 1/r,
{ field_simp [(ne_of_lt hp0_lt).symm,
(ne_of_lt hq0_lt).symm],
ring, },
calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p)
≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) :
ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.nnnorm.ennreal_coe
ae_measurable_const
... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) :
by simp [hpqr],
end
lemma snorm'_le_snorm_ess_sup_mul_rpow_measure_univ (hq_pos : 0 < q) {f : α → F} :
snorm' f q μ ≤ snorm_ess_sup f μ * (μ set.univ) ^ (1/q) :=
begin
have h_le : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ ≤ ∫⁻ (a : α), (snorm_ess_sup f μ) ^ q ∂μ,
{ refine lintegral_mono_ae _,
have h_nnnorm_le_snorm_ess_sup := coe_nnnorm_ae_le_snorm_ess_sup f μ,
refine h_nnnorm_le_snorm_ess_sup.mono (λ x hx, ennreal.rpow_le_rpow hx (le_of_lt hq_pos)), },
rw [snorm', ←ennreal.rpow_one (snorm_ess_sup f μ)],
nth_rewrite 1 ←mul_inv_cancel (ne_of_lt hq_pos).symm,
rw [ennreal.rpow_mul, one_div,
←@ennreal.mul_rpow_of_nonneg _ _ q⁻¹ (by simp [hq_pos.le])],
refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le]),
rwa lintegral_const at h_le,
end
lemma snorm'_le_snorm'_of_exponent_le {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α)
[probability_measure μ] {f : α → E} (hf : ae_measurable f μ) :
snorm' f p μ ≤ snorm' f q μ :=
begin
have h_le_μ := snorm'_le_snorm'_mul_rpow_measure_univ hp0_lt hpq hf,
rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ,
end
lemma snorm'_le_snorm_ess_sup (hq_pos : 0 < q) {f : α → F} [probability_measure μ] :
snorm' f q μ ≤ snorm_ess_sup f μ :=
le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hq_pos) (le_of_eq (by simp [measure_univ]))
lemma snorm_le_snorm_of_exponent_le {p q : ℝ≥0∞} (hpq : p ≤ q) [probability_measure μ]
{f : α → E} (hf : ae_measurable f μ) :
snorm f p μ ≤ snorm f q μ :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
rw ←ne.def at hp0,
by_cases hq_top : q = ∞,
{ by_cases hp_top : p = ∞,
{ rw [hq_top, hp_top],
exact le_refl _, },
{ have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
rw [snorm_eq_snorm' hp0 hp_top, hq_top, snorm_exponent_top],
refine le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) (le_of_eq _),
simp [measure_univ], }, },
{ have hp_top : p ≠ ∞,
{ by_contra hp_eq_top,
push_neg at hp_eq_top,
refine hq_top _,
rwa [hp_eq_top, top_le_iff] at hpq, },
have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
have hq0 : q ≠ 0,
{ by_contra hq_eq_zero,
push_neg at hq_eq_zero,
have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _),
rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos,
exact (lt_irrefl _) hp_pos, },
have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top,
rw [snorm_eq_snorm' hp0 hp_top, snorm_eq_snorm' hq0 hq_top],
exact snorm'_le_snorm'_of_exponent_le hp_pos hpq_real _ hf, },
end
lemma snorm'_lt_top_of_snorm'_lt_top_of_exponent_le {p q : ℝ} [finite_measure μ] {f : α → E}
(hf : ae_measurable f μ) (hfq_lt_top : snorm' f q μ < ∞) (hp_nonneg : 0 ≤ p) (hpq : p ≤ q) :
snorm' f p μ < ∞ :=
begin
cases le_or_lt p 0 with hp_nonpos hp_pos,
{ rw le_antisymm hp_nonpos hp_nonneg,
simp, },
have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq,
calc snorm' f p μ
≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) :
snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq hf
... < ∞ :
begin
rw ennreal.mul_lt_top_iff,
refine or.inl ⟨hfq_lt_top, ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)⟩,
rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos],
end
end
lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ℝ≥0∞} [finite_measure μ] {f : α → E}
(hfq : mem_ℒp f q μ) (hpq : p ≤ q) :
mem_ℒp f p μ :=
begin
cases hfq with hfq_m hfq_lt_top,
by_cases hp0 : p = 0,
{ rwa [hp0, mem_ℒp_zero_iff_ae_measurable], },
rw ←ne.def at hp0,
refine ⟨hfq_m, _⟩,
by_cases hp_top : p = ∞,
{ have hq_top : q = ∞,
by rwa [hp_top, top_le_iff] at hpq,
rw [hp_top],
rwa hq_top at hfq_lt_top, },
have hp_pos : 0 < p.to_real,
from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩,
by_cases hq_top : q = ∞,
{ rw snorm_eq_snorm' hp0 hp_top,
rw [hq_top, snorm_exponent_top] at hfq_lt_top,
refine lt_of_le_of_lt (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) _,
refine ennreal.mul_lt_top hfq_lt_top _,
exact ennreal.rpow_lt_top_of_nonneg (by simp [le_of_lt hp_pos]) (measure_ne_top μ set.univ), },
have hq0 : q ≠ 0,
{ by_contra hq_eq_zero,
push_neg at hq_eq_zero,
have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _),
rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos,
exact (lt_irrefl _) hp_pos, },
have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top,
rw snorm_eq_snorm' hp0 hp_top,
rw snorm_eq_snorm' hq0 hq_top at hfq_lt_top,
exact snorm'_lt_top_of_snorm'_lt_top_of_exponent_le hfq_m hfq_lt_top (le_of_lt hp_pos) hpq_real,
end
lemma snorm'_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hq1 : 1 ≤ q) :
snorm' (f + g) q μ ≤ snorm' f q μ + snorm' g q μ :=
calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q)
≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞))
+ (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) :
begin
refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [le_trans zero_le_one hq1]),
refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hq1)),
simp [←ennreal.coe_add, nnnorm_add_le],
end
... ≤ snorm' f q μ + snorm' g q μ :
ennreal.lintegral_Lp_add_le hf.nnnorm.ennreal_coe hg.nnnorm.ennreal_coe hq1
lemma snorm_ess_sup_add_le {f g : α → F} :
snorm_ess_sup (f + g) μ ≤ snorm_ess_sup f μ + snorm_ess_sup g μ :=
begin
refine le_trans (ess_sup_mono_ae (filter.eventually_of_forall (λ x, _)))
(ennreal.ess_sup_add_le _ _),
simp_rw [pi.add_apply, ←ennreal.coe_add, ennreal.coe_le_coe],
exact nnnorm_add_le _ _,
end
lemma snorm_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) :
snorm (f + g) p μ ≤ snorm f p μ + snorm g p μ :=
begin
by_cases hp0 : p = 0,
{ simp [hp0], },
by_cases hp_top : p = ∞,
{ simp [hp_top, snorm_ess_sup_add_le], },
have hp1_real : 1 ≤ p.to_real,
by rwa [← ennreal.one_to_real, ennreal.to_real_le_to_real ennreal.one_ne_top hp_top],
repeat { rw snorm_eq_snorm' hp0 hp_top, },
exact snorm'_add_le hf hg hp1_real,
end
lemma snorm_add_lt_top_of_one_le {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ)
(hq1 : 1 ≤ p) : snorm (f + g) p μ < ∞ :=
lt_of_le_of_lt (snorm_add_le hf.1 hg.1 hq1) (ennreal.add_lt_top.mpr ⟨hf.2, hg.2⟩)
lemma snorm'_add_lt_top_of_le_one {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ)
(hf_snorm : snorm' f q μ < ∞) (hg_snorm : snorm' g q μ < ∞) (hq_pos : 0 < q) (hq1 : q ≤ 1) :
snorm' (f + g) q μ < ∞ :=
calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q)
≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞))
+ (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) :
begin
refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [hq_pos.le]),
refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ hq_pos.le),
simp [←ennreal.coe_add, nnnorm_add_le],
end
... ≤ (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q + (nnnorm (g a) : ℝ≥0∞) ^ q ∂μ) ^ (1 / q) :
begin
refine @ennreal.rpow_le_rpow _ _ (1/q) (lintegral_mono (λ a, _)) (by simp [hq_pos.le]),
exact ennreal.rpow_add_le_add_rpow _ _ hq_pos hq1,
end
... < ∞ :
begin
refine @ennreal.rpow_lt_top_of_nonneg _ (1/q) (by simp [hq_pos.le]) _,
rw [lintegral_add' hf.nnnorm.ennreal_coe.ennreal_rpow_const
hg.nnnorm.ennreal_coe.ennreal_rpow_const, ennreal.add_ne_top, ←lt_top_iff_ne_top,
←lt_top_iff_ne_top],
exact ⟨lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hf_snorm,
lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hg_snorm⟩,
end
lemma snorm_add_lt_top {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
snorm (f + g) p μ < ∞ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
rw ←ne.def at h0,
cases le_total 1 p with hp1 hp1,
{ exact snorm_add_lt_top_of_one_le hf hg hp1, },
have hp_top : p ≠ ∞, from (lt_of_le_of_lt hp1 ennreal.coe_lt_top).ne,
have hp_pos : 0 < p.to_real,
{ rw [← ennreal.zero_to_real, @ennreal.to_real_lt_to_real 0 p ennreal.coe_ne_top hp_top],
exact ((zero_le p).lt_of_ne h0.symm), },
have hp1_real : p.to_real ≤ 1,
{ rwa [← ennreal.one_to_real, @ennreal.to_real_le_to_real p 1 hp_top ennreal.coe_ne_top], },
rw snorm_eq_snorm' h0 hp_top,
rw [mem_ℒp, snorm_eq_snorm' h0 hp_top] at hf hg,
exact snorm'_add_lt_top_of_le_one hf.1 hg.1 hf.2 hg.2 hp_pos hp1_real,
end
section second_countable_topology
variable [second_countable_topology E]
lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f + g) p μ :=
⟨ae_measurable.add hf.1 hg.1, snorm_add_lt_top hf hg⟩
lemma mem_ℒp.sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f - g) p μ :=
by { rw sub_eq_add_neg, exact hf.add hg.neg }
end second_countable_topology
end borel_space
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F]
lemma snorm'_const_smul {f : α → F} (c : 𝕜) (hq0_lt : 0 < q) :
snorm' (c • f) q μ = (nnnorm c : ℝ≥0∞) * snorm' f q μ :=
begin
rw snorm',
simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul,
ennreal.mul_rpow_of_nonneg _ _ (le_of_lt hq0_lt)],
suffices h_integral : ∫⁻ a, ↑(nnnorm c) ^ q * ↑(nnnorm (f a)) ^ q ∂μ
= (nnnorm c : ℝ≥0∞)^q * ∫⁻ a, (nnnorm (f a)) ^ q ∂μ,
{ apply_fun (λ x, x ^ (1/q)) at h_integral,
rw [h_integral, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [le_of_lt hq0_lt])],
congr,
simp_rw [←ennreal.rpow_mul, one_div, mul_inv_cancel (ne_of_lt hq0_lt).symm,
ennreal.rpow_one], },
rw lintegral_const_mul',
rw ennreal.coe_rpow_of_nonneg _ hq0_lt.le,
exact ennreal.coe_ne_top,
end
lemma snorm_ess_sup_const_smul {f : α → F} (c : 𝕜) :
snorm_ess_sup (c • f) μ = (nnnorm c : ℝ≥0∞) * snorm_ess_sup f μ :=
by simp_rw [snorm_ess_sup, pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.ess_sup_const_mul]
lemma snorm_const_smul {f : α → F} (c : 𝕜) :
snorm (c • f) p μ = (nnnorm c : ℝ≥0∞) * snorm f p μ :=
begin
by_cases h0 : p = 0,
{ simp [h0], },
by_cases h_top : p = ∞,
{ simp [h_top, snorm_ess_sup_const_smul], },
repeat { rw snorm_eq_snorm' h0 h_top, },
rw ←ne.def at h0,
exact snorm'_const_smul c
(ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩),
end
lemma mem_ℒp.const_smul [borel_space E] {f : α → E} (hf : mem_ℒp f p μ) (c : 𝕜) :
mem_ℒp (c • f) p μ :=
⟨ae_measurable.const_smul hf.1 c,
lt_of_le_of_lt (le_of_eq (snorm_const_smul c)) (ennreal.mul_lt_top ennreal.coe_lt_top hf.2)⟩
lemma mem_ℒp.const_mul [measurable_space 𝕜] [borel_space 𝕜]
{f : α → 𝕜} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (λ x, c * f x) p μ :=
hf.const_smul c
lemma snorm'_smul_le_mul_snorm' [opens_measurable_space E] [measurable_space 𝕜]
[opens_measurable_space 𝕜] {p q r : ℝ}
{f : α → E} (hf : ae_measurable f μ) {φ : α → 𝕜} (hφ : ae_measurable φ μ)
(hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) :
snorm' (φ • f) p μ ≤ snorm' φ q μ * snorm' f r μ :=
begin
simp_rw [snorm', pi.smul_apply', nnnorm_smul, ennreal.coe_mul],
exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.nnnorm.ennreal_coe
hf.nnnorm.ennreal_coe,
end
end normed_space
section monotonicity
lemma snorm_le_mul_snorm_aux_of_nonneg {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : 0 ≤ c) (p : ℝ≥0∞) :
snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ :=
begin
lift c to ℝ≥0 using hc,
rw [ennreal.of_real_coe_nnreal, ← c.nnnorm_eq, ← snorm_norm g, ← snorm_const_smul (c : ℝ)],
swap, apply_instance,
refine snorm_mono_ae _,
simpa
end
lemma snorm_le_mul_snorm_aux_of_neg {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : c < 0) (p : ℝ≥0∞) :
snorm f p μ = 0 ∧ snorm g p μ = 0 :=
begin
suffices : f =ᵐ[μ] 0 ∧ g =ᵐ[μ] 0,
by simp [snorm_congr_ae this.1, snorm_congr_ae this.2],
refine ⟨h.mono $ λ x hx, _, h.mono $ λ x hx, _⟩,
{ refine norm_le_zero_iff.1 (hx.trans _),
exact mul_nonpos_of_nonpos_of_nonneg hc.le (norm_nonneg _) },
{ refine norm_le_zero_iff.1 (nonpos_of_mul_nonneg_right _ hc),
exact (norm_nonneg _).trans hx }
end
lemma snorm_le_mul_snorm_of_ae_le_mul {f : α → F} {g : α → G} {c : ℝ}
(h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (p : ℝ≥0∞) :
snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ :=
begin
cases le_or_lt 0 c with hc hc,
{ exact snorm_le_mul_snorm_aux_of_nonneg h hc p },
{ simp [snorm_le_mul_snorm_aux_of_neg h hc p] }
end
lemma mem_ℒp.of_le_mul [measurable_space F] {f : α → E} {g : α → F} {c : ℝ}
(hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) :
mem_ℒp f p μ :=
begin
simp only [mem_ℒp, hf, true_and],
apply lt_of_le_of_lt (snorm_le_mul_snorm_of_ae_le_mul hfg p),
simp [lt_top_iff_ne_top, hg.snorm_ne_top],
end
end monotonicity
end ℒp
/-!
### Lp space
The space of equivalence classes of measurable functions for which `snorm f p μ < ∞`.
-/
@[simp] lemma snorm_ae_eq_fun {α E : Type*} [measurable_space α] {μ : measure α}
[measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hf : ae_measurable f μ) :
snorm (ae_eq_fun.mk f hf) p μ = snorm f p μ :=
snorm_congr_ae (ae_eq_fun.coe_fn_mk _ _)
lemma mem_ℒp.snorm_mk_lt_top {α E : Type*} [measurable_space α] {μ : measure α}
[measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hfp : mem_ℒp f p μ) :
snorm (ae_eq_fun.mk f hfp.1) p μ < ∞ :=
by simp [hfp.2]
/-- Lp space -/
def Lp {α} (E : Type*) [measurable_space α] [measurable_space E] [normed_group E]
[borel_space E] [second_countable_topology E]
(p : ℝ≥0∞) (μ : measure α) : add_subgroup (α →ₘ[μ] E) :=
{ carrier := {f | snorm f p μ < ∞},
zero_mem' := by simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero],
add_mem' := λ f g hf hg, by simp [snorm_congr_ae (ae_eq_fun.coe_fn_add _ _),
snorm_add_lt_top ⟨f.ae_measurable, hf⟩ ⟨g.ae_measurable, hg⟩],
neg_mem' := λ f hf,
by rwa [set.mem_set_of_eq, snorm_congr_ae (ae_eq_fun.coe_fn_neg _), snorm_neg] }
notation α ` →₁[`:25 μ `] ` E := measure_theory.Lp E 1 μ
namespace mem_ℒp
variables [borel_space E] [second_countable_topology E]
/-- make an element of Lp from a function verifying `mem_ℒp` -/
def to_Lp (f : α → E) (h_mem_ℒp : mem_ℒp f p μ) : Lp E p μ :=
⟨ae_eq_fun.mk f h_mem_ℒp.1, h_mem_ℒp.snorm_mk_lt_top⟩
lemma coe_fn_to_Lp {f : α → E} (hf : mem_ℒp f p μ) : hf.to_Lp f =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk _ _
@[simp] lemma to_Lp_eq_to_Lp_iff {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
hf.to_Lp f = hg.to_Lp g ↔ f =ᵐ[μ] g :=
by simp [to_Lp]
@[simp] lemma to_Lp_zero (h : mem_ℒp (0 : α → E) p μ ) : h.to_Lp 0 = 0 := rfl
lemma to_Lp_add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
(hf.add hg).to_Lp (f + g) = hf.to_Lp f + hg.to_Lp g := rfl
lemma to_Lp_neg {f : α → E} (hf : mem_ℒp f p μ) : hf.neg.to_Lp (-f) = - hf.to_Lp f := rfl
lemma to_Lp_sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
(hf.sub hg).to_Lp (f - g) = hf.to_Lp f - hg.to_Lp g :=
by { convert hf.to_Lp_add hg.neg, exact sub_eq_add_neg f g }
end mem_ℒp
namespace Lp
variables [borel_space E] [second_countable_topology E]
instance : has_coe_to_fun (Lp E p μ) := ⟨λ _, α → E, λ f, ((f : α →ₘ[μ] E) : α → E)⟩
@[ext] lemma ext {f g : Lp E p μ} (h : f =ᵐ[μ] g) : f = g :=
begin
cases f,
cases g,
simp only [subtype.mk_eq_mk],
exact ae_eq_fun.ext h
end
lemma ext_iff {f g : Lp E p μ} : f = g ↔ f =ᵐ[μ] g :=
⟨λ h, by rw h, λ h, ext h⟩
lemma mem_Lp_iff_snorm_lt_top {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ snorm f p μ < ∞ := iff.refl _
lemma mem_Lp_iff_mem_ℒp {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ mem_ℒp f p μ :=
by simp [mem_Lp_iff_snorm_lt_top, mem_ℒp, f.measurable.ae_measurable]
lemma antimono [finite_measure μ] {p q : ℝ≥0∞} (hpq : p ≤ q) : Lp E q μ ≤ Lp E p μ :=
λ f hf, (mem_ℒp.mem_ℒp_of_exponent_le ⟨f.ae_measurable, hf⟩ hpq).2
@[simp] lemma coe_fn_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) :
((⟨f, hf⟩ : Lp E p μ) : α → E) = f := rfl
@[simp] lemma coe_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) :
((⟨f, hf⟩ : Lp E p μ) : α →ₘ[μ] E) = f := rfl
@[simp] lemma to_Lp_coe_fn (f : Lp E p μ) (hf : mem_ℒp f p μ) : hf.to_Lp f = f :=
by { cases f, simp [mem_ℒp.to_Lp] }
lemma snorm_lt_top (f : Lp E p μ) : snorm f p μ < ∞ := f.prop
lemma snorm_ne_top (f : Lp E p μ) : snorm f p μ ≠ ∞ := (snorm_lt_top f).ne
protected lemma measurable (f : Lp E p μ) : measurable f := f.val.measurable
protected lemma ae_measurable (f : Lp E p μ) : ae_measurable f μ := f.val.ae_measurable
protected lemma mem_ℒp (f : Lp E p μ) : mem_ℒp f p μ := ⟨Lp.ae_measurable f, f.prop⟩
variables (E p μ)
lemma coe_fn_zero : ⇑(0 : Lp E p μ) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero
variables {E p μ}
lemma coe_fn_neg (f : Lp E p μ) : ⇑(-f) =ᵐ[μ] -f := ae_eq_fun.coe_fn_neg _
lemma coe_fn_add (f g : Lp E p μ) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _
lemma coe_fn_sub (f g : Lp E p μ) : ⇑(f - g) =ᵐ[μ] f - g := ae_eq_fun.coe_fn_sub _ _
lemma mem_Lp_const (α) [measurable_space α] (μ : measure α) (c : E) [finite_measure μ] :
@ae_eq_fun.const α _ _ μ _ c ∈ Lp E p μ :=
(mem_ℒp_const c).snorm_mk_lt_top
instance : has_norm (Lp E p μ) := { norm := λ f, ennreal.to_real (snorm f p μ) }
instance : has_dist (Lp E p μ) := { dist := λ f g, ∥f - g∥}
instance : has_edist (Lp E p μ) := { edist := λ f g, ennreal.of_real (dist f g) }
lemma norm_def (f : Lp E p μ) : ∥f∥ = ennreal.to_real (snorm f p μ) := rfl
@[simp] lemma norm_to_Lp (f : α → E) (hf : mem_ℒp f p μ) :
∥hf.to_Lp f∥ = ennreal.to_real (snorm f p μ) :=
by rw [norm_def, snorm_congr_ae (mem_ℒp.coe_fn_to_Lp hf)]
lemma dist_def (f g : Lp E p μ) : dist f g = (snorm (f - g) p μ).to_real :=
begin
simp_rw [dist, norm_def],
congr' 1,
apply snorm_congr_ae (coe_fn_sub _ _),
end
lemma edist_def (f g : Lp E p μ) : edist f g = snorm (f - g) p μ :=
begin
simp_rw [edist, dist, norm_def, ennreal.of_real_to_real (snorm_ne_top _)],
exact snorm_congr_ae (coe_fn_sub _ _)
end
@[simp] lemma edist_to_Lp_to_Lp (f g : α → E) (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) :
edist (hf.to_Lp f) (hg.to_Lp g) = snorm (f - g) p μ :=
by { rw edist_def, exact snorm_congr_ae (hf.coe_fn_to_Lp.sub hg.coe_fn_to_Lp) }
@[simp] lemma edist_to_Lp_zero (f : α → E) (hf : mem_ℒp f p μ) :
edist (hf.to_Lp f) 0 = snorm f p μ :=
by { convert edist_to_Lp_to_Lp f 0 hf zero_mem_ℒp, simp }
@[simp] lemma norm_zero : ∥(0 : Lp E p μ)∥ = 0 :=
begin
change (snorm ⇑(0 : α →ₘ[μ] E) p μ).to_real = 0,
simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero]
end
lemma norm_eq_zero_iff {f : Lp E p μ} (hp : 0 < p) : ∥f∥ = 0 ↔ f = 0 :=
begin
refine ⟨λ hf, _, λ hf, by simp [hf]⟩,
rw [norm_def, ennreal.to_real_eq_zero_iff] at hf,
cases hf,
{ rw snorm_eq_zero_iff (Lp.ae_measurable f) hp.ne.symm at hf,
exact subtype.eq (ae_eq_fun.ext (hf.trans ae_eq_fun.coe_fn_zero.symm)), },
{ exact absurd hf (snorm_ne_top f), },
end
lemma eq_zero_iff_ae_eq_zero {f : Lp E p μ} : f = 0 ↔ f =ᵐ[μ] 0 :=
begin
split,
{ assume h,
rw h,
exact ae_eq_fun.coe_fn_const _ _ },
{ assume h,
ext1,
filter_upwards [h, ae_eq_fun.coe_fn_const α (0 : E)],
assume a ha h'a,
rw ha,
exact h'a.symm }
end
@[simp] lemma norm_neg {f : Lp E p μ} : ∥-f∥ = ∥f∥ :=
by rw [norm_def, norm_def, snorm_congr_ae (coe_fn_neg _), snorm_neg]
lemma norm_le_mul_norm_of_ae_le_mul
[second_countable_topology F] [measurable_space F] [borel_space F]
{c : ℝ} {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : ∥f∥ ≤ c * ∥g∥ :=
begin
by_cases pzero : p = 0,
{ simp [pzero, norm_def] },
cases le_or_lt 0 c with hc hc,
{ have := snorm_le_mul_snorm_aux_of_nonneg h hc p,
rw [← ennreal.to_real_le_to_real, ennreal.to_real_mul, ennreal.to_real_of_real hc] at this,
{ exact this },
{ exact (Lp.mem_ℒp _).snorm_ne_top },
{ simp [(Lp.mem_ℒp _).snorm_ne_top] } },
{ have := snorm_le_mul_snorm_aux_of_neg h hc p,
simp only [snorm_eq_zero_iff (Lp.ae_measurable _) pzero, ← eq_zero_iff_ae_eq_zero] at this,
simp [this] }
end
lemma norm_le_norm_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F]
{f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : ∥f∥ ≤ ∥g∥ :=
begin
rw [norm_def, norm_def, ennreal.to_real_le_to_real (snorm_ne_top _) (snorm_ne_top _)],
exact snorm_mono_ae h
end
lemma mem_Lp_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F]
{c : ℝ} {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : f ∈ Lp E p μ :=
mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le_mul (Lp.mem_ℒp g) (ae_eq_fun.ae_measurable f) h
lemma mem_Lp_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F]
{f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : f ∈ Lp E p μ :=
mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le (Lp.mem_ℒp g) (ae_eq_fun.ae_measurable f) h
instance [hp : fact (1 ≤ p)] : normed_group (Lp E p μ) :=
normed_group.of_core _
{ norm_eq_zero_iff := λ f, norm_eq_zero_iff (ennreal.zero_lt_one.trans_le hp),
triangle := begin
assume f g,
simp only [norm_def],
rw ← ennreal.to_real_add (snorm_ne_top f) (snorm_ne_top g),
suffices h_snorm : snorm ⇑(f + g) p μ ≤ snorm ⇑f p μ + snorm ⇑g p μ,
{ rwa ennreal.to_real_le_to_real (snorm_ne_top (f + g)),
exact ennreal.add_ne_top.mpr ⟨snorm_ne_top f, snorm_ne_top g⟩, },
rw [snorm_congr_ae (coe_fn_add _ _)],
exact snorm_add_le (Lp.ae_measurable f) (Lp.ae_measurable g) hp,
end,
norm_neg := by simp }
instance normed_group_L1 : normed_group (Lp E 1 μ) := by apply_instance
instance normed_group_L2 : normed_group (Lp E 2 μ) := by apply_instance
instance normed_group_Ltop : normed_group (Lp E ∞ μ) := by apply_instance
section normed_space
variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E]
lemma mem_Lp_const_smul (c : 𝕜) (f : Lp E p μ) : c • ↑f ∈ Lp E p μ :=
begin
rw [mem_Lp_iff_snorm_lt_top, snorm_congr_ae (ae_eq_fun.coe_fn_smul _ _), snorm_const_smul,
ennreal.mul_lt_top_iff],
exact or.inl ⟨ennreal.coe_lt_top, f.prop⟩,
end
instance : has_scalar 𝕜 (Lp E p μ) := { smul := λ c f, ⟨c • ↑f, mem_Lp_const_smul c f⟩ }
lemma coe_fn_smul (c : 𝕜) (f : Lp E p μ) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _
instance : semimodule 𝕜 (Lp E p μ) :=
{ one_smul := λ _, subtype.eq (one_smul 𝕜 _),
mul_smul := λ _ _ _, subtype.eq (mul_smul _ _ _),
smul_add := λ _ _ _, subtype.eq (smul_add _ _ _),
smul_zero := λ _, subtype.eq (smul_zero _),
add_smul := λ _ _ _, subtype.eq (add_smul _ _ _),
zero_smul := λ _, subtype.eq (zero_smul _ _) }
lemma norm_const_smul (c : 𝕜) (f : Lp E p μ) : ∥c • f∥ = ∥c∥ * ∥f∥ :=
by rw [norm_def, snorm_congr_ae (coe_fn_smul _ _), snorm_const_smul c,
ennreal.to_real_mul, ennreal.coe_to_real, coe_nnnorm, norm_def]
instance [fact (1 ≤ p)] : normed_space 𝕜 (Lp E p μ) :=
{ norm_smul_le := λ _ _, by simp [norm_const_smul] }
instance normed_space_L1 : normed_space 𝕜 (Lp E 1 μ) := by apply_instance
instance normed_space_L2 : normed_space 𝕜 (Lp E 2 μ) := by apply_instance
instance normed_space_Ltop : normed_space 𝕜 (Lp E ∞ μ) := by apply_instance
end normed_space
end Lp
namespace mem_ℒp
variables
[borel_space E] [second_countable_topology E]
{𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E]
lemma to_Lp_const_smul {f : α → E} (c : 𝕜) (hf : mem_ℒp f p μ) :
(hf.const_smul c).to_Lp (c • f) = c • hf.to_Lp f := rfl
end mem_ℒp
end measure_theory
open measure_theory
/-!
### Composition on `L^p`
We show that Lipschitz functions vanishing at zero act by composition on `L^p`, and specialize
this to the composition with continuous linear maps, and to the definition of the positive
part of an `L^p` function.
-/
section composition
variables [second_countable_topology E] [borel_space E]
[second_countable_topology F] [measurable_space F] [borel_space F]
{g : E → F} {c : nnreal}
namespace lipschitz_with
/-- When `g` is a Lipschitz function sending `0` to `0` and `f` is in `Lp`, then `g ∘ f` is well
defined as an element of `Lp`. -/
def comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : Lp F p μ :=
⟨ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E),
begin
suffices : ∀ᵐ x ∂μ, ∥ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E) x∥ ≤ c * ∥f x∥,
{ exact Lp.mem_Lp_of_ae_le_mul this },
filter_upwards [ae_eq_fun.coe_fn_comp g hg.continuous.measurable (f : α →ₘ[μ] E)],
assume a ha,
simp only [ha],
rw [← dist_zero_right, ← dist_zero_right, ← g0],
exact hg.dist_le_mul (f a) 0,
end⟩
lemma coe_fn_comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) :
hg.comp_Lp g0 f =ᵐ[μ] g ∘ f :=
ae_eq_fun.coe_fn_comp _ _ _
@[simp] lemma comp_Lp_zero (hg : lipschitz_with c g) (g0 : g 0 = 0) :
hg.comp_Lp g0 (0 : Lp E p μ) = 0 :=
begin
rw Lp.eq_zero_iff_ae_eq_zero,
apply (coe_fn_comp_Lp _ _ _).trans,
filter_upwards [Lp.coe_fn_zero E p μ],
assume a ha,
simp [ha, g0]
end
lemma norm_comp_Lp_sub_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f f' : Lp E p μ) :
∥hg.comp_Lp g0 f - hg.comp_Lp g0 f'∥ ≤ c * ∥f - f'∥ :=
begin
apply Lp.norm_le_mul_norm_of_ae_le_mul,
filter_upwards [hg.coe_fn_comp_Lp g0 f, hg.coe_fn_comp_Lp g0 f',
Lp.coe_fn_sub (hg.comp_Lp g0 f) (hg.comp_Lp g0 f'), Lp.coe_fn_sub f f'],
assume a ha1 ha2 ha3 ha4,
simp [ha1, ha2, ha3, ha4, ← dist_eq_norm],
exact hg.dist_le_mul (f a) (f' a)
end
lemma norm_comp_Lp_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) :
∥hg.comp_Lp g0 f∥ ≤ c * ∥f∥ :=
by simpa using hg.norm_comp_Lp_sub_le g0 f 0
lemma lipschitz_with_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) :
lipschitz_with c (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) :=
lipschitz_with.of_dist_le_mul $ λ f g, by simp [dist_eq_norm, norm_comp_Lp_sub_le]
lemma continuous_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) :
continuous (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) :=
(lipschitz_with_comp_Lp hg g0).continuous
end lipschitz_with
namespace continuous_linear_map
variables [normed_space ℝ E] [normed_space ℝ F]
/-- Composing `f : Lp ` with `L : E →L[ℝ] F`. -/
def comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) : Lp F p μ :=
L.lipschitz.comp_Lp (map_zero L) f
lemma coe_fn_comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) :
∀ᵐ a ∂μ, (L.comp_Lp f) a = L (f a) :=
lipschitz_with.coe_fn_comp_Lp _ _ _
variables (μ p)
/-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `Lp E p μ`. -/
def comp_Lpₗ (L : E →L[ℝ] F) : (Lp E p μ) →ₗ[ℝ] (Lp F p μ) :=
{ to_fun := λ f, L.comp_Lp f,
map_add' := begin
intros f g,
ext1,
filter_upwards [Lp.coe_fn_add f g, coe_fn_comp_Lp L (f + g), coe_fn_comp_Lp L f,
coe_fn_comp_Lp L g, Lp.coe_fn_add (L.comp_Lp f) (L.comp_Lp g)],
assume a ha1 ha2 ha3 ha4 ha5,
simp only [ha1, ha2, ha3, ha4, ha5, map_add, pi.add_apply],
end,
map_smul' := begin
intros c f,
ext1,
filter_upwards [Lp.coe_fn_smul c f, coe_fn_comp_Lp L (c • f), Lp.coe_fn_smul c (L.comp_Lp f),
coe_fn_comp_Lp L f],
assume a ha1 ha2 ha3 ha4,
simp only [ha1, ha2, ha3, ha4, map_smul, pi.smul_apply],
end }
variables {μ p}
lemma norm_comp_Lp_le (L : E →L[ℝ] F) (f : Lp E p μ) : ∥L.comp_Lp f∥ ≤ ∥L∥ * ∥f∥ :=
lipschitz_with.norm_comp_Lp_le _ _ _
variables (μ p)
/-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on
`Lp E p μ`. -/
def comp_LpL [fact (1 ≤ p)] (L : E →L[ℝ] F) : (Lp E p μ) →L[ℝ] (Lp F p μ) :=
linear_map.mk_continuous (L.comp_Lpₗ p μ) ∥L∥ L.norm_comp_Lp_le
lemma norm_compLpL_le [fact (1 ≤ p)] (L : E →L[ℝ] F) :
∥L.comp_LpL p μ∥ ≤ ∥L∥ :=
linear_map.mk_continuous_norm_le _ (norm_nonneg _) _
end continuous_linear_map
namespace measure_theory
namespace Lp
section pos_part
lemma lipschitz_with_pos_part : lipschitz_with 1 (λ (x : ℝ), max x 0) :=
lipschitz_with.of_dist_le_mul $ λ x y, by simp [dist, abs_max_sub_max_le_abs]
/-- Positive part of a function in `L^p`. -/
def pos_part (f : Lp ℝ p μ) : Lp ℝ p μ :=
lipschitz_with_pos_part.comp_Lp (max_eq_right (le_refl _)) f
/-- Negative part of a function in `L^p`. -/
def neg_part (f : Lp ℝ p μ) : Lp ℝ p μ := pos_part (-f)
@[norm_cast]
lemma coe_pos_part (f : Lp ℝ p μ) : (pos_part f : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl
lemma coe_fn_pos_part (f : Lp ℝ p μ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 :=
ae_eq_fun.coe_fn_pos_part _
lemma coe_fn_neg_part_eq_max (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 :=
begin
rw neg_part,
filter_upwards [coe_fn_pos_part (-f), coe_fn_neg f],
assume a h₁ h₂,
rw [h₁, h₂, pi.neg_apply]
end
lemma coe_fn_neg_part (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 :=
(coe_fn_neg_part_eq_max f).mono $ assume a h,
by rw [h, ← max_neg_neg, neg_zero]
lemma continuous_pos_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, pos_part f) :=
lipschitz_with.continuous_comp_Lp _ _
lemma continuous_neg_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, neg_part f) :=
have eq : (λf : Lp ℝ p μ, neg_part f) = (λf : Lp ℝ p μ, pos_part (-f)) := rfl,
by { rw eq, exact continuous_pos_part.comp continuous_neg }
end pos_part
end Lp
end measure_theory
end composition
|
76f6d1f1d834e61b94f0f825a022cb5d78f6b4a5 | bb31430994044506fa42fd667e2d556327e18dfe | /src/tactic/ring_exp.lean | e39e2ff0db77e3b2178961a67eeab1c867341f15 | [
"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 | 57,279 | lean | /-
Copyright (c) 2019 Tim Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baanen
-/
import tactic.norm_num
import control.traversable.basic
/-!
# `ring_exp` tactic
A tactic for solving equations in commutative (semi)rings,
where the exponents can also contain variables.
More precisely, expressions of the following form are supported:
- constants (non-negative integers)
- variables
- coefficients (any rational number, embedded into the (semi)ring)
- addition of expressions
- multiplication of expressions
- exponentiation of expressions (the exponent must have type `ℕ`)
- subtraction and negation of expressions (if the base is a full ring)
The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`,
something that the `ring` tactic cannot do, but `ring_exp` can.
## Implementation notes
The basic approach to prove equalities is to normalise both sides and check for equality.
The normalisation is guided by building a value in the type `ex` at the meta level,
together with a proof (at the base level) that the original value is equal to
the normalised version.
The normalised version and normalisation proofs are also stored in the `ex` type.
The outline of the file:
- Define an inductive family of types `ex`, parametrised over `ex_type`,
which can represent expressions with `+`, `*`, `^` and rational numerals.
The parametrisation over `ex_type` ensures that associativity and distributivity are applied,
by restricting which kinds of subexpressions appear as arguments to the various operators.
- Represent addition, multiplication and exponentiation in the `ex` type,
thus allowing us to map expressions to `ex` (the `eval` function drives this).
We apply associativity and distributivity of the operators here (helped by `ex_type`)
and commutativity as well (by sorting the subterms; unfortunately not helped by anything).
Any expression not of the above formats is treated as an atom (the same as a variable).
There are some details we glossed over which make the plan more complicated:
- The order on atoms is not initially obvious.
We construct a list containing them in order of initial appearance in the expression,
then use the index into the list as a key to order on.
- In the tactic, a normalized expression `ps : ex` lives in the meta-world,
but the normalization proofs live in the real world.
Thus, we cannot directly say `ps.orig = ps.pretty` anywhere,
but we have to carefully construct the proof when we compute `ps`.
This was a major source of bugs in development!
- For `pow`, the exponent must be a natural number, while the base can be any semiring `α`.
We swap out operations for the base ring `α` with those for the exponent ring `ℕ`
as soon as we deal with exponents.
This is accomplished by the `in_exponent` function and is relatively painless since
we work in a `reader` monad.
- The normalized form of an expression is the one that is useful for the tactic,
but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`.
## Caveats and future work
Subtraction cancels out identical terms, but division does not.
That is: `a - a = 0 := by ring_exp` solves the goal,
but `a / a := 1 by ring_exp` doesn't.
Note that `0 / 0` is generally defined to be `0`,
so division cancelling out is not true in general.
Multiplication of powers can be simplified a little bit further:
`2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented
in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works.
This feature wasn't needed yet, so it's not implemented yet.
## Tags
ring, semiring, exponent, power
-/
-- The base ring `α` will have a universe level `u`.
-- We do not introduce `α` as a variable yet,
-- in order to make it explicit or implicit as required.
universes u
namespace tactic.ring_exp
open nat
/--
The `atom` structure is used to represent atomic expressions:
those which `ring_exp` cannot parse any further.
For instance, `a + (a % b)` has `a` and `(a % b)` as atoms.
The `ring_exp_eq` tactic does not normalize the subexpressions in atoms,
but `ring_exp` does if `ring_exp_eq` was not sufficient.
Atoms in fact represent equivalence classes of expressions,
modulo definitional equality.
The field `index : ℕ` should be a unique number for each class,
while `value : expr` contains a representative of this class.
The function `resolve_atom` determines the appropriate atom
for a given expression.
-/
meta structure atom : Type := (value : expr) (index : ℕ)
namespace atom
/--
The `eq` operation on `atom`s works modulo definitional equality,
ignoring their `value`s.
The invariants on `atom` ensure indices are unique per value.
Thus, `eq` indicates equality as long as the `atom`s come from the same context.
-/
meta def eq (a b : atom) : bool := a.index = b.index
/--
We order `atom`s on the order of appearance in the main expression.
-/
meta def lt (a b : atom) : bool := a.index < b.index
meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩
end atom
section expression
/-!
### `expression` section
In this section, we define the `ex` type and its basic operations.
First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`.
For understanding the code, it's easier to check out `ex` itself first,
then refer back to the supporting types.
The arithmetic operations on `ex` need additional definitions,
so they are defined in a later section.
-/
/--
Coefficients in the expression are stored in a wrapper structure,
allowing for easier modification of the data structures.
The modifications might be caching of the result of `expr.of_rat`,
or using a different meta representation of numerals.
-/
@[derive decidable_eq, derive inhabited]
structure coeff : Type := (value : ℚ)
/-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/
@[derive decidable_eq, derive inhabited]
inductive ex_type : Type
| base : ex_type
| sum : ex_type
| prod : ex_type
| exp : ex_type
open ex_type
/--
Each `ex` stores information for its normalization proof.
The `orig` expression is the expression that was passed to `eval`.
The `pretty` expression is the normalised form that the `ex` represents.
(I didn't call this something like `norm`, because there are already
too many things called `norm` in mathematics!)
The field `proof` contains an optional proof term of type `%%orig = %%pretty`.
The value `none` for the proof indicates that everything reduces to reflexivity.
(Which saves space in quite a lot of cases.)
-/
meta structure ex_info : Type :=
(orig : expr) (pretty : expr) (proof : option expr)
/--
The `ex` type is an abstract representation of an expression with `+`, `*` and `^`.
Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively.
The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented
by (something along the lines of) `sum 1 (sum 2 zero)`.
The `coeff` constructor is the base case for `ex prod`, and is used for numerals.
The code maintains the invariant that the coefficient is never `0`.
The `var` constructor is the base case for `ex exp`, and is used for atoms.
The `sum_b` constructor allows for addition in the base of an exponentiation;
it serves a similar purpose as the parentheses in `(a + b)^c`.
The code maintains the invariant that the argument to `sum_b` is not `zero`
or `sum _ zero`.
All of the constructors contain an `ex_info` field,
used to carry around (arguments to) proof terms.
While the `ex_type` parameter enforces some simplification invariants,
the following ones must be manually maintained at the risk of insufficient power:
- the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`)
- the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`)
- normalisation proofs of subexpressions must be `refl ps.pretty`
- if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted
according to the `lt` relation defined further down; similarly for `prod` and `coeff`
(to ensure `a + b = b + a`).
The first two invariants could be encoded in a subtype of `ex`,
but aren't (yet) to spare some implementation burden.
The other invariants cannot be encoded because we need the `tactic` monad to check them.
(For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.)
-/
meta inductive ex : ex_type → Type
| zero (info : ex_info) : ex sum
| sum (info : ex_info) : ex prod → ex sum → ex sum
| coeff (info : ex_info) : coeff → ex prod
| prod (info : ex_info) : ex exp → ex prod → ex prod
| var (info : ex_info) : atom → ex base
| sum_b (info : ex_info) : ex sum → ex base
| exp (info : ex_info) : ex base → ex prod → ex exp
/--
Return the proof information associated to the `ex`.
-/
meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info
| sum (ex.zero i) := i
| sum (ex.sum i _ _) := i
| prod (ex.coeff i _) := i
| prod (ex.prod i _ _) := i
| base (ex.var i _) := i
| base (ex.sum_b i _) := i
| exp (ex.exp i _ _) := i
/--
Return the original, non-normalized version of this `ex`.
Note that arguments to another `ex` are always "pre-normalized":
their `orig` and `pretty` are equal, and their `proof` is reflexivity.
-/
meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig
/--
Return the normalized version of this `ex`.
-/
meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty
/--
Return the normalisation proof of the given expression.
If the proof is `refl`, we give `none` instead,
which helps to control the size of proof terms.
To get an actual term, use `ex.proof_term`,
or use `mk_proof` with the correct set of arguments.
-/
meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof
/--
Update the `orig` and `proof` fields of the `ex_info`.
Intended for use in `ex.set_info`.
-/
meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info :=
{orig := o.get_or_else i.pretty, proof := pf, .. i}
/--
Update the `ex_info` of the given expression.
We use this to combine intermediate normalisation proofs.
Since `pretty` only depends on the subexpressions,
which do not change, we do not set `pretty`.
-/
meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et
| sum (ex.zero i) o pf := ex.zero (i.set o pf)
| sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps
| prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x
| prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps
| base (ex.var i x) o pf := ex.var (i.set o pf) x
| base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps
| exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps
instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩
/-- Convert an `ex` to a `string`. -/
meta def ex.repr : Π {et : ex_type}, ex et → string
| sum (ex.zero _) := "0"
| sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps
| prod (ex.coeff _ x) := repr x
| prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps
| base (ex.var _ x) := repr x
| base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")"
| exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps
meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩
/--
Equality test for expressions.
Since equivalence of `atom`s is not the same as equality,
we cannot make a true `(=)` operator for `ex` either.
-/
meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool
| sum (ex.zero _) (ex.zero _) := tt
| sum (ex.zero _) (ex.sum _ _ _) := ff
| sum (ex.sum _ _ _) (ex.zero _) := ff
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs
| prod (ex.coeff _ x) (ex.coeff _ y) := x = y
| prod (ex.coeff _ _) (ex.prod _ _ _) := ff
| prod (ex.prod _ _ _) (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs
| base (ex.var _ x) (ex.var _ y) := x.eq y
| base (ex.var _ _) (ex.sum_b _ _) := ff
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs
/--
The ordering on expressions.
As for `ex.eq`, this is a linear order only in one context.
-/
meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool
| sum _ (ex.zero _) := ff
| sum (ex.zero _) _ := tt
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1
| prod (ex.coeff _ _) _ := tt
| prod _ (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| base (ex.var _ x) (ex.var _ y) := x.lt y
| base (ex.var _ _) (ex.sum_b _ _) := tt
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs)
end expression
section operations
/-!
### `operations` section
This section defines the operations (on `ex`) that use tactics.
They live in the `ring_exp_m` monad,
which adds a cache and a list of encountered atoms to the `tactic` monad.
Throughout this section, we will be constructing proof terms.
The lemmas used in the construction are all defined over a commutative semiring α.
-/
variables {α : Type u} [comm_semiring α]
open tactic
open ex_type
/--
Stores the information needed in the `eval` function and its dependencies,
so they can (re)construct expressions.
The `eval_info` structure stores this information for one type,
and the `context` combines the two types, one for bases and one for exponents.
-/
meta structure eval_info :=
(α : expr) (univ : level)
-- Cache the instances for optimization and consistency
(csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr)
-- Optional instances (only required for (-) and (/) respectively)
(ring_instance : option expr) (dr_instance : option expr)
-- Cache common constants.
(zero : expr) (one : expr)
/--
The `context` contains the full set of information needed for the `eval` function.
This structure has two copies of `eval_info`:
one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`).
When evaluating an exponent, we put `info_e` in `info_b`.
-/
meta structure context :=
(info_b : eval_info) (info_e : eval_info) (transp : transparency)
/--
The `ring_exp_m` monad is used instead of `tactic` to store the context.
-/
@[derive [monad, alternative]]
meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α
/--
Access the instance cache.
-/
meta def get_context : ring_exp_m context := reader_t.read
/--
Lift an operation in the `tactic` monad to the `ring_exp_m` monad.
This operation will not access the cache.
-/
meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m)
/--
Change the context of the given computation,
so that expressions are evaluated in the exponent ring,
instead of the base ring.
-/
meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do
ctx ← get_context,
reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class f (ctx.info_b.csr_instance) args
/--
Specialized version of `mk_app ``has_add.add`.
Should be faster because it can use the cached instances.
-/
meta def mk_add (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_add.add ctx.info_b.ha_instance args
/--
Specialized version of `mk_app ``has_mul.mul`.
Should be faster because it can use the cached instances.
-/
meta def mk_mul (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_mul.mul ctx.info_b.hm_instance args
/--
Specialized version of `mk_app ``has_pow.pow`.
Should be faster because it can use the cached instances.
-/
meta def mk_pow (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt ``has_pow.pow
[ctx.info_b.univ, ctx.info_e.univ]
ctx.info_b.α ctx.info_e.α
ctx.info_b.hp_instance).mk_app args
/-- Construct a normalization proof term or return the cached one. -/
meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr :=
match ps.proof with
| none := lift $ tactic.mk_eq_refl ps.pretty
| (some p) := pure p
end
/-- Construct a normalization proof term or return the cached one. -/
meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term
/--
If all `ex_info` have trivial proofs, return a trivial proof.
Otherwise, construct all proof terms.
Useful in applications where trivial proofs combine to another trivial proof,
most importantly to pass to `mk_proof_or_refl`.
-/
meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr))
| [] := pure none
| (x :: xs) := do
xs_pfs ← none_or_proof_term xs,
match (x.proof, xs_pfs) with
| (none, none) := pure none
| (some x_pf, none) := do
xs_pfs ← traverse ex_info.proof_term xs,
pure (some (x_pf :: xs_pfs))
| (_, some xs_pfs) := do
x_pf ← x.proof_term,
pure (some (x_pf :: xs_pfs))
end
/--
Use the proof terms as arguments to the given lemma.
If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.`
-/
meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do
hs' ← traverse ex_info.proof_term hs,
mk_app_csr lem (args ++ hs')
/--
Use the proof terms as arguments to the given lemma.
Often, we construct a proof term using congruence where reflexivity suffices.
To solve this, the following function tries to get away with reflexivity.
-/
meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) :
ring_exp_m expr := do
hs_full ← none_or_proof_term hs,
match hs_full with
| none := lift $ mk_eq_refl term
| (some hs') := mk_app_csr lem (args ++ hs')
end
/-- A shortcut for adding the original terms of two expressions. -/
meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_add [ps.orig, qs.orig]
/-- A shortcut for multiplying the original terms of two expressions. -/
meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_mul [ps.orig, qs.orig]
/-- A shortcut for exponentiating the original terms of two expressions. -/
meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_pow [ps.orig, qs.orig]
/-- Congruence lemma for constructing `ex.sum`. -/
lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc
/-- Congruence lemma for constructing `ex.prod`. -/
lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc
/-- Congruence lemma for constructing `ex.exp`. -/
lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc
/-- Constructs `ex.zero` with the correct arguments. -/
meta def ex_zero : ring_exp_m (ex sum) := do
ctx ← get_context,
pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩
/-- Constructs `ex.sum` with the correct arguments. -/
meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do
pps_o ← add_orig p ps,
pps_p ← mk_add [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``sum_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/--
Constructs `ex.coeff` with the correct arguments.
There are more efficient constructors for specific numerals:
if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`.
-/
meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do
ctx ← get_context,
x_p ← lift $ expr.of_rat ctx.info_b.α x,
pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩)
/--
Constructs `ex.coeff 1` with the correct arguments.
This is a special case for optimization purposes.
-/
meta def ex_one : ring_exp_m (ex prod) := do
ctx ← get_context,
pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩
/-- Constructs `ex.prod` with the correct arguments. -/
meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do
pps_o ← mul_orig p ps,
pps_p ← mk_mul [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``prod_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/-- Constructs `ex.var` with the correct arguments. -/
meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p)
/-- Constructs `ex.sum_b` with the correct arguments. -/
meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) :=
pure (ex.sum_b ps.info (ps.set_info none none))
/-- Constructs `ex.exp` with the correct arguments. -/
meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do
ctx ← get_context,
pps_o ← pow_orig p ps,
pps_p ← mk_pow [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``exp_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp
/-- Conversion from `ex base` to `ex exp`. -/
meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do
o ← in_exponent $ ex_one,
ps ← ex_exp p o,
pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp
/-- Conversion from `ex exp` to `ex prod`. -/
meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do
o ← ex_one,
ps ← ex_prod p o,
pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp
/-- Conversion from `ex prod` to `ex sum`. -/
meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do
z ← ex_zero,
ps ← ex_sum p z,
pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp
/--
A more efficient conversion from `atom` to `ex sum`.
The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`,
except we need to calculate less intermediate steps.
-/
meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do
p' ← ex_var p,
o ← in_exponent $ ex_one,
p' ← ex_exp p' o,
o ← ex_one,
p' ← ex_prod p' o,
z ← ex_zero,
p' ← ex_sum p' z,
pf ← mk_proof ``atom_to_sum_pf [p.1] [],
pure $ p'.set_info p.1 pf
/--
Compute the sum of two coefficients.
Note that the result might not be a valid expression:
if `p = -q`, then the result should be `ex.zero : ex sum` instead.
The caller must detect when this happens!
The returned value is of the form `ex.coeff _ (p + q)`,
with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`.
-/
meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq_o ← mk_add [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq_o,
pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩
lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q
lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p
/--
Compute the product of two coefficients.
The returned value is of the form `ex.coeff _ (p * q)`,
with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`.
-/
meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) :=
match p.1, q.1 with -- Special case to speed up multiplication with 1.
| ⟨1, 1, _, _⟩, _ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p],
pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩
| _, ⟨1, 1, _, _⟩ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p],
pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩
| _, _ := do
ctx ← get_context,
pq' ← mk_mul [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
end
section rewrite
/-! ### `rewrite` section
In this section we deal with rewriting terms to fit in the basic grammar of `eval`.
For example, `nat.succ n` is rewritten to `n + 1` before it is evaluated further.
-/
/-- Given a proof that the expressions `ps_o` and `ps'.orig` are equal,
show that `ps_o` and `ps'.pretty` are equal.
Useful to deal with aliases in `eval`. For instance, `nat.succ p` can be handled
as an alias of `p + 1` as follows:
```
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
```
-/
meta def rewrite (ps_o : expr) (ps' : ex sum) (pf : expr) : ring_exp_m (ex sum) :=
do
ps'_pf ← ps'.info.proof_term,
pf ← lift $ mk_eq_trans pf ps'_pf,
pure $ ps'.set_info ps_o pf
end rewrite
/--
Represents the way in which two products are equal except coefficient.
This type is used in the function `add_overlap`.
In order to deal with equations of the form `a * 2 + a = 3 * a`,
the `add` function will add up overlapping products,
turning `a * 2 + a` into `a * 3`.
We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this,
and the `overlap` type carries the information on how it overlaps.
The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`;
the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a`
(the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`);
the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`.
We distinguish those two cases because in the second, the whole product reduces to `0`.
A potential extension to the tactic would also do this for the base of exponents,
e.g. to show `2^n * 2^n = 4^n`.
-/
meta inductive overlap : Type
| none : overlap
| nonzero : ex prod → overlap
| zero : ex sum → overlap
lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * pq : by rw pq_pf
lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * 0 : by rw pq_pf
... = 0 : mul_zero _
/--
Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively
return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients).
For other arguments, return `overlap.none`.
-/
meta def add_overlap : ex prod → ex prod → ring_exp_m overlap
| (ex.coeff x_i x) (ex.coeff y_i y) := do
xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y
| lift $ fail "internal error: add_coeff should return ex.coeff",
if xy_c.1 = 0
then do
z ← ex_zero,
pure $ overlap.zero (z.set_info xy.orig xy.proof)
else pure $ overlap.nonzero xy
| (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none
| (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none
| pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q
then do
pq_ol ← add_overlap ps qs,
pqs_o ← add_orig pps qqs,
match pq_ol with
| overlap.none := pure overlap.none
| (overlap.nonzero pq) := do
pqs ← ex_prod p pq,
pf ← mk_proof ``add_overlap_pf
[ps.pretty, qs.pretty, pq.pretty, p.pretty]
[pq.info],
pure $ overlap.nonzero (pqs.set_info pqs_o pf)
| (overlap.zero pq) := do
z ← ex_zero,
pf ← mk_proof ``add_overlap_pf_zero
[ps.pretty, qs.pretty, p.pretty]
[pq.info],
pure $ overlap.zero (z.set_info pqs_o pf)
end
else pure overlap.none
section addition
lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc
ps + qs = 0 + qs' : by rw [ps_pf, qs_pf]
... = qs' : zero_add _
lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc
ps + qs = ps' + 0 : by rw [ps_pf, qs_pf]
... = ps' : add_zero _
lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} :
pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc
lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} :
pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs :=
λ pps_pf qqs_pf pq_pf pqs_pf, calc
pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf]
... = (p + q) + (ps + qs) : by cc
... = 0 + pqs : by rw [pq_pf, pqs_pf]
... = pqs : zero_add _
lemma add_pf_sum_lt {pps p ps qqs pqs : α} :
pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc
lemma add_pf_sum_gt {pps qqs q qs pqs : α} :
qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc
/--
Add two expressions.
* `0 + qs = 0`
* `ps + 0 = 0`
* `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`)
* `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`)
* `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`)
-/
meta def add : ex sum → ex sum → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ qs.set_info pqs_o pf
| ps qs@(ex.zero qs_i) := do
pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ ps.set_info pqs_o pf
| pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do
ol ← add_overlap p q,
ppqqs_o ← add_orig pps qqs,
match ol with
| (overlap.nonzero pq) := do
pqs ← add ps qs,
pqqs ← ex_sum pq pqs,
qqs_pf ← qqs.proof_term,
pf ← mk_proof ``add_pf_sum_overlap
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
| (overlap.zero pq) := do
pqs ← add ps qs,
pf ← mk_proof ``add_pf_sum_overlap_zero
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqs.set_info ppqqs_o pf
| overlap.none := if p.lt q
then do
pqs ← add ps qqs,
ppqs ← ex_sum p pqs,
pf ← mk_proof ``add_pf_sum_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← add pps qs,
pqqs ← ex_sum q pqs,
pf ← mk_proof ``add_pf_sum_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
end addition
section multiplication
lemma mul_pf_c_c {ps ps' qs qs' pq : α} :
ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc
lemma mul_pf_c_prod {ps qqs q qs pqs : α} :
qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc
lemma mul_pf_prod_c {pps p ps qs pqs : α} :
pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc
lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} :
pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs →
p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs
:= λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, pow_add, ps_pf, qs_pf]; ac_refl
lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} :
pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc
lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} :
qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc
/--
Multiply two expressions.
* `x * y = (x * y)` (for `x`, `y` coefficients)
* `x * (q * qs) = q * (qs * x)` (for `x` coefficient)
* `(p * ps) * y = p * (ps * y)` (for `y` coefficient)
* `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)`
(if `p_e` and `q_e` are identical except coefficient)
* `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`)
* `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`)
-/
meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do
pq ← mul_coeff ps.pretty qs.pretty x y,
pq_o ← mul_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c
[ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do
pqs ← mul_pp ps qs,
pqqs ← ex_prod q pqs,
pqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_c_prod
[ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do
pqs ← mul_pp ps qs,
ppqs ← ex_prod p pqs,
ppqs_o ← mul_orig pps qs,
pf ← mk_proof ``mul_pf_prod_c
[pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqs_o pf
| pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do
ppqqs_o ← mul_orig pps qqs,
pq_ol ← in_exponent $ add_overlap p_e q_e,
match pq_ol, p_b.eq q_b with
| (overlap.nonzero pq_e), tt := do
psqs ← mul_pp ps qs,
pq ← ex_exp p_b pq_e,
ppsqqs ← ex_prod pq psqs,
pf ← mk_proof ``mul_pp_pf_overlap
[pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty]
[pps.info, qqs.info, ppsqqs.info],
pure $ ppsqqs.set_info ppqqs_o pf
| _, _ := if p.lt q then do
pqs ← mul_pp ps qqs,
ppqs ← ex_prod p pqs,
pf ← mk_proof ``mul_pp_pf_prod_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← mul_pp pps qs,
pqqs ← ex_prod q pqs,
pf ← mk_proof ``mul_pp_pf_prod_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 :=
λ ps_pf, by rw [ps_pf, zero_mul]
lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps →
p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc
pps * qs = (p + ps) * qs : by rw [pps_pf]
... = p * qs + ps * qs : add_mul _ _ _
... = ppsqs : ppsqs_pf
/--
Multiply two expressions.
* `0 * qs = 0`
* `(p + ps) * qs = (p * qs) + (ps * qs)`
-/
meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info],
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p ps) qs := do
pqs ← mul_pp p qs >>= prod_to_sum,
psqs ← mul_p ps qs,
ppsqs ← add pqs psqs,
pps_pf ← pps.proof_term,
ppsqs_o ← mul_orig pps qs,
ppsqs_pf ← ppsqs.proof_term,
pf ← mk_proof ``mul_p_pf_sum
[pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty]
[pps.info, ppsqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 :=
λ qs_pf, by rw [qs_pf, mul_zero]
lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs →
ps * qqs = psqqs := λ qs_pf psqqs_pf, calc
ps * qqs = ps * (q + qs) : by rw [qs_pf]
... = ps * q + ps * qs : mul_add _ _ _
... = psqqs : psqqs_pf
/--
Multiply two expressions.
* `ps * 0 = 0`
* `ps * (q + qs) = (ps * q) + (ps * qs)`
-/
meta def mul : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info],
pure $ z.set_info z_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← mul_p ps q,
psqs ← mul ps qs,
psqqs ← add psq psqs,
psqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_sum
[ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end multiplication
section exponentiation
lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} :
pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs :=
λ pps_pf psqs_pf, calc
pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf]
... = p ^ (ps * qs) : symm (pow_mul _ _ _)
... = p ^ psqs : by rw [psqs_pf]
/--
Compute the exponentiation of two coefficients.
The returned value is of the form `ex.coeff _ (p ^ q)`,
with the proof of `expr.of_rat p ^ expr.of_rat q = expr.of_rat (p ^ q)`.
-/
meta def pow_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq' ← mk_pow [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_pow pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
/--
Exponentiate two expressions.
* `(p ^ ps) ^ qs = p ^ (ps * qs)`
-/
meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp)
| pps@(ex.exp pps_i p ps) qs := do
psqs ← in_exponent $ mul_pp ps qs,
ppsqs ← ex_exp p psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_e_pf_exp
[pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty]
[pps.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 :=
λ ps_pf, by rw [ps_pf, one_pow]
lemma pow_pf_c_c {ps ps' pq : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pq → ps ^ qs = pq := by cc
lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 :=
by simp; cc
lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps →
p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs :=
λ pps_pf pqs_pf psqs_pf, calc
pps ^ qs = (p * ps) ^ qs : by rw [pps_pf]
... = p ^ qs * ps ^ qs : mul_pow _ _ _
... = pqs * psqs : by rw [pqs_pf, psqs_pf]
/--
Exponentiate two expressions.
* `1 ^ qs = 1`
* `x ^ qs = x ^ qs` (for `x` coefficient)
* `(p * ps) ^ qs = p ^ qs + ps ^ qs`
-/
meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info],
pure $ o.set_info o_o pf
| ps@(ex.coeff ps_i x) qs@(ex.coeff qs_i y) := do
pq ← pow_coeff ps.pretty qs.pretty x y,
pq_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``pow_pf_c_c
[ps.orig, ps.pretty, pq.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff ps_i x) qs := do
ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b,
pqs ← ex_exp ps'' qs,
pqs_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c
[ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pqs.info],
pqs' ← exp_to_prod pqs,
pure $ pqs'.set_info pqs_o pf
| pps@(ex.prod pps_i p ps) qs := do
pqs ← pow_e p qs,
psqs ← pow_pp ps qs,
ppsqs ← ex_prod pqs psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_pp_pf_prod
[pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig]
[pps.info, pqs.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' :=
λ ps_pf qs_pf, calc
ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf]
... = ps' : pow_one _
lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 :=
λ ps_pf qs_pf, calc
ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf]
... = 0 : zero_pow (succ_pos qs')
lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} :
qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs :=
λ qs_pf pqqs_pf, calc
ps ^ qs = ps ^ succ qs' : by rw [qs_pf]
... = ps * ps ^ qs' : pow_succ _ _
... = pqqs : by rw [pqqs_pf]
lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} :
pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs :=
λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf]
lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc
/--
Exponentiate two expressions.
* `ps ^ 1 = ps`
* `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`)
* `(p + 0) ^ qs = p ^ qs`
* `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`)
* `ps ^ qs = ps ^ qs` (otherwise)
-/
meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do
ps_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pure $ ps.set_info ps_o pf
| ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do
ctx ← get_context,
z ← ex_zero,
qs_pred ← lift $ expr.of_nat ctx.info_e.α y,
pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info],
z_o ← pow_orig ps qs,
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p (ex.zero _)) qqs := do
pqs ← pow_pp p qqs,
pqs_o ← pow_orig pps qqs,
pf ← mk_proof ``pow_p_pf_singleton
[pps.orig, p.pretty, pqs.pretty, qqs.orig]
[pps.info, pqs.info],
prod_to_sum $ pqs.set_info pqs_o pf
| ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do
qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩,
pqs ← pow_p ps qs',
pqqs ← mul ps pqs,
pqqs_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_succ
[ps.orig, pqqs.pretty, qs.orig, qs'.pretty]
[qs.info, pqqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps qqs := do -- fallback: treat them as atoms
pps' ← ex_sum_b pps,
psqs ← ex_exp pps' qqs,
psqs_o ← pow_orig pps qqs,
pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons
[pps.orig, pps.pretty, qqs.orig, qqs.pretty]
[pps.info, qqs.info],
exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum
lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc
ps ^ qs = ps ^ 0 : by rw [qs_pf]
... = 1 : pow_zero _
lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs →
ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc
ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf]
... = ps ^ q * ps ^ qs : pow_add _ _ _
... = psqqs : psqqs_pf
/--
Exponentiate two expressions.
* `ps ^ 0 = 1`
* `ps ^ (q + qs) = ps ^ q * ps ^ qs`
-/
meta def pow : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info],
prod_to_sum $ o.set_info o_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← pow_p ps q,
psqs ← pow ps qs,
psqqs ← mul psq psqs,
psqqs_o ← pow_orig ps qqs,
pf ← mk_proof ``pow_pf_sum
[ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end exponentiation
lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp
lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp
lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp
lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp
lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp
/--
Give a simpler, more human-readable representation of the normalized expression.
Normalized expressions might have the form `a^1 * 1 + 0`,
since the dummy operations reduce special cases in pattern-matching.
Humans prefer to read `a` instead.
This tactic gets rid of the dummy additions, multiplications and exponentiations.
Returns a normalized expression `e'` and a proof that `e.pretty = e'`.
-/
meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr)
| sum pps@(ex.sum pps_i p (ex.zero _)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf]
| sum (ex.sum pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_add [p_p, ps_p]
<*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf]
| prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := prod.mk pps.pretty <$> lift (mk_eq_refl pps.pretty)
| (some ringi) := do
(p_p, p_pf) ← p.simple,
prod.mk
<$> lift (mk_app ``has_neg.neg [p_p])
<*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf]
end
| prod (ex.prod pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_mul [p_p, ps_p]
<*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| base (ex.sum_b pps_i ps) := ps.simple
| exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf]
| exp (ex.exp pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← in_exponent $ ps.simple,
prod.mk
<$> mk_pow [p_p, ps_p]
<*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| et ps := prod.mk ps.pretty <$> lift (mk_eq_refl ps.pretty)
/--
Performs a lookup of the atom `a` in the list of known atoms,
or allocates a new one.
If `a` is not definitionally equal to any of the list's entries,
a new atom is appended to the list and returned.
The index of this atom is kept track of in the second inductive argument.
This function is mostly useful in `resolve_atom`,
which updates the state with the new list of atoms.
-/
meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom)
| [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm])
| bas@(b :: as) n := do
ctx ← get_context,
(lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do
(atm, as') ← resolve_atom_aux as (succ n),
pure (atm, b :: as')
/--
Convert the expression to an atom:
either look up a definitionally equal atom,
or allocate it as a new atom.
You probably want to use `eval_base` if `eval` doesn't work
instead of directly calling `resolve_atom`,
since `eval_base` can also handle numerals.
-/
meta def resolve_atom (a : expr) : ring_exp_m atom := do
atoms ← reader_t.lift $ state_t.get,
(atm, atoms') ← resolve_atom_aux a atoms 0,
reader_t.lift $ state_t.put atoms',
pure atm
/--
Treat the expression atomically: as a coefficient or atom.
Handles cases where `eval` cannot treat the expression as a known operation
because it is just a number or single variable.
-/
meta def eval_base (ps : expr) : ring_exp_m (ex sum) :=
match ps.to_rat with
| some ⟨0, 1, _, _⟩ := ex_zero
| some x := ex_coeff x >>= prod_to_sum
| none := do
a ← resolve_atom ps,
atom_to_sum a
end
lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp
/--
Negate an expression by multiplying with `-1`.
Only works if there is a `ring` instance; otherwise it will `fail`.
-/
meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := lift $ fail "internal error: negate called in semiring"
| (some ring_instance) := do
minus_one ← ex_coeff (-1) >>= prod_to_sum,
ps' ← mul minus_one ps,
ps_pf ← ps'.proof_term,
pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf],
ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig],
pure $ ps'.set_info ps'_o pf
end
lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} :
ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' :=
by cc
/--
Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom.
Only works if there is a `division_ring` instance; otherwise it will `fail`.
-/
meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only supported in a division ring"
| (some dri) := pure dri
end,
(ps_simple, ps_simple_pf) ← ps.simple,
e ← lift $ mk_app ``has_inv.inv [ps_simple],
(e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)),
e'' ← eval_base e',
ps_pf ← ps.proof_term,
e''_pf ← e''.proof_term,
pf ← mk_app_class ``inverse_pf dri
[ ps.orig, ps.pretty, ps_simple, e', e''.pretty,
ps_pf, ps_simple_pf, e_pf, e''_pf],
e''_o ← lift $ mk_app ``has_inv.inv [ps.orig],
pure $ e''.set_info e''_o pf
lemma sub_pf {α} [ring α] {ps qs psqs : α} (h : ps + -qs = psqs) : ps - qs = psqs :=
by rwa sub_eq_add_neg
lemma div_pf {α} [division_ring α] {ps qs psqs : α} (h : ps * qs⁻¹ = psqs) : ps / qs = psqs :=
by rwa div_eq_mul_inv
end operations
section wiring
/-!
### `wiring` section
This section deals with going from `expr` to `ex` and back.
The main attraction is `eval`, which uses `add`, `mul`, etc.
to calculate an `ex` from a given `expr`.
Other functions use `ex`es to produce `expr`s together with a proof,
or produce the context to run `ring_exp_m` from an `expr`.
-/
open tactic
open ex_type
/--
Compute a normalized form (of type `ex`) from an expression (of type `expr`).
This is the main driver of the `ring_exp` tactic,
calling out to `add`, `mul`, `pow`, etc. to parse the `expr`.
-/
meta def eval : expr → ring_exp_m (ex sum)
| e@`(%%ps + %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
add ps' qs'
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
| e@`(%%ps - %%qs) := (do
ctx ← get_context,
ri ← match ctx.info_b.ring_instance with
| none := lift $ fail "subtraction is not directly supported in a semiring"
| (some ri) := pure ri
end,
ps' ← eval ps,
qs' ← eval qs >>= negate,
psqs ← add ps' qs',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(- %%ps) := do
ps' ← eval ps,
negate ps' <|> eval_base e
| e@`(%%ps * %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
mul ps' qs'
| e@`(has_inv.inv %%ps) := do
ps' ← eval ps,
inverse ps' <|> eval_base e
| e@`(%%ps / %%qs) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only directly supported in a division ring"
| (some dri) := pure dri
end,
ps' ← eval ps,
qs' ← eval qs,
(do qs'' ← inverse qs',
psqs ← mul ps' qs'',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do
ctx ← get_context,
ps' ← eval ps,
qs' ← in_exponent $ eval qs,
psqs ← pow ps' qs',
psqs_pf ← psqs.proof_term,
(do
lift (is_def_eq hp_instance ctx.info_b.hp_instance
<|> fail "has_pow instance must be nat.has_pow or monoid.has_pow"),
has_pow_pf ← lift $ mk_eq_refl e,
pf ← lift $ mk_eq_trans has_pow_pf psqs_pf,
pure $ psqs.set_info e pf) <|> eval_base e
| ps := eval_base ps
/--
Run `eval` on the expression and return the result together with normalization proof.
See also `eval_simple` if you want something that behaves like `norm_num`.
-/
meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do
e' ← eval e,
prod.mk e' <$> e'.proof_term
/--
Run `eval` on the expression and simplify the result.
Returns a simplified normalized expression, together with an equality proof.
See also `eval_with_proof` if you just want to check the equality of two expressions.
-/
meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do
(complicated, complicated_pf) ← eval_with_proof e,
(simple, simple_pf) ← complicated.simple,
prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf)
/-- Compute the `eval_info` for a given type `α`. -/
meta def make_eval_info (α : expr) : tactic eval_info := do
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance,
ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none),
dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none),
ha_instance ← mk_app ``has_add [α] >>= mk_instance,
hm_instance ← mk_app ``has_mul [α] >>= mk_instance,
hp_instance ← mk_mapp ``monoid.has_pow [some α, none],
z ← mk_mapp ``has_zero.zero [α, none],
o ← mk_mapp ``has_one.one [α, none],
pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩
/-- Use `e` to build the context for running `mx`. -/
meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do
info_b ← infer_type e >>= make_eval_info,
info_e ← mk_const ``nat >>= make_eval_info,
(λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) [])
/-- Repeatedly apply `eval_simple` on (sub)expressions. -/
meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do
(_, e', pf') ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
(e'', pf) ← run_ring_exp transp e $ eval_simple e,
guard (¬ e'' =ₐ e),
return ((), e'', some pf, ff))
(λ _ _ _ _ _, failed) `eq e,
pure (e', pf')
end wiring
end tactic.ring_exp
namespace tactic.interactive
open interactive interactive.types lean.parser tactic tactic.ring_exp
local postfix (name := parser.optional) `?`:9001 := optional
/--
Tactic for solving equations of *commutative* (semi)rings,
allowing variables in the exponent.
This version of `ring_exp` fails if the target is not an equality.
The variant `ring_exp_eq!` will use a more aggressive reducibility setting
to determine equality of atoms.
-/
meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do
`(eq %%ps %%qs) ← target >>= whnf,
let transp := if red.is_some then semireducible else reducible,
((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $
prod.mk <$> eval_with_proof ps <*> eval_with_proof qs,
if ps'.eq qs'
then do
qs_pf_inv ← mk_eq_symm qs_pf,
pf ← mk_eq_trans ps_pf qs_pf_inv,
tactic.interactive.exact ``(%%pf)
else fail "ring_exp failed to prove equality"
/--
Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the
exponent.
This tactic extends `ring`: it should solve every goal that `ring` can solve.
Additionally, it knows how to evaluate expressions with complicated exponents
(where `ring` only understands constant exponents).
The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine
equality of atoms.
For example:
```lean
example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp
example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp
example (x y : ℕ) : x + id y = y + id x := by ring_exp!
```
-/
meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := ring_exp_eq red
| _ := failed
end <|>
do ns ← loc.get_locals,
let transp := if red.is_some then semireducible else reducible,
tt ← tactic.replace_at (normalize transp) ns loc.include_goal
| fail "ring_exp failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_tactic_doc
{ name := "ring_exp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ring_exp],
tags := ["arithmetic", "simplification", "decision procedure"] }
end tactic.interactive
namespace conv.interactive
open conv interactive
open tactic tactic.interactive (ring_exp_eq)
open tactic.ring_exp (normalize)
local postfix (name := parser.optional) `?`:9001 := optional
/--
Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic
`ring_exp`.
-/
meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit :=
let transp := if red.is_some then semireducible else reducible in
discharge_eq_lhs (ring_exp_eq red)
<|> replace_lhs (normalize transp)
<|> fail "ring_exp failed to simplify"
end conv.interactive
|
041ced78adc18c67dcba46a38ea3503e860dc994 | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/data/fin.lean | 68a031035cf40e01cabac666a6d6b8979859e07c | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 50,559 | lean | /-
Copyright (c) 2017 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Keeley Hoek
-/
import data.nat.cast
import tactic.localized
import order.rel_iso
/-!
# The finite type with `n` elements
`fin n` is the type whose elements are natural numbers smaller than `n`.
This file expands on the development in the core library.
## Main definitions
### Induction principles
* `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`.
* `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted
as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines
`0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element
of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple.
* `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument;
* `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the
`nat`-like base cases of `C 0` and `C (i.succ)`.
* `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument.
### Casts
* `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into;
* `cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`;
* `cast eq` : embed `fin n` into `fin m`, `eq : n = m`;
* `cast_add m` : embed `fin n` into `fin (n+m)`;
* `cast_succ` : embed `fin n` into `fin (n+1)`;
* `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`;
* `pred_above p i h` : embed `i : fin (n+1)` into `fin n` by ignoring `p`;
* `sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`;
* `add_nat i h` : add `m` on `i` on the right, generalizes `fin.succ`;
* `nat_add i h` adds `n` on `i` on the left;
* `clamp n m` : `min n m` as an element of `fin (m + 1)`;
### Operation on tuples
We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`.
If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal)
to `vector`s.
We define the following operations:
* `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries;
* `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple;
* `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries;
* `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc`
comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order.
* `insert_nth` : insert an element to a tuple at a given position.
* `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied.
### Misc definitions
* `fin.last n` : The greatest value of `fin (n+1)`.
-/
universes u v
open fin nat function
/-- Elimination principle for the empty set `fin 0`, dependent version. -/
def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0
lemma fact.succ.pos {n} : fact (0 < succ n) := zero_lt_succ _
lemma fact.bit0.pos {n} [h : fact (0 < n)] : fact (0 < bit0 n) :=
nat.zero_lt_bit0 $ ne_of_gt h
lemma fact.bit1.pos {n} : fact (0 < bit1 n) :=
nat.zero_lt_bit1 _
lemma fact.pow.pos {p n : ℕ} [h : fact $ 0 < p] : fact (0 < p ^ n) :=
pow_pos h _
localized "attribute [instance] fact.succ.pos" in fin_fact
localized "attribute [instance] fact.bit0.pos" in fin_fact
localized "attribute [instance] fact.bit1.pos" in fin_fact
localized "attribute [instance] fact.pow.pos" in fin_fact
namespace fin
variables {n m : ℕ} {a b : fin n}
instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨subtype.val⟩
lemma is_lt (i : fin n) : (i : ℕ) < n := i.2
/-- convert a `ℕ` to `fin n`, provided `n` is positive -/
def of_nat' [h : fact (0 < n)] (i : ℕ) : fin n := ⟨i%n, mod_lt _ h⟩
@[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a :=
by cases a; refl
@[ext]
lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h
lemma ext_iff (a b : fin n) : a = b ↔ (a : ℕ) = b :=
iff.intro (congr_arg _) fin.eq_of_veq
lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := subtype.coe_injective
lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 :=
⟨veq_of_eq, eq_of_veq⟩
lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 :=
⟨vne_of_ne, ne_of_vne⟩
@[simp] lemma mk_eq_subtype_mk (a : ℕ) (h : a < n) : mk a h = ⟨a, h⟩ := rfl
protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} :
(⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b :=
⟨subtype.mk.inj, λ h, by subst h⟩
lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl
lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k :=
fin.eq_iff_veq a ⟨k, hk⟩
@[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl
lemma mk_coe (i : fin n) : (⟨i, i.is_lt⟩ : fin n) = i :=
fin.eta _ _
lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl
@[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl
attribute [simp] val_zero
@[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl
@[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl
@[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl
@[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl
@[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl
/-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/
@[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b :=
iff.rfl
/-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/
@[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b :=
iff.rfl
lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n
| ⟨_, _⟩ ⟨_, _⟩ := rfl
lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl
lemma coe_one' {n : ℕ} : ((1 : fin (n+1)) : ℕ) = 1 % (n+1) := rfl
@[simp] lemma val_zero' (n) : (0 : fin (n+1)).val = 0 := rfl
@[simp] lemma mk_zero : (⟨0, nat.succ_pos'⟩ : fin (n + 1)) = (0 : fin _) := rfl
@[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl
section bit
@[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) :
(⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) :=
eq_of_veq (nat.mod_eq_of_lt h).symm
@[simp] lemma mk_bit1 {m n : ℕ} (h : bit1 m < n + 1) :
(⟨bit1 m, h⟩ : fin (n + 1)) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt
((m + m).lt_succ_self.trans h)⟩ : fin _) :=
begin
ext,
simp only [bit1, bit0] at h,
simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h],
end
end bit
@[simp]
lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a :=
begin
induction a with a ih, { refl },
ext, show (a+1) % (n+1) = subtype.val (a+1 : fin (n+1)),
{ rw [val_add, ← ih, of_nat],
exact add_mod _ _ _ }
end
/-- Converting an in-range number to `fin (n + 1)` produces a result
whose value is the original number. -/
lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) :
((a : fin (n + 1)).val) = a :=
begin
rw ←of_nat_eq_coe,
exact nat.mod_eq_of_lt h
end
/-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results
in the same value. -/
lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a :=
begin
rw fin.eq_iff_veq,
exact coe_val_of_lt a.property
end
/-- Coercing an in-range number to `fin (n + 1)`, and converting back
to `ℕ`, results in that number. -/
lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) :
((a : fin (n + 1)) : ℕ) = a :=
coe_val_of_lt h
/-- Converting a `fin (n + 1)` to `ℕ` and back results in the same
value. -/
@[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a :=
coe_val_eq_self a
/-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element,
then they coincide (in the heq sense). -/
protected lemma heq_fun_iff {α : Type*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} :
f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) :=
by { induction h, simp [heq_iff_eq, function.funext_iff] }
protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} :
i == j ↔ (i : ℕ) = (j : ℕ) :=
by { induction h, simp [ext_iff] }
instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩
instance {n : ℕ} : linear_order (fin n) :=
{ le := (≤), lt := (<),
decidable_le := fin.decidable_le,
decidable_lt := fin.decidable_lt,
decidable_eq := fin.decidable_eq _,
..linear_order.lift (coe : fin n → ℕ) (@fin.eq_of_veq _) }
lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ :=
⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩),
λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩
lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ :=
⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩
lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl
lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl
lemma mk_lt_of_lt_coe {a : ℕ} (h : a < b) : (⟨a, h.trans b.is_lt⟩ : fin n) < b := h
lemma mk_le_of_le_coe {a : ℕ} (h : a ≤ b) : (⟨a, h.trans_lt b.is_lt⟩ : fin n) ≤ b := h
lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1
@[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 :=
by cases j; simp [fin.succ]
lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe]
/-- The greatest value of `fin (n+1)` -/
def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩
@[simp, norm_cast] lemma coe_last (n : ℕ) : (last n : ℕ) = n := rfl
lemma last_val (n : ℕ) : (last n).val = n := rfl
theorem le_last (i : fin (n+1)) : i ≤ last n :=
le_of_lt_succ i.is_lt
instance : bounded_lattice (fin (n + 1)) :=
{ top := last n,
le_top := le_last,
bot := 0,
bot_le := zero_le,
.. fin.linear_order, .. lattice_of_linear_order }
/-- `fin.succ` as an `order_embedding` -/
def succ_embedding (n : ℕ) : fin n ↪o fin (n + 1) :=
order_embedding.of_strict_mono fin.succ $ λ ⟨i, hi⟩ ⟨j, hj⟩ h, succ_lt_succ h
@[simp] lemma coe_succ_embedding : ⇑(succ_embedding n) = fin.succ := rfl
@[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b :=
(succ_embedding n).le_iff_le
@[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b :=
(succ_embedding n).lt_iff_lt
lemma succ_injective (n : ℕ) : injective (@fin.succ n) :=
(succ_embedding n).injective
@[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b :=
(succ_injective n).eq_iff
lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0
| ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (ext_iff _ _).1 heq
@[simp] lemma succ_zero_eq_one : fin.succ (0 : fin (n + 1)) = 1 := rfl
lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ :=
by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i }
lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ :=
begin
cases n,
{ exact fin_zero_elim a },
{ rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a }
end
lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a)
@[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 :=
by { cases j, refl }
@[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i
| ⟨0, h⟩ hi := by contradiction
| ⟨n + 1, h⟩ hi := rfl
@[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i :=
by { cases i, refl }
@[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) :
fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ :=
by simp only [ext_iff, coe_pred, coe_mk, nat.add_sub_cancel]
@[simp] lemma pred_le_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} :
a.pred ha ≤ b.pred hb ↔ a ≤ b :=
by rw [←succ_le_succ_iff, succ_pred, succ_pred]
@[simp] lemma pred_lt_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} :
a.pred ha < b.pred hb ↔ a < b :=
by rw [←succ_lt_succ_iff, succ_pred, succ_pred]
@[simp] lemma pred_inj :
∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b
| ⟨0, _⟩ b ha hb := by contradiction
| ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction
| ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq]
/-- The inclusion map `fin n → ℕ` is a relation embedding. -/
def coe_embedding (n) : (fin n) ↪o ℕ :=
⟨⟨coe, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩
/-- The ordering on `fin n` is a well order. -/
instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) :=
(coe_embedding n).is_well_order
/-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/
def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩
@[simp] lemma coe_cast_lt (i : fin m) (h : i.1 < n) : (cast_lt i h : ℕ) = i := rfl
/-- `cast_le h i` embeds `i` into a larger `fin` type. -/
def cast_le (h : n ≤ m) : fin n ↪o fin m :=
order_embedding.of_strict_mono (λ a, cast_lt a (lt_of_lt_of_le a.2 h)) $ λ a b h, h
@[simp] lemma coe_cast_le (h : n ≤ m) (i : fin n) : (cast_le h i : ℕ) = i := rfl
/-- `cast eq i` embeds `i` into a equal `fin` type. -/
def cast (eq : n = m) : fin n ≃o fin m :=
{ to_equiv := ⟨cast_le eq.le, cast_le eq.symm.le, λ a, eq_of_veq rfl, λ a, eq_of_veq rfl⟩,
map_rel_iff' := λ a b, iff.rfl }
@[simp] lemma symm_cast (h : n = m) : (cast h).symm = cast h.symm := rfl
lemma coe_cast (h : n = m) (i : fin n) : (cast h i : ℕ) = i := rfl
@[simp] lemma cast_trans {k : ℕ} (h : n = m) (h' : m = k) {i : fin n} :
cast h' (cast h i) = cast (eq.trans h h') i := rfl
@[simp] lemma cast_refl {i : fin n} : cast rfl i = i :=
by { ext, refl }
/-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/
def cast_add (m) : fin n ↪o fin (n + m) := cast_le $ le_add_right n m
@[simp] lemma coe_cast_add (m : ℕ) (i : fin n) : (cast_add m i : ℕ) = i := rfl
/-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/
def cast_succ : fin n ↪o fin (n + 1) := cast_add 1
@[simp] lemma coe_cast_succ (i : fin n) : (i.cast_succ : ℕ) = i := rfl
lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ :=
lt_iff_coe_lt_coe.2 $ by simp only [coe_cast_succ, coe_succ, nat.lt_succ_self]
lemma succ_above_aux (p : fin (n + 1)) :
strict_mono (λ i : fin n, if i.cast_succ < p then i.cast_succ else i.succ) :=
(cast_succ : fin n ↪o _).strict_mono.ite (succ_embedding n).strict_mono
(λ i j hij hj, lt_trans ((cast_succ : fin n ↪o _).lt_iff_lt.2 hij) hj)
(λ i, (cast_succ_lt_succ i).le)
/-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/
def succ_above (p : fin (n + 1)) : fin n ↪o fin (n + 1) :=
order_embedding.of_strict_mono _ p.succ_above_aux
/-- `pred_above p i h` embeds `i : fin (n+1)` into `fin n` by ignoring `p`. -/
def pred_above (p : fin (n+1)) (i : fin (n+1)) (hi : i ≠ p) : fin n :=
if h : i < p
then i.cast_lt (lt_of_lt_of_le h $ nat.le_of_lt_succ p.2)
else i.pred $
have p < i, from lt_of_le_of_ne (le_of_not_gt h) hi.symm,
ne_of_gt (lt_of_le_of_lt (zero_le p) this)
/-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/
def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n :=
⟨(i : ℕ) - m, by { rw [nat.sub_lt_right_iff_lt_add h], exact i.is_lt }⟩
@[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m :=
rfl
/-- `add_nat i h` adds `m` to `i`, generalizes `fin.succ`. -/
def add_nat (m) : fin n ↪o fin (n + m) :=
order_embedding.of_strict_mono (λ i, ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩) $
λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_right h _
@[simp] lemma coe_add_nat (m : ℕ) (i : fin n) : (add_nat m i : ℕ) = i + m := rfl
/-- `nat_add i h` adds `n` to `i` "on the left". -/
def nat_add (n) {m} : fin m ↪o fin (n + m) :=
order_embedding.of_strict_mono (λ i, ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩) $
λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_left h _
@[simp] lemma coe_nat_add (n : ℕ) {m : ℕ} (i : fin m) : (nat_add n i : ℕ) = n + i := rfl
/-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity
map. In this lemma we state that for each `i : fin n` we have `(e i : ℕ) = (i : ℕ)`. -/
@[simp] lemma coe_order_iso_apply (e : fin n ≃o fin m) (i : fin n) : (e i : ℕ) = i :=
begin
rcases i with ⟨i, hi⟩,
rw [subtype.coe_mk],
induction i using nat.strong_induction_on with i h,
refine le_antisymm (forall_lt_iff_le.1 $ λ j hj, _) (forall_lt_iff_le.1 $ λ j hj, _),
{ have := e.symm.lt_iff_lt.2 (mk_lt_of_lt_coe hj),
rw e.symm_apply_apply at this,
convert this,
simpa using h _ this (e.symm _).is_lt },
{ rwa [← h j hj (hj.trans hi), ← lt_iff_coe_lt_coe, e.lt_iff_lt] }
end
section
variables {α : Type*} [preorder α]
open set
instance order_iso_subsingleton : subsingleton (fin n ≃o α) :=
⟨λ e e', by { ext i,
rw [← e.symm.apply_eq_iff_eq, e.symm_apply_apply, ← e'.trans_apply, ext_iff,
coe_order_iso_apply] }⟩
instance order_iso_subsingleton' : subsingleton (α ≃o fin n) :=
order_iso.symm_injective.subsingleton
instance order_iso_unique : unique (fin n ≃o fin n) := unique.mk' _
/-- Two strictly monotone functions from `fin n` are equal provided that their ranges
are equal. -/
lemma strict_mono_unique {f g : fin n → α} (hf : strict_mono f) (hg : strict_mono g)
(h : range f = range g) : f = g :=
have (hf.order_iso f).trans (order_iso.set_congr _ _ h) = hg.order_iso g,
from subsingleton.elim _ _,
congr_arg (function.comp (coe : range g → α)) (funext $ rel_iso.ext_iff.1 this)
/-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/
lemma order_embedding_eq {f g : fin n ↪o α} (h : range f = range g) : f = g :=
rel_embedding.ext $ funext_iff.1 $ strict_mono_unique f.strict_mono g.strict_mono h
end
@[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl
@[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i :=
fin.eq_of_veq rfl
@[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) :
cast_lt (cast_succ a) h = a :=
by cases a; refl
lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) :=
(cast_succ : fin n ↪o _).injective
lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b :=
(cast_succ_injective n).eq_iff
lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt
@[simp] lemma cast_succ_zero : cast_succ (0 : fin (n + 1)) = 0 := rfl
/-- `cast_succ i` is positive when `i` is positive -/
lemma cast_succ_pos (i : fin (n + 1)) (h : 0 < i) : 0 < cast_succ i :=
by simpa [lt_iff_coe_lt_coe] using h
lemma last_pos : (0 : fin (n + 2)) < last (n + 1) :=
by simp [lt_iff_coe_lt_coe]
lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n :=
by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] }
lemma le_coe_last (i : fin (n + 1)) : i ≤ n :=
by { rw fin.coe_nat_eq_last, exact fin.le_last i }
lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n :=
le_antisymm (le_last i) (not_lt.1 h)
lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 :=
begin
cases n,
{ exact absurd h (nat.not_lt_zero _) },
{ rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h,
rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h],
exact nat.zero_lt_succ _ }
end
lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0
lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos
@[simp] lemma zero_eq_one_iff : (0 : fin (n + 1)) = 1 ↔ n = 0 :=
begin
split,
{ cases n; intro h,
{ refl },
{ have := zero_ne_one, contradiction } },
{ rintro rfl, refl }
end
@[simp] lemma one_eq_zero_iff : (1 : fin (n + 1)) = 0 ↔ n = 0 :=
by rw [eq_comm, zero_eq_one_iff]
lemma cast_succ_fin_succ (n : ℕ) (j : fin n) :
cast_succ (fin.succ j) = fin.succ (cast_succ j) :=
by { simp [fin.ext_iff], }
@[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ :=
begin
ext,
exact coe_val_of_lt (nat.lt.step a.is_lt),
end
@[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ :=
begin
cases n,
{ exact fin_zero_elim a },
{ simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] }
end
lemma lt_succ : a.cast_succ < a.succ :=
by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val }
@[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl
lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) :
pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h :=
begin
rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, nat.add_sub_cancel],
exact add_lt_add_right h 1,
end
lemma nat_add_zero {n : ℕ} : fin.nat_add 0 = (fin.cast (zero_add n).symm).to_rel_embedding :=
by { ext, apply zero_add }
/-- `min n m` as an element of `fin (m + 1)`. -/
def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m
@[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m :=
nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/
lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) :
p.succ_above i = i.cast_succ :=
by { rw [succ_above], exact if_pos h }
/-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/
@[simp] lemma succ_above_zero : ⇑(succ_above (0 : fin (n + 1))) = fin.succ := rfl
/-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/
@[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ :=
by { ext, simp only [succ_above_below, cast_succ_lt_last] }
lemma succ_above_last_apply (i : fin n) : succ_above (fin.last n) i = i.cast_succ :=
by rw succ_above_last
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
embeds `i` by `succ` when the resulting `p < i.succ`. -/
lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) :
p.succ_above i = i.succ :=
by simp [succ_above, h.not_lt]
/-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/
lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ :=
lt_or_ge (cast_succ i) p
/-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/
lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ :=
or.cases_on (succ_above_lt_ge p i)
(λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i)))
/-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater
results in a value that is less than `p`. -/
@[simp] lemma succ_above_lt_iff (p : fin (n + 1)) (i : fin n) :
p.succ_above i < p ↔ i.cast_succ < p :=
begin
refine iff.intro _ _,
{ intro h,
cases succ_above_lt_ge p i with H H,
{ exact H },
{ rw succ_above_above _ _ H at h,
exact lt_trans (cast_succ_lt_succ i) h } },
{ intro h,
rw succ_above_below _ _ h,
exact h }
end
/-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser
results in a value that is greater than `p`. -/
lemma lt_succ_above_iff (p : fin (n + 1)) (i : fin n) : p < p.succ_above i ↔ p ≤ i.cast_succ :=
begin
refine iff.intro _ _,
{ intro h,
cases succ_above_lt_ge p i with H H,
{ rw succ_above_below _ _ H at h,
exact le_of_lt h },
{ exact H } },
{ intro h,
rw succ_above_above _ _ h,
exact lt_of_le_of_lt h (cast_succ_lt_succ i) },
end
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
never results in `p` itself -/
theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p :=
begin
intro eq,
by_cases H : i.cast_succ < p,
{ simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H },
{ simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i }
end
/-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/
lemma succ_above_pos (p : fin (n + 2)) (i : fin (n + 1)) (h : 0 < i) : 0 < p.succ_above i :=
begin
by_cases H : i.cast_succ < p,
{ simpa [succ_above_below _ _ H] using cast_succ_pos _ h },
{ simpa [succ_above_above _ _ (le_of_not_lt H)] using succ_pos _ },
end
/-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/
lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) :=
(succ_above x).injective
/-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/
lemma succ_above_right_inj {x : fin (n + 1)} :
x.succ_above a = x.succ_above b ↔ a = b :=
succ_above_right_injective.eq_iff
/-- Embedding a `fin (n + 1)` into `fin n` and embedding it back around the same hole
gives the starting `fin (n + 1)` -/
@[simp] lemma succ_above_pred_above (p i : fin (n + 1)) (h : i ≠ p) :
p.succ_above (p.pred_above i h) = i :=
begin
rw pred_above,
cases lt_or_le i p with H H,
{ simp only [succ_above_below, cast_succ_cast_lt, H, dif_pos]},
{ rw le_iff_coe_le_coe at H,
rw succ_above_above,
{ simp only [le_iff_coe_le_coe, H, not_lt, dif_neg, succ_pred] },
{ simp only [le_iff_coe_le_coe, H, coe_pred, not_lt, dif_neg, coe_cast_succ],
exact le_pred_of_lt (lt_of_le_of_ne H (vne_of_ne h.symm)) } }
end
/-- Embedding a `fin n` into `fin (n + 1)` and embedding it back around the same hole
gives the starting `fin n` -/
@[simp] lemma pred_above_succ_above (p : fin (n + 1)) (i : fin n) :
p.pred_above (p.succ_above i) (succ_above_ne _ _) = i :=
by rw [← succ_above_right_inj, succ_above_pred_above]
@[simp] theorem pred_above_zero {i : fin (n + 1)} (hi : i ≠ 0) :
pred_above 0 i hi = i.pred hi :=
rfl
lemma forall_iff_succ_above {p : fin (n + 1) → Prop} (i : fin (n + 1)) :
(∀ j, p j) ↔ p i ∧ ∀ j, p (i.succ_above j) :=
⟨λ h, ⟨h _, λ j, h _⟩,
λ h j, if hj : j = i then (hj.symm ▸ h.1) else (i.succ_above_pred_above j hj ▸ h.2 _)⟩
/-- `succ_above` is injective at the pivot -/
lemma succ_above_left_injective : injective (@succ_above n) :=
λ x y, begin
contrapose!,
intros H h,
have key : succ_above x (y.pred_above x H) = succ_above y (y.pred_above x H), by rw h,
rw [succ_above_pred_above] at key,
exact absurd key (succ_above_ne x _)
end
/-- `succ_above` is injective at the pivot -/
lemma succ_above_left_inj {x y : fin (n + 1)} :
x.succ_above = y.succ_above ↔ x = y :=
succ_above_left_injective.eq_iff
/-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/
lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} :
strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ :=
begin
split,
{ assume H i hi,
apply H,
exact nat.lt_succ_self _ },
{ assume H,
have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩,
{ assume i j h h',
induction h with k h IH,
{ exact H _ _ },
{ exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } },
assume i j hij,
convert A (i : ℕ) (j : ℕ) hij j.2; ext; simp only [subtype.coe_eta] }
end
section rec
/-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`.
This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple,
and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element
of `n`-tuple. -/
@[elab_as_eliminator] def succ_rec
{C : Π n, fin n → Sort*}
(H0 : Π n, C (succ n) 0)
(Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i
| 0 i := i.elim0
| (succ n) ⟨0, _⟩ := H0 _
| (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩)
/-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`.
This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple,
and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element
of `n`-tuple.
A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/
@[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n)
{C : Π n, fin n → Sort*}
(H0 : Π n, C (succ n) 0)
(Hs : Π n i, C n i → C (succ n) i.succ) : C n i :=
i.succ_rec H0 Hs
@[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) :
@fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n :=
rfl
@[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) :
@fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) :=
by cases i; refl
/--
Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `h0` handles the base case on `C 0`,
and `hs` defines the inductive step using `C i.cast_succ`.
-/
@[elab_as_eliminator] def induction
{C : fin (n + 1) → Sort*}
(h0 : C 0)
(hs : ∀ i : fin n, C i.cast_succ → C i.succ) :
Π (i : fin (n + 1)), C i :=
begin
rintro ⟨i, hi⟩,
induction i with i IH,
{ rwa [fin.mk_zero] },
{ refine hs ⟨i, lt_of_succ_lt_succ hi⟩ _,
exact IH (lt_of_succ_lt hi) }
end
/--
Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `h0` handles the base case on `C 0`,
and `hs` defines the inductive step using `C i.cast_succ`.
A version of `fin.induction` taking `i : fin (n + 1)` as the first argument.
-/
@[elab_as_eliminator] def induction_on (i : fin (n + 1))
{C : fin (n + 1) → Sort*}
(h0 : C 0)
(hs : ∀ i : fin n, C i.cast_succ → C i.succ) : C i :=
induction h0 hs i
/-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and
`i = j.succ`, `j : fin n`. -/
@[elab_as_eliminator] def cases
{C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) :
Π (i : fin (succ n)), C i :=
induction H0 (λ i _, Hs i)
@[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 :=
rfl
@[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) :
@fin.cases n C H0 Hs i.succ = Hs i :=
by cases i; refl
@[simp] theorem cases_succ' {n} {C : fin (succ n) → Sort*} {H0 Hs} {i : ℕ} (h : i + 1 < n + 1) :
@fin.cases n C H0 Hs ⟨i.succ, h⟩ = Hs ⟨i, lt_of_succ_lt_succ h⟩ :=
by cases i; refl
lemma forall_fin_succ {P : fin (n+1) → Prop} :
(∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) :=
⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩
lemma exists_fin_succ {P : fin (n+1) → Prop} :
(∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) :=
⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h,
λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩
end rec
section tuple
/-!
### Tuples
We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type
`α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant
operations, first about adding or removing elements at the beginning of a tuple.
-/
/-- There is exactly one tuple of size zero. -/
instance tuple0_unique (α : fin 0 → Type u) : unique (Π i : fin 0, α i) :=
{ default := fin_zero_elim, uniq := λ x, funext fin_zero_elim }
@[simp] lemma tuple0_le {α : Π i : fin 0, Type*} [Π i, preorder (α i)] (f g : Π i, α i) : f ≤ g :=
fin_zero_elim
variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ))
(i : fin n) (y : α i.succ) (z : α 0)
/-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/
def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ
/-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/
def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i :=
λ j, fin.cases x p j
@[simp] lemma tail_cons : tail (cons x p) = p :=
by simp [tail, cons]
@[simp] lemma cons_succ : cons x p i.succ = p i :=
by simp [cons]
@[simp] lemma cons_zero : cons x p 0 = x :=
by simp [cons]
/-- Updating a tuple and adding an element at the beginning commute. -/
@[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp [ne.symm (succ_ne_zero i)] },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ],
by_cases h' : j' = i,
{ rw h', simp },
{ have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj],
rw [update_noteq h', update_noteq this, cons_succ] } }
end
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
lemma update_cons_zero : update (cons x p) 0 z = cons z p :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp },
{ simp only [h, update_noteq, ne.def, not_false_iff],
let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ, cons_succ] }
end
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp] lemma cons_self_tail : cons (q 0) (tail q) = q :=
begin
ext j,
by_cases h : j = 0,
{ rw h, simp },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, tail, cons_succ] }
end
/-- Updating the first element of a tuple does not change the tail. -/
@[simp] lemma tail_update_zero : tail (update q 0 z) = tail q :=
by { ext j, simp [tail, fin.succ_ne_zero] }
/-- Updating a nonzero element and taking the tail commute. -/
@[simp] lemma tail_update_succ :
tail (update q i.succ y) = update (tail q) i y :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp [tail] },
{ simp [tail, (fin.succ_injective n).ne h, h] }
end
lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) :
g ∘ (cons y q) = cons (g y) (g ∘ q) :=
begin
ext j,
by_cases h : j = 0,
{ rw h, refl },
{ let j' := pred j h,
have : j'.succ = j := succ_pred j h,
rw [← this, cons_succ, comp_app, cons_succ] }
end
lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) :
g ∘ (tail q) = tail (g ∘ q) :=
by { ext j, simp [tail] }
lemma le_cons [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} :
q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p :=
forall_fin_succ.trans $ and_congr iff.rfl $ forall_congr $ λ j, by simp [tail]
lemma cons_le [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} :
cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q :=
@le_cons _ (λ i, order_dual (α i)) _ x q p
/-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce
one of length `o = m + n`. `ho` provides control of definitional equality
for the vector length. -/
def append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α :=
λ i, if h : (i : ℕ) < m
then u ⟨i, h⟩
else v ⟨(i : ℕ) - m, (nat.sub_lt_left_iff_lt_add (le_of_not_lt h)).2 (ho ▸ i.property)⟩
end tuple
section tuple_right
/-! In the previous section, we have discussed inserting or removing elements on the left of a
tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed
inductively from `fin n` starting from the left, not from the right. This implies that Lean needs
more help to realize that elements belong to the right types, i.e., we need to insert casts at
several places. -/
variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ)
(i : fin n) (y : α i.cast_succ) (z : α (last n))
/-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/
def init (q : Πi, α i) (i : fin n) : α i.cast_succ :=
q i.cast_succ
/-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from
`cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/
def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i :=
if h : i.val < n
then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h))
else _root_.cast (by rw eq_last_of_not_lt h) x
@[simp] lemma init_snoc : init (snoc p x) = p :=
begin
ext i,
have h' := fin.cast_lt_cast_succ i i.is_lt,
simp [init, snoc, i.is_lt, h'],
convert cast_eq rfl (p i)
end
@[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i :=
begin
have : i.cast_succ.val < n := i.is_lt,
have h' := fin.cast_lt_cast_succ i i.is_lt,
simp [snoc, this, h'],
convert cast_eq rfl (p i)
end
@[simp] lemma snoc_last : snoc p x (last n) = x :=
by { simp [snoc] }
/-- Updating a tuple and adding an element at the end commute. -/
@[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y :=
begin
ext j,
by_cases h : j.val < n,
{ simp only [snoc, h, dif_pos],
by_cases h' : j = cast_succ i,
{ have C1 : α i.cast_succ = α j, by rw h',
have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y,
{ have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp,
convert this,
{ exact h'.symm },
{ exact heq_of_eq_mp (congr_arg α (eq.symm h')) rfl } },
have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)),
by rw [cast_succ_cast_lt, h'],
have E2 : update p i y (cast_lt j h) = _root_.cast C2 y,
{ have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y,
by simp,
convert this,
{ simp [h, h'] },
{ exact heq_of_eq_mp C2 rfl } },
rw [E1, E2],
exact eq_rec_compose _ _ _ },
{ have : ¬(cast_lt j h = i),
by { assume E, apply h', rw [← E, cast_succ_cast_lt] },
simp [h', this, snoc, h] } },
{ rw eq_last_of_not_lt h,
simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] }
end
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, update_noteq, this, snoc] },
{ rw eq_last_of_not_lt h,
simp }
end
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt],
have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _,
rw ← cast_eq rfl (q j),
congr' 1; rw A },
{ rw eq_last_of_not_lt h,
simp }
end
/-- Updating the last element of a tuple does not change the beginning. -/
@[simp] lemma init_update_last : init (update q (last n) z) = init q :=
by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] }
/-- Updating an element and taking the beginning commute. -/
@[simp] lemma init_update_cast_succ :
init (update q i.cast_succ y) = update (init q) i y :=
begin
ext j,
by_cases h : j = i,
{ rw h, simp [init] },
{ simp [init, h] }
end
/-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) :
tail (init q) = init (tail q) :=
by { ext i, simp [tail, init, cast_succ_fin_succ] }
/-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) :
@cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b :=
begin
ext i,
by_cases h : i = 0,
{ rw h, refl },
set j := pred i h with ji,
have : i = j.succ, by rw [ji, succ_pred],
rw [this, cons_succ],
by_cases h' : j.val < n,
{ set k := cast_lt j h' with jk,
have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt],
rw [this, ← cast_succ_fin_succ],
simp },
rw [eq_last_of_not_lt h', succ_last],
simp
end
lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) :
g ∘ (snoc q y) = snoc (g ∘ q) (g y) :=
begin
ext j,
by_cases h : j.val < n,
{ have : j ≠ last n := ne_of_lt h,
simp [h, this, snoc, cast_succ_cast_lt] },
{ rw eq_last_of_not_lt h,
simp }
end
lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) :
g ∘ (init q) = init (g ∘ q) :=
by { ext j, simp [init] }
end tuple_right
section insert_nth
variables {α : fin (n+1) → Type u} {β : Type v}
/-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`,
for `i = fin.last n` see `fin.snoc`. -/
def insert_nth (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j))
(j : fin (n + 1)) : α j :=
if h : j = i
then _root_.cast (congr_arg α h.symm) x
else _root_.cast (congr_arg α $ succ_above_pred_above i _ h) (p $ i.pred_above j h)
@[simp] lemma insert_nth_apply_same (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) :
insert_nth i x p i = x :=
by simp [insert_nth]
@[simp] lemma insert_nth_apply_succ_above (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j))
(j : fin n) :
insert_nth i x p (i.succ_above j) = p j :=
begin
simp only [insert_nth, dif_neg (succ_above_ne _ _)],
refine eq_of_heq ((cast_heq _ _).trans _),
rw [pred_above_succ_above]
end
@[simp] lemma insert_nth_comp_succ_above (i : fin (n + 1)) (x : β) (p : fin n → β) :
insert_nth i x p ∘ i.succ_above = p :=
funext $ insert_nth_apply_succ_above i x p
lemma insert_nth_eq_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
i.insert_nth x p = q ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) :=
by simp [funext_iff, forall_iff_succ_above i, eq_comm]
lemma eq_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
q = i.insert_nth x p ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) :=
eq_comm.trans insert_nth_eq_iff
lemma insert_nth_zero (x : α 0) (p : Π j : fin n, α (succ_above 0 j)) :
insert_nth 0 x p = cons x (λ j, _root_.cast (congr_arg α (congr_fun succ_above_zero j)) (p j)) :=
begin
refine insert_nth_eq_iff.2 ⟨by simp, _⟩,
ext j,
convert (cons_succ _ _ _).symm
end
@[simp] lemma insert_nth_zero' (x : β) (p : fin n → β) :
@insert_nth _ (λ _, β) 0 x p = cons x p :=
by simp [insert_nth_zero]
lemma insert_nth_last (x : α (last n)) (p : Π j : fin n, α ((last n).succ_above j)) :
insert_nth (last n) x p =
snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x :=
begin
refine insert_nth_eq_iff.2 ⟨by simp, _⟩,
ext j,
apply eq_of_heq,
transitivity snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x j.cast_succ,
{ rw [snoc_cast_succ], exact (cast_heq _ _).symm },
{ apply congr_arg_heq,
rw [succ_above_last] }
end
@[simp] lemma insert_nth_last' (x : β) (p : fin n → β) :
@insert_nth _ (λ _, β) (last n) x p = snoc p x :=
by simp [insert_nth_last]
variables [Π i, preorder (α i)]
lemma insert_nth_le_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
i.insert_nth x p ≤ q ↔ x ≤ q i ∧ p ≤ (λ j, q (i.succ_above j)) :=
by simp [pi.le_def, forall_iff_succ_above i]
lemma le_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} :
q ≤ i.insert_nth x p ↔ q i ≤ x ∧ (λ j, q (i.succ_above j)) ≤ p :=
by simp [pi.le_def, forall_iff_succ_above i]
open set
lemma insert_nth_mem_Icc {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)}
{q₁ q₂ : Π j, α j} :
i.insert_nth x p ∈ Icc q₁ q₂ ↔
x ∈ Icc (q₁ i) (q₂ i) ∧ p ∈ Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) :=
by simp only [mem_Icc, insert_nth_le_iff, le_insert_nth_iff, and.assoc, and.left_comm]
lemma preimage_insert_nth_Icc_of_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j}
(hx : x ∈ Icc (q₁ i) (q₂ i)) :
i.insert_nth x ⁻¹' (Icc q₁ q₂) = Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) :=
set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, true_and]
lemma preimage_insert_nth_Icc_of_not_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j}
(hx : x ∉ Icc (q₁ i) (q₂ i)) :
i.insert_nth x ⁻¹' (Icc q₁ q₂) = ∅ :=
set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, false_and, mem_empty_eq]
end insert_nth
section find
/-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied. -/
def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n)
| 0 p _ := none
| (n+1) p _ := by resetI; exact option.cases_on
(@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _)
(if h : p (fin.last n) then some (fin.last n) else none)
(λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2)))
/-- If `find p = some i`, then `p i` holds -/
lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n}
(hi : i ∈ by exactI fin.find p), p i
| 0 p I i hi := option.no_confusion hi
| (n+1) p I i hi := begin
dsimp [find] at hi,
resetI,
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j,
{ rw h at hi,
dsimp at hi,
split_ifs at hi with hl hl,
{ exact option.some_inj.1 hi ▸ hl },
{ exact option.no_confusion hi } },
{ rw h at hi,
rw [← option.some_inj.1 hi],
exact find_spec _ h }
end
/-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/
lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p],
by exactI (find p).is_some ↔ ∃ i, p i
| 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i)
| (n+1) p _ := ⟨λ h, begin
rw [option.is_some_iff_exists] at h,
cases h with i hi,
exactI ⟨i, find_spec _ hi⟩
end, λ ⟨⟨i, hin⟩, hi⟩,
begin
resetI,
dsimp [find],
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j,
{ split_ifs with hl hl,
{ exact option.is_some_some },
{ have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2
⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin)
(λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩,
rw h at this,
exact this } },
{ simp }
end⟩
/-- `find p` returns `none` if and only if `p i` never holds. -/
lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] :
find p = none ↔ ∀ i, ¬ p i :=
by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp
/-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among
the indices where `p` holds. -/
lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n}
(hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j
| 0 p _ i hi j hj hpj := option.no_confusion hi
| (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin
resetI,
dsimp [find] at hi,
cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k,
{ rw [h] at hi,
split_ifs at hi with hl hl,
{ have := option.some_inj.1 hi,
subst this,
rw [find_eq_none_iff] at h,
exact h ⟨j, hj⟩ hpj },
{ exact option.no_confusion hi } },
{ rw h at hi,
dsimp at hi,
have := option.some_inj.1 hi,
subst this,
exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj }
end
lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n}
(h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j :=
le_of_not_gt (λ hij, find_min h hij hj)
lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p]
(h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) :
(⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p :=
let ⟨i, hin, hi⟩ := h in
begin
cases hf : find p with f,
{ rw [find_eq_none_iff] at hf,
exact (hf ⟨i, hin⟩ hi).elim },
{ refine option.some_inj.2 (le_antisymm _ _),
{ exact find_min' hf (nat.find_spec h).snd },
{ exact nat.find_min' _ ⟨f.2, by convert find_spec p hf;
exact fin.eta _ _⟩ } }
end
lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} :
i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j :=
⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩,
begin
rintros ⟨hpi, hj⟩,
cases hfp : fin.find p,
{ rw [find_eq_none_iff] at hfp,
exact (hfp _ hpi).elim },
{ exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) }
end⟩
lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} :
fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j :=
mem_find_iff
lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p]
(h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p :=
mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩
end find
@[simp]
lemma coe_of_nat_eq_mod (m n : ℕ) :
((n : fin (succ m)) : ℕ) = n % succ m :=
by rw [← of_nat_eq_coe]; refl
@[simp] lemma coe_of_nat_eq_mod' (m n : ℕ) [I : fact (0 < m)] :
(@fin.of_nat' _ I n : ℕ) = n % m :=
rfl
end fin
|
5b820b0f06cd58c6a184ce2817ef569a9bcd49f9 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/eqnsAtSimp2.lean | 862b4de62ba71ece1187873a5c1b01b0eafb746c | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 801 | lean | mutual
@[simp] def isEven : Nat → Bool
| 0 => true
| n+1 => isOdd n
@[simp] def isOdd : Nat → Bool
| 0 => false
| n+1 => isEven n
end
termination_by' measure fun
| PSum.inl n => n
| PSum.inr n => n
decreasing_by apply Nat.lt_succ_self
theorem isEven_double (x : Nat) : isEven (2 * x) = true := by
induction x with
| zero => simp
| succ x ih => simp [Nat.mul_succ, Nat.add_succ, ih]
def f (x : Nat) : Nat :=
match x with
| 0 => 1
| x + 1 => f x * 2
termination_by' measure id
decreasing_by apply Nat.lt_succ_self
attribute [simp] f
theorem f_succ (x : Nat) : f (x+1) = f x * 2 := by
simp
theorem f_succ₂ (x : Nat) : f (x+1) = f x * 2 := by
simp [-f]
simp
attribute [-simp] f
theorem f_succ₃ (x : Nat) : f (x+1) = f x * 2 := by
simp
simp [f]
|
f6e41ae73f1ed396df2759622814a1eedf1a5d66 | a338c3e75cecad4fb8d091bfe505f7399febfd2b | /src/ring_theory/jacobson.lean | e2e57202acdbd5f9c605dfd47e5d5424e1f72d9f | [
"Apache-2.0"
] | permissive | bacaimano/mathlib | 88eb7911a9054874fba2a2b74ccd0627c90188af | f2edc5a3529d95699b43514d6feb7eb11608723f | refs/heads/master | 1,686,410,075,833 | 1,625,497,070,000 | 1,625,497,070,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 34,301 | lean | /-
Copyright (c) 2020 Devon Tuma. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Devon Tuma
-/
import data.mv_polynomial
import ring_theory.ideal.over
import ring_theory.jacobson_ideal
import ring_theory.localization
/-!
# Jacobson Rings
The following conditions are equivalent for a ring `R`:
1. Every radical ideal `I` is equal to its Jacobson radical
2. Every radical ideal `I` can be written as an intersection of maximal ideals
3. Every prime ideal `I` is equal to its Jacobson radical
Any ring satisfying any of these equivalent conditions is said to be Jacobson.
Some particular examples of Jacobson rings are also proven.
`is_jacobson_quotient` says that the quotient of a Jacobson ring is Jacobson.
`is_jacobson_localization` says the localization of a Jacobson ring to a single element is Jacobson.
`is_jacobson_polynomial_iff_is_jacobson` says polynomials over a Jacobson ring form a Jacobson ring.
## Main definitions
Let `R` be a commutative ring. Jacobson Rings are defined using the first of the above conditions
* `is_jacobson R` is the proposition that `R` is a Jacobson ring. It is a class,
implemented as the predicate that for any ideal, `I.radical = I` implies `I.jacobson = I`.
## Main statements
* `is_jacobson_iff_prime_eq` is the equivalence between conditions 1 and 3 above.
* `is_jacobson_iff_Inf_maximal` is the equivalence between conditions 1 and 2 above.
* `is_jacobson_of_surjective` says that if `R` is a Jacobson ring and `f : R →+* S` is surjective,
then `S` is also a Jacobson ring
* `is_jacobson_mv_polynomial` says that multi-variate polynomials over a Jacobson ring are Jacobson.
## Tags
Jacobson, Jacobson Ring
-/
namespace ideal
open polynomial
section is_jacobson
variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R}
/-- A ring is a Jacobson ring if for every radical ideal `I`,
the Jacobson radical of `I` is equal to `I`.
See `is_jacobson_iff_prime_eq` and `is_jacobson_iff_Inf_maximal` for equivalent definitions. -/
class is_jacobson (R : Type*) [comm_ring R] : Prop :=
(out' : ∀ (I : ideal R), I.radical = I → I.jacobson = I)
theorem is_jacobson_iff {R} [comm_ring R] :
is_jacobson R ↔ ∀ (I : ideal R), I.radical = I → I.jacobson = I :=
⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem is_jacobson.out {R} [comm_ring R] :
is_jacobson R → ∀ {I : ideal R}, I.radical = I → I.jacobson = I := is_jacobson_iff.1
/-- A ring is a Jacobson ring if and only if for all prime ideals `P`,
the Jacobson radical of `P` is equal to `P`. -/
lemma is_jacobson_iff_prime_eq : is_jacobson R ↔ ∀ P : ideal R, is_prime P → P.jacobson = P :=
begin
refine is_jacobson_iff.trans ⟨λ h I hI, h I (is_prime.radical hI), _⟩,
refine λ h I hI, le_antisymm (λ x hx, _) (λ x hx, mem_Inf.mpr (λ _ hJ, hJ.left hx)),
rw [← hI, radical_eq_Inf I, mem_Inf],
intros P hP,
rw set.mem_set_of_eq at hP,
erw mem_Inf at hx,
erw [← h P hP.right, mem_Inf],
exact λ J hJ, hx ⟨le_trans hP.left hJ.left, hJ.right⟩
end
/-- A ring `R` is Jacobson if and only if for every prime ideal `I`,
`I` can be written as the infimum of some collection of maximal ideals.
Allowing ⊤ in the set `M` of maximal ideals is equivalent, but makes some proofs cleaner. -/
lemma is_jacobson_iff_Inf_maximal : is_jacobson R ↔
∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M :=
⟨λ H I h, eq_jacobson_iff_Inf_maximal.1 (H.out (is_prime.radical h)),
λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal.2 (H hP))⟩
lemma is_jacobson_iff_Inf_maximal' : is_jacobson R ↔
∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R),
(∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M :=
⟨λ H I h, eq_jacobson_iff_Inf_maximal'.1 (H.out (is_prime.radical h)),
λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal'.2 (H hP))⟩
lemma radical_eq_jacobson [H : is_jacobson R] (I : ideal R) : I.radical = I.jacobson :=
le_antisymm (le_Inf (λ J ⟨hJ, hJ_max⟩, (is_prime.radical_le_iff hJ_max.is_prime).mpr hJ))
((H.out (radical_idem I)) ▸ (jacobson_mono le_radical))
/-- Fields have only two ideals, and the condition holds for both of them. -/
@[priority 100]
instance is_jacobson_field {K : Type*} [field K] : is_jacobson K :=
⟨λ I hI, or.rec_on (eq_bot_or_top I)
(λ h, le_antisymm
(Inf_le ⟨le_of_eq rfl, (eq.symm h) ▸ bot_is_maximal⟩)
((eq.symm h) ▸ bot_le))
(λ h, by rw [h, jacobson_eq_top_iff])⟩
theorem is_jacobson_of_surjective [H : is_jacobson R] :
(∃ (f : R →+* S), function.surjective f) → is_jacobson S :=
begin
rintros ⟨f, hf⟩,
rw is_jacobson_iff_Inf_maximal,
intros p hp,
use map f '' {J : ideal R | comap f p ≤ J ∧ J.is_maximal },
use λ j ⟨J, hJ, hmap⟩, hmap ▸ or.symm (map_eq_top_or_is_maximal_of_surjective f hf hJ.right),
have : p = map f ((comap f p).jacobson),
from (is_jacobson.out' (comap f p) (by rw [← comap_radical, is_prime.radical hp])).symm
▸ (map_comap_of_surjective f hf p).symm,
exact eq.trans this (map_Inf hf (λ J ⟨hJ, _⟩, le_trans (ideal.ker_le_comap f) hJ)),
end
@[priority 100]
instance is_jacobson_quotient [is_jacobson R] : is_jacobson (quotient I) :=
is_jacobson_of_surjective ⟨quotient.mk I, (by rintro ⟨x⟩; use x; refl)⟩
lemma is_jacobson_iso (e : R ≃+* S) : is_jacobson R ↔ is_jacobson S :=
⟨λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e : R →+* S), e.surjective⟩,
λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e.symm : S →+* R), e.symm.surjective⟩⟩
lemma is_jacobson_of_is_integral [algebra R S] (hRS : algebra.is_integral R S)
(hR : is_jacobson R) : is_jacobson S :=
begin
rw is_jacobson_iff_prime_eq,
introsI P hP,
by_cases hP_top : comap (algebra_map R S) P = ⊤,
{ simp [comap_eq_top_iff.1 hP_top] },
{ haveI : nontrivial (comap (algebra_map R S) P).quotient := quotient.nontrivial hP_top,
rw jacobson_eq_iff_jacobson_quotient_eq_bot,
refine eq_bot_of_comap_eq_bot (is_integral_quotient_of_is_integral hRS) _,
rw [eq_bot_iff, ← jacobson_eq_iff_jacobson_quotient_eq_bot.1 ((is_jacobson_iff_prime_eq.1 hR)
(comap (algebra_map R S) P) (comap_is_prime _ _)), comap_jacobson],
refine Inf_le_Inf (λ J hJ, _),
simp only [true_and, set.mem_image, bot_le, set.mem_set_of_eq],
haveI : J.is_maximal := by simpa using hJ,
exact exists_ideal_over_maximal_of_is_integral (is_integral_quotient_of_is_integral hRS) J
(comap_bot_le_of_injective _ algebra_map_quotient_injective) }
end
lemma is_jacobson_of_is_integral' (f : R →+* S) (hf : f.is_integral)
(hR : is_jacobson R) : is_jacobson S :=
@is_jacobson_of_is_integral _ _ _ _ f.to_algebra hf hR
end is_jacobson
section localization
open is_localization submonoid
variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R}
variables (y : R) [algebra R S] [is_localization.away y S]
lemma disjoint_powers_iff_not_mem (hI : I.radical = I) :
disjoint ((submonoid.powers y) : set R) ↑I ↔ y ∉ I.1 :=
begin
refine ⟨λ h, set.disjoint_left.1 h (mem_powers _), λ h, (disjoint_iff).mpr (eq_bot_iff.mpr _)⟩,
rintros x ⟨⟨n, rfl⟩, hx'⟩,
rw [← hI] at hx',
exact absurd (hI ▸ mem_radical_of_pow_mem hx' : y ∈ I.carrier) h
end
variables (S)
/-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y`
correspond to maximal ideals in the original ring `R` that don't contain `y`.
This lemma gives the correspondence in the particular case of an ideal and its comap.
See `le_rel_iso_of_maximal` for the more general relation isomorphism -/
lemma is_maximal_iff_is_maximal_disjoint [H : is_jacobson R] (J : ideal S) :
J.is_maximal ↔ (comap (algebra_map R S) J).is_maximal ∧ y ∉ ideal.comap (algebra_map R S) J :=
begin
split,
{ refine λ h, ⟨_, λ hy, h.ne_top (ideal.eq_top_of_is_unit_mem _ hy
(map_units _ ⟨y, submonoid.mem_powers _⟩))⟩,
have hJ : J.is_prime := is_maximal.is_prime h,
rw is_prime_iff_is_prime_disjoint (submonoid.powers y) at hJ,
have : y ∉ (comap (algebra_map R S) J).1 :=
set.disjoint_left.1 hJ.right (submonoid.mem_powers _),
erw [← H.out (is_prime.radical hJ.left), mem_Inf] at this,
push_neg at this,
rcases this with ⟨I, hI, hI'⟩,
convert hI.right,
by_cases hJ : J = map (algebra_map R S) I,
{ rw [hJ, comap_map_of_is_prime_disjoint (powers y) S I (is_maximal.is_prime hI.right)],
rwa disjoint_powers_iff_not_mem y (is_maximal.is_prime hI.right).radical },
{ have hI_p : (map (algebra_map R S) I).is_prime,
{ refine is_prime_of_is_prime_disjoint (powers y) _ I hI.right.is_prime _,
rwa disjoint_powers_iff_not_mem y (is_maximal.is_prime hI.right).radical },
have : J ≤ map (algebra_map R S) I :=
(map_comap (submonoid.powers y) S J) ▸ (map_mono hI.left),
exact absurd (h.1.2 _ (lt_of_le_of_ne this hJ)) hI_p.1 } },
{ refine λ h, ⟨⟨λ hJ, h.1.ne_top (eq_top_iff.2 _), λ I hI, _⟩⟩,
{ rwa [eq_top_iff, ← (is_localization.order_embedding (powers y) S).le_iff_le] at hJ },
{ have := congr_arg (map (algebra_map R S)) (h.1.1.2 _ ⟨comap_mono (le_of_lt hI), _⟩),
rwa [map_comap (powers y) S I, map_top] at this,
refine λ hI', hI.right _,
rw [← map_comap (powers y) S I, ← map_comap (powers y) S J],
exact map_mono hI' } }
end
variables {S}
/-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y`
correspond to maximal ideals in the original ring `R` that don't contain `y`.
This lemma gives the correspondence in the particular case of an ideal and its map.
See `le_rel_iso_of_maximal` for the more general statement, and the reverse of this implication -/
lemma is_maximal_of_is_maximal_disjoint [is_jacobson R] (I : ideal R) (hI : I.is_maximal)
(hy : y ∉ I) : (map (algebra_map R S) I).is_maximal :=
begin
rw [is_maximal_iff_is_maximal_disjoint S y,
comap_map_of_is_prime_disjoint (powers y) S I (is_maximal.is_prime hI)
((disjoint_powers_iff_not_mem y (is_maximal.is_prime hI).radical).2 hy)],
exact ⟨hI, hy⟩
end
/-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y`
correspond to maximal ideals in the original ring `R` that don't contain `y` -/
def order_iso_of_maximal [is_jacobson R] :
{p : ideal S // p.is_maximal} ≃o {p : ideal R // p.is_maximal ∧ y ∉ p} :=
{ to_fun := λ p,
⟨ideal.comap (algebra_map R S) p.1, (is_maximal_iff_is_maximal_disjoint S y p.1).1 p.2⟩,
inv_fun := λ p,
⟨ideal.map (algebra_map R S) p.1, is_maximal_of_is_maximal_disjoint y p.1 p.2.1 p.2.2⟩,
left_inv := λ J, subtype.eq (map_comap (powers y) S J),
right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint _ _ I.1 (is_maximal.is_prime I.2.1)
((disjoint_powers_iff_not_mem y I.2.1.is_prime.radical).2 I.2.2)),
map_rel_iff' := λ I I', ⟨λ h, (show I.val ≤ I'.val,
from (map_comap (powers y) S I.val) ▸ (map_comap (powers y) S I'.val) ▸ (ideal.map_mono h)),
λ h x hx, h hx⟩ }
include y
/-- If `S` is the localization of the Jacobson ring `R` at the submonoid generated by `y : R`, then
`S` is Jacobson. -/
lemma is_jacobson_localization [H : is_jacobson R] : is_jacobson S :=
begin
rw is_jacobson_iff_prime_eq,
refine λ P' hP', le_antisymm _ le_jacobson,
obtain ⟨hP', hPM⟩ := (is_localization.is_prime_iff_is_prime_disjoint (powers y) S P').mp hP',
have hP := H.out (is_prime.radical hP'),
refine (le_of_eq (is_localization.map_comap (powers y) S P'.jacobson).symm).trans
((map_mono _).trans (le_of_eq (is_localization.map_comap (powers y) S P'))),
have : Inf { I : ideal R | comap (algebra_map R S) P' ≤ I ∧ I.is_maximal ∧ y ∉ I } ≤
comap (algebra_map R S) P',
{ intros x hx,
have hxy : x * y ∈ (comap (algebra_map R S) P').jacobson,
{ rw [ideal.jacobson, mem_Inf],
intros J hJ,
by_cases y ∈ J,
{ exact J.smul_mem x h },
{ exact (mul_comm y x) ▸ J.smul_mem y ((mem_Inf.1 hx) ⟨hJ.left, ⟨hJ.right, h⟩⟩) } },
rw hP at hxy,
cases hP'.mem_or_mem hxy with hxy hxy,
{ exact hxy },
{ exact (hPM ⟨submonoid.mem_powers _, hxy⟩).elim } },
refine le_trans _ this,
rw [ideal.jacobson, comap_Inf', Inf_eq_infi],
refine infi_le_infi_of_subset (λ I hI, ⟨map (algebra_map R S) I, ⟨_, _⟩⟩),
{ exact ⟨le_trans (le_of_eq ((is_localization.map_comap (powers y) S P').symm)) (map_mono hI.1),
is_maximal_of_is_maximal_disjoint y _ hI.2.1 hI.2.2⟩ },
{ exact is_localization.comap_map_of_is_prime_disjoint _ S I (is_maximal.is_prime hI.2.1)
((disjoint_powers_iff_not_mem y hI.2.1.is_prime.radical).2 hI.2.2) }
end
end localization
namespace polynomial
open polynomial
section comm_ring
variables {R S : Type*} [comm_ring R] [integral_domain S]
variables {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ]
/-- If `I` is a prime ideal of `polynomial R` and `pX ∈ I` is a non-constant polynomial,
then the map `R →+* R[x]/I` descends to an integral map when localizing at `pX.leading_coeff`.
In particular `X` is integral because it satisfies `pX`, and constants are trivially integral,
so integrality of the entire extension follows by closure under addition and multiplication. -/
lemma is_integral_is_localization_polynomial_quotient
(P : ideal (polynomial R)) [P.is_prime] (pX : polynomial R) (hpX : pX ∈ P)
[algebra (P.comap (C : R →+* _)).quotient Rₘ]
[is_localization.away (pX.map (quotient.mk (P.comap C))).leading_coeff Rₘ]
[algebra P.quotient Sₘ]
[is_localization ((submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff).map
(quotient_map P C le_rfl) : submonoid P.quotient) Sₘ] :
(is_localization.map Sₘ (quotient_map P C le_rfl)
((submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff).le_comap_map) : Rₘ →+* _)
.is_integral :=
begin
let P' : ideal R := P.comap C,
let M : submonoid P'.quotient :=
submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff,
let M' : submonoid P.quotient :=
(submonoid.powers (pX.map (quotient.mk (P.comap C))).leading_coeff).map (quotient_map P C le_rfl),
let φ : P'.quotient →+* P.quotient := quotient_map P C le_rfl,
let φ' := is_localization.map Sₘ φ M.le_comap_map,
have hφ' : φ.comp (quotient.mk P') = (quotient.mk P).comp C := rfl,
intro p,
obtain ⟨⟨p', ⟨q, hq⟩⟩, hp⟩ := is_localization.surj M' p,
suffices : φ'.is_integral_elem (algebra_map _ _ p'),
{ obtain ⟨q', hq', rfl⟩ := hq,
obtain ⟨q'', hq''⟩ := is_unit_iff_exists_inv'.1 (is_localization.map_units Rₘ (⟨q', hq'⟩ : M)),
refine φ'.is_integral_of_is_integral_mul_unit p (algebra_map _ _ (φ q')) q'' _ (hp.symm ▸ this),
convert trans (trans (φ'.map_mul _ _).symm (congr_arg φ' hq'')) φ'.map_one using 2,
rw [← φ'.comp_apply, is_localization.map_comp, ring_hom.comp_apply, subtype.coe_mk] },
refine is_integral_of_mem_closure''
(((algebra_map _ Sₘ).comp (quotient.mk P)) '' (insert X {p | p.degree ≤ 0})) _ _ _,
{ rintros x ⟨p, hp, rfl⟩,
refine hp.rec_on (λ hy, _) (λ hy, _),
{ refine hy.symm ▸ (φ.is_integral_elem_localization_at_leading_coeff ((quotient.mk P) X)
(pX.map (quotient.mk P')) _ M ⟨1, pow_one _⟩),
rwa [eval₂_map, hφ', ← hom_eval₂, quotient.eq_zero_iff_mem, eval₂_C_X] },
{ rw [set.mem_set_of_eq, degree_le_zero_iff] at hy,
refine hy.symm ▸ ⟨X - C (algebra_map _ _ ((quotient.mk P') (p.coeff 0))), monic_X_sub_C _, _⟩,
simp only [eval₂_sub, eval₂_C, eval₂_X],
rw [sub_eq_zero, ← φ'.comp_apply, is_localization.map_comp],
refl } },
{ obtain ⟨p, rfl⟩ := quotient.mk_surjective p',
refine polynomial.induction_on p
(λ r, subring.subset_closure $ set.mem_image_of_mem _ (or.inr degree_C_le))
(λ _ _ h1 h2, _) (λ n _ hr, _),
{ convert subring.add_mem _ h1 h2,
rw [ring_hom.map_add, ring_hom.map_add] },
{ rw [pow_succ X n, mul_comm X, ← mul_assoc, ring_hom.map_mul, ring_hom.map_mul],
exact subring.mul_mem _ hr (subring.subset_closure (set.mem_image_of_mem _ (or.inl rfl))) } },
end
/-- If `f : R → S` descends to an integral map in the localization at `x`,
and `R` is a Jacobson ring, then the intersection of all maximal ideals in `S` is trivial -/
lemma jacobson_bot_of_integral_localization {R : Type*} [integral_domain R] [is_jacobson R]
(Rₘ Sₘ : Type*) [comm_ring Rₘ] [comm_ring Sₘ]
(φ : R →+* S) (hφ : function.injective φ) (x : R) (hx : x ≠ 0)
[algebra R Rₘ] [is_localization.away x Rₘ]
[algebra S Sₘ] [is_localization ((submonoid.powers x).map φ : submonoid S) Sₘ]
(hφ' : ring_hom.is_integral
(is_localization.map Sₘ φ (submonoid.powers x).le_comap_map : Rₘ →+* Sₘ)) :
(⊥ : ideal S).jacobson = (⊥ : ideal S) :=
begin
have hM : ((submonoid.powers x).map φ : submonoid S) ≤ non_zero_divisors S :=
map_le_non_zero_divisors_of_injective hφ (powers_le_non_zero_divisors_of_domain hx),
letI : integral_domain Sₘ := is_localization.integral_domain_of_le_non_zero_divisors _ hM,
let φ' : Rₘ →+* Sₘ := is_localization.map _ φ (submonoid.powers x).le_comap_map,
suffices : ∀ I : ideal Sₘ, I.is_maximal → (I.comap (algebra_map S Sₘ)).is_maximal,
{ have hϕ' : comap (algebra_map S Sₘ) (⊥ : ideal Sₘ) = (⊥ : ideal S),
{ rw [← ring_hom.ker_eq_comap_bot, ← ring_hom.injective_iff_ker_eq_bot],
exact is_localization.injective Sₘ hM },
have hSₘ : is_jacobson Sₘ := is_jacobson_of_is_integral' φ' hφ' (is_jacobson_localization x),
refine eq_bot_iff.mpr (le_trans _ (le_of_eq hϕ')),
rw [← hSₘ.out radical_bot_of_integral_domain, comap_jacobson],
exact Inf_le_Inf (λ j hj, ⟨bot_le, let ⟨J, hJ⟩ := hj in hJ.2 ▸ this J hJ.1.2⟩) },
introsI I hI,
-- Remainder of the proof is pulling and pushing ideals around the square and the quotient square
haveI : (I.comap (algebra_map S Sₘ)).is_prime := comap_is_prime _ I,
haveI : (I.comap φ').is_prime := comap_is_prime φ' I,
haveI : (⊥ : ideal (I.comap (algebra_map S Sₘ)).quotient).is_prime := bot_prime,
have hcomm: φ'.comp (algebra_map R Rₘ) = (algebra_map S Sₘ).comp φ := is_localization.map_comp _,
let f := quotient_map (I.comap (algebra_map S Sₘ)) φ le_rfl,
let g := quotient_map I (algebra_map S Sₘ) le_rfl,
have := is_maximal_comap_of_is_integral_of_is_maximal' φ' hφ' I
(by convert hI; casesI _inst_4; refl),
have := ((is_maximal_iff_is_maximal_disjoint Rₘ x _).1 this).left,
have : ((I.comap (algebra_map S Sₘ)).comap φ).is_maximal,
{ rwa [comap_comap, hcomm, ← comap_comap] at this },
rw ← bot_quotient_is_maximal_iff at this ⊢,
refine is_maximal_of_is_integral_of_is_maximal_comap' f _ ⊥
((eq_bot_iff.2 (comap_bot_le_of_injective f quotient_map_injective)).symm ▸ this),
exact f.is_integral_tower_bot_of_is_integral g quotient_map_injective
((comp_quotient_map_eq_of_comp_eq hcomm I).symm ▸
(ring_hom.is_integral_trans _ _ (ring_hom.is_integral_of_surjective _
(is_localization.surjective_quotient_map_of_maximal_of_localization (submonoid.powers x) Rₘ
(by rwa [comap_comap, hcomm, ← bot_quotient_is_maximal_iff])))
(ring_hom.is_integral_quotient_of_is_integral _ hφ'))),
end
/-- Used to bootstrap the proof of `is_jacobson_polynomial_iff_is_jacobson`.
That theorem is more general and should be used instead of this one. -/
private lemma is_jacobson_polynomial_of_domain (R : Type*) [integral_domain R] [hR : is_jacobson R]
(P : ideal (polynomial R)) [is_prime P] (hP : ∀ (x : R), C x ∈ P → x = 0) :
P.jacobson = P :=
begin
by_cases Pb : P = ⊥,
{ exact Pb.symm ▸ jacobson_bot_polynomial_of_jacobson_bot
(hR.out radical_bot_of_integral_domain) },
{ rw jacobson_eq_iff_jacobson_quotient_eq_bot,
haveI : (P.comap (C : R →+* polynomial R)).is_prime := comap_is_prime C P,
obtain ⟨p, pP, p0⟩ := exists_nonzero_mem_of_ne_bot Pb hP,
let x := (polynomial.map (quotient.mk (comap (C : R →+* _) P)) p).leading_coeff,
have hx : x ≠ 0 := by rwa [ne.def, leading_coeff_eq_zero],
refine jacobson_bot_of_integral_localization
(localization.away x)
(localization ((submonoid.powers x).map (P.quotient_map C le_rfl) : submonoid P.quotient))
(quotient_map P C le_rfl) quotient_map_injective
x hx
_,
-- `convert` is noticeably faster than `exact` here:
convert is_integral_is_localization_polynomial_quotient P p pP }
end
lemma is_jacobson_polynomial_of_is_jacobson (hR : is_jacobson R) :
is_jacobson (polynomial R) :=
begin
refine is_jacobson_iff_prime_eq.mpr (λ I, _),
introI hI,
let R' : subring I.quotient := ((quotient.mk I).comp C).range,
let i : R →+* R' := ((quotient.mk I).comp C).range_restrict,
have hi : function.surjective (i : R → R') := ((quotient.mk I).comp C).range_restrict_surjective,
have hi' : (polynomial.map_ring_hom i : polynomial R →+* polynomial R').ker ≤ I,
{ refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _),
replace hf := congr_arg (λ (g : polynomial (((quotient.mk I).comp C).range)), g.coeff n) hf,
change (polynomial.map ((quotient.mk I).comp C).range_restrict f).coeff n = 0 at hf,
rw [coeff_map, subtype.ext_iff] at hf,
rwa [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], },
haveI : (ideal.map (map_ring_hom i) I).is_prime :=
map_is_prime_of_surjective (map_surjective i hi) hi',
suffices : (I.map (polynomial.map_ring_hom i)).jacobson = (I.map (polynomial.map_ring_hom i)),
{ replace this := congr_arg (comap (polynomial.map_ring_hom i)) this,
rw [← map_jacobson_of_surjective _ hi',
comap_map_of_surjective _ _, comap_map_of_surjective _ _] at this,
refine le_antisymm (le_trans (le_sup_of_le_left le_rfl)
(le_trans (le_of_eq this) (sup_le le_rfl hi'))) le_jacobson,
all_goals {exact polynomial.map_surjective i hi} },
exact @is_jacobson_polynomial_of_domain R' _ (is_jacobson_of_surjective ⟨i, hi⟩)
(map (map_ring_hom i) I) _ (eq_zero_of_polynomial_mem_map_range I),
end
theorem is_jacobson_polynomial_iff_is_jacobson :
is_jacobson (polynomial R) ↔ is_jacobson R :=
begin
refine ⟨_, is_jacobson_polynomial_of_is_jacobson⟩,
introI H,
exact is_jacobson_of_surjective ⟨eval₂_ring_hom (ring_hom.id _) 1, λ x,
⟨C x, by simp only [coe_eval₂_ring_hom, ring_hom.id_apply, eval₂_C]⟩⟩,
end
instance [is_jacobson R] : is_jacobson (polynomial R) :=
is_jacobson_polynomial_iff_is_jacobson.mpr ‹is_jacobson R›
end comm_ring
section integral_domain
variables {R : Type*} [integral_domain R] [is_jacobson R]
variables (P : ideal (polynomial R)) [hP : P.is_maximal]
include P hP
lemma is_maximal_comap_C_of_is_maximal (hP' : ∀ (x : R), C x ∈ P → x = 0) :
is_maximal (comap C P : ideal R) :=
begin
haveI hp'_prime : (P.comap C : ideal R).is_prime := comap_is_prime C P,
obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_of_maximal P polynomial_not_is_field),
have : (m : polynomial R) ≠ 0, rwa [ne.def, submodule.coe_eq_zero],
let φ : (P.comap C : ideal R).quotient →+* P.quotient := quotient_map P C le_rfl,
let M : submonoid (P.comap C : ideal R).quotient :=
submonoid.powers ((m : polynomial R).map (quotient.mk (P.comap C : ideal R))).leading_coeff,
rw ← bot_quotient_is_maximal_iff at hP ⊢,
have hp0 : ((m : polynomial R).map (quotient.mk (P.comap C : ideal R))).leading_coeff ≠ 0 :=
λ hp0', this $ map_injective (quotient.mk (P.comap C : ideal R))
((quotient.mk (P.comap C : ideal R)).injective_iff.2 (λ x hx,
by rwa [quotient.eq_zero_iff_mem, (by rwa eq_bot_iff : (P.comap C : ideal R) = ⊥)] at hx))
(by simpa only [leading_coeff_eq_zero, map_zero] using hp0'),
have hM : (0 : ((P.comap C : ideal R)).quotient) ∉ M := λ ⟨n, hn⟩, hp0 (pow_eq_zero hn),
suffices : (⊥ : ideal (localization M)).is_maximal,
{ rw ← is_localization.comap_map_of_is_prime_disjoint M (localization M) ⊥ bot_prime
(λ x hx, hM (hx.2 ▸ hx.1)),
refine ((is_maximal_iff_is_maximal_disjoint (localization M) _ _).mp (by rwa map_bot)).1,
swap, exact localization.is_localization },
let M' : submonoid P.quotient := M.map φ,
have hM' : (0 : P.quotient) ∉ M' :=
λ ⟨z, hz⟩, hM (quotient_map_injective (trans hz.2 φ.map_zero.symm) ▸ hz.1),
letI : integral_domain (localization M') :=
is_localization.integral_domain_localization (le_non_zero_divisors_of_domain hM'),
suffices : (⊥ : ideal (localization M')).is_maximal,
{ rw le_antisymm bot_le (comap_bot_le_of_injective _ (is_localization.map_injective_of_injective
M (localization M) (localization M')
quotient_map_injective (le_non_zero_divisors_of_domain hM'))),
refine is_maximal_comap_of_is_integral_of_is_maximal' _ _ ⊥ this,
apply is_integral_is_localization_polynomial_quotient P _ (submodule.coe_mem m) },
rw (map_bot.symm : (⊥ : ideal (localization M')) =
map (algebra_map P.quotient (localization M')) ⊥),
refine map.is_maximal (algebra_map _ _) (localization_map_bijective_of_field hM' _) hP,
rwa [← quotient.maximal_ideal_iff_is_field_quotient, ← bot_quotient_is_maximal_iff],
end
/-- Used to bootstrap the more general `quotient_mk_comp_C_is_integral_of_jacobson` -/
private lemma quotient_mk_comp_C_is_integral_of_jacobson' (hR : is_jacobson R)
(hP' : ∀ (x : R), C x ∈ P → x = 0) :
((quotient.mk P).comp C : R →+* P.quotient).is_integral :=
begin
refine (is_integral_quotient_map_iff _).mp _,
let P' : ideal R := P.comap C,
obtain ⟨pX, hpX, hp0⟩ :=
exists_nonzero_mem_of_ne_bot (ne_of_lt (bot_lt_of_maximal P polynomial_not_is_field)).symm hP',
let M : submonoid P'.quotient := submonoid.powers (pX.map (quotient.mk P')).leading_coeff,
let φ : P'.quotient →+* P.quotient := quotient_map P C le_rfl,
haveI hp'_prime : P'.is_prime := comap_is_prime C P,
have hM : (0 : P'.quotient) ∉ M := λ ⟨n, hn⟩, hp0 $ leading_coeff_eq_zero.mp (pow_eq_zero hn),
let M' : submonoid P.quotient := M.map (quotient_map P C le_rfl),
refine ((quotient_map P C le_rfl).is_integral_tower_bot_of_is_integral
(algebra_map _ (localization M')) _ _),
{ refine is_localization.injective (localization M')
(show M' ≤ _, from le_non_zero_divisors_of_domain (λ hM', hM _)),
exact (let ⟨z, zM, z0⟩ := hM' in (quotient_map_injective (trans z0 φ.map_zero.symm)) ▸ zM) },
{ rw ← is_localization.map_comp M.le_comap_map,
refine ring_hom.is_integral_trans (algebra_map P'.quotient (localization M))
(is_localization.map _ _ M.le_comap_map) _ _,
{ exact (algebra_map P'.quotient (localization M)).is_integral_of_surjective
(localization_map_bijective_of_field hM
((quotient.maximal_ideal_iff_is_field_quotient _).mp
(is_maximal_comap_C_of_is_maximal P hP'))).2 },
{ -- `convert` here is faster than `exact`, and this proof is near the time limit.
convert is_integral_is_localization_polynomial_quotient P pX hpX } }
end
/-- If `R` is a Jacobson ring, and `P` is a maximal ideal of `polynomial R`,
then `R → (polynomial R)/P` is an integral map. -/
lemma quotient_mk_comp_C_is_integral_of_jacobson :
((quotient.mk P).comp C : R →+* P.quotient).is_integral :=
begin
let P' : ideal R := P.comap C,
haveI : P'.is_prime := comap_is_prime C P,
let f : polynomial R →+* polynomial P'.quotient := polynomial.map_ring_hom (quotient.mk P'),
have hf : function.surjective f := map_surjective (quotient.mk P') quotient.mk_surjective,
have hPJ : P = (P.map f).comap f,
{ rw comap_map_of_surjective _ hf,
refine le_antisymm (le_sup_of_le_left le_rfl) (sup_le le_rfl _),
refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _),
simpa only [coeff_map, coe_map_ring_hom] using (polynomial.ext_iff.mp hp) n },
refine ring_hom.is_integral_tower_bot_of_is_integral _ _ (injective_quotient_le_comap_map P) _,
rw ← quotient_mk_maps_eq,
refine ring_hom.is_integral_trans _ _
((quotient.mk P').is_integral_of_surjective quotient.mk_surjective) _,
apply quotient_mk_comp_C_is_integral_of_jacobson' _ _ (λ x hx, _),
any_goals { exact ideal.is_jacobson_quotient },
{ exact or.rec_on (map_eq_top_or_is_maximal_of_surjective f hf hP)
(λ h, absurd (trans (h ▸ hPJ : P = comap f ⊤) comap_top : P = ⊤) hP.ne_top) id },
{ obtain ⟨z, rfl⟩ := quotient.mk_surjective x,
rwa [quotient.eq_zero_iff_mem, mem_comap, hPJ, mem_comap, coe_map_ring_hom, map_C] }
end
lemma is_maximal_comap_C_of_is_jacobson : (P.comap (C : R →+* polynomial R)).is_maximal :=
begin
rw [← @mk_ker _ _ P, ring_hom.ker_eq_comap_bot, comap_comap],
exact is_maximal_comap_of_is_integral_of_is_maximal' _
(quotient_mk_comp_C_is_integral_of_jacobson P) ⊥ ((bot_quotient_is_maximal_iff _).mpr hP),
end
omit P hP
lemma comp_C_integral_of_surjective_of_jacobson
{S : Type*} [field S] (f : (polynomial R) →+* S) (hf : function.surjective f) :
(f.comp C).is_integral :=
begin
haveI : (f.ker).is_maximal := @comap_is_maximal_of_surjective _ _ _ _ f ⊥ hf bot_is_maximal,
let g : f.ker.quotient →+* S := ideal.quotient.lift f.ker f (λ _ h, h),
have hfg : (g.comp (quotient.mk f.ker)) = f := ring_hom_ext' rfl rfl,
rw [← hfg, ring_hom.comp_assoc],
refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f.ker)
(g.is_integral_of_surjective _), --(quotient.lift_surjective f.ker f _ hf)),
rw [← hfg] at hf,
exact function.surjective.of_comp hf,
end
end integral_domain
end polynomial
namespace mv_polynomial
open mv_polynomial ring_hom
lemma is_jacobson_mv_polynomial_fin {R : Type*} [comm_ring R] [H : is_jacobson R] :
∀ (n : ℕ), is_jacobson (mv_polynomial (fin n) R)
| 0 := ((is_jacobson_iso ((rename_equiv R
(equiv.equiv_pempty (fin 0))).to_ring_equiv.trans (pempty_ring_equiv R))).mpr H)
| (n+1) := (is_jacobson_iso (fin_succ_equiv R n).to_ring_equiv).2
(polynomial.is_jacobson_polynomial_iff_is_jacobson.2 (is_jacobson_mv_polynomial_fin n))
/-- General form of the nullstellensatz for Jacobson rings, since in a Jacobson ring we have
`Inf {P maximal | P ≥ I} = Inf {P prime | P ≥ I} = I.radical`. Fields are always Jacobson,
and in that special case this is (most of) the classical Nullstellensatz,
since `I(V(I))` is the intersection of maximal ideals containing `I`, which is then `I.radical` -/
instance {R : Type*} [comm_ring R] {ι : Type*} [fintype ι] [is_jacobson R] :
is_jacobson (mv_polynomial ι R) :=
begin
haveI := classical.dec_eq ι,
let e := fintype.equiv_fin ι,
rw is_jacobson_iso (rename_equiv R e).to_ring_equiv,
exact is_jacobson_mv_polynomial_fin _
end
variables {n : ℕ}
lemma quotient_mk_comp_C_is_integral_of_jacobson {R : Type*} [integral_domain R] [is_jacobson R]
(P : ideal (mv_polynomial (fin n) R)) [P.is_maximal] :
((quotient.mk P).comp mv_polynomial.C : R →+* P.quotient).is_integral :=
begin
unfreezingI {induction n with n IH},
{ refine ring_hom.is_integral_of_surjective _ (function.surjective.comp quotient.mk_surjective _),
exact C_surjective_fin_0 },
{ rw [← fin_succ_equiv_comp_C_eq_C, ← ring_hom.comp_assoc, ← ring_hom.comp_assoc,
← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc (polynomial.C),
← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc, ring_hom.comp_assoc,
← quotient_map_comp_mk le_rfl, ← ring_hom.comp_assoc (quotient.mk _)],
refine ring_hom.is_integral_trans _ _ _ _,
{ refine ring_hom.is_integral_trans _ _ (is_integral_of_surjective _ quotient.mk_surjective) _,
refine ring_hom.is_integral_trans _ _ _ _,
{ apply (is_integral_quotient_map_iff _).mpr (IH _),
apply polynomial.is_maximal_comap_C_of_is_jacobson _,
{ exact mv_polynomial.is_jacobson_mv_polynomial_fin n },
{ apply comap_is_maximal_of_surjective,
exact (fin_succ_equiv R n).symm.surjective } },
{ refine (is_integral_quotient_map_iff _).mpr _,
rw ← quotient_map_comp_mk le_rfl,
refine ring_hom.is_integral_trans _ _ _ ((is_integral_quotient_map_iff _).mpr _),
{ exact ring_hom.is_integral_of_surjective _ quotient.mk_surjective },
{ apply polynomial.quotient_mk_comp_C_is_integral_of_jacobson _,
{ exact mv_polynomial.is_jacobson_mv_polynomial_fin n },
{ exact comap_is_maximal_of_surjective _ (fin_succ_equiv R n).symm.surjective } } } },
{ refine (is_integral_quotient_map_iff _).mpr _,
refine ring_hom.is_integral_trans _ _ _ (is_integral_of_surjective _ quotient.mk_surjective),
exact ring_hom.is_integral_of_surjective _ (fin_succ_equiv R n).symm.surjective } }
end
lemma comp_C_integral_of_surjective_of_jacobson {R : Type*} [integral_domain R] [is_jacobson R]
{σ : Type*} [fintype σ] {S : Type*} [field S] (f : mv_polynomial σ R →+* S)
(hf : function.surjective f) : (f.comp C).is_integral :=
begin
haveI := classical.dec_eq σ,
obtain ⟨e⟩ := fintype.trunc_equiv_fin σ,
let f' : mv_polynomial (fin _) R →+* S :=
f.comp (rename_equiv R e.symm).to_ring_equiv.to_ring_hom,
have hf' : function.surjective f' :=
((function.surjective.comp hf (rename_equiv R e.symm).surjective)),
have : (f'.comp C).is_integral,
{ haveI : (f'.ker).is_maximal := @comap_is_maximal_of_surjective _ _ _ _ f' ⊥ hf' bot_is_maximal,
let g : f'.ker.quotient →+* S := ideal.quotient.lift f'.ker f' (λ _ h, h),
have hfg : (g.comp (quotient.mk f'.ker)) = f' := ring_hom_ext (λ r, rfl) (λ i, rfl),
rw [← hfg, ring_hom.comp_assoc],
refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f'.ker)
(g.is_integral_of_surjective _),
rw ← hfg at hf',
exact function.surjective.of_comp hf' },
rw ring_hom.comp_assoc at this,
convert this,
refine ring_hom.ext (λ x, _),
exact ((rename_equiv R e.symm).commutes' x).symm,
end
end mv_polynomial
end ideal
|
b94c914e908cfadf243c33dc8db3bd24c5c18020 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebraic_geometry/properties.lean | 0ff5991de7e79fe0650492cb9d68bd79bf5a60c8 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 13,967 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import algebraic_geometry.AffineScheme
import ring_theory.nilpotent
import topology.sheaves.sheaf_condition.sites
import category_theory.limits.constructions.binary_products
import algebra.category.Ring.constructions
import ring_theory.integral_domain
import ring_theory.local_properties
/-!
# Basic properties of schemes
We provide some basic properties of schemes
## Main definition
* `algebraic_geometry.is_integral`: A scheme is integral if it is nontrivial and all nontrivial
components of the structure sheaf are integral domains.
* `algebraic_geometry.is_reduced`: A scheme is reduced if all the components of the structure sheaf
is reduced.
-/
open topological_space opposite category_theory category_theory.limits Top
namespace algebraic_geometry
variable (X : Scheme)
instance : t0_space X.carrier :=
begin
refine t0_space.of_open_cover (λ x, _),
obtain ⟨U, R, ⟨e⟩⟩ := X.local_affine x,
let e' : U.1 ≃ₜ prime_spectrum R :=
homeo_of_iso ((LocallyRingedSpace.forget_to_SheafedSpace ⋙ SheafedSpace.forget _).map_iso e),
exact ⟨U.1.1, U.2, U.1.2, e'.embedding.t0_space⟩
end
instance : quasi_sober X.carrier :=
begin
apply_with (quasi_sober_of_open_cover
(set.range (λ x, set.range $ (X.affine_cover.map x).1.base)))
{ instances := ff },
{ rintro ⟨_,i,rfl⟩, exact (X.affine_cover.is_open i).base_open.open_range },
{ rintro ⟨_,i,rfl⟩,
exact @@open_embedding.quasi_sober _ _ _
(homeomorph.of_embedding _ (X.affine_cover.is_open i).base_open.to_embedding)
.symm.open_embedding prime_spectrum.quasi_sober },
{ rw [set.top_eq_univ, set.sUnion_range, set.eq_univ_iff_forall],
intro x, exact ⟨_, ⟨_, rfl⟩, X.affine_cover.covers x⟩ }
end
/-- A scheme `X` is reduced if all `𝒪ₓ(U)` are reduced. -/
class is_reduced : Prop :=
(component_reduced : ∀ U, _root_.is_reduced (X.presheaf.obj (op U)) . tactic.apply_instance)
attribute [instance] is_reduced.component_reduced
lemma is_reduced_of_stalk_is_reduced [∀ x : X.carrier, _root_.is_reduced (X.presheaf.stalk x)] :
is_reduced X :=
begin
refine ⟨λ U, ⟨λ s hs, _⟩⟩,
apply presheaf.section_ext X.sheaf U s 0,
intro x,
rw ring_hom.map_zero,
change X.presheaf.germ x s = 0,
exact (hs.map _).eq_zero
end
instance stalk_is_reduced_of_reduced [is_reduced X] (x : X.carrier) :
_root_.is_reduced (X.presheaf.stalk x) :=
begin
constructor,
rintros g ⟨n, e⟩,
obtain ⟨U, hxU, s, rfl⟩ := X.presheaf.germ_exist x g,
rw [← map_pow, ← map_zero (X.presheaf.germ ⟨x, hxU⟩)] at e,
obtain ⟨V, hxV, iU, iV, e'⟩ := X.presheaf.germ_eq x hxU hxU _ 0 e,
rw [map_pow, map_zero] at e',
replace e' := (is_nilpotent.mk _ _ e').eq_zero,
erw ← concrete_category.congr_hom (X.presheaf.germ_res iU ⟨x, hxV⟩) s,
rw [comp_apply, e', map_zero]
end
lemma is_reduced_of_open_immersion {X Y : Scheme} (f : X ⟶ Y) [H : is_open_immersion f]
[is_reduced Y] : is_reduced X :=
begin
constructor,
intro U,
have : U = (opens.map f.1.base).obj (H.base_open.is_open_map.functor.obj U),
{ ext1, exact (set.preimage_image_eq _ H.base_open.inj).symm },
rw this,
exact is_reduced_of_injective (inv $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U))
(as_iso $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U) : Y.presheaf.obj _ ≅ _).symm
.CommRing_iso_to_ring_equiv.injective
end
instance {R : CommRing} [H : _root_.is_reduced R] : is_reduced (Scheme.Spec.obj $ op R) :=
begin
apply_with is_reduced_of_stalk_is_reduced { instances := ff },
intro x, dsimp,
haveI : _root_.is_reduced (CommRing.of $ localization.at_prime (prime_spectrum.as_ideal x)),
{ dsimp, apply_instance },
exact is_reduced_of_injective (structure_sheaf.stalk_iso R x).hom
(structure_sheaf.stalk_iso R x).CommRing_iso_to_ring_equiv.injective,
end
lemma affine_is_reduced_iff (R : CommRing) :
is_reduced (Scheme.Spec.obj $ op R) ↔ _root_.is_reduced R :=
begin
refine ⟨_, λ h, by exactI infer_instance⟩,
intro h,
resetI,
haveI : _root_.is_reduced (LocallyRingedSpace.Γ.obj (op $ Spec.to_LocallyRingedSpace.obj $ op R)),
{ change _root_.is_reduced ((Scheme.Spec.obj $ op R).presheaf.obj $ op ⊤), apply_instance },
exact is_reduced_of_injective (to_Spec_Γ R)
((as_iso $ to_Spec_Γ R).CommRing_iso_to_ring_equiv.injective)
end
lemma is_reduced_of_is_affine_is_reduced [is_affine X]
[h : _root_.is_reduced (X.presheaf.obj (op ⊤))] : is_reduced X :=
begin
haveI : is_reduced (Scheme.Spec.obj (op (Scheme.Γ.obj (op X)))),
{ rw affine_is_reduced_iff, exact h },
exact is_reduced_of_open_immersion X.iso_Spec.hom,
end
/-- To show that a statement `P` holds for all open subsets of all schemes, it suffices to show that
1. In any scheme `X`, if `P` holds for an open cover of `U`, then `P` holds for `U`.
2. For an open immerison `f : X ⟶ Y`, if `P` holds for the entire space of `X`, then `P` holds for
the image of `f`.
3. `P` holds for the entire space of an affine scheme.
-/
lemma reduce_to_affine_global (P : ∀ (X : Scheme) (U : opens X.carrier), Prop)
(h₁ : ∀ (X : Scheme) (U : opens X.carrier),
(∀ (x : U), ∃ {V} (h : x.1 ∈ V) (i : V ⟶ U), P X V) → P X U)
(h₂ : ∀ {X Y} (f : X ⟶ Y) [hf : is_open_immersion f], ∃ {U : set X.carrier} {V : set Y.carrier}
(hU : U = ⊤) (hV : V = set.range f.1.base), P X ⟨U, hU.symm ▸ is_open_univ⟩ →
P Y ⟨V, hV.symm ▸ hf.base_open.open_range⟩)
(h₃ : ∀ (R : CommRing), P (Scheme.Spec.obj $ op R) ⊤) :
∀ (X : Scheme) (U : opens X.carrier), P X U :=
begin
intros X U,
apply h₁,
intro x,
obtain ⟨_,⟨j,rfl⟩,hx,i⟩ := X.affine_basis_cover_is_basis.exists_subset_of_mem_open x.prop U.2,
let U' : opens _ := ⟨_, (X.affine_basis_cover.is_open j).base_open.open_range⟩,
let i' : U' ⟶ U :=
hom_of_le i,
refine ⟨U', hx, i', _⟩,
obtain ⟨_,_,rfl,rfl,h₂'⟩ := h₂ (X.affine_basis_cover.map j),
apply h₂',
apply h₃
end
.
lemma reduce_to_affine_nbhd (P : ∀ (X : Scheme) (x : X.carrier), Prop)
(h₁ : ∀ (R : CommRing) (x : prime_spectrum R), P (Scheme.Spec.obj $ op R) x)
(h₂ : ∀ {X Y} (f : X ⟶ Y) [is_open_immersion f] (x : X.carrier), P X x → P Y (f.1.base x)) :
∀ (X : Scheme) (x : X.carrier), P X x :=
begin
intros X x,
obtain ⟨y, e⟩ := X.affine_cover.covers x,
convert h₂ (X.affine_cover.map (X.affine_cover.f x)) y _,
{ rw e },
apply h₁,
end
lemma eq_zero_of_basic_open_empty {X : Scheme} [hX : is_reduced X] {U : opens X.carrier}
(s : X.presheaf.obj (op U)) (hs : X.basic_open s = ∅) :
s = 0 :=
begin
apply Top.presheaf.section_ext X.sheaf U,
simp_rw ring_hom.map_zero,
unfreezingI { revert X U hX s },
refine reduce_to_affine_global _ _ _ _,
{ intros X U hx hX s hs x,
obtain ⟨V, hx, i, H⟩ := hx x,
unfreezingI { specialize H (X.presheaf.map i.op s) },
erw Scheme.basic_open_res at H,
rw [hs, ← subtype.coe_injective.eq_iff, opens.empty_eq, opens.inter_eq, inf_bot_eq] at H,
specialize H rfl ⟨x, hx⟩,
erw Top.presheaf.germ_res_apply at H,
exact H },
{ rintros X Y f hf,
have e : (f.val.base) ⁻¹' set.range ⇑(f.val.base) = ⊤,
{ rw [← set.image_univ, set.preimage_image_eq _ hf.base_open.inj, set.top_eq_univ] },
refine ⟨_, _, e, rfl, _⟩,
rintros H hX s hs ⟨_, x, rfl⟩,
unfreezingI { haveI := is_reduced_of_open_immersion f },
specialize H (f.1.c.app _ s) _ ⟨x, by { change x ∈ (f.val.base) ⁻¹' _, rw e, trivial }⟩,
{ rw [← Scheme.preimage_basic_open, hs], ext1, simp [opens.map] },
{ erw ← PresheafedSpace.stalk_map_germ_apply f.1 ⟨_,_⟩ ⟨x,_⟩ at H,
apply_fun (inv $ PresheafedSpace.stalk_map f.val x) at H,
erw [category_theory.is_iso.hom_inv_id_apply, map_zero] at H,
exact H } },
{ intros R hX s hs x,
erw [basic_open_eq_of_affine', prime_spectrum.basic_open_eq_bot_iff] at hs,
replace hs := (hs.map (Spec_Γ_identity.app R).inv),
-- what the hell?!
replace hs := @is_nilpotent.eq_zero _ _ _ _ (show _, from _) hs,
rw iso.hom_inv_id_apply at hs,
rw [hs, map_zero],
exact @@is_reduced.component_reduced hX ⊤ }
end
@[simp]
lemma basic_open_eq_bot_iff {X : Scheme} [is_reduced X] {U : opens X.carrier}
(s : X.presheaf.obj $ op U) :
X.basic_open s = ⊥ ↔ s = 0 :=
begin
refine ⟨eq_zero_of_basic_open_empty s, _⟩,
rintro rfl,
simp,
end
/-- A scheme `X` is integral if its carrier is nonempty,
and `𝒪ₓ(U)` is an integral domain for each `U ≠ ∅`. -/
class is_integral : Prop :=
(nonempty : nonempty X.carrier . tactic.apply_instance)
(component_integral : ∀ (U : opens X.carrier) [_root_.nonempty U],
is_domain (X.presheaf.obj (op U)) . tactic.apply_instance)
attribute [instance] is_integral.component_integral is_integral.nonempty
instance [h : is_integral X] : is_domain (X.presheaf.obj (op ⊤)) :=
@@is_integral.component_integral _ _ (by simp)
@[priority 900]
instance is_reduced_of_is_integral [is_integral X] : is_reduced X :=
begin
constructor,
intro U,
cases U.1.eq_empty_or_nonempty,
{ have : U = ∅ := subtype.eq h,
haveI := CommRing.subsingleton_of_is_terminal (X.sheaf.is_terminal_of_eq_empty this),
change _root_.is_reduced (X.sheaf.val.obj (op U)),
apply_instance },
{ haveI : nonempty U := by simpa, apply_instance }
end
instance is_irreducible_of_is_integral [is_integral X] : irreducible_space X.carrier :=
begin
by_contradiction H,
replace H : ¬ is_preirreducible (⊤ : set X.carrier) := λ h,
H { to_preirreducible_space := ⟨h⟩, to_nonempty := infer_instance },
simp_rw [is_preirreducible_iff_closed_union_closed, not_forall, not_or_distrib] at H,
rcases H with ⟨S, T, hS, hT, h₁, h₂, h₃⟩,
erw not_forall at h₂ h₃,
simp_rw not_forall at h₂ h₃,
haveI : nonempty (⟨Sᶜ, hS.1⟩ : opens X.carrier) := ⟨⟨_, h₂.some_spec.some_spec⟩⟩,
haveI : nonempty (⟨Tᶜ, hT.1⟩ : opens X.carrier) := ⟨⟨_, h₃.some_spec.some_spec⟩⟩,
haveI : nonempty (⟨Sᶜ, hS.1⟩ ⊔ ⟨Tᶜ, hT.1⟩ : opens X.carrier) :=
⟨⟨_, or.inl h₂.some_spec.some_spec⟩⟩,
let e : X.presheaf.obj _ ≅ CommRing.of _ := (X.sheaf.is_product_of_disjoint ⟨_, hS.1⟩ ⟨_, hT.1⟩ _)
.cone_point_unique_up_to_iso (CommRing.prod_fan_is_limit _ _),
apply_with false_of_nontrivial_of_product_domain { instances := ff },
{ exact e.symm.CommRing_iso_to_ring_equiv.is_domain _ },
{ apply X.to_LocallyRingedSpace.component_nontrivial },
{ apply X.to_LocallyRingedSpace.component_nontrivial },
{ ext x,
split,
{ rintros ⟨hS,hT⟩,
cases h₁ (show x ∈ ⊤, by trivial),
exacts [hS h, hT h] },
{ intro x, exact x.rec _ } }
end
lemma is_integral_of_is_irreducible_is_reduced [is_reduced X] [H : irreducible_space X.carrier] :
is_integral X :=
begin
split, refine λ U hU, ⟨λ a b e, _,
(@@LocallyRingedSpace.component_nontrivial X.to_LocallyRingedSpace U hU).1⟩,
simp_rw [← basic_open_eq_bot_iff, ← opens.not_nonempty_iff_eq_bot],
by_contra' h,
obtain ⟨_, ⟨x, hx₁, rfl⟩, ⟨x, hx₂, e'⟩⟩ := @@nonempty_preirreducible_inter _ H.1
(X.basic_open a).2 (X.basic_open b).2
h.1 h.2,
replace e' := subtype.eq e',
subst e',
replace e := congr_arg (X.presheaf.germ x) e,
rw [ring_hom.map_mul, ring_hom.map_zero] at e,
refine @zero_ne_one (X.presheaf.stalk x.1) _ _ (is_unit_zero_iff.1 _),
convert hx₁.mul hx₂,
exact e.symm
end
lemma is_integral_iff_is_irreducible_and_is_reduced :
is_integral X ↔ irreducible_space X.carrier ∧ is_reduced X :=
⟨λ _, by exactI ⟨infer_instance, infer_instance⟩,
λ ⟨_, _⟩, by exactI is_integral_of_is_irreducible_is_reduced X⟩
lemma is_integral_of_open_immersion {X Y : Scheme} (f : X ⟶ Y) [H : is_open_immersion f]
[is_integral Y] [nonempty X.carrier] : is_integral X :=
begin
constructor,
intros U hU,
have : U = (opens.map f.1.base).obj (H.base_open.is_open_map.functor.obj U),
{ ext1, exact (set.preimage_image_eq _ H.base_open.inj).symm },
rw this,
haveI : is_domain (Y.presheaf.obj (op (H.base_open.is_open_map.functor.obj U))),
{ apply_with is_integral.component_integral { instances := ff },
apply_instance,
refine ⟨⟨_, _, hU.some.prop, rfl⟩⟩ },
exact (as_iso $ f.1.c.app (op $ H.base_open.is_open_map.functor.obj U) :
Y.presheaf.obj _ ≅ _).symm.CommRing_iso_to_ring_equiv.is_domain _
end
instance {R : CommRing} [H : is_domain R] : is_integral (Scheme.Spec.obj $ op R) :=
begin
apply_with is_integral_of_is_irreducible_is_reduced { instances := ff },
{ apply_instance },
{ dsimp [Spec.Top_obj],
apply_instance },
end
lemma affine_is_integral_iff (R : CommRing) :
is_integral (Scheme.Spec.obj $ op R) ↔ is_domain R :=
⟨λ h, by exactI ring_equiv.is_domain ((Scheme.Spec.obj $ op R).presheaf.obj _)
(as_iso $ to_Spec_Γ R).CommRing_iso_to_ring_equiv, λ h, by exactI infer_instance⟩
lemma is_integral_of_is_affine_is_domain [is_affine X] [nonempty X.carrier]
[h : is_domain (X.presheaf.obj (op ⊤))] : is_integral X :=
begin
haveI : is_integral (Scheme.Spec.obj (op (Scheme.Γ.obj (op X)))),
{ rw affine_is_integral_iff, exact h },
exact is_integral_of_open_immersion X.iso_Spec.hom,
end
lemma map_injective_of_is_integral [is_integral X] {U V : opens X.carrier} (i : U ⟶ V)
[H : nonempty U] :
function.injective (X.presheaf.map i.op) :=
begin
rw injective_iff_map_eq_zero,
intros x hx,
rw ← basic_open_eq_bot_iff at ⊢ hx,
rw Scheme.basic_open_res at hx,
revert hx,
contrapose!,
simp_rw [← opens.not_nonempty_iff_eq_bot, not_not],
apply nonempty_preirreducible_inter U.prop (RingedSpace.basic_open _ _).prop,
simpa using H
end
end algebraic_geometry
|
32ecf89e15c15266b105f9663aefad21a78347f2 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/Command.lean | 65a7836e58dcb43545248f75bb62c572e89b8e70 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 18,865 | 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.Parser.Command
import Lean.ResolveName
import Lean.Meta.Reduce
import Lean.Elab.Log
import Lean.Elab.Term
import Lean.Elab.Binders
import Lean.Elab.SyntheticMVars
import Lean.Elab.DeclModifiers
import Lean.Elab.InfoTree
import Lean.Elab.SetOption
namespace Lean.Elab.Command
structure Scope where
header : String
opts : Options := {}
currNamespace : Name := Name.anonymous
openDecls : List OpenDecl := []
levelNames : List Name := []
/-- section variables as `bracketedBinder`s -/
varDecls : Array Syntax := #[]
/-- Globally unique internal identifiers for the `varDecls` -/
varUIds : Array Name := #[]
/-- noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for. -/
isNoncomputable : Bool := false
deriving Inhabited
structure State where
env : Environment
messages : MessageLog := {}
scopes : List Scope := [{ header := "" }]
nextMacroScope : Nat := firstFrontendMacroScope + 1
maxRecDepth : Nat
nextInstIdx : Nat := 1 -- for generating anonymous instance names
ngen : NameGenerator := {}
infoState : InfoState := {}
traceState : TraceState := {}
deriving Inhabited
structure Context where
fileName : String
fileMap : FileMap
currRecDepth : Nat := 0
cmdPos : String.Pos := 0
macroStack : MacroStack := []
currMacroScope : MacroScope := firstFrontendMacroScope
ref : Syntax := Syntax.missing
abbrev CommandElabCoreM (ε) := ReaderT Context $ StateRefT State $ EIO ε
abbrev CommandElabM := CommandElabCoreM Exception
abbrev CommandElab := Syntax → CommandElabM Unit
abbrev Linter := Syntax → CommandElabM Unit
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad CommandElabM := let i := inferInstanceAs (Monad CommandElabM); { pure := i.pure, bind := i.bind }
def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := {
env := env
messages := messages
scopes := [{ header := "", opts := opts }]
maxRecDepth := maxRecDepth.get opts
}
/- Linters should be loadable as plugins, so store in a global IO ref instead of an attribute managed by the
environment (which only contains `import`ed objects). -/
builtin_initialize lintersRef : IO.Ref (Array Linter) ← IO.mkRef #[]
def addLinter (l : Linter) : IO Unit := do
let ls ← lintersRef.get
lintersRef.set (ls.push l)
instance : MonadInfoTree CommandElabM where
getInfoState := return (← get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
instance : MonadEnv CommandElabM where
getEnv := do pure (← get).env
modifyEnv f := modify fun s => { s with env := f s.env }
instance : MonadOptions CommandElabM where
getOptions := do pure (← get).scopes.head!.opts
protected def getRef : CommandElabM Syntax :=
return (← read).ref
instance : AddMessageContext CommandElabM where
addMessageContext := addMessageContextPartial
instance : MonadRef CommandElabM where
getRef := Command.getRef
withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x
instance : MonadTrace CommandElabM where
getTraceState := return (← get).traceState
modifyTraceState f := modify fun s => { s with traceState := f s.traceState }
instance : AddErrorMessageContext CommandElabM where
add ref msg := do
let ctx ← read
let ref := getBetterRef ref ctx.macroStack
let msg ← addMessageContext msg
let msg ← addMacroStack msg ctx.macroStack
return (ref, msg)
def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message :=
mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos?.getD ctx.cmdPos)
private def mkCoreContext (ctx : Context) (s : State) (heartbeats : Nat) : Core.Context :=
let scope := s.scopes.head!
{ options := scope.opts
currRecDepth := ctx.currRecDepth
maxRecDepth := s.maxRecDepth
ref := ctx.ref
currNamespace := scope.currNamespace
openDecls := scope.openDecls
initHeartbeats := heartbeats }
def liftCoreM {α} (x : CoreM α) : CommandElabM α := do
let s ← get
let ctx ← read
let heartbeats ← IO.getNumHeartbeats
let Eα := Except Exception α
let x : CoreM Eα := try let a ← x; pure <| Except.ok a catch ex => pure <| Except.error ex
let x : EIO Exception (Eα × Core.State) := (ReaderT.run x (mkCoreContext ctx s heartbeats)).run { env := s.env, ngen := s.ngen, traceState := s.traceState }
let (ea, coreS) ← liftM x
modify fun s => { s with env := coreS.env, ngen := coreS.ngen, traceState := coreS.traceState }
match ea with
| Except.ok a => pure a
| Except.error e => throw e
private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message :=
let ref := getBetterRef ref ctx.macroStack
mkMessageAux ctx ref (toString err) MessageSeverity.error
@[inline] def liftEIO {α} (x : EIO Exception α) : CommandElabM α := liftM x
@[inline] def liftIO {α} (x : IO α) : CommandElabM α := do
let ctx ← read
IO.toEIO (fun (ex : IO.Error) => Exception.error ctx.ref ex.toString) x
instance : MonadLiftT IO CommandElabM where
monadLift := liftIO
def getScope : CommandElabM Scope := do pure (← get).scopes.head!
instance : MonadResolveName CommandElabM where
getCurrNamespace := return (← getScope).currNamespace
getOpenDecls := return (← getScope).openDecls
instance : MonadLog CommandElabM where
getRef := getRef
getFileMap := return (← read).fileMap
getFileName := return (← read).fileName
logMessage msg := do
let currNamespace ← getCurrNamespace
let openDecls ← getOpenDecls
let msg := { msg with data := MessageData.withNamingContext { currNamespace := currNamespace, openDecls := openDecls } msg.data }
modify fun s => { s with messages := s.messages.add msg }
def runLinters (stx : Syntax) : CommandElabM Unit := do
let linters ← lintersRef.get
unless linters.isEmpty do
for linter in linters do
let savedState ← get
try
linter stx
catch ex =>
logException ex
finally
modify fun s => { savedState with messages := s.messages }
protected def getCurrMacroScope : CommandElabM Nat := do pure (← read).currMacroScope
protected def getMainModule : CommandElabM Name := do pure (← getEnv).mainModule
protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do
let fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation CommandElabM where
getCurrMacroScope := Command.getCurrMacroScope
getMainModule := Command.getMainModule
withFreshMacroScope := Command.withFreshMacroScope
unsafe def mkCommandElabAttributeUnsafe : IO (KeyedDeclsAttribute CommandElab) :=
mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command"
@[implementedBy mkCommandElabAttributeUnsafe]
constant mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab)
builtin_initialize commandElabAttribute : KeyedDeclsAttribute CommandElab ← mkCommandElabAttribute
private def addTraceAsMessagesCore (ctx : Context) (log : MessageLog) (traceState : TraceState) : MessageLog :=
traceState.traces.foldl (init := log) fun (log : MessageLog) traceElem =>
let ref := replaceRef traceElem.ref ctx.ref;
let pos := ref.getPos?.getD 0;
log.add (mkMessageCore ctx.fileName ctx.fileMap traceElem.msg MessageSeverity.information pos)
private def addTraceAsMessages : CommandElabM Unit := do
let ctx ← read
modify fun s => { s with
messages := addTraceAsMessagesCore ctx s.messages s.traceState
traceState.traces := {}
}
private def mkInfoTree (elaborator : Name) (stx : Syntax) (trees : Std.PersistentArray InfoTree) : CommandElabM InfoTree := do
let ctx ← read
let s ← get
let scope := s.scopes.head!
let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees
return InfoTree.context {
env := s.env, fileMap := ctx.fileMap, mctx := {}, currNamespace := scope.currNamespace, openDecls := scope.openDecls, options := scope.opts
} tree
private def elabCommandUsing (s : State) (stx : Syntax) : List (KeyedDeclsAttribute.AttributeEntry CommandElab) → CommandElabM Unit
| [] => withInfoTreeContext (mkInfoTree := mkInfoTree `no_elab stx) <| throwError "unexpected syntax{indentD stx}"
| (elabFn::elabFns) =>
catchInternalId unsupportedSyntaxExceptionId
(withInfoTreeContext (mkInfoTree := mkInfoTree elabFn.declName stx) <| elabFn.value stx)
(fun _ => do set s; elabCommandUsing s stx elabFns)
/- Elaborate `x` with `stx` on the macro stack -/
def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α :=
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
instance : MonadMacroAdapter CommandElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (← get).nextMacroScope
setNextMacroScope next := modify fun s => { s with nextMacroScope := next }
instance : MonadRecDepth CommandElabM where
withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x
getRecDepth := return (← read).currRecDepth
getMaxRecDepth := return (← get).maxRecDepth
register_builtin_option showPartialSyntaxErrors : Bool := {
defValue := false
descr := "show elaboration errors from partial syntax trees (i.e. after parser recovery)"
}
def withLogging (x : CommandElabM Unit) : CommandElabM Unit := do
try
x
catch ex => match ex with
| Exception.error _ _ => logException ex
| Exception.internal id _ =>
if isAbortExceptionId id then
pure ()
else
let idName ← liftIO <| id.getName;
logError m!"internal exception {idName}"
builtin_initialize registerTraceClass `Elab.command
partial def elabCommand (stx : Syntax) : CommandElabM Unit := do
withLogging <| withRef stx <| withIncRecDepth <| withFreshMacroScope do
match stx with
| Syntax.node _ k args =>
if k == nullKind then
-- list of commands => elaborate in order
-- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones
args.forM elabCommand
else do
trace `Elab.command fun _ => stx;
let s ← get
match (← liftMacroM <| expandMacroImpl? s.env stx) with
| some (decl, stxNew?) =>
withInfoTreeContext (mkInfoTree := mkInfoTree decl stx) do
let stxNew ← liftMacroM <| liftExcept stxNew?
withMacroExpansion stx stxNew do
elabCommand stxNew
| _ =>
match commandElabAttribute.getEntries s.env k with
| [] =>
withInfoTreeContext (mkInfoTree := mkInfoTree `no_elab stx) <|
throwError "elaboration function for '{k}' has not been implemented"
| elabFns => elabCommandUsing s stx elabFns
| _ => throwError "unexpected command"
/--
`elabCommand` wrapper that should be used for the initial invocation, not for recursive calls after
macro expansion etc.
-/
def elabCommandTopLevel (stx : Syntax) : CommandElabM Unit := withRef stx do
let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} })
let initInfoTrees ← getResetInfoTrees
withLogging do
runLinters stx
-- We should *not* factor out `elabCommand`'s `withLogging` to here since it would make its error
-- recovery more coarse. In particular, If `c` in `set_option ... in $c` fails, the remaining
-- `end` command of the `in` macro would be skipped and the option would be leaked to the outside!
elabCommand stx
-- note the order: first process current messages & info trees, then add back old messages & trees,
-- then convert new traces to messages
let mut msgs ← (← get).messages
-- `stx.hasMissing` should imply `initMsgs.hasErrors`, but the latter should be cheaper to check in general
if !showPartialSyntaxErrors.get (← getOptions) && initMsgs.hasErrors && stx.hasMissing then
-- discard elaboration errors, except for a few important and unlikely misleading ones, on parse error
msgs := ⟨msgs.msgs.filter fun msg =>
msg.data.hasTag (fun tag => tag == `Elab.synthPlaceholder || tag == `Tactic.unsolvedGoals || (`_traceMsg).isSuffixOf tag)⟩
for tree in (← getInfoTrees) do
trace[Elab.info] (← tree.format)
modify fun st => { st with
messages := initMsgs ++ msgs
infoState := { st.infoState with trees := initInfoTrees ++ st.infoState.trees }
}
addTraceAsMessages
/-- Adapt a syntax transformation to a regular, command-producing elaborator. -/
def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do
let stx' ← exp stx
withMacroExpansion stx stx' <| elabCommand stx'
private def getVarDecls (s : State) : Array Syntax :=
s.scopes.head!.varDecls
instance {α} : Inhabited (CommandElabM α) where
default := throw arbitrary
private def mkMetaContext : Meta.Context := {
config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true }
}
def getBracketedBinderIds : Syntax → Array Name
| `(bracketedBinder|($ids* $[: $ty?]? $(annot?)?)) => ids.map Syntax.getId
| `(bracketedBinder|{$ids* $[: $ty?]?}) => ids.map Syntax.getId
| `(bracketedBinder|[$id : $ty]) => #[id.getId]
| `(bracketedBinder|[$ty]) => #[Name.anonymous]
| _ => #[]
private def mkTermContext (ctx : Context) (s : State) (declName? : Option Name) : Term.Context := Id.run <| do
let scope := s.scopes.head!
let mut sectionVars := {}
for id in scope.varDecls.concatMap getBracketedBinderIds, uid in scope.varUIds do
sectionVars := sectionVars.insert id uid
{ macroStack := ctx.macroStack
fileName := ctx.fileName
fileMap := ctx.fileMap
currMacroScope := ctx.currMacroScope
declName? := declName?
sectionVars := sectionVars
isNoncomputableSection := scope.isNoncomputable }
private def mkTermState (scope : Scope) (s : State) : Term.State := {
messages := {}
levelNames := scope.levelNames
infoState.enabled := s.infoState.enabled
}
def liftTermElabM {α} (declName? : Option Name) (x : TermElabM α) : CommandElabM α := do
let ctx ← read
let s ← get
let heartbeats ← IO.getNumHeartbeats
-- dbg_trace "heartbeats: {heartbeats}"
let scope := s.scopes.head!
-- We execute `x` with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands.
-- This is useful for implementing `runTermElabM` where we use `Term.resetMessageLog`
let x : TermElabM _ := withSaveInfoContext x
let x : MetaM _ := (observing x).run (mkTermContext ctx s declName?) (mkTermState scope s)
let x : CoreM _ := x.run mkMetaContext {}
let x : EIO _ _ := x.run (mkCoreContext ctx s heartbeats) { env := s.env, ngen := s.ngen, nextMacroScope := s.nextMacroScope }
let (((ea, termS), metaS), coreS) ← liftEIO x
modify fun s => { s with
env := coreS.env
messages := addTraceAsMessagesCore ctx (s.messages ++ termS.messages) coreS.traceState
nextMacroScope := coreS.nextMacroScope
ngen := coreS.ngen
infoState.trees := s.infoState.trees.append termS.infoState.trees
}
match ea with
| Except.ok a => pure a
| Except.error ex => throw ex
@[inline] def runTermElabM {α} (declName? : Option Name) (elabFn : Array Expr → TermElabM α) : CommandElabM α := do
let scope ← getScope
liftTermElabM declName? <|
Term.withAutoBoundImplicit <|
Term.elabBinders scope.varDecls fun xs => do
-- We need to synthesize postponed terms because this is a checkpoint for the auto-bound implicit feature
-- If we don't use this checkpoint here, then auto-bound implicits in the postponed terms will not be handled correctly.
Term.synthesizeSyntheticMVarsNoPostponing
let mut sectionFVars := {}
for uid in scope.varUIds, x in xs do
sectionFVars := sectionFVars.insert uid x
withReader ({ · with sectionFVars := sectionFVars }) do
-- We don't want to store messages produced when elaborating `(getVarDecls s)` because they have already been saved when we elaborated the `variable`(s) command.
-- So, we use `Term.resetMessageLog`.
Term.resetMessageLog
let xs ← Term.addAutoBoundImplicits xs
Term.withoutAutoBoundImplicit <| elabFn xs
@[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx ref =>
EIO.catchExceptions (withLogging x ctx ref) (fun _ => pure ())
private def liftAttrM {α} (x : AttrM α) : CommandElabM α := do
liftCoreM x
def getScopes : CommandElabM (List Scope) := do
pure (← get).scopes
def modifyScope (f : Scope → Scope) : CommandElabM Unit :=
modify fun s => { s with
scopes := match s.scopes with
| h::t => f h :: t
| [] => unreachable!
}
def withScope (f : Scope → Scope) (x : CommandElabM α) : CommandElabM α := do
match (← get).scopes with
| [] => x
| h :: t =>
try
modify fun s => { s with scopes := f h :: t }
x
finally
modify fun s => { s with scopes := h :: t }
def getLevelNames : CommandElabM (List Name) :=
return (← getScope).levelNames
def addUnivLevel (idStx : Syntax) : CommandElabM Unit := withRef idStx do
let id := idStx.getId
let levelNames ← getLevelNames
if levelNames.elem id then
throwAlreadyDeclaredUniverseLevel id
else
modifyScope fun scope => { scope with levelNames := id :: scope.levelNames }
def expandDeclId (declId : Syntax) (modifiers : Modifiers) : CommandElabM ExpandDeclIdResult := do
let currNamespace ← getCurrNamespace
let currLevelNames ← getLevelNames
Lean.Elab.expandDeclId currNamespace currLevelNames declId modifiers
end Elab.Command
export Elab.Command (Linter addLinter)
end Lean
|
bc428498f145c26244487bf025caa7c02f0a3f35 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/combinatorics/pigeonhole.lean | 29224d8e4cf2b8a304878bd8d91aa38f3b17515f | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 18,908 | lean | /-
Copyright (c) 2020 Kyle Miller. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller, Yury Kudryashov
-/
import data.fintype.basic
import algebra.big_operators.order
/-!
# Pigeonhole principles
Given pigeons (possibly infinitely many) in pigeonholes, the
pigeonhole principle states that, if there are more pigeons than
pigeonholes, then there is a pigeonhole with two or more pigeons.
There are a few variations on this statement, and the conclusion can
be made stronger depending on how many pigeons you know you might
have.
The basic statements of the pigeonhole principle appear in the
following locations:
* `data.finset.basic` has `finset.exists_ne_map_eq_of_card_lt_of_maps_to`
* `data.fintype.basic` has `fintype.exists_ne_map_eq_of_card_lt`
* `data.fintype.basic` has `fintype.exists_ne_map_eq_of_infinite`
* `data.fintype.basic` has `fintype.exists_infinite_fiber`
This module gives access to these pigeonhole principles along with 20 more.
The versions vary by:
* using a function between `fintype`s or a function between possibly infinite types restricted to
`finset`s;
* counting pigeons by a general weight function (`∑ x in s, w x`) or by heads (`finset.card s`);
* using strict or non-strict inequalities;
* establishing upper or lower estimate on the number (or the total weight) of the pigeons in one
pigeonhole;
* in case when we count pigeons by some weight function `w` and consider a function `f` between
`finset`s `s` and `t`, we can either assume that each pigeon is in one of the pigeonholes
(`∀ x ∈ s, f x ∈ t`), or assume that for `y ∉ t`, the total weight of the pigeons in this
pigeonhole `∑ x in s.filter (λ x, f x = y), w x` is nonpositive or nonnegative depending on
the inequality we are proving.
Lemma names follow `mathlib` convention (e.g.,
`finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`); "pigeonhole principle" is mentioned in the
docstrings instead of the names.
## See also
* `ordinal.infinite_pigeonhole`: pigeonhole principle for cardinals, formulated using cofinality;
* `measure_theory.exists_nonempty_inter_of_measure_univ_lt_tsum_measure`,
`measure_theory.exists_nonempty_inter_of_measure_univ_lt_sum_measure`: pigeonhole principle in a
measure space.
## Tags
pigeonhole principle
-/
universes u v w
variables {α : Type u} {β : Type v} {M : Type w} [linear_ordered_cancel_add_comm_monoid M]
[decidable_eq β]
open_locale big_operators
namespace finset
variables {s : finset α} {t : finset β} {f : α → β} {w : α → M} {b : M} {n : ℕ}
/-!
### The pigeonhole principles on `finset`s, pigeons counted by weight
In this section we prove the following version of the pigeonhole principle: if the total weight of a
finite set of pigeons is greater than `n •ℕ b`, and they are sorted into `n` pigeonholes, then for
some pigeonhole, the total weight of the pigeons in this pigeonhole is greateer than `b`, and a few
variations of this theorem.
The principle is formalized in the following way, see
`finset.exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum`: if `f : α → β` is a function which maps all
elements of `s : finset α` to `t : finset β` and `card t •ℕ b < ∑ x in s, w x`, where `w : α → M` is
a weight function taking values in a `linear_ordered_cancel_add_comm_monoid`, then for
some `y ∈ t`, the sum of the weights of all `x ∈ s` such that `f x = y` is greater than `b`.
There are a few bits we can change in this theorem:
* reverse all inequalities, with obvious adjustments to the name;
* replace the assumption `∀ a ∈ s, f a ∈ t` with `∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0`,
and replace `of_maps_to` with `of_sum_fiber_nonpos` in the name;
* use non-strict inequalities assuming `t` is nonempty.
We can do all these variations independently, so we have eight versions of the theorem.
-/
/-!
#### Strict inequality versions
-/
/-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version:
if the total weight of a finite set of pigeons is greater than `n •ℕ b`, and they are sorted into
`n` pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is
greater than `b`. -/
lemma exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (hf : ∀ a ∈ s, f a ∈ t)
(hb : t.card •ℕ b < ∑ x in s, w x) :
∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x :=
exists_lt_of_sum_lt $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const]
/-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version:
if the total weight of a finite set of pigeons is less than `n •ℕ b`, and they are sorted into `n`
pigeonholes, then for some pigeonhole, the total weight of the pigeons in this pigeonhole is less
than `b`. -/
lemma exists_sum_fiber_lt_of_maps_to_of_sum_lt_nsmul (hf : ∀ a ∈ s, f a ∈ t)
(hb : (∑ x in s, w x) < t.card •ℕ b) :
∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b :=
@exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ hf hb
/-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version:
if the total weight of a finite set of pigeons is greater than `n •ℕ b`, they are sorted into some
pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonpositive,
then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole
is greater than `b`. -/
lemma exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum
(ht : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (hb : t.card •ℕ b < ∑ x in s, w x) :
∃ y ∈ t, b < ∑ x in s.filter (λ x, f x = y), w x :=
exists_lt_of_sum_lt $
calc (∑ y in t, b) < ∑ x in s, w x : by simpa
... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x :
sum_le_sum_fiberwise_of_sum_fiber_nonpos ht
/-- The pigeonhole principle for finitely many pigeons counted by weight, strict inequality version:
if the total weight of a finite set of pigeons is less than `n •ℕ b`, they are sorted into some
pigeonholes, and for all but `n` pigeonholes the total weight of the pigeons there is nonnegative,
then for at least one of these `n` pigeonholes, the total weight of the pigeons in this pigeonhole
is less than `b`. -/
lemma exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul
(ht : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (hb : (∑ x in s, w x) < t.card •ℕ b) :
∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) < b :=
@exists_lt_sum_fiber_of_sum_fiber_nonpos_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ _ _ ht hb
/-!
#### Non-strict inequality versions
-/
/-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality
version: if the total weight of a finite set of pigeons is greater than or equal to `n •ℕ b`, and
they are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons
in this pigeonhole is greater than or equal to `b`. -/
lemma exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty)
(hb : t.card •ℕ b ≤ ∑ x in s, w x) :
∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x :=
exists_le_of_sum_le ht $ by simpa only [sum_fiberwise_of_maps_to hf, sum_const]
/-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality
version: if the total weight of a finite set of pigeons is less than or equal to `n •ℕ b`, and they
are sorted into `n > 0` pigeonholes, then for some pigeonhole, the total weight of the pigeons in
this pigeonhole is less than or equal to `b`. -/
lemma exists_sum_fiber_le_of_maps_to_of_sum_le_nsmul (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty)
(hb : (∑ x in s, w x) ≤ t.card •ℕ b) :
∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b :=
@exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb
/-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality
version: if the total weight of a finite set of pigeons is greater than or equal to `n •ℕ b`, they
are sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the
pigeons there is nonpositive, then for at least one of these `n` pigeonholes, the total weight of
the pigeons in this pigeonhole is greater than or equal to `b`. -/
lemma exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum
(hf : ∀ y ∉ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ 0) (ht : t.nonempty)
(hb : t.card •ℕ b ≤ ∑ x in s, w x) :
∃ y ∈ t, b ≤ ∑ x in s.filter (λ x, f x = y), w x :=
exists_le_of_sum_le ht $
calc (∑ y in t, b) ≤ ∑ x in s, w x : by simpa
... ≤ ∑ y in t, ∑ x in s.filter (λ x, f x = y), w x :
sum_le_sum_fiberwise_of_sum_fiber_nonpos hf
/-- The pigeonhole principle for finitely many pigeons counted by weight, non-strict inequality
version: if the total weight of a finite set of pigeons is less than or equal to `n •ℕ b`, they are
sorted into some pigeonholes, and for all but `n > 0` pigeonholes the total weight of the pigeons
there is nonnegative, then for at least one of these `n` pigeonholes, the total weight of the
pigeons in this pigeonhole is less than or equal to `b`. -/
lemma exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul
(hf : ∀ y ∉ t, (0:M) ≤ ∑ x in s.filter (λ x, f x = y), w x) (ht : t.nonempty)
(hb : (∑ x in s, w x) ≤ t.card •ℕ b) :
∃ y ∈ t, (∑ x in s.filter (λ x, f x = y), w x) ≤ b :=
@exists_le_sum_fiber_of_sum_fiber_nonpos_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ _ _ hf ht hb
/-!
### The pigeonhole principles on `finset`s, pigeons counted by heads
In this section we formalize a few versions of the following pigeonhole principle: there is a
pigeonhole with at least as many pigeons as the ceiling of the average number of pigeons across all
pigeonholes.
First, we can use strict or non-strict inequalities. While the versions with non-strict inequalities
are weaker than those with strict inequalities, sometimes it might be more convenient to apply the
weaker version. Second, we can either state that there exists a pigeonhole with at least `n`
pigeons, or state that there exists a pigeonhole with at most `n` pigeons. In the latter case we do
not need the assumption `∀ a ∈ s, f a ∈ t`.
So, we prove four theorems: `finset.exists_lt_card_fiber_of_maps_to_of_mul_lt_card`,
`finset.exists_le_card_fiber_of_maps_to_of_mul_le_card`,
`finset.exists_card_fiber_lt_of_card_lt_mul`, and `finset.exists_card_fiber_le_of_card_le_mul`. -/
/-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with
at least as many pigeons as the ceiling of the average number of pigeons across all pigeonholes.
("The maximum is at least the mean" specialized to integers.)
More formally, given a function between finite sets `s` and `t` and a natural number `n` such that
`card t * n < card s`, there exists `y ∈ t` such that its preimage in `s` has more than `n`
elements. -/
lemma exists_lt_card_fiber_of_mul_lt_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t)
(hn : t.card * n < s.card) :
∃ y ∈ t, n < (s.filter (λ x, f x = y)).card :=
begin
simp only [card_eq_sum_ones],
apply exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum hf,
simpa
end
/-- The pigeonhole principle for finitely many pigeons counted by heads: there is a pigeonhole with
at most as many pigeons as the floor of the average number of pigeons across all pigeonholes. ("The
minimum is at most the mean" specialized to integers.)
More formally, given a function `f`, a finite sets `s` in its domain, a finite set `t` in its
codomain, and a natural number `n` such that `card s < card t * n`, there exists `y ∈ t` such that
its preimage in `s` has less than `n` elements. -/
lemma exists_card_fiber_lt_of_card_lt_mul (hn : s.card < t.card * n) :
∃ y ∈ t, (s.filter (λ x, f x = y)).card < n:=
begin
simp only [card_eq_sum_ones],
apply exists_sum_fiber_lt_of_sum_fiber_nonneg_of_sum_lt_nsmul (λ _ _, nat.zero_le _),
simpa
end
/-- The pigeonhole principle for finitely many pigeons counted by heads: given a function between
finite sets `s` and `t` and a natural number `n` such that `card t * n ≤ card s`, there exists `y ∈
t` such that its preimage in `s` has at least `n` elements. See also
`finset.exists_lt_card_fiber_of_mul_lt_card_of_maps_to` for a stronger statement. -/
lemma exists_le_card_fiber_of_mul_le_card_of_maps_to (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty)
(hn : t.card * n ≤ s.card) :
∃ y ∈ t, n ≤ (s.filter (λ x, f x = y)).card :=
begin
simp only [card_eq_sum_ones],
apply exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum hf ht,
simpa
end
/-- The pigeonhole principle for finitely many pigeons counted by heads: given a function `f`, a
finite sets `s` in its domain, a finite set `t` in its codomain, and a natural number `n` such that
`card s ≤ card t * n`, there exists `y ∈ t` such that its preimage in `s` has no more than `n`
elements. See also `finset.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/
lemma exists_card_fiber_le_of_card_le_mul (ht : t.nonempty) (hn : s.card ≤ t.card * n) :
∃ y ∈ t, (s.filter (λ x, f x = y)).card ≤ n:=
begin
simp only [card_eq_sum_ones],
apply exists_sum_fiber_le_of_sum_fiber_nonneg_of_sum_le_nsmul (λ _ _, nat.zero_le _) ht,
simpa
end
end finset
namespace fintype
open finset
variables [fintype α] [fintype β] (f : α → β) {w : α → M} {b : M} {n : ℕ}
/-!
### The pigeonhole principles on `fintypes`s, pigeons counted by weight
In this section we specialize theorems from the previous section to the special case of functions
between `fintype`s and `s = univ`, `t = univ`. In this case the assumption `∀ x ∈ s, f x ∈ t` always
holds, so we have four theorems instead of eight. -/
/-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality
version: there is a pigeonhole with the total weight of pigeons in it greater than `b` provided that
the total number of pigeonholes times `b` is less than the total weight of all pigeons. -/
lemma exists_lt_sum_fiber_of_nsmul_lt_sum (hb : card β •ℕ b < ∑ x, w x) :
∃ y, b < ∑ x in univ.filter (λ x, f x = y), w x :=
let ⟨y, _, hy⟩ := exists_lt_sum_fiber_of_maps_to_of_nsmul_lt_sum (λ _ _, mem_univ _) hb in ⟨y, hy⟩
/-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality
version: there is a pigeonhole with the total weight of pigeons in it greater than or equal to `b`
provided that the total number of pigeonholes times `b` is less than or equal to the total weight of
all pigeons. -/
lemma exists_le_sum_fiber_of_nsmul_le_sum [nonempty β] (hb : card β •ℕ b ≤ ∑ x, w x) :
∃ y, b ≤ ∑ x in univ.filter (λ x, f x = y), w x :=
let ⟨y, _, hy⟩ :=
exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum (λ _ _, mem_univ _) univ_nonempty hb
in ⟨y, hy⟩
/-- The pigeonhole principle for finitely many pigeons of different weights, strict inequality
version: there is a pigeonhole with the total weight of pigeons in it less than `b` provided that
the total number of pigeonholes times `b` is greater than the total weight of all pigeons. -/
lemma exists_sum_fiber_lt_of_sum_lt_nsmul (hb : (∑ x, w x) < card β •ℕ b) :
∃ y, (∑ x in univ.filter (λ x, f x = y), w x) < b :=
@exists_lt_sum_fiber_of_nsmul_lt_sum α β (order_dual M) _ _ _ _ _ w b hb
/-- The pigeonhole principle for finitely many pigeons of different weights, non-strict inequality
version: there is a pigeonhole with the total weight of pigeons in it less than or equal to `b`
provided that the total number of pigeonholes times `b` is greater than or equal to the total weight
of all pigeons. -/
lemma exists_sum_fiber_le_of_sum_le_nsmul [nonempty β] (hb : (∑ x, w x) ≤ card β •ℕ b) :
∃ y, (∑ x in univ.filter (λ x, f x = y), w x) ≤ b :=
@exists_le_sum_fiber_of_nsmul_le_sum α β (order_dual M) _ _ _ _ _ w b _ hb
/--
The strong pigeonhole principle for finitely many pigeons and pigeonholes.
There is a pigeonhole with at least as many pigeons as
the ceiling of the average number of pigeons across all pigeonholes.
("The maximum is at least the mean" specialized to integers.)
More formally, given a function `f` between finite types `α` and `β` and a number `n` such that
`card β * n < card α`, there exists an element `y : β` such that its preimage has more than `n`
elements. -/
lemma exists_lt_card_fiber_of_mul_lt_card (hn : card β * n < card α) :
∃ y : β, n < (univ.filter (λ x, f x = y)).card :=
let ⟨y, _, h⟩ := exists_lt_card_fiber_of_mul_lt_card_of_maps_to (λ _ _, mem_univ _) hn in ⟨y, h⟩
/--
The strong pigeonhole principle for finitely many pigeons and pigeonholes.
There is a pigeonhole with at most as many pigeons as
the floor of the average number of pigeons across all pigeonholes.
("The minimum is at most the mean" specialized to integers.)
More formally, given a function `f` between finite types `α` and `β` and a number `n` such that
`card α < card β * n`, there exists an element `y : β` such that its preimage has less than `n`
elements. -/
lemma exists_card_fiber_lt_of_card_lt_mul (hn : card α < card β * n) :
∃ y : β, (univ.filter (λ x, f x = y)).card < n :=
let ⟨y, _, h⟩ := exists_card_fiber_lt_of_card_lt_mul hn in ⟨y, h⟩
/-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f`
between finite types `α` and `β` and a number `n` such that `card β * n ≤ card α`, there exists an
element `y : β` such that its preimage has at least `n` elements. See also
`fintype.exists_lt_card_fiber_of_mul_lt_card` for a stronger statement. -/
lemma exists_le_card_fiber_of_mul_le_card [nonempty β] (hn : card β * n ≤ card α) :
∃ y : β, n ≤ (univ.filter (λ x, f x = y)).card :=
let ⟨y, _, h⟩ := exists_le_card_fiber_of_mul_le_card_of_maps_to (λ _ _, mem_univ _) univ_nonempty hn
in ⟨y, h⟩
/-- The strong pigeonhole principle for finitely many pigeons and pigeonholes. Given a function `f`
between finite types `α` and `β` and a number `n` such that `card α ≤ card β * n`, there exists an
element `y : β` such that its preimage has at most `n` elements. See also
`fintype.exists_card_fiber_lt_of_card_lt_mul` for a stronger statement. -/
lemma exists_card_fiber_le_of_card_le_mul [nonempty β] (hn : card α ≤ card β * n) :
∃ y : β, (univ.filter (λ x, f x = y)).card ≤ n :=
let ⟨y, _, h⟩ := exists_card_fiber_le_of_card_le_mul univ_nonempty hn in ⟨y, h⟩
end fintype
|
c0ded0052afc716ebd44a4cd17a41bf0bd38a2d8 | fa01e273a2a9f22530e6adb1ed7d4f54bb15c8d7 | /src/N2O/Data/Parser.lean | 82bd99070c8d2f3a37cc67f418d88401708436f3 | [
"LicenseRef-scancode-mit-taylor-variant",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | o89/n2o | 4c99afb11fff0a1e3dae6b3bc8a3b7fc42c314ac | 58c1fbf4ef892ed86bdc6b78ec9ca5a403715c2d | refs/heads/master | 1,670,314,676,229 | 1,669,086,375,000 | 1,669,086,375,000 | 200,506,953 | 16 | 6 | null | null | null | null | UTF-8 | Lean | false | false | 6,733 | lean | -- data.buffer.parser from Lean 3 stdlib
import N2O.Data.Bytes
import N2O.Data.Vector
inductive ParseResult (α : Type)
| done (pos : Nat) (result : α) : ParseResult α
| fail (pos : Nat) (msg : List String) : ParseResult α
class BuiltFrom (Γ : Type) (π : Type) :=
(size {} : Γ → Nat)
(eq {} : π → π → Bool)
(get {} : Γ → Nat → π)
(escape {} : π → String)
def Parser (Γ π : Type) [BuiltFrom Γ π] (α : Type) :=
∀ (input : Γ) (start : Nat), ParseResult α
instance : BuiltFrom ByteArray UInt8 :=
{ size := ByteArray.size,
eq := BEq.beq,
get := ByteArray.get!,
escape := toString }
abbrev ByteParser := Parser ByteArray UInt8
def ByteParser.ch : ByteParser Char :=
λ input pos =>
if pos < input.size then
let ch := UInt32.ofNat (input.get! pos).toNat;
if h : isValidChar ch then ParseResult.done (pos + 1) (Char.mk ch h)
else ParseResult.fail pos [ "<valid char>" ]
else ParseResult.fail pos [ "<char>" ]
namespace Parser
variable {Γ : Type} {π : Type} [BuiltFrom Γ π] {α β : Type}
protected def bind (p : Parser Γ π α) (f : α → Parser Γ π β) : Parser Γ π β :=
λ input pos => match p input pos with
| ParseResult.done pos a => f a input pos
| ParseResult.fail pos msg => ParseResult.fail pos msg
protected def pure (a : α) : Parser Γ π α :=
λ input pos => ParseResult.done pos a
protected def fail (msg : String) : Parser Γ π α :=
λ _ pos => ParseResult.fail pos [ msg ]
instance : Monad (Parser Γ π) :=
{ pure := @Parser.pure Γ π _,
bind := @Parser.bind Γ π _ }
protected def failure : Parser Γ π α :=
λ _ pos => ParseResult.fail pos []
protected def orElse (p : Parser Γ π α) (q : Unit → Parser Γ π α) : Parser Γ π α :=
λ input pos => match p input pos with
| ParseResult.fail pos₁ msg₁ =>
if pos₁ ≠ pos then ParseResult.fail pos₁ msg₁
else match q () input pos with
| ParseResult.fail pos₂ msg₂ =>
if pos₁ < pos₂ then ParseResult.fail pos₁ msg₁
else if pos₂ < pos₁ then ParseResult.fail pos₂ msg₂
else ParseResult.fail pos₁ (msg₁ ++ msg₂)
| ok => ok
| ok => ok
instance : Alternative (Parser Γ π) :=
{ failure := @Parser.failure Γ π _,
orElse := @Parser.orElse Γ π _ }
instance : Inhabited (Parser Γ π α) := ⟨failure⟩
def decorateErrors (msgs : List String) (p : Parser Γ π α) : Parser Γ π α :=
λ input pos => match p input pos with
| ParseResult.fail _ _ => ParseResult.fail pos msgs
| ok => ok
def decorateError (msg : String) : Parser Γ π α → Parser Γ π α :=
decorateErrors [ msg ]
def foldrCore (f : α → β → β) (p : Parser Γ π α) (b : β) : Nat → Parser Γ π β
| 0 => failure
| reps + 1 => (do let x ← p; let xs ← foldrCore f p b reps; pure (f x xs)) <|> pure b
def foldr (f : α → β → β) (p : Parser Γ π α) (b : β) : Parser Γ π β :=
λ input pos => foldrCore f p b (BuiltFrom.size π input - pos + 1) input pos
def eps : Parser Γ π Unit := pure ()
def many (p : Parser Γ π α) : Parser Γ π (List α) :=
foldr List.cons p []
def many1 (p : Parser Γ π α) : Parser Γ π (List α) :=
List.cons <$> p <*> many p
def fixCore (F : Parser Γ π α → Parser Γ π α) : Nat → Parser Γ π α
| 0 => failure
| maxDepth + 1 => F (fixCore F maxDepth)
def fix (F : Parser Γ π α → Parser Γ π α) : Parser Γ π α :=
λ input pos => fixCore F (BuiltFrom.size π input - pos + 1) input pos
def sat (p : π → Bool) : Parser Γ π π :=
λ input pos =>
if pos < BuiltFrom.size π input then
let c : π := BuiltFrom.get π input pos;
if p c then ParseResult.done (pos + 1) c
else ParseResult.fail pos []
else ParseResult.fail pos []
def byte : Parser Γ π π := sat (λ _ => true)
def count (p : Parser Γ π α) : ∀ n, Parser Γ π (Vector α n)
| 0 => pure Vector.nil
| n + 1 => Vector.cons <$> p <*> count p n
partial def countLength (p : Parser Γ π (α × Nat)) : Nat → Parser Γ π (List α)
| 0 => pure []
| m => do let (x, n) ← p; let xs ← countLength p (m - n); pure (x :: xs)
def tok (b : π) : Parser Γ π Unit :=
decorateError (BuiltFrom.escape Γ b) $
do sat (BuiltFrom.eq Γ b) >>= λ _ => eps
def remaining : Parser Γ π Nat :=
λ input pos => ParseResult.done pos (BuiltFrom.size π input - pos)
def eof : Parser Γ π Unit :=
decorateError "<end-of-file>" $
do let rem ← remaining; guard (rem = 0)
def run (p : Parser Γ π α) (input : Γ) : Sum String α :=
match (p <* eof) input 0 with
| ParseResult.done pos res => Sum.inr res
| ParseResult.fail pos msg =>
Sum.inl ("expected: " ++ String.intercalate "or " msg)
end Parser
def Prod.rev {α β : Type} (y : β) (x : α) : α × β := (x, y)
namespace ByteParser.utf8
def isHelpful (x : UInt8) : Bool := x.shiftRight 6 = 0b10
def isFirst (x : UInt8) : Bool := x.shiftRight 7 = 0
def isSecond (x : UInt8) : Bool := x.shiftRight 5 = 0b110
def isThird (x : UInt8) : Bool := x.shiftRight 4 = 0b1110
def isFourth (x : UInt8) : Bool := x.shiftRight 3 = 0b11110
def parseValidChar (x : UInt32) : ByteParser Char :=
if h : isValidChar x then pure (Char.mk x h)
else Parser.fail "invalid character"
def readFirst : ByteParser (Char × Nat) := Parser.decorateError "<1>" $ do
let a ← Parser.byte; guard (isFirst a); Prod.rev 1 <$> parseValidChar a.toUInt32
def readSecond : ByteParser (Char × Nat) := Parser.decorateError "<2>" $ do
let a ← Parser.byte; let b ← Parser.byte;
guard (isSecond a); guard (isHelpful b);
Prod.rev 2 <$> (parseValidChar $
(a.toUInt32.land 0b00011111).shiftLeft 6 +
b.toUInt32.land 0b00111111)
def readThird : ByteParser (Char × Nat) := Parser.decorateError "<3>" $ do
let a ← Parser.byte; let b ← Parser.byte; let c ← Parser.byte;
guard (isThird a); guard (isHelpful b); guard (isHelpful c);
Prod.rev 3 <$> (parseValidChar $
(a.toUInt32.land 0b00001111).shiftLeft 12 +
(b.toUInt32.land 0b00111111).shiftLeft 6 +
c.toUInt32.land 0b00111111 )
def readFourth : ByteParser (Char × Nat) := Parser.decorateError "<4>" $ do
let a ← Parser.byte; let b ← Parser.byte; let c ← Parser.byte; let d ← Parser.byte;
guard (isFourth a); guard (isHelpful b);
guard (isHelpful c); guard (isHelpful d);
Prod.rev 4 <$> (parseValidChar $
(a.toUInt32.land 0b00000111).shiftLeft 18 +
(b.toUInt32.land 0b00111111).shiftLeft 12 +
(c.toUInt32.land 0b00111111).shiftLeft 6 +
d.toUInt32.land 0b00111111)
def uchr := readFirst <|> readSecond <|> readThird <|> readFourth
def stringWithLength (s : Nat) : ByteParser String :=
String.mk <$> Parser.countLength uchr s
end ByteParser.utf8
|
97965337416d0d35a92e960422db3e3d79c5e0ed | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/data/nat/pairing.lean | 369a753f251bce3652430692c9a4783629e1a1e0 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,597 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.nat.pairing
Authors: Leonardo de Moura
Elegant pairing function.
-/
import data.nat.sqrt data.nat.div
open prod decidable
namespace nat
definition mkpair (a b : nat) : nat :=
if a < b then b*b + a else a*a + a + b
definition unpair (n : nat) : nat × nat :=
let s := sqrt n in
if n - s*s < s then (n - s*s, s) else (s, n - s*s - s)
theorem mkpair_unpair (n : nat) : mkpair (pr1 (unpair n)) (pr2 (unpair n)) = n :=
let s := sqrt n in
by_cases
(λ h₁ : n - s*s < s,
begin
esimp [unpair],
rewrite [if_pos h₁],
esimp [mkpair],
rewrite [if_pos h₁, add_sub_of_le (sqrt_lower n)]
end)
(λ h₂ : ¬ n - s*s < s,
have g₁ : s ≤ n - s*s, from le_of_not_lt h₂,
assert g₂ : s + s*s ≤ n - s*s + s*s, from add_le_add_right g₁ (s*s),
assert g₃ : s*s + s ≤ n, by rewrite [sub_add_cancel (sqrt_lower n) at g₂, add.comm at g₂]; exact g₂,
have l₁ : n ≤ s*s + s + s, from sqrt_upper n,
have l₂ : n - s*s ≤ s + s, from calc
n - s*s ≤ (s*s + s + s) - s*s : sub_le_sub_right l₁ (s*s)
... = (s*s + (s+s)) - s*s : by rewrite add.assoc
... = s + s : by rewrite add_sub_cancel_left,
have l₃ : n - s*s - s ≤ s, from calc
n - s*s - s ≤ (s + s) - s : sub_le_sub_right l₂ s
... = s : by rewrite add_sub_cancel_left,
assert l₄ : ¬ s < n - s*s - s, from not_lt_of_le l₃,
begin
esimp [unpair],
rewrite [if_neg h₂], esimp,
esimp [mkpair],
rewrite [if_neg l₄, sub_sub, add_sub_of_le g₃],
end)
theorem unpair_mkpair (a b : nat) : unpair (mkpair a b) = (a, b) :=
by_cases
(λ h : a < b,
assert aux₁ : a ≤ b + b, from calc
a ≤ b : le_of_lt h
... ≤ b+b : !le_add_right,
begin
esimp [mkpair],
rewrite [if_pos h],
esimp [unpair],
rewrite [sqrt_offset_eq aux₁, add_sub_cancel_left, if_pos h]
end)
(λ h : ¬ a < b,
have h₁ : b ≤ a, from le_of_not_lt h,
assert aux₁ : a + b ≤ a + a, from add_le_add_left h₁ a,
have aux₂ : a + b ≥ a, from !le_add_right,
assert aux₃ : ¬ a + b < a, from not_lt_of_le aux₂,
begin
esimp [mkpair],
rewrite [if_neg h],
esimp [unpair],
rewrite [add.assoc (a * a) a b, sqrt_offset_eq aux₁, *add_sub_cancel_left, if_neg aux₃]
end)
end nat
|
f4d5d31f5242825d2bb9b84c2b9e5148e197dc00 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /src/Init/WF.lean | 83f92195116471de107d507679d1d553c108cbfc | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,191 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.SizeOf
import Init.Data.Nat.Basic
universes u v
set_option codegen false
inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop where
| intro (x : α) (h : (y : α) → r y x → Acc r y) : Acc r x
abbrev Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1}
(m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x)
{a : α} (n : Acc r a) : C a :=
Acc.rec (motive := fun α _ => C α) m n
abbrev Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1}
{a : α} (n : Acc r a)
(m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x)
: C a :=
Acc.rec (motive := fun α _ => C α) m n
namespace Acc
variable {α : Sort u} {r : α → α → Prop}
def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y :=
Acc.recOn (motive := fun (x : α) _ => r y x → Acc r y)
h₁ (fun x₁ ac₁ ih h₂ => ac₁ y h₂) h₂
end Acc
inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop where
| intro (h : ∀ a, Acc r a) : WellFounded r
class WellFoundedRelation (α : Sort u) : Type u where
r : α → α → Prop
wf : WellFounded r
namespace WellFounded
def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) (a : α) : Acc r a :=
WellFounded.recOn (motive := fun x => (y : α) → Acc r y)
wf (fun p => p) a
section
variable {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r)
theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := by
induction (apply hwf a) with
| intro x₁ ac₁ ih => exact h x₁ ih
theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a :=
recursion hwf a h
variable {C : α → Sort v}
variable (F : ∀ x, (∀ y, r y x → C y) → C x)
def fixF (x : α) (a : Acc r x) : C x := by
induction a with
| intro x₁ ac₁ ih => exact F x₁ ih
def fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := by
induction acx with
| intro x r ih => exact rfl
end
variable {α : Sort u} {C : α → Sort v} {r : α → α → Prop}
-- Well-founded fixpoint
def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x :=
fixF F x (apply hwf x)
-- Well-founded fixpoint satisfies fixpoint equation
theorem fixEq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) :
fix hwf F x = F x (fun y h => fix hwf F y) :=
fixFEq F x (apply hwf x)
end WellFounded
open WellFounded
-- Empty relation is well-founded
def emptyWf {α : Sort u} : WellFounded (@emptyRelation α) := by
apply WellFounded.intro
intro a
apply Acc.intro a
intro b h
cases h
-- Subrelation of a well-founded relation is well-founded
namespace Subrelation
variable {α : Sort u} {r q : α → α → Prop}
def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := by
induction ac with
| intro x ax ih =>
apply Acc.intro
intro y h
exact ih y (h₁ h)
def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q :=
⟨fun a => accessible @h₁ (apply h₂ a)⟩
end Subrelation
-- The inverse image of a well-founded relation is well-founded
namespace InvImage
variable {α : Sort u} {β : Sort v} {r : β → β → Prop}
private def accAux (f : α → β) {b : β} (ac : Acc r b) : (x : α) → f x = b → Acc (InvImage r f) x := by
induction ac with
| intro x acx ih =>
intro z e
apply Acc.intro
intro y lt
subst x
apply ih (f y) lt y rfl
def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a :=
accAux f ac a rfl
def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) :=
⟨fun a => accessible f (apply h (f a))⟩
end InvImage
-- The transitive closure of a well-founded relation is well-founded
namespace TC
variable {α : Sort u} {r : α → α → Prop}
def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := by
induction ac with
| intro x acx ih =>
apply Acc.intro x
intro y rel
induction rel generalizing acx ih with
| base a b rab => exact ih a rab
| trans a b c rab rbc ih₁ ih₂ => apply Acc.inv (ih₂ acx ih) rab
def wf (h : WellFounded r) : WellFounded (TC r) :=
⟨fun a => accessible (apply h a)⟩
end TC
-- less-than is well-founded
def Nat.ltWf : WellFounded Nat.lt := by
apply WellFounded.intro
intro n
induction n with
| zero =>
apply Acc.intro 0
intro _ h
apply absurd h (Nat.notLtZero _)
| succ n ih =>
apply Acc.intro (Nat.succ n)
intro m h
have m = n ∨ m < n from Nat.eqOrLtOfLe (Nat.leOfSuccLeSucc h)
match this with
| Or.inl e => subst e; assumption
| Or.inr e => exact Acc.inv ih e
def measure {α : Sort u} : (α → Nat) → α → α → Prop :=
InvImage (fun a b => a < b)
def measureWf {α : Sort u} (f : α → Nat) : WellFounded (measure f) :=
InvImage.wf f Nat.ltWf
def sizeofMeasure (α : Sort u) [SizeOf α] : α → α → Prop :=
measure sizeOf
def sizeofMeasureWf (α : Sort u) [SizeOf α] : WellFounded (sizeofMeasure α) :=
measureWf sizeOf
instance hasWellFoundedOfSizeOf (α : Sort u) [SizeOf α] : WellFoundedRelation α where
r := sizeofMeasure α
wf := sizeofMeasureWf α
namespace Prod
open WellFounded
section
variable {α : Type u} {β : Type v}
variable (ra : α → α → Prop)
variable (rb : β → β → Prop)
-- Lexicographical order based on ra and rb
inductive Lex : α × β → α × β → Prop where
| left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂)
| right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂)
-- relational product based on ra and rb
inductive Rprod : α × β → α × β → Prop where
| intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : Rprod (a₁, b₁) (a₂, b₂)
end
section
variable {α : Type u} {β : Type v}
variable {ra : α → α → Prop} {rb : β → β → Prop}
def lexAccessible (aca : (a : α) → Acc ra a) (acb : (b : β) → Acc rb b) (a : α) (b : β) : Acc (Lex ra rb) (a, b) := by
induction (aca a) generalizing b with
| intro xa aca iha =>
induction (acb b) with
| intro xb acb ihb =>
apply Acc.intro (xa, xb)
intro p lt
cases lt with
| left _ _ h => apply iha _ h
| right _ h => apply ihb _ h
-- The lexicographical order of well founded relations is well-founded
def lexWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Lex ra rb) :=
⟨fun (a, b) => lexAccessible (WellFounded.apply ha) (WellFounded.apply hb) a b⟩
-- relational product is a Subrelation of the Lex
def rprodSubLex (a : α × β) (b : α × β) (h : Rprod ra rb a b) : Lex ra rb a b := by
cases h with
| intro h₁ h₂ => exact Lex.left _ _ h₁
-- The relational product of well founded relations is well-founded
def rprodWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Rprod ra rb) := by
apply Subrelation.wf (r := Lex ra rb) (h₂ := lexWf ha hb)
intro a b h
exact rprodSubLex a b h
end
instance {α : Type u} {β : Type v} [s₁ : WellFoundedRelation α] [s₂ : WellFoundedRelation β] : WellFoundedRelation (α × β) where
r := Lex s₁.r s₂.r
wf := lexWf s₁.wf s₂.wf
end Prod
namespace PSigma
section
variable {α : Sort u} {β : α → Sort v}
variable (r : α → α → Prop)
variable (s : ∀ a, β a → β a → Prop)
-- Lexicographical order based on r and s
inductive Lex : PSigma β → PSigma β → Prop where
| left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
| right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩
end
section
variable {α : Sort u} {β : α → Sort v}
variable {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop}
def lexAccessible {a} (aca : Acc r a) (acb : (a : α) → WellFounded (s a)) (b : β a) : Acc (Lex r s) ⟨a, b⟩ := by
induction aca generalizing b with
| intro xa aca iha =>
induction (WellFounded.apply (acb xa) b) with
| intro xb acb ihb =>
apply Acc.intro
intro p lt
cases lt with
| left => apply iha; assumption
| right => apply ihb; assumption
-- The lexicographical order of well founded relations is well-founded
def lexWf (ha : WellFounded r) (hb : (x : α) → WellFounded (s x)) : WellFounded (Lex r s) :=
WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b
end
section
variable {α : Sort u} {β : Sort v}
def lexNdep (r : α → α → Prop) (s : β → β → Prop) :=
Lex r (fun a => s)
def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) :=
WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun x => hb) b
end
section
variable {α : Sort u} {β : Sort v}
-- Reverse lexicographical order based on r and s
inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop where
| left : {a₁ a₂ : α} → (b : β) → r a₁ a₂ → RevLex r s ⟨a₁, b⟩ ⟨a₂, b⟩
| right : (a₁ : α) → {b₁ : β} → (a₂ : α) → {b₂ : β} → s b₁ b₂ → RevLex r s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩
end
section
open WellFounded
variable {α : Sort u} {β : Sort v}
variable {r : α → α → Prop} {s : β → β → Prop}
def revLexAccessible {b} (acb : Acc s b) (aca : (a : α) → Acc r a): (a : α) → Acc (RevLex r s) ⟨a, b⟩ := by
induction acb with
| intro xb acb ihb =>
intro a
induction (aca a) with
| intro xa aca iha =>
apply Acc.intro
intro p lt
cases lt with
| left => apply iha; assumption
| right => apply ihb; assumption
def revLexWf (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) :=
WellFounded.intro fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a
end
section
def skipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop :=
RevLex emptyRelation s
def skipLeftWf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : WellFounded s) : WellFounded (skipLeft α s) :=
revLexWf emptyWf hb
def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : skipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ :=
RevLex.right _ _ h
end
instance WellFoundedRelation {α : Type u} {β : α → Type v} [s₁ : WellFoundedRelation α] [s₂ : ∀ a, WellFoundedRelation (β a)] : WellFoundedRelation (PSigma β) where
r := Lex s₁.r (fun a => (s₂ a).r)
wf := lexWf s₁.wf (fun a => (s₂ a).wf)
end PSigma
|
98084ce82874c39258b463dea740989b64742ee7 | 05b503addd423dd68145d68b8cde5cd595d74365 | /src/category_theory/differential_object.lean | 6a158f2a56672d1f01343359362bc4f7f82dcd61 | [
"Apache-2.0"
] | permissive | aestriplex/mathlib | 77513ff2b176d74a3bec114f33b519069788811d | e2fa8b2b1b732d7c25119229e3cdfba8370cb00f | refs/heads/master | 1,621,969,960,692 | 1,586,279,279,000 | 1,586,279,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,632 | 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.limits.shapes.zero
import category_theory.shift
/-!
# Differential objects in a category.
A differential object in a category with zero morphisms and a shift is
an object `X` equipped with
a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`.
We build the category of differential objects, and some basic constructions
such as the forgetful functor, and zero morphisms and zero objects.
-/
open category_theory.limits
universes v u
namespace category_theory
variables (C : Type u) [𝒞 : category.{v} C]
include 𝒞
variables [has_zero_morphisms.{v} C] [has_shift.{v} C]
/--
A differential object in a category with zero morphisms and a shift is
an object `X` equipped with
a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`.
-/
@[nolint has_inhabited_instance]
structure differential_object :=
(X : C)
(d : X ⟶ X⟦1⟧)
(d_squared' : d ≫ d⟦1⟧' = 0 . obviously)
restate_axiom differential_object.d_squared'
attribute [simp] differential_object.d_squared
variables {C}
namespace differential_object
/--
A morphism of differential objects is a morphism commuting with the differentials.
-/
@[ext, nolint has_inhabited_instance]
structure hom (X Y : differential_object.{v} C) :=
(f : X.X ⟶ Y.X)
(comm' : X.d ≫ f⟦1⟧' = f ≫ Y.d . obviously)
restate_axiom hom.comm'
attribute [simp, reassoc] hom.comm
namespace hom
/-- The identity morphism of a differential object. -/
@[simps]
def id (X : differential_object.{v} C) : hom X X :=
{ f := 𝟙 X.X }
/-- The composition of morphisms of differential objects. -/
@[simps]
def comp {X Y Z : differential_object.{v} C} (f : hom X Y) (g : hom Y Z) : hom X Z :=
{ f := f.f ≫ g.f, }
end hom
instance category_of_differential_objects : category.{v} (differential_object.{v} C) :=
{ hom := hom,
id := hom.id,
comp := λ X Y Z f g, hom.comp f g, }
@[simp]
lemma id_f (X : differential_object.{v} C) : ((𝟙 X) : X ⟶ X).f = 𝟙 (X.X) := rfl
@[simp]
lemma comp_f {X Y Z : differential_object.{v} C} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g).f = f.f ≫ g.f :=
rfl
variables (C)
/-- The forgetful functor taking a differential object to its underlying object. -/
def forget : (differential_object.{v} C) ⥤ C :=
{ obj := λ X, X.X,
map := λ X Y f, f.f, }
instance forget_faithful : faithful (forget C) :=
{ }
instance has_zero_morphisms : has_zero_morphisms.{v} (differential_object.{v} C) :=
{ has_zero := λ X Y,
⟨{ f := 0, }⟩}
end differential_object
end category_theory
namespace category_theory
namespace differential_object
variables (C : Type u) [𝒞 : category.{v} C]
include 𝒞
variables [has_zero_object.{v} C] [has_zero_morphisms.{v} C] [has_shift.{v} C]
local attribute [instance] has_zero_object.has_zero
instance has_zero_object : has_zero_object.{v} (differential_object.{v} C) :=
{ zero :=
{ X := (0 : C),
d := 0, },
unique_to := λ X, ⟨⟨{ f := 0 }⟩, λ f, (by ext)⟩,
unique_from := λ X, ⟨⟨{ f := 0 }⟩, λ f, (by ext)⟩, }
end differential_object
namespace differential_object
variables (C : Type (u+1)) [large_category C] [𝒞 : concrete_category C]
[has_zero_morphisms.{u} C] [has_shift.{u} C]
include 𝒞
instance concrete_category_of_differential_objects :
concrete_category (differential_object.{u} C) :=
{ forget := forget C ⋙ category_theory.forget C }
instance : has_forget₂ (differential_object.{u} C) C :=
{ forget₂ := forget C }
end differential_object
end category_theory
|
2445b963a719c2cb3e7c664d04836a7637fab25a | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/slim_check.lean | 652cd3b4319ba4c26b93d22e63b0e4aac4eb2c15 | [
"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 | 8,202 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import testing.slim_check.testable
import testing.slim_check.functions
import data.list.sort
/-!
## Finding counterexamples automatically using `slim_check`
A proposition can be tested by writing it out as:
```lean
example (xs : list ℕ) (w : ∃ x ∈ xs, x < 3) : ∀ y ∈ xs, y < 5 := by slim_check
-- ===================
-- Found problems!
-- xs := [0, 5]
-- x := 0
-- y := 5
-- -------------------
example (x : ℕ) (h : 2 ∣ x) : x < 100 := by slim_check
-- ===================
-- Found problems!
-- x := 258
-- -------------------
example (α : Type) (xs ys : list α) : xs ++ ys = ys ++ xs := by slim_check
-- ===================
-- Found problems!
-- α := ℤ
-- xs := [-4]
-- ys := [1]
-- -------------------
example : ∀ x ∈ [1,2,3], x < 4 := by slim_check
-- Success
```
In the first example, `slim_check` is called on the following goal:
```lean
xs : list ℕ,
h : ∃ (x : ℕ) (H : x ∈ xs), x < 3
⊢ ∀ (y : ℕ), y ∈ xs → y < 5
```
The local constants are reverted and an instance is found for
`testable (∀ (xs : list ℕ), (∃ x ∈ xs, x < 3) → (∀ y ∈ xs, y < 5))`.
The `testable` instance is supported by instances of `sampleable (list ℕ)`,
`decidable (x < 3)` and `decidable (y < 5)`. `slim_check` builds a
`testable` instance step by step with:
```
- testable (∀ (xs : list ℕ), (∃ x ∈ xs, x < 3) → (∀ y ∈ xs, y < 5))
-: sampleable (list xs)
- testable ((∃ x ∈ xs, x < 3) → (∀ y ∈ xs, y < 5))
- testable (∀ x ∈ xs, x < 3 → (∀ y ∈ xs, y < 5))
- testable (x < 3 → (∀ y ∈ xs, y < 5))
-: decidable (x < 3)
- testable (∀ y ∈ xs, y < 5)
-: decidable (y < 5)
```
`sampleable (list ℕ)` lets us create random data of type `list ℕ` in a way that
helps find small counter-examples. Next, the test of the proposition
hinges on `x < 3` and `y < 5` to both be decidable. The
implication between the two could be tested as a whole but it would be
less informative. Indeed, if we generate lists that only contain numbers
greater than `3`, the implication will always trivially hold but we should
conclude that we haven't found meaningful examples. Instead, when `x < 3`
does not hold, we reject the example (i.e. we do not count it toward
the 100 required positive examples) and we start over. Therefore, when
`slim_check` prints `Success`, it means that a hundred suitable lists
were found and successfully tested.
If no counter-examples are found, `slim_check` behaves like `admit`.
`slim_check` can also be invoked using `#eval`:
```lean
#eval slim_check.testable.check (∀ (α : Type) (xs ys : list α), xs ++ ys = ys ++ xs)
-- ===================
-- Found problems!
-- α := ℤ
-- xs := [-4]
-- ys := [1]
-- -------------------
```
For more information on writing your own `sampleable` and `testable`
instances, see `testing.slim_check.testable`.
-/
namespace tactic.interactive
open tactic slim_check
declare_trace slim_check.instance
declare_trace slim_check.decoration
declare_trace slim_check.discarded
declare_trace slim_check.success
declare_trace slim_check.shrink.steps
declare_trace slim_check.shrink.candidates .
open expr
/-- Tree structure representing a `testable` instance. -/
meta inductive instance_tree
| node : name → expr → list instance_tree → instance_tree
/-- Gather information about a `testable` instance. Given
an expression of type `testable ?p`, gather the
name of the `testable` instances that it is built from
and the proposition that they test. -/
meta def summarize_instance : expr → tactic instance_tree
| (lam n bi d b) := do
v ← mk_local' n bi d,
summarize_instance $ b.instantiate_var v
| e@(app f x) := do
`(testable %%p) ← infer_type e,
xs ← e.get_app_args.mmap_filter (try_core ∘ summarize_instance),
pure $ instance_tree.node e.get_app_fn.const_name p xs
| e := do
failed
/-- format a `instance_tree` -/
meta def instance_tree.to_format : instance_tree → tactic format
| (instance_tree.node n p xs) := do
xs ← format.join <$> (xs.mmap $ λ t, flip format.indent 2 <$> instance_tree.to_format t),
ys ← pformat!"testable ({p})",
pformat!"+ {n} :{format.indent ys 2}\n{xs}"
meta instance instance_tree.has_to_tactic_format : has_to_tactic_format instance_tree :=
⟨ instance_tree.to_format ⟩
/--
`slim_check` considers a proof goal and tries to generate examples
that would contradict the statement.
Let's consider the following proof goal.
```lean
xs : list ℕ,
h : ∃ (x : ℕ) (H : x ∈ xs), x < 3
⊢ ∀ (y : ℕ), y ∈ xs → y < 5
```
The local constants will be reverted and an instance will be found for
`testable (∀ (xs : list ℕ), (∃ x ∈ xs, x < 3) → (∀ y ∈ xs, y < 5))`.
The `testable` instance is supported by an instance of `sampleable (list ℕ)`,
`decidable (x < 3)` and `decidable (y < 5)`.
Examples will be created in ascending order of size (more or less)
The first counter-examples found will be printed and will result in an error:
```
===================
Found problems!
xs := [1, 28]
x := 1
y := 28
-------------------
```
If `slim_check` successfully tests 100 examples, it acts like
admit. If it gives up or finds a counter-example, it reports an error.
For more information on writing your own `sampleable` and `testable`
instances, see `testing.slim_check.testable`.
Optional arguments given with `slim_check_cfg`
* num_inst (default 100): number of examples to test properties with
* max_size (default 100): final size argument
* enable_tracing (default ff): enable the printing of discarded samples
Options:
* `set_option trace.slim_check.decoration true`: print the proposition with quantifier annotations
* `set_option trace.slim_check.discarded true`: print the examples discarded because they do not satisfy assumptions
* `set_option trace.slim_check.shrink.steps true`: trace the shrinking of counter-example
* `set_option trace.slim_check.shrink.candidates true`: print the lists of candidates considered when shrinking each variable
* `set_option trace.slim_check.instance true`: print the instances of `testable` being used to test the proposition
* `set_option trace.slim_check.success true`: print the tested samples that satisfy a property
-/
meta def slim_check (cfg : slim_check_cfg := {}) : tactic unit := do
{ tgt ← retrieve $ tactic.revert_all >> target,
let tgt' := tactic.add_decorations tgt,
let cfg := { cfg with
trace_discarded := cfg.trace_discarded || is_trace_enabled_for `slim_check.discarded,
trace_shrink := cfg.trace_shrink || is_trace_enabled_for `slim_check.shrink.steps,
trace_shrink_candidates := cfg.trace_shrink_candidates || is_trace_enabled_for `slim_check.shrink.candidates,
trace_success := cfg.trace_success || is_trace_enabled_for `slim_check.success },
inst ← mk_app ``testable [tgt'] >>= mk_instance <|>
fail!"Failed to create a `testable` instance for `{tgt}`.
What to do:
1. make sure that the types you are using have `slim_check.sampleable` instances (you can use `#sample my_type` if you are unsure);
2. make sure that the relations and predicates that your proposition use are decidable;
3. make sure that instances of `slim_check.testable` exist that, when combined, apply to your decorated proposition:
```
{tgt'}
```
Use `set_option trace.class_instances true` to understand what instances are missing.
Try this:
set_option trace.class_instances true
#check (by apply_instance : slim_check.testable ({tgt'}))",
e ← mk_mapp ``testable.check [tgt, `(cfg), tgt', inst],
when_tracing `slim_check.decoration trace!"[testable decoration]\n {tgt'}",
when_tracing `slim_check.instance $ do
{ inst ← summarize_instance inst >>= pp,
trace!"\n[testable instance]{format.indent inst 2}" },
code ← eval_expr (io punit) e,
unsafe_run_io code,
admit }
end tactic.interactive
|
e5256f3566f6ddb7135e7d179289acb3ee485af8 | b3fced0f3ff82d577384fe81653e47df68bb2fa1 | /test/lint.lean | 4b58ee0be51ea062afac96dbfe28f8ac9e6d8eea | [
"Apache-2.0"
] | permissive | ratmice/mathlib | 93b251ef5df08b6fd55074650ff47fdcc41a4c75 | 3a948a6a4cd5968d60e15ed914b1ad2f4423af8d | refs/heads/master | 1,599,240,104,318 | 1,572,981,183,000 | 1,572,981,183,000 | 219,830,178 | 0 | 0 | Apache-2.0 | 1,572,980,897,000 | 1,572,980,896,000 | null | UTF-8 | Lean | false | false | 2,211 | lean | import tactic.lint
def foo1 (n m : ℕ) : ℕ := n + 1
def foo2 (n m : ℕ) : m = m := by refl
lemma foo3 (n m : ℕ) : ℕ := n - m
lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n
instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances
-- section
-- local attribute [instance, priority 1001] classical.prop_decidable
-- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl)
-- end
open tactic
run_cmd do
let t := name × list ℕ,
e ← get_env,
l ← e.mfilter (λ d, return $
e.in_current_file' d.to_name && ¬ d.to_name.is_internal && ¬ d.is_auto_generated e),
l2 ← fold_over_with_cond l (return ∘ check_unused_arguments),
guard $ l2.length = 3,
let l2 : list t := l2.map $ λ x, ⟨x.1.to_name, x.2⟩,
guard $ (⟨`foo1, [2]⟩ : t) ∈ l2,
guard $ (⟨`foo2, [1]⟩ : t) ∈ l2,
guard $ (⟨`foo.foo, [2]⟩ : t) ∈ l2,
l2 ← fold_over_with_cond l incorrect_def_lemma,
guard $ l2.length = 2,
let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩,
guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2,
guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3,
l3 ← fold_over_with_cond l dup_namespace,
guard $ l3.length = 1,
guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo,
l4 ← fold_over_with_cond l illegal_constants_in_statement,
guard $ l4.length = 1,
guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo,
-- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4,
s ← lint ff,
guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string,
s2 ← lint tt,
guard $ s.to_string ≠ s2.to_string,
skip
/- check customizability and nolint -/
@[nolint] def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl)
meta def dummy_check (d : declaration) : tactic (option string) :=
return $ if d.to_name.last = "foo" then some "gotcha!" else none
meta def linter.dummy_linter : linter :=
{ test := dummy_check,
no_errors_found := "found nothing",
errors_found := "found something" }
run_cmd do
s ← lint tt tt [`linter.dummy_linter] tt,
guard $ "/- found something: -/\n#print foo.foo /- gotcha! -/\n\n".is_suffix_of s.to_string
|
8928b063e2e25433eba4ce219a8052413d58f59b | 2a70b774d16dbdf5a533432ee0ebab6838df0948 | /_target/deps/mathlib/src/topology/algebra/infinite_sum.lean | 46948cea4be7deda55b45b3c56d16a927da6dfb5 | [
"Apache-2.0"
] | permissive | hjvromen/lewis | 40b035973df7c77ebf927afab7878c76d05ff758 | 105b675f73630f028ad5d890897a51b3c1146fb0 | refs/heads/master | 1,677,944,636,343 | 1,676,555,301,000 | 1,676,555,301,000 | 327,553,599 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 42,747 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.big_operators.intervals
import topology.instances.real
import topology.algebra.module
import data.indicator_function
import data.equiv.encodable.lattice
import order.filter.at_top_bot
/-!
# Infinite sum over a topological monoid
This sum is known as unconditionally convergent, as it sums to the same value under all possible
permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute
convergence.
Note: There are summable sequences which are not unconditionally convergent! The other way holds
generally, see `has_sum.tendsto_sum_nat`.
## References
* Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups)
-/
noncomputable theory
open finset filter function classical
open_locale topological_space classical big_operators nnreal
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
section has_sum
variables [add_comm_monoid α] [topological_space α]
/-- Infinite sum on a topological monoid
The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum
up bigger and bigger sets. This sum operation is invariant under reordering. In particular,
the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a
sum for this definition, but a series which is absolutely convergent will have the correct sum.
This is based on Mario Carneiro's
[infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html).
For the definition or many statements, `α` does not need to be a topological monoid. We only add
this assumption later, for the lemmas where it is relevant.
-/
def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a)
/-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/
def summable (f : β → α) : Prop := ∃a, has_sum f a
/-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/
@[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0
notation `∑'` binders `, ` r:(scoped f, tsum f) := r
variables {f g : β → α} {a b : α} {s : finset β}
lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) :=
by simp [ha, tsum]; exact some_spec ha
lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩
/-- Constant zero function has sum `0` -/
lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 :=
by simp [has_sum, tendsto_const_nhds]
lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable
lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : (∑'b, f b) = 0 :=
by simp [tsum, h]
lemma has_sum.has_sum_of_sum_eq {g : γ → α}
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b)
(hf : has_sum g a) :
has_sum f a :=
le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf
lemma has_sum_iff_has_sum {g : γ → α}
(h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b)
(h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) :
has_sum f a ↔ has_sum g a :=
⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩
lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g)
(hf : ∀ x ∉ set.range g, f x = 0) :
has_sum (f ∘ g) a ↔ has_sum f a :=
by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf]
lemma function.injective.summable_iff {g : γ → β} (hg : injective g)
(hf : ∀ x ∉ set.range g, f x = 0) :
summable (f ∘ g) ↔ summable f :=
exists_congr $ λ _, hg.has_sum_iff hf
lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) :
has_sum (f ∘ coe : s → α) a ↔ has_sum f a :=
subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf
lemma has_sum_subtype_iff_indicator {s : set β} :
has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a :=
by rw [← set.indicator_range_comp, subtype.range_coe,
has_sum_subtype_iff_of_support_subset set.support_indicator]
@[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a :=
has_sum_subtype_iff_of_support_subset $ set.subset.refl _
lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) :=
order_top.tendsto_at_top_nhds _
protected lemma finset.has_sum (s : finset β) (f : β → α) :
has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) :=
by { rw ← sum_attach, exact has_sum_fintype _ }
protected lemma finset.summable (s : finset β) (f : β → α) :
summable (f ∘ coe : (↑s : set β) → α) :=
(s.has_sum f).summable
protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) :
summable (f ∘ coe : s → α) :=
by convert hs.to_finset.summable f; simp only [hs.coe_to_finset]
/-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/
lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) :=
(has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f
lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f :=
(has_sum_sum_of_ne_finset_zero hf).summable
lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
has_sum f (f b) :=
suffices has_sum f (∑ b' in {b}, f b'),
by simpa using this,
has_sum_sum_of_ne_finset_zero $ by simpa [hf]
lemma has_sum_ite_eq (b : β) (a : α) : has_sum (λb', if b' = b then a else 0) a :=
begin
convert has_sum_single b _,
{ exact (if_pos rfl).symm },
assume b' hb',
exact if_neg hb'
end
lemma equiv.has_sum_iff (e : γ ≃ β) :
has_sum (f ∘ e) a ↔ has_sum f a :=
e.injective.has_sum_iff $ by simp
lemma equiv.summable_iff (e : γ ≃ β) :
summable (f ∘ e) ↔ summable f :=
exists_congr $ λ a, e.has_sum_iff
lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) :=
(equiv.prod_comm γ β).summable_iff.2 hf
lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g)
(he : ∀ x : support f, g (e x) = f x) :
has_sum f a ↔ has_sum g a :=
have (g ∘ coe) ∘ e = f ∘ coe, from funext he,
by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support]
lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β)
(hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y)
(hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) :
has_sum f a ↔ has_sum g a :=
iff.symm $ equiv.has_sum_iff_of_support
(equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩)
⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h,
λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩)
hfg
lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g)
(he : ∀ x : support f, g (e x) = f x) :
summable f ↔ summable g :=
exists_congr $ λ _, e.has_sum_iff_of_support he
protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a)
(g : α →+ γ) (hg : continuous g) :
has_sum (g ∘ f) (g a) :=
have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)),
from funext $ g.map_sum _,
show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)),
from this ▸ (hg.tendsto a).comp hf
protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f)
(g : α →+ γ) (hg : continuous g) :
summable (g ∘ f) :=
(hf.has_sum.map g hg).summable
/-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/
lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) :
tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
h.comp tendsto_finset_range
lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ :=
tendsto_nhds_unique
lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) :
has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) :=
begin
refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩,
rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat,
exact hf.has_sum
end
lemma equiv.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α']
[topological_space α'] (e : α' ≃ α) {f : β → α} {g : γ → α'}
(he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) :
summable f ↔ summable g :=
⟨λ ⟨a, ha⟩, ⟨e.symm a, he.1 $ by rwa [e.apply_symm_apply]⟩, λ ⟨a, ha⟩, ⟨e a, he.2 ha⟩⟩
variable [has_continuous_add α]
lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) :=
by simp only [has_sum, sum_add_distrib]; exact hf.add hg
lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) :=
(hf.has_sum.add hg.has_sum).summable
lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} :
(∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) :=
finset.induction_on s (by simp [has_sum_zero]) (by simp [has_sum.add] {contextual := tt})
lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) :
summable (λb, ∑ i in s, f i b) :=
(has_sum_sum $ assume i hi, (hf i hi).has_sum).summable
lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a)
(hb : has_sum (f ∘ coe : sᶜ → α) b) :
has_sum f (a + b) :=
by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb)
lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α))
(hsc : summable (f ∘ coe : sᶜ → α)) :
summable f :=
(hs.has_sum.add_compl hsc.has_sum).summable
lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a)
(hb : has_sum (f ∘ coe : s → α) b) :
has_sum f (a + b) :=
by simpa using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb)
lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α))
(hsc : summable (f ∘ coe : s → α)) :
summable f :=
(hs.has_sum.compl_add hsc.has_sum).summable
lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α}
(ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a :=
begin
refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _,
rintros s ⟨hs, hsc⟩,
rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩,
use [u.image sigma.fst, trivial],
intros bs hbs,
simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu,
have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p)
at_top (𝓝 $ ∑ b in bs, g b),
{ simp only [← sigma_preimage_mk, sum_sigma],
refine tendsto_finset_sum _ (λ b hb, _),
change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)),
exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) },
refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩),
exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩
end
/-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ`
has sum `g b`, then the series `g` has sum `a`. -/
lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α}
(ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) :
has_sum g a :=
has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf
lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) :
summable (λb, ∑'c, f ⟨b, c⟩) :=
(ha.has_sum.sigma (assume b, (hf b).has_sum)).summable
lemma has_sum.sigma_of_has_sum [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α}
{a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) :
has_sum f a :=
by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum
end has_sum
section tsum
variables [add_comm_monoid α] [topological_space α] [t2_space α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum.tsum_eq (ha : has_sum f a) : (∑'b, f b) = a :=
(summable.has_sum ⟨a, ha⟩).unique ha
lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ (∑'b, f b) = a :=
iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum)
@[simp] lemma tsum_zero : (∑'b:β, 0:α) = 0 := has_sum_zero.tsum_eq
lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) :
(∑'b, f b) = ∑ b in s, f b :=
(has_sum_sum_of_ne_finset_zero hf).tsum_eq
lemma tsum_fintype [fintype β] (f : β → α) : (∑'b, f b) = ∑ b, f b :=
(has_sum_fintype f).tsum_eq
@[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) :
(∑'x : {x // x ∈ s}, f x) = ∑ x in s, f x :=
(s.has_sum f).tsum_eq
lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) :
(∑'b, f b) = f b :=
(has_sum_single b hf).tsum_eq
@[simp] lemma tsum_ite_eq (b : β) (a : α) : (∑'b', if b' = b then a else 0) = a :=
(has_sum_ite_eq b a).tsum_eq
lemma equiv.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α']
[topological_space α'] (e : α' ≃ α) (h0 : e 0 = 0) {f : β → α} {g : γ → α'}
(h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) :
(∑' b, f b) = e (∑' c, g c) :=
by_cases
(assume : summable g, (h.mpr this.has_sum).tsum_eq)
(assume hg : ¬ summable g,
have hf : ¬ summable f, from mt (e.summable_iff_of_has_sum_iff @h).1 hg,
by simp [tsum, hf, hg, h0])
lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α}
(h : ∀{a}, has_sum f a ↔ has_sum g a) :
(∑'b, f b) = (∑'c, g c) :=
(equiv.refl α).tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h
lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : (∑'c, f (j c)) = (∑'b, f b) :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff
lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g)
(he : ∀ x, g (e x) = f x) :
(∑' x, f x) = ∑' y, g y :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he
lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β)
(hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y)
(hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) :
(∑' x, f x) = ∑' y, g y :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg
lemma tsum_subtype (s : set β) (f : β → α) :
(∑' x : s, f x) = ∑' x, s.indicator f x :=
tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator
section has_continuous_add
variable [has_continuous_add α]
lemma tsum_add (hf : summable f) (hg : summable g) : (∑'b, f b + g b) = (∑'b, f b) + (∑'b, g b) :=
(hf.has_sum.add hg.has_sum).tsum_eq
lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) :
(∑'b, ∑ i in s, f i b) = ∑ i in s, ∑'b, f i b :=
(has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq
lemma tsum_sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) :=
(h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm
lemma tsum_prod' [regular_space α] {f : β × γ → α} (h : summable f)
(h₁ : ∀b, summable (λc, f (b, c))) :
(∑'p, f p) = (∑'b c, f (b, c)) :=
(h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm
lemma tsum_comm' [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f))
(h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) :
(∑' c b, f b c) = (∑' b c, f b c) :=
begin
erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm β γ).tsum_eq],
refl,
assumption
end
end has_continuous_add
section encodable
open encodable
variable [encodable γ]
/-- You can compute a sum over an encodably type by summing over the natural numbers and
taking a supremum. This is useful for outer measures. -/
theorem tsum_supr_decode2 [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(s : γ → β) : (∑' i : ℕ, m (⨆ b ∈ decode2 γ i, s b)) = (∑' b : γ, m (s b)) :=
begin
have H : ∀ n, m (⨆ b ∈ decode2 γ n, s b) ≠ 0 → (decode2 γ n).is_some,
{ intros n h,
cases decode2 γ n with b,
{ refine (h $ by simp [m0]).elim },
{ exact rfl } },
symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _,
{ rintros ⟨m, hm⟩ ⟨n, hn⟩ e,
have := mem_decode2.1 (option.get_mem (H n hn)),
rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this },
{ intros b h,
refine ⟨⟨encode b, _⟩, _⟩,
{ simp only [mem_support, encodek2] at h ⊢, convert h, simp [set.ext_iff, encodek2] },
{ exact option.get_of_mem _ (encodek2 _) } },
{ rintros ⟨n, h⟩, dsimp only [subtype.coe_mk],
transitivity, swap,
rw [show decode2 γ n = _, from option.get_mem (H n h)],
congr, simp [ext_iff, -option.some_get] }
end
/-- `tsum_supr_decode2` specialized to the complete lattice of sets. -/
theorem tsum_Union_decode2 (m : set β → α) (m0 : m ∅ = 0)
(s : γ → set β) : (∑' i, m (⋃ b ∈ decode2 γ i, s b)) = (∑' b, m (s b)) :=
tsum_supr_decode2 m m0 s
/-! Some properties about measure-like functions.
These could also be functions defined on complete sublattices of sets, with the property
that they are countably sub-additive.
`R` will probably be instantiated with `(≤)` in all applications.
-/
/-- If a function is countably sub-additive then it is sub-additive on encodable types -/
theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i)))
(s : γ → β) : R (m (⨆ b : γ, s b)) (∑' b : γ, m (s b)) :=
by { rw [← supr_decode2, ← tsum_supr_decode2 _ m0 s], exact m_supr _ }
/-- If a function is countably sub-additive then it is sub-additive on finite sets -/
theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i)))
(s : δ → β) (t : finset δ) :
R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) :=
by { cases t.nonempty_encodable, rw [supr_subtype'], convert rel_supr_tsum m m0 R m_supr _,
rw [← finset.tsum_subtype], assumption }
/-- If a function is countably sub-additive then it is binary sub-additive -/
theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0)
(R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i)))
(s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) :=
begin
convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂),
{ simp only [supr_bool_eq, cond] },
{ rw [tsum_fintype, fintype.sum_bool, cond, cond] }
end
end encodable
end tsum
section pi
variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)]
lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} :
has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) :=
by simp [has_sum, tendsto_pi]
lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) :=
by simp [summable, pi.has_sum, classical.skolem]
lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) :
(∑' i, f i) x = ∑' i, f i x :=
(pi.has_sum.mp hf.has_sum x).tsum_eq.symm
end pi
section topological_group
variables [add_comm_group α] [topological_space α] [topological_add_group α]
variables {f g : β → α} {a a₁ a₂ : α}
-- `by simpa using` speeds up elaboration. Why?
lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) :=
by simpa only using h.map (-add_monoid_hom.id α) continuous_neg
lemma summable.neg (hf : summable f) : summable (λb, - f b) :=
hf.has_sum.neg.summable
lemma summable.of_neg (hf : summable (λb, - f b)) : summable f :=
by simpa only [neg_neg] using hf.neg
lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f :=
⟨summable.of_neg, summable.neg⟩
lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) :=
by { simp [sub_eq_add_neg], exact hf.add hg.neg }
lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) :=
(hf.has_sum.sub hg.has_sum).summable
lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) :
has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) :=
begin
refine ⟨λ h, hf.add_compl h, λ h, _⟩,
rw [has_sum_subtype_iff_indicator] at hf ⊢,
rw [set.indicator_compl],
simpa only [add_sub_cancel'] using h.sub hf
end
lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) :
has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) :=
iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right]
lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) :
summable (f ∘ coe : sᶜ → α) ↔ summable f :=
⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable,
λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩
protected lemma finset.has_sum_compl_iff (s : finset β) :
has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) :=
(s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm]
protected lemma finset.has_sum_iff_compl (s : finset β) :
has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) :=
(s.has_sum f).has_sum_iff_compl
protected lemma finset.summable_compl_iff (s : finset β) :
summable (λ x : {x // x ∉ s}, f x) ↔ summable f :=
(s.summable f).summable_compl_iff
lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) :
summable (f ∘ coe : sᶜ → α) ↔ summable f :=
(hs.summable f).summable_compl_iff
section tsum
variables [t2_space α]
lemma tsum_neg (hf : summable f) : (∑'b, - f b) = - (∑'b, f b) :=
hf.has_sum.neg.tsum_eq
lemma tsum_sub (hf : summable f) (hg : summable g) : (∑'b, f b - g b) = (∑'b, f b) - (∑'b, g b) :=
(hf.has_sum.sub hg.has_sum).tsum_eq
lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α))
(hsc : summable (f ∘ coe : sᶜ → α)) :
(∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x :=
(hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm
lemma sum_add_tsum_compl {s : finset β} (hf : summable f) :
(∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x :=
((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm
end tsum
/-!
### Sums on subtypes
If `s` is a finset of `α`, we show that the summability of `f` in the whole space and on the subtype
`univ - s` are equivalent, and relate their sums. For a function defined on `ℕ`, we deduce the
formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`.
-/
section subtype
lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} :
has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) :=
begin
refine iff.trans _ ((range k).has_sum_compl_iff),
rw [← (not_mem_range_equiv k).symm.has_sum_iff],
refl
end
lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f :=
iff.symm $ (equiv.add_right (∑ i in range k, f i)).summable_iff_of_has_sum_iff $
λ a, (has_sum_nat_add_iff k).symm
lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} :
has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a :=
by simp [has_sum_nat_add_iff]
lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) :
(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i) :=
by simpa [add_comm] using
((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum
lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) :
(∑'b, f b) = f 0 + (∑'b, f (b + 1)) :=
by simpa only [range_one, sum_singleton] using (sum_add_tsum_nat_add 1 hf).symm
/-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability
assumption on `f`, as otherwise all sums are zero. -/
lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) :=
begin
by_cases hf : summable f,
{ have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i),
{ ext1 i,
rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] },
have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds,
simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat },
{ convert tendsto_const_nhds,
ext1 i,
rw ← summable_nat_add_iff i at hf,
{ exact tsum_eq_zero_of_not_summable hf },
{ apply_instance } }
end
end subtype
end topological_group
section topological_semiring
variables [semiring α] [topological_space α] [topological_semiring α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum.mul_left (a₂) (h : has_sum f a₁) : has_sum (λb, a₂ * f b) (a₂ * a₁) :=
by simpa only using h.map (add_monoid_hom.mul_left a₂) (continuous_const.mul continuous_id)
lemma has_sum.mul_right (a₂) (hf : has_sum f a₁) : has_sum (λb, f b * a₂) (a₁ * a₂) :=
by simpa only using hf.map (add_monoid_hom.mul_right a₂) (continuous_id.mul continuous_const)
lemma summable.mul_left (a) (hf : summable f) : summable (λb, a * f b) :=
(hf.has_sum.mul_left _).summable
lemma summable.mul_right (a) (hf : summable f) : summable (λb, f b * a) :=
(hf.has_sum.mul_right _).summable
section tsum
variables [t2_space α]
lemma summable.tsum_mul_left (a) (hf : summable f) : (∑'b, a * f b) = a * (∑'b, f b) :=
(hf.has_sum.mul_left _).tsum_eq
lemma summable.tsum_mul_right (a) (hf : summable f) : (∑'b, f b * a) = (∑'b, f b) * a :=
(hf.has_sum.mul_right _).tsum_eq
end tsum
end topological_semiring
section topological_semimodule
variables {R : Type*}
[semiring R] [topological_space R]
[topological_space α] [add_comm_monoid α]
[semimodule R α] [topological_semimodule R α]
{f : β → α}
lemma has_sum.smul {a : α} {r : R} (hf : has_sum f a) : has_sum (λ z, r • f z) (r • a) :=
hf.map (const_smul_hom α r) (continuous_const.smul continuous_id)
lemma summable.smul {r : R} (hf : summable f) : summable (λ z, r • f z) :=
hf.has_sum.smul.summable
lemma tsum_smul [t2_space α] {r : R} (hf : summable f) : (∑' z, r • f z) = r • (∑' z, f z) :=
hf.has_sum.smul.tsum_eq
end topological_semimodule
section division_ring
variables [division_ring α] [topological_space α] [topological_semiring α]
{f g : β → α} {a a₁ a₂ : α}
lemma has_sum_mul_left_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, a₂ * f b) (a₂ * a₁) :=
⟨has_sum.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a₂⁻¹⟩
lemma has_sum_mul_right_iff (h : a₂ ≠ 0) : has_sum f a₁ ↔ has_sum (λb, f b * a₂) (a₁ * a₂) :=
⟨has_sum.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a₂⁻¹⟩
lemma summable_mul_left_iff (h : a ≠ 0) : summable f ↔ summable (λb, a * f b) :=
⟨λ H, H.mul_left _, λ H, by simpa only [inv_mul_cancel_left' h] using H.mul_left a⁻¹⟩
lemma summable_mul_right_iff (h : a ≠ 0) : summable f ↔ summable (λb, f b * a) :=
⟨λ H, H.mul_right _, λ H, by simpa only [mul_inv_cancel_right' h] using H.mul_right a⁻¹⟩
lemma tsum_mul_left [t2_space α] : (∑' x, a * f x) = a * ∑' x, f x :=
if hf : summable f then hf.tsum_mul_left a
else if ha : a = 0 then by simp [ha]
else by rw [tsum_eq_zero_of_not_summable hf,
tsum_eq_zero_of_not_summable (mt (summable_mul_left_iff ha).2 hf), mul_zero]
lemma tsum_mul_right [t2_space α] : (∑' x, f x * a) = (∑' x, f x) * a :=
if hf : summable f then hf.tsum_mul_right a
else if ha : a = 0 then by simp [ha]
else by rw [tsum_eq_zero_of_not_summable hf,
tsum_eq_zero_of_not_summable (mt (summable_mul_right_iff ha).2 hf), zero_mul]
end division_ring
section order_topology
variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α]
variables {f g : β → α} {a a₁ a₂ : α}
lemma has_sum_le (h : ∀b, f b ≤ g b) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ :=
le_of_tendsto_of_tendsto' hf hg $ assume s, sum_le_sum $ assume b _, h b
lemma has_sum_le_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c)
(h : ∀b, f b ≤ g (i b)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ :=
have has_sum (λc, (partial_inv i c).cases_on' 0 f) a₁,
begin
refine (has_sum_iff_has_sum_of_ne_zero_bij (i ∘ coe) _ _ _).2 hf,
{ exact assume c₁ c₂ eq, hi eq },
{ intros c hc,
rw [mem_support] at hc,
cases eq : partial_inv i c with b; rw eq at hc,
{ contradiction },
{ rw [partial_inv_of_injective hi] at eq,
exact ⟨⟨b, hc⟩, eq⟩ } },
{ assume c, simp [partial_inv_left hi, option.cases_on'] }
end,
begin
refine has_sum_le (assume c, _) this hg,
by_cases c ∈ set.range i,
{ rcases h with ⟨b, rfl⟩,
rw [partial_inv_left hi, option.cases_on'],
exact h _ },
{ have : partial_inv i c = none := dif_neg h,
rw [this, option.cases_on'],
exact hs _ h }
end
lemma tsum_le_tsum_of_inj {g : γ → α} (i : β → γ) (hi : injective i) (hs : ∀c∉set.range i, 0 ≤ g c)
(h : ∀b, f b ≤ g (i b)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g :=
has_sum_le_inj i hi hs h hf.has_sum hg.has_sum
lemma sum_le_has_sum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : has_sum f a) :
∑ b in s, f b ≤ a :=
ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst,
sum_le_sum_of_subset_of_nonneg hst $ λ b hbt hbs, hs b hbs⟩)
lemma le_has_sum (hf : has_sum f a) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ a :=
calc f b = ∑ b in {b}, f b : finset.sum_singleton.symm
... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf
lemma sum_le_tsum {f : β → α} (s : finset β) (hs : ∀ b∉s, 0 ≤ f b) (hf : summable f) :
∑ b in s, f b ≤ tsum f :=
sum_le_has_sum s hs hf.has_sum
lemma le_tsum (hf : summable f) (b : β) (hb : ∀ b' ≠ b, 0 ≤ f b') : f b ≤ ∑' b, f b :=
le_has_sum (summable.has_sum hf) b hb
lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : summable f) (hg : summable g) : (∑'b, f b) ≤ (∑'b, g b) :=
has_sum_le h hf.has_sum hg.has_sum
lemma has_sum.nonneg (h : ∀ b, 0 ≤ g b) (ha : has_sum g a) : 0 ≤ a :=
has_sum_le h has_sum_zero ha
lemma has_sum.nonpos (h : ∀ b, g b ≤ 0) (ha : has_sum g a) : a ≤ 0 :=
has_sum_le h ha has_sum_zero
lemma tsum_nonneg (h : ∀ b, 0 ≤ g b) : 0 ≤ (∑'b, g b) :=
begin
by_cases hg : summable g,
{ exact hg.has_sum.nonneg h },
{ simp [tsum_eq_zero_of_not_summable hg] }
end
lemma tsum_nonpos (h : ∀ b, f b ≤ 0) : (∑'b, f b) ≤ 0 :=
begin
by_cases hf : summable f,
{ exact hf.has_sum.nonpos h },
{ simp [tsum_eq_zero_of_not_summable hf] }
end
end order_topology
section canonically_ordered
variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α]
variables {f : β → α} {a : α}
lemma le_has_sum' (hf : has_sum f a) (b : β) : f b ≤ a :=
le_has_sum hf b $ λ _ _, zero_le _
lemma le_tsum' (hf : summable f) (b : β) : f b ≤ ∑' b, f b :=
le_tsum hf b $ λ _ _, zero_le _
lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 :=
begin
refine ⟨_, λ h, _⟩,
{ contrapose!,
exact λ ⟨x, hx⟩ h, irrefl _ (lt_of_lt_of_le (pos_iff_ne_zero.2 hx) (le_has_sum' h x)) },
{ convert has_sum_zero,
exact funext h }
end
lemma tsum_eq_zero_iff (hf : summable f) : (∑' i, f i) = 0 ↔ ∀ x, f x = 0 :=
by rw [←has_sum_zero_iff, hf.has_sum_iff]
end canonically_ordered
section uniform_group
variables [add_comm_group α] [uniform_space α]
lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} :
summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) :=
cauchy_map_iff_exists_tendsto.symm
variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α}
lemma cauchy_seq_finset_iff_vanishing :
cauchy_seq (λ (s : finset β), ∑ b in s, f b)
↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) :=
begin
simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot,
prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)],
rw [tendsto_at_top'],
split,
{ assume h e he,
rcases h e he with ⟨⟨s₁, s₂⟩, h⟩,
use [s₁ ∪ s₂],
assume t ht,
specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_left_of_le le_sup_right⟩,
simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h },
{ assume h e he,
rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩,
rcases h d hd with ⟨s, h⟩,
use [(s, s)],
rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩,
have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b,
{ simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm,
add_sub_add_right_eq_sub] },
simp only [this],
exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) }
end
variable [complete_space α]
lemma summable_iff_vanishing :
summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing]
/- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/
lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) :
summable g :=
summable_iff_vanishing.2 $
assume e he,
let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in
⟨s, assume t ht,
have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b :=
calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b :
finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm)
... = ∑ b in t, g b :
begin
refine finset.sum_subset (finset.filter_subset _ _) _,
assume b hbt hb,
simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb,
exact (h b).resolve_right hb
end,
eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩
protected lemma summable.indicator (hf : summable f) (s : set β) :
summable (s.indicator f) :=
hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _
lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) :
summable (f ∘ i) :=
begin
simpa only [set.indicator_range_comp]
using (hi.summable_iff _).2 (hf.indicator (set.range i)),
exact λ x hx, set.indicator_of_not_mem hx _
end
lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) :=
hf.comp_injective subtype.coe_injective
lemma summable_subtype_and_compl {s : set β} :
summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f :=
⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩
lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) :=
ha.comp_injective sigma_mk_injective
lemma summable.sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) :=
ha.sigma' (λ b, ha.sigma_factor b)
lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) :
summable (λ c, f (b, c)) :=
h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2
lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α}
(ha : summable f) : (∑'p, f p) = (∑'b c, f ⟨b, c⟩) :=
tsum_sigma' (λ b, ha.sigma_factor b) ha
lemma tsum_prod [regular_space α] {f : β × γ → α} (h : summable f) :
(∑'p, f p) = (∑'b c, f ⟨b, c⟩) :=
tsum_prod' h h.prod_factor
lemma tsum_comm [regular_space α] {f : β → γ → α} (h : summable (function.uncurry f)) :
(∑' c b, f b c) = (∑' b c, f b c) :=
tsum_comm' h h.prod_factor h.prod_symm.prod_factor
end uniform_group
section topological_group
variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G]
{f : α → G}
lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) :
∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e :=
begin
letI : uniform_space G := topological_add_group.to_uniform_space G,
letI : uniform_add_group G := topological_add_group_is_uniform,
rcases hf with ⟨y, hy⟩,
exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he
end
/-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along
`cofinite`. -/
lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) :=
begin
intros e he,
rw [filter.mem_map],
rcases hf.vanishing he with ⟨s, hs⟩,
refine s.eventually_cofinite_nmem.mono (λ x hx, _),
by simpa using hs {x} (singleton_disjoint.2 hx)
end
end topological_group
lemma summable_abs_iff [linear_ordered_add_comm_group β] [uniform_space β]
[uniform_add_group β] [complete_space β] {f : α → β} :
summable (λ x, abs (f x)) ↔ summable f :=
have h1 : ∀ x : {x | 0 ≤ f x}, abs (f x) = f x := λ x, abs_of_nonneg x.2,
have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, abs (f x) = -f x := λ x, abs_of_neg (not_le.1 x.2),
calc summable (λ x, abs (f x)) ↔
summable (λ x : {x | 0 ≤ f x}, abs (f x)) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, abs (f x)) :
summable_subtype_and_compl.symm
... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) :
by simp only [h1, h2]
... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl]
alias summable_abs_iff ↔ summable.of_abs summable.abs
section cauchy_seq
open finset.Ico filter
/-- If the extended distance between consequent points of a sequence is estimated
by a summable series of `nnreal`s, then the original sequence is a Cauchy sequence. -/
lemma cauchy_seq_of_edist_le_of_summable [emetric_space α] {f : ℕ → α} (d : ℕ → ℝ≥0)
(hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f :=
begin
refine emetric.cauchy_seq_iff_nnreal.2 (λ ε εpos, _),
-- Actually we need partial sums of `d` to be a Cauchy sequence
replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) :=
let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq,
-- Now we take the same `N` as in one of the definitions of a Cauchy sequence
refine (metric.cauchy_seq_iff'.1 hd ε (nnreal.coe_pos.2 εpos)).imp (λ N hN n hn, _),
have hsum := hN n hn,
-- We simplify the known inequality
rw [dist_nndist, nnreal.nndist_eq, ← sum_range_add_sum_Ico _ hn, nnreal.add_sub_cancel'] at hsum,
norm_cast at hsum,
replace hsum := lt_of_le_of_lt (le_max_left _ _) hsum,
rw edist_comm,
-- Then use `hf` to simplify the goal to the same form
apply lt_of_le_of_lt (edist_le_Ico_sum_of_edist_le hn (λ k _ _, hf k)),
assumption_mod_cast
end
/-- If the distance between consequent points of a sequence is estimated by a summable series,
then the original sequence is a Cauchy sequence. -/
lemma cauchy_seq_of_dist_le_of_summable [metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) : cauchy_seq f :=
begin
refine metric.cauchy_seq_iff'.2 (λε εpos, _),
replace hd : cauchy_seq (λ (n : ℕ), ∑ x in range n, d x) :=
let ⟨_, H⟩ := hd in H.tendsto_sum_nat.cauchy_seq,
refine (metric.cauchy_seq_iff'.1 hd ε εpos).imp (λ N hN n hn, _),
have hsum := hN n hn,
rw [real.dist_eq, ← sum_Ico_eq_sub _ hn] at hsum,
calc dist (f n) (f N) = dist (f N) (f n) : dist_comm _ _
... ≤ ∑ x in Ico N n, d x : dist_le_Ico_sum_of_dist_le hn (λ k _ _, hf k)
... ≤ abs (∑ x in Ico N n, d x) : le_abs_self _
... < ε : hsum
end
lemma cauchy_seq_of_summable_dist [metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ (λ _, le_refl _) h
lemma dist_le_tsum_of_dist_le_of_tendsto [metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a))
(n : ℕ) :
dist (f n) a ≤ ∑' m, d (n + m) :=
begin
refine le_of_tendsto (tendsto_const_nhds.dist ha)
(eventually_at_top.2 ⟨n, λ m hnm, _⟩),
refine le_trans (dist_le_Ico_sum_of_dist_le hnm (λ k _ _, hf k)) _,
rw [sum_Ico_eq_sum_range],
refine sum_le_tsum (range _) (λ _ _, le_trans dist_nonneg (hf _)) _,
exact hd.comp_injective (add_right_injective n)
end
lemma dist_le_tsum_of_dist_le_of_tendsto₀ [metric_space α] {f : ℕ → α} (d : ℕ → ℝ)
(hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : summable d) {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ tsum d :=
by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0
lemma dist_le_tsum_dist_of_tendsto [metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) (n) :
dist (f n) a ≤ ∑' m, dist (f (n+m)) (f (n+m).succ) :=
show dist (f n) a ≤ ∑' m, (λx, dist (f x) (f x.succ)) (n + m), from
dist_le_tsum_of_dist_le_of_tendsto (λ n, dist (f n) (f n.succ)) (λ _, le_refl _) h ha n
lemma dist_le_tsum_dist_of_tendsto₀ [metric_space α] {f : ℕ → α}
(h : summable (λn, dist (f n) (f n.succ))) {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) :=
by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0
end cauchy_seq
|
3fcb9caffb3567276bd5fc12c6ea7f5741d0e225 | a1179fa077c09acc49e4fbc8d67084ba89ac4f4c | /tutorials/src/exercises/00_first_proofs.lean | ccd0bb83f6dc3aad902d898cc5af4951f5f0fe24 | [] | no_license | Seeram/Lean-proof-assistant | 11ca0ca0e0446bacdd1773c4c481a3653b2f1074 | e672d46e0e5f39d8de2933ad4f4cac095ca6094f | refs/heads/master | 1,682,754,224,366 | 1,620,959,431,000 | 1,620,959,431,000 | 299,000,950 | 0 | 1 | null | 1,620,680,462,000 | 1,601,200,258,000 | Lean | UTF-8 | Lean | false | false | 18,054 | lean | /-
This file is intended for Lean beginners. The goal is to demonstrate what it feels like to prove
things using Lean and mathlib. Complicated definitions and theory building are not covered.
Everything is covered again more slowly and with exercises in the next files.
-/
-- We want real numbers and their basic properties
import data.real.basic
-- We want to be able to use Lean's built-in "help" functionality
import tactic.suggest
-- We want to be able to define functions using the law of excluded middle
noncomputable theory
open_locale classical
/-
Our first goal is to define the set of upper bounds of a set of real numbers.
This is already defined in mathlib (in a more general context), but we repeat
it for the sake of exposition. Right-click "upper_bounds" below to get offered
to jump to mathlib's version
-/
#check upper_bounds
/-- The set of upper bounds of a set of real numbers ℝ -/
def up_bounds (A : set ℝ) := { x : ℝ | ∀ a ∈ A, a ≤ x}
/-- Predicate `is_max a A` means `a` is a maximum of `A` -/
def is_max (a : ℝ) (A : set ℝ) := a ∈ A ∧ a ∈ up_bounds A
/-
In the above definition, the symbol `∧` means "and". We also see the most
visible difference between set theoretic foundations and type theoretic ones
(used by almost all proof assistants). In set theory, everything is a set, and the
only relation you get from foundations are `=` and `∈`. In type theory, there is
a meta-theoretic relation of "typing": `a : ℝ` reads "`a` is a real number" or,
more precisely, "the type of `a` is `ℝ`". Here "meta-theoretic" means this is not a
statement you can prove or disprove inside the theory, it's a fact that is true or
not. Here we impose this fact, in other circumstances, it would be checked by the
Lean kernel.
By contrast, `a ∈ A` is a statement inside the theory. Here it's part of the
definition, in other circumstances it could be something proven inside Lean.
-/
/- For illustrative purposes, we now define an infix version of the above predicate.
It will allow us to write `a is_a_max_of A`, which is closer to a sentence.
-/
infix ` is_a_max_of `:55 := is_max
/-
Let's prove something now! A set of real numbers has at most one maximum. Here
everything left of the final `:` is introducing the objects and assumption. The equality
`x = y` right of the colon is the conclusion.
-/
lemma unique_max (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y :=
begin
-- We first break our assumptions in their two constituent pieces.
-- We are free to choose the name following `with`
cases hx with x_in x_up,
cases hy with y_in y_up,
-- Assumption `x_up` means x isn't less than elements of A, let's apply this to y
specialize x_up y,
-- Assumption `x_up` now needs the information that `y` is indeed in `A`.
specialize x_up y_in,
-- Let's do this quicker with roles swapped
specialize y_up x x_in,
-- We explained to Lean the idea of this proof.
-- Now we know `x ≤ y` and `y ≤ x`, and Lean shouldn't need more help.
-- `linarith` proves equalities and inequalities that follow linearly from
-- the assumption we have.
linarith,
end
/-
The above proof is too long, even if you remove comments. We don't really need the
unpacking steps at the beginning; we can access both parts of the assumption
`hx : x is_a_max_of A` using shortcuts `h.1` and `h.2`. We can also improve
readability without assistance from the tactic state display, clearly announcing
intermediate goals using `have`. This way we get to the following version of the
same proof.
-/
example (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y :=
begin
have : x ≤ y, from hy.2 x hx.1,
have : y ≤ x, from hx.2 y hy.1,
linarith,
end
/-
Notice how mathematics based on type theory treats the assumption
`∀ a ∈ A, a ≤ y` as a function turning an element `a` of `A` into the statement
`a ≤ y`. More precisely, this assumption is the abbreviation of
`∀ a : ℝ, a ∈ A → a ≤ y`. The expression `hy.2 x` appearing in the above proof
is then the statement `x ∈ A → x ≤ y`, which itself is a function turning a
statement `x ∈ A` into `x ≤ y` so that the full expression `hy.2 x hx.1` is
indeed a proof of `x ≤ y`.
One could argue a three-line-long proof of this lemma is still two lines too long.
This is debatable, but mathlib's style is to write very short proofs for trivial
lemmas. Those proofs are not easy to read but they are meant to indicate that the
proof is probably not worth reading.
In order to reach this stage, we need to know what `linarith` did for us. It invoked
the lemma `le_antisymm` which says: `x ≤ y → y ≤ x → x = y`. This arrow, which
is used both for function and implication, is right associative. So the statement is
`x ≤ y → (y ≤ x → x = y)` which reads: I will send a proof `p` of `x ≤ y` to a function
sending a proof `q'` of `y ≤ x` to a proof of `x = y`. Hence `le_antisymm p q'` is a
proof of `x = y`.
Using this we can get our one-line proof:
-/
example (A : set ℝ) (x y : ℝ) (hx : x is_a_max_of A) (hy : y is_a_max_of A) : x = y :=
le_antisymm (hy.2 x hx.1) (hx.2 y hy.1)
/-
Such a proof is called a proof term (or a "term mode" proof). Notice it has no `begin`
and `end`. It is directly the kind of low level proof that the Lean kernel is
consuming. Commands like `cases`, `specialize` or `linarith` are called tactics, they
help users constructing proof terms that could be very tedious to write directly.
The most efficient proof style combines tactics with proof terms like our previous
`have : x ≤ y, from hy.2 x hx.1` where `hy.2 x hx.1` is a proof term embeded inside
a tactic mode proof.
In the remaining of this file, we'll be characterizing infima of sets of real numbers
in term of sequences.
-/
/-- The set of lower bounds of a set of real numbers ℝ -/
def low_bounds (A : set ℝ) := { x : ℝ | ∀ a ∈ A, x ≤ a}
/-
We now define `a` is an infimum of `A`. Again there is already a more general version
in mathlib.
-/
def is_inf (x : ℝ) (A : set ℝ) := x is_a_max_of (low_bounds A)
infix ` is_an_inf_of `:55 := is_inf
/-
We need to prove that any number which is greater than the infimum of A is greater
than some element of A.
-/
lemma inf_lt {A : set ℝ} {x : ℝ} (hx : x is_an_inf_of A) :
∀ y, x < y → ∃ a ∈ A, a < y :=
begin
-- Let `y` be any real number.
intro y,
-- Let's prove the contrapositive
contrapose,
-- The symbol `¬` means negation. Let's ask Lean to rewrite the goal without negation,
-- pushing negation through quantifiers and inequalities
push_neg,
-- Let's assume the premise, calling the assumption `h`
intro h,
-- `h` is exactly saying `y` is a lower bound of `A` so the second part of
-- the infimum assumption `hx` applied to `y` and `h` is exactly what we want.
exact hx.2 y h
end
/-
In the above proof, the sequence `contrapose, push_neg` is so common that it can be
abbreviated to `contrapose!`. With these commands, we enter the gray zone between
proof checking and proof finding. Practical computer proof checking crucially needs
the computer to handle tedious proof steps. In the next proof, we'll start using
`linarith` a bit more seriously, going one step further into automation.
Our next real goal is to prove inequalities for limits of sequences. We extract the
following lemma: if `y ≤ x + ε` for all positive `ε` then `y ≤ x`.
-/
lemma le_of_le_add_eps {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x :=
begin
-- Let's prove the contrapositive, asking Lean to push negations right away.
contrapose!,
-- Assume `h : x < y`.
intro h,
-- We need to find `ε` such that `ε` is positive and `x + ε < y`.
-- Let's use `(y-x)/2`
use ((y-x)/2),
-- we now have two properties to prove. Let's do both in turn, using `linarith`
split,
linarith,
linarith,
end
/-
Note how `linarith` was used for both sub-goals at the end of the above proof.
We could have shortened that using the semi-colon combinator instead of comma,
writing `split ; linarith`.
Next we will study a compressed version of that proof:
-/
example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x :=
begin
contrapose!,
exact assume h, ⟨(y-x)/2, by linarith, by linarith⟩,
end
/-
The angle brackets `⟨` and `⟩` introduce compound data or proofs. A proof
of a `∃ z, P z` statemement is composed of a witness `z₀` and a proof `h` of
`P z₀`. The compound is denoted by `⟨z₀, h⟩`. In the example above, the predicate is
itself compound, it is a conjunction `P z ∧ Q z`. So the proof term should read
`⟨z₀, ⟨h₁, h₂⟩⟩` where `h₁` (resp. `h₂`) is a proof of `P z₀` (resp. `Q z₀`).
But these so-called "anonymous constructor" brackets are right-associative, so we can
get rid of the nested brackets.
The keyword `by` introduces tactic mode inside term mode, it is a shorter version
of the `begin`/`end` pair, which is more convenient for single tactic blocks.
In this example, `begin` enters tactic mode, `exact` leaves it, `by` re-enters it.
Going all the way to a proof term would make the proof much longer, because we
crucially use automation with `contrapose!` and `linarith`. We can still get a one-line
proof using curly braces to gather several tactic invocations, and the `by` abbreviation
instead of `begin`/`end`:
-/
example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x :=
by { contrapose!, exact assume h, ⟨(y-x)/2, by linarith, by linarith⟩ }
/-
One could argue that the above proof is a bit too terse, and we are relying too much
on linarith. Let's have more `linarith` calls for smaller steps. For the sake
of (tiny) variation, we will also assume the premise and argue by contradiction
instead of contraposing.
-/
example {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x :=
begin
intro h,
-- Assume the conclusion is false, and call this assumption H.
by_contradiction H,
push_neg at H,
-- Now let's compute.
have key := calc
-- Each line must end with a colon followed by a proof term
-- We want to specialize our assumption `h` to `ε = (y-x)/2` but this is long to
-- type, so let's put a hole `_` that Lean will fill in by comparing the
-- statement we want to prove and our proof term with a hole. As usual,
-- positivity of `(y-x)/2` is proved by `linarith`
y ≤ x + (y-x)/2 : h _ (by linarith)
... = x/2 + y/2 : by ring
... < y : by linarith,
-- our key now says `y < y` (notice how the sequence `≤`, `=`, `<` was correctly
-- merged into a `<`). Let `linarith` find the desired contradiction now.
linarith,
-- alternatively, we could have provided the proof term
-- `exact lt_irrefl y key`
end
/-
Now we are ready for some analysis. Let's set up notation for absolute value
-/
local notation `|`x`|` := abs x
/-
And let's define convergence of sequences of real numbers (of course there is
a much more general definition in mathlib).
-/
/-- The sequence `u` tends to `l` -/
def limit (u : ℕ → ℝ) (l : ℝ) := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε
/-
In the above definition, `u n` denotes the n-th term of the sequence. We can
add parentheses to get `u(n)` but we try to avoid parentheses because they pile up
very quickly
-/
-- If y ≤ u n for all n and u n goes to x then y ≤ x
lemma le_lim {x y : ℝ} {u : ℕ → ℝ} (hu : limit u x) (ineq : ∀ n, y ≤ u n) : y ≤ x :=
begin
-- Let's apply our previous lemma
apply le_of_le_add_eps,
-- We need to prove y ≤ x + ε for all positive ε.
-- Let ε be any positive real
intros ε ε_pos,
-- we now specialize our limit assumption to this `ε`, and immediately
-- fix a `N` as promised by the definition.
cases hu ε ε_pos with N HN,
-- Now we only need to compute until reaching the conclusion
calc
y ≤ u N : ineq N
... = x + (u N - x) : by linarith
-- We'll need `add_le_add` which says `a ≤ b` and `c ≤ d` implies `a + c ≤ b + d`
-- We need a lemma saying `z ≤ |z|`. Because we don't know the name of this lemma,
-- let's use `library_search`. Because searching thourgh the library is slow,
-- Lean will write what it found in the Lean message window when cursor is on
-- that line, so that we can replace it by the lemma. We see `le_max_self`, which
-- says `a ≤ |a|`, exactly what we're looking for.
... ≤ x + |u N - x| : add_le_add (by linarith) (le_abs_self (u N - x))
... ≤ x + ε : add_le_add (by linarith) (HN N (by linarith)),
end
/-
The next lemma has been extracted from the main proof in order to discuss numbers.
In ordinary maths, we know that ℕ is *not* contained in `ℝ`, whatever the
construction of real numbers that we use. For instance a natural number is not
an equivalence class of Cauchy sequences. But it's very easy to
pretend otherwise. Formal maths requires slightly more care. In the statement below,
the "type ascription" `(n + 1 : ℝ)` forces Lean to convert the natural number
`n+1` into a real number. The "inclusion" map will be displayed in tactic state
as `↑`. There are various lemmas asserting this map is compatible with addition and
monotone, but we don't want to bother writing their names. The `norm_cast`
tactic is designed to wisely apply those lemmas for us.
-/
lemma inv_succ_pos : ∀ n : ℕ, 1/(n+1 : ℝ) > 0 :=
begin
-- Let `n` be any integer
intro n,
-- Since we don't know the name of the relevant lemma, asserting that the inverse of
-- a positive number is positive, let's state that is suffices
-- to prove that `n+1`, seen as a real number, is positive, and ask `library_search`
suffices : (n + 1 : ℝ) > 0,
{ library_search },
-- Now we want to reduce to a statement about natural numbers, not real numbers
-- coming from natural numbers.
norm_cast,
-- and then get the usual help from `linarith`
linarith,
end
/-
That was a pretty long proof for an obvious fact. And stating it as a lemma feels
stupid, so let's find a way to write it on one line in case we want to include it
in some other proof without stating a lemma. First the `library_search` call
above displays the name of the relevant lemma: `one_div_pos`. We can also
replace the `linarith` call on the last line by `library_search` to learn the name
of the lemma `nat.succ_pos` asserting that the successor of a natural number is
positive. There is also a variant on `norm_cast` that combines it with `exact`.
The term mode analogue of `intro` is `λ`. We get down to:
-/
example : ∀ n : ℕ, 1/(n+1 : ℝ) > 0 :=
λ n, one_div_pos.mpr (by exact_mod_cast nat.succ_pos n)
/-
The next proof uses mostly known things, so we will commment only new aspects.
-/
lemma limit_inv_succ : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε :=
begin
intros ε ε_pos,
suffices : ∃ N : ℕ, 1/ε ≤ N,
{ -- Because we didn't provide a name for the above statement, Lean called it `this`.
-- Let's fix an `N` that works.
cases this with N HN,
use N,
intros n Hn,
-- Now we want to rewrite the goal using lemmas
-- `div_le_iff' : 0 < b → (a / b ≤ c ↔ a ≤ b * c)`
-- `div_le_iff : 0 < b → (a / b ≤ c ↔ a ≤ c * b)`
-- the second one will be rewritten from right to left, as indicated by `←`.
-- Lean will create a side goal for the required positivity assumption that
-- we don't provide for `div_le_iff'`.
rw [div_le_iff', ← div_le_iff ε_pos],
-- We want to replace assumption `Hn` by its real counter-part so that
-- linarith can find what it needs.
replace Hn : (N : ℝ) ≤ n, exact_mod_cast Hn,
linarith,
-- we are still left with the positivity assumption, but already discussed
-- how to prove it in the preceding lemma
exact_mod_cast nat.succ_pos n },
-- Now we need to prove that sufficient statement.
-- We want to use that `ℝ` is archimedean. So we start typing
-- `exact archimedean_` and hit Ctrl-space to see what completion Lean proposes
-- the lemma `archimedean_iff_nat_le` sounds promising. We select the left to
-- right implication using `.1`. This a generic lemma for fields equiped with
-- a linear (ie total) order. We need to provide a proof that `ℝ` is indeed
-- archimedean. This is done using the `apply_instance` tactic that will be
-- covered elsewhere.
exact archimedean_iff_nat_le.1 (by apply_instance) (1/ε),
end
/-
We can now put all pieces together, with almost no new things to explain.
-/
lemma inf_seq (A : set ℝ) (x : ℝ) :
(x is_an_inf_of A) ↔ (x ∈ low_bounds A ∧ ∃ u : ℕ → ℝ, limit u x ∧ ∀ n, u n ∈ A ) :=
begin
split,
{ intro h,
split,
{ exact h.1 },
-- On the next line, we don't need to tell Lean to treat `n+1` as a real number because
-- we add `x` to it, so Lean knows there is only one way to make sense of this expression.
have key : ∀ n : ℕ, ∃ a ∈ A, a < x + 1/(n+1),
{ intro n,
-- we can use the lemma we proved above
apply inf_lt h,
-- and another one we proved!
have : 0 < 1/(n+1 : ℝ), from inv_succ_pos n,
linarith },
-- Now we need to use axiom of (countable) choice
choose u hu using key,
use u,
split,
{ intros ε ε_pos,
-- again we use a lemma we proved, specializing it to our fixed `ε`, and fixing a `N`
cases limit_inv_succ ε ε_pos with N H,
use N,
intros n hn,
have : x ≤ u n, from h.1 _ (hu n).1,
have := calc
u n < x + 1/(n + 1) : (hu n).2
... ≤ x + ε : add_le_add (le_refl x) (H n hn),
rw abs_of_nonneg ; linarith },
{ intro n,
exact (hu n).1 } },
{ intro h,
-- Assumption `h` is made of nested compound statements. We can use the
-- recursive version of `cases` to unpack it in one go.
rcases h with ⟨x_min, u, lim, huA⟩,
split,
exact x_min,
intros y y_mino,
apply le_lim lim,
intro n,
exact y_mino (u n) (huA n) },
end
|
3688933662b9943b38b7b552372a57812b61c466 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/data/nat/gcd.lean | 034720732aba5037ed4bbd539fd070e079333d55 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,888 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import data.nat.pow
/-!
# Definitions and properties of `gcd`, `lcm`, and `coprime`
-/
namespace nat
/-! ### `gcd` -/
theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) :=
gcd.induction m n
(λn, by rw gcd_zero_left; exact ⟨dvd_zero n, dvd_refl n⟩)
(λm n npos, by rw ←gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩)
theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := (gcd_dvd m n).left
theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := (gcd_dvd m n).right
theorem gcd_le_left {m} (n) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h $ gcd_dvd_left m n
theorem gcd_le_right (m) {n} (h : 0 < n) : gcd m n ≤ n := le_of_dvd h $ gcd_dvd_right m n
theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n :=
gcd.induction m n (λn _ kn, by rw gcd_zero_left; exact kn)
(λn m mpos IH H1 H2, by rw gcd_rec; exact IH ((dvd_mod_iff H1).2 H2) H1)
theorem dvd_gcd_iff {m n k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n :=
iff.intro (λ h, ⟨h.trans (gcd_dvd m n).left, h.trans (gcd_dvd m n).right⟩)
(λ h, dvd_gcd h.left h.right)
theorem gcd_comm (m n : ℕ) : gcd m n = gcd n m :=
dvd_antisymm
(dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n))
(dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m))
theorem gcd_eq_left_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd m n = m :=
⟨λ h, by rw [gcd_rec, mod_eq_zero_of_dvd h, gcd_zero_left],
λ h, h ▸ gcd_dvd_right m n⟩
theorem gcd_eq_right_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd n m = m :=
by rw gcd_comm; apply gcd_eq_left_iff_dvd
theorem gcd_assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) :=
dvd_antisymm
(dvd_gcd
((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_left m n))
(dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_right m n))
(gcd_dvd_right (gcd m n) k)))
(dvd_gcd
(dvd_gcd (gcd_dvd_left m (gcd n k)) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_left n k)))
((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_right n k)))
@[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 :=
eq.trans (gcd_comm n 1) $ gcd_one_left n
theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k :=
gcd.induction n k
(λk, by repeat {rw mul_zero <|> rw gcd_zero_left})
(λk n H IH, by rwa [←mul_mod_mul_left, ←gcd_rec, ←gcd_rec] at IH)
theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n :=
by rw [mul_comm m n, mul_comm k n, mul_comm (gcd m k) n, gcd_mul_left]
theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n :=
pos_of_dvd_of_pos (gcd_dvd_left m n) mpos
theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n :=
pos_of_dvd_of_pos (gcd_dvd_right m n) npos
theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 :=
or.elim (nat.eq_zero_or_pos m) id
(assume H1 : 0 < m, absurd (eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1)))
theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 :=
by rw gcd_comm at H; exact eq_zero_of_gcd_eq_zero_left H
theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) :
gcd (m / k) (n / k) = gcd m n / k :=
or.elim (nat.eq_zero_or_pos k)
(λk0, by rw [k0, nat.div_zero, nat.div_zero, nat.div_zero, gcd_zero_right])
(λH3, nat.eq_of_mul_eq_mul_right H3 $ by rw [
nat.div_mul_cancel (dvd_gcd H1 H2), ←gcd_mul_right,
nat.div_mul_cancel H1, nat.div_mul_cancel H2])
theorem gcd_dvd_gcd_of_dvd_left {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n :=
dvd_gcd ((gcd_dvd_left m n).trans H) (gcd_dvd_right m n)
theorem gcd_dvd_gcd_of_dvd_right {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k :=
dvd_gcd (gcd_dvd_left n m) ((gcd_dvd_right n m).trans H)
theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n :=
gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n :=
gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _)
theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) :=
gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _)
theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) :=
gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _)
theorem gcd_eq_left {m n : ℕ} (H : m ∣ n) : gcd m n = m :=
dvd_antisymm (gcd_dvd_left _ _) (dvd_gcd (dvd_refl _) H)
theorem gcd_eq_right {m n : ℕ} (H : n ∣ m) : gcd m n = n :=
by rw [gcd_comm, gcd_eq_left H]
@[simp] lemma gcd_mul_left_left (m n : ℕ) : gcd (m * n) n = n :=
dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (dvd_mul_left _ _) (dvd_refl _))
@[simp] lemma gcd_mul_left_right (m n : ℕ) : gcd n (m * n) = n :=
by rw [gcd_comm, gcd_mul_left_left]
@[simp] lemma gcd_mul_right_left (m n : ℕ) : gcd (n * m) n = n :=
by rw [mul_comm, gcd_mul_left_left]
@[simp] lemma gcd_mul_right_right (m n : ℕ) : gcd n (n * m) = n :=
by rw [gcd_comm, gcd_mul_right_left]
@[simp] lemma gcd_gcd_self_right_left (m n : ℕ) : gcd m (gcd m n) = gcd m n :=
dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (gcd_dvd_left _ _) (dvd_refl _))
@[simp] lemma gcd_gcd_self_right_right (m n : ℕ) : gcd m (gcd n m) = gcd n m :=
by rw [gcd_comm n m, gcd_gcd_self_right_left]
@[simp] lemma gcd_gcd_self_left_right (m n : ℕ) : gcd (gcd n m) m = gcd n m :=
by rw [gcd_comm, gcd_gcd_self_right_right]
@[simp] lemma gcd_gcd_self_left_left (m n : ℕ) : gcd (gcd m n) m = gcd m n :=
by rw [gcd_comm m n, gcd_gcd_self_left_right]
lemma gcd_add_mul_self (m n k : ℕ) : gcd m (n + k * m) = gcd m n :=
by simp [gcd_rec m (n + k * m), gcd_rec m n]
theorem gcd_eq_zero_iff {i j : ℕ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 :=
begin
split,
{ intro h,
exact ⟨eq_zero_of_gcd_eq_zero_left h, eq_zero_of_gcd_eq_zero_right h⟩, },
{ intro h,
rw [h.1, h.2],
exact nat.gcd_zero_right _ }
end
/-! ### `lcm` -/
theorem lcm_comm (m n : ℕ) : lcm m n = lcm n m :=
by delta lcm; rw [mul_comm, gcd_comm]
@[simp]
theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 :=
by delta lcm; rw [zero_mul, nat.zero_div]
@[simp]
theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m
@[simp]
theorem lcm_one_left (m : ℕ) : lcm 1 m = m :=
by delta lcm; rw [one_mul, gcd_one_left, nat.div_one]
@[simp]
theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m
@[simp]
theorem lcm_self (m : ℕ) : lcm m m = m :=
or.elim (nat.eq_zero_or_pos m)
(λh, by rw [h, lcm_zero_left])
(λh, by delta lcm; rw [gcd_self, nat.mul_div_cancel _ h])
theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n :=
dvd.intro (n / gcd m n) (nat.mul_div_assoc _ $ gcd_dvd_right m n).symm
theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n :=
lcm_comm n m ▸ dvd_lcm_left n m
theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n :=
by delta lcm; rw [nat.mul_div_cancel' ((gcd_dvd_left m n).trans (dvd_mul_right m n))]
theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k :=
or.elim (nat.eq_zero_or_pos k)
(λh, by rw h; exact dvd_zero _)
(λkpos, dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos)) $
by rw [gcd_mul_lcm, ←gcd_mul_right, mul_comm n k];
exact dvd_gcd (mul_dvd_mul_left _ H2) (mul_dvd_mul_right H1 _))
lemma lcm_dvd_iff {m n k : ℕ} : lcm m n ∣ k ↔ m ∣ k ∧ n ∣ k :=
⟨λ h, ⟨(dvd_lcm_left _ _).trans h, (dvd_lcm_right _ _).trans h⟩,
and_imp.2 lcm_dvd⟩
theorem lcm_assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) :=
dvd_antisymm
(lcm_dvd
(lcm_dvd (dvd_lcm_left m (lcm n k)) ((dvd_lcm_left n k).trans (dvd_lcm_right m (lcm n k))))
((dvd_lcm_right n k).trans (dvd_lcm_right m (lcm n k))))
(lcm_dvd
((dvd_lcm_left m n).trans (dvd_lcm_left (lcm m n) k))
(lcm_dvd ((dvd_lcm_right m n).trans (dvd_lcm_left (lcm m n) k))
(dvd_lcm_right (lcm m n) k)))
theorem lcm_ne_zero {m n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 :=
by { intro h, simpa [h, hm, hn] using gcd_mul_lcm m n, }
/-!
### `coprime`
See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`.
-/
instance (m n : ℕ) : decidable (coprime m n) := by unfold coprime; apply_instance
theorem coprime_iff_gcd_eq_one {m n : ℕ} : coprime m n ↔ gcd m n = 1 := iff.rfl
theorem coprime.gcd_eq_one {m n : ℕ} : coprime m n → gcd m n = 1 := id
theorem coprime.symm {m n : ℕ} : coprime n m → coprime m n := (gcd_comm m n).trans
theorem coprime_comm {m n : ℕ} : coprime n m ↔ coprime m n := ⟨coprime.symm, coprime.symm⟩
theorem coprime.dvd_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m :=
let t := dvd_gcd (dvd_mul_left k m) H2 in
by rwa [gcd_mul_left, H1.gcd_eq_one, mul_one] at t
theorem coprime.dvd_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n :=
by rw mul_comm at H2; exact H1.dvd_of_dvd_mul_right H2
theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) :
gcd (k * m) n = gcd m n :=
have H1 : coprime (gcd (k * m) n) k,
by rw [coprime, gcd_assoc, H.symm.gcd_eq_one, gcd_one_right],
dvd_antisymm
(dvd_gcd (H1.dvd_of_dvd_mul_left (gcd_dvd_left _ _)) (gcd_dvd_right _ _))
(gcd_dvd_gcd_mul_left _ _ _)
theorem coprime.gcd_mul_right_cancel (m : ℕ) {k n : ℕ} (H : coprime k n) :
gcd (m * k) n = gcd m n :=
by rw [mul_comm m k, H.gcd_mul_left_cancel m]
theorem coprime.gcd_mul_left_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) :
gcd m (k * n) = gcd m n :=
by rw [gcd_comm m n, gcd_comm m (k * n), H.gcd_mul_left_cancel n]
theorem coprime.gcd_mul_right_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) :
gcd m (n * k) = gcd m n :=
by rw [mul_comm n k, H.gcd_mul_left_cancel_right n]
theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : 0 < gcd m n) :
coprime (m / gcd m n) (n / gcd m n) :=
by rw [coprime_iff_gcd_eq_one, gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), nat.div_self H]
theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) :
¬ coprime m n :=
λ co, not_lt_of_ge (le_of_dvd zero_lt_one $ by rw [←co.gcd_eq_one]; exact dvd_gcd Hm Hn) dgt1
theorem exists_coprime {m n : ℕ} (H : 0 < gcd m n) :
∃ m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n :=
⟨_, _, coprime_div_gcd_div_gcd H,
(nat.div_mul_cancel (gcd_dvd_left m n)).symm,
(nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩
theorem exists_coprime' {m n : ℕ} (H : 0 < gcd m n) :
∃ g m' n', 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g :=
let ⟨m', n', h⟩ := exists_coprime H in ⟨_, m', n', H, h⟩
theorem coprime.mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k :=
(H1.gcd_mul_left_cancel n).trans H2
theorem coprime.mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) :=
(H1.symm.mul H2.symm).symm
theorem coprime.coprime_dvd_left {m k n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n :=
eq_one_of_dvd_one (by delta coprime at H2; rw ← H2; exact gcd_dvd_gcd_of_dvd_left _ H1)
theorem coprime.coprime_dvd_right {m k n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n :=
(H2.symm.coprime_dvd_left H1).symm
theorem coprime.coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n :=
H.coprime_dvd_left (dvd_mul_left _ _)
theorem coprime.coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n :=
H.coprime_dvd_left (dvd_mul_right _ _)
theorem coprime.coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n :=
H.coprime_dvd_right (dvd_mul_left _ _)
theorem coprime.coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n :=
H.coprime_dvd_right (dvd_mul_right _ _)
theorem coprime.coprime_div_left {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) :
coprime (m / a) n :=
begin
by_cases a_split : (a = 0),
{ subst a_split,
rw zero_dvd_iff at dvd,
simpa [dvd] using cmn, },
{ rcases dvd with ⟨k, rfl⟩,
rw nat.mul_div_cancel_left _ (nat.pos_of_ne_zero a_split),
exact coprime.coprime_mul_left cmn, },
end
theorem coprime.coprime_div_right {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) :
coprime m (n / a) :=
(coprime.coprime_div_left cmn.symm dvd).symm
lemma coprime_mul_iff_left {k m n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k :=
⟨λ h, ⟨coprime.coprime_mul_right h, coprime.coprime_mul_left h⟩,
λ ⟨h, _⟩, by rwa [coprime_iff_gcd_eq_one, coprime.gcd_mul_left_cancel n h]⟩
lemma coprime_mul_iff_right {k m n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n :=
by simpa only [coprime_comm] using coprime_mul_iff_left
lemma coprime.gcd_left (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n :=
hmn.coprime_dvd_left $ gcd_dvd_right k m
lemma coprime.gcd_right (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) :=
hmn.coprime_dvd_right $ gcd_dvd_right k n
lemma coprime.gcd_both (k l : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) :=
(hmn.gcd_left k).gcd_right l
lemma coprime.mul_dvd_of_dvd_of_dvd {a n m : ℕ} (hmn : coprime m n)
(hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a :=
let ⟨k, hk⟩ := hm in hk.symm ▸ mul_dvd_mul_left _ (hmn.symm.dvd_of_dvd_mul_left (hk ▸ hn))
theorem coprime_one_left : ∀ n, coprime 1 n := gcd_one_left
theorem coprime_one_right : ∀ n, coprime n 1 := gcd_one_right
theorem coprime.pow_left {m k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k :=
nat.rec_on n (coprime_one_left _) (λn IH, H1.mul IH)
theorem coprime.pow_right {m k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) :=
(H1.symm.pow_left n).symm
theorem coprime.pow {k l : ℕ} (m n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) :=
(H1.pow_left _).pow_right _
lemma coprime_pow_left_iff {n : ℕ} (hn : 0 < n) (a b : ℕ) :
nat.coprime (a ^ n) b ↔ nat.coprime a b :=
begin
obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero hn.ne',
rw [pow_succ, nat.coprime_mul_iff_left],
exact ⟨and.left, λ hab, ⟨hab, hab.pow_left _⟩⟩
end
lemma coprime_pow_right_iff {n : ℕ} (hn : 0 < n) (a b : ℕ) :
nat.coprime a (b ^ n) ↔ nat.coprime a b :=
by rw [nat.coprime_comm, coprime_pow_left_iff hn, nat.coprime_comm]
theorem coprime.eq_one_of_dvd {k m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 :=
by rw [← H.gcd_eq_one, gcd_eq_left d]
@[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 :=
by simp [coprime]
@[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 :=
by simp [coprime]
theorem not_coprime_zero_zero : ¬ coprime 0 0 := by simp
@[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ true :=
by simp [coprime]
@[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ true :=
by simp [coprime]
@[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 :=
by simp [coprime]
lemma coprime.eq_of_mul_eq_zero {m n : ℕ} (h : m.coprime n) (hmn : m * n = 0) :
m = 0 ∧ n = 1 ∨ m = 1 ∧ n = 0 :=
(nat.eq_zero_of_mul_eq_zero hmn).imp
(λ hm, ⟨hm, n.coprime_zero_left.mp $ hm ▸ h⟩)
(λ hn, ⟨m.coprime_zero_left.mp $ hn ▸ h.symm, hn⟩)
/-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/
def prod_dvd_and_dvd_of_dvd_prod {m n k : ℕ} (H : k ∣ m * n) :
{ d : {m' // m' ∣ m} × {n' // n' ∣ n} // k = d.1 * d.2 } :=
begin
cases h0 : (gcd k m),
case nat.zero {
have : k = 0 := eq_zero_of_gcd_eq_zero_left h0, subst this,
have : m = 0 := eq_zero_of_gcd_eq_zero_right h0, subst this,
exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ },
case nat.succ : tmp {
have hpos : 0 < gcd k m := h0.symm ▸ nat.zero_lt_succ _; clear h0 tmp,
have hd : gcd k m * (k / gcd k m) = k := (nat.mul_div_cancel' (gcd_dvd_left k m)),
refine ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩,
apply dvd_of_mul_dvd_mul_left hpos,
rw [hd, ← gcd_mul_right],
exact dvd_gcd (dvd_mul_right _ _) H }
end
theorem gcd_mul_dvd_mul_gcd (k m n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n :=
begin
rcases (prod_dvd_and_dvd_of_dvd_prod $ gcd_dvd_right k (m * n)) with ⟨⟨⟨m', hm'⟩, ⟨n', hn'⟩⟩, h⟩,
replace h : gcd k (m * n) = m' * n' := h,
rw h,
have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _,
apply mul_dvd_mul,
{ have hm'k : m' ∣ k := (dvd_mul_right m' n').trans hm'n',
exact dvd_gcd hm'k hm' },
{ have hn'k : n' ∣ k := (dvd_mul_left n' m').trans hm'n',
exact dvd_gcd hn'k hn' }
end
theorem coprime.gcd_mul (k : ℕ) {m n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n :=
dvd_antisymm
(gcd_mul_dvd_mul_gcd k m n)
((h.gcd_both k k).mul_dvd_of_dvd_of_dvd
(gcd_dvd_gcd_mul_right_right _ _ _)
(gcd_dvd_gcd_mul_left_right _ _ _))
theorem pow_dvd_pow_iff {a b n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b :=
begin
refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩,
cases nat.eq_zero_or_pos (gcd a b) with g0 g0,
{ simp [eq_zero_of_gcd_eq_zero_right g0] },
rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩,
rw [mul_pow, mul_pow] at h,
replace h := dvd_of_mul_dvd_mul_right (pow_pos g0' _) h,
have := pow_dvd_pow a' n0,
rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this,
simp [eq_one_of_dvd_one this]
end
lemma gcd_mul_gcd_of_coprime_of_mul_eq_mul {a b c d : ℕ} (cop : c.coprime d) (h : a * b = c * d) :
a.gcd c * b.gcd c = c :=
begin
apply dvd_antisymm,
{ apply nat.coprime.dvd_of_dvd_mul_right (nat.coprime.mul (cop.gcd_left _) (cop.gcd_left _)),
rw ← h,
apply mul_dvd_mul (gcd_dvd _ _).1 (gcd_dvd _ _).1 },
{ rw [gcd_comm a _, gcd_comm b _],
transitivity c.gcd (a * b),
rw [h, gcd_mul_right_right d c],
apply gcd_mul_dvd_mul_gcd }
end
end nat
|
54532f9c9ee2a5eb64d2f8e90f76f4c030734821 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /library/data/finset/bigops.lean | 14845f8308ea91bb1c7d0e75e767ce786e5b70cf | [
"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 | 5,758 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Haitao Zhang
Finite unions and intersections on finsets.
Note: for the moment we only do unions. We need to generalize bigops for intersections.
-/
import data.finset.comb algebra.group_bigops
open list
namespace finset
variables {A B : Type} [deceqA : decidable_eq A] [deceqB : decidable_eq B]
/- Unionl and Union -/
section union
definition to_comm_monoid_Union (B : Type) [deceqB : decidable_eq B] :
algebra.comm_monoid (finset B) :=
⦃ algebra.comm_monoid,
mul := union,
mul_assoc := union.assoc,
one := empty,
mul_one := union_empty,
one_mul := empty_union,
mul_comm := union.comm
⦄
open [classes] algebra
local attribute finset.to_comm_monoid_Union [instance]
include deceqB
definition Unionl (l : list A) (f : A → finset B) : finset B := algebra.Prodl l f
notation `⋃` binders `←` l, r:(scoped f, Unionl l f) := r
definition Union (s : finset A) (f : A → finset B) : finset B := algebra.finset.Prod s f
notation `⋃` binders `∈` s, r:(scoped f, finset.Union s f) := r
theorem Unionl_nil (f : A → finset B) : Unionl [] f = ∅ := algebra.Prodl_nil f
theorem Unionl_cons (f : A → finset B) (a : A) (l : list A) :
Unionl (a::l) f = f a ∪ Unionl l f := algebra.Prodl_cons f a l
theorem Unionl_append (l₁ l₂ : list A) (f : A → finset B) :
Unionl (l₁++l₂) f = Unionl l₁ f ∪ Unionl l₂ f := algebra.Prodl_append l₁ l₂ f
theorem Unionl_mul (l : list A) (f g : A → finset B) :
Unionl l (λx, f x ∪ g x) = Unionl l f ∪ Unionl l g := algebra.Prodl_mul l f g
section deceqA
include deceqA
theorem Unionl_insert_of_mem (f : A → finset B) {a : A} {l : list A} (H : a ∈ l) :
Unionl (list.insert a l) f = Unionl l f := algebra.Prodl_insert_of_mem f H
theorem Unionl_insert_of_not_mem (f : A → finset B) {a : A} {l : list A} (H : a ∉ l) :
Unionl (list.insert a l) f = f a ∪ Unionl l f := algebra.Prodl_insert_of_not_mem f H
theorem Unionl_union {l₁ l₂ : list A} (f : A → finset B) (d : list.disjoint l₁ l₂) :
Unionl (list.union l₁ l₂) f = Unionl l₁ f ∪ Unionl l₂ f := algebra.Prodl_union f d
theorem Unionl_empty (l : list A) : Unionl l (λ x, ∅) = (∅ : finset B) := algebra.Prodl_one l
end deceqA
theorem Union_empty (f : A → finset B) : Union ∅ f = ∅ := algebra.finset.Prod_empty f
theorem Union_mul (s : finset A) (f g : A → finset B) :
Union s (λx, f x ∪ g x) = Union s f ∪ Union s g := algebra.finset.Prod_mul s f g
section deceqA
include deceqA
theorem Union_insert_of_mem (f : A → finset B) {a : A} {s : finset A} (H : a ∈ s) :
Union (insert a s) f = Union s f := algebra.finset.Prod_insert_of_mem f H
private theorem Union_insert_of_not_mem (f : A → finset B) {a : A} {s : finset A} (H : a ∉ s) :
Union (insert a s) f = f a ∪ Union s f := algebra.finset.Prod_insert_of_not_mem f H
theorem Union_union (f : A → finset B) {s₁ s₂ : finset A} (disj : s₁ ∩ s₂ = ∅) :
Union (s₁ ∪ s₂) f = Union s₁ f ∪ Union s₂ f := algebra.finset.Prod_union f disj
theorem Union_ext {s : finset A} {f g : A → finset B} (H : ∀x, x ∈ s → f x = g x) :
Union s f = Union s g := algebra.finset.Prod_ext H
theorem Union_empty' (s : finset A) : Union s (λ x, ∅) = (∅ : finset B) := algebra.finset.Prod_one s
-- this will eventually be an instance of something more general
theorem inter_Union (s : finset B) (t : finset A) (f : A → finset B) :
s ∩ (⋃ x ∈ t, f x) = (⋃ x ∈ t, s ∩ f x) :=
begin
induction t with s' x H IH,
rewrite [*Union_empty, inter_empty],
rewrite [*Union_insert_of_not_mem _ H, inter.distrib_left, IH],
end
theorem mem_Union_iff (s : finset A) (f : A → finset B) (b : B) :
b ∈ (⋃ x ∈ s, f x) ↔ (∃ x, x ∈ s ∧ b ∈ f x ) :=
begin
induction s with s' a H IH,
rewrite [exists_mem_empty_eq],
rewrite [Union_insert_of_not_mem _ H, mem_union_eq, IH, exists_mem_insert_eq]
end
theorem mem_Union_eq (s : finset A) (f : A → finset B) (b : B) :
b ∈ (⋃ x ∈ s, f x) = (∃ x, x ∈ s ∧ b ∈ f x ) :=
propext !mem_Union_iff
theorem Union_insert (f : A → finset B) {a : A} {s : finset A} :
Union (insert a s) f = f a ∪ Union s f :=
decidable.by_cases
(assume Pin : a ∈ s,
begin
rewrite [Union_insert_of_mem f Pin],
apply ext,
intro x,
apply iff.intro,
exact mem_union_r,
rewrite [mem_union_eq],
intro Por,
exact or.elim Por
(assume Pl, begin
rewrite mem_Union_eq, exact (exists.intro a (and.intro Pin Pl)) end)
(assume Pr, Pr)
end)
(assume H : a ∉ s, !Union_insert_of_not_mem H)
lemma image_eq_Union_index_image (s : finset A) (f : A → finset B) :
Union s f = Union (image f s) id :=
finset.induction_on s
(by rewrite Union_empty)
(take s1 a Pa IH, by rewrite [image_insert, *Union_insert, IH])
lemma Union_const [deceqB : decidable_eq B] {f : A → finset B} {s : finset A} {t : finset B} :
s ≠ ∅ → (∀ x, x ∈ s → f x = t) → Union s f = t :=
begin
induction s with a' s' H IH,
{intros [H1, H2], exfalso, apply H1 !rfl},
intros [H1, H2],
rewrite [Union_insert, H2 _ !mem_insert],
cases (decidable.em (s' = ∅)) with [seq, sne],
{rewrite [seq, Union_empty, union_empty]},
have H3 : ∀ x, x ∈ s' → f x = t, from (λ x H', H2 x (mem_insert_of_mem _ H')),
rewrite [IH sne H3, union_self]
end
end deceqA
end union
end finset
|
a19bea90de9fc923b89d9bf5bf4651f7bf35d084 | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2019/lectures/emptyset.lean | ade297328d185266d56b5ecdb5de679e5fbdbe34 | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 236 | lean | example (P : Prop) : ∀ x ∈ (∅ : set ℕ), P :=
begin
intro x,
intro hx,
cases hx,
end
example (P : Prop) : ∀ x ∈ (∅ : set ℕ), P :=
begin
intros x hx, cases hx,
end
|
e92321c6d12ccfeef86ae7208e5a645b199d0c41 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/rbtree/min_max.lean | 996e90440ddfd79d91aaedfb95f60170335c06ed | [
"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,693 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import data.rbtree.basic
universe u
namespace rbnode
variables {α : Type u} {lt : α → α → Prop}
lemma mem_of_min_eq (lt : α → α → Prop) [is_irrefl α lt] {a : α} {t : rbnode α} :
t.min = some a → mem lt a t :=
begin
induction t,
{ intros, contradiction },
all_goals
{ cases t_lchild; simp [rbnode.min]; intro h,
{ subst t_val, simp [mem, irrefl_of lt a] },
all_goals { rw [mem], simp [t_ih_lchild h] } }
end
lemma mem_of_max_eq (lt : α → α → Prop) [is_irrefl α lt] {a : α} {t : rbnode α} :
t.max = some a → mem lt a t :=
begin
induction t,
{ intros, contradiction },
all_goals
{ cases t_rchild; simp [rbnode.max]; intro h,
{ subst t_val, simp [mem, irrefl_of lt a] },
all_goals { rw [mem], simp [t_ih_rchild h] } }
end
variables [is_strict_weak_order α lt]
lemma eq_leaf_of_min_eq_none {t : rbnode α} : t.min = none → t = leaf :=
begin
induction t,
{ intros, refl },
all_goals
{ cases t_lchild; simp [rbnode.min, false_implies_iff]; intro h,
all_goals { have := t_ih_lchild h, contradiction } }
end
lemma eq_leaf_of_max_eq_none {t : rbnode α} : t.max = none → t = leaf :=
begin
induction t,
{ intros, refl },
all_goals
{ cases t_rchild; simp [rbnode.max, false_implies_iff]; intro h,
all_goals { have := t_ih_rchild h, contradiction } }
end
lemma min_is_minimal {a : α} {t : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → t.min = some a → ∀ {b}, mem lt b t → a ≈[lt] b ∨ lt a b :=
begin
classical,
induction t,
{ simp [strict_weak_order.equiv], intros _ _ hs hmin b, contradiction },
all_goals
{ cases t_lchild; intros lo hi hs hmin b hmem,
{ simp [rbnode.min] at hmin, subst t_val,
simp [mem] at hmem, cases hmem with heqv hmem,
{ left, exact heqv.swap },
{ have := lt_of_mem_right hs (by constructor) hmem,
right, assumption } },
all_goals
{ have hs' := hs,
cases hs, simp [rbnode.min] at hmin,
rw [mem] at hmem, blast_disjs,
{ exact t_ih_lchild hs_hs₁ hmin hmem },
{ have hmm := mem_of_min_eq lt hmin,
have a_lt_val := lt_of_mem_left hs' (by constructor) hmm,
have a_lt_b := lt_of_lt_of_incomp a_lt_val hmem.swap,
right, assumption },
{ have hmm := mem_of_min_eq lt hmin,
have a_lt_b := lt_of_mem_left_right hs' (by constructor) hmm hmem,
right, assumption } } }
end
lemma max_is_maximal {a : α} {t : rbnode α} :
∀ {lo hi}, is_searchable lt t lo hi → t.max = some a → ∀ {b}, mem lt b t → a ≈[lt] b ∨ lt b a :=
begin
classical,
induction t,
{ simp [strict_weak_order.equiv], intros _ _ hs hmax b, contradiction },
all_goals
{ cases t_rchild; intros lo hi hs hmax b hmem,
{ simp [rbnode.max] at hmax, subst t_val,
simp [mem] at hmem, cases hmem with hmem heqv,
{ have := lt_of_mem_left hs (by constructor) hmem,
right, assumption },
{ left, exact heqv.swap } },
all_goals
{ have hs' := hs,
cases hs, simp [rbnode.max] at hmax,
rw [mem] at hmem, blast_disjs,
{ have hmm := mem_of_max_eq lt hmax,
have a_lt_b := lt_of_mem_left_right hs' (by constructor) hmem hmm,
right, assumption },
{ have hmm := mem_of_max_eq lt hmax,
have val_lt_a := lt_of_mem_right hs' (by constructor) hmm,
have a_lt_b := lt_of_incomp_of_lt hmem val_lt_a,
right, assumption },
{ exact t_ih_rchild hs_hs₂ hmax hmem } } }
end
end rbnode
|
8feb28ac3e33a6d59a4b4bf961fa5e6db2ca6c30 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/const_auto.lean | cdc8b831a389c9cb2358dbf5d22a4e95ed3a460f | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,865 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.opposites
import Mathlib.PostPort
universes u₂ v₂ u₁ v₁ u₃ v₃
namespace Mathlib
namespace category_theory.functor
/--
The functor sending `X : C` to the constant functor `J ⥤ C` sending everything to `X`.
-/
def const (J : Type u₁) [category J] {C : Type u₂} [category C] : C ⥤ J ⥤ C :=
mk (fun (X : C) => mk (fun (j : J) => X) fun (j j' : J) (f : j ⟶ j') => 𝟙)
fun (X Y : C) (f : X ⟶ Y) => nat_trans.mk fun (j : J) => f
namespace const
@[simp] theorem obj_obj {J : Type u₁} [category J] {C : Type u₂} [category C] (X : C) (j : J) :
obj (obj (const J) X) j = X :=
rfl
@[simp] theorem obj_map {J : Type u₁} [category J] {C : Type u₂} [category C] (X : C) {j : J}
{j' : J} (f : j ⟶ j') : map (obj (const J) X) f = 𝟙 :=
rfl
@[simp] theorem map_app {J : Type u₁} [category J] {C : Type u₂} [category C] {X : C} {Y : C}
(f : X ⟶ Y) (j : J) : nat_trans.app (map (const J) f) j = f :=
rfl
/--
The contant functor `Jᵒᵖ ⥤ Cᵒᵖ` sending everything to `op X`
is (naturally isomorphic to) the opposite of the constant functor `J ⥤ C` sending everything to `X`.
-/
def op_obj_op {J : Type u₁} [category J] {C : Type u₂} [category C] (X : C) :
obj (const (Jᵒᵖ)) (opposite.op X) ≅ functor.op (obj (const J) X) :=
iso.mk (nat_trans.mk fun (j : Jᵒᵖ) => 𝟙) (nat_trans.mk fun (j : Jᵒᵖ) => 𝟙)
@[simp] theorem op_obj_op_hom_app {J : Type u₁} [category J] {C : Type u₂} [category C] (X : C)
(j : Jᵒᵖ) : nat_trans.app (iso.hom (op_obj_op X)) j = 𝟙 :=
rfl
@[simp] theorem op_obj_op_inv_app {J : Type u₁} [category J] {C : Type u₂} [category C] (X : C)
(j : Jᵒᵖ) : nat_trans.app (iso.inv (op_obj_op X)) j = 𝟙 :=
rfl
/--
The contant functor `Jᵒᵖ ⥤ C` sending everything to `unop X`
is (naturally isomorphic to) the opposite of
the constant functor `J ⥤ Cᵒᵖ` sending everything to `X`.
-/
def op_obj_unop {J : Type u₁} [category J] {C : Type u₂} [category C] (X : Cᵒᵖ) :
obj (const (Jᵒᵖ)) (opposite.unop X) ≅ functor.left_op (obj (const J) X) :=
iso.mk (nat_trans.mk fun (j : Jᵒᵖ) => 𝟙) (nat_trans.mk fun (j : Jᵒᵖ) => 𝟙)
-- Lean needs some help with universes here.
@[simp] theorem op_obj_unop_hom_app {J : Type u₁} [category J] {C : Type u₂} [category C] (X : Cᵒᵖ)
(j : Jᵒᵖ) : nat_trans.app (iso.hom (op_obj_unop X)) j = 𝟙 :=
rfl
@[simp] theorem op_obj_unop_inv_app {J : Type u₁} [category J] {C : Type u₂} [category C] (X : Cᵒᵖ)
(j : Jᵒᵖ) : nat_trans.app (iso.inv (op_obj_unop X)) j = 𝟙 :=
rfl
@[simp] theorem unop_functor_op_obj_map {J : Type u₁} [category J] {C : Type u₂} [category C]
(X : Cᵒᵖ) {j₁ : J} {j₂ : J} (f : j₁ ⟶ j₂) :
map (opposite.unop (obj (functor.op (const J)) X)) f = 𝟙 :=
rfl
end const
/-- These are actually equal, of course, but not definitionally equal
(the equality requires F.map (𝟙 _) = 𝟙 _). A natural isomorphism is
more convenient than an equality between functors (compare id_to_iso). -/
def const_comp (J : Type u₁) [category J] {C : Type u₂} [category C] {D : Type u₃} [category D]
(X : C) (F : C ⥤ D) : obj (const J) X ⋙ F ≅ obj (const J) (obj F X) :=
iso.mk (nat_trans.mk fun (_x : J) => 𝟙) (nat_trans.mk fun (_x : J) => 𝟙)
/-- If `J` is nonempty, then the constant functor over `J` is faithful. -/
protected instance const.category_theory.faithful (J : Type u₁) [category J] {C : Type u₂}
[category C] [Nonempty J] : faithful (const J) :=
faithful.mk
end Mathlib |
f7fb077938fed875a7264b5039491ff672abc1e3 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/polynomial/vieta.lean | e35b1f8358651b2d1fed830ed67d4f004e21ec85 | [
"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 | 6,910 | lean | /-
Copyright (c) 2020 Hanting Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Hanting Zhang
-/
import data.polynomial.splits
import ring_theory.mv_polynomial.symmetric
/-!
# Vieta's Formula
The main result is `multiset.prod_X_add_C_eq_sum_esymm`, which shows that the product of
linear terms `X + λ` with `λ` in a `multiset s` is equal to a linear combination of the
symmetric functions `esymm s`.
From this, we deduce `mv_polynomial.prod_X_add_C_eq_sum_esymm` which is the equivalent formula
for the product of linear terms `X + X i` with `i` in a `fintype σ` as a linear combination
of the symmetric polynomials `esymm σ R j`.
For `R` be an integral domain (so that `p.roots` is defined for any `p : R[X]` as a multiset),
we derive `polynomial.coeff_eq_esymm_roots_of_card`, the relationship between the coefficients and
the roots of `p` for a polynomial `p` that splits (i.e. having as many roots as its degree).
-/
open_locale big_operators polynomial
namespace multiset
open polynomial
section semiring
variables {R : Type*} [comm_semiring R]
/-- A sum version of Vieta's formula for `multiset`: the product of the linear terms `X + λ` where
`λ` runs through a multiset `s` is equal to a linear combination of the symmetric functions
`esymm s` of the `λ`'s .-/
lemma prod_X_add_C_eq_sum_esymm (s : multiset R) :
(s.map (λ r, X + C r)).prod =
∑ j in finset.range (s.card + 1), C (s.esymm j) * X ^ (s.card - j) :=
begin
classical,
rw [prod_map_add, antidiagonal_eq_map_powerset, map_map, ←bind_powerset_len, function.comp,
map_bind, sum_bind, finset.sum_eq_multiset_sum, finset.range_coe, map_congr (eq.refl _)],
intros _ _,
rw [esymm, ←sum_hom', ←sum_map_mul_right, map_congr (eq.refl _)],
intros _ ht,
rw mem_powerset_len at ht,
simp [ht, map_const, prod_repeat, prod_hom', map_id', card_sub],
end
/-- Vieta's formula for the coefficients of the product of linear terms `X + λ` where `λ` runs
through a multiset `s` : the `k`th coefficient is the symmetric function `esymm (card s - k) s`. -/
lemma prod_X_add_C_coeff (s : multiset R) {k : ℕ} (h : k ≤ s.card) :
(s.map (λ r, X + C r)).prod.coeff k = s.esymm (s.card - k) :=
begin
convert polynomial.ext_iff.mp (prod_X_add_C_eq_sum_esymm s) k,
simp_rw [finset_sum_coeff, coeff_C_mul_X_pow],
rw finset.sum_eq_single_of_mem (s.card - k) _,
{ rw if_pos (nat.sub_sub_self h).symm, },
{ intros j hj1 hj2,
suffices : k ≠ card s - j,
{ rw if_neg this, },
{ intro hn,
rw [hn, nat.sub_sub_self (nat.lt_succ_iff.mp (finset.mem_range.mp hj1))] at hj2,
exact ne.irrefl hj2, }},
{ rw finset.mem_range,
exact nat.sub_lt_succ s.card k }
end
lemma prod_X_add_C_coeff' {σ} (s : multiset σ) (r : σ → R) {k : ℕ} (h : k ≤ s.card) :
(s.map (λ i, X + C (r i))).prod.coeff k = (s.map r).esymm (s.card - k) :=
by rw [← map_map (λ r, X + C r) r, prod_X_add_C_coeff]; rwa s.card_map r
lemma _root_.finset.prod_X_add_C_coeff {σ} (s : finset σ) (r : σ → R) {k : ℕ} (h : k ≤ s.card) :
(∏ i in s, (X + C (r i))).coeff k = ∑ t in s.powerset_len (s.card - k), ∏ i in t, r i :=
by { rw [finset.prod, prod_X_add_C_coeff' _ r h, finset.esymm_map_val], refl }
end semiring
section ring
variables {R : Type*} [comm_ring R]
lemma esymm_neg (s : multiset R) (k : ℕ) :
(map has_neg.neg s).esymm k = (-1) ^ k * esymm s k :=
begin
rw [esymm, esymm, ←multiset.sum_map_mul_left, multiset.powerset_len_map, multiset.map_map,
map_congr (eq.refl _)],
intros x hx,
rw [(by { exact (mem_powerset_len.mp hx).right.symm }), ←prod_repeat, ←multiset.map_const],
nth_rewrite 2 ←map_id' x,
rw [←prod_map_mul, map_congr (eq.refl _)],
exact λ z _, neg_one_mul z,
end
lemma prod_X_sub_C_eq_sum_esymm (s : multiset R) :
(s.map (λ t, X - C t)).prod =
∑ j in finset.range (s.card + 1), (-1) ^ j * (C (s.esymm j) * X ^ (s.card - j)) :=
begin
conv_lhs { congr, congr, funext, rw sub_eq_add_neg, rw ←map_neg C _, },
convert prod_X_add_C_eq_sum_esymm (map (λ t, -t) s) using 1,
{ rwa map_map, },
{ simp only [esymm_neg, card_map, mul_assoc, map_mul, map_pow, map_neg, map_one], },
end
lemma prod_X_sub_C_coeff (s : multiset R) {k : ℕ} (h : k ≤ s.card) :
(s.map (λ t, X - C t)).prod.coeff k = (-1) ^ (s.card - k) * s.esymm (s.card - k) :=
begin
conv_lhs { congr, congr, congr, funext, rw sub_eq_add_neg, rw ←map_neg C _, },
convert prod_X_add_C_coeff (map (λ t, -t) s) _ using 1,
{ rwa map_map, },
{ rwa [esymm_neg, card_map] },
{ rwa card_map },
end
/-- Vieta's formula for the coefficients and the roots of a polynomial over an integral domain
with as many roots as its degree. -/
theorem _root_.polynomial.coeff_eq_esymm_roots_of_card [is_domain R] {p : R[X]}
(hroots : p.roots.card = p.nat_degree) {k : ℕ} (h : k ≤ p.nat_degree) :
p.coeff k = p.leading_coeff * (-1) ^ (p.nat_degree - k) * p.roots.esymm (p.nat_degree - k) :=
begin
conv_lhs { rw ← C_leading_coeff_mul_prod_multiset_X_sub_C hroots },
rw [coeff_C_mul, mul_assoc], congr,
convert p.roots.prod_X_sub_C_coeff _ using 3; rw hroots, exact h,
end
/-- Vieta's formula for split polynomials over a field. -/
theorem _root_.polynomial.coeff_eq_esymm_roots_of_splits {F} [field F] {p : F[X]}
(hsplit : p.splits (ring_hom.id F)) {k : ℕ} (h : k ≤ p.nat_degree) :
p.coeff k = p.leading_coeff * (-1) ^ (p.nat_degree - k) * p.roots.esymm (p.nat_degree - k) :=
polynomial.coeff_eq_esymm_roots_of_card (splits_iff_card_roots.1 hsplit) h
end ring
end multiset
section mv_polynomial
open finset polynomial fintype
variables (R σ : Type*) [comm_semiring R] [fintype σ]
/-- A sum version of Vieta's formula for `mv_polynomial`: viewing `X i` as variables,
the product of linear terms `λ + X i` is equal to a linear combination of
the symmetric polynomials `esymm σ R j`. -/
lemma mv_polynomial.prod_C_add_X_eq_sum_esymm :
∏ i : σ, (X + C (mv_polynomial.X i)) =
∑ j in range (card σ + 1), (C (mv_polynomial.esymm σ R j) * X ^ (card σ - j)) :=
begin
let s := finset.univ.val.map (λ i : σ, mv_polynomial.X i),
rw (_ : card σ = s.card),
{ simp_rw [mv_polynomial.esymm_eq_multiset_esymm σ R, finset.prod_eq_multiset_prod],
convert multiset.prod_X_add_C_eq_sum_esymm s,
rwa multiset.map_map, },
{ rw multiset.card_map, refl, }
end
lemma mv_polynomial.prod_X_add_C_coeff (k : ℕ) (h : k ≤ card σ) :
(∏ i : σ, (X + C (mv_polynomial.X i))).coeff k = mv_polynomial.esymm σ R (card σ - k) :=
begin
let s := finset.univ.val.map (λ i, (mv_polynomial.X i : mv_polynomial σ R)),
rw (_ : card σ = s.card) at ⊢ h,
{ rw [mv_polynomial.esymm_eq_multiset_esymm σ R, finset.prod_eq_multiset_prod],
convert multiset.prod_X_add_C_coeff s h,
rwa multiset.map_map },
repeat { rw multiset.card_map, refl, },
end
end mv_polynomial
|
3a3556d7759109db48a0543c8c7f7664e08a40bc | d450724ba99f5b50b57d244eb41fef9f6789db81 | /src/mywork/Homework/practice_1.lean | 4fd9155f529606d5341a8bda5e938519e4f52a2e | [] | no_license | jakekauff/CS2120F21 | 4f009adeb4ce4a148442b562196d66cc6c04530c | e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad | refs/heads/main | 1,693,841,880,030 | 1,637,604,848,000 | 1,637,604,848,000 | 399,946,698 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,469 | lean | /-
EQUALITY
-/
/- #1
Suppose that x, y, z, and w are arbitrary objects of some type,
T; and suppose further that we know (have proofs of the facts)
that x = y, y = z, and w = z. Give a very, very short English
proof of the conjecture that z = w. You can use not only the
axioms of equality, but either of the theorems about properties
of equality that we have proven. Hint: There's something about
this question that makes it much easier to answer than it might
at first appear.
-/
/- #2
Give a formal statement of the conjecture (proposition) from
#1 by filling in the "hole" in the following definition. The
def is a keyword. The name you're binding to your proposition
is prop_1. The type of the value is Prop (which is the type of
all propositions in Lean).
-/
def prop_1 : Prop :=
_
/- #3 (extra credit)
Give a formal proof of the proposition from #2 by filling in
the hole in this next definition. Hint: Use Lean's versions of
the axioms and basic theorems concerning equality. They are,
again, called eq.refl, eq.subst, eq.symm, eq.trans.
-/
theorem prop_1_proof : prop_1 :=
begin
_
end
/-
FOR ALL: ∀.
-/
/- #4
Give a very brief explanation in English of the introduction
rule for ∀. For example, suppose you need to prove (∀ x, P x);
what do you do? (I'm being a little informal in leaving out the
type of X.)
-/
/- #5
Suppose you have a proof, let's call it pf, of the proposition,
(∀ x, P x), and you need a proof of P t, for some particular t.
Write an expression then uses the elimination rule for ∀ to get
such a proof. Complete the answer by replacing the underscores
in the following expression: ( _ _ ).
-/
/-
IMPLIES: →
In the "code" that follows, we define two predicates, each
taking one natural number as an argument. We call them ev and
odd. When applied to any value, n, ev yields the proposition
that n is even (n % 2 = 0), while odd yields the proposition
that n is odd (n % 2 = 1).
-/
def ev (n : ℕ) := n % 2 = 0
def odd (n : ℕ) := n % 2 = 1
/- #6
Write a formal version of the proposition that, for *any*
natural number n, *if* n is even, *then* n + 1 is odd. Give
your answer by filling the hole in the following definition.
Hint: put parenthesis around "n + 1" in your answer.
-/
def successor_of_even_is_odd : Prop :=
_
/- #7
Suppose that "its_raining" and "the_streets_are_wet" are
propositions. (We formalize these assumptions as axioms in
what follows. Then give a formal definition of the (larger)
proposition, "if it's raining out then the streets are wet")
by filling in the hole
-/
axioms (raining streets_wet : Prop)
axiom if_raining_then_streets_wet : _
/- #9
Now suppose that in addition, its_raining is true, and
we have a proof of it, pf_its_raining. Again, we again give
you this assumption formally as an axiom below. Finish
the formal proof that the streets must be wet. Hint: here
you are asked to use the elimination rule for →.
-/
axiom pf_raining : raining
example : streets_wet :=
_
/-
AND: ∧
-/
/- #10
In our last class, we proved that "∧ is *commutative*."
That is, for any given *propositions*, P and Q, (P ∧ Q) →
(Q ∧ P). The way we proved it was to *assume* that we're
given such a P, Q, and proof, pq, of (P ∧ Q) -- applying
the introduction rules for ∀ and →). In this context, we
*use* the proof, pq, to derive separate proofs, let's call
them p, a proof of P, and q, a proof of Q. With these in
hand, we then apply the introduction rule for ∧ to put
them back together into a proof of (Q ∧ P). We give you
a formal version of this proof as a reminder, next.
-/
theorem and_commutative : ∀ (P Q : Prop), P ∧ Q → Q ∧ P :=
begin
assume P Q pq,
apply and.intro _ _,
exact (and.elim_right pq),
exact (and.elim_left pq),
end
/-
Your task now is to prove the theorem, "∧ is *associative*."
What this means is that for arbitrary propositions, P, Q, and
R, if (P ∧ (Q ∧ R)) is true, then ((P ∧ Q) ∧ R) is true, *and
vice versa*. You just need to prove it in the first direction.
Hint, if you have a proof, p_qr, of (P ∧ (Q ∧ R)), then the
application of and.elim_left will give you a proof of P, and
and.elim_right will give you a proof of (Q ∧ R).
To help you along, we give you the first part of the proof,
including an example of a new Lean tactic called have, which
allows you to give a name to a new value in the middle of a
proof script.
-/
theorem and_associative :
∀ (P Q R : Prop),
(P ∧ (Q ∧ R)) → ((P ∧ Q) ∧ R) :=
begin
intros P Q R h,
have p : P := and.elim_left h,
end
/- #11
Give an English language proof of the preceding
theorem. Do it by finishing off the following
partial "proof explanation."
Proof. We assume that P, Q, and R are arbitrary
but specific propositions, and that we have a
proof, let's call it p_qr, of (P ∧ (Q ∧ R)) [by
application of ∧ and → introduction.] What now
remains to be proved is ((P ∧ Q) ∧ R). We can
construct a proof of this proposition by applying
_____ to a proof of (P ∧ Q) and a proof of R.
What remains, then, is to obtain these proofs.
But this is easily done by the application of
____ to ____. QED.
-/
/-
Note that Lean includes versions of these
theorems (and many, many, many others) in
its extensive library of formalized maths,
as the following check commands reveal.
Note the difference in naming relative to
the definitions we give in this file.
-/
#check @and.comm
#check @and.assoc |
f992ce708ca0822e33ea463232e21c6f11d84c59 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /test/norm_num.lean | b4f9ba8c9a675574610f4aa2f0567cc780ddff40 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 12,337 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Mario Carneiro
Tests for norm_num
-/
import tactic.norm_num
import data.complex.basic
-- constant real : Type
-- notation `ℝ` := real
-- @[instance] constant real.linear_ordered_ring : linear_ordered_field ℝ
-- constant complex : Type
-- notation `ℂ` := complex
-- @[instance] constant complex.field : field ℂ
-- @[instance] constant complex.char_zero : char_zero ℂ
example : 374 + (32 - (2 * 8123) : ℤ) - 61 * 50 = 86 + 32 * 32 - 4 * 5000
∧ 43 ≤ 74 + (33 : ℤ) := by norm_num
example : ¬ (7-2)/(2*3) ≥ (1:ℝ) + 2/(3^2) := by norm_num
example : (6:real) + 9 = 15 := by norm_num
example : (2:real)/4 + 4 = 3*3/2 := by norm_num
example : (((3:real)/4)-12)<6 := by norm_num
example : (5:real) ≠ 8 := by norm_num
example : (10:real) > 7 := by norm_num
example : (2:real) * 2 + 3 = 7 := by norm_num
example : (6:real) < 10 := by norm_num
example : (7:real)/2 > 3 := by norm_num
example : (4:real)⁻¹ < 1 := by norm_num
example : ((1:real) / 2)⁻¹ = 2 := by norm_num
example : 2 ^ 17 - 1 = 131071 :=
by {norm_num, tactic.try_for 200 (tactic.result >>= tactic.type_check)}
example : (1:complex) ≠ 2 := by norm_num
example : (1:complex) / 3 ≠ 2 / 7 := by norm_num
example {α} [semiring α] [char_zero α] : (1:α) ≠ 2 := by norm_num
example {α} [ring α] [char_zero α] : (-1:α) ≠ 2 := by norm_num
example {α} [division_ring α] [char_zero α] : (-1:α) ≠ 2 := by norm_num
example {α} [division_ring α] [char_zero α] : (1:α) / 3 ≠ 2 / 7 := by norm_num
example {α} [division_ring α] [char_zero α] : (1:α) / 3 ≠ 0 := by norm_num
example : (5 / 2:ℕ) = 2 := by norm_num
example : (5 / -2:ℤ) < -1 := by norm_num
example : (0 + 1) / 2 < 0 + 1 := by norm_num
example : nat.succ (nat.succ (2 ^ 3)) = 10 := by norm_num
example : 10 = (-1 : ℤ) % 11 := by norm_num
example : (12321 - 2 : ℤ) = 12319 := by norm_num
example (x : ℤ) (h : 1000 + 2000 < x) : 100 * 30 < x :=
by norm_num at *; try_for 100 {exact h}
example : (1103 : ℤ) ≤ (2102 : ℤ) := by norm_num
example : (110474 : ℤ) ≤ (210485 : ℤ) := by norm_num
example : (11047462383473829263 : ℤ) ≤ (21048574677772382462 : ℤ) := by norm_num
example : (210485742382937847263 : ℤ) ≤ (1104857462382937847262 : ℤ) := by norm_num
example : (210485987642382937847263 : ℕ) ≤ (11048512347462382937847262 : ℕ) := by norm_num
example : (210485987642382937847263 : ℚ) ≤ (11048512347462382937847262 : ℚ) := by norm_num
example : (2 * 12868 + 25705) * 11621 ^ 2 ≤ 23235 ^ 2 * 12868 := by norm_num
example (x : ℕ) : ℕ := begin
let n : ℕ, {apply_normed (2^32 - 71)},
exact n
end
example (a : ℚ) (h : 3⁻¹ * a = a) : true :=
begin
norm_num at h,
guard_hyp h : 1 / 3 * a = a,
trivial
end
example : nat.prime 1277 := by norm_num
example : nat.min_fac 221 = 13 := by norm_num
example (h : (5 : ℤ) ∣ 2) : false := by norm_num at h
example : 10 + 2 = 1 + 11 := by norm_num
example : 10 - 1 = 9 := by norm_num
example : 12 - 5 = 3 + 4 := by norm_num
example : 5 - 20 = 0 := by norm_num
example : 0 - 2 = 0 := by norm_num
example : 4 - (5 - 10) = 2 + (3 - 1) := by norm_num
example : 0 - 0 = 0 := by norm_num
example : 100 - 100 = 0 := by norm_num
example : 5 * (2 - 3) = 0 := by norm_num
example : 10 - 5 * 5 + (7 - 3) * 6 = 27 - 3 := by norm_num
def foo : ℕ := 1
@[norm_num] meta def eval_foo : expr → tactic (expr × expr)
| `(foo) := pure (`(1:ℕ), `(eq.refl 1))
| _ := tactic.failed
example : foo = 1 := by norm_num
-- ordered field examples
variable {α : Type}
variable [linear_ordered_field α]
example : (-1 :α) * 1 = -1 := by norm_num
example : (-2 :α) * 1 = -2 := by norm_num
example : (-2 :α) * -1 = 2 := by norm_num
example : (-2 :α) * -2 = 4 := by norm_num
example : (1 : α) * 0 = 0 := by norm_num
example : ((1 : α) + 1) * 5 = 6 + 4 := by norm_num
example : (1 : α) = 0 + 1 := by norm_num
example : (1 : α) = 1 + 0 := by norm_num
example : (2 : α) = 1 + 1 := by norm_num
example : (2 : α) = 0 + 2 := by norm_num
example : (3 : α) = 1 + 2 := by norm_num
example : (3 : α) = 2 + 1 := by norm_num
example : (4 : α) = 3 + 1 := by norm_num
example : (4 : α) = 2 + 2 := by norm_num
example : (5 : α) = 4 + 1 := by norm_num
example : (5 : α) = 3 + 2 := by norm_num
example : (5 : α) = 2 + 3 := by norm_num
example : (6 : α) = 0 + 6 := by norm_num
example : (6 : α) = 3 + 3 := by norm_num
example : (6 : α) = 4 + 2 := by norm_num
example : (6 : α) = 5 + 1 := by norm_num
example : (7 : α) = 4 + 3 := by norm_num
example : (7 : α) = 1 + 6 := by norm_num
example : (7 : α) = 6 + 1 := by norm_num
example : 33 = 5 + (28 : α) := by norm_num
example : (12 : α) = 0 + (2 + 3) + 7 := by norm_num
example : (105 : α) = 70 + (33 + 2) := by norm_num
example : (45000000000 : α) = 23000000000 + 22000000000 := by norm_num
example : (0 : α) - 3 = -3 := by norm_num
example : (0 : α) - 2 = -2 := by norm_num
example : (1 : α) - 3 = -2 := by norm_num
example : (1 : α) - 1 = 0 := by norm_num
example : (0 : α) - 3 = -3 := by norm_num
example : (0 : α) - 3 = -3 := by norm_num
example : (12 : α) - 4 - (5 + -2) = 5 := by norm_num
example : (12 : α) - 4 - (5 + -2) - 20 = -15 := by norm_num
example : (0 : α) * 0 = 0 := by norm_num
example : (0 : α) * 1 = 0 := by norm_num
example : (0 : α) * 2 = 0 := by norm_num
example : (2 : α) * 0 = 0 := by norm_num
example : (1 : α) * 0 = 0 := by norm_num
example : (1 : α) * 1 = 1 := by norm_num
example : (2 : α) * 1 = 2 := by norm_num
example : (1 : α) * 2 = 2 := by norm_num
example : (2 : α) * 2 = 4 := by norm_num
example : (3 : α) * 2 = 6 := by norm_num
example : (2 : α) * 3 = 6 := by norm_num
example : (4 : α) * 1 = 4 := by norm_num
example : (1 : α) * 4 = 4 := by norm_num
example : (3 : α) * 3 = 9 := by norm_num
example : (3 : α) * 4 = 12 := by norm_num
example : (4 : α) * 4 = 16 := by norm_num
example : (11 : α) * 2 = 22 := by norm_num
example : (15 : α) * 6 = 90 := by norm_num
example : (123456 : α) * 123456 = 15241383936 := by norm_num
example : (4 : α) / 2 = 2 := by norm_num
example : (4 : α) / 1 = 4 := by norm_num
example : (4 : α) / 3 = 4 / 3 := by norm_num
example : (50 : α) / 5 = 10 := by norm_num
example : (1056 : α) / 1 = 1056 := by norm_num
example : (6 : α) / 4 = 3/2 := by norm_num
example : (0 : α) / 3 = 0 := by norm_num
example : (3 : α) / 0 = 0 := by norm_num
example : (9 * 9 * 9) * (12 : α) / 27 = 81 * (2 + 2) := by norm_num
example : (-2 : α) * 4 / 3 = -8 / 3 := by norm_num
example : - (-4 / 3) = 1 / (3 / (4 : α)) := by norm_num
-- auto gen tests
example : ((25 * (1 / 1)) + (30 - 16)) = (39 : α) := by norm_num
example : ((19 * (- 2 - 3)) / 6) = (-95/6 : α) := by norm_num
example : - (3 * 28) = (-84 : α) := by norm_num
example : - - (16 / ((11 / (- - (6 * 19) + 12)) * 21)) = (96/11 : α) := by norm_num
example : (- (- 21 + 24) - - (- - (28 + (- 21 / - (16 / ((1 * 26) * ((0 * - 11) + 13))))) * 21)) =
(79209/8 : α) := by norm_num
example : (27 * (((16 + - (12 + 4)) + (22 - - 19)) - 23)) = (486 : α) := by norm_num
example : - (13 * (- 30 / ((7 / 24) + - 7))) = (-9360/161 : α) := by norm_num
example : - (0 + 20) = (-20 : α) := by norm_num
example : (- 2 - (27 + (((2 / 14) - (7 + 21)) + (16 - - - 14)))) = (-22/7 : α) := by norm_num
example : (25 + ((8 - 2) + 16)) = (47 : α) := by norm_num
example : (- - 26 / 27) = (26/27 : α) := by norm_num
example : ((((16 * (22 / 14)) - 18) / 11) + 30) = (2360/77 : α) := by norm_num
example : (((- 28 * 28) / (29 - 24)) * 24) = (-18816/5 : α) := by norm_num
example : ((- (18 - ((- - (10 + - 2) - - (23 / 5)) / 5)) - (21 * 22)) -
(((20 / - ((((19 + 18) + 15) + 3) + - 22)) + 14) / 17)) = (-394571/825 : α) := by norm_num
example : ((3 + 25) - - 4) = (32 : α) := by norm_num
example : ((1 - 0) - 22) = (-21 : α) := by norm_num
example : (((- (8 / 7) / 14) + 20) + 22) = (2054/49 : α) := by norm_num
example : ((21 / 20) - 29) = (-559/20 : α) := by norm_num
example : - - 20 = (20 : α) := by norm_num
example : (24 - (- 9 / 4)) = (105/4 : α) := by norm_num
example : (((7 / ((23 * 19) + (27 * 10))) - ((28 - - 15) * 24)) + (9 / - (10 * - 3))) =
(-1042007/1010 : α) := by norm_num
example : (26 - (- 29 + (12 / 25))) = (1363/25 : α) := by norm_num
example : ((11 * 27) / (4 - 5)) = (-297 : α) := by norm_num
example : (24 - (9 + 15)) = (0 : α) := by norm_num
example : (- 9 - - 0) = (-9 : α) := by norm_num
example : (- 10 / (30 + 10)) = (-1/4 : α) := by norm_num
example : (22 - (6 * (28 * - 8))) = (1366 : α) := by norm_num
example : ((- - 2 * (9 * - 3)) + (22 / 30)) = (-799/15 : α) := by norm_num
example : - (26 / ((3 + 7) / - (27 * (12 / - 16)))) = (-1053/20 : α) := by norm_num
example : ((- 29 / 1) + 28) = (-1 : α) := by norm_num
example : ((21 * ((10 - (((17 + 28) - - 0) + 20)) + 26)) + ((17 + - 16) * 7)) = (-602 : α) :=
by norm_num
example : (((- 5 - ((24 + - - 8) + 3)) + 20) + - 23) = (-43 : α) := by norm_num
example : ((- ((14 - 15) * (14 + 8)) + ((- (18 - 27) - 0) + 12)) - 11) = (32 : α) := by norm_num
example : (((15 / 17) * (26 / 27)) + 28) = (4414/153 : α) := by norm_num
example : (14 - ((- 16 - 3) * - (20 * 19))) = (-7206 : α) := by norm_num
example : (21 - - - (28 - (12 * 11))) = (125 : α) := by norm_num
example : ((0 + (7 + (25 + 8))) * - (11 * 27)) = (-11880 : α) := by norm_num
example : (19 * - 5) = (-95 : α) := by norm_num
example : (29 * - 8) = (-232 : α) := by norm_num
example : ((22 / 9) - 29) = (-239/9 : α) := by norm_num
example : (3 + (19 / 12)) = (55/12 : α) := by norm_num
example : - (13 + 30) = (-43 : α) := by norm_num
example : - - - (((21 * - - ((- 25 - (- (30 - 5) / (- 5 - 5))) /
(((6 + ((25 * - 13) + 22)) - 3) / 2))) / (- 3 / 10)) * (- 8 - 0)) = (-308/3 : α) := by norm_num
example : - (2 * - (- 24 * 22)) = (-1056 : α) := by norm_num
example : - - (((28 / - ((- 13 * - 5) / - (((7 - 30) / 16) + 6))) * 0) - 24) = (-24 : α) :=
by norm_num
example : ((13 + 24) - (27 / (21 * 13))) = (3358/91 : α) := by norm_num
example : ((3 / - 21) * 25) = (-25/7 : α) := by norm_num
example : (17 - (29 - 18)) = (6 : α) := by norm_num
example : ((28 / 20) * 15) = (21 : α) := by norm_num
example : ((((26 * (- (23 - 13) - 3)) / 20) / (14 - (10 + 20))) / ((16 / 6) / (16 * - (3 / 28)))) =
(-1521/2240 : α) := by norm_num
example : (46 / (- ((- 17 * 28) - 77) + 87)) = (23/320 : α) := by norm_num
example : (73 * - (67 - (74 * - - 11))) = (54531 : α) := by norm_num
example : ((8 * (25 / 9)) + 59) = (731/9 : α) := by norm_num
example : - ((59 + 85) * - 70) = (10080 : α) := by norm_num
example : (66 + (70 * 58)) = (4126 : α) := by norm_num
example : (- - 49 * 0) = (0 : α) := by norm_num
example : ((- 78 - 69) * 9) = (-1323 : α) := by norm_num
example : - - (7 - - (50 * 79)) = (3957 : α) := by norm_num
example : - (85 * (((4 * 93) * 19) * - 31)) = (18624180 : α) := by norm_num
example : (21 + (- 5 / ((74 * 85) / 45))) = (26373/1258 : α) := by norm_num
example : (42 - ((27 + 64) + 26)) = (-75 : α) := by norm_num
example : (- ((38 - - 17) + 86) - (74 + 58)) = (-273 : α) := by norm_num
example : ((29 * - (75 + - 68)) + (- 41 / 28)) = (-5725/28 : α) := by norm_num
example : (- - (40 - 11) - (68 * 86)) = (-5819 : α) := by norm_num
example : (6 + ((65 - 14) + - 89)) = (-32 : α) := by norm_num
example : (97 * - (29 * 35)) = (-98455 : α) := by norm_num
example : - (66 / 33) = (-2 : α) := by norm_num
example : - ((94 * 89) + (79 - (23 - (((- 1 / 55) + 95) * (28 - (54 / - - - 22)))))) =
(-1369070/121 : α) := by norm_num
example : (- 23 + 61) = (38 : α) := by norm_num
example : - (93 / 69) = (-31/23 : α) := by norm_num
example : (- - ((68 / (39 + (((45 * - (59 - (37 + 35))) / (53 - 75)) -
- (100 + - (50 / (- 30 - 59)))))) - (69 - (23 * 30))) / (57 + 17)) = (137496481/16368578 : α) :=
by norm_num
example : (- 19 * - - (75 * - - 41)) = (-58425 : α) := by norm_num
example : ((3 / ((- 28 * 45) * (19 + ((- (- 88 - (- (- 1 + 90) + 8)) + 87) * 48)))) + 1) =
(1903019/1903020 : α) := by norm_num
example : ((- - (28 + 48) / 75) + ((- 59 - 14) - 0)) = (-5399/75 : α) := by norm_num
example : (- ((- (((66 - 86) - 36) / 94) - 3) / - - (77 / (56 - - - 79))) + 87) =
(312254/3619 : α) := by norm_num
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.